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.
 
 
 
 
 
 

81468 lines
2.3 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. function compressBatches(batchA, batchB) {
  9757. var mapA = {};
  9758. var mapB = {};
  9759. makeMap(batchA || [], mapA);
  9760. makeMap(batchB || [], mapB, mapA);
  9761. return [mapToArray(mapA), mapToArray(mapB)];
  9762. function makeMap(sourceBatch, map$$1, otherMap) {
  9763. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  9764. var seriesId = sourceBatch[i].seriesId;
  9765. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  9766. var otherDataIndices = otherMap && otherMap[seriesId];
  9767. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  9768. var dataIndex = dataIndices[j];
  9769. if (otherDataIndices && otherDataIndices[dataIndex]) {
  9770. otherDataIndices[dataIndex] = null;
  9771. }
  9772. else {
  9773. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  9774. }
  9775. }
  9776. }
  9777. }
  9778. function mapToArray(map$$1, isData) {
  9779. var result = [];
  9780. for (var i in map$$1) {
  9781. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  9782. if (isData) {
  9783. result.push(+i);
  9784. }
  9785. else {
  9786. var dataIndices = mapToArray(map$$1[i], true);
  9787. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  9788. }
  9789. }
  9790. }
  9791. return result;
  9792. }
  9793. }
  9794. /**
  9795. * @param {module:echarts/data/List} data
  9796. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9797. * each of which can be Array or primary type.
  9798. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9799. */
  9800. function queryDataIndex(data, payload) {
  9801. if (payload.dataIndexInside != null) {
  9802. return payload.dataIndexInside;
  9803. }
  9804. else if (payload.dataIndex != null) {
  9805. return isArray(payload.dataIndex)
  9806. ? map(payload.dataIndex, function (value) {
  9807. return data.indexOfRawIndex(value);
  9808. })
  9809. : data.indexOfRawIndex(payload.dataIndex);
  9810. }
  9811. else if (payload.name != null) {
  9812. return isArray(payload.name)
  9813. ? map(payload.name, function (value) {
  9814. return data.indexOfName(value);
  9815. })
  9816. : data.indexOfName(payload.name);
  9817. }
  9818. }
  9819. /**
  9820. * Enable property storage to any host object.
  9821. * Notice: Serialization is not supported.
  9822. *
  9823. * For example:
  9824. * var inner = zrUitl.makeInner();
  9825. *
  9826. * function some1(hostObj) {
  9827. * inner(hostObj).someProperty = 1212;
  9828. * ...
  9829. * }
  9830. * function some2() {
  9831. * var fields = inner(this);
  9832. * fields.someProperty1 = 1212;
  9833. * fields.someProperty2 = 'xx';
  9834. * ...
  9835. * }
  9836. *
  9837. * @return {Function}
  9838. */
  9839. function makeInner() {
  9840. // Consider different scope by es module import.
  9841. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9842. return function (hostObj) {
  9843. return hostObj[key] || (hostObj[key] = {});
  9844. };
  9845. }
  9846. var innerUniqueIndex = 0;
  9847. /**
  9848. * @param {module:echarts/model/Global} ecModel
  9849. * @param {string|Object} finder
  9850. * If string, e.g., 'geo', means {geoIndex: 0}.
  9851. * If Object, could contain some of these properties below:
  9852. * {
  9853. * seriesIndex, seriesId, seriesName,
  9854. * geoIndex, geoId, geoName,
  9855. * bmapIndex, bmapId, bmapName,
  9856. * xAxisIndex, xAxisId, xAxisName,
  9857. * yAxisIndex, yAxisId, yAxisName,
  9858. * gridIndex, gridId, gridName,
  9859. * ... (can be extended)
  9860. * }
  9861. * Each properties can be number|string|Array.<number>|Array.<string>
  9862. * For example, a finder could be
  9863. * {
  9864. * seriesIndex: 3,
  9865. * geoId: ['aa', 'cc'],
  9866. * gridName: ['xx', 'rr']
  9867. * }
  9868. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9869. * If nothing or null/undefined specified, return nothing.
  9870. * @param {Object} [opt]
  9871. * @param {string} [opt.defaultMainType]
  9872. * @param {Array.<string>} [opt.includeMainTypes]
  9873. * @return {Object} result like:
  9874. * {
  9875. * seriesModels: [seriesModel1, seriesModel2],
  9876. * seriesModel: seriesModel1, // The first model
  9877. * geoModels: [geoModel1, geoModel2],
  9878. * geoModel: geoModel1, // The first model
  9879. * ...
  9880. * }
  9881. */
  9882. function parseFinder(ecModel, finder, opt) {
  9883. if (isString(finder)) {
  9884. var obj = {};
  9885. obj[finder + 'Index'] = 0;
  9886. finder = obj;
  9887. }
  9888. var defaultMainType = opt && opt.defaultMainType;
  9889. if (defaultMainType
  9890. && !has(finder, defaultMainType + 'Index')
  9891. && !has(finder, defaultMainType + 'Id')
  9892. && !has(finder, defaultMainType + 'Name')
  9893. ) {
  9894. finder[defaultMainType + 'Index'] = 0;
  9895. }
  9896. var result = {};
  9897. each$2(finder, function (value, key) {
  9898. var value = finder[key];
  9899. // Exclude 'dataIndex' and other illgal keys.
  9900. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9901. result[key] = value;
  9902. return;
  9903. }
  9904. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9905. var mainType = parsedKey[1];
  9906. var queryType = (parsedKey[2] || '').toLowerCase();
  9907. if (!mainType
  9908. || !queryType
  9909. || value == null
  9910. || (queryType === 'index' && value === 'none')
  9911. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9912. ) {
  9913. return;
  9914. }
  9915. var queryParam = {mainType: mainType};
  9916. if (queryType !== 'index' || value !== 'all') {
  9917. queryParam[queryType] = value;
  9918. }
  9919. var models = ecModel.queryComponents(queryParam);
  9920. result[mainType + 'Models'] = models;
  9921. result[mainType + 'Model'] = models[0];
  9922. });
  9923. return result;
  9924. }
  9925. function has(obj, prop) {
  9926. return obj && obj.hasOwnProperty(prop);
  9927. }
  9928. function setAttribute(dom, key, value) {
  9929. dom.setAttribute
  9930. ? dom.setAttribute(key, value)
  9931. : (dom[key] = value);
  9932. }
  9933. function getAttribute(dom, key) {
  9934. return dom.getAttribute
  9935. ? dom.getAttribute(key)
  9936. : dom[key];
  9937. }
  9938. var TYPE_DELIMITER = '.';
  9939. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9940. /**
  9941. * Notice, parseClassType('') should returns {main: '', sub: ''}
  9942. * @public
  9943. */
  9944. function parseClassType$1(componentType) {
  9945. var ret = {main: '', sub: ''};
  9946. if (componentType) {
  9947. componentType = componentType.split(TYPE_DELIMITER);
  9948. ret.main = componentType[0] || '';
  9949. ret.sub = componentType[1] || '';
  9950. }
  9951. return ret;
  9952. }
  9953. /**
  9954. * @public
  9955. */
  9956. function checkClassType(componentType) {
  9957. assert$1(
  9958. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  9959. 'componentType "' + componentType + '" illegal'
  9960. );
  9961. }
  9962. /**
  9963. * @public
  9964. */
  9965. function enableClassExtend(RootClass, mandatoryMethods) {
  9966. RootClass.$constructor = RootClass;
  9967. RootClass.extend = function (proto) {
  9968. if (__DEV__) {
  9969. each$1(mandatoryMethods, function (method) {
  9970. if (!proto[method]) {
  9971. console.warn(
  9972. 'Method `' + method + '` should be implemented'
  9973. + (proto.type ? ' in ' + proto.type : '') + '.'
  9974. );
  9975. }
  9976. });
  9977. }
  9978. var superClass = this;
  9979. var ExtendedClass = function () {
  9980. if (!proto.$constructor) {
  9981. superClass.apply(this, arguments);
  9982. }
  9983. else {
  9984. proto.$constructor.apply(this, arguments);
  9985. }
  9986. };
  9987. extend(ExtendedClass.prototype, proto);
  9988. ExtendedClass.extend = this.extend;
  9989. ExtendedClass.superCall = superCall;
  9990. ExtendedClass.superApply = superApply;
  9991. inherits(ExtendedClass, this);
  9992. ExtendedClass.superClass = superClass;
  9993. return ExtendedClass;
  9994. };
  9995. }
  9996. var classBase = 0;
  9997. /**
  9998. * Can not use instanceof, consider different scope by
  9999. * cross domain or es module import in ec extensions.
  10000. * Mount a method "isInstance()" to Clz.
  10001. */
  10002. function enableClassCheck(Clz) {
  10003. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10004. Clz.prototype[classAttr] = true;
  10005. if (__DEV__) {
  10006. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10007. }
  10008. Clz.isInstance = function (obj) {
  10009. return !!(obj && obj[classAttr]);
  10010. };
  10011. }
  10012. // superCall should have class info, which can not be fetch from 'this'.
  10013. // Consider this case:
  10014. // class A has method f,
  10015. // class B inherits class A, overrides method f, f call superApply('f'),
  10016. // class C inherits class B, do not overrides method f,
  10017. // then when method of class C is called, dead loop occured.
  10018. function superCall(context, methodName) {
  10019. var args = slice(arguments, 2);
  10020. return this.superClass.prototype[methodName].apply(context, args);
  10021. }
  10022. function superApply(context, methodName, args) {
  10023. return this.superClass.prototype[methodName].apply(context, args);
  10024. }
  10025. /**
  10026. * @param {Object} entity
  10027. * @param {Object} options
  10028. * @param {boolean} [options.registerWhenExtend]
  10029. * @public
  10030. */
  10031. function enableClassManagement(entity, options) {
  10032. options = options || {};
  10033. /**
  10034. * Component model classes
  10035. * key: componentType,
  10036. * value:
  10037. * componentClass, when componentType is 'xxx'
  10038. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10039. * @type {Object}
  10040. */
  10041. var storage = {};
  10042. entity.registerClass = function (Clazz, componentType) {
  10043. if (componentType) {
  10044. checkClassType(componentType);
  10045. componentType = parseClassType$1(componentType);
  10046. if (!componentType.sub) {
  10047. if (__DEV__) {
  10048. if (storage[componentType.main]) {
  10049. console.warn(componentType.main + ' exists.');
  10050. }
  10051. }
  10052. storage[componentType.main] = Clazz;
  10053. }
  10054. else if (componentType.sub !== IS_CONTAINER) {
  10055. var container = makeContainer(componentType);
  10056. container[componentType.sub] = Clazz;
  10057. }
  10058. }
  10059. return Clazz;
  10060. };
  10061. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10062. var Clazz = storage[componentMainType];
  10063. if (Clazz && Clazz[IS_CONTAINER]) {
  10064. Clazz = subType ? Clazz[subType] : null;
  10065. }
  10066. if (throwWhenNotFound && !Clazz) {
  10067. throw new Error(
  10068. !subType
  10069. ? componentMainType + '.' + 'type should be specified.'
  10070. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10071. );
  10072. }
  10073. return Clazz;
  10074. };
  10075. entity.getClassesByMainType = function (componentType) {
  10076. componentType = parseClassType$1(componentType);
  10077. var result = [];
  10078. var obj = storage[componentType.main];
  10079. if (obj && obj[IS_CONTAINER]) {
  10080. each$1(obj, function (o, type) {
  10081. type !== IS_CONTAINER && result.push(o);
  10082. });
  10083. }
  10084. else {
  10085. result.push(obj);
  10086. }
  10087. return result;
  10088. };
  10089. entity.hasClass = function (componentType) {
  10090. // Just consider componentType.main.
  10091. componentType = parseClassType$1(componentType);
  10092. return !!storage[componentType.main];
  10093. };
  10094. /**
  10095. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10096. */
  10097. entity.getAllClassMainTypes = function () {
  10098. var types = [];
  10099. each$1(storage, function (obj, type) {
  10100. types.push(type);
  10101. });
  10102. return types;
  10103. };
  10104. /**
  10105. * If a main type is container and has sub types
  10106. * @param {string} mainType
  10107. * @return {boolean}
  10108. */
  10109. entity.hasSubTypes = function (componentType) {
  10110. componentType = parseClassType$1(componentType);
  10111. var obj = storage[componentType.main];
  10112. return obj && obj[IS_CONTAINER];
  10113. };
  10114. entity.parseClassType = parseClassType$1;
  10115. function makeContainer(componentType) {
  10116. var container = storage[componentType.main];
  10117. if (!container || !container[IS_CONTAINER]) {
  10118. container = storage[componentType.main] = {};
  10119. container[IS_CONTAINER] = true;
  10120. }
  10121. return container;
  10122. }
  10123. if (options.registerWhenExtend) {
  10124. var originalExtend = entity.extend;
  10125. if (originalExtend) {
  10126. entity.extend = function (proto) {
  10127. var ExtendedClass = originalExtend.call(this, proto);
  10128. return entity.registerClass(ExtendedClass, proto.type);
  10129. };
  10130. }
  10131. }
  10132. return entity;
  10133. }
  10134. /**
  10135. * @param {string|Array.<string>} properties
  10136. */
  10137. // TODO Parse shadow style
  10138. // TODO Only shallow path support
  10139. var makeStyleMapper = function (properties) {
  10140. // Normalize
  10141. for (var i = 0; i < properties.length; i++) {
  10142. if (!properties[i][1]) {
  10143. properties[i][1] = properties[i][0];
  10144. }
  10145. }
  10146. return function (model, excludes, includes) {
  10147. var style = {};
  10148. for (var i = 0; i < properties.length; i++) {
  10149. var propName = properties[i][1];
  10150. if ((excludes && indexOf(excludes, propName) >= 0)
  10151. || (includes && indexOf(includes, propName) < 0)
  10152. ) {
  10153. continue;
  10154. }
  10155. var val = model.getShallow(propName);
  10156. if (val != null) {
  10157. style[properties[i][0]] = val;
  10158. }
  10159. }
  10160. return style;
  10161. };
  10162. };
  10163. var getLineStyle = makeStyleMapper(
  10164. [
  10165. ['lineWidth', 'width'],
  10166. ['stroke', 'color'],
  10167. ['opacity'],
  10168. ['shadowBlur'],
  10169. ['shadowOffsetX'],
  10170. ['shadowOffsetY'],
  10171. ['shadowColor']
  10172. ]
  10173. );
  10174. var lineStyleMixin = {
  10175. getLineStyle: function (excludes) {
  10176. var style = getLineStyle(this, excludes);
  10177. var lineDash = this.getLineDash(style.lineWidth);
  10178. lineDash && (style.lineDash = lineDash);
  10179. return style;
  10180. },
  10181. getLineDash: function (lineWidth) {
  10182. if (lineWidth == null) {
  10183. lineWidth = 1;
  10184. }
  10185. var lineType = this.get('type');
  10186. var dotSize = Math.max(lineWidth, 2);
  10187. var dashSize = lineWidth * 4;
  10188. return (lineType === 'solid' || lineType == null) ? null
  10189. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10190. }
  10191. };
  10192. var getAreaStyle = makeStyleMapper(
  10193. [
  10194. ['fill', 'color'],
  10195. ['shadowBlur'],
  10196. ['shadowOffsetX'],
  10197. ['shadowOffsetY'],
  10198. ['opacity'],
  10199. ['shadowColor']
  10200. ]
  10201. );
  10202. var areaStyleMixin = {
  10203. getAreaStyle: function (excludes, includes) {
  10204. return getAreaStyle(this, excludes, includes);
  10205. }
  10206. };
  10207. /**
  10208. * 曲线辅助模块
  10209. * @module zrender/core/curve
  10210. * @author pissang(https://www.github.com/pissang)
  10211. */
  10212. var mathPow = Math.pow;
  10213. var mathSqrt$2 = Math.sqrt;
  10214. var EPSILON$1 = 1e-8;
  10215. var EPSILON_NUMERIC = 1e-4;
  10216. var THREE_SQRT = mathSqrt$2(3);
  10217. var ONE_THIRD = 1 / 3;
  10218. // 临时变量
  10219. var _v0 = create();
  10220. var _v1 = create();
  10221. var _v2 = create();
  10222. function isAroundZero(val) {
  10223. return val > -EPSILON$1 && val < EPSILON$1;
  10224. }
  10225. function isNotAroundZero$1(val) {
  10226. return val > EPSILON$1 || val < -EPSILON$1;
  10227. }
  10228. /**
  10229. * 计算三次贝塞尔值
  10230. * @memberOf module:zrender/core/curve
  10231. * @param {number} p0
  10232. * @param {number} p1
  10233. * @param {number} p2
  10234. * @param {number} p3
  10235. * @param {number} t
  10236. * @return {number}
  10237. */
  10238. function cubicAt(p0, p1, p2, p3, t) {
  10239. var onet = 1 - t;
  10240. return onet * onet * (onet * p0 + 3 * t * p1)
  10241. + t * t * (t * p3 + 3 * onet * p2);
  10242. }
  10243. /**
  10244. * 计算三次贝塞尔导数值
  10245. * @memberOf module:zrender/core/curve
  10246. * @param {number} p0
  10247. * @param {number} p1
  10248. * @param {number} p2
  10249. * @param {number} p3
  10250. * @param {number} t
  10251. * @return {number}
  10252. */
  10253. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10254. var onet = 1 - t;
  10255. return 3 * (
  10256. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10257. + (p3 - p2) * t * t
  10258. );
  10259. }
  10260. /**
  10261. * 计算三次贝塞尔方程根,使用盛金公式
  10262. * @memberOf module:zrender/core/curve
  10263. * @param {number} p0
  10264. * @param {number} p1
  10265. * @param {number} p2
  10266. * @param {number} p3
  10267. * @param {number} val
  10268. * @param {Array.<number>} roots
  10269. * @return {number} 有效根数目
  10270. */
  10271. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10272. // Evaluate roots of cubic functions
  10273. var a = p3 + 3 * (p1 - p2) - p0;
  10274. var b = 3 * (p2 - p1 * 2 + p0);
  10275. var c = 3 * (p1 - p0);
  10276. var d = p0 - val;
  10277. var A = b * b - 3 * a * c;
  10278. var B = b * c - 9 * a * d;
  10279. var C = c * c - 3 * b * d;
  10280. var n = 0;
  10281. if (isAroundZero(A) && isAroundZero(B)) {
  10282. if (isAroundZero(b)) {
  10283. roots[0] = 0;
  10284. }
  10285. else {
  10286. var t1 = -c / b; //t1, t2, t3, b is not zero
  10287. if (t1 >= 0 && t1 <= 1) {
  10288. roots[n++] = t1;
  10289. }
  10290. }
  10291. }
  10292. else {
  10293. var disc = B * B - 4 * A * C;
  10294. if (isAroundZero(disc)) {
  10295. var K = B / A;
  10296. var t1 = -b / a + K; // t1, a is not zero
  10297. var t2 = -K / 2; // t2, t3
  10298. if (t1 >= 0 && t1 <= 1) {
  10299. roots[n++] = t1;
  10300. }
  10301. if (t2 >= 0 && t2 <= 1) {
  10302. roots[n++] = t2;
  10303. }
  10304. }
  10305. else if (disc > 0) {
  10306. var discSqrt = mathSqrt$2(disc);
  10307. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10308. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10309. if (Y1 < 0) {
  10310. Y1 = -mathPow(-Y1, ONE_THIRD);
  10311. }
  10312. else {
  10313. Y1 = mathPow(Y1, ONE_THIRD);
  10314. }
  10315. if (Y2 < 0) {
  10316. Y2 = -mathPow(-Y2, ONE_THIRD);
  10317. }
  10318. else {
  10319. Y2 = mathPow(Y2, ONE_THIRD);
  10320. }
  10321. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10322. if (t1 >= 0 && t1 <= 1) {
  10323. roots[n++] = t1;
  10324. }
  10325. }
  10326. else {
  10327. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10328. var theta = Math.acos(T) / 3;
  10329. var ASqrt = mathSqrt$2(A);
  10330. var tmp = Math.cos(theta);
  10331. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10332. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10333. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10334. if (t1 >= 0 && t1 <= 1) {
  10335. roots[n++] = t1;
  10336. }
  10337. if (t2 >= 0 && t2 <= 1) {
  10338. roots[n++] = t2;
  10339. }
  10340. if (t3 >= 0 && t3 <= 1) {
  10341. roots[n++] = t3;
  10342. }
  10343. }
  10344. }
  10345. return n;
  10346. }
  10347. /**
  10348. * 计算三次贝塞尔方程极限值的位置
  10349. * @memberOf module:zrender/core/curve
  10350. * @param {number} p0
  10351. * @param {number} p1
  10352. * @param {number} p2
  10353. * @param {number} p3
  10354. * @param {Array.<number>} extrema
  10355. * @return {number} 有效数目
  10356. */
  10357. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10358. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10359. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10360. var c = 3 * p1 - 3 * p0;
  10361. var n = 0;
  10362. if (isAroundZero(a)) {
  10363. if (isNotAroundZero$1(b)) {
  10364. var t1 = -c / b;
  10365. if (t1 >= 0 && t1 <=1) {
  10366. extrema[n++] = t1;
  10367. }
  10368. }
  10369. }
  10370. else {
  10371. var disc = b * b - 4 * a * c;
  10372. if (isAroundZero(disc)) {
  10373. extrema[0] = -b / (2 * a);
  10374. }
  10375. else if (disc > 0) {
  10376. var discSqrt = mathSqrt$2(disc);
  10377. var t1 = (-b + discSqrt) / (2 * a);
  10378. var t2 = (-b - discSqrt) / (2 * a);
  10379. if (t1 >= 0 && t1 <= 1) {
  10380. extrema[n++] = t1;
  10381. }
  10382. if (t2 >= 0 && t2 <= 1) {
  10383. extrema[n++] = t2;
  10384. }
  10385. }
  10386. }
  10387. return n;
  10388. }
  10389. /**
  10390. * 细分三次贝塞尔曲线
  10391. * @memberOf module:zrender/core/curve
  10392. * @param {number} p0
  10393. * @param {number} p1
  10394. * @param {number} p2
  10395. * @param {number} p3
  10396. * @param {number} t
  10397. * @param {Array.<number>} out
  10398. */
  10399. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10400. var p01 = (p1 - p0) * t + p0;
  10401. var p12 = (p2 - p1) * t + p1;
  10402. var p23 = (p3 - p2) * t + p2;
  10403. var p012 = (p12 - p01) * t + p01;
  10404. var p123 = (p23 - p12) * t + p12;
  10405. var p0123 = (p123 - p012) * t + p012;
  10406. // Seg0
  10407. out[0] = p0;
  10408. out[1] = p01;
  10409. out[2] = p012;
  10410. out[3] = p0123;
  10411. // Seg1
  10412. out[4] = p0123;
  10413. out[5] = p123;
  10414. out[6] = p23;
  10415. out[7] = p3;
  10416. }
  10417. /**
  10418. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10419. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10420. * @param {number} x0
  10421. * @param {number} y0
  10422. * @param {number} x1
  10423. * @param {number} y1
  10424. * @param {number} x2
  10425. * @param {number} y2
  10426. * @param {number} x3
  10427. * @param {number} y3
  10428. * @param {number} x
  10429. * @param {number} y
  10430. * @param {Array.<number>} [out] 投射点
  10431. * @return {number}
  10432. */
  10433. function cubicProjectPoint(
  10434. x0, y0, x1, y1, x2, y2, x3, y3,
  10435. x, y, out
  10436. ) {
  10437. // http://pomax.github.io/bezierinfo/#projections
  10438. var t;
  10439. var interval = 0.005;
  10440. var d = Infinity;
  10441. var prev;
  10442. var next;
  10443. var d1;
  10444. var d2;
  10445. _v0[0] = x;
  10446. _v0[1] = y;
  10447. // 先粗略估计一下可能的最小距离的 t 值
  10448. // PENDING
  10449. for (var _t = 0; _t < 1; _t += 0.05) {
  10450. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10451. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10452. d1 = distSquare(_v0, _v1);
  10453. if (d1 < d) {
  10454. t = _t;
  10455. d = d1;
  10456. }
  10457. }
  10458. d = Infinity;
  10459. // At most 32 iteration
  10460. for (var i = 0; i < 32; i++) {
  10461. if (interval < EPSILON_NUMERIC) {
  10462. break;
  10463. }
  10464. prev = t - interval;
  10465. next = t + interval;
  10466. // t - interval
  10467. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10468. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10469. d1 = distSquare(_v1, _v0);
  10470. if (prev >= 0 && d1 < d) {
  10471. t = prev;
  10472. d = d1;
  10473. }
  10474. else {
  10475. // t + interval
  10476. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10477. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10478. d2 = distSquare(_v2, _v0);
  10479. if (next <= 1 && d2 < d) {
  10480. t = next;
  10481. d = d2;
  10482. }
  10483. else {
  10484. interval *= 0.5;
  10485. }
  10486. }
  10487. }
  10488. // t
  10489. if (out) {
  10490. out[0] = cubicAt(x0, x1, x2, x3, t);
  10491. out[1] = cubicAt(y0, y1, y2, y3, t);
  10492. }
  10493. // console.log(interval, i);
  10494. return mathSqrt$2(d);
  10495. }
  10496. /**
  10497. * 计算二次方贝塞尔值
  10498. * @param {number} p0
  10499. * @param {number} p1
  10500. * @param {number} p2
  10501. * @param {number} t
  10502. * @return {number}
  10503. */
  10504. function quadraticAt(p0, p1, p2, t) {
  10505. var onet = 1 - t;
  10506. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10507. }
  10508. /**
  10509. * 计算二次方贝塞尔导数值
  10510. * @param {number} p0
  10511. * @param {number} p1
  10512. * @param {number} p2
  10513. * @param {number} t
  10514. * @return {number}
  10515. */
  10516. function quadraticDerivativeAt(p0, p1, p2, t) {
  10517. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10518. }
  10519. /**
  10520. * 计算二次方贝塞尔方程根
  10521. * @param {number} p0
  10522. * @param {number} p1
  10523. * @param {number} p2
  10524. * @param {number} t
  10525. * @param {Array.<number>} roots
  10526. * @return {number} 有效根数目
  10527. */
  10528. function quadraticRootAt(p0, p1, p2, val, roots) {
  10529. var a = p0 - 2 * p1 + p2;
  10530. var b = 2 * (p1 - p0);
  10531. var c = p0 - val;
  10532. var n = 0;
  10533. if (isAroundZero(a)) {
  10534. if (isNotAroundZero$1(b)) {
  10535. var t1 = -c / b;
  10536. if (t1 >= 0 && t1 <= 1) {
  10537. roots[n++] = t1;
  10538. }
  10539. }
  10540. }
  10541. else {
  10542. var disc = b * b - 4 * a * c;
  10543. if (isAroundZero(disc)) {
  10544. var t1 = -b / (2 * a);
  10545. if (t1 >= 0 && t1 <= 1) {
  10546. roots[n++] = t1;
  10547. }
  10548. }
  10549. else if (disc > 0) {
  10550. var discSqrt = mathSqrt$2(disc);
  10551. var t1 = (-b + discSqrt) / (2 * a);
  10552. var t2 = (-b - discSqrt) / (2 * a);
  10553. if (t1 >= 0 && t1 <= 1) {
  10554. roots[n++] = t1;
  10555. }
  10556. if (t2 >= 0 && t2 <= 1) {
  10557. roots[n++] = t2;
  10558. }
  10559. }
  10560. }
  10561. return n;
  10562. }
  10563. /**
  10564. * 计算二次贝塞尔方程极限值
  10565. * @memberOf module:zrender/core/curve
  10566. * @param {number} p0
  10567. * @param {number} p1
  10568. * @param {number} p2
  10569. * @return {number}
  10570. */
  10571. function quadraticExtremum(p0, p1, p2) {
  10572. var divider = p0 + p2 - 2 * p1;
  10573. if (divider === 0) {
  10574. // p1 is center of p0 and p2
  10575. return 0.5;
  10576. }
  10577. else {
  10578. return (p0 - p1) / divider;
  10579. }
  10580. }
  10581. /**
  10582. * 细分二次贝塞尔曲线
  10583. * @memberOf module:zrender/core/curve
  10584. * @param {number} p0
  10585. * @param {number} p1
  10586. * @param {number} p2
  10587. * @param {number} t
  10588. * @param {Array.<number>} out
  10589. */
  10590. function quadraticSubdivide(p0, p1, p2, t, out) {
  10591. var p01 = (p1 - p0) * t + p0;
  10592. var p12 = (p2 - p1) * t + p1;
  10593. var p012 = (p12 - p01) * t + p01;
  10594. // Seg0
  10595. out[0] = p0;
  10596. out[1] = p01;
  10597. out[2] = p012;
  10598. // Seg1
  10599. out[3] = p012;
  10600. out[4] = p12;
  10601. out[5] = p2;
  10602. }
  10603. /**
  10604. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10605. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10606. * @param {number} x0
  10607. * @param {number} y0
  10608. * @param {number} x1
  10609. * @param {number} y1
  10610. * @param {number} x2
  10611. * @param {number} y2
  10612. * @param {number} x
  10613. * @param {number} y
  10614. * @param {Array.<number>} out 投射点
  10615. * @return {number}
  10616. */
  10617. function quadraticProjectPoint(
  10618. x0, y0, x1, y1, x2, y2,
  10619. x, y, out
  10620. ) {
  10621. // http://pomax.github.io/bezierinfo/#projections
  10622. var t;
  10623. var interval = 0.005;
  10624. var d = Infinity;
  10625. _v0[0] = x;
  10626. _v0[1] = y;
  10627. // 先粗略估计一下可能的最小距离的 t 值
  10628. // PENDING
  10629. for (var _t = 0; _t < 1; _t += 0.05) {
  10630. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10631. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10632. var d1 = distSquare(_v0, _v1);
  10633. if (d1 < d) {
  10634. t = _t;
  10635. d = d1;
  10636. }
  10637. }
  10638. d = Infinity;
  10639. // At most 32 iteration
  10640. for (var i = 0; i < 32; i++) {
  10641. if (interval < EPSILON_NUMERIC) {
  10642. break;
  10643. }
  10644. var prev = t - interval;
  10645. var next = t + interval;
  10646. // t - interval
  10647. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10648. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10649. var d1 = distSquare(_v1, _v0);
  10650. if (prev >= 0 && d1 < d) {
  10651. t = prev;
  10652. d = d1;
  10653. }
  10654. else {
  10655. // t + interval
  10656. _v2[0] = quadraticAt(x0, x1, x2, next);
  10657. _v2[1] = quadraticAt(y0, y1, y2, next);
  10658. var d2 = distSquare(_v2, _v0);
  10659. if (next <= 1 && d2 < d) {
  10660. t = next;
  10661. d = d2;
  10662. }
  10663. else {
  10664. interval *= 0.5;
  10665. }
  10666. }
  10667. }
  10668. // t
  10669. if (out) {
  10670. out[0] = quadraticAt(x0, x1, x2, t);
  10671. out[1] = quadraticAt(y0, y1, y2, t);
  10672. }
  10673. // console.log(interval, i);
  10674. return mathSqrt$2(d);
  10675. }
  10676. /**
  10677. * @author Yi Shen(https://github.com/pissang)
  10678. */
  10679. var mathMin$3 = Math.min;
  10680. var mathMax$3 = Math.max;
  10681. var mathSin$2 = Math.sin;
  10682. var mathCos$2 = Math.cos;
  10683. var PI2 = Math.PI * 2;
  10684. var start = create();
  10685. var end = create();
  10686. var extremity = create();
  10687. /**
  10688. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10689. * @module zrender/core/bbox
  10690. * @param {Array<Object>} points 顶点数组
  10691. * @param {number} min
  10692. * @param {number} max
  10693. */
  10694. function fromPoints(points, min$$1, max$$1) {
  10695. if (points.length === 0) {
  10696. return;
  10697. }
  10698. var p = points[0];
  10699. var left = p[0];
  10700. var right = p[0];
  10701. var top = p[1];
  10702. var bottom = p[1];
  10703. var i;
  10704. for (i = 1; i < points.length; i++) {
  10705. p = points[i];
  10706. left = mathMin$3(left, p[0]);
  10707. right = mathMax$3(right, p[0]);
  10708. top = mathMin$3(top, p[1]);
  10709. bottom = mathMax$3(bottom, p[1]);
  10710. }
  10711. min$$1[0] = left;
  10712. min$$1[1] = top;
  10713. max$$1[0] = right;
  10714. max$$1[1] = bottom;
  10715. }
  10716. /**
  10717. * @memberOf module:zrender/core/bbox
  10718. * @param {number} x0
  10719. * @param {number} y0
  10720. * @param {number} x1
  10721. * @param {number} y1
  10722. * @param {Array.<number>} min
  10723. * @param {Array.<number>} max
  10724. */
  10725. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10726. min$$1[0] = mathMin$3(x0, x1);
  10727. min$$1[1] = mathMin$3(y0, y1);
  10728. max$$1[0] = mathMax$3(x0, x1);
  10729. max$$1[1] = mathMax$3(y0, y1);
  10730. }
  10731. var xDim = [];
  10732. var yDim = [];
  10733. /**
  10734. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10735. * @memberOf module:zrender/core/bbox
  10736. * @param {number} x0
  10737. * @param {number} y0
  10738. * @param {number} x1
  10739. * @param {number} y1
  10740. * @param {number} x2
  10741. * @param {number} y2
  10742. * @param {number} x3
  10743. * @param {number} y3
  10744. * @param {Array.<number>} min
  10745. * @param {Array.<number>} max
  10746. */
  10747. function fromCubic(
  10748. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10749. ) {
  10750. var cubicExtrema$$1 = cubicExtrema;
  10751. var cubicAt$$1 = cubicAt;
  10752. var i;
  10753. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10754. min$$1[0] = Infinity;
  10755. min$$1[1] = Infinity;
  10756. max$$1[0] = -Infinity;
  10757. max$$1[1] = -Infinity;
  10758. for (i = 0; i < n; i++) {
  10759. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10760. min$$1[0] = mathMin$3(x, min$$1[0]);
  10761. max$$1[0] = mathMax$3(x, max$$1[0]);
  10762. }
  10763. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10764. for (i = 0; i < n; i++) {
  10765. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10766. min$$1[1] = mathMin$3(y, min$$1[1]);
  10767. max$$1[1] = mathMax$3(y, max$$1[1]);
  10768. }
  10769. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10770. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10771. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10772. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10773. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10774. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10775. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10776. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10777. }
  10778. /**
  10779. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10780. * @memberOf module:zrender/core/bbox
  10781. * @param {number} x0
  10782. * @param {number} y0
  10783. * @param {number} x1
  10784. * @param {number} y1
  10785. * @param {number} x2
  10786. * @param {number} y2
  10787. * @param {Array.<number>} min
  10788. * @param {Array.<number>} max
  10789. */
  10790. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10791. var quadraticExtremum$$1 = quadraticExtremum;
  10792. var quadraticAt$$1 = quadraticAt;
  10793. // Find extremities, where derivative in x dim or y dim is zero
  10794. var tx =
  10795. mathMax$3(
  10796. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10797. );
  10798. var ty =
  10799. mathMax$3(
  10800. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10801. );
  10802. var x = quadraticAt$$1(x0, x1, x2, tx);
  10803. var y = quadraticAt$$1(y0, y1, y2, ty);
  10804. min$$1[0] = mathMin$3(x0, x2, x);
  10805. min$$1[1] = mathMin$3(y0, y2, y);
  10806. max$$1[0] = mathMax$3(x0, x2, x);
  10807. max$$1[1] = mathMax$3(y0, y2, y);
  10808. }
  10809. /**
  10810. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10811. * @method
  10812. * @memberOf module:zrender/core/bbox
  10813. * @param {number} x
  10814. * @param {number} y
  10815. * @param {number} rx
  10816. * @param {number} ry
  10817. * @param {number} startAngle
  10818. * @param {number} endAngle
  10819. * @param {number} anticlockwise
  10820. * @param {Array.<number>} min
  10821. * @param {Array.<number>} max
  10822. */
  10823. function fromArc(
  10824. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10825. ) {
  10826. var vec2Min = min;
  10827. var vec2Max = max;
  10828. var diff = Math.abs(startAngle - endAngle);
  10829. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10830. // Is a circle
  10831. min$$1[0] = x - rx;
  10832. min$$1[1] = y - ry;
  10833. max$$1[0] = x + rx;
  10834. max$$1[1] = y + ry;
  10835. return;
  10836. }
  10837. start[0] = mathCos$2(startAngle) * rx + x;
  10838. start[1] = mathSin$2(startAngle) * ry + y;
  10839. end[0] = mathCos$2(endAngle) * rx + x;
  10840. end[1] = mathSin$2(endAngle) * ry + y;
  10841. vec2Min(min$$1, start, end);
  10842. vec2Max(max$$1, start, end);
  10843. // Thresh to [0, Math.PI * 2]
  10844. startAngle = startAngle % (PI2);
  10845. if (startAngle < 0) {
  10846. startAngle = startAngle + PI2;
  10847. }
  10848. endAngle = endAngle % (PI2);
  10849. if (endAngle < 0) {
  10850. endAngle = endAngle + PI2;
  10851. }
  10852. if (startAngle > endAngle && !anticlockwise) {
  10853. endAngle += PI2;
  10854. }
  10855. else if (startAngle < endAngle && anticlockwise) {
  10856. startAngle += PI2;
  10857. }
  10858. if (anticlockwise) {
  10859. var tmp = endAngle;
  10860. endAngle = startAngle;
  10861. startAngle = tmp;
  10862. }
  10863. // var number = 0;
  10864. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10865. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10866. if (angle > startAngle) {
  10867. extremity[0] = mathCos$2(angle) * rx + x;
  10868. extremity[1] = mathSin$2(angle) * ry + y;
  10869. vec2Min(min$$1, extremity, min$$1);
  10870. vec2Max(max$$1, extremity, max$$1);
  10871. }
  10872. }
  10873. }
  10874. /**
  10875. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10876. * 可以用于 isInsidePath 判断以及获取boundingRect
  10877. *
  10878. * @module zrender/core/PathProxy
  10879. * @author Yi Shen (http://www.github.com/pissang)
  10880. */
  10881. // TODO getTotalLength, getPointAtLength
  10882. var CMD = {
  10883. M: 1,
  10884. L: 2,
  10885. C: 3,
  10886. Q: 4,
  10887. A: 5,
  10888. Z: 6,
  10889. // Rect
  10890. R: 7
  10891. };
  10892. // var CMD_MEM_SIZE = {
  10893. // M: 3,
  10894. // L: 3,
  10895. // C: 7,
  10896. // Q: 5,
  10897. // A: 9,
  10898. // R: 5,
  10899. // Z: 1
  10900. // };
  10901. var min$1 = [];
  10902. var max$1 = [];
  10903. var min2 = [];
  10904. var max2 = [];
  10905. var mathMin$2 = Math.min;
  10906. var mathMax$2 = Math.max;
  10907. var mathCos$1 = Math.cos;
  10908. var mathSin$1 = Math.sin;
  10909. var mathSqrt$1 = Math.sqrt;
  10910. var mathAbs = Math.abs;
  10911. var hasTypedArray = typeof Float32Array != 'undefined';
  10912. /**
  10913. * @alias module:zrender/core/PathProxy
  10914. * @constructor
  10915. */
  10916. var PathProxy = function (notSaveData) {
  10917. this._saveData = !(notSaveData || false);
  10918. if (this._saveData) {
  10919. /**
  10920. * Path data. Stored as flat array
  10921. * @type {Array.<Object>}
  10922. */
  10923. this.data = [];
  10924. }
  10925. this._ctx = null;
  10926. };
  10927. /**
  10928. * 快速计算Path包围盒(并不是最小包围盒)
  10929. * @return {Object}
  10930. */
  10931. PathProxy.prototype = {
  10932. constructor: PathProxy,
  10933. _xi: 0,
  10934. _yi: 0,
  10935. _x0: 0,
  10936. _y0: 0,
  10937. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10938. _ux: 0,
  10939. _uy: 0,
  10940. _len: 0,
  10941. _lineDash: null,
  10942. _dashOffset: 0,
  10943. _dashIdx: 0,
  10944. _dashSum: 0,
  10945. /**
  10946. * @readOnly
  10947. */
  10948. setScale: function (sx, sy) {
  10949. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  10950. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  10951. },
  10952. getContext: function () {
  10953. return this._ctx;
  10954. },
  10955. /**
  10956. * @param {CanvasRenderingContext2D} ctx
  10957. * @return {module:zrender/core/PathProxy}
  10958. */
  10959. beginPath: function (ctx) {
  10960. this._ctx = ctx;
  10961. ctx && ctx.beginPath();
  10962. ctx && (this.dpr = ctx.dpr);
  10963. // Reset
  10964. if (this._saveData) {
  10965. this._len = 0;
  10966. }
  10967. if (this._lineDash) {
  10968. this._lineDash = null;
  10969. this._dashOffset = 0;
  10970. }
  10971. return this;
  10972. },
  10973. /**
  10974. * @param {number} x
  10975. * @param {number} y
  10976. * @return {module:zrender/core/PathProxy}
  10977. */
  10978. moveTo: function (x, y) {
  10979. this.addData(CMD.M, x, y);
  10980. this._ctx && this._ctx.moveTo(x, y);
  10981. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  10982. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  10983. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  10984. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  10985. this._x0 = x;
  10986. this._y0 = y;
  10987. this._xi = x;
  10988. this._yi = y;
  10989. return this;
  10990. },
  10991. /**
  10992. * @param {number} x
  10993. * @param {number} y
  10994. * @return {module:zrender/core/PathProxy}
  10995. */
  10996. lineTo: function (x, y) {
  10997. var exceedUnit = mathAbs(x - this._xi) > this._ux
  10998. || mathAbs(y - this._yi) > this._uy
  10999. // Force draw the first segment
  11000. || this._len < 5;
  11001. this.addData(CMD.L, x, y);
  11002. if (this._ctx && exceedUnit) {
  11003. this._needsDash() ? this._dashedLineTo(x, y)
  11004. : this._ctx.lineTo(x, y);
  11005. }
  11006. if (exceedUnit) {
  11007. this._xi = x;
  11008. this._yi = y;
  11009. }
  11010. return this;
  11011. },
  11012. /**
  11013. * @param {number} x1
  11014. * @param {number} y1
  11015. * @param {number} x2
  11016. * @param {number} y2
  11017. * @param {number} x3
  11018. * @param {number} y3
  11019. * @return {module:zrender/core/PathProxy}
  11020. */
  11021. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11022. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11023. if (this._ctx) {
  11024. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11025. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11026. }
  11027. this._xi = x3;
  11028. this._yi = y3;
  11029. return this;
  11030. },
  11031. /**
  11032. * @param {number} x1
  11033. * @param {number} y1
  11034. * @param {number} x2
  11035. * @param {number} y2
  11036. * @return {module:zrender/core/PathProxy}
  11037. */
  11038. quadraticCurveTo: function (x1, y1, x2, y2) {
  11039. this.addData(CMD.Q, x1, y1, x2, y2);
  11040. if (this._ctx) {
  11041. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11042. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11043. }
  11044. this._xi = x2;
  11045. this._yi = y2;
  11046. return this;
  11047. },
  11048. /**
  11049. * @param {number} cx
  11050. * @param {number} cy
  11051. * @param {number} r
  11052. * @param {number} startAngle
  11053. * @param {number} endAngle
  11054. * @param {boolean} anticlockwise
  11055. * @return {module:zrender/core/PathProxy}
  11056. */
  11057. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11058. this.addData(
  11059. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11060. );
  11061. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11062. this._xi = mathCos$1(endAngle) * r + cx;
  11063. this._yi = mathSin$1(endAngle) * r + cx;
  11064. return this;
  11065. },
  11066. // TODO
  11067. arcTo: function (x1, y1, x2, y2, radius) {
  11068. if (this._ctx) {
  11069. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11070. }
  11071. return this;
  11072. },
  11073. // TODO
  11074. rect: function (x, y, w, h) {
  11075. this._ctx && this._ctx.rect(x, y, w, h);
  11076. this.addData(CMD.R, x, y, w, h);
  11077. return this;
  11078. },
  11079. /**
  11080. * @return {module:zrender/core/PathProxy}
  11081. */
  11082. closePath: function () {
  11083. this.addData(CMD.Z);
  11084. var ctx = this._ctx;
  11085. var x0 = this._x0;
  11086. var y0 = this._y0;
  11087. if (ctx) {
  11088. this._needsDash() && this._dashedLineTo(x0, y0);
  11089. ctx.closePath();
  11090. }
  11091. this._xi = x0;
  11092. this._yi = y0;
  11093. return this;
  11094. },
  11095. /**
  11096. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11097. * stroke 同样
  11098. * @param {CanvasRenderingContext2D} ctx
  11099. * @return {module:zrender/core/PathProxy}
  11100. */
  11101. fill: function (ctx) {
  11102. ctx && ctx.fill();
  11103. this.toStatic();
  11104. },
  11105. /**
  11106. * @param {CanvasRenderingContext2D} ctx
  11107. * @return {module:zrender/core/PathProxy}
  11108. */
  11109. stroke: function (ctx) {
  11110. ctx && ctx.stroke();
  11111. this.toStatic();
  11112. },
  11113. /**
  11114. * 必须在其它绘制命令前调用
  11115. * Must be invoked before all other path drawing methods
  11116. * @return {module:zrender/core/PathProxy}
  11117. */
  11118. setLineDash: function (lineDash) {
  11119. if (lineDash instanceof Array) {
  11120. this._lineDash = lineDash;
  11121. this._dashIdx = 0;
  11122. var lineDashSum = 0;
  11123. for (var i = 0; i < lineDash.length; i++) {
  11124. lineDashSum += lineDash[i];
  11125. }
  11126. this._dashSum = lineDashSum;
  11127. }
  11128. return this;
  11129. },
  11130. /**
  11131. * 必须在其它绘制命令前调用
  11132. * Must be invoked before all other path drawing methods
  11133. * @return {module:zrender/core/PathProxy}
  11134. */
  11135. setLineDashOffset: function (offset) {
  11136. this._dashOffset = offset;
  11137. return this;
  11138. },
  11139. /**
  11140. *
  11141. * @return {boolean}
  11142. */
  11143. len: function () {
  11144. return this._len;
  11145. },
  11146. /**
  11147. * 直接设置 Path 数据
  11148. */
  11149. setData: function (data) {
  11150. var len$$1 = data.length;
  11151. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11152. this.data = new Float32Array(len$$1);
  11153. }
  11154. for (var i = 0; i < len$$1; i++) {
  11155. this.data[i] = data[i];
  11156. }
  11157. this._len = len$$1;
  11158. },
  11159. /**
  11160. * 添加子路径
  11161. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11162. */
  11163. appendPath: function (path) {
  11164. if (!(path instanceof Array)) {
  11165. path = [path];
  11166. }
  11167. var len$$1 = path.length;
  11168. var appendSize = 0;
  11169. var offset = this._len;
  11170. for (var i = 0; i < len$$1; i++) {
  11171. appendSize += path[i].len();
  11172. }
  11173. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11174. this.data = new Float32Array(offset + appendSize);
  11175. }
  11176. for (var i = 0; i < len$$1; i++) {
  11177. var appendPathData = path[i].data;
  11178. for (var k = 0; k < appendPathData.length; k++) {
  11179. this.data[offset++] = appendPathData[k];
  11180. }
  11181. }
  11182. this._len = offset;
  11183. },
  11184. /**
  11185. * 填充 Path 数据。
  11186. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11187. */
  11188. addData: function (cmd) {
  11189. if (!this._saveData) {
  11190. return;
  11191. }
  11192. var data = this.data;
  11193. if (this._len + arguments.length > data.length) {
  11194. // 因为之前的数组已经转换成静态的 Float32Array
  11195. // 所以不够用时需要扩展一个新的动态数组
  11196. this._expandData();
  11197. data = this.data;
  11198. }
  11199. for (var i = 0; i < arguments.length; i++) {
  11200. data[this._len++] = arguments[i];
  11201. }
  11202. this._prevCmd = cmd;
  11203. },
  11204. _expandData: function () {
  11205. // Only if data is Float32Array
  11206. if (!(this.data instanceof Array)) {
  11207. var newData = [];
  11208. for (var i = 0; i < this._len; i++) {
  11209. newData[i] = this.data[i];
  11210. }
  11211. this.data = newData;
  11212. }
  11213. },
  11214. /**
  11215. * If needs js implemented dashed line
  11216. * @return {boolean}
  11217. * @private
  11218. */
  11219. _needsDash: function () {
  11220. return this._lineDash;
  11221. },
  11222. _dashedLineTo: function (x1, y1) {
  11223. var dashSum = this._dashSum;
  11224. var offset = this._dashOffset;
  11225. var lineDash = this._lineDash;
  11226. var ctx = this._ctx;
  11227. var x0 = this._xi;
  11228. var y0 = this._yi;
  11229. var dx = x1 - x0;
  11230. var dy = y1 - y0;
  11231. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11232. var x = x0;
  11233. var y = y0;
  11234. var dash;
  11235. var nDash = lineDash.length;
  11236. var idx;
  11237. dx /= dist$$1;
  11238. dy /= dist$$1;
  11239. if (offset < 0) {
  11240. // Convert to positive offset
  11241. offset = dashSum + offset;
  11242. }
  11243. offset %= dashSum;
  11244. x -= offset * dx;
  11245. y -= offset * dy;
  11246. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11247. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11248. idx = this._dashIdx;
  11249. dash = lineDash[idx];
  11250. x += dx * dash;
  11251. y += dy * dash;
  11252. this._dashIdx = (idx + 1) % nDash;
  11253. // Skip positive offset
  11254. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11255. continue;
  11256. }
  11257. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11258. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11259. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11260. );
  11261. }
  11262. // Offset for next lineTo
  11263. dx = x - x1;
  11264. dy = y - y1;
  11265. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11266. },
  11267. // Not accurate dashed line to
  11268. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11269. var dashSum = this._dashSum;
  11270. var offset = this._dashOffset;
  11271. var lineDash = this._lineDash;
  11272. var ctx = this._ctx;
  11273. var x0 = this._xi;
  11274. var y0 = this._yi;
  11275. var t;
  11276. var dx;
  11277. var dy;
  11278. var cubicAt$$1 = cubicAt;
  11279. var bezierLen = 0;
  11280. var idx = this._dashIdx;
  11281. var nDash = lineDash.length;
  11282. var x;
  11283. var y;
  11284. var tmpLen = 0;
  11285. if (offset < 0) {
  11286. // Convert to positive offset
  11287. offset = dashSum + offset;
  11288. }
  11289. offset %= dashSum;
  11290. // Bezier approx length
  11291. for (t = 0; t < 1; t += 0.1) {
  11292. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11293. - cubicAt$$1(x0, x1, x2, x3, t);
  11294. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11295. - cubicAt$$1(y0, y1, y2, y3, t);
  11296. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11297. }
  11298. // Find idx after add offset
  11299. for (; idx < nDash; idx++) {
  11300. tmpLen += lineDash[idx];
  11301. if (tmpLen > offset) {
  11302. break;
  11303. }
  11304. }
  11305. t = (tmpLen - offset) / bezierLen;
  11306. while (t <= 1) {
  11307. x = cubicAt$$1(x0, x1, x2, x3, t);
  11308. y = cubicAt$$1(y0, y1, y2, y3, t);
  11309. // Use line to approximate dashed bezier
  11310. // Bad result if dash is long
  11311. idx % 2 ? ctx.moveTo(x, y)
  11312. : ctx.lineTo(x, y);
  11313. t += lineDash[idx] / bezierLen;
  11314. idx = (idx + 1) % nDash;
  11315. }
  11316. // Finish the last segment and calculate the new offset
  11317. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11318. dx = x3 - x;
  11319. dy = y3 - y;
  11320. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11321. },
  11322. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11323. // Convert quadratic to cubic using degree elevation
  11324. var x3 = x2;
  11325. var y3 = y2;
  11326. x2 = (x2 + 2 * x1) / 3;
  11327. y2 = (y2 + 2 * y1) / 3;
  11328. x1 = (this._xi + 2 * x1) / 3;
  11329. y1 = (this._yi + 2 * y1) / 3;
  11330. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11331. },
  11332. /**
  11333. * 转成静态的 Float32Array 减少堆内存占用
  11334. * Convert dynamic array to static Float32Array
  11335. */
  11336. toStatic: function () {
  11337. var data = this.data;
  11338. if (data instanceof Array) {
  11339. data.length = this._len;
  11340. if (hasTypedArray) {
  11341. this.data = new Float32Array(data);
  11342. }
  11343. }
  11344. },
  11345. /**
  11346. * @return {module:zrender/core/BoundingRect}
  11347. */
  11348. getBoundingRect: function () {
  11349. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11350. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11351. var data = this.data;
  11352. var xi = 0;
  11353. var yi = 0;
  11354. var x0 = 0;
  11355. var y0 = 0;
  11356. for (var i = 0; i < data.length;) {
  11357. var cmd = data[i++];
  11358. if (i == 1) {
  11359. // 如果第一个命令是 L, C, Q
  11360. // 则 previous point 同绘制命令的第一个 point
  11361. //
  11362. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11363. xi = data[i];
  11364. yi = data[i + 1];
  11365. x0 = xi;
  11366. y0 = yi;
  11367. }
  11368. switch (cmd) {
  11369. case CMD.M:
  11370. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11371. // 在 closePath 的时候使用
  11372. x0 = data[i++];
  11373. y0 = data[i++];
  11374. xi = x0;
  11375. yi = y0;
  11376. min2[0] = x0;
  11377. min2[1] = y0;
  11378. max2[0] = x0;
  11379. max2[1] = y0;
  11380. break;
  11381. case CMD.L:
  11382. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11383. xi = data[i++];
  11384. yi = data[i++];
  11385. break;
  11386. case CMD.C:
  11387. fromCubic(
  11388. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11389. min2, max2
  11390. );
  11391. xi = data[i++];
  11392. yi = data[i++];
  11393. break;
  11394. case CMD.Q:
  11395. fromQuadratic(
  11396. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11397. min2, max2
  11398. );
  11399. xi = data[i++];
  11400. yi = data[i++];
  11401. break;
  11402. case CMD.A:
  11403. // TODO Arc 判断的开销比较大
  11404. var cx = data[i++];
  11405. var cy = data[i++];
  11406. var rx = data[i++];
  11407. var ry = data[i++];
  11408. var startAngle = data[i++];
  11409. var endAngle = data[i++] + startAngle;
  11410. // TODO Arc 旋转
  11411. var psi = data[i++];
  11412. var anticlockwise = 1 - data[i++];
  11413. if (i == 1) {
  11414. // 直接使用 arc 命令
  11415. // 第一个命令起点还未定义
  11416. x0 = mathCos$1(startAngle) * rx + cx;
  11417. y0 = mathSin$1(startAngle) * ry + cy;
  11418. }
  11419. fromArc(
  11420. cx, cy, rx, ry, startAngle, endAngle,
  11421. anticlockwise, min2, max2
  11422. );
  11423. xi = mathCos$1(endAngle) * rx + cx;
  11424. yi = mathSin$1(endAngle) * ry + cy;
  11425. break;
  11426. case CMD.R:
  11427. x0 = xi = data[i++];
  11428. y0 = yi = data[i++];
  11429. var width = data[i++];
  11430. var height = data[i++];
  11431. // Use fromLine
  11432. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11433. break;
  11434. case CMD.Z:
  11435. xi = x0;
  11436. yi = y0;
  11437. break;
  11438. }
  11439. // Union
  11440. min(min$1, min$1, min2);
  11441. max(max$1, max$1, max2);
  11442. }
  11443. // No data
  11444. if (i === 0) {
  11445. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11446. }
  11447. return new BoundingRect(
  11448. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11449. );
  11450. },
  11451. /**
  11452. * Rebuild path from current data
  11453. * Rebuild path will not consider javascript implemented line dash.
  11454. * @param {CanvasRenderingContext2D} ctx
  11455. */
  11456. rebuildPath: function (ctx) {
  11457. var d = this.data;
  11458. var x0, y0;
  11459. var xi, yi;
  11460. var x, y;
  11461. var ux = this._ux;
  11462. var uy = this._uy;
  11463. var len$$1 = this._len;
  11464. for (var i = 0; i < len$$1;) {
  11465. var cmd = d[i++];
  11466. if (i == 1) {
  11467. // 如果第一个命令是 L, C, Q
  11468. // 则 previous point 同绘制命令的第一个 point
  11469. //
  11470. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11471. xi = d[i];
  11472. yi = d[i + 1];
  11473. x0 = xi;
  11474. y0 = yi;
  11475. }
  11476. switch (cmd) {
  11477. case CMD.M:
  11478. x0 = xi = d[i++];
  11479. y0 = yi = d[i++];
  11480. ctx.moveTo(xi, yi);
  11481. break;
  11482. case CMD.L:
  11483. x = d[i++];
  11484. y = d[i++];
  11485. // Not draw too small seg between
  11486. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11487. ctx.lineTo(x, y);
  11488. xi = x;
  11489. yi = y;
  11490. }
  11491. break;
  11492. case CMD.C:
  11493. ctx.bezierCurveTo(
  11494. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11495. );
  11496. xi = d[i - 2];
  11497. yi = d[i - 1];
  11498. break;
  11499. case CMD.Q:
  11500. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11501. xi = d[i - 2];
  11502. yi = d[i - 1];
  11503. break;
  11504. case CMD.A:
  11505. var cx = d[i++];
  11506. var cy = d[i++];
  11507. var rx = d[i++];
  11508. var ry = d[i++];
  11509. var theta = d[i++];
  11510. var dTheta = d[i++];
  11511. var psi = d[i++];
  11512. var fs = d[i++];
  11513. var r = (rx > ry) ? rx : ry;
  11514. var scaleX = (rx > ry) ? 1 : rx / ry;
  11515. var scaleY = (rx > ry) ? ry / rx : 1;
  11516. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11517. var endAngle = theta + dTheta;
  11518. if (isEllipse) {
  11519. ctx.translate(cx, cy);
  11520. ctx.rotate(psi);
  11521. ctx.scale(scaleX, scaleY);
  11522. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11523. ctx.scale(1 / scaleX, 1 / scaleY);
  11524. ctx.rotate(-psi);
  11525. ctx.translate(-cx, -cy);
  11526. }
  11527. else {
  11528. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11529. }
  11530. if (i == 1) {
  11531. // 直接使用 arc 命令
  11532. // 第一个命令起点还未定义
  11533. x0 = mathCos$1(theta) * rx + cx;
  11534. y0 = mathSin$1(theta) * ry + cy;
  11535. }
  11536. xi = mathCos$1(endAngle) * rx + cx;
  11537. yi = mathSin$1(endAngle) * ry + cy;
  11538. break;
  11539. case CMD.R:
  11540. x0 = xi = d[i];
  11541. y0 = yi = d[i + 1];
  11542. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11543. break;
  11544. case CMD.Z:
  11545. ctx.closePath();
  11546. xi = x0;
  11547. yi = y0;
  11548. }
  11549. }
  11550. }
  11551. };
  11552. PathProxy.CMD = CMD;
  11553. /**
  11554. * 线段包含判断
  11555. * @param {number} x0
  11556. * @param {number} y0
  11557. * @param {number} x1
  11558. * @param {number} y1
  11559. * @param {number} lineWidth
  11560. * @param {number} x
  11561. * @param {number} y
  11562. * @return {boolean}
  11563. */
  11564. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11565. if (lineWidth === 0) {
  11566. return false;
  11567. }
  11568. var _l = lineWidth;
  11569. var _a = 0;
  11570. var _b = x0;
  11571. // Quick reject
  11572. if (
  11573. (y > y0 + _l && y > y1 + _l)
  11574. || (y < y0 - _l && y < y1 - _l)
  11575. || (x > x0 + _l && x > x1 + _l)
  11576. || (x < x0 - _l && x < x1 - _l)
  11577. ) {
  11578. return false;
  11579. }
  11580. if (x0 !== x1) {
  11581. _a = (y0 - y1) / (x0 - x1);
  11582. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11583. }
  11584. else {
  11585. return Math.abs(x - x0) <= _l / 2;
  11586. }
  11587. var tmp = _a * x - y + _b;
  11588. var _s = tmp * tmp / (_a * _a + 1);
  11589. return _s <= _l / 2 * _l / 2;
  11590. }
  11591. /**
  11592. * 三次贝塞尔曲线描边包含判断
  11593. * @param {number} x0
  11594. * @param {number} y0
  11595. * @param {number} x1
  11596. * @param {number} y1
  11597. * @param {number} x2
  11598. * @param {number} y2
  11599. * @param {number} x3
  11600. * @param {number} y3
  11601. * @param {number} lineWidth
  11602. * @param {number} x
  11603. * @param {number} y
  11604. * @return {boolean}
  11605. */
  11606. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11607. if (lineWidth === 0) {
  11608. return false;
  11609. }
  11610. var _l = lineWidth;
  11611. // Quick reject
  11612. if (
  11613. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11614. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11615. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11616. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11617. ) {
  11618. return false;
  11619. }
  11620. var d = cubicProjectPoint(
  11621. x0, y0, x1, y1, x2, y2, x3, y3,
  11622. x, y, null
  11623. );
  11624. return d <= _l / 2;
  11625. }
  11626. /**
  11627. * 二次贝塞尔曲线描边包含判断
  11628. * @param {number} x0
  11629. * @param {number} y0
  11630. * @param {number} x1
  11631. * @param {number} y1
  11632. * @param {number} x2
  11633. * @param {number} y2
  11634. * @param {number} lineWidth
  11635. * @param {number} x
  11636. * @param {number} y
  11637. * @return {boolean}
  11638. */
  11639. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11640. if (lineWidth === 0) {
  11641. return false;
  11642. }
  11643. var _l = lineWidth;
  11644. // Quick reject
  11645. if (
  11646. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11647. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11648. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11649. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11650. ) {
  11651. return false;
  11652. }
  11653. var d = quadraticProjectPoint(
  11654. x0, y0, x1, y1, x2, y2,
  11655. x, y, null
  11656. );
  11657. return d <= _l / 2;
  11658. }
  11659. var PI2$3 = Math.PI * 2;
  11660. function normalizeRadian(angle) {
  11661. angle %= PI2$3;
  11662. if (angle < 0) {
  11663. angle += PI2$3;
  11664. }
  11665. return angle;
  11666. }
  11667. var PI2$2 = Math.PI * 2;
  11668. /**
  11669. * 圆弧描边包含判断
  11670. * @param {number} cx
  11671. * @param {number} cy
  11672. * @param {number} r
  11673. * @param {number} startAngle
  11674. * @param {number} endAngle
  11675. * @param {boolean} anticlockwise
  11676. * @param {number} lineWidth
  11677. * @param {number} x
  11678. * @param {number} y
  11679. * @return {Boolean}
  11680. */
  11681. function containStroke$4(
  11682. cx, cy, r, startAngle, endAngle, anticlockwise,
  11683. lineWidth, x, y
  11684. ) {
  11685. if (lineWidth === 0) {
  11686. return false;
  11687. }
  11688. var _l = lineWidth;
  11689. x -= cx;
  11690. y -= cy;
  11691. var d = Math.sqrt(x * x + y * y);
  11692. if ((d - _l > r) || (d + _l < r)) {
  11693. return false;
  11694. }
  11695. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11696. // Is a circle
  11697. return true;
  11698. }
  11699. if (anticlockwise) {
  11700. var tmp = startAngle;
  11701. startAngle = normalizeRadian(endAngle);
  11702. endAngle = normalizeRadian(tmp);
  11703. } else {
  11704. startAngle = normalizeRadian(startAngle);
  11705. endAngle = normalizeRadian(endAngle);
  11706. }
  11707. if (startAngle > endAngle) {
  11708. endAngle += PI2$2;
  11709. }
  11710. var angle = Math.atan2(y, x);
  11711. if (angle < 0) {
  11712. angle += PI2$2;
  11713. }
  11714. return (angle >= startAngle && angle <= endAngle)
  11715. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11716. }
  11717. function windingLine(x0, y0, x1, y1, x, y) {
  11718. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11719. return 0;
  11720. }
  11721. // Ignore horizontal line
  11722. if (y1 === y0) {
  11723. return 0;
  11724. }
  11725. var dir = y1 < y0 ? 1 : -1;
  11726. var t = (y - y0) / (y1 - y0);
  11727. // Avoid winding error when intersection point is the connect point of two line of polygon
  11728. if (t === 1 || t === 0) {
  11729. dir = y1 < y0 ? 0.5 : -0.5;
  11730. }
  11731. var x_ = t * (x1 - x0) + x0;
  11732. return x_ > x ? dir : 0;
  11733. }
  11734. var CMD$1 = PathProxy.CMD;
  11735. var PI2$1 = Math.PI * 2;
  11736. var EPSILON$2 = 1e-4;
  11737. function isAroundEqual(a, b) {
  11738. return Math.abs(a - b) < EPSILON$2;
  11739. }
  11740. // 临时数组
  11741. var roots = [-1, -1, -1];
  11742. var extrema = [-1, -1];
  11743. function swapExtrema() {
  11744. var tmp = extrema[0];
  11745. extrema[0] = extrema[1];
  11746. extrema[1] = tmp;
  11747. }
  11748. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11749. // Quick reject
  11750. if (
  11751. (y > y0 && y > y1 && y > y2 && y > y3)
  11752. || (y < y0 && y < y1 && y < y2 && y < y3)
  11753. ) {
  11754. return 0;
  11755. }
  11756. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11757. if (nRoots === 0) {
  11758. return 0;
  11759. }
  11760. else {
  11761. var w = 0;
  11762. var nExtrema = -1;
  11763. var y0_, y1_;
  11764. for (var i = 0; i < nRoots; i++) {
  11765. var t = roots[i];
  11766. // Avoid winding error when intersection point is the connect point of two line of polygon
  11767. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11768. var x_ = cubicAt(x0, x1, x2, x3, t);
  11769. if (x_ < x) { // Quick reject
  11770. continue;
  11771. }
  11772. if (nExtrema < 0) {
  11773. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11774. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11775. swapExtrema();
  11776. }
  11777. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11778. if (nExtrema > 1) {
  11779. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11780. }
  11781. }
  11782. if (nExtrema == 2) {
  11783. // 分成三段单调函数
  11784. if (t < extrema[0]) {
  11785. w += y0_ < y0 ? unit : -unit;
  11786. }
  11787. else if (t < extrema[1]) {
  11788. w += y1_ < y0_ ? unit : -unit;
  11789. }
  11790. else {
  11791. w += y3 < y1_ ? unit : -unit;
  11792. }
  11793. }
  11794. else {
  11795. // 分成两段单调函数
  11796. if (t < extrema[0]) {
  11797. w += y0_ < y0 ? unit : -unit;
  11798. }
  11799. else {
  11800. w += y3 < y0_ ? unit : -unit;
  11801. }
  11802. }
  11803. }
  11804. return w;
  11805. }
  11806. }
  11807. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11808. // Quick reject
  11809. if (
  11810. (y > y0 && y > y1 && y > y2)
  11811. || (y < y0 && y < y1 && y < y2)
  11812. ) {
  11813. return 0;
  11814. }
  11815. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11816. if (nRoots === 0) {
  11817. return 0;
  11818. }
  11819. else {
  11820. var t = quadraticExtremum(y0, y1, y2);
  11821. if (t >= 0 && t <= 1) {
  11822. var w = 0;
  11823. var y_ = quadraticAt(y0, y1, y2, t);
  11824. for (var i = 0; i < nRoots; i++) {
  11825. // Remove one endpoint.
  11826. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11827. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11828. if (x_ < x) { // Quick reject
  11829. continue;
  11830. }
  11831. if (roots[i] < t) {
  11832. w += y_ < y0 ? unit : -unit;
  11833. }
  11834. else {
  11835. w += y2 < y_ ? unit : -unit;
  11836. }
  11837. }
  11838. return w;
  11839. }
  11840. else {
  11841. // Remove one endpoint.
  11842. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11843. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11844. if (x_ < x) { // Quick reject
  11845. return 0;
  11846. }
  11847. return y2 < y0 ? unit : -unit;
  11848. }
  11849. }
  11850. }
  11851. // TODO
  11852. // Arc 旋转
  11853. function windingArc(
  11854. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11855. ) {
  11856. y -= cy;
  11857. if (y > r || y < -r) {
  11858. return 0;
  11859. }
  11860. var tmp = Math.sqrt(r * r - y * y);
  11861. roots[0] = -tmp;
  11862. roots[1] = tmp;
  11863. var diff = Math.abs(startAngle - endAngle);
  11864. if (diff < 1e-4) {
  11865. return 0;
  11866. }
  11867. if (diff % PI2$1 < 1e-4) {
  11868. // Is a circle
  11869. startAngle = 0;
  11870. endAngle = PI2$1;
  11871. var dir = anticlockwise ? 1 : -1;
  11872. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11873. return dir;
  11874. } else {
  11875. return 0;
  11876. }
  11877. }
  11878. if (anticlockwise) {
  11879. var tmp = startAngle;
  11880. startAngle = normalizeRadian(endAngle);
  11881. endAngle = normalizeRadian(tmp);
  11882. }
  11883. else {
  11884. startAngle = normalizeRadian(startAngle);
  11885. endAngle = normalizeRadian(endAngle);
  11886. }
  11887. if (startAngle > endAngle) {
  11888. endAngle += PI2$1;
  11889. }
  11890. var w = 0;
  11891. for (var i = 0; i < 2; i++) {
  11892. var x_ = roots[i];
  11893. if (x_ + cx > x) {
  11894. var angle = Math.atan2(y, x_);
  11895. var dir = anticlockwise ? 1 : -1;
  11896. if (angle < 0) {
  11897. angle = PI2$1 + angle;
  11898. }
  11899. if (
  11900. (angle >= startAngle && angle <= endAngle)
  11901. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11902. ) {
  11903. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11904. dir = -dir;
  11905. }
  11906. w += dir;
  11907. }
  11908. }
  11909. }
  11910. return w;
  11911. }
  11912. function containPath(data, lineWidth, isStroke, x, y) {
  11913. var w = 0;
  11914. var xi = 0;
  11915. var yi = 0;
  11916. var x0 = 0;
  11917. var y0 = 0;
  11918. for (var i = 0; i < data.length;) {
  11919. var cmd = data[i++];
  11920. // Begin a new subpath
  11921. if (cmd === CMD$1.M && i > 1) {
  11922. // Close previous subpath
  11923. if (!isStroke) {
  11924. w += windingLine(xi, yi, x0, y0, x, y);
  11925. }
  11926. // 如果被任何一个 subpath 包含
  11927. // if (w !== 0) {
  11928. // return true;
  11929. // }
  11930. }
  11931. if (i == 1) {
  11932. // 如果第一个命令是 L, C, Q
  11933. // 则 previous point 同绘制命令的第一个 point
  11934. //
  11935. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11936. xi = data[i];
  11937. yi = data[i + 1];
  11938. x0 = xi;
  11939. y0 = yi;
  11940. }
  11941. switch (cmd) {
  11942. case CMD$1.M:
  11943. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11944. // 在 closePath 的时候使用
  11945. x0 = data[i++];
  11946. y0 = data[i++];
  11947. xi = x0;
  11948. yi = y0;
  11949. break;
  11950. case CMD$1.L:
  11951. if (isStroke) {
  11952. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  11953. return true;
  11954. }
  11955. }
  11956. else {
  11957. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  11958. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  11959. }
  11960. xi = data[i++];
  11961. yi = data[i++];
  11962. break;
  11963. case CMD$1.C:
  11964. if (isStroke) {
  11965. if (containStroke$2(xi, yi,
  11966. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11967. lineWidth, x, y
  11968. )) {
  11969. return true;
  11970. }
  11971. }
  11972. else {
  11973. w += windingCubic(
  11974. xi, yi,
  11975. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11976. x, y
  11977. ) || 0;
  11978. }
  11979. xi = data[i++];
  11980. yi = data[i++];
  11981. break;
  11982. case CMD$1.Q:
  11983. if (isStroke) {
  11984. if (containStroke$3(xi, yi,
  11985. data[i++], data[i++], data[i], data[i + 1],
  11986. lineWidth, x, y
  11987. )) {
  11988. return true;
  11989. }
  11990. }
  11991. else {
  11992. w += windingQuadratic(
  11993. xi, yi,
  11994. data[i++], data[i++], data[i], data[i + 1],
  11995. x, y
  11996. ) || 0;
  11997. }
  11998. xi = data[i++];
  11999. yi = data[i++];
  12000. break;
  12001. case CMD$1.A:
  12002. // TODO Arc 判断的开销比较大
  12003. var cx = data[i++];
  12004. var cy = data[i++];
  12005. var rx = data[i++];
  12006. var ry = data[i++];
  12007. var theta = data[i++];
  12008. var dTheta = data[i++];
  12009. // TODO Arc 旋转
  12010. var psi = data[i++];
  12011. var anticlockwise = 1 - data[i++];
  12012. var x1 = Math.cos(theta) * rx + cx;
  12013. var y1 = Math.sin(theta) * ry + cy;
  12014. // 不是直接使用 arc 命令
  12015. if (i > 1) {
  12016. w += windingLine(xi, yi, x1, y1, x, y);
  12017. }
  12018. else {
  12019. // 第一个命令起点还未定义
  12020. x0 = x1;
  12021. y0 = y1;
  12022. }
  12023. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12024. var _x = (x - cx) * ry / rx + cx;
  12025. if (isStroke) {
  12026. if (containStroke$4(
  12027. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12028. lineWidth, _x, y
  12029. )) {
  12030. return true;
  12031. }
  12032. }
  12033. else {
  12034. w += windingArc(
  12035. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12036. _x, y
  12037. );
  12038. }
  12039. xi = Math.cos(theta + dTheta) * rx + cx;
  12040. yi = Math.sin(theta + dTheta) * ry + cy;
  12041. break;
  12042. case CMD$1.R:
  12043. x0 = xi = data[i++];
  12044. y0 = yi = data[i++];
  12045. var width = data[i++];
  12046. var height = data[i++];
  12047. var x1 = x0 + width;
  12048. var y1 = y0 + height;
  12049. if (isStroke) {
  12050. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12051. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12052. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12053. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12054. ) {
  12055. return true;
  12056. }
  12057. }
  12058. else {
  12059. // FIXME Clockwise ?
  12060. w += windingLine(x1, y0, x1, y1, x, y);
  12061. w += windingLine(x0, y1, x0, y0, x, y);
  12062. }
  12063. break;
  12064. case CMD$1.Z:
  12065. if (isStroke) {
  12066. if (containStroke$1(
  12067. xi, yi, x0, y0, lineWidth, x, y
  12068. )) {
  12069. return true;
  12070. }
  12071. }
  12072. else {
  12073. // Close a subpath
  12074. w += windingLine(xi, yi, x0, y0, x, y);
  12075. // 如果被任何一个 subpath 包含
  12076. // FIXME subpaths may overlap
  12077. // if (w !== 0) {
  12078. // return true;
  12079. // }
  12080. }
  12081. xi = x0;
  12082. yi = y0;
  12083. break;
  12084. }
  12085. }
  12086. if (!isStroke && !isAroundEqual(yi, y0)) {
  12087. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12088. }
  12089. return w !== 0;
  12090. }
  12091. function contain(pathData, x, y) {
  12092. return containPath(pathData, 0, false, x, y);
  12093. }
  12094. function containStroke(pathData, lineWidth, x, y) {
  12095. return containPath(pathData, lineWidth, true, x, y);
  12096. }
  12097. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12098. var abs = Math.abs;
  12099. var pathProxyForDraw = new PathProxy(true);
  12100. /**
  12101. * @alias module:zrender/graphic/Path
  12102. * @extends module:zrender/graphic/Displayable
  12103. * @constructor
  12104. * @param {Object} opts
  12105. */
  12106. function Path(opts) {
  12107. Displayable.call(this, opts);
  12108. /**
  12109. * @type {module:zrender/core/PathProxy}
  12110. * @readOnly
  12111. */
  12112. this.path = null;
  12113. }
  12114. Path.prototype = {
  12115. constructor: Path,
  12116. type: 'path',
  12117. __dirtyPath: true,
  12118. strokeContainThreshold: 5,
  12119. brush: function (ctx, prevEl) {
  12120. var style = this.style;
  12121. var path = this.path || pathProxyForDraw;
  12122. var hasStroke = style.hasStroke();
  12123. var hasFill = style.hasFill();
  12124. var fill = style.fill;
  12125. var stroke = style.stroke;
  12126. var hasFillGradient = hasFill && !!(fill.colorStops);
  12127. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12128. var hasFillPattern = hasFill && !!(fill.image);
  12129. var hasStrokePattern = hasStroke && !!(stroke.image);
  12130. style.bind(ctx, this, prevEl);
  12131. this.setTransform(ctx);
  12132. if (this.__dirty) {
  12133. var rect;
  12134. // Update gradient because bounding rect may changed
  12135. if (hasFillGradient) {
  12136. rect = rect || this.getBoundingRect();
  12137. this._fillGradient = style.getGradient(ctx, fill, rect);
  12138. }
  12139. if (hasStrokeGradient) {
  12140. rect = rect || this.getBoundingRect();
  12141. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12142. }
  12143. }
  12144. // Use the gradient or pattern
  12145. if (hasFillGradient) {
  12146. // PENDING If may have affect the state
  12147. ctx.fillStyle = this._fillGradient;
  12148. }
  12149. else if (hasFillPattern) {
  12150. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12151. }
  12152. if (hasStrokeGradient) {
  12153. ctx.strokeStyle = this._strokeGradient;
  12154. }
  12155. else if (hasStrokePattern) {
  12156. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12157. }
  12158. var lineDash = style.lineDash;
  12159. var lineDashOffset = style.lineDashOffset;
  12160. var ctxLineDash = !!ctx.setLineDash;
  12161. // Update path sx, sy
  12162. var scale = this.getGlobalScale();
  12163. path.setScale(scale[0], scale[1]);
  12164. // Proxy context
  12165. // Rebuild path in following 2 cases
  12166. // 1. Path is dirty
  12167. // 2. Path needs javascript implemented lineDash stroking.
  12168. // In this case, lineDash information will not be saved in PathProxy
  12169. if (this.__dirtyPath
  12170. || (lineDash && !ctxLineDash && hasStroke)
  12171. ) {
  12172. path.beginPath(ctx);
  12173. // Setting line dash before build path
  12174. if (lineDash && !ctxLineDash) {
  12175. path.setLineDash(lineDash);
  12176. path.setLineDashOffset(lineDashOffset);
  12177. }
  12178. this.buildPath(path, this.shape, false);
  12179. // Clear path dirty flag
  12180. if (this.path) {
  12181. this.__dirtyPath = false;
  12182. }
  12183. }
  12184. else {
  12185. // Replay path building
  12186. ctx.beginPath();
  12187. this.path.rebuildPath(ctx);
  12188. }
  12189. hasFill && path.fill(ctx);
  12190. if (lineDash && ctxLineDash) {
  12191. ctx.setLineDash(lineDash);
  12192. ctx.lineDashOffset = lineDashOffset;
  12193. }
  12194. hasStroke && path.stroke(ctx);
  12195. if (lineDash && ctxLineDash) {
  12196. // PENDING
  12197. // Remove lineDash
  12198. ctx.setLineDash([]);
  12199. }
  12200. // Draw rect text
  12201. if (style.text != null) {
  12202. // Only restore transform when needs draw text.
  12203. this.restoreTransform(ctx);
  12204. this.drawRectText(ctx, this.getBoundingRect());
  12205. }
  12206. },
  12207. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12208. // Like in circle
  12209. buildPath: function (ctx, shapeCfg, inBundle) {},
  12210. createPathProxy: function () {
  12211. this.path = new PathProxy();
  12212. },
  12213. getBoundingRect: function () {
  12214. var rect = this._rect;
  12215. var style = this.style;
  12216. var needsUpdateRect = !rect;
  12217. if (needsUpdateRect) {
  12218. var path = this.path;
  12219. if (!path) {
  12220. // Create path on demand.
  12221. path = this.path = new PathProxy();
  12222. }
  12223. if (this.__dirtyPath) {
  12224. path.beginPath();
  12225. this.buildPath(path, this.shape, false);
  12226. }
  12227. rect = path.getBoundingRect();
  12228. }
  12229. this._rect = rect;
  12230. if (style.hasStroke()) {
  12231. // Needs update rect with stroke lineWidth when
  12232. // 1. Element changes scale or lineWidth
  12233. // 2. Shape is changed
  12234. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12235. if (this.__dirty || needsUpdateRect) {
  12236. rectWithStroke.copy(rect);
  12237. // FIXME Must after updateTransform
  12238. var w = style.lineWidth;
  12239. // PENDING, Min line width is needed when line is horizontal or vertical
  12240. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12241. // Only add extra hover lineWidth when there are no fill
  12242. if (!style.hasFill()) {
  12243. w = Math.max(w, this.strokeContainThreshold || 4);
  12244. }
  12245. // Consider line width
  12246. // Line scale can't be 0;
  12247. if (lineScale > 1e-10) {
  12248. rectWithStroke.width += w / lineScale;
  12249. rectWithStroke.height += w / lineScale;
  12250. rectWithStroke.x -= w / lineScale / 2;
  12251. rectWithStroke.y -= w / lineScale / 2;
  12252. }
  12253. }
  12254. // Return rect with stroke
  12255. return rectWithStroke;
  12256. }
  12257. return rect;
  12258. },
  12259. contain: function (x, y) {
  12260. var localPos = this.transformCoordToLocal(x, y);
  12261. var rect = this.getBoundingRect();
  12262. var style = this.style;
  12263. x = localPos[0];
  12264. y = localPos[1];
  12265. if (rect.contain(x, y)) {
  12266. var pathData = this.path.data;
  12267. if (style.hasStroke()) {
  12268. var lineWidth = style.lineWidth;
  12269. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12270. // Line scale can't be 0;
  12271. if (lineScale > 1e-10) {
  12272. // Only add extra hover lineWidth when there are no fill
  12273. if (!style.hasFill()) {
  12274. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12275. }
  12276. if (containStroke(
  12277. pathData, lineWidth / lineScale, x, y
  12278. )) {
  12279. return true;
  12280. }
  12281. }
  12282. }
  12283. if (style.hasFill()) {
  12284. return contain(pathData, x, y);
  12285. }
  12286. }
  12287. return false;
  12288. },
  12289. /**
  12290. * @param {boolean} dirtyPath
  12291. */
  12292. dirty: function (dirtyPath) {
  12293. if (dirtyPath == null) {
  12294. dirtyPath = true;
  12295. }
  12296. // Only mark dirty, not mark clean
  12297. if (dirtyPath) {
  12298. this.__dirtyPath = dirtyPath;
  12299. this._rect = null;
  12300. }
  12301. this.__dirty = true;
  12302. this.__zr && this.__zr.refresh();
  12303. // Used as a clipping path
  12304. if (this.__clipTarget) {
  12305. this.__clipTarget.dirty();
  12306. }
  12307. },
  12308. /**
  12309. * Alias for animate('shape')
  12310. * @param {boolean} loop
  12311. */
  12312. animateShape: function (loop) {
  12313. return this.animate('shape', loop);
  12314. },
  12315. // Overwrite attrKV
  12316. attrKV: function (key, value) {
  12317. // FIXME
  12318. if (key === 'shape') {
  12319. this.setShape(value);
  12320. this.__dirtyPath = true;
  12321. this._rect = null;
  12322. }
  12323. else {
  12324. Displayable.prototype.attrKV.call(this, key, value);
  12325. }
  12326. },
  12327. /**
  12328. * @param {Object|string} key
  12329. * @param {*} value
  12330. */
  12331. setShape: function (key, value) {
  12332. var shape = this.shape;
  12333. // Path from string may not have shape
  12334. if (shape) {
  12335. if (isObject$1(key)) {
  12336. for (var name in key) {
  12337. if (key.hasOwnProperty(name)) {
  12338. shape[name] = key[name];
  12339. }
  12340. }
  12341. }
  12342. else {
  12343. shape[key] = value;
  12344. }
  12345. this.dirty(true);
  12346. }
  12347. return this;
  12348. },
  12349. getLineScale: function () {
  12350. var m = this.transform;
  12351. // Get the line scale.
  12352. // Determinant of `m` means how much the area is enlarged by the
  12353. // transformation. So its square root can be used as a scale factor
  12354. // for width.
  12355. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12356. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12357. : 1;
  12358. }
  12359. };
  12360. /**
  12361. * 扩展一个 Path element, 比如星形,圆等。
  12362. * Extend a path element
  12363. * @param {Object} props
  12364. * @param {string} props.type Path type
  12365. * @param {Function} props.init Initialize
  12366. * @param {Function} props.buildPath Overwrite buildPath method
  12367. * @param {Object} [props.style] Extended default style config
  12368. * @param {Object} [props.shape] Extended default shape config
  12369. */
  12370. Path.extend = function (defaults$$1) {
  12371. var Sub = function (opts) {
  12372. Path.call(this, opts);
  12373. if (defaults$$1.style) {
  12374. // Extend default style
  12375. this.style.extendFrom(defaults$$1.style, false);
  12376. }
  12377. // Extend default shape
  12378. var defaultShape = defaults$$1.shape;
  12379. if (defaultShape) {
  12380. this.shape = this.shape || {};
  12381. var thisShape = this.shape;
  12382. for (var name in defaultShape) {
  12383. if (
  12384. ! thisShape.hasOwnProperty(name)
  12385. && defaultShape.hasOwnProperty(name)
  12386. ) {
  12387. thisShape[name] = defaultShape[name];
  12388. }
  12389. }
  12390. }
  12391. defaults$$1.init && defaults$$1.init.call(this, opts);
  12392. };
  12393. inherits(Sub, Path);
  12394. // FIXME 不能 extend position, rotation 等引用对象
  12395. for (var name in defaults$$1) {
  12396. // Extending prototype values and methods
  12397. if (name !== 'style' && name !== 'shape') {
  12398. Sub.prototype[name] = defaults$$1[name];
  12399. }
  12400. }
  12401. return Sub;
  12402. };
  12403. inherits(Path, Displayable);
  12404. var CMD$2 = PathProxy.CMD;
  12405. var points = [[], [], []];
  12406. var mathSqrt$3 = Math.sqrt;
  12407. var mathAtan2 = Math.atan2;
  12408. var transformPath = function (path, m) {
  12409. var data = path.data;
  12410. var cmd;
  12411. var nPoint;
  12412. var i;
  12413. var j;
  12414. var k;
  12415. var p;
  12416. var M = CMD$2.M;
  12417. var C = CMD$2.C;
  12418. var L = CMD$2.L;
  12419. var R = CMD$2.R;
  12420. var A = CMD$2.A;
  12421. var Q = CMD$2.Q;
  12422. for (i = 0, j = 0; i < data.length;) {
  12423. cmd = data[i++];
  12424. j = i;
  12425. nPoint = 0;
  12426. switch (cmd) {
  12427. case M:
  12428. nPoint = 1;
  12429. break;
  12430. case L:
  12431. nPoint = 1;
  12432. break;
  12433. case C:
  12434. nPoint = 3;
  12435. break;
  12436. case Q:
  12437. nPoint = 2;
  12438. break;
  12439. case A:
  12440. var x = m[4];
  12441. var y = m[5];
  12442. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12443. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12444. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12445. // cx
  12446. data[i] *= sx;
  12447. data[i++] += x;
  12448. // cy
  12449. data[i] *= sy;
  12450. data[i++] += y;
  12451. // Scale rx and ry
  12452. // FIXME Assume psi is 0 here
  12453. data[i++] *= sx;
  12454. data[i++] *= sy;
  12455. // Start angle
  12456. data[i++] += angle;
  12457. // end angle
  12458. data[i++] += angle;
  12459. // FIXME psi
  12460. i += 2;
  12461. j = i;
  12462. break;
  12463. case R:
  12464. // x0, y0
  12465. p[0] = data[i++];
  12466. p[1] = data[i++];
  12467. applyTransform(p, p, m);
  12468. data[j++] = p[0];
  12469. data[j++] = p[1];
  12470. // x1, y1
  12471. p[0] += data[i++];
  12472. p[1] += data[i++];
  12473. applyTransform(p, p, m);
  12474. data[j++] = p[0];
  12475. data[j++] = p[1];
  12476. }
  12477. for (k = 0; k < nPoint; k++) {
  12478. var p = points[k];
  12479. p[0] = data[i++];
  12480. p[1] = data[i++];
  12481. applyTransform(p, p, m);
  12482. // Write back
  12483. data[j++] = p[0];
  12484. data[j++] = p[1];
  12485. }
  12486. }
  12487. };
  12488. // command chars
  12489. var cc = [
  12490. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12491. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12492. ];
  12493. var mathSqrt = Math.sqrt;
  12494. var mathSin = Math.sin;
  12495. var mathCos = Math.cos;
  12496. var PI = Math.PI;
  12497. var vMag = function(v) {
  12498. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12499. };
  12500. var vRatio = function(u, v) {
  12501. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12502. };
  12503. var vAngle = function(u, v) {
  12504. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12505. * Math.acos(vRatio(u, v));
  12506. };
  12507. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12508. var psi = psiDeg * (PI / 180.0);
  12509. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12510. + mathSin(psi) * (y1 - y2) / 2.0;
  12511. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12512. + mathCos(psi) * (y1 - y2) / 2.0;
  12513. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12514. if (lambda > 1) {
  12515. rx *= mathSqrt(lambda);
  12516. ry *= mathSqrt(lambda);
  12517. }
  12518. var f = (fa === fs ? -1 : 1)
  12519. * mathSqrt((((rx * rx) * (ry * ry))
  12520. - ((rx * rx) * (yp * yp))
  12521. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12522. + (ry * ry) * (xp * xp))
  12523. ) || 0;
  12524. var cxp = f * rx * yp / ry;
  12525. var cyp = f * -ry * xp / rx;
  12526. var cx = (x1 + x2) / 2.0
  12527. + mathCos(psi) * cxp
  12528. - mathSin(psi) * cyp;
  12529. var cy = (y1 + y2) / 2.0
  12530. + mathSin(psi) * cxp
  12531. + mathCos(psi) * cyp;
  12532. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12533. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12534. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12535. var dTheta = vAngle(u, v);
  12536. if (vRatio(u, v) <= -1) {
  12537. dTheta = PI;
  12538. }
  12539. if (vRatio(u, v) >= 1) {
  12540. dTheta = 0;
  12541. }
  12542. if (fs === 0 && dTheta > 0) {
  12543. dTheta = dTheta - 2 * PI;
  12544. }
  12545. if (fs === 1 && dTheta < 0) {
  12546. dTheta = dTheta + 2 * PI;
  12547. }
  12548. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12549. }
  12550. function createPathProxyFromString(data) {
  12551. if (!data) {
  12552. return [];
  12553. }
  12554. // command string
  12555. var cs = data.replace(/-/g, ' -')
  12556. .replace(/ /g, ' ')
  12557. .replace(/ /g, ',')
  12558. .replace(/,,/g, ',');
  12559. var n;
  12560. // create pipes so that we can split the data
  12561. for (n = 0; n < cc.length; n++) {
  12562. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12563. }
  12564. // create array
  12565. var arr = cs.split('|');
  12566. // init context point
  12567. var cpx = 0;
  12568. var cpy = 0;
  12569. var path = new PathProxy();
  12570. var CMD = PathProxy.CMD;
  12571. var prevCmd;
  12572. for (n = 1; n < arr.length; n++) {
  12573. var str = arr[n];
  12574. var c = str.charAt(0);
  12575. var off = 0;
  12576. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12577. var cmd;
  12578. if (p.length > 0 && p[0] === '') {
  12579. p.shift();
  12580. }
  12581. for (var i = 0; i < p.length; i++) {
  12582. p[i] = parseFloat(p[i]);
  12583. }
  12584. while (off < p.length && !isNaN(p[off])) {
  12585. if (isNaN(p[0])) {
  12586. break;
  12587. }
  12588. var ctlPtx;
  12589. var ctlPty;
  12590. var rx;
  12591. var ry;
  12592. var psi;
  12593. var fa;
  12594. var fs;
  12595. var x1 = cpx;
  12596. var y1 = cpy;
  12597. // convert l, H, h, V, and v to L
  12598. switch (c) {
  12599. case 'l':
  12600. cpx += p[off++];
  12601. cpy += p[off++];
  12602. cmd = CMD.L;
  12603. path.addData(cmd, cpx, cpy);
  12604. break;
  12605. case 'L':
  12606. cpx = p[off++];
  12607. cpy = p[off++];
  12608. cmd = CMD.L;
  12609. path.addData(cmd, cpx, cpy);
  12610. break;
  12611. case 'm':
  12612. cpx += p[off++];
  12613. cpy += p[off++];
  12614. cmd = CMD.M;
  12615. path.addData(cmd, cpx, cpy);
  12616. c = 'l';
  12617. break;
  12618. case 'M':
  12619. cpx = p[off++];
  12620. cpy = p[off++];
  12621. cmd = CMD.M;
  12622. path.addData(cmd, cpx, cpy);
  12623. c = 'L';
  12624. break;
  12625. case 'h':
  12626. cpx += p[off++];
  12627. cmd = CMD.L;
  12628. path.addData(cmd, cpx, cpy);
  12629. break;
  12630. case 'H':
  12631. cpx = p[off++];
  12632. cmd = CMD.L;
  12633. path.addData(cmd, cpx, cpy);
  12634. break;
  12635. case 'v':
  12636. cpy += p[off++];
  12637. cmd = CMD.L;
  12638. path.addData(cmd, cpx, cpy);
  12639. break;
  12640. case 'V':
  12641. cpy = p[off++];
  12642. cmd = CMD.L;
  12643. path.addData(cmd, cpx, cpy);
  12644. break;
  12645. case 'C':
  12646. cmd = CMD.C;
  12647. path.addData(
  12648. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12649. );
  12650. cpx = p[off - 2];
  12651. cpy = p[off - 1];
  12652. break;
  12653. case 'c':
  12654. cmd = CMD.C;
  12655. path.addData(
  12656. cmd,
  12657. p[off++] + cpx, p[off++] + cpy,
  12658. p[off++] + cpx, p[off++] + cpy,
  12659. p[off++] + cpx, p[off++] + cpy
  12660. );
  12661. cpx += p[off - 2];
  12662. cpy += p[off - 1];
  12663. break;
  12664. case 'S':
  12665. ctlPtx = cpx;
  12666. ctlPty = cpy;
  12667. var len = path.len();
  12668. var pathData = path.data;
  12669. if (prevCmd === CMD.C) {
  12670. ctlPtx += cpx - pathData[len - 4];
  12671. ctlPty += cpy - pathData[len - 3];
  12672. }
  12673. cmd = CMD.C;
  12674. x1 = p[off++];
  12675. y1 = p[off++];
  12676. cpx = p[off++];
  12677. cpy = p[off++];
  12678. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12679. break;
  12680. case 's':
  12681. ctlPtx = cpx;
  12682. ctlPty = cpy;
  12683. var len = path.len();
  12684. var pathData = path.data;
  12685. if (prevCmd === CMD.C) {
  12686. ctlPtx += cpx - pathData[len - 4];
  12687. ctlPty += cpy - pathData[len - 3];
  12688. }
  12689. cmd = CMD.C;
  12690. x1 = cpx + p[off++];
  12691. y1 = cpy + p[off++];
  12692. cpx += p[off++];
  12693. cpy += p[off++];
  12694. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12695. break;
  12696. case 'Q':
  12697. x1 = p[off++];
  12698. y1 = p[off++];
  12699. cpx = p[off++];
  12700. cpy = p[off++];
  12701. cmd = CMD.Q;
  12702. path.addData(cmd, x1, y1, cpx, cpy);
  12703. break;
  12704. case 'q':
  12705. x1 = p[off++] + cpx;
  12706. y1 = p[off++] + cpy;
  12707. cpx += p[off++];
  12708. cpy += p[off++];
  12709. cmd = CMD.Q;
  12710. path.addData(cmd, x1, y1, cpx, cpy);
  12711. break;
  12712. case 'T':
  12713. ctlPtx = cpx;
  12714. ctlPty = cpy;
  12715. var len = path.len();
  12716. var pathData = path.data;
  12717. if (prevCmd === CMD.Q) {
  12718. ctlPtx += cpx - pathData[len - 4];
  12719. ctlPty += cpy - pathData[len - 3];
  12720. }
  12721. cpx = p[off++];
  12722. cpy = p[off++];
  12723. cmd = CMD.Q;
  12724. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12725. break;
  12726. case 't':
  12727. ctlPtx = cpx;
  12728. ctlPty = cpy;
  12729. var len = path.len();
  12730. var pathData = path.data;
  12731. if (prevCmd === CMD.Q) {
  12732. ctlPtx += cpx - pathData[len - 4];
  12733. ctlPty += cpy - pathData[len - 3];
  12734. }
  12735. cpx += p[off++];
  12736. cpy += p[off++];
  12737. cmd = CMD.Q;
  12738. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12739. break;
  12740. case 'A':
  12741. rx = p[off++];
  12742. ry = p[off++];
  12743. psi = p[off++];
  12744. fa = p[off++];
  12745. fs = p[off++];
  12746. x1 = cpx, y1 = cpy;
  12747. cpx = p[off++];
  12748. cpy = p[off++];
  12749. cmd = CMD.A;
  12750. processArc(
  12751. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12752. );
  12753. break;
  12754. case 'a':
  12755. rx = p[off++];
  12756. ry = p[off++];
  12757. psi = p[off++];
  12758. fa = p[off++];
  12759. fs = p[off++];
  12760. x1 = cpx, y1 = cpy;
  12761. cpx += p[off++];
  12762. cpy += p[off++];
  12763. cmd = CMD.A;
  12764. processArc(
  12765. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12766. );
  12767. break;
  12768. }
  12769. }
  12770. if (c === 'z' || c === 'Z') {
  12771. cmd = CMD.Z;
  12772. path.addData(cmd);
  12773. }
  12774. prevCmd = cmd;
  12775. }
  12776. path.toStatic();
  12777. return path;
  12778. }
  12779. // TODO Optimize double memory cost problem
  12780. function createPathOptions(str, opts) {
  12781. var pathProxy = createPathProxyFromString(str);
  12782. opts = opts || {};
  12783. opts.buildPath = function (path) {
  12784. if (path.setData) {
  12785. path.setData(pathProxy.data);
  12786. // Svg and vml renderer don't have context
  12787. var ctx = path.getContext();
  12788. if (ctx) {
  12789. path.rebuildPath(ctx);
  12790. }
  12791. }
  12792. else {
  12793. var ctx = path;
  12794. pathProxy.rebuildPath(ctx);
  12795. }
  12796. };
  12797. opts.applyTransform = function (m) {
  12798. transformPath(pathProxy, m);
  12799. this.dirty(true);
  12800. };
  12801. return opts;
  12802. }
  12803. /**
  12804. * Create a Path object from path string data
  12805. * http://www.w3.org/TR/SVG/paths.html#PathData
  12806. * @param {Object} opts Other options
  12807. */
  12808. function createFromString(str, opts) {
  12809. return new Path(createPathOptions(str, opts));
  12810. }
  12811. /**
  12812. * Create a Path class from path string data
  12813. * @param {string} str
  12814. * @param {Object} opts Other options
  12815. */
  12816. function extendFromString(str, opts) {
  12817. return Path.extend(createPathOptions(str, opts));
  12818. }
  12819. /**
  12820. * Merge multiple paths
  12821. */
  12822. // TODO Apply transform
  12823. // TODO stroke dash
  12824. // TODO Optimize double memory cost problem
  12825. function mergePath$1(pathEls, opts) {
  12826. var pathList = [];
  12827. var len = pathEls.length;
  12828. for (var i = 0; i < len; i++) {
  12829. var pathEl = pathEls[i];
  12830. if (!pathEl.path) {
  12831. pathEl.createPathProxy();
  12832. }
  12833. if (pathEl.__dirtyPath) {
  12834. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12835. }
  12836. pathList.push(pathEl.path);
  12837. }
  12838. var pathBundle = new Path(opts);
  12839. // Need path proxy.
  12840. pathBundle.createPathProxy();
  12841. pathBundle.buildPath = function (path) {
  12842. path.appendPath(pathList);
  12843. // Svg and vml renderer don't have context
  12844. var ctx = path.getContext();
  12845. if (ctx) {
  12846. path.rebuildPath(ctx);
  12847. }
  12848. };
  12849. return pathBundle;
  12850. }
  12851. /**
  12852. * @alias zrender/graphic/Text
  12853. * @extends module:zrender/graphic/Displayable
  12854. * @constructor
  12855. * @param {Object} opts
  12856. */
  12857. var Text = function (opts) { // jshint ignore:line
  12858. Displayable.call(this, opts);
  12859. };
  12860. Text.prototype = {
  12861. constructor: Text,
  12862. type: 'text',
  12863. brush: function (ctx, prevEl) {
  12864. var style = this.style;
  12865. // Optimize, avoid normalize every time.
  12866. this.__dirty && normalizeTextStyle(style, true);
  12867. // Use props with prefix 'text'.
  12868. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12869. style.shadowOffsetX = style.shadowOffsetY = null;
  12870. var text = style.text;
  12871. // Convert to string
  12872. text != null && (text += '');
  12873. // Always bind style
  12874. style.bind(ctx, this, prevEl);
  12875. if (!needDrawText(text, style)) {
  12876. return;
  12877. }
  12878. this.setTransform(ctx);
  12879. renderText(this, ctx, text, style);
  12880. this.restoreTransform(ctx);
  12881. },
  12882. getBoundingRect: function () {
  12883. var style = this.style;
  12884. // Optimize, avoid normalize every time.
  12885. this.__dirty && normalizeTextStyle(style, true);
  12886. if (!this._rect) {
  12887. var text = style.text;
  12888. text != null ? (text += '') : (text = '');
  12889. var rect = getBoundingRect(
  12890. style.text + '',
  12891. style.font,
  12892. style.textAlign,
  12893. style.textVerticalAlign,
  12894. style.textPadding,
  12895. style.rich
  12896. );
  12897. rect.x += style.x || 0;
  12898. rect.y += style.y || 0;
  12899. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12900. var w = style.textStrokeWidth;
  12901. rect.x -= w / 2;
  12902. rect.y -= w / 2;
  12903. rect.width += w;
  12904. rect.height += w;
  12905. }
  12906. this._rect = rect;
  12907. }
  12908. return this._rect;
  12909. }
  12910. };
  12911. inherits(Text, Displayable);
  12912. /**
  12913. * 圆形
  12914. * @module zrender/shape/Circle
  12915. */
  12916. var Circle = Path.extend({
  12917. type: 'circle',
  12918. shape: {
  12919. cx: 0,
  12920. cy: 0,
  12921. r: 0
  12922. },
  12923. buildPath : function (ctx, shape, inBundle) {
  12924. // Better stroking in ShapeBundle
  12925. // Always do it may have performence issue ( fill may be 2x more cost)
  12926. if (inBundle) {
  12927. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12928. }
  12929. // else {
  12930. // if (ctx.allocate && !ctx.data.length) {
  12931. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  12932. // }
  12933. // }
  12934. // Better stroking in ShapeBundle
  12935. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  12936. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  12937. }
  12938. });
  12939. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  12940. // where exception "unexpected call to method or property access"
  12941. // might be thrown when calling ctx.fill or ctx.stroke after a path
  12942. // whose area size is zero is drawn and ctx.clip() is called and
  12943. // shadowBlur is set. See #4572, #3112, #5777.
  12944. // (e.g.,
  12945. // ctx.moveTo(10, 10);
  12946. // ctx.lineTo(20, 10);
  12947. // ctx.closePath();
  12948. // ctx.clip();
  12949. // ctx.shadowBlur = 10;
  12950. // ...
  12951. // ctx.fill();
  12952. // )
  12953. var shadowTemp = [
  12954. ['shadowBlur', 0],
  12955. ['shadowColor', '#000'],
  12956. ['shadowOffsetX', 0],
  12957. ['shadowOffsetY', 0]
  12958. ];
  12959. var fixClipWithShadow = function (orignalBrush) {
  12960. // version string can be: '11.0'
  12961. return (env$1.browser.ie && env$1.browser.version >= 11)
  12962. ? function () {
  12963. var clipPaths = this.__clipPaths;
  12964. var style = this.style;
  12965. var modified;
  12966. if (clipPaths) {
  12967. for (var i = 0; i < clipPaths.length; i++) {
  12968. var clipPath = clipPaths[i];
  12969. var shape = clipPath && clipPath.shape;
  12970. var type = clipPath && clipPath.type;
  12971. if (shape && (
  12972. (type === 'sector' && shape.startAngle === shape.endAngle)
  12973. || (type === 'rect' && (!shape.width || !shape.height))
  12974. )) {
  12975. for (var j = 0; j < shadowTemp.length; j++) {
  12976. // It is save to put shadowTemp static, because shadowTemp
  12977. // will be all modified each item brush called.
  12978. shadowTemp[j][2] = style[shadowTemp[j][0]];
  12979. style[shadowTemp[j][0]] = shadowTemp[j][1];
  12980. }
  12981. modified = true;
  12982. break;
  12983. }
  12984. }
  12985. }
  12986. orignalBrush.apply(this, arguments);
  12987. if (modified) {
  12988. for (var j = 0; j < shadowTemp.length; j++) {
  12989. style[shadowTemp[j][0]] = shadowTemp[j][2];
  12990. }
  12991. }
  12992. }
  12993. : orignalBrush;
  12994. };
  12995. /**
  12996. * 扇形
  12997. * @module zrender/graphic/shape/Sector
  12998. */
  12999. var Sector = Path.extend({
  13000. type: 'sector',
  13001. shape: {
  13002. cx: 0,
  13003. cy: 0,
  13004. r0: 0,
  13005. r: 0,
  13006. startAngle: 0,
  13007. endAngle: Math.PI * 2,
  13008. clockwise: true
  13009. },
  13010. brush: fixClipWithShadow(Path.prototype.brush),
  13011. buildPath: function (ctx, shape) {
  13012. var x = shape.cx;
  13013. var y = shape.cy;
  13014. var r0 = Math.max(shape.r0 || 0, 0);
  13015. var r = Math.max(shape.r, 0);
  13016. var startAngle = shape.startAngle;
  13017. var endAngle = shape.endAngle;
  13018. var clockwise = shape.clockwise;
  13019. var unitX = Math.cos(startAngle);
  13020. var unitY = Math.sin(startAngle);
  13021. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13022. ctx.lineTo(unitX * r + x, unitY * r + y);
  13023. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13024. ctx.lineTo(
  13025. Math.cos(endAngle) * r0 + x,
  13026. Math.sin(endAngle) * r0 + y
  13027. );
  13028. if (r0 !== 0) {
  13029. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13030. }
  13031. ctx.closePath();
  13032. }
  13033. });
  13034. /**
  13035. * 圆环
  13036. * @module zrender/graphic/shape/Ring
  13037. */
  13038. var Ring = Path.extend({
  13039. type: 'ring',
  13040. shape: {
  13041. cx: 0,
  13042. cy: 0,
  13043. r: 0,
  13044. r0: 0
  13045. },
  13046. buildPath: function (ctx, shape) {
  13047. var x = shape.cx;
  13048. var y = shape.cy;
  13049. var PI2 = Math.PI * 2;
  13050. ctx.moveTo(x + shape.r, y);
  13051. ctx.arc(x, y, shape.r, 0, PI2, false);
  13052. ctx.moveTo(x + shape.r0, y);
  13053. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13054. }
  13055. });
  13056. /**
  13057. * Catmull-Rom spline 插值折线
  13058. * @module zrender/shape/util/smoothSpline
  13059. * @author pissang (https://www.github.com/pissang)
  13060. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13061. * errorrik (errorrik@gmail.com)
  13062. */
  13063. /**
  13064. * @inner
  13065. */
  13066. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13067. var v0 = (p2 - p0) * 0.5;
  13068. var v1 = (p3 - p1) * 0.5;
  13069. return (2 * (p1 - p2) + v0 + v1) * t3
  13070. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13071. + v0 * t + p1;
  13072. }
  13073. /**
  13074. * @alias module:zrender/shape/util/smoothSpline
  13075. * @param {Array} points 线段顶点数组
  13076. * @param {boolean} isLoop
  13077. * @return {Array}
  13078. */
  13079. var smoothSpline = function (points, isLoop) {
  13080. var len$$1 = points.length;
  13081. var ret = [];
  13082. var distance$$1 = 0;
  13083. for (var i = 1; i < len$$1; i++) {
  13084. distance$$1 += distance(points[i - 1], points[i]);
  13085. }
  13086. var segs = distance$$1 / 2;
  13087. segs = segs < len$$1 ? len$$1 : segs;
  13088. for (var i = 0; i < segs; i++) {
  13089. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13090. var idx = Math.floor(pos);
  13091. var w = pos - idx;
  13092. var p0;
  13093. var p1 = points[idx % len$$1];
  13094. var p2;
  13095. var p3;
  13096. if (!isLoop) {
  13097. p0 = points[idx === 0 ? idx : idx - 1];
  13098. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13099. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13100. }
  13101. else {
  13102. p0 = points[(idx - 1 + len$$1) % len$$1];
  13103. p2 = points[(idx + 1) % len$$1];
  13104. p3 = points[(idx + 2) % len$$1];
  13105. }
  13106. var w2 = w * w;
  13107. var w3 = w * w2;
  13108. ret.push([
  13109. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13110. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13111. ]);
  13112. }
  13113. return ret;
  13114. };
  13115. /**
  13116. * 贝塞尔平滑曲线
  13117. * @module zrender/shape/util/smoothBezier
  13118. * @author pissang (https://www.github.com/pissang)
  13119. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13120. * errorrik (errorrik@gmail.com)
  13121. */
  13122. /**
  13123. * 贝塞尔平滑曲线
  13124. * @alias module:zrender/shape/util/smoothBezier
  13125. * @param {Array} points 线段顶点数组
  13126. * @param {number} smooth 平滑等级, 0-1
  13127. * @param {boolean} isLoop
  13128. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13129. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13130. * 整个折线的包围盒做一个并集用来约束控制点。
  13131. * @param {Array} 计算出来的控制点数组
  13132. */
  13133. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13134. var cps = [];
  13135. var v = [];
  13136. var v1 = [];
  13137. var v2 = [];
  13138. var prevPoint;
  13139. var nextPoint;
  13140. var min$$1, max$$1;
  13141. if (constraint) {
  13142. min$$1 = [Infinity, Infinity];
  13143. max$$1 = [-Infinity, -Infinity];
  13144. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13145. min(min$$1, min$$1, points[i]);
  13146. max(max$$1, max$$1, points[i]);
  13147. }
  13148. // 与指定的包围盒做并集
  13149. min(min$$1, min$$1, constraint[0]);
  13150. max(max$$1, max$$1, constraint[1]);
  13151. }
  13152. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13153. var point = points[i];
  13154. if (isLoop) {
  13155. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13156. nextPoint = points[(i + 1) % len$$1];
  13157. }
  13158. else {
  13159. if (i === 0 || i === len$$1 - 1) {
  13160. cps.push(clone$1(points[i]));
  13161. continue;
  13162. }
  13163. else {
  13164. prevPoint = points[i - 1];
  13165. nextPoint = points[i + 1];
  13166. }
  13167. }
  13168. sub(v, nextPoint, prevPoint);
  13169. // use degree to scale the handle length
  13170. scale(v, v, smooth);
  13171. var d0 = distance(point, prevPoint);
  13172. var d1 = distance(point, nextPoint);
  13173. var sum = d0 + d1;
  13174. if (sum !== 0) {
  13175. d0 /= sum;
  13176. d1 /= sum;
  13177. }
  13178. scale(v1, v, -d0);
  13179. scale(v2, v, d1);
  13180. var cp0 = add([], point, v1);
  13181. var cp1 = add([], point, v2);
  13182. if (constraint) {
  13183. max(cp0, cp0, min$$1);
  13184. min(cp0, cp0, max$$1);
  13185. max(cp1, cp1, min$$1);
  13186. min(cp1, cp1, max$$1);
  13187. }
  13188. cps.push(cp0);
  13189. cps.push(cp1);
  13190. }
  13191. if (isLoop) {
  13192. cps.push(cps.shift());
  13193. }
  13194. return cps;
  13195. };
  13196. function buildPath$1(ctx, shape, closePath) {
  13197. var points = shape.points;
  13198. var smooth = shape.smooth;
  13199. if (points && points.length >= 2) {
  13200. if (smooth && smooth !== 'spline') {
  13201. var controlPoints = smoothBezier(
  13202. points, smooth, closePath, shape.smoothConstraint
  13203. );
  13204. ctx.moveTo(points[0][0], points[0][1]);
  13205. var len = points.length;
  13206. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13207. var cp1 = controlPoints[i * 2];
  13208. var cp2 = controlPoints[i * 2 + 1];
  13209. var p = points[(i + 1) % len];
  13210. ctx.bezierCurveTo(
  13211. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13212. );
  13213. }
  13214. }
  13215. else {
  13216. if (smooth === 'spline') {
  13217. points = smoothSpline(points, closePath);
  13218. }
  13219. ctx.moveTo(points[0][0], points[0][1]);
  13220. for (var i = 1, l = points.length; i < l; i++) {
  13221. ctx.lineTo(points[i][0], points[i][1]);
  13222. }
  13223. }
  13224. closePath && ctx.closePath();
  13225. }
  13226. }
  13227. /**
  13228. * 多边形
  13229. * @module zrender/shape/Polygon
  13230. */
  13231. var Polygon = Path.extend({
  13232. type: 'polygon',
  13233. shape: {
  13234. points: null,
  13235. smooth: false,
  13236. smoothConstraint: null
  13237. },
  13238. buildPath: function (ctx, shape) {
  13239. buildPath$1(ctx, shape, true);
  13240. }
  13241. });
  13242. /**
  13243. * @module zrender/graphic/shape/Polyline
  13244. */
  13245. var Polyline = Path.extend({
  13246. type: 'polyline',
  13247. shape: {
  13248. points: null,
  13249. smooth: false,
  13250. smoothConstraint: null
  13251. },
  13252. style: {
  13253. stroke: '#000',
  13254. fill: null
  13255. },
  13256. buildPath: function (ctx, shape) {
  13257. buildPath$1(ctx, shape, false);
  13258. }
  13259. });
  13260. /**
  13261. * 矩形
  13262. * @module zrender/graphic/shape/Rect
  13263. */
  13264. var Rect = Path.extend({
  13265. type: 'rect',
  13266. shape: {
  13267. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13268. // r缩写为1 相当于 [1, 1, 1, 1]
  13269. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13270. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13271. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13272. r: 0,
  13273. x: 0,
  13274. y: 0,
  13275. width: 0,
  13276. height: 0
  13277. },
  13278. buildPath: function (ctx, shape) {
  13279. var x = shape.x;
  13280. var y = shape.y;
  13281. var width = shape.width;
  13282. var height = shape.height;
  13283. if (!shape.r) {
  13284. ctx.rect(x, y, width, height);
  13285. }
  13286. else {
  13287. buildPath(ctx, shape);
  13288. }
  13289. ctx.closePath();
  13290. return;
  13291. }
  13292. });
  13293. /**
  13294. * 直线
  13295. * @module zrender/graphic/shape/Line
  13296. */
  13297. var Line = Path.extend({
  13298. type: 'line',
  13299. shape: {
  13300. // Start point
  13301. x1: 0,
  13302. y1: 0,
  13303. // End point
  13304. x2: 0,
  13305. y2: 0,
  13306. percent: 1
  13307. },
  13308. style: {
  13309. stroke: '#000',
  13310. fill: null
  13311. },
  13312. buildPath: function (ctx, shape) {
  13313. var x1 = shape.x1;
  13314. var y1 = shape.y1;
  13315. var x2 = shape.x2;
  13316. var y2 = shape.y2;
  13317. var percent = shape.percent;
  13318. if (percent === 0) {
  13319. return;
  13320. }
  13321. ctx.moveTo(x1, y1);
  13322. if (percent < 1) {
  13323. x2 = x1 * (1 - percent) + x2 * percent;
  13324. y2 = y1 * (1 - percent) + y2 * percent;
  13325. }
  13326. ctx.lineTo(x2, y2);
  13327. },
  13328. /**
  13329. * Get point at percent
  13330. * @param {number} percent
  13331. * @return {Array.<number>}
  13332. */
  13333. pointAt: function (p) {
  13334. var shape = this.shape;
  13335. return [
  13336. shape.x1 * (1 - p) + shape.x2 * p,
  13337. shape.y1 * (1 - p) + shape.y2 * p
  13338. ];
  13339. }
  13340. });
  13341. /**
  13342. * 贝塞尔曲线
  13343. * @module zrender/shape/BezierCurve
  13344. */
  13345. var out = [];
  13346. function someVectorAt(shape, t, isTangent) {
  13347. var cpx2 = shape.cpx2;
  13348. var cpy2 = shape.cpy2;
  13349. if (cpx2 === null || cpy2 === null) {
  13350. return [
  13351. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13352. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13353. ];
  13354. }
  13355. else {
  13356. return [
  13357. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13358. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13359. ];
  13360. }
  13361. }
  13362. var BezierCurve = Path.extend({
  13363. type: 'bezier-curve',
  13364. shape: {
  13365. x1: 0,
  13366. y1: 0,
  13367. x2: 0,
  13368. y2: 0,
  13369. cpx1: 0,
  13370. cpy1: 0,
  13371. // cpx2: 0,
  13372. // cpy2: 0
  13373. // Curve show percent, for animating
  13374. percent: 1
  13375. },
  13376. style: {
  13377. stroke: '#000',
  13378. fill: null
  13379. },
  13380. buildPath: function (ctx, shape) {
  13381. var x1 = shape.x1;
  13382. var y1 = shape.y1;
  13383. var x2 = shape.x2;
  13384. var y2 = shape.y2;
  13385. var cpx1 = shape.cpx1;
  13386. var cpy1 = shape.cpy1;
  13387. var cpx2 = shape.cpx2;
  13388. var cpy2 = shape.cpy2;
  13389. var percent = shape.percent;
  13390. if (percent === 0) {
  13391. return;
  13392. }
  13393. ctx.moveTo(x1, y1);
  13394. if (cpx2 == null || cpy2 == null) {
  13395. if (percent < 1) {
  13396. quadraticSubdivide(
  13397. x1, cpx1, x2, percent, out
  13398. );
  13399. cpx1 = out[1];
  13400. x2 = out[2];
  13401. quadraticSubdivide(
  13402. y1, cpy1, y2, percent, out
  13403. );
  13404. cpy1 = out[1];
  13405. y2 = out[2];
  13406. }
  13407. ctx.quadraticCurveTo(
  13408. cpx1, cpy1,
  13409. x2, y2
  13410. );
  13411. }
  13412. else {
  13413. if (percent < 1) {
  13414. cubicSubdivide(
  13415. x1, cpx1, cpx2, x2, percent, out
  13416. );
  13417. cpx1 = out[1];
  13418. cpx2 = out[2];
  13419. x2 = out[3];
  13420. cubicSubdivide(
  13421. y1, cpy1, cpy2, y2, percent, out
  13422. );
  13423. cpy1 = out[1];
  13424. cpy2 = out[2];
  13425. y2 = out[3];
  13426. }
  13427. ctx.bezierCurveTo(
  13428. cpx1, cpy1,
  13429. cpx2, cpy2,
  13430. x2, y2
  13431. );
  13432. }
  13433. },
  13434. /**
  13435. * Get point at percent
  13436. * @param {number} t
  13437. * @return {Array.<number>}
  13438. */
  13439. pointAt: function (t) {
  13440. return someVectorAt(this.shape, t, false);
  13441. },
  13442. /**
  13443. * Get tangent at percent
  13444. * @param {number} t
  13445. * @return {Array.<number>}
  13446. */
  13447. tangentAt: function (t) {
  13448. var p = someVectorAt(this.shape, t, true);
  13449. return normalize(p, p);
  13450. }
  13451. });
  13452. /**
  13453. * 圆弧
  13454. * @module zrender/graphic/shape/Arc
  13455. */
  13456. var Arc = Path.extend({
  13457. type: 'arc',
  13458. shape: {
  13459. cx: 0,
  13460. cy: 0,
  13461. r: 0,
  13462. startAngle: 0,
  13463. endAngle: Math.PI * 2,
  13464. clockwise: true
  13465. },
  13466. style: {
  13467. stroke: '#000',
  13468. fill: null
  13469. },
  13470. buildPath: function (ctx, shape) {
  13471. var x = shape.cx;
  13472. var y = shape.cy;
  13473. var r = Math.max(shape.r, 0);
  13474. var startAngle = shape.startAngle;
  13475. var endAngle = shape.endAngle;
  13476. var clockwise = shape.clockwise;
  13477. var unitX = Math.cos(startAngle);
  13478. var unitY = Math.sin(startAngle);
  13479. ctx.moveTo(unitX * r + x, unitY * r + y);
  13480. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13481. }
  13482. });
  13483. // CompoundPath to improve performance
  13484. var CompoundPath = Path.extend({
  13485. type: 'compound',
  13486. shape: {
  13487. paths: null
  13488. },
  13489. _updatePathDirty: function () {
  13490. var dirtyPath = this.__dirtyPath;
  13491. var paths = this.shape.paths;
  13492. for (var i = 0; i < paths.length; i++) {
  13493. // Mark as dirty if any subpath is dirty
  13494. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13495. }
  13496. this.__dirtyPath = dirtyPath;
  13497. this.__dirty = this.__dirty || dirtyPath;
  13498. },
  13499. beforeBrush: function () {
  13500. this._updatePathDirty();
  13501. var paths = this.shape.paths || [];
  13502. var scale = this.getGlobalScale();
  13503. // Update path scale
  13504. for (var i = 0; i < paths.length; i++) {
  13505. if (!paths[i].path) {
  13506. paths[i].createPathProxy();
  13507. }
  13508. paths[i].path.setScale(scale[0], scale[1]);
  13509. }
  13510. },
  13511. buildPath: function (ctx, shape) {
  13512. var paths = shape.paths || [];
  13513. for (var i = 0; i < paths.length; i++) {
  13514. paths[i].buildPath(ctx, paths[i].shape, true);
  13515. }
  13516. },
  13517. afterBrush: function () {
  13518. var paths = this.shape.paths || [];
  13519. for (var i = 0; i < paths.length; i++) {
  13520. paths[i].__dirtyPath = false;
  13521. }
  13522. },
  13523. getBoundingRect: function () {
  13524. this._updatePathDirty();
  13525. return Path.prototype.getBoundingRect.call(this);
  13526. }
  13527. });
  13528. /**
  13529. * @param {Array.<Object>} colorStops
  13530. */
  13531. var Gradient = function (colorStops) {
  13532. this.colorStops = colorStops || [];
  13533. };
  13534. Gradient.prototype = {
  13535. constructor: Gradient,
  13536. addColorStop: function (offset, color) {
  13537. this.colorStops.push({
  13538. offset: offset,
  13539. color: color
  13540. });
  13541. }
  13542. };
  13543. /**
  13544. * x, y, x2, y2 are all percent from 0 to 1
  13545. * @param {number} [x=0]
  13546. * @param {number} [y=0]
  13547. * @param {number} [x2=1]
  13548. * @param {number} [y2=0]
  13549. * @param {Array.<Object>} colorStops
  13550. * @param {boolean} [globalCoord=false]
  13551. */
  13552. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13553. // Should do nothing more in this constructor. Because gradient can be
  13554. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13555. // this constructor will not be called.
  13556. this.x = x == null ? 0 : x;
  13557. this.y = y == null ? 0 : y;
  13558. this.x2 = x2 == null ? 1 : x2;
  13559. this.y2 = y2 == null ? 0 : y2;
  13560. // Can be cloned
  13561. this.type = 'linear';
  13562. // If use global coord
  13563. this.global = globalCoord || false;
  13564. Gradient.call(this, colorStops);
  13565. };
  13566. LinearGradient.prototype = {
  13567. constructor: LinearGradient
  13568. };
  13569. inherits(LinearGradient, Gradient);
  13570. /**
  13571. * x, y, r are all percent from 0 to 1
  13572. * @param {number} [x=0.5]
  13573. * @param {number} [y=0.5]
  13574. * @param {number} [r=0.5]
  13575. * @param {Array.<Object>} [colorStops]
  13576. * @param {boolean} [globalCoord=false]
  13577. */
  13578. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13579. // Should do nothing more in this constructor. Because gradient can be
  13580. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13581. // this constructor will not be called.
  13582. this.x = x == null ? 0.5 : x;
  13583. this.y = y == null ? 0.5 : y;
  13584. this.r = r == null ? 0.5 : r;
  13585. // Can be cloned
  13586. this.type = 'radial';
  13587. // If use global coord
  13588. this.global = globalCoord || false;
  13589. Gradient.call(this, colorStops);
  13590. };
  13591. RadialGradient.prototype = {
  13592. constructor: RadialGradient
  13593. };
  13594. inherits(RadialGradient, Gradient);
  13595. /**
  13596. * Displayable for incremental rendering. It will be rendered in a separate layer
  13597. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13598. * addDisplayables will render the added displayables incremetally.
  13599. *
  13600. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13601. */
  13602. // TODO Style override ?
  13603. function IncrementalDisplayble(opts) {
  13604. Displayable.call(this, opts);
  13605. this._displayables = [];
  13606. this._temporaryDisplayables = [];
  13607. this._cursor = 0;
  13608. this.notClear = true;
  13609. }
  13610. IncrementalDisplayble.prototype.incremental = true;
  13611. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13612. this._displayables = [];
  13613. this._temporaryDisplayables = [];
  13614. this._cursor = 0;
  13615. this.dirty();
  13616. this.notClear = false;
  13617. };
  13618. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13619. if (notPersistent) {
  13620. this._temporaryDisplayables.push(displayable);
  13621. }
  13622. else {
  13623. this._displayables.push(displayable);
  13624. }
  13625. this.dirty();
  13626. };
  13627. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13628. notPersistent = notPersistent || false;
  13629. for (var i = 0; i < displayables.length; i++) {
  13630. this.addDisplayable(displayables[i], notPersistent);
  13631. }
  13632. };
  13633. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13634. for (var i = this._cursor; i < this._displayables.length; i++) {
  13635. cb && cb(this._displayables[i]);
  13636. }
  13637. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13638. cb && cb(this._temporaryDisplayables[i]);
  13639. }
  13640. };
  13641. IncrementalDisplayble.prototype.update = function () {
  13642. this.updateTransform();
  13643. for (var i = this._cursor; i < this._displayables.length; i++) {
  13644. var displayable = this._displayables[i];
  13645. // PENDING
  13646. displayable.parent = this;
  13647. displayable.update();
  13648. displayable.parent = null;
  13649. }
  13650. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13651. var displayable = this._temporaryDisplayables[i];
  13652. // PENDING
  13653. displayable.parent = this;
  13654. displayable.update();
  13655. displayable.parent = null;
  13656. }
  13657. };
  13658. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13659. // Render persistant displayables.
  13660. for (var i = this._cursor; i < this._displayables.length; i++) {
  13661. var displayable = this._temporaryDisplayables[i];
  13662. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13663. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13664. displayable.afterBrush && displayable.afterBrush(ctx);
  13665. }
  13666. this._cursor = i;
  13667. // Render temporary displayables.
  13668. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13669. var displayable = this._temporaryDisplayables[i];
  13670. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13671. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13672. displayable.afterBrush && displayable.afterBrush(ctx);
  13673. }
  13674. this._temporaryDisplayables = [];
  13675. this.notClear = true;
  13676. };
  13677. var m = [];
  13678. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13679. if (!this._rect) {
  13680. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13681. for (var i = 0; i < this._displayables.length; i++) {
  13682. var displayable = this._displayables[i];
  13683. var childRect = displayable.getBoundingRect().clone();
  13684. if (displayable.needLocalTransform()) {
  13685. childRect.applyTransform(displayable.getLocalTransform(m));
  13686. }
  13687. rect.union(childRect);
  13688. }
  13689. this._rect = rect;
  13690. }
  13691. return this._rect;
  13692. };
  13693. IncrementalDisplayble.prototype.contain = function (x, y) {
  13694. var localPos = this.transformCoordToLocal(x, y);
  13695. var rect = this.getBoundingRect();
  13696. if (rect.contain(localPos[0], localPos[1])) {
  13697. for (var i = 0; i < this._displayables.length; i++) {
  13698. var displayable = this._displayables[i];
  13699. if (displayable.contain(x, y)) {
  13700. return true;
  13701. }
  13702. }
  13703. }
  13704. return false;
  13705. };
  13706. inherits(IncrementalDisplayble, Displayable);
  13707. var round = Math.round;
  13708. var mathMax$1 = Math.max;
  13709. var mathMin$1 = Math.min;
  13710. var EMPTY_OBJ = {};
  13711. /**
  13712. * Extend shape with parameters
  13713. */
  13714. function extendShape(opts) {
  13715. return Path.extend(opts);
  13716. }
  13717. /**
  13718. * Extend path
  13719. */
  13720. function extendPath(pathData, opts) {
  13721. return extendFromString(pathData, opts);
  13722. }
  13723. /**
  13724. * Create a path element from path data string
  13725. * @param {string} pathData
  13726. * @param {Object} opts
  13727. * @param {module:zrender/core/BoundingRect} rect
  13728. * @param {string} [layout=cover] 'center' or 'cover'
  13729. */
  13730. function makePath(pathData, opts, rect, layout) {
  13731. var path = createFromString(pathData, opts);
  13732. var boundingRect = path.getBoundingRect();
  13733. if (rect) {
  13734. if (layout === 'center') {
  13735. rect = centerGraphic(rect, boundingRect);
  13736. }
  13737. resizePath(path, rect);
  13738. }
  13739. return path;
  13740. }
  13741. /**
  13742. * Create a image element from image url
  13743. * @param {string} imageUrl image url
  13744. * @param {Object} opts options
  13745. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13746. * @param {string} [layout=cover] 'center' or 'cover'
  13747. */
  13748. function makeImage(imageUrl, rect, layout) {
  13749. var path = new ZImage({
  13750. style: {
  13751. image: imageUrl,
  13752. x: rect.x,
  13753. y: rect.y,
  13754. width: rect.width,
  13755. height: rect.height
  13756. },
  13757. onload: function (img) {
  13758. if (layout === 'center') {
  13759. var boundingRect = {
  13760. width: img.width,
  13761. height: img.height
  13762. };
  13763. path.setStyle(centerGraphic(rect, boundingRect));
  13764. }
  13765. }
  13766. });
  13767. return path;
  13768. }
  13769. /**
  13770. * Get position of centered element in bounding box.
  13771. *
  13772. * @param {Object} rect element local bounding box
  13773. * @param {Object} boundingRect constraint bounding box
  13774. * @return {Object} element position containing x, y, width, and height
  13775. */
  13776. function centerGraphic(rect, boundingRect) {
  13777. // Set rect to center, keep width / height ratio.
  13778. var aspect = boundingRect.width / boundingRect.height;
  13779. var width = rect.height * aspect;
  13780. var height;
  13781. if (width <= rect.width) {
  13782. height = rect.height;
  13783. }
  13784. else {
  13785. width = rect.width;
  13786. height = width / aspect;
  13787. }
  13788. var cx = rect.x + rect.width / 2;
  13789. var cy = rect.y + rect.height / 2;
  13790. return {
  13791. x: cx - width / 2,
  13792. y: cy - height / 2,
  13793. width: width,
  13794. height: height
  13795. };
  13796. }
  13797. var mergePath = mergePath$1;
  13798. /**
  13799. * Resize a path to fit the rect
  13800. * @param {module:zrender/graphic/Path} path
  13801. * @param {Object} rect
  13802. */
  13803. function resizePath(path, rect) {
  13804. if (!path.applyTransform) {
  13805. return;
  13806. }
  13807. var pathRect = path.getBoundingRect();
  13808. var m = pathRect.calculateTransform(rect);
  13809. path.applyTransform(m);
  13810. }
  13811. /**
  13812. * Sub pixel optimize line for canvas
  13813. *
  13814. * @param {Object} param
  13815. * @param {Object} [param.shape]
  13816. * @param {number} [param.shape.x1]
  13817. * @param {number} [param.shape.y1]
  13818. * @param {number} [param.shape.x2]
  13819. * @param {number} [param.shape.y2]
  13820. * @param {Object} [param.style]
  13821. * @param {number} [param.style.lineWidth]
  13822. * @return {Object} Modified param
  13823. */
  13824. function subPixelOptimizeLine(param) {
  13825. var shape = param.shape;
  13826. var lineWidth = param.style.lineWidth;
  13827. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  13828. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13829. }
  13830. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  13831. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13832. }
  13833. return param;
  13834. }
  13835. /**
  13836. * Sub pixel optimize rect for canvas
  13837. *
  13838. * @param {Object} param
  13839. * @param {Object} [param.shape]
  13840. * @param {number} [param.shape.x]
  13841. * @param {number} [param.shape.y]
  13842. * @param {number} [param.shape.width]
  13843. * @param {number} [param.shape.height]
  13844. * @param {Object} [param.style]
  13845. * @param {number} [param.style.lineWidth]
  13846. * @return {Object} Modified param
  13847. */
  13848. function subPixelOptimizeRect(param) {
  13849. var shape = param.shape;
  13850. var lineWidth = param.style.lineWidth;
  13851. var originX = shape.x;
  13852. var originY = shape.y;
  13853. var originWidth = shape.width;
  13854. var originHeight = shape.height;
  13855. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13856. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13857. shape.width = Math.max(
  13858. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13859. originWidth === 0 ? 0 : 1
  13860. );
  13861. shape.height = Math.max(
  13862. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13863. originHeight === 0 ? 0 : 1
  13864. );
  13865. return param;
  13866. }
  13867. /**
  13868. * Sub pixel optimize for canvas
  13869. *
  13870. * @param {number} position Coordinate, such as x, y
  13871. * @param {number} lineWidth Should be nonnegative integer.
  13872. * @param {boolean=} positiveOrNegative Default false (negative).
  13873. * @return {number} Optimized position.
  13874. */
  13875. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  13876. // Assure that (position + lineWidth / 2) is near integer edge,
  13877. // otherwise line will be fuzzy in canvas.
  13878. var doubledPosition = round(position * 2);
  13879. return (doubledPosition + round(lineWidth)) % 2 === 0
  13880. ? doubledPosition / 2
  13881. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13882. }
  13883. function hasFillOrStroke(fillOrStroke) {
  13884. return fillOrStroke != null && fillOrStroke != 'none';
  13885. }
  13886. function liftColor(color) {
  13887. return typeof color === 'string' ? lift(color, -0.1) : color;
  13888. }
  13889. /**
  13890. * @private
  13891. */
  13892. function cacheElementStl(el) {
  13893. if (el.__hoverStlDirty) {
  13894. var stroke = el.style.stroke;
  13895. var fill = el.style.fill;
  13896. // Create hoverStyle on mouseover
  13897. var hoverStyle = el.__hoverStl;
  13898. hoverStyle.fill = hoverStyle.fill
  13899. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  13900. hoverStyle.stroke = hoverStyle.stroke
  13901. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  13902. var normalStyle = {};
  13903. for (var name in hoverStyle) {
  13904. // See comment in `doSingleEnterHover`.
  13905. if (hoverStyle[name] != null) {
  13906. normalStyle[name] = el.style[name];
  13907. }
  13908. }
  13909. el.__normalStl = normalStyle;
  13910. el.__hoverStlDirty = false;
  13911. }
  13912. }
  13913. /**
  13914. * @private
  13915. */
  13916. function doSingleEnterHover(el) {
  13917. if (el.__isHover) {
  13918. return;
  13919. }
  13920. cacheElementStl(el);
  13921. if (el.useHoverLayer) {
  13922. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  13923. }
  13924. else {
  13925. var style = el.style;
  13926. var insideRollbackOpt = style.insideRollbackOpt;
  13927. // Consider case: only `position: 'top'` is set on emphasis, then text
  13928. // color should be returned to `autoColor`, rather than remain '#fff'.
  13929. // So we should rollback then apply again after style merging.
  13930. insideRollbackOpt && rollbackInsideStyle(style);
  13931. // styles can be:
  13932. // {
  13933. // label: {
  13934. // show: false,
  13935. // position: 'outside',
  13936. // fontSize: 18
  13937. // },
  13938. // emphasis: {
  13939. // label: {
  13940. // show: true
  13941. // }
  13942. // }
  13943. // },
  13944. // where properties of `emphasis` may not appear in `normal`. We previously use
  13945. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  13946. // But consider rich text and setOption in merge mode, it is impossible to cover
  13947. // all properties in merge. So we use merge mode when setting style here, where
  13948. // only properties that is not `null/undefined` can be set. The disadventage:
  13949. // null/undefined can not be used to remove style any more in `emphasis`.
  13950. style.extendFrom(el.__hoverStl);
  13951. // Do not save `insideRollback`.
  13952. if (insideRollbackOpt) {
  13953. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  13954. // textFill may be rollbacked to null.
  13955. if (style.textFill == null) {
  13956. style.textFill = insideRollbackOpt.autoColor;
  13957. }
  13958. }
  13959. el.dirty(false);
  13960. el.z2 += 1;
  13961. }
  13962. el.__isHover = true;
  13963. }
  13964. /**
  13965. * @inner
  13966. */
  13967. function doSingleLeaveHover(el) {
  13968. if (!el.__isHover) {
  13969. return;
  13970. }
  13971. var normalStl = el.__normalStl;
  13972. if (el.useHoverLayer) {
  13973. el.__zr && el.__zr.removeHover(el);
  13974. }
  13975. else {
  13976. // Consider null/undefined value, should use
  13977. // `setStyle` but not `extendFrom(stl, true)`.
  13978. normalStl && el.setStyle(normalStl);
  13979. el.z2 -= 1;
  13980. }
  13981. el.__isHover = false;
  13982. }
  13983. /**
  13984. * @inner
  13985. */
  13986. function doEnterHover(el) {
  13987. el.type === 'group'
  13988. ? el.traverse(function (child) {
  13989. if (child.type !== 'group') {
  13990. doSingleEnterHover(child);
  13991. }
  13992. })
  13993. : doSingleEnterHover(el);
  13994. }
  13995. function doLeaveHover(el) {
  13996. el.type === 'group'
  13997. ? el.traverse(function (child) {
  13998. if (child.type !== 'group') {
  13999. doSingleLeaveHover(child);
  14000. }
  14001. })
  14002. : doSingleLeaveHover(el);
  14003. }
  14004. /**
  14005. * @inner
  14006. */
  14007. function setElementHoverStl(el, hoverStl) {
  14008. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14009. // Often used when item group has a label element and it's hoverStyle is different
  14010. el.__hoverStl = el.hoverStyle || hoverStl || {};
  14011. el.__hoverStlDirty = true;
  14012. if (el.__isHover) {
  14013. cacheElementStl(el);
  14014. }
  14015. }
  14016. /**
  14017. * @inner
  14018. */
  14019. function onElementMouseOver(e) {
  14020. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14021. return;
  14022. }
  14023. // Only if element is not in emphasis status
  14024. !this.__isEmphasis && doEnterHover(this);
  14025. }
  14026. /**
  14027. * @inner
  14028. */
  14029. function onElementMouseOut(e) {
  14030. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14031. return;
  14032. }
  14033. // Only if element is not in emphasis status
  14034. !this.__isEmphasis && doLeaveHover(this);
  14035. }
  14036. /**
  14037. * @inner
  14038. */
  14039. function enterEmphasis() {
  14040. this.__isEmphasis = true;
  14041. doEnterHover(this);
  14042. }
  14043. /**
  14044. * @inner
  14045. */
  14046. function leaveEmphasis() {
  14047. this.__isEmphasis = false;
  14048. doLeaveHover(this);
  14049. }
  14050. /**
  14051. * Set hover style of element.
  14052. * This method can be called repeatly without side-effects.
  14053. * @param {module:zrender/Element} el
  14054. * @param {Object} [hoverStyle]
  14055. * @param {Object} [opt]
  14056. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14057. * In touch device, mouseover event will be trigger on touchstart event
  14058. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14059. * conviniently use hoverStyle when tap on touch screen without additional
  14060. * code for compatibility.
  14061. * But if the chart/component has select feature, which usually also use
  14062. * hoverStyle, there might be conflict between 'select-highlight' and
  14063. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14064. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14065. * on touch device.
  14066. */
  14067. function setHoverStyle(el, hoverStyle, opt) {
  14068. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  14069. el.type === 'group'
  14070. ? el.traverse(function (child) {
  14071. if (child.type !== 'group') {
  14072. setElementHoverStl(child, hoverStyle);
  14073. }
  14074. })
  14075. : setElementHoverStl(el, hoverStyle);
  14076. // Duplicated function will be auto-ignored, see Eventful.js.
  14077. el.on('mouseover', onElementMouseOver)
  14078. .on('mouseout', onElementMouseOut);
  14079. // Emphasis, normal can be triggered manually
  14080. el.on('emphasis', enterEmphasis)
  14081. .on('normal', leaveEmphasis);
  14082. }
  14083. /**
  14084. * @param {Object|module:zrender/graphic/Style} normalStyle
  14085. * @param {Object} emphasisStyle
  14086. * @param {module:echarts/model/Model} normalModel
  14087. * @param {module:echarts/model/Model} emphasisModel
  14088. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14089. * @param {string|Function} [opt.defaultText]
  14090. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14091. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14092. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14093. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14094. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14095. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14096. * @param {Object} [normalSpecified]
  14097. * @param {Object} [emphasisSpecified]
  14098. */
  14099. function setLabelStyle(
  14100. normalStyle, emphasisStyle,
  14101. normalModel, emphasisModel,
  14102. opt,
  14103. normalSpecified, emphasisSpecified
  14104. ) {
  14105. opt = opt || EMPTY_OBJ;
  14106. var labelFetcher = opt.labelFetcher;
  14107. var labelDataIndex = opt.labelDataIndex;
  14108. var labelDimIndex = opt.labelDimIndex;
  14109. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14110. // is not supported util someone requests.
  14111. var showNormal = normalModel.getShallow('show');
  14112. var showEmphasis = emphasisModel.getShallow('show');
  14113. // Consider performance, only fetch label when necessary.
  14114. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14115. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14116. var baseText;
  14117. if (showNormal || showEmphasis) {
  14118. if (labelFetcher) {
  14119. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14120. }
  14121. if (baseText == null) {
  14122. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14123. }
  14124. }
  14125. var normalStyleText = showNormal ? baseText : null;
  14126. var emphasisStyleText = showEmphasis
  14127. ? retrieve2(
  14128. labelFetcher
  14129. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14130. : null,
  14131. baseText
  14132. )
  14133. : null;
  14134. // Optimize: If style.text is null, text will not be drawn.
  14135. if (normalStyleText != null || emphasisStyleText != null) {
  14136. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14137. // values have to be set on `normalStyle`.
  14138. // If we set default values on `emphasisStyle`, consider case:
  14139. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14140. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14141. // Then the 'red' will not work on emphasis.
  14142. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14143. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14144. }
  14145. normalStyle.text = normalStyleText;
  14146. emphasisStyle.text = emphasisStyleText;
  14147. }
  14148. /**
  14149. * Set basic textStyle properties.
  14150. * @param {Object|module:zrender/graphic/Style} textStyle
  14151. * @param {module:echarts/model/Model} model
  14152. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14153. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14154. * @param {boolean} [isEmphasis]
  14155. */
  14156. function setTextStyle(
  14157. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14158. ) {
  14159. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14160. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14161. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14162. return textStyle;
  14163. }
  14164. /**
  14165. * Set text option in the style.
  14166. * @deprecated
  14167. * @param {Object} textStyle
  14168. * @param {module:echarts/model/Model} labelModel
  14169. * @param {string|boolean} defaultColor Default text color.
  14170. * If set as false, it will be processed as a emphasis style.
  14171. */
  14172. function setText(textStyle, labelModel, defaultColor) {
  14173. var opt = {isRectText: true};
  14174. var isEmphasis;
  14175. if (defaultColor === false) {
  14176. isEmphasis = true;
  14177. }
  14178. else {
  14179. // Support setting color as 'auto' to get visual color.
  14180. opt.autoColor = defaultColor;
  14181. }
  14182. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14183. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14184. }
  14185. /**
  14186. * {
  14187. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14188. * isRectText: boolean,
  14189. * autoColor: string, specify a color when color is 'auto',
  14190. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14191. * If autoColor specified, it is used as default textFill.
  14192. * useInsideStyle:
  14193. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14194. * if `textFill` is not specified.
  14195. * `false`: Do not use inside style.
  14196. * `null/undefined`: use inside style if `isRectText` is true and
  14197. * `textFill` is not specified and textPosition contains `'inside'`.
  14198. * forceRich: boolean
  14199. * }
  14200. */
  14201. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14202. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14203. opt = opt || EMPTY_OBJ;
  14204. if (opt.isRectText) {
  14205. var textPosition = textStyleModel.getShallow('position')
  14206. || (isEmphasis ? null : 'inside');
  14207. // 'outside' is not a valid zr textPostion value, but used
  14208. // in bar series, and magric type should be considered.
  14209. textPosition === 'outside' && (textPosition = 'top');
  14210. textStyle.textPosition = textPosition;
  14211. textStyle.textOffset = textStyleModel.getShallow('offset');
  14212. var labelRotate = textStyleModel.getShallow('rotate');
  14213. labelRotate != null && (labelRotate *= Math.PI / 180);
  14214. textStyle.textRotation = labelRotate;
  14215. textStyle.textDistance = retrieve2(
  14216. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14217. );
  14218. }
  14219. var ecModel = textStyleModel.ecModel;
  14220. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14221. // Consider case:
  14222. // {
  14223. // data: [{
  14224. // value: 12,
  14225. // label: {
  14226. // rich: {
  14227. // // no 'a' here but using parent 'a'.
  14228. // }
  14229. // }
  14230. // }],
  14231. // rich: {
  14232. // a: { ... }
  14233. // }
  14234. // }
  14235. var richItemNames = getRichItemNames(textStyleModel);
  14236. var richResult;
  14237. if (richItemNames) {
  14238. richResult = {};
  14239. for (var name in richItemNames) {
  14240. if (richItemNames.hasOwnProperty(name)) {
  14241. // Cascade is supported in rich.
  14242. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14243. // In rich, never `disableBox`.
  14244. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14245. }
  14246. }
  14247. }
  14248. textStyle.rich = richResult;
  14249. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14250. if (opt.forceRich && !opt.textStyle) {
  14251. opt.textStyle = {};
  14252. }
  14253. return textStyle;
  14254. }
  14255. // Consider case:
  14256. // {
  14257. // data: [{
  14258. // value: 12,
  14259. // label: {
  14260. // rich: {
  14261. // // no 'a' here but using parent 'a'.
  14262. // }
  14263. // }
  14264. // }],
  14265. // rich: {
  14266. // a: { ... }
  14267. // }
  14268. // }
  14269. function getRichItemNames(textStyleModel) {
  14270. // Use object to remove duplicated names.
  14271. var richItemNameMap;
  14272. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14273. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14274. if (rich) {
  14275. richItemNameMap = richItemNameMap || {};
  14276. for (var name in rich) {
  14277. if (rich.hasOwnProperty(name)) {
  14278. richItemNameMap[name] = 1;
  14279. }
  14280. }
  14281. }
  14282. textStyleModel = textStyleModel.parentModel;
  14283. }
  14284. return richItemNameMap;
  14285. }
  14286. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14287. // In merge mode, default value should not be given.
  14288. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14289. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14290. || globalTextStyle.color;
  14291. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14292. || globalTextStyle.textBorderColor;
  14293. textStyle.textStrokeWidth = retrieve2(
  14294. textStyleModel.getShallow('textBorderWidth'),
  14295. globalTextStyle.textBorderWidth
  14296. );
  14297. if (!isEmphasis) {
  14298. if (isBlock) {
  14299. // Always set `insideRollback`, for clearing previous.
  14300. var originalTextPosition = textStyle.textPosition;
  14301. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14302. // Save original textPosition, because style.textPosition will be repalced by
  14303. // real location (like [10, 30]) in zrender.
  14304. textStyle.insideOriginalTextPosition = originalTextPosition;
  14305. textStyle.insideRollbackOpt = opt;
  14306. }
  14307. // Set default finally.
  14308. if (textStyle.textFill == null) {
  14309. textStyle.textFill = opt.autoColor;
  14310. }
  14311. }
  14312. // Do not use `getFont` here, because merge should be supported, where
  14313. // part of these properties may be changed in emphasis style, and the
  14314. // others should remain their original value got from normal style.
  14315. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14316. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14317. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14318. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14319. textStyle.textAlign = textStyleModel.getShallow('align');
  14320. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14321. || textStyleModel.getShallow('baseline');
  14322. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14323. textStyle.textWidth = textStyleModel.getShallow('width');
  14324. textStyle.textHeight = textStyleModel.getShallow('height');
  14325. textStyle.textTag = textStyleModel.getShallow('tag');
  14326. if (!isBlock || !opt.disableBox) {
  14327. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14328. textStyle.textPadding = textStyleModel.getShallow('padding');
  14329. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14330. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14331. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14332. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14333. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14334. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14335. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14336. }
  14337. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14338. || globalTextStyle.textShadowColor;
  14339. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14340. || globalTextStyle.textShadowBlur;
  14341. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14342. || globalTextStyle.textShadowOffsetX;
  14343. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14344. || globalTextStyle.textShadowOffsetY;
  14345. }
  14346. function getAutoColor(color, opt) {
  14347. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14348. }
  14349. function applyInsideStyle(textStyle, textPosition, opt) {
  14350. var useInsideStyle = opt.useInsideStyle;
  14351. var insideRollback;
  14352. if (textStyle.textFill == null
  14353. && useInsideStyle !== false
  14354. && (useInsideStyle === true
  14355. || (opt.isRectText
  14356. && textPosition
  14357. // textPosition can be [10, 30]
  14358. && typeof textPosition === 'string'
  14359. && textPosition.indexOf('inside') >= 0
  14360. )
  14361. )
  14362. ) {
  14363. insideRollback = {
  14364. textFill: null,
  14365. textStroke: textStyle.textStroke,
  14366. textStrokeWidth: textStyle.textStrokeWidth
  14367. };
  14368. textStyle.textFill = '#fff';
  14369. // Consider text with #fff overflow its container.
  14370. if (textStyle.textStroke == null) {
  14371. textStyle.textStroke = opt.autoColor;
  14372. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14373. }
  14374. }
  14375. return insideRollback;
  14376. }
  14377. function rollbackInsideStyle(style) {
  14378. var insideRollback = style.insideRollback;
  14379. if (insideRollback) {
  14380. style.textFill = insideRollback.textFill;
  14381. style.textStroke = insideRollback.textStroke;
  14382. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14383. }
  14384. }
  14385. function getFont(opt, ecModel) {
  14386. // ecModel or default text style model.
  14387. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14388. return trim([
  14389. // FIXME in node-canvas fontWeight is before fontStyle
  14390. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14391. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14392. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14393. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14394. ].join(' '));
  14395. }
  14396. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14397. if (typeof dataIndex === 'function') {
  14398. cb = dataIndex;
  14399. dataIndex = null;
  14400. }
  14401. // Do not check 'animation' property directly here. Consider this case:
  14402. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14403. // but its parent model (`seriesModel`) does.
  14404. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14405. if (animationEnabled) {
  14406. var postfix = isUpdate ? 'Update' : '';
  14407. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14408. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14409. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14410. if (typeof animationDelay === 'function') {
  14411. animationDelay = animationDelay(
  14412. dataIndex,
  14413. animatableModel.getAnimationDelayParams
  14414. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14415. : null
  14416. );
  14417. }
  14418. if (typeof duration === 'function') {
  14419. duration = duration(dataIndex);
  14420. }
  14421. duration > 0
  14422. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14423. : (el.stopAnimation(), el.attr(props), cb && cb());
  14424. }
  14425. else {
  14426. el.stopAnimation();
  14427. el.attr(props);
  14428. cb && cb();
  14429. }
  14430. }
  14431. /**
  14432. * Update graphic element properties with or without animation according to the
  14433. * configuration in series.
  14434. *
  14435. * Caution: this method will stop previous animation.
  14436. * So if do not use this method to one element twice before
  14437. * animation starts, unless you know what you are doing.
  14438. *
  14439. * @param {module:zrender/Element} el
  14440. * @param {Object} props
  14441. * @param {module:echarts/model/Model} [animatableModel]
  14442. * @param {number} [dataIndex]
  14443. * @param {Function} [cb]
  14444. * @example
  14445. * graphic.updateProps(el, {
  14446. * position: [100, 100]
  14447. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14448. * // Or
  14449. * graphic.updateProps(el, {
  14450. * position: [100, 100]
  14451. * }, seriesModel, function () { console.log('Animation done!'); });
  14452. */
  14453. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14454. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14455. }
  14456. /**
  14457. * Init graphic element properties with or without animation according to the
  14458. * configuration in series.
  14459. *
  14460. * Caution: this method will stop previous animation.
  14461. * So if do not use this method to one element twice before
  14462. * animation starts, unless you know what you are doing.
  14463. *
  14464. * @param {module:zrender/Element} el
  14465. * @param {Object} props
  14466. * @param {module:echarts/model/Model} [animatableModel]
  14467. * @param {number} [dataIndex]
  14468. * @param {Function} cb
  14469. */
  14470. function initProps(el, props, animatableModel, dataIndex, cb) {
  14471. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14472. }
  14473. /**
  14474. * Get transform matrix of target (param target),
  14475. * in coordinate of its ancestor (param ancestor)
  14476. *
  14477. * @param {module:zrender/mixin/Transformable} target
  14478. * @param {module:zrender/mixin/Transformable} [ancestor]
  14479. */
  14480. function getTransform(target, ancestor) {
  14481. var mat = identity([]);
  14482. while (target && target !== ancestor) {
  14483. mul$1(mat, target.getLocalTransform(), mat);
  14484. target = target.parent;
  14485. }
  14486. return mat;
  14487. }
  14488. /**
  14489. * Apply transform to an vertex.
  14490. * @param {Array.<number>} target [x, y]
  14491. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14492. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14493. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14494. * @param {boolean=} invert Whether use invert matrix.
  14495. * @return {Array.<number>} [x, y]
  14496. */
  14497. function applyTransform$1(target, transform, invert$$1) {
  14498. if (transform && !isArrayLike(transform)) {
  14499. transform = Transformable.getLocalTransform(transform);
  14500. }
  14501. if (invert$$1) {
  14502. transform = invert([], transform);
  14503. }
  14504. return applyTransform([], target, transform);
  14505. }
  14506. /**
  14507. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14508. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14509. * @param {boolean=} invert Whether use invert matrix.
  14510. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14511. */
  14512. function transformDirection(direction, transform, invert$$1) {
  14513. // Pick a base, ensure that transform result will not be (0, 0).
  14514. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14515. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14516. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14517. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14518. var vertex = [
  14519. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14520. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14521. ];
  14522. vertex = applyTransform$1(vertex, transform, invert$$1);
  14523. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14524. ? (vertex[0] > 0 ? 'right' : 'left')
  14525. : (vertex[1] > 0 ? 'bottom' : 'top');
  14526. }
  14527. /**
  14528. * Apply group transition animation from g1 to g2.
  14529. * If no animatableModel, no animation.
  14530. */
  14531. function groupTransition(g1, g2, animatableModel, cb) {
  14532. if (!g1 || !g2) {
  14533. return;
  14534. }
  14535. function getElMap(g) {
  14536. var elMap = {};
  14537. g.traverse(function (el) {
  14538. if (!el.isGroup && el.anid) {
  14539. elMap[el.anid] = el;
  14540. }
  14541. });
  14542. return elMap;
  14543. }
  14544. function getAnimatableProps(el) {
  14545. var obj = {
  14546. position: clone$1(el.position),
  14547. rotation: el.rotation
  14548. };
  14549. if (el.shape) {
  14550. obj.shape = extend({}, el.shape);
  14551. }
  14552. return obj;
  14553. }
  14554. var elMap1 = getElMap(g1);
  14555. g2.traverse(function (el) {
  14556. if (!el.isGroup && el.anid) {
  14557. var oldEl = elMap1[el.anid];
  14558. if (oldEl) {
  14559. var newProp = getAnimatableProps(el);
  14560. el.attr(getAnimatableProps(oldEl));
  14561. updateProps(el, newProp, animatableModel, el.dataIndex);
  14562. }
  14563. // else {
  14564. // if (el.previousProps) {
  14565. // graphic.updateProps
  14566. // }
  14567. // }
  14568. }
  14569. });
  14570. }
  14571. /**
  14572. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14573. * @param {Object} rect {x, y, width, height}
  14574. * @return {Array.<Array.<number>>} A new clipped points.
  14575. */
  14576. function clipPointsByRect(points, rect) {
  14577. return map(points, function (point) {
  14578. var x = point[0];
  14579. x = mathMax$1(x, rect.x);
  14580. x = mathMin$1(x, rect.x + rect.width);
  14581. var y = point[1];
  14582. y = mathMax$1(y, rect.y);
  14583. y = mathMin$1(y, rect.y + rect.height);
  14584. return [x, y];
  14585. });
  14586. }
  14587. /**
  14588. * @param {Object} targetRect {x, y, width, height}
  14589. * @param {Object} rect {x, y, width, height}
  14590. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14591. */
  14592. function clipRectByRect(targetRect, rect) {
  14593. var x = mathMax$1(targetRect.x, rect.x);
  14594. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14595. var y = mathMax$1(targetRect.y, rect.y);
  14596. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14597. if (x2 >= x && y2 >= y) {
  14598. return {
  14599. x: x,
  14600. y: y,
  14601. width: x2 - x,
  14602. height: y2 - y
  14603. };
  14604. }
  14605. }
  14606. /**
  14607. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14608. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14609. * @param {Object} [rect] {x, y, width, height}
  14610. * @return {module:zrender/Element} Icon path or image element.
  14611. */
  14612. function createIcon(iconStr, opt, rect) {
  14613. opt = extend({rectHover: true}, opt);
  14614. var style = opt.style = {strokeNoScale: true};
  14615. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14616. if (iconStr) {
  14617. return iconStr.indexOf('image://') === 0
  14618. ? (
  14619. style.image = iconStr.slice(8),
  14620. defaults(style, rect),
  14621. new ZImage(opt)
  14622. )
  14623. : (
  14624. makePath(
  14625. iconStr.replace('path://', ''),
  14626. opt,
  14627. rect,
  14628. 'center'
  14629. )
  14630. );
  14631. }
  14632. }
  14633. var graphic = (Object.freeze || Object)({
  14634. extendShape: extendShape,
  14635. extendPath: extendPath,
  14636. makePath: makePath,
  14637. makeImage: makeImage,
  14638. mergePath: mergePath,
  14639. resizePath: resizePath,
  14640. subPixelOptimizeLine: subPixelOptimizeLine,
  14641. subPixelOptimizeRect: subPixelOptimizeRect,
  14642. subPixelOptimize: subPixelOptimize,
  14643. setHoverStyle: setHoverStyle,
  14644. setLabelStyle: setLabelStyle,
  14645. setTextStyle: setTextStyle,
  14646. setText: setText,
  14647. getFont: getFont,
  14648. updateProps: updateProps,
  14649. initProps: initProps,
  14650. getTransform: getTransform,
  14651. applyTransform: applyTransform$1,
  14652. transformDirection: transformDirection,
  14653. groupTransition: groupTransition,
  14654. clipPointsByRect: clipPointsByRect,
  14655. clipRectByRect: clipRectByRect,
  14656. createIcon: createIcon,
  14657. Group: Group,
  14658. Image: ZImage,
  14659. Text: Text,
  14660. Circle: Circle,
  14661. Sector: Sector,
  14662. Ring: Ring,
  14663. Polygon: Polygon,
  14664. Polyline: Polyline,
  14665. Rect: Rect,
  14666. Line: Line,
  14667. BezierCurve: BezierCurve,
  14668. Arc: Arc,
  14669. IncrementalDisplayable: IncrementalDisplayble,
  14670. CompoundPath: CompoundPath,
  14671. LinearGradient: LinearGradient,
  14672. RadialGradient: RadialGradient,
  14673. BoundingRect: BoundingRect
  14674. });
  14675. var PATH_COLOR = ['textStyle', 'color'];
  14676. var textStyleMixin = {
  14677. /**
  14678. * Get color property or get color from option.textStyle.color
  14679. * @param {boolean} [isEmphasis]
  14680. * @return {string}
  14681. */
  14682. getTextColor: function (isEmphasis) {
  14683. var ecModel = this.ecModel;
  14684. return this.getShallow('color')
  14685. || (
  14686. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14687. );
  14688. },
  14689. /**
  14690. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14691. * @return {string}
  14692. */
  14693. getFont: function () {
  14694. return getFont({
  14695. fontStyle: this.getShallow('fontStyle'),
  14696. fontWeight: this.getShallow('fontWeight'),
  14697. fontSize: this.getShallow('fontSize'),
  14698. fontFamily: this.getShallow('fontFamily')
  14699. }, this.ecModel);
  14700. },
  14701. getTextRect: function (text) {
  14702. return getBoundingRect(
  14703. text,
  14704. this.getFont(),
  14705. this.getShallow('align'),
  14706. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14707. this.getShallow('padding'),
  14708. this.getShallow('rich'),
  14709. this.getShallow('truncateText')
  14710. );
  14711. }
  14712. };
  14713. var getItemStyle = makeStyleMapper(
  14714. [
  14715. ['fill', 'color'],
  14716. ['stroke', 'borderColor'],
  14717. ['lineWidth', 'borderWidth'],
  14718. ['opacity'],
  14719. ['shadowBlur'],
  14720. ['shadowOffsetX'],
  14721. ['shadowOffsetY'],
  14722. ['shadowColor'],
  14723. ['textPosition'],
  14724. ['textAlign']
  14725. ]
  14726. );
  14727. var itemStyleMixin = {
  14728. getItemStyle: function (excludes, includes) {
  14729. var style = getItemStyle(this, excludes, includes);
  14730. var lineDash = this.getBorderLineDash();
  14731. lineDash && (style.lineDash = lineDash);
  14732. return style;
  14733. },
  14734. getBorderLineDash: function () {
  14735. var lineType = this.get('borderType');
  14736. return (lineType === 'solid' || lineType == null) ? null
  14737. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14738. }
  14739. };
  14740. /**
  14741. * @module echarts/model/Model
  14742. */
  14743. var mixin$1 = mixin;
  14744. var inner = makeInner();
  14745. /**
  14746. * @alias module:echarts/model/Model
  14747. * @constructor
  14748. * @param {Object} option
  14749. * @param {module:echarts/model/Model} [parentModel]
  14750. * @param {module:echarts/model/Global} [ecModel]
  14751. */
  14752. function Model(option, parentModel, ecModel) {
  14753. /**
  14754. * @type {module:echarts/model/Model}
  14755. * @readOnly
  14756. */
  14757. this.parentModel = parentModel;
  14758. /**
  14759. * @type {module:echarts/model/Global}
  14760. * @readOnly
  14761. */
  14762. this.ecModel = ecModel;
  14763. /**
  14764. * @type {Object}
  14765. * @protected
  14766. */
  14767. this.option = option;
  14768. // Simple optimization
  14769. // if (this.init) {
  14770. // if (arguments.length <= 4) {
  14771. // this.init(option, parentModel, ecModel, extraOpt);
  14772. // }
  14773. // else {
  14774. // this.init.apply(this, arguments);
  14775. // }
  14776. // }
  14777. }
  14778. Model.prototype = {
  14779. constructor: Model,
  14780. /**
  14781. * Model 的初始化函数
  14782. * @param {Object} option
  14783. */
  14784. init: null,
  14785. /**
  14786. * 从新的 Option merge
  14787. */
  14788. mergeOption: function (option) {
  14789. merge(this.option, option, true);
  14790. },
  14791. /**
  14792. * @param {string|Array.<string>} path
  14793. * @param {boolean} [ignoreParent=false]
  14794. * @return {*}
  14795. */
  14796. get: function (path, ignoreParent) {
  14797. if (path == null) {
  14798. return this.option;
  14799. }
  14800. return doGet(
  14801. this.option,
  14802. this.parsePath(path),
  14803. !ignoreParent && getParent(this, path)
  14804. );
  14805. },
  14806. /**
  14807. * @param {string} key
  14808. * @param {boolean} [ignoreParent=false]
  14809. * @return {*}
  14810. */
  14811. getShallow: function (key, ignoreParent) {
  14812. var option = this.option;
  14813. var val = option == null ? option : option[key];
  14814. var parentModel = !ignoreParent && getParent(this, key);
  14815. if (val == null && parentModel) {
  14816. val = parentModel.getShallow(key);
  14817. }
  14818. return val;
  14819. },
  14820. /**
  14821. * @param {string|Array.<string>} [path]
  14822. * @param {module:echarts/model/Model} [parentModel]
  14823. * @return {module:echarts/model/Model}
  14824. */
  14825. getModel: function (path, parentModel) {
  14826. var obj = path == null
  14827. ? this.option
  14828. : doGet(this.option, path = this.parsePath(path));
  14829. var thisParentModel;
  14830. parentModel = parentModel || (
  14831. (thisParentModel = getParent(this, path))
  14832. && thisParentModel.getModel(path)
  14833. );
  14834. return new Model(obj, parentModel, this.ecModel);
  14835. },
  14836. /**
  14837. * If model has option
  14838. */
  14839. isEmpty: function () {
  14840. return this.option == null;
  14841. },
  14842. restoreData: function () {},
  14843. // Pending
  14844. clone: function () {
  14845. var Ctor = this.constructor;
  14846. return new Ctor(clone(this.option));
  14847. },
  14848. setReadOnly: function (properties) {
  14849. // clazzUtil.setReadOnly(this, properties);
  14850. },
  14851. // If path is null/undefined, return null/undefined.
  14852. parsePath: function(path) {
  14853. if (typeof path === 'string') {
  14854. path = path.split('.');
  14855. }
  14856. return path;
  14857. },
  14858. /**
  14859. * @param {Function} getParentMethod
  14860. * param {Array.<string>|string} path
  14861. * return {module:echarts/model/Model}
  14862. */
  14863. customizeGetParent: function (getParentMethod) {
  14864. inner(this).getParent = getParentMethod;
  14865. },
  14866. isAnimationEnabled: function () {
  14867. if (!env$1.node) {
  14868. if (this.option.animation != null) {
  14869. return !!this.option.animation;
  14870. }
  14871. else if (this.parentModel) {
  14872. return this.parentModel.isAnimationEnabled();
  14873. }
  14874. }
  14875. }
  14876. };
  14877. function doGet(obj, pathArr, parentModel) {
  14878. for (var i = 0; i < pathArr.length; i++) {
  14879. // Ignore empty
  14880. if (!pathArr[i]) {
  14881. continue;
  14882. }
  14883. // obj could be number/string/... (like 0)
  14884. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  14885. if (obj == null) {
  14886. break;
  14887. }
  14888. }
  14889. if (obj == null && parentModel) {
  14890. obj = parentModel.get(pathArr);
  14891. }
  14892. return obj;
  14893. }
  14894. // `path` can be null/undefined
  14895. function getParent(model, path) {
  14896. var getParentMethod = inner(model).getParent;
  14897. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  14898. }
  14899. // Enable Model.extend.
  14900. enableClassExtend(Model);
  14901. enableClassCheck(Model);
  14902. mixin$1(Model, lineStyleMixin);
  14903. mixin$1(Model, areaStyleMixin);
  14904. mixin$1(Model, textStyleMixin);
  14905. mixin$1(Model, itemStyleMixin);
  14906. var base = 0;
  14907. /**
  14908. * @public
  14909. * @param {string} type
  14910. * @return {string}
  14911. */
  14912. function getUID(type) {
  14913. // Considering the case of crossing js context,
  14914. // use Math.random to make id as unique as possible.
  14915. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  14916. }
  14917. /**
  14918. * @inner
  14919. */
  14920. function enableSubTypeDefaulter(entity) {
  14921. var subTypeDefaulters = {};
  14922. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  14923. componentType = parseClassType$1(componentType);
  14924. subTypeDefaulters[componentType.main] = defaulter;
  14925. };
  14926. entity.determineSubType = function (componentType, option) {
  14927. var type = option.type;
  14928. if (!type) {
  14929. var componentTypeMain = parseClassType$1(componentType).main;
  14930. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14931. type = subTypeDefaulters[componentTypeMain](option);
  14932. }
  14933. }
  14934. return type;
  14935. };
  14936. return entity;
  14937. }
  14938. /**
  14939. * Topological travel on Activity Network (Activity On Vertices).
  14940. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14941. *
  14942. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14943. *
  14944. * If there is circle dependencey, Error will be thrown.
  14945. *
  14946. */
  14947. function enableTopologicalTravel(entity, dependencyGetter) {
  14948. /**
  14949. * @public
  14950. * @param {Array.<string>} targetNameList Target Component type list.
  14951. * Can be ['aa', 'bb', 'aa.xx']
  14952. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  14953. * @param {Function} callback Params: componentType, dependencies.
  14954. * @param {Object} context Scope of callback.
  14955. */
  14956. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14957. if (!targetNameList.length) {
  14958. return;
  14959. }
  14960. var result = makeDepndencyGraph(fullNameList);
  14961. var graph = result.graph;
  14962. var stack = result.noEntryList;
  14963. var targetNameSet = {};
  14964. each$1(targetNameList, function (name) {
  14965. targetNameSet[name] = true;
  14966. });
  14967. while (stack.length) {
  14968. var currComponentType = stack.pop();
  14969. var currVertex = graph[currComponentType];
  14970. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14971. if (isInTargetNameSet) {
  14972. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14973. delete targetNameSet[currComponentType];
  14974. }
  14975. each$1(
  14976. currVertex.successor,
  14977. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  14978. );
  14979. }
  14980. each$1(targetNameSet, function () {
  14981. throw new Error('Circle dependency may exists');
  14982. });
  14983. function removeEdge(succComponentType) {
  14984. graph[succComponentType].entryCount--;
  14985. if (graph[succComponentType].entryCount === 0) {
  14986. stack.push(succComponentType);
  14987. }
  14988. }
  14989. // Consider this case: legend depends on series, and we call
  14990. // chart.setOption({series: [...]}), where only series is in option.
  14991. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14992. // not be called, but only sereis.mergeOption is called. Thus legend
  14993. // have no chance to update its local record about series (like which
  14994. // name of series is available in legend).
  14995. function removeEdgeAndAdd(succComponentType) {
  14996. targetNameSet[succComponentType] = true;
  14997. removeEdge(succComponentType);
  14998. }
  14999. };
  15000. /**
  15001. * DepndencyGraph: {Object}
  15002. * key: conponentType,
  15003. * value: {
  15004. * successor: [conponentTypes...],
  15005. * originalDeps: [conponentTypes...],
  15006. * entryCount: {number}
  15007. * }
  15008. */
  15009. function makeDepndencyGraph(fullNameList) {
  15010. var graph = {};
  15011. var noEntryList = [];
  15012. each$1(fullNameList, function (name) {
  15013. var thisItem = createDependencyGraphItem(graph, name);
  15014. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15015. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15016. thisItem.entryCount = availableDeps.length;
  15017. if (thisItem.entryCount === 0) {
  15018. noEntryList.push(name);
  15019. }
  15020. each$1(availableDeps, function (dependentName) {
  15021. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15022. thisItem.predecessor.push(dependentName);
  15023. }
  15024. var thatItem = createDependencyGraphItem(graph, dependentName);
  15025. if (indexOf(thatItem.successor, dependentName) < 0) {
  15026. thatItem.successor.push(name);
  15027. }
  15028. });
  15029. });
  15030. return {graph: graph, noEntryList: noEntryList};
  15031. }
  15032. function createDependencyGraphItem(graph, name) {
  15033. if (!graph[name]) {
  15034. graph[name] = {predecessor: [], successor: []};
  15035. }
  15036. return graph[name];
  15037. }
  15038. function getAvailableDependencies(originalDeps, fullNameList) {
  15039. var availableDeps = [];
  15040. each$1(originalDeps, function (dep) {
  15041. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15042. });
  15043. return availableDeps;
  15044. }
  15045. }
  15046. var RADIAN_EPSILON = 1e-4;
  15047. function _trim(str) {
  15048. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15049. }
  15050. /**
  15051. * Linear mapping a value from domain to range
  15052. * @memberOf module:echarts/util/number
  15053. * @param {(number|Array.<number>)} val
  15054. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15055. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15056. * @param {boolean} clamp
  15057. * @return {(number|Array.<number>}
  15058. */
  15059. function linearMap(val, domain, range, clamp) {
  15060. var subDomain = domain[1] - domain[0];
  15061. var subRange = range[1] - range[0];
  15062. if (subDomain === 0) {
  15063. return subRange === 0
  15064. ? range[0]
  15065. : (range[0] + range[1]) / 2;
  15066. }
  15067. // Avoid accuracy problem in edge, such as
  15068. // 146.39 - 62.83 === 83.55999999999999.
  15069. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15070. // It is a little verbose for efficiency considering this method
  15071. // is a hotspot.
  15072. if (clamp) {
  15073. if (subDomain > 0) {
  15074. if (val <= domain[0]) {
  15075. return range[0];
  15076. }
  15077. else if (val >= domain[1]) {
  15078. return range[1];
  15079. }
  15080. }
  15081. else {
  15082. if (val >= domain[0]) {
  15083. return range[0];
  15084. }
  15085. else if (val <= domain[1]) {
  15086. return range[1];
  15087. }
  15088. }
  15089. }
  15090. else {
  15091. if (val === domain[0]) {
  15092. return range[0];
  15093. }
  15094. if (val === domain[1]) {
  15095. return range[1];
  15096. }
  15097. }
  15098. return (val - domain[0]) / subDomain * subRange + range[0];
  15099. }
  15100. /**
  15101. * Convert a percent string to absolute number.
  15102. * Returns NaN if percent is not a valid string or number
  15103. * @memberOf module:echarts/util/number
  15104. * @param {string|number} percent
  15105. * @param {number} all
  15106. * @return {number}
  15107. */
  15108. function parsePercent$1(percent, all) {
  15109. switch (percent) {
  15110. case 'center':
  15111. case 'middle':
  15112. percent = '50%';
  15113. break;
  15114. case 'left':
  15115. case 'top':
  15116. percent = '0%';
  15117. break;
  15118. case 'right':
  15119. case 'bottom':
  15120. percent = '100%';
  15121. break;
  15122. }
  15123. if (typeof percent === 'string') {
  15124. if (_trim(percent).match(/%$/)) {
  15125. return parseFloat(percent) / 100 * all;
  15126. }
  15127. return parseFloat(percent);
  15128. }
  15129. return percent == null ? NaN : +percent;
  15130. }
  15131. /**
  15132. * (1) Fix rounding error of float numbers.
  15133. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15134. *
  15135. * @param {number} x
  15136. * @param {number} [precision]
  15137. * @param {boolean} [returnStr]
  15138. * @return {number|string}
  15139. */
  15140. function round$1(x, precision, returnStr) {
  15141. if (precision == null) {
  15142. precision = 10;
  15143. }
  15144. // Avoid range error
  15145. precision = Math.min(Math.max(0, precision), 20);
  15146. x = (+x).toFixed(precision);
  15147. return returnStr ? x : +x;
  15148. }
  15149. function asc(arr) {
  15150. arr.sort(function (a, b) {
  15151. return a - b;
  15152. });
  15153. return arr;
  15154. }
  15155. /**
  15156. * Get precision
  15157. * @param {number} val
  15158. */
  15159. function getPrecision(val) {
  15160. val = +val;
  15161. if (isNaN(val)) {
  15162. return 0;
  15163. }
  15164. // It is much faster than methods converting number to string as follows
  15165. // var tmp = val.toString();
  15166. // return tmp.length - 1 - tmp.indexOf('.');
  15167. // especially when precision is low
  15168. var e = 1;
  15169. var count = 0;
  15170. while (Math.round(val * e) / e !== val) {
  15171. e *= 10;
  15172. count++;
  15173. }
  15174. return count;
  15175. }
  15176. /**
  15177. * @param {string|number} val
  15178. * @return {number}
  15179. */
  15180. function getPrecisionSafe(val) {
  15181. var str = val.toString();
  15182. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15183. var eIndex = str.indexOf('e');
  15184. if (eIndex > 0) {
  15185. var precision = +str.slice(eIndex + 1);
  15186. return precision < 0 ? -precision : 0;
  15187. }
  15188. else {
  15189. var dotIndex = str.indexOf('.');
  15190. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15191. }
  15192. }
  15193. /**
  15194. * Minimal dicernible data precisioin according to a single pixel.
  15195. *
  15196. * @param {Array.<number>} dataExtent
  15197. * @param {Array.<number>} pixelExtent
  15198. * @return {number} precision
  15199. */
  15200. function getPixelPrecision(dataExtent, pixelExtent) {
  15201. var log = Math.log;
  15202. var LN10 = Math.LN10;
  15203. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15204. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15205. // toFixed() digits argument must be between 0 and 20.
  15206. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15207. return !isFinite(precision) ? 20 : precision;
  15208. }
  15209. /**
  15210. * Get a data of given precision, assuring the sum of percentages
  15211. * in valueList is 1.
  15212. * The largest remainer method is used.
  15213. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15214. *
  15215. * @param {Array.<number>} valueList a list of all data
  15216. * @param {number} idx index of the data to be processed in valueList
  15217. * @param {number} precision integer number showing digits of precision
  15218. * @return {number} percent ranging from 0 to 100
  15219. */
  15220. function getPercentWithPrecision(valueList, idx, precision) {
  15221. if (!valueList[idx]) {
  15222. return 0;
  15223. }
  15224. var sum = reduce(valueList, function (acc, val) {
  15225. return acc + (isNaN(val) ? 0 : val);
  15226. }, 0);
  15227. if (sum === 0) {
  15228. return 0;
  15229. }
  15230. var digits = Math.pow(10, precision);
  15231. var votesPerQuota = map(valueList, function (val) {
  15232. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15233. });
  15234. var targetSeats = digits * 100;
  15235. var seats = map(votesPerQuota, function (votes) {
  15236. // Assign automatic seats.
  15237. return Math.floor(votes);
  15238. });
  15239. var currentSum = reduce(seats, function (acc, val) {
  15240. return acc + val;
  15241. }, 0);
  15242. var remainder = map(votesPerQuota, function (votes, idx) {
  15243. return votes - seats[idx];
  15244. });
  15245. // Has remainding votes.
  15246. while (currentSum < targetSeats) {
  15247. // Find next largest remainder.
  15248. var max = Number.NEGATIVE_INFINITY;
  15249. var maxId = null;
  15250. for (var i = 0, len = remainder.length; i < len; ++i) {
  15251. if (remainder[i] > max) {
  15252. max = remainder[i];
  15253. maxId = i;
  15254. }
  15255. }
  15256. // Add a vote to max remainder.
  15257. ++seats[maxId];
  15258. remainder[maxId] = 0;
  15259. ++currentSum;
  15260. }
  15261. return seats[idx] / digits;
  15262. }
  15263. // Number.MAX_SAFE_INTEGER, ie do not support.
  15264. var MAX_SAFE_INTEGER = 9007199254740991;
  15265. /**
  15266. * To 0 - 2 * PI, considering negative radian.
  15267. * @param {number} radian
  15268. * @return {number}
  15269. */
  15270. function remRadian(radian) {
  15271. var pi2 = Math.PI * 2;
  15272. return (radian % pi2 + pi2) % pi2;
  15273. }
  15274. /**
  15275. * @param {type} radian
  15276. * @return {boolean}
  15277. */
  15278. function isRadianAroundZero(val) {
  15279. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15280. }
  15281. 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
  15282. /**
  15283. * @param {string|Date|number} value These values can be accepted:
  15284. * + An instance of Date, represent a time in its own time zone.
  15285. * + Or string in a subset of ISO 8601, only including:
  15286. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15287. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15288. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15289. * all of which will be treated as local time if time zone is not specified
  15290. * (see <https://momentjs.com/>).
  15291. * + Or other string format, including (all of which will be treated as loacal time):
  15292. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15293. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15294. * + a timestamp, which represent a time in UTC.
  15295. * @return {Date} date
  15296. */
  15297. function parseDate(value) {
  15298. if (value instanceof Date) {
  15299. return value;
  15300. }
  15301. else if (typeof value === 'string') {
  15302. // Different browsers parse date in different way, so we parse it manually.
  15303. // Some other issues:
  15304. // new Date('1970-01-01') is UTC,
  15305. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15306. // See issue #3623
  15307. var match = TIME_REG.exec(value);
  15308. if (!match) {
  15309. // return Invalid Date.
  15310. return new Date(NaN);
  15311. }
  15312. // Use local time when no timezone offset specifed.
  15313. if (!match[8]) {
  15314. // match[n] can only be string or undefined.
  15315. // But take care of '12' + 1 => '121'.
  15316. return new Date(
  15317. +match[1],
  15318. +(match[2] || 1) - 1,
  15319. +match[3] || 1,
  15320. +match[4] || 0,
  15321. +(match[5] || 0),
  15322. +match[6] || 0,
  15323. +match[7] || 0
  15324. );
  15325. }
  15326. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15327. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15328. // For example, system timezone is set as "Time Zone: America/Toronto",
  15329. // then these code will get different result:
  15330. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15331. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15332. // So we should not use `new Date`, but use `Date.UTC`.
  15333. else {
  15334. var hour = +match[4] || 0;
  15335. if (match[8].toUpperCase() !== 'Z') {
  15336. hour -= match[8].slice(0, 3);
  15337. }
  15338. return new Date(Date.UTC(
  15339. +match[1],
  15340. +(match[2] || 1) - 1,
  15341. +match[3] || 1,
  15342. hour,
  15343. +(match[5] || 0),
  15344. +match[6] || 0,
  15345. +match[7] || 0
  15346. ));
  15347. }
  15348. }
  15349. else if (value == null) {
  15350. return new Date(NaN);
  15351. }
  15352. return new Date(Math.round(value));
  15353. }
  15354. /**
  15355. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15356. *
  15357. * @param {number} val
  15358. * @return {number}
  15359. */
  15360. function quantity(val) {
  15361. return Math.pow(10, quantityExponent(val));
  15362. }
  15363. function quantityExponent(val) {
  15364. return Math.floor(Math.log(val) / Math.LN10);
  15365. }
  15366. /**
  15367. * find a “nice” number approximately equal to x. Round the number if round = true,
  15368. * take ceiling if round = false. The primary observation is that the “nicest”
  15369. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15370. *
  15371. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15372. *
  15373. * @param {number} val Non-negative value.
  15374. * @param {boolean} round
  15375. * @return {number}
  15376. */
  15377. function nice(val, round) {
  15378. var exponent = quantityExponent(val);
  15379. var exp10 = Math.pow(10, exponent);
  15380. var f = val / exp10; // 1 <= f < 10
  15381. var nf;
  15382. if (round) {
  15383. if (f < 1.5) { nf = 1; }
  15384. else if (f < 2.5) { nf = 2; }
  15385. else if (f < 4) { nf = 3; }
  15386. else if (f < 7) { nf = 5; }
  15387. else { nf = 10; }
  15388. }
  15389. else {
  15390. if (f < 1) { nf = 1; }
  15391. else if (f < 2) { nf = 2; }
  15392. else if (f < 3) { nf = 3; }
  15393. else if (f < 5) { nf = 5; }
  15394. else { nf = 10; }
  15395. }
  15396. val = nf * exp10;
  15397. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15398. // 20 is the uppper bound of toFixed.
  15399. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15400. }
  15401. /**
  15402. * Order intervals asc, and split them when overlap.
  15403. * expect(numberUtil.reformIntervals([
  15404. * {interval: [18, 62], close: [1, 1]},
  15405. * {interval: [-Infinity, -70], close: [0, 0]},
  15406. * {interval: [-70, -26], close: [1, 1]},
  15407. * {interval: [-26, 18], close: [1, 1]},
  15408. * {interval: [62, 150], close: [1, 1]},
  15409. * {interval: [106, 150], close: [1, 1]},
  15410. * {interval: [150, Infinity], close: [0, 0]}
  15411. * ])).toEqual([
  15412. * {interval: [-Infinity, -70], close: [0, 0]},
  15413. * {interval: [-70, -26], close: [1, 1]},
  15414. * {interval: [-26, 18], close: [0, 1]},
  15415. * {interval: [18, 62], close: [0, 1]},
  15416. * {interval: [62, 150], close: [0, 1]},
  15417. * {interval: [150, Infinity], close: [0, 0]}
  15418. * ]);
  15419. * @param {Array.<Object>} list, where `close` mean open or close
  15420. * of the interval, and Infinity can be used.
  15421. * @return {Array.<Object>} The origin list, which has been reformed.
  15422. */
  15423. function reformIntervals(list) {
  15424. list.sort(function (a, b) {
  15425. return littleThan(a, b, 0) ? -1 : 1;
  15426. });
  15427. var curr = -Infinity;
  15428. var currClose = 1;
  15429. for (var i = 0; i < list.length;) {
  15430. var interval = list[i].interval;
  15431. var close = list[i].close;
  15432. for (var lg = 0; lg < 2; lg++) {
  15433. if (interval[lg] <= curr) {
  15434. interval[lg] = curr;
  15435. close[lg] = !lg ? 1 - currClose : 1;
  15436. }
  15437. curr = interval[lg];
  15438. currClose = close[lg];
  15439. }
  15440. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15441. list.splice(i, 1);
  15442. }
  15443. else {
  15444. i++;
  15445. }
  15446. }
  15447. return list;
  15448. function littleThan(a, b, lg) {
  15449. return a.interval[lg] < b.interval[lg]
  15450. || (
  15451. a.interval[lg] === b.interval[lg]
  15452. && (
  15453. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  15454. || (!lg && littleThan(a, b, 1))
  15455. )
  15456. );
  15457. }
  15458. }
  15459. /**
  15460. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15461. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15462. * subtraction forces infinities to NaN
  15463. *
  15464. * @param {*} v
  15465. * @return {boolean}
  15466. */
  15467. function isNumeric(v) {
  15468. return v - parseFloat(v) >= 0;
  15469. }
  15470. var number = (Object.freeze || Object)({
  15471. linearMap: linearMap,
  15472. parsePercent: parsePercent$1,
  15473. round: round$1,
  15474. asc: asc,
  15475. getPrecision: getPrecision,
  15476. getPrecisionSafe: getPrecisionSafe,
  15477. getPixelPrecision: getPixelPrecision,
  15478. getPercentWithPrecision: getPercentWithPrecision,
  15479. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15480. remRadian: remRadian,
  15481. isRadianAroundZero: isRadianAroundZero,
  15482. parseDate: parseDate,
  15483. quantity: quantity,
  15484. nice: nice,
  15485. reformIntervals: reformIntervals,
  15486. isNumeric: isNumeric
  15487. });
  15488. /**
  15489. * 每三位默认加,格式化
  15490. * @param {string|number} x
  15491. * @return {string}
  15492. */
  15493. function addCommas(x) {
  15494. if (isNaN(x)) {
  15495. return '-';
  15496. }
  15497. x = (x + '').split('.');
  15498. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  15499. + (x.length > 1 ? ('.' + x[1]) : '');
  15500. }
  15501. /**
  15502. * @param {string} str
  15503. * @param {boolean} [upperCaseFirst=false]
  15504. * @return {string} str
  15505. */
  15506. function toCamelCase(str, upperCaseFirst) {
  15507. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  15508. return group1.toUpperCase();
  15509. });
  15510. if (upperCaseFirst && str) {
  15511. str = str.charAt(0).toUpperCase() + str.slice(1);
  15512. }
  15513. return str;
  15514. }
  15515. var normalizeCssArray$1 = normalizeCssArray;
  15516. function encodeHTML(source) {
  15517. return String(source)
  15518. .replace(/&/g, '&amp;')
  15519. .replace(/</g, '&lt;')
  15520. .replace(/>/g, '&gt;')
  15521. .replace(/"/g, '&quot;')
  15522. .replace(/'/g, '&#39;');
  15523. }
  15524. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15525. var wrapVar = function (varName, seriesIdx) {
  15526. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15527. };
  15528. /**
  15529. * Template formatter
  15530. * @param {string} tpl
  15531. * @param {Array.<Object>|Object} paramsList
  15532. * @param {boolean} [encode=false]
  15533. * @return {string}
  15534. */
  15535. function formatTpl(tpl, paramsList, encode) {
  15536. if (!isArray(paramsList)) {
  15537. paramsList = [paramsList];
  15538. }
  15539. var seriesLen = paramsList.length;
  15540. if (!seriesLen) {
  15541. return '';
  15542. }
  15543. var $vars = paramsList[0].$vars || [];
  15544. for (var i = 0; i < $vars.length; i++) {
  15545. var alias = TPL_VAR_ALIAS[i];
  15546. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15547. }
  15548. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15549. for (var k = 0; k < $vars.length; k++) {
  15550. var val = paramsList[seriesIdx][$vars[k]];
  15551. tpl = tpl.replace(
  15552. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  15553. encode ? encodeHTML(val) : val
  15554. );
  15555. }
  15556. }
  15557. return tpl;
  15558. }
  15559. /**
  15560. * simple Template formatter
  15561. *
  15562. * @param {string} tpl
  15563. * @param {Object} param
  15564. * @param {boolean} [encode=false]
  15565. * @return {string}
  15566. */
  15567. function formatTplSimple(tpl, param, encode) {
  15568. each$1(param, function (value, key) {
  15569. tpl = tpl.replace(
  15570. '{' + key + '}',
  15571. encode ? encodeHTML(value) : value
  15572. );
  15573. });
  15574. return tpl;
  15575. }
  15576. /**
  15577. * @param {Object|string} [opt] If string, means color.
  15578. * @param {string} [opt.color]
  15579. * @param {string} [opt.extraCssText]
  15580. * @param {string} [opt.type='item'] 'item' or 'subItem'
  15581. * @return {string}
  15582. */
  15583. function getTooltipMarker(opt, extraCssText) {
  15584. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  15585. var color = opt.color;
  15586. var type = opt.type;
  15587. var extraCssText = opt.extraCssText;
  15588. if (!color) {
  15589. return '';
  15590. }
  15591. return type === 'subItem'
  15592. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  15593. + 'border-radius:4px;width:4px;height:4px;background-color:'
  15594. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  15595. : '<span style="display:inline-block;margin-right:5px;'
  15596. + 'border-radius:10px;width:10px;height:10px;background-color:'
  15597. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  15598. }
  15599. function pad(str, len) {
  15600. str += '';
  15601. return '0000'.substr(0, len - str.length) + str;
  15602. }
  15603. /**
  15604. * ISO Date format
  15605. * @param {string} tpl
  15606. * @param {number} value
  15607. * @param {boolean} [isUTC=false] Default in local time.
  15608. * see `module:echarts/scale/Time`
  15609. * and `module:echarts/util/number#parseDate`.
  15610. * @inner
  15611. */
  15612. function formatTime(tpl, value, isUTC) {
  15613. if (tpl === 'week'
  15614. || tpl === 'month'
  15615. || tpl === 'quarter'
  15616. || tpl === 'half-year'
  15617. || tpl === 'year'
  15618. ) {
  15619. tpl = 'MM-dd\nyyyy';
  15620. }
  15621. var date = parseDate(value);
  15622. var utc = isUTC ? 'UTC' : '';
  15623. var y = date['get' + utc + 'FullYear']();
  15624. var M = date['get' + utc + 'Month']() + 1;
  15625. var d = date['get' + utc + 'Date']();
  15626. var h = date['get' + utc + 'Hours']();
  15627. var m = date['get' + utc + 'Minutes']();
  15628. var s = date['get' + utc + 'Seconds']();
  15629. var S = date['get' + utc + 'Milliseconds']();
  15630. tpl = tpl.replace('MM', pad(M, 2))
  15631. .replace('M', M)
  15632. .replace('yyyy', y)
  15633. .replace('yy', y % 100)
  15634. .replace('dd', pad(d, 2))
  15635. .replace('d', d)
  15636. .replace('hh', pad(h, 2))
  15637. .replace('h', h)
  15638. .replace('mm', pad(m, 2))
  15639. .replace('m', m)
  15640. .replace('ss', pad(s, 2))
  15641. .replace('s', s)
  15642. .replace('SSS', pad(S, 3));
  15643. return tpl;
  15644. }
  15645. /**
  15646. * Capital first
  15647. * @param {string} str
  15648. * @return {string}
  15649. */
  15650. function capitalFirst(str) {
  15651. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15652. }
  15653. var truncateText$1 = truncateText;
  15654. var getTextRect = getBoundingRect;
  15655. var format = (Object.freeze || Object)({
  15656. addCommas: addCommas,
  15657. toCamelCase: toCamelCase,
  15658. normalizeCssArray: normalizeCssArray$1,
  15659. encodeHTML: encodeHTML,
  15660. formatTpl: formatTpl,
  15661. formatTplSimple: formatTplSimple,
  15662. getTooltipMarker: getTooltipMarker,
  15663. formatTime: formatTime,
  15664. capitalFirst: capitalFirst,
  15665. truncateText: truncateText$1,
  15666. getTextRect: getTextRect
  15667. });
  15668. // Layout helpers for each component positioning
  15669. var each$3 = each$1;
  15670. /**
  15671. * @public
  15672. */
  15673. var LOCATION_PARAMS = [
  15674. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15675. ];
  15676. /**
  15677. * @public
  15678. */
  15679. var HV_NAMES = [
  15680. ['width', 'left', 'right'],
  15681. ['height', 'top', 'bottom']
  15682. ];
  15683. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15684. var x = 0;
  15685. var y = 0;
  15686. if (maxWidth == null) {
  15687. maxWidth = Infinity;
  15688. }
  15689. if (maxHeight == null) {
  15690. maxHeight = Infinity;
  15691. }
  15692. var currentLineMaxSize = 0;
  15693. group.eachChild(function (child, idx) {
  15694. var position = child.position;
  15695. var rect = child.getBoundingRect();
  15696. var nextChild = group.childAt(idx + 1);
  15697. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15698. var nextX;
  15699. var nextY;
  15700. if (orient === 'horizontal') {
  15701. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15702. nextX = x + moveX;
  15703. // Wrap when width exceeds maxWidth or meet a `newline` group
  15704. // FIXME compare before adding gap?
  15705. if (nextX > maxWidth || child.newline) {
  15706. x = 0;
  15707. nextX = moveX;
  15708. y += currentLineMaxSize + gap;
  15709. currentLineMaxSize = rect.height;
  15710. }
  15711. else {
  15712. // FIXME: consider rect.y is not `0`?
  15713. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15714. }
  15715. }
  15716. else {
  15717. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15718. nextY = y + moveY;
  15719. // Wrap when width exceeds maxHeight or meet a `newline` group
  15720. if (nextY > maxHeight || child.newline) {
  15721. x += currentLineMaxSize + gap;
  15722. y = 0;
  15723. nextY = moveY;
  15724. currentLineMaxSize = rect.width;
  15725. }
  15726. else {
  15727. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15728. }
  15729. }
  15730. if (child.newline) {
  15731. return;
  15732. }
  15733. position[0] = x;
  15734. position[1] = y;
  15735. orient === 'horizontal'
  15736. ? (x = nextX + gap)
  15737. : (y = nextY + gap);
  15738. });
  15739. }
  15740. /**
  15741. * VBox or HBox layouting
  15742. * @param {string} orient
  15743. * @param {module:zrender/container/Group} group
  15744. * @param {number} gap
  15745. * @param {number} [width=Infinity]
  15746. * @param {number} [height=Infinity]
  15747. */
  15748. var box = boxLayout;
  15749. /**
  15750. * VBox layouting
  15751. * @param {module:zrender/container/Group} group
  15752. * @param {number} gap
  15753. * @param {number} [width=Infinity]
  15754. * @param {number} [height=Infinity]
  15755. */
  15756. var vbox = curry(boxLayout, 'vertical');
  15757. /**
  15758. * HBox layouting
  15759. * @param {module:zrender/container/Group} group
  15760. * @param {number} gap
  15761. * @param {number} [width=Infinity]
  15762. * @param {number} [height=Infinity]
  15763. */
  15764. var hbox = curry(boxLayout, 'horizontal');
  15765. /**
  15766. * If x or x2 is not specified or 'center' 'left' 'right',
  15767. * the width would be as long as possible.
  15768. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  15769. * the height would be as long as possible.
  15770. *
  15771. * @param {Object} positionInfo
  15772. * @param {number|string} [positionInfo.x]
  15773. * @param {number|string} [positionInfo.y]
  15774. * @param {number|string} [positionInfo.x2]
  15775. * @param {number|string} [positionInfo.y2]
  15776. * @param {Object} containerRect {width, height}
  15777. * @param {string|number} margin
  15778. * @return {Object} {width, height}
  15779. */
  15780. function getAvailableSize(positionInfo, containerRect, margin) {
  15781. var containerWidth = containerRect.width;
  15782. var containerHeight = containerRect.height;
  15783. var x = parsePercent$1(positionInfo.x, containerWidth);
  15784. var y = parsePercent$1(positionInfo.y, containerHeight);
  15785. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  15786. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  15787. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  15788. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  15789. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  15790. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  15791. margin = normalizeCssArray$1(margin || 0);
  15792. return {
  15793. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  15794. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  15795. };
  15796. }
  15797. /**
  15798. * Parse position info.
  15799. *
  15800. * @param {Object} positionInfo
  15801. * @param {number|string} [positionInfo.left]
  15802. * @param {number|string} [positionInfo.top]
  15803. * @param {number|string} [positionInfo.right]
  15804. * @param {number|string} [positionInfo.bottom]
  15805. * @param {number|string} [positionInfo.width]
  15806. * @param {number|string} [positionInfo.height]
  15807. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  15808. * @param {Object} containerRect
  15809. * @param {string|number} [margin]
  15810. *
  15811. * @return {module:zrender/core/BoundingRect}
  15812. */
  15813. function getLayoutRect(
  15814. positionInfo, containerRect, margin
  15815. ) {
  15816. margin = normalizeCssArray$1(margin || 0);
  15817. var containerWidth = containerRect.width;
  15818. var containerHeight = containerRect.height;
  15819. var left = parsePercent$1(positionInfo.left, containerWidth);
  15820. var top = parsePercent$1(positionInfo.top, containerHeight);
  15821. var right = parsePercent$1(positionInfo.right, containerWidth);
  15822. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15823. var width = parsePercent$1(positionInfo.width, containerWidth);
  15824. var height = parsePercent$1(positionInfo.height, containerHeight);
  15825. var verticalMargin = margin[2] + margin[0];
  15826. var horizontalMargin = margin[1] + margin[3];
  15827. var aspect = positionInfo.aspect;
  15828. // If width is not specified, calculate width from left and right
  15829. if (isNaN(width)) {
  15830. width = containerWidth - right - horizontalMargin - left;
  15831. }
  15832. if (isNaN(height)) {
  15833. height = containerHeight - bottom - verticalMargin - top;
  15834. }
  15835. if (aspect != null) {
  15836. // If width and height are not given
  15837. // 1. Graph should not exceeds the container
  15838. // 2. Aspect must be keeped
  15839. // 3. Graph should take the space as more as possible
  15840. // FIXME
  15841. // Margin is not considered, because there is no case that both
  15842. // using margin and aspect so far.
  15843. if (isNaN(width) && isNaN(height)) {
  15844. if (aspect > containerWidth / containerHeight) {
  15845. width = containerWidth * 0.8;
  15846. }
  15847. else {
  15848. height = containerHeight * 0.8;
  15849. }
  15850. }
  15851. // Calculate width or height with given aspect
  15852. if (isNaN(width)) {
  15853. width = aspect * height;
  15854. }
  15855. if (isNaN(height)) {
  15856. height = width / aspect;
  15857. }
  15858. }
  15859. // If left is not specified, calculate left from right and width
  15860. if (isNaN(left)) {
  15861. left = containerWidth - right - width - horizontalMargin;
  15862. }
  15863. if (isNaN(top)) {
  15864. top = containerHeight - bottom - height - verticalMargin;
  15865. }
  15866. // Align left and top
  15867. switch (positionInfo.left || positionInfo.right) {
  15868. case 'center':
  15869. left = containerWidth / 2 - width / 2 - margin[3];
  15870. break;
  15871. case 'right':
  15872. left = containerWidth - width - horizontalMargin;
  15873. break;
  15874. }
  15875. switch (positionInfo.top || positionInfo.bottom) {
  15876. case 'middle':
  15877. case 'center':
  15878. top = containerHeight / 2 - height / 2 - margin[0];
  15879. break;
  15880. case 'bottom':
  15881. top = containerHeight - height - verticalMargin;
  15882. break;
  15883. }
  15884. // If something is wrong and left, top, width, height are calculated as NaN
  15885. left = left || 0;
  15886. top = top || 0;
  15887. if (isNaN(width)) {
  15888. // Width may be NaN if only one value is given except width
  15889. width = containerWidth - horizontalMargin - left - (right || 0);
  15890. }
  15891. if (isNaN(height)) {
  15892. // Height may be NaN if only one value is given except height
  15893. height = containerHeight - verticalMargin - top - (bottom || 0);
  15894. }
  15895. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15896. rect.margin = margin;
  15897. return rect;
  15898. }
  15899. /**
  15900. * Position a zr element in viewport
  15901. * Group position is specified by either
  15902. * {left, top}, {right, bottom}
  15903. * If all properties exists, right and bottom will be igonred.
  15904. *
  15905. * Logic:
  15906. * 1. Scale (against origin point in parent coord)
  15907. * 2. Rotate (against origin point in parent coord)
  15908. * 3. Traslate (with el.position by this method)
  15909. * So this method only fixes the last step 'Traslate', which does not affect
  15910. * scaling and rotating.
  15911. *
  15912. * If be called repeatly with the same input el, the same result will be gotten.
  15913. *
  15914. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  15915. * @param {Object} positionInfo
  15916. * @param {number|string} [positionInfo.left]
  15917. * @param {number|string} [positionInfo.top]
  15918. * @param {number|string} [positionInfo.right]
  15919. * @param {number|string} [positionInfo.bottom]
  15920. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  15921. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  15922. * @param {Object} containerRect
  15923. * @param {string|number} margin
  15924. * @param {Object} [opt]
  15925. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  15926. * @param {Array.<number>} [opt.boundingMode='all']
  15927. * Specify how to calculate boundingRect when locating.
  15928. * 'all': Position the boundingRect that is transformed and uioned
  15929. * both itself and its descendants.
  15930. * This mode simplies confine the elements in the bounding
  15931. * of their container (e.g., using 'right: 0').
  15932. * 'raw': Position the boundingRect that is not transformed and only itself.
  15933. * This mode is useful when you want a element can overflow its
  15934. * container. (Consider a rotated circle needs to be located in a corner.)
  15935. * In this mode positionInfo.width/height can only be number.
  15936. */
  15937. function positionElement(el, positionInfo, containerRect, margin, opt) {
  15938. var h = !opt || !opt.hv || opt.hv[0];
  15939. var v = !opt || !opt.hv || opt.hv[1];
  15940. var boundingMode = opt && opt.boundingMode || 'all';
  15941. if (!h && !v) {
  15942. return;
  15943. }
  15944. var rect;
  15945. if (boundingMode === 'raw') {
  15946. rect = el.type === 'group'
  15947. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  15948. : el.getBoundingRect();
  15949. }
  15950. else {
  15951. rect = el.getBoundingRect();
  15952. if (el.needLocalTransform()) {
  15953. var transform = el.getLocalTransform();
  15954. // Notice: raw rect may be inner object of el,
  15955. // which should not be modified.
  15956. rect = rect.clone();
  15957. rect.applyTransform(transform);
  15958. }
  15959. }
  15960. // The real width and height can not be specified but calculated by the given el.
  15961. positionInfo = getLayoutRect(
  15962. defaults(
  15963. {width: rect.width, height: rect.height},
  15964. positionInfo
  15965. ),
  15966. containerRect,
  15967. margin
  15968. );
  15969. // Because 'tranlate' is the last step in transform
  15970. // (see zrender/core/Transformable#getLocalTransform),
  15971. // we can just only modify el.position to get final result.
  15972. var elPos = el.position;
  15973. var dx = h ? positionInfo.x - rect.x : 0;
  15974. var dy = v ? positionInfo.y - rect.y : 0;
  15975. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  15976. }
  15977. /**
  15978. * @param {Object} option Contains some of the properties in HV_NAMES.
  15979. * @param {number} hvIdx 0: horizontal; 1: vertical.
  15980. */
  15981. function sizeCalculable(option, hvIdx) {
  15982. return option[HV_NAMES[hvIdx][0]] != null
  15983. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  15984. }
  15985. /**
  15986. * Consider Case:
  15987. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  15988. * through setOption or media query, using normal zrUtil.merge will cause
  15989. * {right: 0} does not take effect.
  15990. *
  15991. * @example
  15992. * ComponentModel.extend({
  15993. * init: function () {
  15994. * ...
  15995. * var inputPositionParams = layout.getLayoutParams(option);
  15996. * this.mergeOption(inputPositionParams);
  15997. * },
  15998. * mergeOption: function (newOption) {
  15999. * newOption && zrUtil.merge(thisOption, newOption, true);
  16000. * layout.mergeLayoutParam(thisOption, newOption);
  16001. * }
  16002. * });
  16003. *
  16004. * @param {Object} targetOption
  16005. * @param {Object} newOption
  16006. * @param {Object|string} [opt]
  16007. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16008. * that width (or height) should not be calculated by left and right (or top and bottom).
  16009. */
  16010. function mergeLayoutParam(targetOption, newOption, opt) {
  16011. !isObject$1(opt) && (opt = {});
  16012. var ignoreSize = opt.ignoreSize;
  16013. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16014. var hResult = merge$$1(HV_NAMES[0], 0);
  16015. var vResult = merge$$1(HV_NAMES[1], 1);
  16016. copy(HV_NAMES[0], targetOption, hResult);
  16017. copy(HV_NAMES[1], targetOption, vResult);
  16018. function merge$$1(names, hvIdx) {
  16019. var newParams = {};
  16020. var newValueCount = 0;
  16021. var merged = {};
  16022. var mergedValueCount = 0;
  16023. var enoughParamNumber = 2;
  16024. each$3(names, function (name) {
  16025. merged[name] = targetOption[name];
  16026. });
  16027. each$3(names, function (name) {
  16028. // Consider case: newOption.width is null, which is
  16029. // set by user for removing width setting.
  16030. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16031. hasValue(newParams, name) && newValueCount++;
  16032. hasValue(merged, name) && mergedValueCount++;
  16033. });
  16034. if (ignoreSize[hvIdx]) {
  16035. // Only one of left/right is premitted to exist.
  16036. if (hasValue(newOption, names[1])) {
  16037. merged[names[2]] = null;
  16038. }
  16039. else if (hasValue(newOption, names[2])) {
  16040. merged[names[1]] = null;
  16041. }
  16042. return merged;
  16043. }
  16044. // Case: newOption: {width: ..., right: ...},
  16045. // or targetOption: {right: ...} and newOption: {width: ...},
  16046. // There is no conflict when merged only has params count
  16047. // little than enoughParamNumber.
  16048. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16049. return merged;
  16050. }
  16051. // Case: newOption: {width: ..., right: ...},
  16052. // Than we can make sure user only want those two, and ignore
  16053. // all origin params in targetOption.
  16054. else if (newValueCount >= enoughParamNumber) {
  16055. return newParams;
  16056. }
  16057. else {
  16058. // Chose another param from targetOption by priority.
  16059. for (var i = 0; i < names.length; i++) {
  16060. var name = names[i];
  16061. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16062. newParams[name] = targetOption[name];
  16063. break;
  16064. }
  16065. }
  16066. return newParams;
  16067. }
  16068. }
  16069. function hasProp(obj, name) {
  16070. return obj.hasOwnProperty(name);
  16071. }
  16072. function hasValue(obj, name) {
  16073. return obj[name] != null && obj[name] !== 'auto';
  16074. }
  16075. function copy(names, target, source) {
  16076. each$3(names, function (name) {
  16077. target[name] = source[name];
  16078. });
  16079. }
  16080. }
  16081. /**
  16082. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16083. * @param {Object} source
  16084. * @return {Object} Result contains those props.
  16085. */
  16086. function getLayoutParams(source) {
  16087. return copyLayoutParams({}, source);
  16088. }
  16089. /**
  16090. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16091. * @param {Object} source
  16092. * @return {Object} Result contains those props.
  16093. */
  16094. function copyLayoutParams(target, source) {
  16095. source && target && each$3(LOCATION_PARAMS, function (name) {
  16096. source.hasOwnProperty(name) && (target[name] = source[name]);
  16097. });
  16098. return target;
  16099. }
  16100. var boxLayoutMixin = {
  16101. getBoxLayoutParams: function () {
  16102. return {
  16103. left: this.get('left'),
  16104. top: this.get('top'),
  16105. right: this.get('right'),
  16106. bottom: this.get('bottom'),
  16107. width: this.get('width'),
  16108. height: this.get('height')
  16109. };
  16110. }
  16111. };
  16112. /**
  16113. * Component model
  16114. *
  16115. * @module echarts/model/Component
  16116. */
  16117. var inner$1 = makeInner();
  16118. /**
  16119. * @alias module:echarts/model/Component
  16120. * @constructor
  16121. * @param {Object} option
  16122. * @param {module:echarts/model/Model} parentModel
  16123. * @param {module:echarts/model/Model} ecModel
  16124. */
  16125. var ComponentModel = Model.extend({
  16126. type: 'component',
  16127. /**
  16128. * @readOnly
  16129. * @type {string}
  16130. */
  16131. id: '',
  16132. /**
  16133. * Because simplified concept is probably better, series.name (or component.name)
  16134. * has been having too many resposibilities:
  16135. * (1) Generating id (which requires name in option should not be modified).
  16136. * (2) As an index to mapping series when merging option or calling API (a name
  16137. * can refer to more then one components, which is convinient is some case).
  16138. * (3) Display.
  16139. * @readOnly
  16140. */
  16141. name: '',
  16142. /**
  16143. * @readOnly
  16144. * @type {string}
  16145. */
  16146. mainType: '',
  16147. /**
  16148. * @readOnly
  16149. * @type {string}
  16150. */
  16151. subType: '',
  16152. /**
  16153. * @readOnly
  16154. * @type {number}
  16155. */
  16156. componentIndex: 0,
  16157. /**
  16158. * @type {Object}
  16159. * @protected
  16160. */
  16161. defaultOption: null,
  16162. /**
  16163. * @type {module:echarts/model/Global}
  16164. * @readOnly
  16165. */
  16166. ecModel: null,
  16167. /**
  16168. * key: componentType
  16169. * value: Component model list, can not be null.
  16170. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16171. * @readOnly
  16172. */
  16173. dependentModels: [],
  16174. /**
  16175. * @type {string}
  16176. * @readOnly
  16177. */
  16178. uid: null,
  16179. /**
  16180. * Support merge layout params.
  16181. * Only support 'box' now (left/right/top/bottom/width/height).
  16182. * @type {string|Object} Object can be {ignoreSize: true}
  16183. * @readOnly
  16184. */
  16185. layoutMode: null,
  16186. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16187. Model.call(this, option, parentModel, ecModel, extraOpt);
  16188. this.uid = getUID('ec_cpt_model');
  16189. },
  16190. init: function (option, parentModel, ecModel, extraOpt) {
  16191. this.mergeDefaultAndTheme(option, ecModel);
  16192. },
  16193. mergeDefaultAndTheme: function (option, ecModel) {
  16194. var layoutMode = this.layoutMode;
  16195. var inputPositionParams = layoutMode
  16196. ? getLayoutParams(option) : {};
  16197. var themeModel = ecModel.getTheme();
  16198. merge(option, themeModel.get(this.mainType));
  16199. merge(option, this.getDefaultOption());
  16200. if (layoutMode) {
  16201. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16202. }
  16203. },
  16204. mergeOption: function (option, extraOpt) {
  16205. merge(this.option, option, true);
  16206. var layoutMode = this.layoutMode;
  16207. if (layoutMode) {
  16208. mergeLayoutParam(this.option, option, layoutMode);
  16209. }
  16210. },
  16211. // Hooker after init or mergeOption
  16212. optionUpdated: function (newCptOption, isInit) {},
  16213. getDefaultOption: function () {
  16214. var fields = inner$1(this);
  16215. if (!fields.defaultOption) {
  16216. var optList = [];
  16217. var Class = this.constructor;
  16218. while (Class) {
  16219. var opt = Class.prototype.defaultOption;
  16220. opt && optList.push(opt);
  16221. Class = Class.superClass;
  16222. }
  16223. var defaultOption = {};
  16224. for (var i = optList.length - 1; i >= 0; i--) {
  16225. defaultOption = merge(defaultOption, optList[i], true);
  16226. }
  16227. fields.defaultOption = defaultOption;
  16228. }
  16229. return fields.defaultOption;
  16230. },
  16231. getReferringComponents: function (mainType) {
  16232. return this.ecModel.queryComponents({
  16233. mainType: mainType,
  16234. index: this.get(mainType + 'Index', true),
  16235. id: this.get(mainType + 'Id', true)
  16236. });
  16237. }
  16238. });
  16239. // Reset ComponentModel.extend, add preConstruct.
  16240. // clazzUtil.enableClassExtend(
  16241. // ComponentModel,
  16242. // function (option, parentModel, ecModel, extraOpt) {
  16243. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16244. // zrUtil.extend(this, extraOpt);
  16245. // this.uid = componentUtil.getUID('componentModel');
  16246. // // this.setReadOnly([
  16247. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16248. // // 'dependentModels', 'componentIndex'
  16249. // // ]);
  16250. // }
  16251. // );
  16252. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16253. enableClassManagement(
  16254. ComponentModel, {registerWhenExtend: true}
  16255. );
  16256. enableSubTypeDefaulter(ComponentModel);
  16257. // Add capability of ComponentModel.topologicalTravel.
  16258. enableTopologicalTravel(ComponentModel, getDependencies);
  16259. function getDependencies(componentType) {
  16260. var deps = [];
  16261. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16262. deps = deps.concat(Clazz.prototype.dependencies || []);
  16263. });
  16264. // Ensure main type.
  16265. deps = map(deps, function (type) {
  16266. return parseClassType$1(type).main;
  16267. });
  16268. // Hack dataset for convenience.
  16269. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16270. deps.unshift('dataset');
  16271. }
  16272. return deps;
  16273. }
  16274. mixin(ComponentModel, boxLayoutMixin);
  16275. var platform = '';
  16276. // Navigator not exists in node
  16277. if (typeof navigator !== 'undefined') {
  16278. platform = navigator.platform || '';
  16279. }
  16280. var globalDefault = {
  16281. // backgroundColor: 'rgba(0,0,0,0)',
  16282. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16283. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16284. // Light colors:
  16285. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16286. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16287. // Dark colors:
  16288. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16289. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16290. // If xAxis and yAxis declared, grid is created by default.
  16291. // grid: {},
  16292. textStyle: {
  16293. // color: '#000',
  16294. // decoration: 'none',
  16295. // PENDING
  16296. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16297. // fontFamily: 'Arial, Verdana, sans-serif',
  16298. fontSize: 12,
  16299. fontStyle: 'normal',
  16300. fontWeight: 'normal'
  16301. },
  16302. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16303. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16304. // Default is source-over
  16305. blendMode: null,
  16306. animation: 'auto',
  16307. animationDuration: 1000,
  16308. animationDurationUpdate: 300,
  16309. animationEasing: 'exponentialOut',
  16310. animationEasingUpdate: 'cubicOut',
  16311. animationThreshold: 2000,
  16312. // Configuration for progressive/incremental rendering
  16313. progressiveThreshold: 3000,
  16314. progressive: 400,
  16315. // Threshold of if use single hover layer to optimize.
  16316. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16317. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16318. // which is unexpected.
  16319. // see example <echarts/test/heatmap-large.html>.
  16320. hoverLayerThreshold: 3000,
  16321. // See: module:echarts/scale/Time
  16322. useUTC: false
  16323. };
  16324. var inner$2 = makeInner();
  16325. function getNearestColorPalette(colors, requestColorNum) {
  16326. var paletteNum = colors.length;
  16327. // TODO colors must be in order
  16328. for (var i = 0; i < paletteNum; i++) {
  16329. if (colors[i].length > requestColorNum) {
  16330. return colors[i];
  16331. }
  16332. }
  16333. return colors[paletteNum - 1];
  16334. }
  16335. var colorPaletteMixin = {
  16336. clearColorPalette: function () {
  16337. inner$2(this).colorIdx = 0;
  16338. inner$2(this).colorNameMap = {};
  16339. },
  16340. /**
  16341. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  16342. * twise with the same parameters will get different result.
  16343. * @param {Object} [scope=this]
  16344. * @param {Object} [requestColorNum]
  16345. * @return {string} color string.
  16346. */
  16347. getColorFromPalette: function (name, scope, requestColorNum) {
  16348. scope = scope || this;
  16349. var scopeFields = inner$2(scope);
  16350. var colorIdx = scopeFields.colorIdx || 0;
  16351. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  16352. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16353. if (colorNameMap.hasOwnProperty(name)) {
  16354. return colorNameMap[name];
  16355. }
  16356. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16357. var layeredColorPalette = this.get('colorLayer', true);
  16358. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  16359. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  16360. // In case can't find in layered color palette.
  16361. colorPalette = colorPalette || defaultColorPalette;
  16362. if (!colorPalette || !colorPalette.length) {
  16363. return;
  16364. }
  16365. var color = colorPalette[colorIdx];
  16366. if (name) {
  16367. colorNameMap[name] = color;
  16368. }
  16369. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16370. return color;
  16371. }
  16372. };
  16373. /**
  16374. * Helper for model references.
  16375. * There are many manners to refer axis/coordSys.
  16376. */
  16377. // TODO
  16378. // merge relevant logic to this file?
  16379. // check: "modelHelper" of tooltip and "BrushTargetManager".
  16380. /**
  16381. * @return {Object} For example:
  16382. * {
  16383. * coordSysName: 'cartesian2d',
  16384. * coordSysDims: ['x', 'y', ...],
  16385. * axisMap: HashMap({
  16386. * x: xAxisModel,
  16387. * y: yAxisModel
  16388. * }),
  16389. * categoryAxisMap: HashMap({
  16390. * x: xAxisModel,
  16391. * y: undefined
  16392. * }),
  16393. * // It also indicate that whether there is category axis.
  16394. * firstCategoryDimIndex: 1,
  16395. * // To replace user specified encode.
  16396. * }
  16397. */
  16398. function getCoordSysDefineBySeries(seriesModel) {
  16399. var coordSysName = seriesModel.get('coordinateSystem');
  16400. var result = {
  16401. coordSysName: coordSysName,
  16402. coordSysDims: [],
  16403. axisMap: createHashMap(),
  16404. categoryAxisMap: createHashMap()
  16405. };
  16406. var fetch = fetchers[coordSysName];
  16407. if (fetch) {
  16408. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  16409. return result;
  16410. }
  16411. }
  16412. var fetchers = {
  16413. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  16414. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  16415. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  16416. if (__DEV__) {
  16417. if (!xAxisModel) {
  16418. throw new Error('xAxis "' + retrieve(
  16419. seriesModel.get('xAxisIndex'),
  16420. seriesModel.get('xAxisId'),
  16421. 0
  16422. ) + '" not found');
  16423. }
  16424. if (!yAxisModel) {
  16425. throw new Error('yAxis "' + retrieve(
  16426. seriesModel.get('xAxisIndex'),
  16427. seriesModel.get('yAxisId'),
  16428. 0
  16429. ) + '" not found');
  16430. }
  16431. }
  16432. result.coordSysDims = ['x', 'y'];
  16433. axisMap.set('x', xAxisModel);
  16434. axisMap.set('y', yAxisModel);
  16435. if (isCategory(xAxisModel)) {
  16436. categoryAxisMap.set('x', xAxisModel);
  16437. result.firstCategoryDimIndex = 0;
  16438. }
  16439. if (isCategory(yAxisModel)) {
  16440. categoryAxisMap.set('y', yAxisModel);
  16441. result.firstCategoryDimIndex = 1;
  16442. }
  16443. },
  16444. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  16445. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  16446. if (__DEV__) {
  16447. if (!singleAxisModel) {
  16448. throw new Error('singleAxis should be specified.');
  16449. }
  16450. }
  16451. result.coordSysDims = ['single'];
  16452. axisMap.set('single', singleAxisModel);
  16453. if (isCategory(singleAxisModel)) {
  16454. categoryAxisMap.set('single', singleAxisModel);
  16455. result.firstCategoryDimIndex = 0;
  16456. }
  16457. },
  16458. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  16459. var polarModel = seriesModel.getReferringComponents('polar')[0];
  16460. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  16461. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  16462. if (__DEV__) {
  16463. if (!angleAxisModel) {
  16464. throw new Error('angleAxis option not found');
  16465. }
  16466. if (!radiusAxisModel) {
  16467. throw new Error('radiusAxis option not found');
  16468. }
  16469. }
  16470. result.coordSysDims = ['radius', 'angle'];
  16471. axisMap.set('radius', radiusAxisModel);
  16472. axisMap.set('angle', angleAxisModel);
  16473. if (isCategory(radiusAxisModel)) {
  16474. categoryAxisMap.set('radius', radiusAxisModel);
  16475. result.firstCategoryDimIndex = 0;
  16476. }
  16477. if (isCategory(angleAxisModel)) {
  16478. categoryAxisMap.set('angle', angleAxisModel);
  16479. result.firstCategoryDimIndex = 1;
  16480. }
  16481. },
  16482. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  16483. result.coordSysDims = ['lng', 'lat'];
  16484. },
  16485. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  16486. var ecModel = seriesModel.ecModel;
  16487. var parallelModel = ecModel.getComponent(
  16488. 'parallel', seriesModel.get('parallelIndex')
  16489. );
  16490. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  16491. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  16492. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  16493. var axisDim = coordSysDims[index];
  16494. axisMap.set(axisDim, axisModel);
  16495. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  16496. categoryAxisMap.set(axisDim, axisModel);
  16497. result.firstCategoryDimIndex = index;
  16498. }
  16499. });
  16500. }
  16501. };
  16502. function isCategory(axisModel) {
  16503. return axisModel.get('type') === 'category';
  16504. }
  16505. // Avoid typo.
  16506. var SOURCE_FORMAT_ORIGINAL = 'original';
  16507. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16508. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16509. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16510. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16511. // ??? CHANGE A NAME
  16512. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16513. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16514. var SERIES_LAYOUT_BY_ROW = 'row';
  16515. /**
  16516. * [sourceFormat]
  16517. *
  16518. * + "original":
  16519. * This format is only used in series.data, where
  16520. * itemStyle can be specified in data item.
  16521. *
  16522. * + "arrayRows":
  16523. * [
  16524. * ['product', 'score', 'amount'],
  16525. * ['Matcha Latte', 89.3, 95.8],
  16526. * ['Milk Tea', 92.1, 89.4],
  16527. * ['Cheese Cocoa', 94.4, 91.2],
  16528. * ['Walnut Brownie', 85.4, 76.9]
  16529. * ]
  16530. *
  16531. * + "objectRows":
  16532. * [
  16533. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  16534. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  16535. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  16536. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  16537. * ]
  16538. *
  16539. * + "keyedColumns":
  16540. * {
  16541. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  16542. * 'count': [823, 235, 1042, 988],
  16543. * 'score': [95.8, 81.4, 91.2, 76.9]
  16544. * }
  16545. *
  16546. * + "typedArray"
  16547. *
  16548. * + "unknown"
  16549. */
  16550. /**
  16551. * @constructor
  16552. * @param {Object} fields
  16553. * @param {string} fields.sourceFormat
  16554. * @param {Array|Object} fields.fromDataset
  16555. * @param {Array|Object} [fields.data]
  16556. * @param {string} [seriesLayoutBy='column']
  16557. * @param {Array.<Object|string>} [dimensionsDefine]
  16558. * @param {Objet|HashMap} [encodeDefine]
  16559. * @param {number} [startIndex=0]
  16560. * @param {number} [dimensionsDetectCount]
  16561. */
  16562. function Source(fields) {
  16563. /**
  16564. * @type {boolean}
  16565. */
  16566. this.fromDataset = fields.fromDataset;
  16567. /**
  16568. * Not null/undefined.
  16569. * @type {Array|Object}
  16570. */
  16571. this.data = fields.data || (
  16572. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  16573. );
  16574. /**
  16575. * See also "detectSourceFormat".
  16576. * Not null/undefined.
  16577. * @type {string}
  16578. */
  16579. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  16580. /**
  16581. * 'row' or 'column'
  16582. * Not null/undefined.
  16583. * @type {string} seriesLayoutBy
  16584. */
  16585. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  16586. /**
  16587. * dimensions definition in option.
  16588. * can be null/undefined.
  16589. * @type {Array.<Object|string>}
  16590. */
  16591. this.dimensionsDefine = fields.dimensionsDefine;
  16592. /**
  16593. * encode definition in option.
  16594. * can be null/undefined.
  16595. * @type {Objet|HashMap}
  16596. */
  16597. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  16598. /**
  16599. * Not null/undefined, uint.
  16600. * @type {number}
  16601. */
  16602. this.startIndex = fields.startIndex || 0;
  16603. /**
  16604. * Can be null/undefined (when unknown), uint.
  16605. * @type {number}
  16606. */
  16607. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  16608. }
  16609. /**
  16610. * Wrap original series data for some compatibility cases.
  16611. */
  16612. Source.seriesDataToSource = function (data) {
  16613. return new Source({
  16614. data: data,
  16615. sourceFormat: isTypedArray(data)
  16616. ? SOURCE_FORMAT_TYPED_ARRAY
  16617. : SOURCE_FORMAT_ORIGINAL,
  16618. fromDataset: false
  16619. });
  16620. };
  16621. enableClassCheck(Source);
  16622. var inner$3 = makeInner();
  16623. /**
  16624. * @see {module:echarts/data/Source}
  16625. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  16626. * @return {string} sourceFormat
  16627. */
  16628. function detectSourceFormat(datasetModel) {
  16629. var data = datasetModel.option.source;
  16630. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  16631. if (isTypedArray(data)) {
  16632. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  16633. }
  16634. else if (isArray(data)) {
  16635. // FIXME Whether tolerate null in top level array?
  16636. for (var i = 0, len = data.length; i < len; i++) {
  16637. var item = data[i];
  16638. if (item == null) {
  16639. continue;
  16640. }
  16641. else if (isArray(item)) {
  16642. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  16643. break;
  16644. }
  16645. else if (isObject$1(item)) {
  16646. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  16647. break;
  16648. }
  16649. }
  16650. }
  16651. else if (isObject$1(data)) {
  16652. for (var key in data) {
  16653. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  16654. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  16655. break;
  16656. }
  16657. }
  16658. }
  16659. else if (data != null) {
  16660. throw new Error('Invalid data');
  16661. }
  16662. inner$3(datasetModel).sourceFormat = sourceFormat;
  16663. }
  16664. /**
  16665. * [Scenarios]:
  16666. * (1) Provide source data directly:
  16667. * series: {
  16668. * encode: {...},
  16669. * dimensions: [...]
  16670. * seriesLayoutBy: 'row',
  16671. * data: [[...]]
  16672. * }
  16673. * (2) Refer to datasetModel.
  16674. * series: [{
  16675. * encode: {...}
  16676. * // Ignore datasetIndex means `datasetIndex: 0`
  16677. * // and the dimensions defination in dataset is used
  16678. * }, {
  16679. * encode: {...},
  16680. * seriesLayoutBy: 'column',
  16681. * datasetIndex: 1
  16682. * }]
  16683. *
  16684. * Get data from series itself or datset.
  16685. * @return {module:echarts/data/Source} source
  16686. */
  16687. function getSource(seriesModel) {
  16688. return inner$3(seriesModel).source;
  16689. }
  16690. /**
  16691. * MUST be called before mergeOption of all series.
  16692. * @param {module:echarts/model/Global} ecModel
  16693. */
  16694. function resetSourceDefaulter(ecModel) {
  16695. // `datasetMap` is used to make default encode.
  16696. inner$3(ecModel).datasetMap = createHashMap();
  16697. }
  16698. /**
  16699. * [Caution]:
  16700. * MUST be called after series option merged and
  16701. * before "series.getInitailData()" called.
  16702. *
  16703. * [The rule of making default encode]:
  16704. * Category axis (if exists) alway map to the first dimension.
  16705. * Each other axis occupies a subsequent dimension.
  16706. *
  16707. * [Why make default encode]:
  16708. * Simplify the typing of encode in option, avoiding the case like that:
  16709. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  16710. * where the "y" have to be manually typed as "1, 2, 3, ...".
  16711. *
  16712. * @param {module:echarts/model/Series} seriesModel
  16713. */
  16714. function prepareSource(seriesModel) {
  16715. var seriesOption = seriesModel.option;
  16716. var data = seriesOption.data;
  16717. var sourceFormat = isTypedArray(data)
  16718. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  16719. var fromDataset = false;
  16720. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  16721. var sourceHeader = seriesOption.sourceHeader;
  16722. var dimensionsDefine = seriesOption.dimensions;
  16723. var datasetModel = getDatasetModel(seriesModel);
  16724. if (datasetModel) {
  16725. var datasetOption = datasetModel.option;
  16726. data = datasetOption.source;
  16727. sourceFormat = inner$3(datasetModel).sourceFormat;
  16728. fromDataset = true;
  16729. // These settings from series has higher priority.
  16730. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  16731. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  16732. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  16733. }
  16734. var completeResult = completeBySourceData(
  16735. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  16736. );
  16737. // Note: dataset option does not have `encode`.
  16738. var encodeDefine = seriesOption.encode;
  16739. if (!encodeDefine && datasetModel) {
  16740. encodeDefine = makeDefaultEncode(
  16741. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16742. );
  16743. }
  16744. inner$3(seriesModel).source = new Source({
  16745. data: data,
  16746. fromDataset: fromDataset,
  16747. seriesLayoutBy: seriesLayoutBy,
  16748. sourceFormat: sourceFormat,
  16749. dimensionsDefine: completeResult.dimensionsDefine,
  16750. startIndex: completeResult.startIndex,
  16751. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  16752. encodeDefine: encodeDefine
  16753. });
  16754. }
  16755. // return {startIndex, dimensionsDefine, dimensionsCount}
  16756. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  16757. if (!data) {
  16758. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  16759. }
  16760. var dimensionsDetectCount;
  16761. var startIndex;
  16762. var findPotentialName;
  16763. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16764. // Rule: Most of the first line are string: it is header.
  16765. // Caution: consider a line with 5 string and 1 number,
  16766. // it still can not be sure it is a head, because the
  16767. // 5 string may be 5 values of category columns.
  16768. if (sourceHeader === 'auto' || sourceHeader == null) {
  16769. arrayRowsTravelFirst(function (val) {
  16770. // '-' is regarded as null/undefined.
  16771. if (val != null && val !== '-') {
  16772. if (isString(val)) {
  16773. startIndex == null && (startIndex = 1);
  16774. }
  16775. else {
  16776. startIndex = 0;
  16777. }
  16778. }
  16779. // 10 is an experience number, avoid long loop.
  16780. }, seriesLayoutBy, data, 10);
  16781. }
  16782. else {
  16783. startIndex = sourceHeader ? 1 : 0;
  16784. }
  16785. if (!dimensionsDefine && startIndex === 1) {
  16786. dimensionsDefine = [];
  16787. arrayRowsTravelFirst(function (val, index) {
  16788. dimensionsDefine[index] = val != null ? val : '';
  16789. }, seriesLayoutBy, data);
  16790. }
  16791. dimensionsDetectCount = dimensionsDefine
  16792. ? dimensionsDefine.length
  16793. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  16794. ? data.length
  16795. : data[0]
  16796. ? data[0].length
  16797. : null;
  16798. }
  16799. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16800. if (!dimensionsDefine) {
  16801. dimensionsDefine = objectRowsCollectDimensions(data);
  16802. findPotentialName = true;
  16803. }
  16804. }
  16805. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16806. if (!dimensionsDefine) {
  16807. dimensionsDefine = [];
  16808. findPotentialName = true;
  16809. each$1(data, function (colArr, key) {
  16810. dimensionsDefine.push(key);
  16811. });
  16812. }
  16813. }
  16814. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16815. var value0 = getDataItemValue(data[0]);
  16816. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  16817. }
  16818. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  16819. if (__DEV__) {
  16820. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  16821. }
  16822. }
  16823. var potentialNameDimIndex;
  16824. if (findPotentialName) {
  16825. each$1(dimensionsDefine, function (dim, idx) {
  16826. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  16827. potentialNameDimIndex = idx;
  16828. }
  16829. });
  16830. }
  16831. return {
  16832. startIndex: startIndex,
  16833. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  16834. dimensionsDetectCount: dimensionsDetectCount,
  16835. potentialNameDimIndex: potentialNameDimIndex
  16836. // TODO: potentialIdDimIdx
  16837. };
  16838. }
  16839. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  16840. // which is reasonable. But dimension name is duplicated.
  16841. // Returns undefined or an array contains only object without null/undefiend or string.
  16842. function normalizeDimensionsDefine(dimensionsDefine) {
  16843. if (!dimensionsDefine) {
  16844. // The meaning of null/undefined is different from empty array.
  16845. return;
  16846. }
  16847. var nameMap = createHashMap();
  16848. return map(dimensionsDefine, function (item, index) {
  16849. item = extend({}, isObject$1(item) ? item : {name: item});
  16850. // User can set null in dimensions.
  16851. // We dont auto specify name, othewise a given name may
  16852. // cause it be refered unexpectedly.
  16853. if (item.name == null) {
  16854. return item;
  16855. }
  16856. // Also consider number form like 2012.
  16857. item.name += '';
  16858. // User may also specify displayName.
  16859. // displayName will always exists except user not
  16860. // specified or dim name is not specified or detected.
  16861. // (A auto generated dim name will not be used as
  16862. // displayName).
  16863. if (item.displayName == null) {
  16864. item.displayName = item.name;
  16865. }
  16866. var exist = nameMap.get(item.name);
  16867. if (!exist) {
  16868. nameMap.set(item.name, {count: 1});
  16869. }
  16870. else {
  16871. item.name += '-' + exist.count++;
  16872. }
  16873. return item;
  16874. });
  16875. }
  16876. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  16877. maxLoop == null && (maxLoop = Infinity);
  16878. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16879. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16880. cb(data[i] ? data[i][0] : null, i);
  16881. }
  16882. }
  16883. else {
  16884. var value0 = data[0] || [];
  16885. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  16886. cb(value0[i], i);
  16887. }
  16888. }
  16889. }
  16890. function objectRowsCollectDimensions(data) {
  16891. var firstIndex = 0;
  16892. var obj;
  16893. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  16894. if (obj) {
  16895. var dimensions = [];
  16896. each$1(obj, function (value, key) {
  16897. dimensions.push(key);
  16898. });
  16899. return dimensions;
  16900. }
  16901. }
  16902. // ??? TODO merge to completedimensions, where also has
  16903. // default encode making logic. And the default rule
  16904. // should depends on series? consider 'map'.
  16905. function makeDefaultEncode(
  16906. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16907. ) {
  16908. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  16909. var encode = {};
  16910. // var encodeTooltip = [];
  16911. // var encodeLabel = [];
  16912. var encodeItemName = [];
  16913. var encodeSeriesName = [];
  16914. var seriesType = seriesModel.subType;
  16915. // ??? TODO refactor: provide by series itself.
  16916. // Consider the case: 'map' series is based on geo coordSys,
  16917. // 'graph', 'heatmap' can be based on cartesian. But can not
  16918. // give default rule simply here.
  16919. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  16920. var cSeriesMap = createHashMap([
  16921. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  16922. ]);
  16923. // Usually in this case series will use the first data
  16924. // dimension as the "value" dimension, or other default
  16925. // processes respectively.
  16926. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  16927. var ecModel = seriesModel.ecModel;
  16928. var datasetMap = inner$3(ecModel).datasetMap;
  16929. var key = datasetModel.uid + '_' + seriesLayoutBy;
  16930. var datasetRecord = datasetMap.get(key)
  16931. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  16932. // TODO
  16933. // Auto detect first time axis and do arrangement.
  16934. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  16935. // In value way.
  16936. if (coordSysDefine.firstCategoryDimIndex == null) {
  16937. var dataDim = datasetRecord.valueWayDim++;
  16938. encode[coordDim] = dataDim;
  16939. // ??? TODO give a better default series name rule?
  16940. // especially when encode x y specified.
  16941. // consider: when mutiple series share one dimension
  16942. // category axis, series name should better use
  16943. // the other dimsion name. On the other hand, use
  16944. // both dimensions name.
  16945. encodeSeriesName.push(dataDim);
  16946. // encodeTooltip.push(dataDim);
  16947. // encodeLabel.push(dataDim);
  16948. }
  16949. // In category way, category axis.
  16950. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  16951. encode[coordDim] = 0;
  16952. encodeItemName.push(0);
  16953. }
  16954. // In category way, non-category axis.
  16955. else {
  16956. var dataDim = datasetRecord.categoryWayDim++;
  16957. encode[coordDim] = dataDim;
  16958. // encodeTooltip.push(dataDim);
  16959. // encodeLabel.push(dataDim);
  16960. encodeSeriesName.push(dataDim);
  16961. }
  16962. });
  16963. }
  16964. // Do not make a complex rule! Hard to code maintain and not necessary.
  16965. // ??? TODO refactor: provide by series itself.
  16966. // [{name: ..., value: ...}, ...] like:
  16967. else if (nSeriesMap.get(seriesType) != null) {
  16968. // Find the first not ordinal. (5 is an experience value)
  16969. var firstNotOrdinal;
  16970. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  16971. if (!doGuessOrdinal(
  16972. data, sourceFormat, seriesLayoutBy,
  16973. completeResult.dimensionsDefine, completeResult.startIndex, i
  16974. )) {
  16975. firstNotOrdinal = i;
  16976. }
  16977. }
  16978. if (firstNotOrdinal != null) {
  16979. encode.value = firstNotOrdinal;
  16980. var nameDimIndex = completeResult.potentialNameDimIndex
  16981. || Math.max(firstNotOrdinal - 1, 0);
  16982. // By default, label use itemName in charts.
  16983. // So we dont set encodeLabel here.
  16984. encodeSeriesName.push(nameDimIndex);
  16985. encodeItemName.push(nameDimIndex);
  16986. // encodeTooltip.push(firstNotOrdinal);
  16987. }
  16988. }
  16989. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  16990. // encodeLabel.length && (encode.label = encodeLabel);
  16991. encodeItemName.length && (encode.itemName = encodeItemName);
  16992. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16993. return encode;
  16994. }
  16995. /**
  16996. * If return null/undefined, indicate that should not use datasetModel.
  16997. */
  16998. function getDatasetModel(seriesModel) {
  16999. var option = seriesModel.option;
  17000. // Caution: consider the scenario:
  17001. // A dataset is declared and a series is not expected to use the dataset,
  17002. // and at the beginning `setOption({series: { noData })` (just prepare other
  17003. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17004. // the user should set an empty array to avoid that dataset is used by default.
  17005. var thisData = option.data;
  17006. if (!thisData) {
  17007. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  17008. }
  17009. }
  17010. /**
  17011. * The rule should not be complex, otherwise user might not
  17012. * be able to known where the data is wrong.
  17013. * The code is ugly, but how to make it neat?
  17014. *
  17015. * @param {module:echars/data/Source} source
  17016. * @param {number} dimIndex
  17017. * @return {boolean} Whether ordinal.
  17018. */
  17019. function guessOrdinal(source, dimIndex) {
  17020. return doGuessOrdinal(
  17021. source.data,
  17022. source.sourceFormat,
  17023. source.seriesLayoutBy,
  17024. source.dimensionsDefine,
  17025. source.startIndex,
  17026. dimIndex
  17027. );
  17028. }
  17029. // dimIndex may be overflow source data.
  17030. function doGuessOrdinal(
  17031. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  17032. ) {
  17033. var result;
  17034. // Experience value.
  17035. var maxLoop = 5;
  17036. if (isTypedArray(data)) {
  17037. return false;
  17038. }
  17039. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17040. // always exists in source.
  17041. var dimName;
  17042. if (dimensionsDefine) {
  17043. dimName = dimensionsDefine[dimIndex];
  17044. dimName = isObject$1(dimName) ? dimName.name : dimName;
  17045. }
  17046. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17047. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17048. var sample = data[dimIndex];
  17049. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17050. if ((result = detectValue(sample[startIndex + i])) != null) {
  17051. return result;
  17052. }
  17053. }
  17054. }
  17055. else {
  17056. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17057. var row = data[startIndex + i];
  17058. if (row && (result = detectValue(row[dimIndex])) != null) {
  17059. return result;
  17060. }
  17061. }
  17062. }
  17063. }
  17064. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17065. if (!dimName) {
  17066. return;
  17067. }
  17068. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17069. var item = data[i];
  17070. if (item && (result = detectValue(item[dimName])) != null) {
  17071. return result;
  17072. }
  17073. }
  17074. }
  17075. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17076. if (!dimName) {
  17077. return;
  17078. }
  17079. var sample = data[dimName];
  17080. if (!sample || isTypedArray(sample)) {
  17081. return false;
  17082. }
  17083. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17084. if ((result = detectValue(sample[i])) != null) {
  17085. return result;
  17086. }
  17087. }
  17088. }
  17089. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17090. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17091. var item = data[i];
  17092. var val = getDataItemValue(item);
  17093. if (!isArray(val)) {
  17094. return false;
  17095. }
  17096. if ((result = detectValue(val[dimIndex])) != null) {
  17097. return result;
  17098. }
  17099. }
  17100. }
  17101. function detectValue(val) {
  17102. // Consider usage convenience, '1', '2' will be treated as "number".
  17103. // `isFinit('')` get `true`.
  17104. if (val != null && isFinite(val) && val !== '') {
  17105. return false;
  17106. }
  17107. else if (isString(val) && val !== '-') {
  17108. return true;
  17109. }
  17110. }
  17111. return false;
  17112. }
  17113. /**
  17114. * ECharts global model
  17115. *
  17116. * @module {echarts/model/Global}
  17117. */
  17118. /**
  17119. * Caution: If the mechanism should be changed some day, these cases
  17120. * should be considered:
  17121. *
  17122. * (1) In `merge option` mode, if using the same option to call `setOption`
  17123. * many times, the result should be the same (try our best to ensure that).
  17124. * (2) In `merge option` mode, if a component has no id/name specified, it
  17125. * will be merged by index, and the result sequence of the components is
  17126. * consistent to the original sequence.
  17127. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17128. * `mergeOption` in module:echarts/model/OptionManager.
  17129. */
  17130. var OPTION_INNER_KEY = '\0_ec_inner';
  17131. /**
  17132. * @alias module:echarts/model/Global
  17133. *
  17134. * @param {Object} option
  17135. * @param {module:echarts/model/Model} parentModel
  17136. * @param {Object} theme
  17137. */
  17138. var GlobalModel = Model.extend({
  17139. constructor: GlobalModel,
  17140. init: function (option, parentModel, theme, optionManager) {
  17141. theme = theme || {};
  17142. this.option = null; // Mark as not initialized.
  17143. /**
  17144. * @type {module:echarts/model/Model}
  17145. * @private
  17146. */
  17147. this._theme = new Model(theme);
  17148. /**
  17149. * @type {module:echarts/model/OptionManager}
  17150. */
  17151. this._optionManager = optionManager;
  17152. },
  17153. setOption: function (option, optionPreprocessorFuncs) {
  17154. assert$1(
  17155. !(OPTION_INNER_KEY in option),
  17156. 'please use chart.getOption()'
  17157. );
  17158. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17159. this.resetOption(null);
  17160. },
  17161. /**
  17162. * @param {string} type null/undefined: reset all.
  17163. * 'recreate': force recreate all.
  17164. * 'timeline': only reset timeline option
  17165. * 'media': only reset media query option
  17166. * @return {boolean} Whether option changed.
  17167. */
  17168. resetOption: function (type) {
  17169. var optionChanged = false;
  17170. var optionManager = this._optionManager;
  17171. if (!type || type === 'recreate') {
  17172. var baseOption = optionManager.mountOption(type === 'recreate');
  17173. if (!this.option || type === 'recreate') {
  17174. initBase.call(this, baseOption);
  17175. }
  17176. else {
  17177. this.restoreData();
  17178. this.mergeOption(baseOption);
  17179. }
  17180. optionChanged = true;
  17181. }
  17182. if (type === 'timeline' || type === 'media') {
  17183. this.restoreData();
  17184. }
  17185. if (!type || type === 'recreate' || type === 'timeline') {
  17186. var timelineOption = optionManager.getTimelineOption(this);
  17187. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17188. }
  17189. if (!type || type === 'recreate' || type === 'media') {
  17190. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17191. if (mediaOptions.length) {
  17192. each$1(mediaOptions, function (mediaOption) {
  17193. this.mergeOption(mediaOption, optionChanged = true);
  17194. }, this);
  17195. }
  17196. }
  17197. return optionChanged;
  17198. },
  17199. /**
  17200. * @protected
  17201. */
  17202. mergeOption: function (newOption) {
  17203. var option = this.option;
  17204. var componentsMap = this._componentsMap;
  17205. var newCptTypes = [];
  17206. resetSourceDefaulter(this);
  17207. // If no component class, merge directly.
  17208. // For example: color, animaiton options, etc.
  17209. each$1(newOption, function (componentOption, mainType) {
  17210. if (componentOption == null) {
  17211. return;
  17212. }
  17213. if (!ComponentModel.hasClass(mainType)) {
  17214. // globalSettingTask.dirty();
  17215. option[mainType] = option[mainType] == null
  17216. ? clone(componentOption)
  17217. : merge(option[mainType], componentOption, true);
  17218. }
  17219. else if (mainType) {
  17220. newCptTypes.push(mainType);
  17221. }
  17222. });
  17223. ComponentModel.topologicalTravel(
  17224. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  17225. );
  17226. function visitComponent(mainType, dependencies) {
  17227. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17228. var mapResult = mappingToExists(
  17229. componentsMap.get(mainType), newCptOptionList
  17230. );
  17231. makeIdAndName(mapResult);
  17232. // Set mainType and complete subType.
  17233. each$1(mapResult, function (item, index) {
  17234. var opt = item.option;
  17235. if (isObject$1(opt)) {
  17236. item.keyInfo.mainType = mainType;
  17237. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17238. }
  17239. });
  17240. var dependentModels = getComponentsByTypes(
  17241. componentsMap, dependencies
  17242. );
  17243. option[mainType] = [];
  17244. componentsMap.set(mainType, []);
  17245. each$1(mapResult, function (resultItem, index) {
  17246. var componentModel = resultItem.exist;
  17247. var newCptOption = resultItem.option;
  17248. assert$1(
  17249. isObject$1(newCptOption) || componentModel,
  17250. 'Empty component definition'
  17251. );
  17252. // Consider where is no new option and should be merged using {},
  17253. // see removeEdgeAndAdd in topologicalTravel and
  17254. // ComponentModel.getAllClassMainTypes.
  17255. if (!newCptOption) {
  17256. componentModel.mergeOption({}, this);
  17257. componentModel.optionUpdated({}, false);
  17258. }
  17259. else {
  17260. var ComponentModelClass = ComponentModel.getClass(
  17261. mainType, resultItem.keyInfo.subType, true
  17262. );
  17263. if (componentModel && componentModel instanceof ComponentModelClass) {
  17264. componentModel.name = resultItem.keyInfo.name;
  17265. // componentModel.settingTask && componentModel.settingTask.dirty();
  17266. componentModel.mergeOption(newCptOption, this);
  17267. componentModel.optionUpdated(newCptOption, false);
  17268. }
  17269. else {
  17270. // PENDING Global as parent ?
  17271. var extraOpt = extend(
  17272. {
  17273. dependentModels: dependentModels,
  17274. componentIndex: index
  17275. },
  17276. resultItem.keyInfo
  17277. );
  17278. componentModel = new ComponentModelClass(
  17279. newCptOption, this, this, extraOpt
  17280. );
  17281. extend(componentModel, extraOpt);
  17282. componentModel.init(newCptOption, this, this, extraOpt);
  17283. // Call optionUpdated after init.
  17284. // newCptOption has been used as componentModel.option
  17285. // and may be merged with theme and default, so pass null
  17286. // to avoid confusion.
  17287. componentModel.optionUpdated(null, true);
  17288. }
  17289. }
  17290. componentsMap.get(mainType)[index] = componentModel;
  17291. option[mainType][index] = componentModel.option;
  17292. }, this);
  17293. // Backup series for filtering.
  17294. if (mainType === 'series') {
  17295. createSeriesIndices(this, componentsMap.get('series'));
  17296. }
  17297. }
  17298. this._seriesIndicesMap = createHashMap(
  17299. this._seriesIndices = this._seriesIndices || []
  17300. );
  17301. },
  17302. /**
  17303. * Get option for output (cloned option and inner info removed)
  17304. * @public
  17305. * @return {Object}
  17306. */
  17307. getOption: function () {
  17308. var option = clone(this.option);
  17309. each$1(option, function (opts, mainType) {
  17310. if (ComponentModel.hasClass(mainType)) {
  17311. var opts = normalizeToArray(opts);
  17312. for (var i = opts.length - 1; i >= 0; i--) {
  17313. // Remove options with inner id.
  17314. if (isIdInner(opts[i])) {
  17315. opts.splice(i, 1);
  17316. }
  17317. }
  17318. option[mainType] = opts;
  17319. }
  17320. });
  17321. delete option[OPTION_INNER_KEY];
  17322. return option;
  17323. },
  17324. /**
  17325. * @return {module:echarts/model/Model}
  17326. */
  17327. getTheme: function () {
  17328. return this._theme;
  17329. },
  17330. /**
  17331. * @param {string} mainType
  17332. * @param {number} [idx=0]
  17333. * @return {module:echarts/model/Component}
  17334. */
  17335. getComponent: function (mainType, idx) {
  17336. var list = this._componentsMap.get(mainType);
  17337. if (list) {
  17338. return list[idx || 0];
  17339. }
  17340. },
  17341. /**
  17342. * If none of index and id and name used, return all components with mainType.
  17343. * @param {Object} condition
  17344. * @param {string} condition.mainType
  17345. * @param {string} [condition.subType] If ignore, only query by mainType
  17346. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17347. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17348. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17349. * @return {Array.<module:echarts/model/Component>}
  17350. */
  17351. queryComponents: function (condition) {
  17352. var mainType = condition.mainType;
  17353. if (!mainType) {
  17354. return [];
  17355. }
  17356. var index = condition.index;
  17357. var id = condition.id;
  17358. var name = condition.name;
  17359. var cpts = this._componentsMap.get(mainType);
  17360. if (!cpts || !cpts.length) {
  17361. return [];
  17362. }
  17363. var result;
  17364. if (index != null) {
  17365. if (!isArray(index)) {
  17366. index = [index];
  17367. }
  17368. result = filter(map(index, function (idx) {
  17369. return cpts[idx];
  17370. }), function (val) {
  17371. return !!val;
  17372. });
  17373. }
  17374. else if (id != null) {
  17375. var isIdArray = isArray(id);
  17376. result = filter(cpts, function (cpt) {
  17377. return (isIdArray && indexOf(id, cpt.id) >= 0)
  17378. || (!isIdArray && cpt.id === id);
  17379. });
  17380. }
  17381. else if (name != null) {
  17382. var isNameArray = isArray(name);
  17383. result = filter(cpts, function (cpt) {
  17384. return (isNameArray && indexOf(name, cpt.name) >= 0)
  17385. || (!isNameArray && cpt.name === name);
  17386. });
  17387. }
  17388. else {
  17389. // Return all components with mainType
  17390. result = cpts.slice();
  17391. }
  17392. return filterBySubType(result, condition);
  17393. },
  17394. /**
  17395. * The interface is different from queryComponents,
  17396. * which is convenient for inner usage.
  17397. *
  17398. * @usage
  17399. * var result = findComponents(
  17400. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17401. * );
  17402. * var result = findComponents(
  17403. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17404. * );
  17405. * var result = findComponents(
  17406. * {mainType: 'series'},
  17407. * function (model, index) {...}
  17408. * );
  17409. * // result like [component0, componnet1, ...]
  17410. *
  17411. * @param {Object} condition
  17412. * @param {string} condition.mainType Mandatory.
  17413. * @param {string} [condition.subType] Optional.
  17414. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17415. * where xxx is mainType.
  17416. * If query attribute is null/undefined or has no index/id/name,
  17417. * do not filtering by query conditions, which is convenient for
  17418. * no-payload situations or when target of action is global.
  17419. * @param {Function} [condition.filter] parameter: component, return boolean.
  17420. * @return {Array.<module:echarts/model/Component>}
  17421. */
  17422. findComponents: function (condition) {
  17423. var query = condition.query;
  17424. var mainType = condition.mainType;
  17425. var queryCond = getQueryCond(query);
  17426. var result = queryCond
  17427. ? this.queryComponents(queryCond)
  17428. : this._componentsMap.get(mainType);
  17429. return doFilter(filterBySubType(result, condition));
  17430. function getQueryCond(q) {
  17431. var indexAttr = mainType + 'Index';
  17432. var idAttr = mainType + 'Id';
  17433. var nameAttr = mainType + 'Name';
  17434. return q && (
  17435. q[indexAttr] != null
  17436. || q[idAttr] != null
  17437. || q[nameAttr] != null
  17438. )
  17439. ? {
  17440. mainType: mainType,
  17441. // subType will be filtered finally.
  17442. index: q[indexAttr],
  17443. id: q[idAttr],
  17444. name: q[nameAttr]
  17445. }
  17446. : null;
  17447. }
  17448. function doFilter(res) {
  17449. return condition.filter
  17450. ? filter(res, condition.filter)
  17451. : res;
  17452. }
  17453. },
  17454. /**
  17455. * @usage
  17456. * eachComponent('legend', function (legendModel, index) {
  17457. * ...
  17458. * });
  17459. * eachComponent(function (componentType, model, index) {
  17460. * // componentType does not include subType
  17461. * // (componentType is 'xxx' but not 'xxx.aa')
  17462. * });
  17463. * eachComponent(
  17464. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17465. * function (model, index) {...}
  17466. * );
  17467. * eachComponent(
  17468. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17469. * function (model, index) {...}
  17470. * );
  17471. *
  17472. * @param {string|Object=} mainType When mainType is object, the definition
  17473. * is the same as the method 'findComponents'.
  17474. * @param {Function} cb
  17475. * @param {*} context
  17476. */
  17477. eachComponent: function (mainType, cb, context) {
  17478. var componentsMap = this._componentsMap;
  17479. if (typeof mainType === 'function') {
  17480. context = cb;
  17481. cb = mainType;
  17482. componentsMap.each(function (components, componentType) {
  17483. each$1(components, function (component, index) {
  17484. cb.call(context, componentType, component, index);
  17485. });
  17486. });
  17487. }
  17488. else if (isString(mainType)) {
  17489. each$1(componentsMap.get(mainType), cb, context);
  17490. }
  17491. else if (isObject$1(mainType)) {
  17492. var queryResult = this.findComponents(mainType);
  17493. each$1(queryResult, cb, context);
  17494. }
  17495. },
  17496. /**
  17497. * @param {string} name
  17498. * @return {Array.<module:echarts/model/Series>}
  17499. */
  17500. getSeriesByName: function (name) {
  17501. var series = this._componentsMap.get('series');
  17502. return filter(series, function (oneSeries) {
  17503. return oneSeries.name === name;
  17504. });
  17505. },
  17506. /**
  17507. * @param {number} seriesIndex
  17508. * @return {module:echarts/model/Series}
  17509. */
  17510. getSeriesByIndex: function (seriesIndex) {
  17511. return this._componentsMap.get('series')[seriesIndex];
  17512. },
  17513. /**
  17514. * Get series list before filtered by type.
  17515. * FIXME: rename to getRawSeriesByType?
  17516. *
  17517. * @param {string} subType
  17518. * @return {Array.<module:echarts/model/Series>}
  17519. */
  17520. getSeriesByType: function (subType) {
  17521. var series = this._componentsMap.get('series');
  17522. return filter(series, function (oneSeries) {
  17523. return oneSeries.subType === subType;
  17524. });
  17525. },
  17526. /**
  17527. * @return {Array.<module:echarts/model/Series>}
  17528. */
  17529. getSeries: function () {
  17530. return this._componentsMap.get('series').slice();
  17531. },
  17532. /**
  17533. * @return {number}
  17534. */
  17535. getSeriesCount: function () {
  17536. return this._componentsMap.get('series').length;
  17537. },
  17538. /**
  17539. * After filtering, series may be different
  17540. * frome raw series.
  17541. *
  17542. * @param {Function} cb
  17543. * @param {*} context
  17544. */
  17545. eachSeries: function (cb, context) {
  17546. assertSeriesInitialized(this);
  17547. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17548. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17549. cb.call(context, series, rawSeriesIndex);
  17550. }, this);
  17551. },
  17552. /**
  17553. * Iterate raw series before filtered.
  17554. *
  17555. * @param {Function} cb
  17556. * @param {*} context
  17557. */
  17558. eachRawSeries: function (cb, context) {
  17559. each$1(this._componentsMap.get('series'), cb, context);
  17560. },
  17561. /**
  17562. * After filtering, series may be different.
  17563. * frome raw series.
  17564. *
  17565. * @parma {string} subType
  17566. * @param {Function} cb
  17567. * @param {*} context
  17568. */
  17569. eachSeriesByType: function (subType, cb, context) {
  17570. assertSeriesInitialized(this);
  17571. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17572. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17573. if (series.subType === subType) {
  17574. cb.call(context, series, rawSeriesIndex);
  17575. }
  17576. }, this);
  17577. },
  17578. /**
  17579. * Iterate raw series before filtered of given type.
  17580. *
  17581. * @parma {string} subType
  17582. * @param {Function} cb
  17583. * @param {*} context
  17584. */
  17585. eachRawSeriesByType: function (subType, cb, context) {
  17586. return each$1(this.getSeriesByType(subType), cb, context);
  17587. },
  17588. /**
  17589. * @param {module:echarts/model/Series} seriesModel
  17590. */
  17591. isSeriesFiltered: function (seriesModel) {
  17592. assertSeriesInitialized(this);
  17593. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17594. },
  17595. /**
  17596. * @return {Array.<number>}
  17597. */
  17598. getCurrentSeriesIndices: function () {
  17599. return (this._seriesIndices || []).slice();
  17600. },
  17601. /**
  17602. * @param {Function} cb
  17603. * @param {*} context
  17604. */
  17605. filterSeries: function (cb, context) {
  17606. assertSeriesInitialized(this);
  17607. var filteredSeries = filter(
  17608. this._componentsMap.get('series'), cb, context
  17609. );
  17610. createSeriesIndices(this, filteredSeries);
  17611. },
  17612. restoreData: function (payload) {
  17613. var componentsMap = this._componentsMap;
  17614. createSeriesIndices(this, componentsMap.get('series'));
  17615. var componentTypes = [];
  17616. componentsMap.each(function (components, componentType) {
  17617. componentTypes.push(componentType);
  17618. });
  17619. ComponentModel.topologicalTravel(
  17620. componentTypes,
  17621. ComponentModel.getAllClassMainTypes(),
  17622. function (componentType, dependencies) {
  17623. each$1(componentsMap.get(componentType), function (component) {
  17624. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  17625. && component.restoreData();
  17626. });
  17627. }
  17628. );
  17629. }
  17630. });
  17631. function isNotTargetSeries(seriesModel, payload) {
  17632. if (payload) {
  17633. var index = payload.seiresIndex;
  17634. var id = payload.seriesId;
  17635. var name = payload.seriesName;
  17636. return (index != null && seriesModel.componentIndex !== index)
  17637. || (id != null && seriesModel.id !== id)
  17638. || (name != null && seriesModel.name !== name);
  17639. }
  17640. }
  17641. /**
  17642. * @inner
  17643. */
  17644. function mergeTheme(option, theme) {
  17645. // PENDING
  17646. // NOT use `colorLayer` in theme if option has `color`
  17647. var notMergeColorLayer = option.color && !option.colorLayer;
  17648. each$1(theme, function (themeItem, name) {
  17649. if (name === 'colorLayer' && notMergeColorLayer) {
  17650. return;
  17651. }
  17652. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  17653. if (!ComponentModel.hasClass(name)) {
  17654. if (typeof themeItem === 'object') {
  17655. option[name] = !option[name]
  17656. ? clone(themeItem)
  17657. : merge(option[name], themeItem, false);
  17658. }
  17659. else {
  17660. if (option[name] == null) {
  17661. option[name] = themeItem;
  17662. }
  17663. }
  17664. }
  17665. });
  17666. }
  17667. function initBase(baseOption) {
  17668. baseOption = baseOption;
  17669. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17670. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17671. this.option = {};
  17672. this.option[OPTION_INNER_KEY] = 1;
  17673. /**
  17674. * Init with series: [], in case of calling findSeries method
  17675. * before series initialized.
  17676. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17677. * @private
  17678. */
  17679. this._componentsMap = createHashMap({series: []});
  17680. /**
  17681. * Mapping between filtered series list and raw series list.
  17682. * key: filtered series indices, value: raw series indices.
  17683. * @type {Array.<nubmer>}
  17684. * @private
  17685. */
  17686. this._seriesIndices;
  17687. this._seriesIndicesMap;
  17688. mergeTheme(baseOption, this._theme.option);
  17689. // TODO Needs clone when merging to the unexisted property
  17690. merge(baseOption, globalDefault, false);
  17691. this.mergeOption(baseOption);
  17692. }
  17693. /**
  17694. * @inner
  17695. * @param {Array.<string>|string} types model types
  17696. * @return {Object} key: {string} type, value: {Array.<Object>} models
  17697. */
  17698. function getComponentsByTypes(componentsMap, types) {
  17699. if (!isArray(types)) {
  17700. types = types ? [types] : [];
  17701. }
  17702. var ret = {};
  17703. each$1(types, function (type) {
  17704. ret[type] = (componentsMap.get(type) || []).slice();
  17705. });
  17706. return ret;
  17707. }
  17708. /**
  17709. * @inner
  17710. */
  17711. function determineSubType(mainType, newCptOption, existComponent) {
  17712. var subType = newCptOption.type
  17713. ? newCptOption.type
  17714. : existComponent
  17715. ? existComponent.subType
  17716. // Use determineSubType only when there is no existComponent.
  17717. : ComponentModel.determineSubType(mainType, newCptOption);
  17718. // tooltip, markline, markpoint may always has no subType
  17719. return subType;
  17720. }
  17721. /**
  17722. * @inner
  17723. */
  17724. function createSeriesIndices(ecModel, seriesModels) {
  17725. ecModel._seriesIndicesMap = createHashMap(
  17726. ecModel._seriesIndices = map(seriesModels, function (series) {
  17727. return series.componentIndex;
  17728. }) || []
  17729. );
  17730. }
  17731. /**
  17732. * @inner
  17733. */
  17734. function filterBySubType(components, condition) {
  17735. // Using hasOwnProperty for restrict. Consider
  17736. // subType is undefined in user payload.
  17737. return condition.hasOwnProperty('subType')
  17738. ? filter(components, function (cpt) {
  17739. return cpt.subType === condition.subType;
  17740. })
  17741. : components;
  17742. }
  17743. /**
  17744. * @inner
  17745. */
  17746. function assertSeriesInitialized(ecModel) {
  17747. // Components that use _seriesIndices should depends on series component,
  17748. // which make sure that their initialization is after series.
  17749. if (__DEV__) {
  17750. if (!ecModel._seriesIndices) {
  17751. throw new Error('Option should contains series.');
  17752. }
  17753. }
  17754. }
  17755. mixin(GlobalModel, colorPaletteMixin);
  17756. var echartsAPIList = [
  17757. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  17758. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  17759. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  17760. ];
  17761. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  17762. function ExtensionAPI(chartInstance) {
  17763. each$1(echartsAPIList, function (name) {
  17764. this[name] = bind(chartInstance[name], chartInstance);
  17765. }, this);
  17766. }
  17767. var coordinateSystemCreators = {};
  17768. function CoordinateSystemManager() {
  17769. this._coordinateSystems = [];
  17770. }
  17771. CoordinateSystemManager.prototype = {
  17772. constructor: CoordinateSystemManager,
  17773. create: function (ecModel, api) {
  17774. var coordinateSystems = [];
  17775. each$1(coordinateSystemCreators, function (creater, type) {
  17776. var list = creater.create(ecModel, api);
  17777. coordinateSystems = coordinateSystems.concat(list || []);
  17778. });
  17779. this._coordinateSystems = coordinateSystems;
  17780. },
  17781. update: function (ecModel, api) {
  17782. each$1(this._coordinateSystems, function (coordSys) {
  17783. coordSys.update && coordSys.update(ecModel, api);
  17784. });
  17785. },
  17786. getCoordinateSystems: function () {
  17787. return this._coordinateSystems.slice();
  17788. }
  17789. };
  17790. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  17791. coordinateSystemCreators[type] = coordinateSystemCreator;
  17792. };
  17793. CoordinateSystemManager.get = function (type) {
  17794. return coordinateSystemCreators[type];
  17795. };
  17796. /**
  17797. * ECharts option manager
  17798. *
  17799. * @module {echarts/model/OptionManager}
  17800. */
  17801. var each$4 = each$1;
  17802. var clone$3 = clone;
  17803. var map$1 = map;
  17804. var merge$1 = merge;
  17805. var QUERY_REG = /^(min|max)?(.+)$/;
  17806. /**
  17807. * TERM EXPLANATIONS:
  17808. *
  17809. * [option]:
  17810. *
  17811. * An object that contains definitions of components. For example:
  17812. * var option = {
  17813. * title: {...},
  17814. * legend: {...},
  17815. * visualMap: {...},
  17816. * series: [
  17817. * {data: [...]},
  17818. * {data: [...]},
  17819. * ...
  17820. * ]
  17821. * };
  17822. *
  17823. * [rawOption]:
  17824. *
  17825. * An object input to echarts.setOption. 'rawOption' may be an
  17826. * 'option', or may be an object contains multi-options. For example:
  17827. * var option = {
  17828. * baseOption: {
  17829. * title: {...},
  17830. * legend: {...},
  17831. * series: [
  17832. * {data: [...]},
  17833. * {data: [...]},
  17834. * ...
  17835. * ]
  17836. * },
  17837. * timeline: {...},
  17838. * options: [
  17839. * {title: {...}, series: {data: [...]}},
  17840. * {title: {...}, series: {data: [...]}},
  17841. * ...
  17842. * ],
  17843. * media: [
  17844. * {
  17845. * query: {maxWidth: 320},
  17846. * option: {series: {x: 20}, visualMap: {show: false}}
  17847. * },
  17848. * {
  17849. * query: {minWidth: 320, maxWidth: 720},
  17850. * option: {series: {x: 500}, visualMap: {show: true}}
  17851. * },
  17852. * {
  17853. * option: {series: {x: 1200}, visualMap: {show: true}}
  17854. * }
  17855. * ]
  17856. * };
  17857. *
  17858. * @alias module:echarts/model/OptionManager
  17859. * @param {module:echarts/ExtensionAPI} api
  17860. */
  17861. function OptionManager(api) {
  17862. /**
  17863. * @private
  17864. * @type {module:echarts/ExtensionAPI}
  17865. */
  17866. this._api = api;
  17867. /**
  17868. * @private
  17869. * @type {Array.<number>}
  17870. */
  17871. this._timelineOptions = [];
  17872. /**
  17873. * @private
  17874. * @type {Array.<Object>}
  17875. */
  17876. this._mediaList = [];
  17877. /**
  17878. * @private
  17879. * @type {Object}
  17880. */
  17881. this._mediaDefault;
  17882. /**
  17883. * -1, means default.
  17884. * empty means no media.
  17885. * @private
  17886. * @type {Array.<number>}
  17887. */
  17888. this._currentMediaIndices = [];
  17889. /**
  17890. * @private
  17891. * @type {Object}
  17892. */
  17893. this._optionBackup;
  17894. /**
  17895. * @private
  17896. * @type {Object}
  17897. */
  17898. this._newBaseOption;
  17899. }
  17900. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17901. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17902. // rawOption cloned and backuped when timeline changed, which does no
  17903. // good to performance. What's more, that both timeline and setOption
  17904. // method supply 'notMerge' brings complex and some problems.
  17905. // Consider this case:
  17906. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17907. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17908. OptionManager.prototype = {
  17909. constructor: OptionManager,
  17910. /**
  17911. * @public
  17912. * @param {Object} rawOption Raw option.
  17913. * @param {module:echarts/model/Global} ecModel
  17914. * @param {Array.<Function>} optionPreprocessorFuncs
  17915. * @return {Object} Init option
  17916. */
  17917. setOption: function (rawOption, optionPreprocessorFuncs) {
  17918. if (rawOption) {
  17919. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17920. each$1(normalizeToArray(rawOption.series), function (series) {
  17921. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17922. });
  17923. }
  17924. // Caution: some series modify option data, if do not clone,
  17925. // it should ensure that the repeat modify correctly
  17926. // (create a new object when modify itself).
  17927. rawOption = clone$3(rawOption, true);
  17928. // FIXME
  17929. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  17930. var oldOptionBackup = this._optionBackup;
  17931. var newParsedOption = parseRawOption.call(
  17932. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  17933. );
  17934. this._newBaseOption = newParsedOption.baseOption;
  17935. // For setOption at second time (using merge mode);
  17936. if (oldOptionBackup) {
  17937. // Only baseOption can be merged.
  17938. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  17939. // For simplicity, timeline options and media options do not support merge,
  17940. // that is, if you `setOption` twice and both has timeline options, the latter
  17941. // timeline opitons will not be merged to the formers, but just substitude them.
  17942. if (newParsedOption.timelineOptions.length) {
  17943. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  17944. }
  17945. if (newParsedOption.mediaList.length) {
  17946. oldOptionBackup.mediaList = newParsedOption.mediaList;
  17947. }
  17948. if (newParsedOption.mediaDefault) {
  17949. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  17950. }
  17951. }
  17952. else {
  17953. this._optionBackup = newParsedOption;
  17954. }
  17955. },
  17956. /**
  17957. * @param {boolean} isRecreate
  17958. * @return {Object}
  17959. */
  17960. mountOption: function (isRecreate) {
  17961. var optionBackup = this._optionBackup;
  17962. // TODO
  17963. // 如果没有reset功能则不clone。
  17964. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  17965. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  17966. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  17967. this._currentMediaIndices = [];
  17968. return clone$3(isRecreate
  17969. // this._optionBackup.baseOption, which is created at the first `setOption`
  17970. // called, and is merged into every new option by inner method `mergeOption`
  17971. // each time `setOption` called, can be only used in `isRecreate`, because
  17972. // its reliability is under suspicion. In other cases option merge is
  17973. // performed by `model.mergeOption`.
  17974. ? optionBackup.baseOption : this._newBaseOption
  17975. );
  17976. },
  17977. /**
  17978. * @param {module:echarts/model/Global} ecModel
  17979. * @return {Object}
  17980. */
  17981. getTimelineOption: function (ecModel) {
  17982. var option;
  17983. var timelineOptions = this._timelineOptions;
  17984. if (timelineOptions.length) {
  17985. // getTimelineOption can only be called after ecModel inited,
  17986. // so we can get currentIndex from timelineModel.
  17987. var timelineModel = ecModel.getComponent('timeline');
  17988. if (timelineModel) {
  17989. option = clone$3(
  17990. timelineOptions[timelineModel.getCurrentIndex()],
  17991. true
  17992. );
  17993. }
  17994. }
  17995. return option;
  17996. },
  17997. /**
  17998. * @param {module:echarts/model/Global} ecModel
  17999. * @return {Array.<Object>}
  18000. */
  18001. getMediaOption: function (ecModel) {
  18002. var ecWidth = this._api.getWidth();
  18003. var ecHeight = this._api.getHeight();
  18004. var mediaList = this._mediaList;
  18005. var mediaDefault = this._mediaDefault;
  18006. var indices = [];
  18007. var result = [];
  18008. // No media defined.
  18009. if (!mediaList.length && !mediaDefault) {
  18010. return result;
  18011. }
  18012. // Multi media may be applied, the latter defined media has higher priority.
  18013. for (var i = 0, len = mediaList.length; i < len; i++) {
  18014. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18015. indices.push(i);
  18016. }
  18017. }
  18018. // FIXME
  18019. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  18020. if (!indices.length && mediaDefault) {
  18021. indices = [-1];
  18022. }
  18023. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18024. result = map$1(indices, function (index) {
  18025. return clone$3(
  18026. index === -1 ? mediaDefault.option : mediaList[index].option
  18027. );
  18028. });
  18029. }
  18030. // Otherwise return nothing.
  18031. this._currentMediaIndices = indices;
  18032. return result;
  18033. }
  18034. };
  18035. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  18036. var timelineOptions = [];
  18037. var mediaList = [];
  18038. var mediaDefault;
  18039. var baseOption;
  18040. // Compatible with ec2.
  18041. var timelineOpt = rawOption.timeline;
  18042. if (rawOption.baseOption) {
  18043. baseOption = rawOption.baseOption;
  18044. }
  18045. // For timeline
  18046. if (timelineOpt || rawOption.options) {
  18047. baseOption = baseOption || {};
  18048. timelineOptions = (rawOption.options || []).slice();
  18049. }
  18050. // For media query
  18051. if (rawOption.media) {
  18052. baseOption = baseOption || {};
  18053. var media = rawOption.media;
  18054. each$4(media, function (singleMedia) {
  18055. if (singleMedia && singleMedia.option) {
  18056. if (singleMedia.query) {
  18057. mediaList.push(singleMedia);
  18058. }
  18059. else if (!mediaDefault) {
  18060. // Use the first media default.
  18061. mediaDefault = singleMedia;
  18062. }
  18063. }
  18064. });
  18065. }
  18066. // For normal option
  18067. if (!baseOption) {
  18068. baseOption = rawOption;
  18069. }
  18070. // Set timelineOpt to baseOption in ec3,
  18071. // which is convenient for merge option.
  18072. if (!baseOption.timeline) {
  18073. baseOption.timeline = timelineOpt;
  18074. }
  18075. // Preprocess.
  18076. each$4([baseOption].concat(timelineOptions)
  18077. .concat(map(mediaList, function (media) {
  18078. return media.option;
  18079. })),
  18080. function (option) {
  18081. each$4(optionPreprocessorFuncs, function (preProcess) {
  18082. preProcess(option, isNew);
  18083. });
  18084. }
  18085. );
  18086. return {
  18087. baseOption: baseOption,
  18088. timelineOptions: timelineOptions,
  18089. mediaDefault: mediaDefault,
  18090. mediaList: mediaList
  18091. };
  18092. }
  18093. /**
  18094. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18095. * Support: width, height, aspectRatio
  18096. * Can use max or min as prefix.
  18097. */
  18098. function applyMediaQuery(query, ecWidth, ecHeight) {
  18099. var realMap = {
  18100. width: ecWidth,
  18101. height: ecHeight,
  18102. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18103. };
  18104. var applicatable = true;
  18105. each$1(query, function (value, attr) {
  18106. var matched = attr.match(QUERY_REG);
  18107. if (!matched || !matched[1] || !matched[2]) {
  18108. return;
  18109. }
  18110. var operator = matched[1];
  18111. var realAttr = matched[2].toLowerCase();
  18112. if (!compare(realMap[realAttr], value, operator)) {
  18113. applicatable = false;
  18114. }
  18115. });
  18116. return applicatable;
  18117. }
  18118. function compare(real, expect, operator) {
  18119. if (operator === 'min') {
  18120. return real >= expect;
  18121. }
  18122. else if (operator === 'max') {
  18123. return real <= expect;
  18124. }
  18125. else { // Equals
  18126. return real === expect;
  18127. }
  18128. }
  18129. function indicesEquals(indices1, indices2) {
  18130. // indices is always order by asc and has only finite number.
  18131. return indices1.join(',') === indices2.join(',');
  18132. }
  18133. /**
  18134. * Consider case:
  18135. * `chart.setOption(opt1);`
  18136. * Then user do some interaction like dataZoom, dataView changing.
  18137. * `chart.setOption(opt2);`
  18138. * Then user press 'reset button' in toolbox.
  18139. *
  18140. * After doing that all of the interaction effects should be reset, the
  18141. * chart should be the same as the result of invoke
  18142. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18143. *
  18144. * Although it is not able ensure that
  18145. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18146. * `chart.setOption(merge(opt1, opt2));` exactly,
  18147. * this might be the only simple way to implement that feature.
  18148. *
  18149. * MEMO: We've considered some other approaches:
  18150. * 1. Each model handle its self restoration but not uniform treatment.
  18151. * (Too complex in logic and error-prone)
  18152. * 2. Use a shadow ecModel. (Performace expensive)
  18153. */
  18154. function mergeOption(oldOption, newOption) {
  18155. newOption = newOption || {};
  18156. each$4(newOption, function (newCptOpt, mainType) {
  18157. if (newCptOpt == null) {
  18158. return;
  18159. }
  18160. var oldCptOpt = oldOption[mainType];
  18161. if (!ComponentModel.hasClass(mainType)) {
  18162. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18163. }
  18164. else {
  18165. newCptOpt = normalizeToArray(newCptOpt);
  18166. oldCptOpt = normalizeToArray(oldCptOpt);
  18167. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18168. oldOption[mainType] = map$1(mapResult, function (item) {
  18169. return (item.option && item.exist)
  18170. ? merge$1(item.exist, item.option, true)
  18171. : (item.exist || item.option);
  18172. });
  18173. }
  18174. });
  18175. }
  18176. var each$5 = each$1;
  18177. var isObject$3 = isObject$1;
  18178. var POSSIBLE_STYLES = [
  18179. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  18180. 'chordStyle', 'label', 'labelLine'
  18181. ];
  18182. function compatEC2ItemStyle(opt) {
  18183. var itemStyleOpt = opt && opt.itemStyle;
  18184. if (!itemStyleOpt) {
  18185. return;
  18186. }
  18187. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18188. var styleName = POSSIBLE_STYLES[i];
  18189. var normalItemStyleOpt = itemStyleOpt.normal;
  18190. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18191. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18192. opt[styleName] = opt[styleName] || {};
  18193. if (!opt[styleName].normal) {
  18194. opt[styleName].normal = normalItemStyleOpt[styleName];
  18195. }
  18196. else {
  18197. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18198. }
  18199. normalItemStyleOpt[styleName] = null;
  18200. }
  18201. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18202. opt[styleName] = opt[styleName] || {};
  18203. if (!opt[styleName].emphasis) {
  18204. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18205. }
  18206. else {
  18207. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18208. }
  18209. emphasisItemStyleOpt[styleName] = null;
  18210. }
  18211. }
  18212. }
  18213. function convertNormalEmphasis(opt, optType, useExtend) {
  18214. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18215. var normalOpt = opt[optType].normal;
  18216. var emphasisOpt = opt[optType].emphasis;
  18217. if (normalOpt) {
  18218. // Timeline controlStyle has other properties besides normal and emphasis
  18219. if (useExtend) {
  18220. opt[optType].normal = opt[optType].emphasis = null;
  18221. defaults(opt[optType], normalOpt);
  18222. }
  18223. else {
  18224. opt[optType] = normalOpt;
  18225. }
  18226. }
  18227. if (emphasisOpt) {
  18228. opt.emphasis = opt.emphasis || {};
  18229. opt.emphasis[optType] = emphasisOpt;
  18230. }
  18231. }
  18232. }
  18233. function removeEC3NormalStatus(opt) {
  18234. convertNormalEmphasis(opt, 'itemStyle');
  18235. convertNormalEmphasis(opt, 'lineStyle');
  18236. convertNormalEmphasis(opt, 'areaStyle');
  18237. convertNormalEmphasis(opt, 'label');
  18238. convertNormalEmphasis(opt, 'labelLine');
  18239. // treemap
  18240. convertNormalEmphasis(opt, 'upperLabel');
  18241. // graph
  18242. convertNormalEmphasis(opt, 'edgeLabel');
  18243. }
  18244. function compatTextStyle(opt, propName) {
  18245. // Check whether is not object (string\null\undefined ...)
  18246. var labelOptSingle = isObject$3(opt) && opt[propName];
  18247. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  18248. if (textStyle) {
  18249. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18250. var propName = TEXT_STYLE_OPTIONS[i];
  18251. if (textStyle.hasOwnProperty(propName)) {
  18252. labelOptSingle[propName] = textStyle[propName];
  18253. }
  18254. }
  18255. }
  18256. }
  18257. function compatEC3CommonStyles(opt) {
  18258. if (opt) {
  18259. removeEC3NormalStatus(opt);
  18260. compatTextStyle(opt, 'label');
  18261. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18262. }
  18263. }
  18264. function processSeries(seriesOpt) {
  18265. if (!isObject$3(seriesOpt)) {
  18266. return;
  18267. }
  18268. compatEC2ItemStyle(seriesOpt);
  18269. removeEC3NormalStatus(seriesOpt);
  18270. compatTextStyle(seriesOpt, 'label');
  18271. // treemap
  18272. compatTextStyle(seriesOpt, 'upperLabel');
  18273. // graph
  18274. compatTextStyle(seriesOpt, 'edgeLabel');
  18275. if (seriesOpt.emphasis) {
  18276. compatTextStyle(seriesOpt.emphasis, 'label');
  18277. // treemap
  18278. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18279. // graph
  18280. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18281. }
  18282. var markPoint = seriesOpt.markPoint;
  18283. if (markPoint) {
  18284. compatEC2ItemStyle(markPoint);
  18285. compatEC3CommonStyles(markPoint);
  18286. }
  18287. var markLine = seriesOpt.markLine;
  18288. if (markLine) {
  18289. compatEC2ItemStyle(markLine);
  18290. compatEC3CommonStyles(markLine);
  18291. }
  18292. var markArea = seriesOpt.markArea;
  18293. if (markArea) {
  18294. compatEC3CommonStyles(markArea);
  18295. }
  18296. var data = seriesOpt.data;
  18297. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18298. // then the backward compat based on option type will not be performed.
  18299. if (seriesOpt.type === 'graph') {
  18300. data = data || seriesOpt.nodes;
  18301. var edgeData = seriesOpt.links || seriesOpt.edges;
  18302. if (edgeData && !isTypedArray(edgeData)) {
  18303. for (var i = 0; i < edgeData.length; i++) {
  18304. compatEC3CommonStyles(edgeData[i]);
  18305. }
  18306. }
  18307. each$1(seriesOpt.categories, function (opt) {
  18308. removeEC3NormalStatus(opt);
  18309. });
  18310. }
  18311. if (data && !isTypedArray(data)) {
  18312. for (var i = 0; i < data.length; i++) {
  18313. compatEC3CommonStyles(data[i]);
  18314. }
  18315. }
  18316. // mark point data
  18317. var markPoint = seriesOpt.markPoint;
  18318. if (markPoint && markPoint.data) {
  18319. var mpData = markPoint.data;
  18320. for (var i = 0; i < mpData.length; i++) {
  18321. compatEC3CommonStyles(mpData[i]);
  18322. }
  18323. }
  18324. // mark line data
  18325. var markLine = seriesOpt.markLine;
  18326. if (markLine && markLine.data) {
  18327. var mlData = markLine.data;
  18328. for (var i = 0; i < mlData.length; i++) {
  18329. if (isArray(mlData[i])) {
  18330. compatEC3CommonStyles(mlData[i][0]);
  18331. compatEC3CommonStyles(mlData[i][1]);
  18332. }
  18333. else {
  18334. compatEC3CommonStyles(mlData[i]);
  18335. }
  18336. }
  18337. }
  18338. // Series
  18339. if (seriesOpt.type === 'gauge') {
  18340. compatTextStyle(seriesOpt, 'axisLabel');
  18341. compatTextStyle(seriesOpt, 'title');
  18342. compatTextStyle(seriesOpt, 'detail');
  18343. }
  18344. else if (seriesOpt.type === 'treemap') {
  18345. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18346. each$1(seriesOpt.levels, function (opt) {
  18347. removeEC3NormalStatus(opt);
  18348. });
  18349. }
  18350. // sunburst starts from ec4, so it does not need to compat levels.
  18351. }
  18352. function toArr(o) {
  18353. return isArray(o) ? o : o ? [o] : [];
  18354. }
  18355. function toObj(o) {
  18356. return (isArray(o) ? o[0] : o) || {};
  18357. }
  18358. var compatStyle = function (option, isTheme) {
  18359. each$5(toArr(option.series), function (seriesOpt) {
  18360. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18361. });
  18362. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18363. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18364. each$5(
  18365. axes,
  18366. function (axisName) {
  18367. each$5(toArr(option[axisName]), function (axisOpt) {
  18368. if (axisOpt) {
  18369. compatTextStyle(axisOpt, 'axisLabel');
  18370. compatTextStyle(axisOpt.axisPointer, 'label');
  18371. }
  18372. });
  18373. }
  18374. );
  18375. each$5(toArr(option.parallel), function (parallelOpt) {
  18376. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18377. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18378. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18379. });
  18380. each$5(toArr(option.calendar), function (calendarOpt) {
  18381. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18382. compatTextStyle(calendarOpt, 'dayLabel');
  18383. compatTextStyle(calendarOpt, 'monthLabel');
  18384. compatTextStyle(calendarOpt, 'yearLabel');
  18385. });
  18386. // radar.name.textStyle
  18387. each$5(toArr(option.radar), function (radarOpt) {
  18388. compatTextStyle(radarOpt, 'name');
  18389. });
  18390. each$5(toArr(option.geo), function (geoOpt) {
  18391. if (isObject$3(geoOpt)) {
  18392. compatEC3CommonStyles(geoOpt);
  18393. each$5(toArr(geoOpt.regions), function (regionObj) {
  18394. compatEC3CommonStyles(regionObj);
  18395. });
  18396. }
  18397. });
  18398. each$5(toArr(option.timeline), function (timelineOpt) {
  18399. compatEC3CommonStyles(timelineOpt);
  18400. convertNormalEmphasis(timelineOpt, 'label');
  18401. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18402. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18403. var data = timelineOpt.data;
  18404. isArray(data) && each$1(data, function (item) {
  18405. if (isObject$1(item)) {
  18406. convertNormalEmphasis(item, 'label');
  18407. convertNormalEmphasis(item, 'itemStyle');
  18408. }
  18409. });
  18410. });
  18411. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18412. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18413. each$5(toolboxOpt.feature, function (featureOpt) {
  18414. convertNormalEmphasis(featureOpt, 'iconStyle');
  18415. });
  18416. });
  18417. compatTextStyle(toObj(option.axisPointer), 'label');
  18418. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18419. };
  18420. // Compatitable with 2.0
  18421. function get(opt, path) {
  18422. path = path.split(',');
  18423. var obj = opt;
  18424. for (var i = 0; i < path.length; i++) {
  18425. obj = obj && obj[path[i]];
  18426. if (obj == null) {
  18427. break;
  18428. }
  18429. }
  18430. return obj;
  18431. }
  18432. function set$1(opt, path, val, overwrite) {
  18433. path = path.split(',');
  18434. var obj = opt;
  18435. var key;
  18436. for (var i = 0; i < path.length - 1; i++) {
  18437. key = path[i];
  18438. if (obj[key] == null) {
  18439. obj[key] = {};
  18440. }
  18441. obj = obj[key];
  18442. }
  18443. if (overwrite || obj[path[i]] == null) {
  18444. obj[path[i]] = val;
  18445. }
  18446. }
  18447. function compatLayoutProperties(option) {
  18448. each$1(LAYOUT_PROPERTIES, function (prop) {
  18449. if (prop[0] in option && !(prop[1] in option)) {
  18450. option[prop[1]] = option[prop[0]];
  18451. }
  18452. });
  18453. }
  18454. var LAYOUT_PROPERTIES = [
  18455. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  18456. ];
  18457. var COMPATITABLE_COMPONENTS = [
  18458. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  18459. ];
  18460. var backwardCompat = function (option, isTheme) {
  18461. compatStyle(option, isTheme);
  18462. // Make sure series array for model initialization.
  18463. option.series = normalizeToArray(option.series);
  18464. each$1(option.series, function (seriesOpt) {
  18465. if (!isObject$1(seriesOpt)) {
  18466. return;
  18467. }
  18468. var seriesType = seriesOpt.type;
  18469. if (seriesType === 'pie' || seriesType === 'gauge') {
  18470. if (seriesOpt.clockWise != null) {
  18471. seriesOpt.clockwise = seriesOpt.clockWise;
  18472. }
  18473. }
  18474. if (seriesType === 'gauge') {
  18475. var pointerColor = get(seriesOpt, 'pointer.color');
  18476. pointerColor != null
  18477. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  18478. }
  18479. compatLayoutProperties(seriesOpt);
  18480. });
  18481. // dataRange has changed to visualMap
  18482. if (option.dataRange) {
  18483. option.visualMap = option.dataRange;
  18484. }
  18485. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  18486. var options = option[componentName];
  18487. if (options) {
  18488. if (!isArray(options)) {
  18489. options = [options];
  18490. }
  18491. each$1(options, function (option) {
  18492. compatLayoutProperties(option);
  18493. });
  18494. }
  18495. });
  18496. };
  18497. // (1) [Caution]: the logic is correct based on the premises:
  18498. // data processing stage is blocked in stream.
  18499. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18500. // (2) Only register once when import repeatly.
  18501. // Should be executed before after series filtered and before stack calculation.
  18502. var dataStack = function (ecModel) {
  18503. var stackInfoMap = createHashMap();
  18504. ecModel.eachSeries(function (seriesModel) {
  18505. var stack = seriesModel.get('stack');
  18506. // Compatibal: when `stack` is set as '', do not stack.
  18507. if (stack) {
  18508. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18509. var data = seriesModel.getData();
  18510. var stackInfo = {
  18511. // Used for calculate axis extent automatically.
  18512. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18513. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18514. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18515. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18516. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18517. data: data,
  18518. seriesModel: seriesModel
  18519. };
  18520. // If stacked on axis that do not support data stack.
  18521. if (!stackInfo.stackedDimension
  18522. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  18523. ) {
  18524. return;
  18525. }
  18526. stackInfoList.length && data.setCalculationInfo(
  18527. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  18528. );
  18529. stackInfoList.push(stackInfo);
  18530. }
  18531. });
  18532. stackInfoMap.each(calculateStack);
  18533. };
  18534. function calculateStack(stackInfoList) {
  18535. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  18536. var resultVal = [];
  18537. var resultNaN = [NaN, NaN];
  18538. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18539. var targetData = targetStackInfo.data;
  18540. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18541. // Should not write on raw data, because stack series model list changes
  18542. // depending on legend selection.
  18543. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  18544. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  18545. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18546. // should also be NaN, to draw a appropriate belt area.
  18547. if (isNaN(sum)) {
  18548. return resultNaN;
  18549. }
  18550. var byValue;
  18551. var stackedDataRawIndex;
  18552. if (isStackedByIndex) {
  18553. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18554. }
  18555. else {
  18556. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18557. }
  18558. // If stackOver is NaN, chart view will render point on value start.
  18559. var stackedOver = NaN;
  18560. for (var j = idxInStack - 1; j >= 0; j--) {
  18561. var stackInfo = stackInfoList[j];
  18562. // Has been optimized by inverted indices on `stackedByDimension`.
  18563. if (!isStackedByIndex) {
  18564. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18565. }
  18566. if (stackedDataRawIndex >= 0) {
  18567. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  18568. // Considering positive stack, negative stack and empty data
  18569. if ((sum >= 0 && val > 0) // Positive stack
  18570. || (sum <= 0 && val < 0) // Negative stack
  18571. ) {
  18572. sum += val;
  18573. stackedOver = val;
  18574. break;
  18575. }
  18576. }
  18577. }
  18578. resultVal[0] = sum;
  18579. resultVal[1] = stackedOver;
  18580. return resultVal;
  18581. });
  18582. targetData.hostModel.setData(newData);
  18583. // Update for consequent calculation
  18584. targetStackInfo.data = newData;
  18585. });
  18586. }
  18587. // TODO
  18588. // ??? refactor? check the outer usage of data provider.
  18589. // merge with defaultDimValueGetter?
  18590. /**
  18591. * If normal array used, mutable chunk size is supported.
  18592. * If typed array used, chunk size must be fixed.
  18593. */
  18594. function DefaultDataProvider(source, dimSize) {
  18595. if (!Source.isInstance(source)) {
  18596. source = Source.seriesDataToSource(source);
  18597. }
  18598. this._source = source;
  18599. var data = this._data = source.data;
  18600. var sourceFormat = source.sourceFormat;
  18601. // Typed array. TODO IE10+?
  18602. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18603. if (__DEV__) {
  18604. if (dimSize == null) {
  18605. throw new Error('Typed array data must specify dimension size');
  18606. }
  18607. }
  18608. this._offset = 0;
  18609. this._dimSize = dimSize;
  18610. this._data = data;
  18611. }
  18612. var methods = providerMethods[
  18613. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  18614. ? sourceFormat + '_' + source.seriesLayoutBy
  18615. : sourceFormat
  18616. ];
  18617. if (__DEV__) {
  18618. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18619. }
  18620. extend(this, methods);
  18621. }
  18622. var providerProto = DefaultDataProvider.prototype;
  18623. // If data is pure without style configuration
  18624. providerProto.pure = false;
  18625. // If data is persistent and will not be released after use.
  18626. providerProto.persistent = true;
  18627. // ???! FIXME legacy data provider do not has method getSource
  18628. providerProto.getSource = function () {
  18629. return this._source;
  18630. };
  18631. var providerMethods = {
  18632. 'arrayRows_column': {
  18633. pure: true,
  18634. count: function () {
  18635. return Math.max(0, this._data.length - this._source.startIndex);
  18636. },
  18637. getItem: function (idx) {
  18638. return this._data[idx + this._source.startIndex];
  18639. },
  18640. appendData: appendDataSimply
  18641. },
  18642. 'arrayRows_row': {
  18643. pure: true,
  18644. count: function () {
  18645. var row = this._data[0];
  18646. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  18647. },
  18648. getItem: function (idx) {
  18649. idx += this._source.startIndex;
  18650. var item = [];
  18651. var data = this._data;
  18652. for (var i = 0; i < data.length; i++) {
  18653. var row = data[i];
  18654. item.push(row ? row[idx] : null);
  18655. }
  18656. return item;
  18657. },
  18658. appendData: function () {
  18659. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18660. }
  18661. },
  18662. 'objectRows': {
  18663. pure: true,
  18664. count: countSimply,
  18665. getItem: getItemSimply,
  18666. appendData: appendDataSimply
  18667. },
  18668. 'keyedColumns': {
  18669. pure: true,
  18670. count: function () {
  18671. var dimName = this._source.dimensionsDefine[0].name;
  18672. var col = this._data[dimName];
  18673. return col ? col.length : 0;
  18674. },
  18675. getItem: function (idx) {
  18676. var item = [];
  18677. var dims = this._source.dimensionsDefine;
  18678. for (var i = 0; i < dims.length; i++) {
  18679. var col = this._data[dims[i].name];
  18680. item.push(col ? col[idx] : null);
  18681. }
  18682. return item;
  18683. },
  18684. appendData: function (newData) {
  18685. var data = this._data;
  18686. each$1(newData, function (newCol, key) {
  18687. var oldCol = data[key] || (data[key] = []);
  18688. for (var i = 0; i < (newCol || []).length; i++) {
  18689. oldCol.push(newCol[i]);
  18690. }
  18691. });
  18692. }
  18693. },
  18694. 'original': {
  18695. count: countSimply,
  18696. getItem: getItemSimply,
  18697. appendData: appendDataSimply
  18698. },
  18699. 'typedArray': {
  18700. persistent: false,
  18701. pure: true,
  18702. count: function () {
  18703. return this._data ? (this._data.length / this._dimSize) : 0;
  18704. },
  18705. getItem: function (idx) {
  18706. idx = idx - this._offset;
  18707. var item = [];
  18708. var offset = this._dimSize * idx;
  18709. for (var i = 0; i < this._dimSize; i++) {
  18710. item[i] = this._data[offset + i];
  18711. }
  18712. return item;
  18713. },
  18714. appendData: function (newData) {
  18715. if (__DEV__) {
  18716. assert$1(
  18717. isTypedArray(newData),
  18718. 'Added data must be TypedArray if data in initialization is TypedArray'
  18719. );
  18720. }
  18721. this._data = newData;
  18722. },
  18723. // Clean self if data is already used.
  18724. clean: function () {
  18725. // PENDING
  18726. this._offset += this.count();
  18727. this._data = null;
  18728. }
  18729. }
  18730. };
  18731. function countSimply() {
  18732. return this._data.length;
  18733. }
  18734. function getItemSimply(idx) {
  18735. return this._data[idx];
  18736. }
  18737. function appendDataSimply(newData) {
  18738. for (var i = 0; i < newData.length; i++) {
  18739. this._data.push(newData[i]);
  18740. }
  18741. }
  18742. var rawValueGetters = {
  18743. arrayRows: getRawValueSimply,
  18744. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  18745. return dimIndex != null ? dataItem[dimName] : dataItem;
  18746. },
  18747. keyedColumns: getRawValueSimply,
  18748. original: function (dataItem, dataIndex, dimIndex, dimName) {
  18749. // FIXME
  18750. // In some case (markpoint in geo (geo-map.html)), dataItem
  18751. // is {coord: [...]}
  18752. var value = getDataItemValue(dataItem);
  18753. return (dimIndex == null || !(value instanceof Array))
  18754. ? value
  18755. : value[dimIndex];
  18756. },
  18757. typedArray: getRawValueSimply
  18758. };
  18759. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  18760. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  18761. }
  18762. var defaultDimValueGetters = {
  18763. arrayRows: getDimValueSimply,
  18764. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  18765. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  18766. },
  18767. keyedColumns: getDimValueSimply,
  18768. original: function (dataItem, dimName, dataIndex, dimIndex) {
  18769. // Performance sensitive, do not use modelUtil.getDataItemValue.
  18770. // If dataItem is an plain object with no value field, the var `value`
  18771. // will be assigned with the object, but it will be tread correctly
  18772. // in the `convertDataValue`.
  18773. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  18774. // If any dataItem is like { value: 10 }
  18775. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  18776. this.hasItemOption = true;
  18777. }
  18778. return converDataValue(
  18779. (value instanceof Array)
  18780. ? value[dimIndex]
  18781. // If value is a single number or something else not array.
  18782. : value,
  18783. this._dimensionInfos[dimName]
  18784. );
  18785. },
  18786. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  18787. return dataItem[dimIndex];
  18788. }
  18789. };
  18790. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  18791. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  18792. }
  18793. /**
  18794. * This helper method convert value in data.
  18795. * @param {string|number|Date} value
  18796. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  18797. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  18798. */
  18799. function converDataValue(value, dimInfo) {
  18800. // Performance sensitive.
  18801. var dimType = dimInfo && dimInfo.type;
  18802. if (dimType === 'ordinal') {
  18803. // If given value is a category string
  18804. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  18805. return ordinalMeta
  18806. ? ordinalMeta.parseAndCollect(value)
  18807. : value;
  18808. }
  18809. if (dimType === 'time'
  18810. // spead up when using timestamp
  18811. && typeof value !== 'number'
  18812. && value != null
  18813. && value !== '-'
  18814. ) {
  18815. value = +parseDate(value);
  18816. }
  18817. // dimType defaults 'number'.
  18818. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  18819. // parse to NaN.
  18820. return (value == null || value === '')
  18821. ? NaN
  18822. // If string (like '-'), using '+' parse to NaN
  18823. // If object, also parse to NaN
  18824. : +value;
  18825. }
  18826. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18827. // Consider persistent.
  18828. // Caution: why use raw value to display on label or tooltip?
  18829. // A reason is to avoid format. For example time value we do not know
  18830. // how to format is expected. More over, if stack is used, calculated
  18831. // value may be 0.91000000001, which have brings trouble to display.
  18832. // TODO: consider how to treat null/undefined/NaN when display?
  18833. /**
  18834. * @param {module:echarts/data/List} data
  18835. * @param {number} dataIndex
  18836. * @param {string|number} [dim] dimName or dimIndex
  18837. * @return {Array.<number>|string|number} can be null/undefined.
  18838. */
  18839. function retrieveRawValue(data, dataIndex, dim) {
  18840. if (!data) {
  18841. return;
  18842. }
  18843. // Consider data may be not persistent.
  18844. var dataItem = data.getRawDataItem(dataIndex);
  18845. if (dataItem == null) {
  18846. return;
  18847. }
  18848. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18849. var dimName;
  18850. var dimIndex;
  18851. var dimInfo = data.getDimensionInfo(dim);
  18852. if (dimInfo) {
  18853. dimName = dimInfo.name;
  18854. dimIndex = dimInfo.index;
  18855. }
  18856. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  18857. }
  18858. /**
  18859. * Compatible with some cases (in pie, map) like:
  18860. * data: [{name: 'xx', value: 5, selected: true}, ...]
  18861. * where only sourceFormat is 'original' and 'objectRows' supported.
  18862. *
  18863. * ??? TODO
  18864. * Supported detail options in data item when using 'arrayRows'.
  18865. *
  18866. * @param {module:echarts/data/List} data
  18867. * @param {number} dataIndex
  18868. * @param {string} attr like 'selected'
  18869. */
  18870. function retrieveRawAttr(data, dataIndex, attr) {
  18871. if (!data) {
  18872. return;
  18873. }
  18874. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18875. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  18876. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  18877. ) {
  18878. return;
  18879. }
  18880. var dataItem = data.getRawDataItem(dataIndex);
  18881. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  18882. dataItem = null;
  18883. }
  18884. if (dataItem) {
  18885. return dataItem[attr];
  18886. }
  18887. }
  18888. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18889. // PENDING A little ugly
  18890. var dataFormatMixin = {
  18891. /**
  18892. * Get params for formatter
  18893. * @param {number} dataIndex
  18894. * @param {string} [dataType]
  18895. * @return {Object}
  18896. */
  18897. getDataParams: function (dataIndex, dataType) {
  18898. var data = this.getData(dataType);
  18899. var rawValue = this.getRawValue(dataIndex, dataType);
  18900. var rawDataIndex = data.getRawIndex(dataIndex);
  18901. var name = data.getName(dataIndex, true);
  18902. var itemOpt = data.getRawDataItem(dataIndex);
  18903. var color = data.getItemVisual(dataIndex, 'color');
  18904. return {
  18905. componentType: this.mainType,
  18906. componentSubType: this.subType,
  18907. seriesType: this.mainType === 'series' ? this.subType : null,
  18908. seriesIndex: this.seriesIndex,
  18909. seriesId: this.id,
  18910. seriesName: this.name,
  18911. name: name,
  18912. dataIndex: rawDataIndex,
  18913. data: itemOpt,
  18914. dataType: dataType,
  18915. value: rawValue,
  18916. color: color,
  18917. marker: getTooltipMarker(color),
  18918. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18919. $vars: ['seriesName', 'name', 'value']
  18920. };
  18921. },
  18922. /**
  18923. * Format label
  18924. * @param {number} dataIndex
  18925. * @param {string} [status='normal'] 'normal' or 'emphasis'
  18926. * @param {string} [dataType]
  18927. * @param {number} [dimIndex]
  18928. * @param {string} [labelProp='label']
  18929. * @return {string} If not formatter, return null/undefined
  18930. */
  18931. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  18932. status = status || 'normal';
  18933. var data = this.getData(dataType);
  18934. var itemModel = data.getItemModel(dataIndex);
  18935. var params = this.getDataParams(dataIndex, dataType);
  18936. if (dimIndex != null && (params.value instanceof Array)) {
  18937. params.value = params.value[dimIndex];
  18938. }
  18939. var formatter = itemModel.get(
  18940. status === 'normal'
  18941. ? [labelProp || 'label', 'formatter']
  18942. : [status, labelProp || 'label', 'formatter']
  18943. );
  18944. if (typeof formatter === 'function') {
  18945. params.status = status;
  18946. return formatter(params);
  18947. }
  18948. else if (typeof formatter === 'string') {
  18949. var str = formatTpl(formatter, params);
  18950. // Support 'aaa{@[3]}bbb{@product}ccc'.
  18951. // Do not support '}' in dim name util have to.
  18952. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  18953. var len = dim.length;
  18954. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  18955. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  18956. }
  18957. return retrieveRawValue(data, dataIndex, dim);
  18958. });
  18959. }
  18960. },
  18961. /**
  18962. * Get raw value in option
  18963. * @param {number} idx
  18964. * @param {string} [dataType]
  18965. * @return {Array|number|string}
  18966. */
  18967. getRawValue: function (idx, dataType) {
  18968. return retrieveRawValue(this.getData(dataType), idx);
  18969. },
  18970. /**
  18971. * Should be implemented.
  18972. * @param {number} dataIndex
  18973. * @param {boolean} [multipleSeries=false]
  18974. * @param {number} [dataType]
  18975. * @return {string} tooltip string
  18976. */
  18977. formatTooltip: function () {
  18978. // Empty function
  18979. }
  18980. };
  18981. /**
  18982. * @param {Object} define
  18983. * @return See the return of `createTask`.
  18984. */
  18985. function createTask(define) {
  18986. return new Task(define);
  18987. }
  18988. /**
  18989. * @constructor
  18990. * @param {Object} define
  18991. * @param {Function} define.reset Custom reset
  18992. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  18993. * @param {Function} [define.count] count is used to determin data task.
  18994. * @param {Function} [define.onDirty] count is used to determin data task.
  18995. */
  18996. function Task(define) {
  18997. define = define || {};
  18998. this._reset = define.reset;
  18999. this._plan = define.plan;
  19000. this._count = define.count;
  19001. this._onDirty = define.onDirty;
  19002. this._dirty = true;
  19003. // Context must be specified implicitly, to
  19004. // avoid miss update context when model changed.
  19005. this.context;
  19006. }
  19007. var taskProto = Task.prototype;
  19008. /**
  19009. * @param {Object} performArgs
  19010. * @param {number} [performArgs.step] Specified step.
  19011. * @param {number} [performArgs.skip] Skip customer perform call.
  19012. */
  19013. taskProto.perform = function (performArgs) {
  19014. var upTask = this._upstream;
  19015. var skip = performArgs && performArgs.skip;
  19016. // TODO some refactor.
  19017. // Pull data. Must pull data each time, because context.data
  19018. // may be updated by Series.setData.
  19019. if (this._dirty && upTask) {
  19020. var context = this.context;
  19021. context.data = context.outputData = upTask.context.outputData;
  19022. }
  19023. if (this.__pipeline) {
  19024. this.__pipeline.currentTask = this;
  19025. }
  19026. var planResult;
  19027. if (this._plan && !skip) {
  19028. planResult = this._plan(this.context);
  19029. }
  19030. var forceFirstProgress;
  19031. if (this._dirty || planResult === 'reset') {
  19032. this._dirty = false;
  19033. forceFirstProgress = reset(this, skip);
  19034. }
  19035. var step = performArgs && performArgs.step;
  19036. if (upTask) {
  19037. if (__DEV__) {
  19038. assert$1(upTask._outputDueEnd != null);
  19039. }
  19040. // ??? FIXME move to schedueler?
  19041. // this._dueEnd = Math.max(upTask._outputDueEnd, this._dueEnd);
  19042. this._dueEnd = upTask._outputDueEnd;
  19043. }
  19044. // DataTask or overallTask
  19045. else {
  19046. if (__DEV__) {
  19047. assert$1(!this._progress || this._count);
  19048. }
  19049. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19050. }
  19051. // Note: Stubs, that its host overall task let it has progress, has progress.
  19052. // If no progress, pass index from upstream to downstream each time plan called.
  19053. if (this._progress) {
  19054. var start = this._dueIndex;
  19055. var end = Math.min(
  19056. step != null ? this._dueIndex + step : Infinity,
  19057. this._dueEnd
  19058. );
  19059. !skip && (forceFirstProgress || start < end) && (
  19060. this._progress({start: start, end: end}, this.context)
  19061. );
  19062. this._dueIndex = end;
  19063. // If no `outputDueEnd`, assume that output data and
  19064. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19065. var outputDueEnd = this._settedOutputEnd != null
  19066. ? this._settedOutputEnd : end;
  19067. if (__DEV__) {
  19068. // ??? Can not rollback.
  19069. assert$1(outputDueEnd >= this._outputDueEnd);
  19070. }
  19071. this._outputDueEnd = outputDueEnd;
  19072. }
  19073. else {
  19074. // (1) Some overall task has no progress.
  19075. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19076. // This should always be performed so it can be passed to downstream.
  19077. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  19078. ? this._settedOutputEnd : this._dueEnd;
  19079. }
  19080. return this.unfinished();
  19081. };
  19082. taskProto.dirty = function () {
  19083. this._dirty = true;
  19084. this._onDirty && this._onDirty(this.context);
  19085. };
  19086. /**
  19087. * @param {Object} [params]
  19088. */
  19089. function reset(taskIns, skip) {
  19090. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  19091. taskIns._settedOutputEnd = null;
  19092. var progress;
  19093. var forceFirstProgress;
  19094. if (!skip && taskIns._reset) {
  19095. progress = taskIns._reset(taskIns.context);
  19096. if (progress && progress.progress) {
  19097. forceFirstProgress = progress.forceFirstProgress;
  19098. progress = progress.progress;
  19099. }
  19100. }
  19101. taskIns._progress = progress;
  19102. var downstream = taskIns._downstream;
  19103. downstream && downstream.dirty();
  19104. return forceFirstProgress;
  19105. }
  19106. /**
  19107. * @return {boolean}
  19108. */
  19109. taskProto.unfinished = function () {
  19110. return this._progress && this._dueIndex < this._dueEnd;
  19111. };
  19112. /**
  19113. * @param {Object} downTask The downstream task.
  19114. * @return {Object} The downstream task.
  19115. */
  19116. taskProto.pipe = function (downTask) {
  19117. if (__DEV__) {
  19118. assert$1(downTask && !downTask._disposed && downTask !== this);
  19119. }
  19120. // If already downstream, do not dirty downTask.
  19121. if (this._downstream !== downTask || this._dirty) {
  19122. this._downstream = downTask;
  19123. downTask._upstream = this;
  19124. downTask.dirty();
  19125. }
  19126. };
  19127. taskProto.dispose = function () {
  19128. if (this._disposed) {
  19129. return;
  19130. }
  19131. this._upstream && (this._upstream._downstream = null);
  19132. this._downstream && (this._downstream._upstream = null);
  19133. this._dirty = false;
  19134. this._disposed = true;
  19135. };
  19136. taskProto.getUpstream = function () {
  19137. return this._upstream;
  19138. };
  19139. taskProto.getDownstream = function () {
  19140. return this._downstream;
  19141. };
  19142. taskProto.setOutputEnd = function (end) {
  19143. // ??? FIXME: check
  19144. // This only happend in dataTask, dataZoom, map, currently.
  19145. // where dataZoom do not set end each time, but only set
  19146. // when reset. So we should record the setted end, in case
  19147. // that the stub of dataZoom perform again and earse the
  19148. // setted end by upstream.
  19149. this._outputDueEnd = this._settedOutputEnd = end;
  19150. // this._outputDueEnd = end;
  19151. };
  19152. ///////////////////////////////////////////////////////////
  19153. // For stream debug (Should be commented out after used!)
  19154. // Usage: printTask(this, 'begin');
  19155. // Usage: printTask(this, null, {someExtraProp});
  19156. // function printTask(task, prefix, extra) {
  19157. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19158. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19159. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19160. // var props = [];
  19161. // if (task.__pipeline) {
  19162. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19163. // props.push({text: 'idx', value: val});
  19164. // } else {
  19165. // var stubCount = 0;
  19166. // task.agentStubMap.each(() => stubCount++);
  19167. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19168. // }
  19169. // props.push({text: 'uid', value: task.uidDebug});
  19170. // if (task.__pipeline) {
  19171. // props.push({text: 'pid', value: task.__pipeline.id});
  19172. // task.agent && props.push(
  19173. // {text: 'stubFor', value: task.agent.uidDebug}
  19174. // );
  19175. // }
  19176. // props.push(
  19177. // {text: 'dirty', value: task._dirty},
  19178. // {text: 'dueIndex', value: task._dueIndex},
  19179. // {text: 'dueEnd', value: task._dueEnd},
  19180. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19181. // );
  19182. // if (extra) {
  19183. // Object.keys(extra).forEach(key => {
  19184. // props.push({text: key, value: extra[key]});
  19185. // });
  19186. // }
  19187. // var args = ['color: blue'];
  19188. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19189. // args.push('color: black', 'color: red'),
  19190. // `${item.text}: %c${item.value}`
  19191. // )).join('%c, ');
  19192. // console.log.apply(console, [msg].concat(args));
  19193. // // console.log(this);
  19194. // }
  19195. var inner$4 = makeInner();
  19196. var SeriesModel = ComponentModel.extend({
  19197. type: 'series.__base__',
  19198. /**
  19199. * @readOnly
  19200. */
  19201. seriesIndex: 0,
  19202. // coodinateSystem will be injected in the echarts/CoordinateSystem
  19203. coordinateSystem: null,
  19204. /**
  19205. * @type {Object}
  19206. * @protected
  19207. */
  19208. defaultOption: null,
  19209. /**
  19210. * Data provided for legend
  19211. * @type {Function}
  19212. */
  19213. // PENDING
  19214. legendDataProvider: null,
  19215. /**
  19216. * Access path of color for visual
  19217. */
  19218. visualColorAccessPath: 'itemStyle.color',
  19219. /**
  19220. * Support merge layout params.
  19221. * Only support 'box' now (left/right/top/bottom/width/height).
  19222. * @type {string|Object} Object can be {ignoreSize: true}
  19223. * @readOnly
  19224. */
  19225. layoutMode: null,
  19226. init: function (option, parentModel, ecModel, extraOpt) {
  19227. /**
  19228. * @type {number}
  19229. * @readOnly
  19230. */
  19231. this.seriesIndex = this.componentIndex;
  19232. this.dataTask = createTask({
  19233. count: dataTaskCount,
  19234. reset: dataTaskReset
  19235. });
  19236. this.dataTask.context = {model: this};
  19237. this.mergeDefaultAndTheme(option, ecModel);
  19238. prepareSource(this);
  19239. var data = this.getInitialData(option, ecModel);
  19240. wrapData(data, this);
  19241. this.dataTask.context.data = data;
  19242. if (__DEV__) {
  19243. assert$1(data, 'getInitialData returned invalid data.');
  19244. }
  19245. /**
  19246. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  19247. * @private
  19248. */
  19249. inner$4(this).dataBeforeProcessed = data;
  19250. // If we reverse the order (make data firstly, and then make
  19251. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19252. // cause data.graph.data !== data when using
  19253. // module:echarts/data/Graph or module:echarts/data/Tree.
  19254. // See module:echarts/data/helper/linkList
  19255. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19256. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19257. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19258. // Call `seriesModel.getRawData()` instead.
  19259. // this.restoreData();
  19260. autoSeriesName(this);
  19261. },
  19262. /**
  19263. * Util for merge default and theme to option
  19264. * @param {Object} option
  19265. * @param {module:echarts/model/Global} ecModel
  19266. */
  19267. mergeDefaultAndTheme: function (option, ecModel) {
  19268. var layoutMode = this.layoutMode;
  19269. var inputPositionParams = layoutMode
  19270. ? getLayoutParams(option) : {};
  19271. // Backward compat: using subType on theme.
  19272. // But if name duplicate between series subType
  19273. // (for example: parallel) add component mainType,
  19274. // add suffix 'Series'.
  19275. var themeSubType = this.subType;
  19276. if (ComponentModel.hasClass(themeSubType)) {
  19277. themeSubType += 'Series';
  19278. }
  19279. merge(
  19280. option,
  19281. ecModel.getTheme().get(this.subType)
  19282. );
  19283. merge(option, this.getDefaultOption());
  19284. // Default label emphasis `show`
  19285. defaultEmphasis(option, 'label', ['show']);
  19286. this.fillDataTextStyle(option.data);
  19287. if (layoutMode) {
  19288. mergeLayoutParam(option, inputPositionParams, layoutMode);
  19289. }
  19290. },
  19291. mergeOption: function (newSeriesOption, ecModel) {
  19292. // this.settingTask.dirty();
  19293. newSeriesOption = merge(this.option, newSeriesOption, true);
  19294. this.fillDataTextStyle(newSeriesOption.data);
  19295. var layoutMode = this.layoutMode;
  19296. if (layoutMode) {
  19297. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  19298. }
  19299. prepareSource(this);
  19300. var data = this.getInitialData(newSeriesOption, ecModel);
  19301. wrapData(data, this);
  19302. this.dataTask.dirty();
  19303. this.dataTask.context.data = data;
  19304. inner$4(this).dataBeforeProcessed = data;
  19305. autoSeriesName(this);
  19306. },
  19307. fillDataTextStyle: function (data) {
  19308. // Default data label emphasis `show`
  19309. // FIXME Tree structure data ?
  19310. // FIXME Performance ?
  19311. if (data) {
  19312. var props = ['show'];
  19313. for (var i = 0; i < data.length; i++) {
  19314. if (data[i] && data[i].label) {
  19315. defaultEmphasis(data[i], 'label', props);
  19316. }
  19317. }
  19318. }
  19319. },
  19320. /**
  19321. * Init a data structure from data related option in series
  19322. * Must be overwritten
  19323. */
  19324. getInitialData: function () {},
  19325. /**
  19326. * Append data to list
  19327. * @param {Object} params
  19328. * @param {Array|TypedArray} params.data
  19329. */
  19330. appendData: function (params) {
  19331. // FIXME ???
  19332. // (1) If data from dataset, forbidden append.
  19333. // (2) support append data of dataset.
  19334. var data = this.getRawData();
  19335. data.appendData(params.data);
  19336. },
  19337. /**
  19338. * Consider some method like `filter`, `map` need make new data,
  19339. * We should make sure that `seriesModel.getData()` get correct
  19340. * data in the stream procedure. So we fetch data from upstream
  19341. * each time `task.perform` called.
  19342. * @param {string} [dataType]
  19343. * @return {module:echarts/data/List}
  19344. */
  19345. getData: function (dataType) {
  19346. var task = getCurrentTask(this);
  19347. if (task) {
  19348. var data = task.context.data;
  19349. return dataType == null ? data : data.getLinkedData(dataType);
  19350. }
  19351. else {
  19352. // When series is not alive (that may happen when click toolbox
  19353. // restore or setOption with not merge mode), series data may
  19354. // be still need to judge animation or something when graphic
  19355. // elements want to know whether fade out.
  19356. return inner$4(this).data;
  19357. }
  19358. },
  19359. /**
  19360. * @param {module:echarts/data/List} data
  19361. */
  19362. setData: function (data) {
  19363. var task = getCurrentTask(this);
  19364. if (task) {
  19365. var context = task.context;
  19366. // Consider case: filter, data sample.
  19367. if (context.data !== data && task.isOverallFilter) {
  19368. task.setOutputEnd(data.count());
  19369. }
  19370. context.outputData = data;
  19371. // Caution: setData should update context.data,
  19372. // Because getData may be called multiply in a
  19373. // single stage and expect to get the data just
  19374. // set. (For example, AxisProxy, x y both call
  19375. // getData and setDate sequentially).
  19376. // So the context.data should be fetched from
  19377. // upstream each time when a stage starts to be
  19378. // performed.
  19379. if (task !== this.dataTask) {
  19380. context.data = data;
  19381. }
  19382. }
  19383. inner$4(this).data = data;
  19384. },
  19385. /**
  19386. * @see {module:echarts/data/helper/sourceHelper#getSource}
  19387. * @return {module:echarts/data/Source} source
  19388. */
  19389. getSource: function () {
  19390. return getSource(this);
  19391. },
  19392. /**
  19393. * Get data before processed
  19394. * @return {module:echarts/data/List}
  19395. */
  19396. getRawData: function () {
  19397. return inner$4(this).dataBeforeProcessed;
  19398. },
  19399. /**
  19400. * Get base axis if has coordinate system and has axis.
  19401. * By default use coordSys.getBaseAxis();
  19402. * Can be overrided for some chart.
  19403. * @return {type} description
  19404. */
  19405. getBaseAxis: function () {
  19406. var coordSys = this.coordinateSystem;
  19407. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  19408. },
  19409. // FIXME
  19410. /**
  19411. * Default tooltip formatter
  19412. *
  19413. * @param {number} dataIndex
  19414. * @param {boolean} [multipleSeries=false]
  19415. * @param {number} [dataType]
  19416. */
  19417. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  19418. function formatArrayValue(value) {
  19419. // ??? TODO refactor these logic.
  19420. // check: category-no-encode-has-axis-data in dataset.html
  19421. var vertially = reduce(value, function (vertially, val, idx) {
  19422. var dimItem = data.getDimensionInfo(idx);
  19423. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  19424. }, 0);
  19425. var result = [];
  19426. tooltipDims.length
  19427. ? each$1(tooltipDims, function (dim) {
  19428. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  19429. })
  19430. // By default, all dims is used on tooltip.
  19431. : each$1(value, setEachItem);
  19432. function setEachItem(val, dim) {
  19433. var dimInfo = data.getDimensionInfo(dim);
  19434. // If `dimInfo.tooltip` is not set, show tooltip.
  19435. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  19436. return;
  19437. }
  19438. var dimType = dimInfo.type;
  19439. var dimHead = getTooltipMarker({color: color, type: 'subItem'});
  19440. var valStr = (vertially
  19441. ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': '
  19442. : ''
  19443. )
  19444. // FIXME should not format time for raw data?
  19445. + encodeHTML(dimType === 'ordinal'
  19446. ? val + ''
  19447. : dimType === 'time'
  19448. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  19449. : addCommas(val)
  19450. );
  19451. valStr && result.push(valStr);
  19452. }
  19453. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  19454. }
  19455. function formatSingleValue(val) {
  19456. return encodeHTML(addCommas(val));
  19457. }
  19458. var data = this.getData();
  19459. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  19460. var tooltipDimLen = tooltipDims.length;
  19461. var value = this.getRawValue(dataIndex);
  19462. var isValueArr = isArray(value);
  19463. var color = data.getItemVisual(dataIndex, 'color');
  19464. if (isObject$1(color) && color.colorStops) {
  19465. color = (color.colorStops[0] || {}).color;
  19466. }
  19467. color = color || 'transparent';
  19468. // Complicated rule for pretty tooltip.
  19469. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  19470. ? formatArrayValue(value)
  19471. : tooltipDimLen
  19472. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  19473. : formatSingleValue(isValueArr ? value[0] : value);
  19474. var colorEl = getTooltipMarker(color);
  19475. var name = data.getName(dataIndex);
  19476. var seriesName = this.name;
  19477. if (!isNameSpecified(this)) {
  19478. seriesName = '';
  19479. }
  19480. seriesName = seriesName
  19481. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  19482. : '';
  19483. return !multipleSeries
  19484. ? seriesName + colorEl
  19485. + (name
  19486. ? encodeHTML(name) + ': ' + formattedValue
  19487. : formattedValue
  19488. )
  19489. : colorEl + seriesName + formattedValue;
  19490. },
  19491. /**
  19492. * @return {boolean}
  19493. */
  19494. isAnimationEnabled: function () {
  19495. if (env$1.node) {
  19496. return false;
  19497. }
  19498. var animationEnabled = this.getShallow('animation');
  19499. if (animationEnabled) {
  19500. if (this.getData().count() > this.getShallow('animationThreshold')) {
  19501. animationEnabled = false;
  19502. }
  19503. }
  19504. return animationEnabled;
  19505. },
  19506. restoreData: function () {
  19507. this.dataTask.dirty();
  19508. },
  19509. getColorFromPalette: function (name, scope, requestColorNum) {
  19510. var ecModel = this.ecModel;
  19511. // PENDING
  19512. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  19513. if (!color) {
  19514. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  19515. }
  19516. return color;
  19517. },
  19518. /**
  19519. * Use `data.mapDimension(coordDim, true)` instead.
  19520. * @deprecated
  19521. */
  19522. coordDimToDataDim: function (coordDim) {
  19523. return this.getRawData().mapDimension(coordDim, true);
  19524. },
  19525. /**
  19526. * Get progressive rendering count each step
  19527. * @return {number}
  19528. */
  19529. getProgressive: function () {
  19530. return this.get('progressive');
  19531. },
  19532. /**
  19533. * Get progressive rendering count each step
  19534. * @return {number}
  19535. */
  19536. getProgressiveThreshold: function () {
  19537. return this.get('progressiveThreshold');
  19538. },
  19539. /**
  19540. * Get data indices for show tooltip content. See tooltip.
  19541. * @abstract
  19542. * @param {Array.<string>|string} dim
  19543. * @param {Array.<number>} value
  19544. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  19545. * @return {Object} {dataIndices, nestestValue}.
  19546. */
  19547. getAxisTooltipData: null,
  19548. /**
  19549. * See tooltip.
  19550. * @abstract
  19551. * @param {number} dataIndex
  19552. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  19553. */
  19554. getTooltipPosition: null,
  19555. /**
  19556. * @see {module:echarts/stream/Scheduler}
  19557. */
  19558. pipeTask: null,
  19559. /**
  19560. * Convinient for override in extended class.
  19561. * @protected
  19562. * @type {Function}
  19563. */
  19564. preventIncremental: null,
  19565. /**
  19566. * @public
  19567. * @readOnly
  19568. * @type {Object}
  19569. */
  19570. pipelineContext: null
  19571. });
  19572. mixin(SeriesModel, dataFormatMixin);
  19573. mixin(SeriesModel, colorPaletteMixin);
  19574. /**
  19575. * MUST be called after `prepareSource` called
  19576. * Here we need to make auto series, especially for auto legend. But we
  19577. * do not modify series.name in option to avoid side effects.
  19578. */
  19579. function autoSeriesName(seriesModel) {
  19580. // User specified name has higher priority, otherwise it may cause
  19581. // series can not be queried unexpectedly.
  19582. var name = seriesModel.name;
  19583. if (!isNameSpecified(seriesModel)) {
  19584. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  19585. }
  19586. }
  19587. function getSeriesAutoName(seriesModel) {
  19588. var data = seriesModel.getRawData();
  19589. var dataDims = data.mapDimension('seriesName', true);
  19590. var nameArr = [];
  19591. each$1(dataDims, function (dataDim) {
  19592. var dimInfo = data.getDimensionInfo(dataDim);
  19593. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  19594. });
  19595. return nameArr.join(' ');
  19596. }
  19597. function dataTaskCount(context) {
  19598. return context.model.getRawData().count();
  19599. }
  19600. function dataTaskReset(context) {
  19601. var seriesModel = context.model;
  19602. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  19603. return dataTaskProgress;
  19604. }
  19605. function dataTaskProgress(param, context) {
  19606. // Avoid repead cloneShallow when data just created in reset.
  19607. if (param.end > context.outputData.count()) {
  19608. context.model.getRawData().cloneShallow(context.outputData);
  19609. }
  19610. }
  19611. // TODO refactor
  19612. function wrapData(data, seriesModel) {
  19613. each$1(data.CHANGABLE_METHODS, function (methodName) {
  19614. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  19615. });
  19616. }
  19617. function onDataSelfChange(seriesModel) {
  19618. var task = getCurrentTask(seriesModel);
  19619. if (task) {
  19620. // Consider case: filter, selectRange
  19621. task.setOutputEnd(this.count());
  19622. }
  19623. }
  19624. function getCurrentTask(seriesModel) {
  19625. var scheduler = (seriesModel.ecModel || {}).scheduler;
  19626. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  19627. if (pipeline) {
  19628. // When pipline finished, the currrentTask keep the last
  19629. // task (renderTask).
  19630. var task = pipeline.currentTask;
  19631. if (task) {
  19632. var agentStubMap = task.agentStubMap;
  19633. if (agentStubMap) {
  19634. task = agentStubMap.get(seriesModel.uid);
  19635. }
  19636. }
  19637. return task;
  19638. }
  19639. }
  19640. var Component = function () {
  19641. /**
  19642. * @type {module:zrender/container/Group}
  19643. * @readOnly
  19644. */
  19645. this.group = new Group();
  19646. /**
  19647. * @type {string}
  19648. * @readOnly
  19649. */
  19650. this.uid = getUID('viewComponent');
  19651. };
  19652. Component.prototype = {
  19653. constructor: Component,
  19654. init: function (ecModel, api) {},
  19655. render: function (componentModel, ecModel, api, payload) {},
  19656. dispose: function () {}
  19657. };
  19658. var componentProto = Component.prototype;
  19659. componentProto.updateView
  19660. = componentProto.updateLayout
  19661. = componentProto.updateVisual
  19662. = function (seriesModel, ecModel, api, payload) {
  19663. // Do nothing;
  19664. };
  19665. // Enable Component.extend.
  19666. enableClassExtend(Component);
  19667. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19668. enableClassManagement(Component, {registerWhenExtend: true});
  19669. /**
  19670. * @return {string} If large mode changed, return string 'reset';
  19671. */
  19672. var createRenderPlanner = function () {
  19673. var inner = makeInner();
  19674. return function (seriesModel) {
  19675. var fields = inner(seriesModel);
  19676. var pipelineContext = seriesModel.pipelineContext;
  19677. var originalLarge = fields.large;
  19678. var originalProgressive = fields.canProgressiveRender;
  19679. var large = fields.large = pipelineContext.large;
  19680. var progressive = fields.canProgressiveRender = pipelineContext.canProgressiveRender;
  19681. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  19682. };
  19683. };
  19684. var inner$5 = makeInner();
  19685. var renderPlanner = createRenderPlanner();
  19686. function Chart() {
  19687. /**
  19688. * @type {module:zrender/container/Group}
  19689. * @readOnly
  19690. */
  19691. this.group = new Group();
  19692. /**
  19693. * @type {string}
  19694. * @readOnly
  19695. */
  19696. this.uid = getUID('viewChart');
  19697. this.renderTask = createTask({
  19698. plan: renderTaskPlan,
  19699. reset: renderTaskReset
  19700. });
  19701. this.renderTask.context = {view: this};
  19702. }
  19703. Chart.prototype = {
  19704. type: 'chart',
  19705. /**
  19706. * Init the chart.
  19707. * @param {module:echarts/model/Global} ecModel
  19708. * @param {module:echarts/ExtensionAPI} api
  19709. */
  19710. init: function (ecModel, api) {},
  19711. /**
  19712. * Render the chart.
  19713. * @param {module:echarts/model/Series} seriesModel
  19714. * @param {module:echarts/model/Global} ecModel
  19715. * @param {module:echarts/ExtensionAPI} api
  19716. * @param {Object} payload
  19717. */
  19718. render: function (seriesModel, ecModel, api, payload) {},
  19719. /**
  19720. * Highlight series or specified data item.
  19721. * @param {module:echarts/model/Series} seriesModel
  19722. * @param {module:echarts/model/Global} ecModel
  19723. * @param {module:echarts/ExtensionAPI} api
  19724. * @param {Object} payload
  19725. */
  19726. highlight: function (seriesModel, ecModel, api, payload) {
  19727. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  19728. },
  19729. /**
  19730. * Downplay series or specified data item.
  19731. * @param {module:echarts/model/Series} seriesModel
  19732. * @param {module:echarts/model/Global} ecModel
  19733. * @param {module:echarts/ExtensionAPI} api
  19734. * @param {Object} payload
  19735. */
  19736. downplay: function (seriesModel, ecModel, api, payload) {
  19737. toggleHighlight(seriesModel.getData(), payload, 'normal');
  19738. },
  19739. /**
  19740. * Remove self.
  19741. * @param {module:echarts/model/Global} ecModel
  19742. * @param {module:echarts/ExtensionAPI} api
  19743. */
  19744. remove: function (ecModel, api) {
  19745. this.group.removeAll();
  19746. },
  19747. /**
  19748. * Dispose self.
  19749. * @param {module:echarts/model/Global} ecModel
  19750. * @param {module:echarts/ExtensionAPI} api
  19751. */
  19752. dispose: function () {},
  19753. /**
  19754. * Rendering preparation in progressive mode.
  19755. * @param {module:echarts/model/Series} seriesModel
  19756. * @param {module:echarts/model/Global} ecModel
  19757. * @param {module:echarts/ExtensionAPI} api
  19758. * @param {Object} payload
  19759. */
  19760. incrementalPrepareRender: null,
  19761. /**
  19762. * Render in progressive mode.
  19763. * @param {module:echarts/model/Series} seriesModel
  19764. * @param {module:echarts/model/Global} ecModel
  19765. * @param {module:echarts/ExtensionAPI} api
  19766. * @param {Object} payload
  19767. */
  19768. incrementalRender: null,
  19769. /**
  19770. * Update transform directly.
  19771. * @param {module:echarts/model/Series} seriesModel
  19772. * @param {module:echarts/model/Global} ecModel
  19773. * @param {module:echarts/ExtensionAPI} api
  19774. * @param {Object} payload
  19775. * @return {Object} {update: true}
  19776. */
  19777. updateTransform: null
  19778. /**
  19779. * The view contains the given point.
  19780. * @interface
  19781. * @param {Array.<number>} point
  19782. * @return {boolean}
  19783. */
  19784. // containPoint: function () {}
  19785. };
  19786. var chartProto = Chart.prototype;
  19787. chartProto.updateView
  19788. = chartProto.updateLayout
  19789. = chartProto.updateVisual
  19790. = function (seriesModel, ecModel, api, payload) {
  19791. this.render(seriesModel, ecModel, api, payload);
  19792. };
  19793. /**
  19794. * Set state of single element
  19795. * @param {module:zrender/Element} el
  19796. * @param {string} state
  19797. */
  19798. function elSetState(el, state) {
  19799. if (el) {
  19800. el.trigger(state);
  19801. if (el.type === 'group') {
  19802. for (var i = 0; i < el.childCount(); i++) {
  19803. elSetState(el.childAt(i), state);
  19804. }
  19805. }
  19806. }
  19807. }
  19808. /**
  19809. * @param {module:echarts/data/List} data
  19810. * @param {Object} payload
  19811. * @param {string} state 'normal'|'emphasis'
  19812. */
  19813. function toggleHighlight(data, payload, state) {
  19814. var dataIndex = queryDataIndex(data, payload);
  19815. if (dataIndex != null) {
  19816. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  19817. elSetState(data.getItemGraphicEl(dataIdx), state);
  19818. });
  19819. }
  19820. else {
  19821. data.eachItemGraphicEl(function (el) {
  19822. elSetState(el, state);
  19823. });
  19824. }
  19825. }
  19826. // Enable Chart.extend.
  19827. enableClassExtend(Chart, ['dispose']);
  19828. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19829. enableClassManagement(Chart, {registerWhenExtend: true});
  19830. Chart.markUpdateMethod = function (payload, methodName) {
  19831. inner$5(payload).updateMethod = methodName;
  19832. };
  19833. function renderTaskPlan(context) {
  19834. return renderPlanner(context.model);
  19835. }
  19836. function renderTaskReset(context) {
  19837. var seriesModel = context.model;
  19838. var ecModel = context.ecModel;
  19839. var api = context.api;
  19840. var payload = context.payload;
  19841. // ???! remove updateView updateVisual
  19842. var canProgressiveRender = seriesModel.pipelineContext.canProgressiveRender;
  19843. var view = context.view;
  19844. var updateMethod = payload && inner$5(payload).updateMethod;
  19845. var methodName = canProgressiveRender
  19846. ? 'incrementalPrepareRender'
  19847. : (updateMethod && view[updateMethod])
  19848. ? updateMethod
  19849. // `appendData` is also supported when data amount
  19850. // is less than progressive threshold.
  19851. : 'render';
  19852. if (methodName !== 'render') {
  19853. view[methodName](seriesModel, ecModel, api, payload);
  19854. }
  19855. return progressMethodMap[methodName];
  19856. }
  19857. var progressMethodMap = {
  19858. incrementalPrepareRender: {
  19859. progress: function (params, context) {
  19860. context.view.incrementalRender(
  19861. params, context.model, context.ecModel, context.api, context.payload
  19862. );
  19863. }
  19864. },
  19865. render: {
  19866. // Put view.render in `progress` to support appendData. But in this case
  19867. // view.render should not be called in reset, otherwise it will be called
  19868. // twise. Use `forceFirstProgress` to make sure that view.render is called
  19869. // in any cases.
  19870. forceFirstProgress: true,
  19871. progress: function (params, context) {
  19872. context.view.render(
  19873. context.model, context.ecModel, context.api, context.payload
  19874. );
  19875. }
  19876. }
  19877. };
  19878. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  19879. var RATE = '\0__throttleRate';
  19880. var THROTTLE_TYPE = '\0__throttleType';
  19881. /**
  19882. * @public
  19883. * @param {(Function)} fn
  19884. * @param {number} [delay=0] Unit: ms.
  19885. * @param {boolean} [debounce=false]
  19886. * true: If call interval less than `delay`, only the last call works.
  19887. * false: If call interval less than `delay, call works on fixed rate.
  19888. * @return {(Function)} throttled fn.
  19889. */
  19890. function throttle(fn, delay, debounce) {
  19891. var currCall;
  19892. var lastCall = 0;
  19893. var lastExec = 0;
  19894. var timer = null;
  19895. var diff;
  19896. var scope;
  19897. var args;
  19898. var debounceNextCall;
  19899. delay = delay || 0;
  19900. function exec() {
  19901. lastExec = (new Date()).getTime();
  19902. timer = null;
  19903. fn.apply(scope, args || []);
  19904. }
  19905. var cb = function () {
  19906. currCall = (new Date()).getTime();
  19907. scope = this;
  19908. args = arguments;
  19909. var thisDelay = debounceNextCall || delay;
  19910. var thisDebounce = debounceNextCall || debounce;
  19911. debounceNextCall = null;
  19912. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  19913. clearTimeout(timer);
  19914. if (thisDebounce) {
  19915. timer = setTimeout(exec, thisDelay);
  19916. }
  19917. else {
  19918. if (diff >= 0) {
  19919. exec();
  19920. }
  19921. else {
  19922. timer = setTimeout(exec, -diff);
  19923. }
  19924. }
  19925. lastCall = currCall;
  19926. };
  19927. /**
  19928. * Clear throttle.
  19929. * @public
  19930. */
  19931. cb.clear = function () {
  19932. if (timer) {
  19933. clearTimeout(timer);
  19934. timer = null;
  19935. }
  19936. };
  19937. /**
  19938. * Enable debounce once.
  19939. */
  19940. cb.debounceNextCall = function (debounceDelay) {
  19941. debounceNextCall = debounceDelay;
  19942. };
  19943. return cb;
  19944. }
  19945. /**
  19946. * Create throttle method or update throttle rate.
  19947. *
  19948. * @example
  19949. * ComponentView.prototype.render = function () {
  19950. * ...
  19951. * throttle.createOrUpdate(
  19952. * this,
  19953. * '_dispatchAction',
  19954. * this.model.get('throttle'),
  19955. * 'fixRate'
  19956. * );
  19957. * };
  19958. * ComponentView.prototype.remove = function () {
  19959. * throttle.clear(this, '_dispatchAction');
  19960. * };
  19961. * ComponentView.prototype.dispose = function () {
  19962. * throttle.clear(this, '_dispatchAction');
  19963. * };
  19964. *
  19965. * @public
  19966. * @param {Object} obj
  19967. * @param {string} fnAttr
  19968. * @param {number} [rate]
  19969. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  19970. * @return {Function} throttled function.
  19971. */
  19972. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  19973. var fn = obj[fnAttr];
  19974. if (!fn) {
  19975. return;
  19976. }
  19977. var originFn = fn[ORIGIN_METHOD] || fn;
  19978. var lastThrottleType = fn[THROTTLE_TYPE];
  19979. var lastRate = fn[RATE];
  19980. if (lastRate !== rate || lastThrottleType !== throttleType) {
  19981. if (rate == null || !throttleType) {
  19982. return (obj[fnAttr] = originFn);
  19983. }
  19984. fn = obj[fnAttr] = throttle(
  19985. originFn, rate, throttleType === 'debounce'
  19986. );
  19987. fn[ORIGIN_METHOD] = originFn;
  19988. fn[THROTTLE_TYPE] = throttleType;
  19989. fn[RATE] = rate;
  19990. }
  19991. return fn;
  19992. }
  19993. /**
  19994. * Clear throttle. Example see throttle.createOrUpdate.
  19995. *
  19996. * @public
  19997. * @param {Object} obj
  19998. * @param {string} fnAttr
  19999. */
  20000. function clear(obj, fnAttr) {
  20001. var fn = obj[fnAttr];
  20002. if (fn && fn[ORIGIN_METHOD]) {
  20003. obj[fnAttr] = fn[ORIGIN_METHOD];
  20004. }
  20005. }
  20006. var seriesColor = {
  20007. createOnAllSeries: true,
  20008. performRawSeries: true,
  20009. reset: function (seriesModel, ecModel) {
  20010. var data = seriesModel.getData();
  20011. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  20012. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  20013. || seriesModel.getColorFromPalette(
  20014. // TODO series count changed.
  20015. seriesModel.name, null, ecModel.getSeriesCount()
  20016. ); // Default color
  20017. // FIXME Set color function or use the platte color
  20018. data.setVisual('color', color);
  20019. // Only visible series has each data be visual encoded
  20020. if (!ecModel.isSeriesFiltered(seriesModel)) {
  20021. if (typeof color === 'function' && !(color instanceof Gradient)) {
  20022. data.each(function (idx) {
  20023. data.setItemVisual(
  20024. idx, 'color', color(seriesModel.getDataParams(idx))
  20025. );
  20026. });
  20027. }
  20028. // itemStyle in each data item
  20029. var dataEach = function (data, idx) {
  20030. var itemModel = data.getItemModel(idx);
  20031. var color = itemModel.get(colorAccessPath, true);
  20032. if (color != null) {
  20033. data.setItemVisual(idx, 'color', color);
  20034. }
  20035. };
  20036. return { dataEach: data.hasItemOption ? dataEach : null };
  20037. }
  20038. }
  20039. };
  20040. var lang = {
  20041. toolbox: {
  20042. brush: {
  20043. title: {
  20044. rect: 'Box Select',
  20045. polygon: 'Lasso Select',
  20046. lineX: 'Horizontally Select',
  20047. lineY: 'Vertically Select',
  20048. keep: 'Keep Selections',
  20049. clear: 'Clear Selections'
  20050. }
  20051. },
  20052. dataView: {
  20053. title: 'Data View',
  20054. lang: ['Data View', 'Close', 'Refresh']
  20055. },
  20056. dataZoom: {
  20057. title: {
  20058. zoom: 'Zoom',
  20059. back: 'Zoom Reset'
  20060. }
  20061. },
  20062. magicType: {
  20063. title: {
  20064. line: 'Switch to Line Chart',
  20065. bar: 'Switch to Bar Chart',
  20066. stack: 'Stack',
  20067. tiled: 'Tile'
  20068. }
  20069. },
  20070. restore: {
  20071. title: 'Restore'
  20072. },
  20073. saveAsImage: {
  20074. title: 'Save as Image',
  20075. lang: ['Right Click to Save Image']
  20076. }
  20077. }
  20078. };
  20079. var aria = function (dom, ecModel) {
  20080. var ariaModel = ecModel.getModel('aria');
  20081. if (!ariaModel.get('show')) {
  20082. return;
  20083. }
  20084. else if (ariaModel.get('description')) {
  20085. dom.setAttribute('aria-label', ariaModel.get('description'));
  20086. return;
  20087. }
  20088. var seriesCnt = 0;
  20089. ecModel.eachSeries(function (seriesModel, idx) {
  20090. ++seriesCnt;
  20091. }, this);
  20092. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  20093. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  20094. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  20095. var ariaLabel;
  20096. if (seriesCnt < 1) {
  20097. // No series, no aria label
  20098. return;
  20099. }
  20100. else {
  20101. var title = getTitle();
  20102. if (title) {
  20103. ariaLabel = replace(getConfig('general.withTitle'), {
  20104. title: title
  20105. });
  20106. }
  20107. else {
  20108. ariaLabel = getConfig('general.withoutTitle');
  20109. }
  20110. var seriesLabels = [];
  20111. var prefix = seriesCnt > 1
  20112. ? 'series.multiple.prefix'
  20113. : 'series.single.prefix';
  20114. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  20115. ecModel.eachSeries(function (seriesModel, idx) {
  20116. if (idx < displaySeriesCnt) {
  20117. var seriesLabel;
  20118. var seriesName = seriesModel.get('name');
  20119. var seriesTpl = 'series.'
  20120. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  20121. seriesLabel = getConfig(seriesName
  20122. ? seriesTpl + 'withName'
  20123. : seriesTpl + 'withoutName');
  20124. seriesLabel = replace(seriesLabel, {
  20125. seriesId: seriesModel.seriesIndex,
  20126. seriesName: seriesModel.get('name'),
  20127. seriesType: getSeriesTypeName(seriesModel.subType)
  20128. });
  20129. var data = seriesModel.getData();
  20130. window.data = data;
  20131. if (data.count() > maxDataCnt) {
  20132. // Show part of data
  20133. seriesLabel += replace(getConfig('data.partialData'), {
  20134. displayCnt: maxDataCnt
  20135. });
  20136. }
  20137. else {
  20138. seriesLabel += getConfig('data.allData');
  20139. }
  20140. var dataLabels = [];
  20141. for (var i = 0; i < data.count(); i++) {
  20142. if (i < maxDataCnt) {
  20143. var name = data.getName(i);
  20144. var value = retrieveRawValue(data, i);
  20145. dataLabels.push(
  20146. replace(
  20147. name
  20148. ? getConfig('data.withName')
  20149. : getConfig('data.withoutName'),
  20150. {
  20151. name: name,
  20152. value: value
  20153. }
  20154. )
  20155. );
  20156. }
  20157. }
  20158. seriesLabel += dataLabels
  20159. .join(getConfig('data.separator.middle'))
  20160. + getConfig('data.separator.end');
  20161. seriesLabels.push(seriesLabel);
  20162. }
  20163. });
  20164. ariaLabel += seriesLabels
  20165. .join(getConfig('series.multiple.separator.middle'))
  20166. + getConfig('series.multiple.separator.end');
  20167. dom.setAttribute('aria-label', ariaLabel);
  20168. }
  20169. function replace(str, keyValues) {
  20170. if (typeof str !== 'string') {
  20171. return str;
  20172. }
  20173. var result = str;
  20174. each$1(keyValues, function (value, key) {
  20175. result = result.replace(
  20176. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  20177. value
  20178. );
  20179. });
  20180. return result;
  20181. }
  20182. function getConfig(path) {
  20183. var userConfig = ariaModel.get(path);
  20184. if (userConfig == null) {
  20185. var pathArr = path.split('.');
  20186. var result = lang.aria;
  20187. for (var i = 0; i < pathArr.length; ++i) {
  20188. result = result[pathArr[i]];
  20189. }
  20190. return result;
  20191. }
  20192. else {
  20193. return userConfig;
  20194. }
  20195. }
  20196. function getTitle() {
  20197. var title = ecModel.getModel('title').option;
  20198. if (title && title.length) {
  20199. title = title[0];
  20200. }
  20201. return title && title.text;
  20202. }
  20203. function getSeriesTypeName(type) {
  20204. return lang.series.typeNames[type] || '自定义图';
  20205. }
  20206. };
  20207. var PI$1 = Math.PI;
  20208. /**
  20209. * @param {module:echarts/ExtensionAPI} api
  20210. * @param {Object} [opts]
  20211. * @param {string} [opts.text]
  20212. * @param {string} [opts.color]
  20213. * @param {string} [opts.textColor]
  20214. * @return {module:zrender/Element}
  20215. */
  20216. var loadingDefault = function (api, opts) {
  20217. opts = opts || {};
  20218. defaults(opts, {
  20219. text: 'loading',
  20220. color: '#c23531',
  20221. textColor: '#000',
  20222. maskColor: 'rgba(255, 255, 255, 0.8)',
  20223. zlevel: 0
  20224. });
  20225. var mask = new Rect({
  20226. style: {
  20227. fill: opts.maskColor
  20228. },
  20229. zlevel: opts.zlevel,
  20230. z: 10000
  20231. });
  20232. var arc = new Arc({
  20233. shape: {
  20234. startAngle: -PI$1 / 2,
  20235. endAngle: -PI$1 / 2 + 0.1,
  20236. r: 10
  20237. },
  20238. style: {
  20239. stroke: opts.color,
  20240. lineCap: 'round',
  20241. lineWidth: 5
  20242. },
  20243. zlevel: opts.zlevel,
  20244. z: 10001
  20245. });
  20246. var labelRect = new Rect({
  20247. style: {
  20248. fill: 'none',
  20249. text: opts.text,
  20250. textPosition: 'right',
  20251. textDistance: 10,
  20252. textFill: opts.textColor
  20253. },
  20254. zlevel: opts.zlevel,
  20255. z: 10001
  20256. });
  20257. arc.animateShape(true)
  20258. .when(1000, {
  20259. endAngle: PI$1 * 3 / 2
  20260. })
  20261. .start('circularInOut');
  20262. arc.animateShape(true)
  20263. .when(1000, {
  20264. startAngle: PI$1 * 3 / 2
  20265. })
  20266. .delay(300)
  20267. .start('circularInOut');
  20268. var group = new Group();
  20269. group.add(arc);
  20270. group.add(labelRect);
  20271. group.add(mask);
  20272. // Inject resize
  20273. group.resize = function () {
  20274. var cx = api.getWidth() / 2;
  20275. var cy = api.getHeight() / 2;
  20276. arc.setShape({
  20277. cx: cx,
  20278. cy: cy
  20279. });
  20280. var r = arc.shape.r;
  20281. labelRect.setShape({
  20282. x: cx - r,
  20283. y: cy - r,
  20284. width: r * 2,
  20285. height: r * 2
  20286. });
  20287. mask.setShape({
  20288. x: 0,
  20289. y: 0,
  20290. width: api.getWidth(),
  20291. height: api.getHeight()
  20292. });
  20293. };
  20294. group.resize();
  20295. return group;
  20296. };
  20297. /**
  20298. * @module echarts/stream/Scheduler
  20299. */
  20300. /**
  20301. * @constructor
  20302. */
  20303. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  20304. // this._pipelineMap = createHashMap();
  20305. this.ecInstance = ecInstance;
  20306. this.api = api;
  20307. this.unfinished;
  20308. // Fix current processors in case that in some rear cases that
  20309. // processors might be registered after echarts instance created.
  20310. // Register processors incrementally for a echarts instance is
  20311. // not supported by this stream architecture.
  20312. this._dataProcessorHandlers = dataProcessorHandlers.slice();
  20313. this._visualHandlers = visualHandlers.slice();
  20314. /**
  20315. * @private
  20316. * @type {
  20317. * [handlerUID: string]: {
  20318. * seriesTaskMap?: {
  20319. * [seriesUID: string]: Task
  20320. * },
  20321. * overallTask?: Task
  20322. * }
  20323. * }
  20324. */
  20325. this._stageTaskMap = createHashMap();
  20326. }
  20327. var proto = Scheduler.prototype;
  20328. // If seriesModel provided, incremental threshold is check by series data.
  20329. proto.getPerformArgs = function (task, isBlock) {
  20330. // For overall task
  20331. if (!task.__pipeline) {
  20332. return;
  20333. }
  20334. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  20335. var pCtx = pipeline.context;
  20336. var incremental = !isBlock
  20337. && pipeline.progressiveEnabled
  20338. && (!pCtx || pCtx.canProgressiveRender)
  20339. && task.__idxInPipeline > pipeline.bockIndex;
  20340. return {step: incremental ? pipeline.step : null};
  20341. };
  20342. proto.getPipeline = function (pipelineId) {
  20343. return this._pipelineMap.get(pipelineId);
  20344. };
  20345. /**
  20346. * Current, progressive rendering starts from visual and layout.
  20347. * Always detect render mode in the same stage, avoiding that incorrect
  20348. * detection caused by data filtering.
  20349. * Caution:
  20350. * `updateStreamModes` use `seriesModel.getData()`.
  20351. */
  20352. proto.updateStreamModes = function (seriesModel, view) {
  20353. var pipeline = this._pipelineMap.get(seriesModel.uid);
  20354. var data = seriesModel.getData();
  20355. var dataLen = data.count();
  20356. // `canProgressiveRender` means that can render progressively in each
  20357. // animation frame. Note that some types of series do not provide
  20358. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  20359. // use the term `incremental` but not `progressive` to describe the
  20360. // case that `chart.appendData`.
  20361. var canProgressiveRender = pipeline.progressiveEnabled
  20362. && view.incrementalPrepareRender
  20363. && dataLen >= pipeline.threshold;
  20364. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  20365. seriesModel.pipelineContext = pipeline.context = {
  20366. canProgressiveRender: canProgressiveRender,
  20367. large: large
  20368. };
  20369. };
  20370. proto.restorePipelines = function (ecModel) {
  20371. var scheduler = this;
  20372. var pipelineMap = scheduler._pipelineMap = createHashMap();
  20373. ecModel.eachSeries(function (seriesModel) {
  20374. var progressive = seriesModel.getProgressive();
  20375. var pipelineId = seriesModel.uid;
  20376. pipelineMap.set(pipelineId, {
  20377. id: pipelineId,
  20378. head: null,
  20379. tail: null,
  20380. threshold: seriesModel.getProgressiveThreshold(),
  20381. progressiveEnabled: progressive
  20382. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  20383. bockIndex: -1,
  20384. step: progressive || 700, // ??? Temporarily number
  20385. count: 0
  20386. });
  20387. pipe(scheduler, seriesModel, seriesModel.dataTask);
  20388. });
  20389. };
  20390. proto.prepareStageTasks = function () {
  20391. var stageTaskMap = this._stageTaskMap;
  20392. var ecModel = this.ecInstance.getModel();
  20393. var api = this.api;
  20394. each$1([this._dataProcessorHandlers, this._visualHandlers], function (stageHandlers) {
  20395. each$1(stageHandlers, function (handler) {
  20396. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  20397. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  20398. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  20399. }, this);
  20400. }, this);
  20401. };
  20402. proto.prepareView = function (view, model, ecModel, api) {
  20403. var renderTask = view.renderTask;
  20404. var context = renderTask.context;
  20405. context.model = model;
  20406. context.ecModel = ecModel;
  20407. context.api = api;
  20408. renderTask.__block = !view.incrementalPrepareRender;
  20409. pipe(this, model, renderTask);
  20410. };
  20411. proto.performDataProcessorTasks = function (ecModel, payload) {
  20412. // If we do not use `block` here, it should be considered when to update modes.
  20413. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  20414. };
  20415. // opt
  20416. // opt.visualType: 'visual' or 'layout'
  20417. // opt.setDirty
  20418. proto.performVisualTasks = function (ecModel, payload, opt) {
  20419. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  20420. };
  20421. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  20422. opt = opt || {};
  20423. var unfinished;
  20424. each$1(stageHandlers, function (stageHandler, idx) {
  20425. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  20426. return;
  20427. }
  20428. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  20429. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  20430. var overallTask = stageHandlerRecord.overallTask;
  20431. if (overallTask) {
  20432. var overallNeedDirty;
  20433. var agentStubMap = overallTask.agentStubMap;
  20434. agentStubMap.each(function (stub) {
  20435. if (needSetDirty(opt, stub)) {
  20436. stub.dirty();
  20437. overallNeedDirty = true;
  20438. }
  20439. });
  20440. overallNeedDirty && overallTask.dirty();
  20441. updatePayload(overallTask, payload);
  20442. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  20443. // Execute stubs firstly, which may set the overall task dirty,
  20444. // then execute the overall task. And stub will call seriesModel.setData,
  20445. // which ensures that in the overallTask seriesModel.getData() will not
  20446. // return incorrect data.
  20447. agentStubMap.each(function (stub) {
  20448. stub.perform(performArgs);
  20449. });
  20450. unfinished |= overallTask.perform(performArgs);
  20451. }
  20452. else if (seriesTaskMap) {
  20453. seriesTaskMap.each(function (task, pipelineId) {
  20454. if (needSetDirty(opt, task)) {
  20455. task.dirty();
  20456. }
  20457. var performArgs = scheduler.getPerformArgs(task, opt.block);
  20458. performArgs.skip = !stageHandler.performRawSeries
  20459. && ecModel.isSeriesFiltered(task.context.model);
  20460. updatePayload(task, payload);
  20461. unfinished |= task.perform(performArgs);
  20462. });
  20463. }
  20464. });
  20465. function needSetDirty(opt, task) {
  20466. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  20467. }
  20468. scheduler.unfinished |= unfinished;
  20469. }
  20470. proto.performSeriesTasks = function (ecModel) {
  20471. var unfinished;
  20472. ecModel.eachSeries(function (seriesModel) {
  20473. // Progress to the end for dataInit and dataRestore.
  20474. unfinished |= seriesModel.dataTask.perform();
  20475. });
  20476. this.unfinished |= unfinished;
  20477. };
  20478. proto.plan = function () {
  20479. // Travel pipelines, check block.
  20480. this._pipelineMap.each(function (pipeline) {
  20481. var task = pipeline.tail;
  20482. do {
  20483. if (task.__block) {
  20484. pipeline.bockIndex = task.__idxInPipeline;
  20485. break;
  20486. }
  20487. task = task.getUpstream();
  20488. }
  20489. while (task);
  20490. });
  20491. };
  20492. var updatePayload = proto.updatePayload = function (task, payload) {
  20493. payload !== 'remain' && (task.context.payload = payload);
  20494. };
  20495. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20496. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  20497. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  20498. var seriesType = stageHandler.seriesType;
  20499. var getTargetSeries = stageHandler.getTargetSeries;
  20500. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  20501. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  20502. // it works but it may cause other irrelevant charts blocked.
  20503. if (stageHandler.createOnAllSeries) {
  20504. ecModel.eachRawSeries(create);
  20505. }
  20506. else if (seriesType) {
  20507. ecModel.eachRawSeriesByType(seriesType, create);
  20508. }
  20509. else if (getTargetSeries) {
  20510. getTargetSeries(ecModel, api).each(create);
  20511. }
  20512. function create(seriesModel) {
  20513. var pipelineId = seriesModel.uid;
  20514. // Init tasks for each seriesModel only once.
  20515. // Reuse original task instance.
  20516. var task = seriesTaskMap.get(pipelineId)
  20517. || seriesTaskMap.set(pipelineId, createTask({
  20518. plan: seriesTaskPlan,
  20519. reset: seriesTaskReset,
  20520. count: seriesTaskCount
  20521. }));
  20522. task.context = {
  20523. model: seriesModel,
  20524. ecModel: ecModel,
  20525. api: api,
  20526. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  20527. plan: stageHandler.plan,
  20528. reset: stageHandler.reset,
  20529. scheduler: scheduler
  20530. };
  20531. pipe(scheduler, seriesModel, task);
  20532. }
  20533. // Clear unused series tasks.
  20534. var pipelineMap = scheduler._pipelineMap;
  20535. seriesTaskMap.each(function (task, pipelineId) {
  20536. if (!pipelineMap.get(pipelineId)) {
  20537. task.dispose();
  20538. seriesTaskMap.removeKey(pipelineId);
  20539. }
  20540. });
  20541. }
  20542. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  20543. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  20544. // For overall task, the function only be called on reset stage.
  20545. || createTask({reset: overallTaskReset});
  20546. overallTask.context = {
  20547. ecModel: ecModel,
  20548. api: api,
  20549. overallReset: stageHandler.overallReset,
  20550. scheduler: scheduler
  20551. };
  20552. // Reuse orignal stubs.
  20553. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  20554. var seriesType = stageHandler.seriesType;
  20555. var getTargetSeries = stageHandler.getTargetSeries;
  20556. var overallProgress = true;
  20557. var isOverallFilter = stageHandler.isOverallFilter;
  20558. // An overall task with seriesType detected or has `getTargetSeries`, we add
  20559. // stub in each pipelines, it will set the overall task dirty when the pipeline
  20560. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  20561. // we set the pipeline block.
  20562. if (seriesType) {
  20563. ecModel.eachRawSeriesByType(seriesType, createStub);
  20564. }
  20565. else if (getTargetSeries) {
  20566. getTargetSeries(ecModel, api).each(createStub);
  20567. }
  20568. // Otherwise, (usually it is legancy case), the overall task will only be
  20569. // executed when upstream dirty. Otherwise the progressive rendering of all
  20570. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  20571. // dirty info from upsteam.
  20572. else {
  20573. overallProgress = false;
  20574. each$1(ecModel.getSeries(), createStub);
  20575. }
  20576. function createStub(seriesModel) {
  20577. var pipelineId = seriesModel.uid;
  20578. var stub = agentStubMap.get(pipelineId) || agentStubMap.set(pipelineId, createTask(
  20579. {reset: stubReset, onDirty: stubOnDirty}
  20580. ));
  20581. stub.context = {
  20582. model: seriesModel,
  20583. overallProgress: overallProgress,
  20584. isOverallFilter: isOverallFilter
  20585. };
  20586. stub.agent = overallTask;
  20587. stub.__block = overallProgress;
  20588. pipe(scheduler, seriesModel, stub);
  20589. }
  20590. // Clear unused stubs.
  20591. var pipelineMap = scheduler._pipelineMap;
  20592. agentStubMap.each(function (stub, pipelineId) {
  20593. if (!pipelineMap.get(pipelineId)) {
  20594. stub.dispose();
  20595. agentStubMap.removeKey(pipelineId);
  20596. }
  20597. });
  20598. }
  20599. function overallTaskReset(context) {
  20600. context.overallReset(
  20601. context.ecModel, context.api, context.payload
  20602. );
  20603. }
  20604. function stubReset(context, upstreamContext) {
  20605. return context.overallProgress && stubProgress;
  20606. }
  20607. function stubProgress() {
  20608. this.agent.dirty();
  20609. this.getDownstream().dirty();
  20610. }
  20611. function stubOnDirty() {
  20612. this.agent && this.agent.dirty();
  20613. }
  20614. function seriesTaskPlan(context) {
  20615. return context.plan && context.plan(
  20616. context.model, context.ecModel, context.api, context.payload
  20617. );
  20618. }
  20619. function seriesTaskReset(context) {
  20620. if (context.useClearVisual) {
  20621. context.data.clearAllVisual();
  20622. }
  20623. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  20624. context.model, context.ecModel, context.api, context.payload
  20625. ));
  20626. if (resetDefines.length) {
  20627. return seriesTaskProgress;
  20628. }
  20629. }
  20630. function seriesTaskProgress(params, context) {
  20631. var data = context.data;
  20632. var resetDefines = context.resetDefines;
  20633. for (var k = 0; k < resetDefines.length; k++) {
  20634. var resetDefine = resetDefines[k];
  20635. if (resetDefine && resetDefine.dataEach) {
  20636. for (var i = params.start; i < params.end; i++) {
  20637. resetDefine.dataEach(data, i);
  20638. }
  20639. }
  20640. else if (resetDefine && resetDefine.progress) {
  20641. resetDefine.progress(params, data);
  20642. }
  20643. }
  20644. }
  20645. function seriesTaskCount(context) {
  20646. return context.data.count();
  20647. }
  20648. function pipe(scheduler, seriesModel, task) {
  20649. var pipelineId = seriesModel.uid;
  20650. var pipeline = scheduler._pipelineMap.get(pipelineId);
  20651. !pipeline.head && (pipeline.head = task);
  20652. pipeline.tail && pipeline.tail.pipe(task);
  20653. pipeline.tail = task;
  20654. task.__idxInPipeline = pipeline.count++;
  20655. task.__pipeline = pipeline;
  20656. }
  20657. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  20658. if (isFunction$1(stageHandler)) {
  20659. stageHandler = {
  20660. overallReset: stageHandler,
  20661. seriesType: detectSeriseType(stageHandler)
  20662. };
  20663. }
  20664. stageHandler.uid = getUID('stageHandler');
  20665. visualType && (stageHandler.visualType = visualType);
  20666. return stageHandler;
  20667. };
  20668. /**
  20669. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  20670. * To ensure that they can work normally, they should work in block mode, that is,
  20671. * they should not be started util the previous tasks finished. So they cause the
  20672. * progressive rendering disabled. We try to detect the series type, to narrow down
  20673. * the block range to only the series type they concern, but not all series.
  20674. */
  20675. function detectSeriseType(legacyFunc) {
  20676. seriesType = null;
  20677. try {
  20678. // Assume there is no async when calling `eachSeriesByType`.
  20679. legacyFunc(ecModelMock, apiMock);
  20680. }
  20681. catch (e) {
  20682. }
  20683. return seriesType;
  20684. }
  20685. var ecModelMock = {};
  20686. var apiMock = {};
  20687. var seriesType;
  20688. mockMethods(ecModelMock, GlobalModel);
  20689. mockMethods(apiMock, ExtensionAPI);
  20690. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  20691. seriesType = type;
  20692. };
  20693. ecModelMock.eachComponent = function (cond) {
  20694. if (cond.mainType === 'series' && cond.subType) {
  20695. seriesType = cond.subType;
  20696. }
  20697. };
  20698. function mockMethods(target, Clz) {
  20699. for (var name in Clz.prototype) {
  20700. // Do not use hasOwnProperty
  20701. target[name] = noop;
  20702. }
  20703. }
  20704. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  20705. var lightTheme = {
  20706. color: colorAll,
  20707. colorLayer: [
  20708. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  20709. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  20710. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  20711. colorAll
  20712. ]
  20713. };
  20714. var contrastColor = '#eee';
  20715. var axisCommon = function () {
  20716. return {
  20717. axisLine: {
  20718. lineStyle: {
  20719. color: contrastColor
  20720. }
  20721. },
  20722. axisTick: {
  20723. lineStyle: {
  20724. color: contrastColor
  20725. }
  20726. },
  20727. axisLabel: {
  20728. textStyle: {
  20729. color: contrastColor
  20730. }
  20731. },
  20732. splitLine: {
  20733. lineStyle: {
  20734. type: 'dashed',
  20735. color: '#aaa'
  20736. }
  20737. },
  20738. splitArea: {
  20739. areaStyle: {
  20740. color: contrastColor
  20741. }
  20742. }
  20743. };
  20744. };
  20745. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  20746. var theme = {
  20747. color: colorPalette,
  20748. backgroundColor: '#333',
  20749. tooltip: {
  20750. axisPointer: {
  20751. lineStyle: {
  20752. color: contrastColor
  20753. },
  20754. crossStyle: {
  20755. color: contrastColor
  20756. }
  20757. }
  20758. },
  20759. legend: {
  20760. textStyle: {
  20761. color: contrastColor
  20762. }
  20763. },
  20764. textStyle: {
  20765. color: contrastColor
  20766. },
  20767. title: {
  20768. textStyle: {
  20769. color: contrastColor
  20770. }
  20771. },
  20772. toolbox: {
  20773. iconStyle: {
  20774. normal: {
  20775. borderColor: contrastColor
  20776. }
  20777. }
  20778. },
  20779. dataZoom: {
  20780. textStyle: {
  20781. color: contrastColor
  20782. }
  20783. },
  20784. visualMap: {
  20785. textStyle: {
  20786. color: contrastColor
  20787. }
  20788. },
  20789. timeline: {
  20790. lineStyle: {
  20791. color: contrastColor
  20792. },
  20793. itemStyle: {
  20794. normal: {
  20795. color: colorPalette[1]
  20796. }
  20797. },
  20798. label: {
  20799. normal: {
  20800. textStyle: {
  20801. color: contrastColor
  20802. }
  20803. }
  20804. },
  20805. controlStyle: {
  20806. normal: {
  20807. color: contrastColor,
  20808. borderColor: contrastColor
  20809. }
  20810. }
  20811. },
  20812. timeAxis: axisCommon(),
  20813. logAxis: axisCommon(),
  20814. valueAxis: axisCommon(),
  20815. categoryAxis: axisCommon(),
  20816. line: {
  20817. symbol: 'circle'
  20818. },
  20819. graph: {
  20820. color: colorPalette
  20821. },
  20822. gauge: {
  20823. title: {
  20824. textStyle: {
  20825. color: contrastColor
  20826. }
  20827. }
  20828. },
  20829. candlestick: {
  20830. itemStyle: {
  20831. normal: {
  20832. color: '#FD1050',
  20833. color0: '#0CF49B',
  20834. borderColor: '#FD1050',
  20835. borderColor0: '#0CF49B'
  20836. }
  20837. }
  20838. }
  20839. };
  20840. theme.categoryAxis.splitLine.show = false;
  20841. /*!
  20842. * ECharts, a free, powerful charting and visualization library.
  20843. *
  20844. * Copyright (c) 2017, Baidu Inc.
  20845. * All rights reserved.
  20846. *
  20847. * LICENSE
  20848. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  20849. */
  20850. var assert = assert$1;
  20851. var each = each$1;
  20852. var isFunction = isFunction$1;
  20853. var isObject = isObject$1;
  20854. var parseClassType = ComponentModel.parseClassType;
  20855. var version = '4.0.4';
  20856. var dependencies = {
  20857. zrender: '4.0.3'
  20858. };
  20859. var TEST_FRAME_REMAIN_TIME = 1;
  20860. var PRIORITY_PROCESSOR_FILTER = 1000;
  20861. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  20862. var PRIORITY_VISUAL_LAYOUT = 1000;
  20863. var PRIORITY_VISUAL_GLOBAL = 2000;
  20864. var PRIORITY_VISUAL_CHART = 3000;
  20865. var PRIORITY_VISUAL_COMPONENT = 4000;
  20866. // FIXME
  20867. // necessary?
  20868. var PRIORITY_VISUAL_BRUSH = 5000;
  20869. var PRIORITY = {
  20870. PROCESSOR: {
  20871. FILTER: PRIORITY_PROCESSOR_FILTER,
  20872. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  20873. },
  20874. VISUAL: {
  20875. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  20876. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  20877. CHART: PRIORITY_VISUAL_CHART,
  20878. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  20879. BRUSH: PRIORITY_VISUAL_BRUSH
  20880. }
  20881. };
  20882. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  20883. // where they must not be invoked nestedly, except the only case: invoke
  20884. // dispatchAction with updateMethod "none" in main process.
  20885. // This flag is used to carry out this rule.
  20886. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  20887. var IN_MAIN_PROCESS = '__flagInMainProcess';
  20888. var OPTION_UPDATED = '__optionUpdated';
  20889. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  20890. function createRegisterEventWithLowercaseName(method) {
  20891. return function (eventName, handler, context) {
  20892. // Event name is all lowercase
  20893. eventName = eventName && eventName.toLowerCase();
  20894. Eventful.prototype[method].call(this, eventName, handler, context);
  20895. };
  20896. }
  20897. /**
  20898. * @module echarts~MessageCenter
  20899. */
  20900. function MessageCenter() {
  20901. Eventful.call(this);
  20902. }
  20903. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  20904. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  20905. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  20906. mixin(MessageCenter, Eventful);
  20907. /**
  20908. * @module echarts~ECharts
  20909. */
  20910. function ECharts(dom, theme$$1, opts) {
  20911. opts = opts || {};
  20912. // Get theme by name
  20913. if (typeof theme$$1 === 'string') {
  20914. theme$$1 = themeStorage[theme$$1];
  20915. }
  20916. /**
  20917. * @type {string}
  20918. */
  20919. this.id;
  20920. /**
  20921. * Group id
  20922. * @type {string}
  20923. */
  20924. this.group;
  20925. /**
  20926. * @type {HTMLElement}
  20927. * @private
  20928. */
  20929. this._dom = dom;
  20930. var defaultRenderer = 'canvas';
  20931. if (__DEV__) {
  20932. defaultRenderer = (
  20933. typeof window === 'undefined' ? global : window
  20934. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  20935. }
  20936. /**
  20937. * @type {module:zrender/ZRender}
  20938. * @private
  20939. */
  20940. var zr = this._zr = init$1(dom, {
  20941. renderer: opts.renderer || defaultRenderer,
  20942. devicePixelRatio: opts.devicePixelRatio,
  20943. width: opts.width,
  20944. height: opts.height
  20945. });
  20946. /**
  20947. * Expect 60 pfs.
  20948. * @type {Function}
  20949. * @private
  20950. */
  20951. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  20952. var theme$$1 = clone(theme$$1);
  20953. theme$$1 && backwardCompat(theme$$1, true);
  20954. /**
  20955. * @type {Object}
  20956. * @private
  20957. */
  20958. this._theme = theme$$1;
  20959. /**
  20960. * @type {Array.<module:echarts/view/Chart>}
  20961. * @private
  20962. */
  20963. this._chartsViews = [];
  20964. /**
  20965. * @type {Object.<string, module:echarts/view/Chart>}
  20966. * @private
  20967. */
  20968. this._chartsMap = {};
  20969. /**
  20970. * @type {Array.<module:echarts/view/Component>}
  20971. * @private
  20972. */
  20973. this._componentsViews = [];
  20974. /**
  20975. * @type {Object.<string, module:echarts/view/Component>}
  20976. * @private
  20977. */
  20978. this._componentsMap = {};
  20979. /**
  20980. * @type {module:echarts/CoordinateSystem}
  20981. * @private
  20982. */
  20983. this._coordSysMgr = new CoordinateSystemManager();
  20984. /**
  20985. * @type {module:echarts/ExtensionAPI}
  20986. * @private
  20987. */
  20988. var api = this._api = createExtensionAPI(this);
  20989. // Sort on demand
  20990. function prioritySortFunc(a, b) {
  20991. return a.__prio - b.__prio;
  20992. }
  20993. sort(visualFuncs, prioritySortFunc);
  20994. sort(dataProcessorFuncs, prioritySortFunc);
  20995. /**
  20996. * @type {module:echarts/stream/Scheduler}
  20997. */
  20998. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  20999. Eventful.call(this);
  21000. /**
  21001. * @type {module:echarts~MessageCenter}
  21002. * @private
  21003. */
  21004. this._messageCenter = new MessageCenter();
  21005. // Init mouse events
  21006. this._initEvents();
  21007. // In case some people write `window.onresize = chart.resize`
  21008. this.resize = bind(this.resize, this);
  21009. // Can't dispatch action during rendering procedure
  21010. this._pendingActions = [];
  21011. zr.animation.on('frame', this._onframe, this);
  21012. bindRenderedEvent(zr, this);
  21013. // ECharts instance can be used as value.
  21014. setAsPrimitive(this);
  21015. }
  21016. var echartsProto = ECharts.prototype;
  21017. echartsProto._onframe = function () {
  21018. if (this._disposed) {
  21019. return;
  21020. }
  21021. var scheduler = this._scheduler;
  21022. // Lazy update
  21023. if (this[OPTION_UPDATED]) {
  21024. var silent = this[OPTION_UPDATED].silent;
  21025. this[IN_MAIN_PROCESS] = true;
  21026. prepare(this);
  21027. updateMethods.update.call(this);
  21028. this[IN_MAIN_PROCESS] = false;
  21029. this[OPTION_UPDATED] = false;
  21030. flushPendingActions.call(this, silent);
  21031. triggerUpdatedEvent.call(this, silent);
  21032. }
  21033. // Avoid do both lazy update and progress in one frame.
  21034. else if (scheduler.unfinished) {
  21035. // Stream progress.
  21036. var remainTime = TEST_FRAME_REMAIN_TIME;
  21037. var ecModel = this._model;
  21038. var api = this._api;
  21039. scheduler.unfinished = false;
  21040. do {
  21041. var startTime = +new Date();
  21042. scheduler.performSeriesTasks(ecModel);
  21043. // Currently dataProcessorFuncs do not check threshold.
  21044. scheduler.performDataProcessorTasks(ecModel);
  21045. updateStreamModes(this, ecModel);
  21046. // Do not update coordinate system here. Because that coord system update in
  21047. // each frame is not a good user experience. So we follow the rule that
  21048. // the extent of the coordinate system is determin in the first frame (the
  21049. // frame is executed immedietely after task reset.
  21050. // this._coordSysMgr.update(ecModel, api);
  21051. // console.log('--- ec frame visual ---', remainTime);
  21052. scheduler.performVisualTasks(ecModel);
  21053. renderSeries(this, this._model, api, 'remain');
  21054. remainTime -= (+new Date() - startTime);
  21055. }
  21056. while (remainTime > 0 && scheduler.unfinished);
  21057. // Call flush explicitly for trigger finished event.
  21058. if (!scheduler.unfinished) {
  21059. this._zr.flush();
  21060. }
  21061. // Else, zr flushing be ensue within the same frame,
  21062. // because zr flushing is after onframe event.
  21063. }
  21064. };
  21065. /**
  21066. * @return {HTMLElement}
  21067. */
  21068. echartsProto.getDom = function () {
  21069. return this._dom;
  21070. };
  21071. /**
  21072. * @return {module:zrender~ZRender}
  21073. */
  21074. echartsProto.getZr = function () {
  21075. return this._zr;
  21076. };
  21077. /**
  21078. * Usage:
  21079. * chart.setOption(option, notMerge, lazyUpdate);
  21080. * chart.setOption(option, {
  21081. * notMerge: ...,
  21082. * lazyUpdate: ...,
  21083. * silent: ...
  21084. * });
  21085. *
  21086. * @param {Object} option
  21087. * @param {Object|boolean} [opts] opts or notMerge.
  21088. * @param {boolean} [opts.notMerge=false]
  21089. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  21090. */
  21091. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  21092. if (__DEV__) {
  21093. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  21094. }
  21095. var silent;
  21096. if (isObject(notMerge)) {
  21097. lazyUpdate = notMerge.lazyUpdate;
  21098. silent = notMerge.silent;
  21099. notMerge = notMerge.notMerge;
  21100. }
  21101. this[IN_MAIN_PROCESS] = true;
  21102. if (!this._model || notMerge) {
  21103. var optionManager = new OptionManager(this._api);
  21104. var theme$$1 = this._theme;
  21105. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  21106. ecModel.scheduler = this._scheduler;
  21107. ecModel.init(null, null, theme$$1, optionManager);
  21108. }
  21109. this._model.setOption(option, optionPreprocessorFuncs);
  21110. if (lazyUpdate) {
  21111. this[OPTION_UPDATED] = {silent: silent};
  21112. this[IN_MAIN_PROCESS] = false;
  21113. }
  21114. else {
  21115. prepare(this);
  21116. updateMethods.update.call(this);
  21117. // Ensure zr refresh sychronously, and then pixel in canvas can be
  21118. // fetched after `setOption`.
  21119. this._zr.flush();
  21120. this[OPTION_UPDATED] = false;
  21121. this[IN_MAIN_PROCESS] = false;
  21122. flushPendingActions.call(this, silent);
  21123. triggerUpdatedEvent.call(this, silent);
  21124. }
  21125. };
  21126. /**
  21127. * @DEPRECATED
  21128. */
  21129. echartsProto.setTheme = function () {
  21130. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  21131. };
  21132. /**
  21133. * @return {module:echarts/model/Global}
  21134. */
  21135. echartsProto.getModel = function () {
  21136. return this._model;
  21137. };
  21138. /**
  21139. * @return {Object}
  21140. */
  21141. echartsProto.getOption = function () {
  21142. return this._model && this._model.getOption();
  21143. };
  21144. /**
  21145. * @return {number}
  21146. */
  21147. echartsProto.getWidth = function () {
  21148. return this._zr.getWidth();
  21149. };
  21150. /**
  21151. * @return {number}
  21152. */
  21153. echartsProto.getHeight = function () {
  21154. return this._zr.getHeight();
  21155. };
  21156. /**
  21157. * @return {number}
  21158. */
  21159. echartsProto.getDevicePixelRatio = function () {
  21160. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  21161. };
  21162. /**
  21163. * Get canvas which has all thing rendered
  21164. * @param {Object} opts
  21165. * @param {string} [opts.backgroundColor]
  21166. * @return {string}
  21167. */
  21168. echartsProto.getRenderedCanvas = function (opts) {
  21169. if (!env$1.canvasSupported) {
  21170. return;
  21171. }
  21172. opts = opts || {};
  21173. opts.pixelRatio = opts.pixelRatio || 1;
  21174. opts.backgroundColor = opts.backgroundColor
  21175. || this._model.get('backgroundColor');
  21176. var zr = this._zr;
  21177. // var list = zr.storage.getDisplayList();
  21178. // Stop animations
  21179. // Never works before in init animation, so remove it.
  21180. // zrUtil.each(list, function (el) {
  21181. // el.stopAnimation(true);
  21182. // });
  21183. return zr.painter.getRenderedCanvas(opts);
  21184. };
  21185. /**
  21186. * Get svg data url
  21187. * @return {string}
  21188. */
  21189. echartsProto.getSvgDataUrl = function () {
  21190. if (!env$1.svgSupported) {
  21191. return;
  21192. }
  21193. var zr = this._zr;
  21194. var list = zr.storage.getDisplayList();
  21195. // Stop animations
  21196. each$1(list, function (el) {
  21197. el.stopAnimation(true);
  21198. });
  21199. return zr.painter.pathToDataUrl();
  21200. };
  21201. /**
  21202. * @return {string}
  21203. * @param {Object} opts
  21204. * @param {string} [opts.type='png']
  21205. * @param {string} [opts.pixelRatio=1]
  21206. * @param {string} [opts.backgroundColor]
  21207. * @param {string} [opts.excludeComponents]
  21208. */
  21209. echartsProto.getDataURL = function (opts) {
  21210. opts = opts || {};
  21211. var excludeComponents = opts.excludeComponents;
  21212. var ecModel = this._model;
  21213. var excludesComponentViews = [];
  21214. var self = this;
  21215. each(excludeComponents, function (componentType) {
  21216. ecModel.eachComponent({
  21217. mainType: componentType
  21218. }, function (component) {
  21219. var view = self._componentsMap[component.__viewId];
  21220. if (!view.group.ignore) {
  21221. excludesComponentViews.push(view);
  21222. view.group.ignore = true;
  21223. }
  21224. });
  21225. });
  21226. var url = this._zr.painter.getType() === 'svg'
  21227. ? this.getSvgDataUrl()
  21228. : this.getRenderedCanvas(opts).toDataURL(
  21229. 'image/' + (opts && opts.type || 'png')
  21230. );
  21231. each(excludesComponentViews, function (view) {
  21232. view.group.ignore = false;
  21233. });
  21234. return url;
  21235. };
  21236. /**
  21237. * @return {string}
  21238. * @param {Object} opts
  21239. * @param {string} [opts.type='png']
  21240. * @param {string} [opts.pixelRatio=1]
  21241. * @param {string} [opts.backgroundColor]
  21242. */
  21243. echartsProto.getConnectedDataURL = function (opts) {
  21244. if (!env$1.canvasSupported) {
  21245. return;
  21246. }
  21247. var groupId = this.group;
  21248. var mathMin = Math.min;
  21249. var mathMax = Math.max;
  21250. var MAX_NUMBER = Infinity;
  21251. if (connectedGroups[groupId]) {
  21252. var left = MAX_NUMBER;
  21253. var top = MAX_NUMBER;
  21254. var right = -MAX_NUMBER;
  21255. var bottom = -MAX_NUMBER;
  21256. var canvasList = [];
  21257. var dpr = (opts && opts.pixelRatio) || 1;
  21258. each$1(instances, function (chart, id) {
  21259. if (chart.group === groupId) {
  21260. var canvas = chart.getRenderedCanvas(
  21261. clone(opts)
  21262. );
  21263. var boundingRect = chart.getDom().getBoundingClientRect();
  21264. left = mathMin(boundingRect.left, left);
  21265. top = mathMin(boundingRect.top, top);
  21266. right = mathMax(boundingRect.right, right);
  21267. bottom = mathMax(boundingRect.bottom, bottom);
  21268. canvasList.push({
  21269. dom: canvas,
  21270. left: boundingRect.left,
  21271. top: boundingRect.top
  21272. });
  21273. }
  21274. });
  21275. left *= dpr;
  21276. top *= dpr;
  21277. right *= dpr;
  21278. bottom *= dpr;
  21279. var width = right - left;
  21280. var height = bottom - top;
  21281. var targetCanvas = createCanvas();
  21282. targetCanvas.width = width;
  21283. targetCanvas.height = height;
  21284. var zr = init$1(targetCanvas);
  21285. each(canvasList, function (item) {
  21286. var img = new ZImage({
  21287. style: {
  21288. x: item.left * dpr - left,
  21289. y: item.top * dpr - top,
  21290. image: item.dom
  21291. }
  21292. });
  21293. zr.add(img);
  21294. });
  21295. zr.refreshImmediately();
  21296. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  21297. }
  21298. else {
  21299. return this.getDataURL(opts);
  21300. }
  21301. };
  21302. /**
  21303. * Convert from logical coordinate system to pixel coordinate system.
  21304. * See CoordinateSystem#convertToPixel.
  21305. * @param {string|Object} finder
  21306. * If string, e.g., 'geo', means {geoIndex: 0}.
  21307. * If Object, could contain some of these properties below:
  21308. * {
  21309. * seriesIndex / seriesId / seriesName,
  21310. * geoIndex / geoId, geoName,
  21311. * bmapIndex / bmapId / bmapName,
  21312. * xAxisIndex / xAxisId / xAxisName,
  21313. * yAxisIndex / yAxisId / yAxisName,
  21314. * gridIndex / gridId / gridName,
  21315. * ... (can be extended)
  21316. * }
  21317. * @param {Array|number} value
  21318. * @return {Array|number} result
  21319. */
  21320. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  21321. /**
  21322. * Convert from pixel coordinate system to logical coordinate system.
  21323. * See CoordinateSystem#convertFromPixel.
  21324. * @param {string|Object} finder
  21325. * If string, e.g., 'geo', means {geoIndex: 0}.
  21326. * If Object, could contain some of these properties below:
  21327. * {
  21328. * seriesIndex / seriesId / seriesName,
  21329. * geoIndex / geoId / geoName,
  21330. * bmapIndex / bmapId / bmapName,
  21331. * xAxisIndex / xAxisId / xAxisName,
  21332. * yAxisIndex / yAxisId / yAxisName
  21333. * gridIndex / gridId / gridName,
  21334. * ... (can be extended)
  21335. * }
  21336. * @param {Array|number} value
  21337. * @return {Array|number} result
  21338. */
  21339. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  21340. function doConvertPixel(methodName, finder, value) {
  21341. var ecModel = this._model;
  21342. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  21343. var result;
  21344. finder = parseFinder(ecModel, finder);
  21345. for (var i = 0; i < coordSysList.length; i++) {
  21346. var coordSys = coordSysList[i];
  21347. if (coordSys[methodName]
  21348. && (result = coordSys[methodName](ecModel, finder, value)) != null
  21349. ) {
  21350. return result;
  21351. }
  21352. }
  21353. if (__DEV__) {
  21354. console.warn(
  21355. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  21356. );
  21357. }
  21358. }
  21359. /**
  21360. * Is the specified coordinate systems or components contain the given pixel point.
  21361. * @param {string|Object} finder
  21362. * If string, e.g., 'geo', means {geoIndex: 0}.
  21363. * If Object, could contain some of these properties below:
  21364. * {
  21365. * seriesIndex / seriesId / seriesName,
  21366. * geoIndex / geoId / geoName,
  21367. * bmapIndex / bmapId / bmapName,
  21368. * xAxisIndex / xAxisId / xAxisName,
  21369. * yAxisIndex / yAxisId / yAxisName,
  21370. * gridIndex / gridId / gridName,
  21371. * ... (can be extended)
  21372. * }
  21373. * @param {Array|number} value
  21374. * @return {boolean} result
  21375. */
  21376. echartsProto.containPixel = function (finder, value) {
  21377. var ecModel = this._model;
  21378. var result;
  21379. finder = parseFinder(ecModel, finder);
  21380. each$1(finder, function (models, key) {
  21381. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  21382. var coordSys = model.coordinateSystem;
  21383. if (coordSys && coordSys.containPoint) {
  21384. result |= !!coordSys.containPoint(value);
  21385. }
  21386. else if (key === 'seriesModels') {
  21387. var view = this._chartsMap[model.__viewId];
  21388. if (view && view.containPoint) {
  21389. result |= view.containPoint(value, model);
  21390. }
  21391. else {
  21392. if (__DEV__) {
  21393. console.warn(key + ': ' + (view
  21394. ? 'The found component do not support containPoint.'
  21395. : 'No view mapping to the found component.'
  21396. ));
  21397. }
  21398. }
  21399. }
  21400. else {
  21401. if (__DEV__) {
  21402. console.warn(key + ': containPoint is not supported');
  21403. }
  21404. }
  21405. }, this);
  21406. }, this);
  21407. return !!result;
  21408. };
  21409. /**
  21410. * Get visual from series or data.
  21411. * @param {string|Object} finder
  21412. * If string, e.g., 'series', means {seriesIndex: 0}.
  21413. * If Object, could contain some of these properties below:
  21414. * {
  21415. * seriesIndex / seriesId / seriesName,
  21416. * dataIndex / dataIndexInside
  21417. * }
  21418. * If dataIndex is not specified, series visual will be fetched,
  21419. * but not data item visual.
  21420. * If all of seriesIndex, seriesId, seriesName are not specified,
  21421. * visual will be fetched from first series.
  21422. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  21423. */
  21424. echartsProto.getVisual = function (finder, visualType) {
  21425. var ecModel = this._model;
  21426. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  21427. var seriesModel = finder.seriesModel;
  21428. if (__DEV__) {
  21429. if (!seriesModel) {
  21430. console.warn('There is no specified seires model');
  21431. }
  21432. }
  21433. var data = seriesModel.getData();
  21434. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  21435. ? finder.dataIndexInside
  21436. : finder.hasOwnProperty('dataIndex')
  21437. ? data.indexOfRawIndex(finder.dataIndex)
  21438. : null;
  21439. return dataIndexInside != null
  21440. ? data.getItemVisual(dataIndexInside, visualType)
  21441. : data.getVisual(visualType);
  21442. };
  21443. /**
  21444. * Get view of corresponding component model
  21445. * @param {module:echarts/model/Component} componentModel
  21446. * @return {module:echarts/view/Component}
  21447. */
  21448. echartsProto.getViewOfComponentModel = function (componentModel) {
  21449. return this._componentsMap[componentModel.__viewId];
  21450. };
  21451. /**
  21452. * Get view of corresponding series model
  21453. * @param {module:echarts/model/Series} seriesModel
  21454. * @return {module:echarts/view/Chart}
  21455. */
  21456. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  21457. return this._chartsMap[seriesModel.__viewId];
  21458. };
  21459. var updateMethods = {
  21460. prepareAndUpdate: function (payload) {
  21461. prepare(this);
  21462. updateMethods.update.call(this, payload);
  21463. },
  21464. /**
  21465. * @param {Object} payload
  21466. * @private
  21467. */
  21468. update: function (payload) {
  21469. // console.profile && console.profile('update');
  21470. var ecModel = this._model;
  21471. var api = this._api;
  21472. var zr = this._zr;
  21473. var coordSysMgr = this._coordSysMgr;
  21474. var scheduler = this._scheduler;
  21475. // update before setOption
  21476. if (!ecModel) {
  21477. return;
  21478. }
  21479. ecModel.restoreData(payload);
  21480. scheduler.performSeriesTasks(ecModel);
  21481. // TODO
  21482. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  21483. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  21484. // Create new coordinate system each update
  21485. // In LineView may save the old coordinate system and use it to get the orignal point
  21486. coordSysMgr.create(ecModel, api);
  21487. scheduler.performDataProcessorTasks(ecModel, payload);
  21488. // Current stream render is not supported in data process. So we can update
  21489. // stream modes after data processing, where the filtered data is used to
  21490. // deteming whether use progressive rendering.
  21491. updateStreamModes(this, ecModel);
  21492. // stackSeriesData(ecModel);
  21493. coordSysMgr.update(ecModel, api);
  21494. clearColorPalette(ecModel);
  21495. scheduler.performVisualTasks(ecModel, payload);
  21496. render(this, ecModel, api, payload);
  21497. // Set background
  21498. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  21499. // In IE8
  21500. if (!env$1.canvasSupported) {
  21501. var colorArr = parse(backgroundColor);
  21502. backgroundColor = stringify(colorArr, 'rgb');
  21503. if (colorArr[3] === 0) {
  21504. backgroundColor = 'transparent';
  21505. }
  21506. }
  21507. else {
  21508. zr.setBackgroundColor(backgroundColor);
  21509. }
  21510. performPostUpdateFuncs(ecModel, api);
  21511. // console.profile && console.profileEnd('update');
  21512. },
  21513. /**
  21514. * @param {Object} payload
  21515. * @private
  21516. */
  21517. updateTransform: function (payload) {
  21518. var ecModel = this._model;
  21519. var ecIns = this;
  21520. var api = this._api;
  21521. // update before setOption
  21522. if (!ecModel) {
  21523. return;
  21524. }
  21525. // ChartView.markUpdateMethod(payload, 'updateTransform');
  21526. var componentDirtyList = [];
  21527. ecModel.eachComponent(function (componentType, componentModel) {
  21528. var componentView = ecIns.getViewOfComponentModel(componentModel);
  21529. if (componentView && componentView.__alive) {
  21530. if (componentView.updateTransform) {
  21531. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  21532. result && result.update && componentDirtyList.push(componentView);
  21533. }
  21534. else {
  21535. componentDirtyList.push(componentView);
  21536. }
  21537. }
  21538. });
  21539. var seriesDirtyMap = createHashMap();
  21540. ecModel.eachSeries(function (seriesModel) {
  21541. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21542. if (chartView.updateTransform) {
  21543. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  21544. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  21545. }
  21546. else {
  21547. seriesDirtyMap.set(seriesModel.uid, 1);
  21548. }
  21549. });
  21550. clearColorPalette(ecModel);
  21551. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21552. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  21553. this._scheduler.performVisualTasks(
  21554. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  21555. );
  21556. // Currently, not call render of components. Geo render cost a lot.
  21557. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  21558. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  21559. performPostUpdateFuncs(ecModel, this._api);
  21560. },
  21561. /**
  21562. * @param {Object} payload
  21563. * @private
  21564. */
  21565. updateView: function (payload) {
  21566. var ecModel = this._model;
  21567. // update before setOption
  21568. if (!ecModel) {
  21569. return;
  21570. }
  21571. Chart.markUpdateMethod(payload, 'updateView');
  21572. clearColorPalette(ecModel);
  21573. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21574. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  21575. render(this, this._model, this._api, payload);
  21576. performPostUpdateFuncs(ecModel, this._api);
  21577. },
  21578. /**
  21579. * @param {Object} payload
  21580. * @private
  21581. */
  21582. updateVisual: function (payload) {
  21583. updateMethods.update.call(this, payload);
  21584. // var ecModel = this._model;
  21585. // // update before setOption
  21586. // if (!ecModel) {
  21587. // return;
  21588. // }
  21589. // ChartView.markUpdateMethod(payload, 'updateVisual');
  21590. // clearColorPalette(ecModel);
  21591. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21592. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  21593. // render(this, this._model, this._api, payload);
  21594. // performPostUpdateFuncs(ecModel, this._api);
  21595. },
  21596. /**
  21597. * @param {Object} payload
  21598. * @private
  21599. */
  21600. updateLayout: function (payload) {
  21601. updateMethods.update.call(this, payload);
  21602. // var ecModel = this._model;
  21603. // // update before setOption
  21604. // if (!ecModel) {
  21605. // return;
  21606. // }
  21607. // ChartView.markUpdateMethod(payload, 'updateLayout');
  21608. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  21609. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  21610. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  21611. // render(this, this._model, this._api, payload);
  21612. // performPostUpdateFuncs(ecModel, this._api);
  21613. }
  21614. };
  21615. function prepare(ecIns) {
  21616. var ecModel = ecIns._model;
  21617. var scheduler = ecIns._scheduler;
  21618. scheduler.restorePipelines(ecModel);
  21619. scheduler.prepareStageTasks();
  21620. prepareView(ecIns, 'component', ecModel, scheduler);
  21621. prepareView(ecIns, 'chart', ecModel, scheduler);
  21622. scheduler.plan();
  21623. }
  21624. /**
  21625. * @private
  21626. */
  21627. function updateDirectly(ecIns, method, payload, mainType, subType) {
  21628. var ecModel = ecIns._model;
  21629. // broadcast
  21630. if (!mainType) {
  21631. // FIXME
  21632. // Chart will not be update directly here, except set dirty.
  21633. // But there is no such scenario now.
  21634. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  21635. return;
  21636. }
  21637. var query = {};
  21638. query[mainType + 'Id'] = payload[mainType + 'Id'];
  21639. query[mainType + 'Index'] = payload[mainType + 'Index'];
  21640. query[mainType + 'Name'] = payload[mainType + 'Name'];
  21641. var condition = {mainType: mainType, query: query};
  21642. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  21643. // If dispatchAction before setOption, do nothing.
  21644. ecModel && ecModel.eachComponent(condition, function (model, index) {
  21645. callView(ecIns[
  21646. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  21647. ][model.__viewId]);
  21648. }, ecIns);
  21649. function callView(view) {
  21650. view && view.__alive && view[method] && view[method](
  21651. view.__model, ecModel, ecIns._api, payload
  21652. );
  21653. }
  21654. }
  21655. /**
  21656. * Resize the chart
  21657. * @param {Object} opts
  21658. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  21659. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  21660. * @param {boolean} [opts.silent=false]
  21661. */
  21662. echartsProto.resize = function (opts) {
  21663. if (__DEV__) {
  21664. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  21665. }
  21666. this._zr.resize(opts);
  21667. var ecModel = this._model;
  21668. // Resize loading effect
  21669. this._loadingFX && this._loadingFX.resize();
  21670. if (!ecModel) {
  21671. return;
  21672. }
  21673. var optionChanged = ecModel.resetOption('media');
  21674. var silent = opts && opts.silent;
  21675. this[IN_MAIN_PROCESS] = true;
  21676. optionChanged && prepare(this);
  21677. updateMethods.update.call(this);
  21678. this[IN_MAIN_PROCESS] = false;
  21679. flushPendingActions.call(this, silent);
  21680. triggerUpdatedEvent.call(this, silent);
  21681. };
  21682. function updateStreamModes(ecIns, ecModel) {
  21683. var chartsMap = ecIns._chartsMap;
  21684. var scheduler = ecIns._scheduler;
  21685. ecModel.eachSeries(function (seriesModel) {
  21686. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  21687. });
  21688. }
  21689. /**
  21690. * Show loading effect
  21691. * @param {string} [name='default']
  21692. * @param {Object} [cfg]
  21693. */
  21694. echartsProto.showLoading = function (name, cfg) {
  21695. if (isObject(name)) {
  21696. cfg = name;
  21697. name = '';
  21698. }
  21699. name = name || 'default';
  21700. this.hideLoading();
  21701. if (!loadingEffects[name]) {
  21702. if (__DEV__) {
  21703. console.warn('Loading effects ' + name + ' not exists.');
  21704. }
  21705. return;
  21706. }
  21707. var el = loadingEffects[name](this._api, cfg);
  21708. var zr = this._zr;
  21709. this._loadingFX = el;
  21710. zr.add(el);
  21711. };
  21712. /**
  21713. * Hide loading effect
  21714. */
  21715. echartsProto.hideLoading = function () {
  21716. this._loadingFX && this._zr.remove(this._loadingFX);
  21717. this._loadingFX = null;
  21718. };
  21719. /**
  21720. * @param {Object} eventObj
  21721. * @return {Object}
  21722. */
  21723. echartsProto.makeActionFromEvent = function (eventObj) {
  21724. var payload = extend({}, eventObj);
  21725. payload.type = eventActionMap[eventObj.type];
  21726. return payload;
  21727. };
  21728. /**
  21729. * @pubilc
  21730. * @param {Object} payload
  21731. * @param {string} [payload.type] Action type
  21732. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  21733. * @param {boolean} [opt.silent=false] Whether trigger events.
  21734. * @param {boolean} [opt.flush=undefined]
  21735. * true: Flush immediately, and then pixel in canvas can be fetched
  21736. * immediately. Caution: it might affect performance.
  21737. * false: Not not flush.
  21738. * undefined: Auto decide whether perform flush.
  21739. */
  21740. echartsProto.dispatchAction = function (payload, opt) {
  21741. if (!isObject(opt)) {
  21742. opt = {silent: !!opt};
  21743. }
  21744. if (!actions[payload.type]) {
  21745. return;
  21746. }
  21747. // Avoid dispatch action before setOption. Especially in `connect`.
  21748. if (!this._model) {
  21749. return;
  21750. }
  21751. // May dispatchAction in rendering procedure
  21752. if (this[IN_MAIN_PROCESS]) {
  21753. this._pendingActions.push(payload);
  21754. return;
  21755. }
  21756. doDispatchAction.call(this, payload, opt.silent);
  21757. if (opt.flush) {
  21758. this._zr.flush(true);
  21759. }
  21760. else if (opt.flush !== false && env$1.browser.weChat) {
  21761. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  21762. // hang when sliding page (on touch event), which cause that zr does not
  21763. // refresh util user interaction finished, which is not expected.
  21764. // But `dispatchAction` may be called too frequently when pan on touch
  21765. // screen, which impacts performance if do not throttle them.
  21766. this._throttledZrFlush();
  21767. }
  21768. flushPendingActions.call(this, opt.silent);
  21769. triggerUpdatedEvent.call(this, opt.silent);
  21770. };
  21771. function doDispatchAction(payload, silent) {
  21772. var payloadType = payload.type;
  21773. var escapeConnect = payload.escapeConnect;
  21774. var actionWrap = actions[payloadType];
  21775. var actionInfo = actionWrap.actionInfo;
  21776. var cptType = (actionInfo.update || 'update').split(':');
  21777. var updateMethod = cptType.pop();
  21778. cptType = cptType[0] != null && parseClassType(cptType[0]);
  21779. this[IN_MAIN_PROCESS] = true;
  21780. var payloads = [payload];
  21781. var batched = false;
  21782. // Batch action
  21783. if (payload.batch) {
  21784. batched = true;
  21785. payloads = map(payload.batch, function (item) {
  21786. item = defaults(extend({}, item), payload);
  21787. item.batch = null;
  21788. return item;
  21789. });
  21790. }
  21791. var eventObjBatch = [];
  21792. var eventObj;
  21793. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  21794. each(payloads, function (batchItem) {
  21795. // Action can specify the event by return it.
  21796. eventObj = actionWrap.action(batchItem, this._model, this._api);
  21797. // Emit event outside
  21798. eventObj = eventObj || extend({}, batchItem);
  21799. // Convert type to eventType
  21800. eventObj.type = actionInfo.event || eventObj.type;
  21801. eventObjBatch.push(eventObj);
  21802. // light update does not perform data process, layout and visual.
  21803. if (isHighDown) {
  21804. // method, payload, mainType, subType
  21805. updateDirectly(this, updateMethod, batchItem, 'series');
  21806. }
  21807. else if (cptType) {
  21808. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  21809. }
  21810. }, this);
  21811. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  21812. // Still dirty
  21813. if (this[OPTION_UPDATED]) {
  21814. // FIXME Pass payload ?
  21815. prepare(this);
  21816. updateMethods.update.call(this, payload);
  21817. this[OPTION_UPDATED] = false;
  21818. }
  21819. else {
  21820. updateMethods[updateMethod].call(this, payload);
  21821. }
  21822. }
  21823. // Follow the rule of action batch
  21824. if (batched) {
  21825. eventObj = {
  21826. type: actionInfo.event || payloadType,
  21827. escapeConnect: escapeConnect,
  21828. batch: eventObjBatch
  21829. };
  21830. }
  21831. else {
  21832. eventObj = eventObjBatch[0];
  21833. }
  21834. this[IN_MAIN_PROCESS] = false;
  21835. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  21836. }
  21837. function flushPendingActions(silent) {
  21838. var pendingActions = this._pendingActions;
  21839. while (pendingActions.length) {
  21840. var payload = pendingActions.shift();
  21841. doDispatchAction.call(this, payload, silent);
  21842. }
  21843. }
  21844. function triggerUpdatedEvent(silent) {
  21845. !silent && this.trigger('updated');
  21846. }
  21847. /**
  21848. * Event `rendered` is triggered when zr
  21849. * rendered. It is useful for realtime
  21850. * snapshot (reflect animation).
  21851. *
  21852. * Event `finished` is triggered when:
  21853. * (1) zrender rendering finished.
  21854. * (2) initial animation finished.
  21855. * (3) progressive rendering finished.
  21856. * (4) no pending action.
  21857. * (5) no delayed setOption needs to be processed.
  21858. */
  21859. function bindRenderedEvent(zr, ecIns) {
  21860. zr.on('rendered', function () {
  21861. ecIns.trigger('rendered');
  21862. // The `finished` event should not be triggered repeatly,
  21863. // so it should only be triggered when rendering indeed happend
  21864. // in zrender. (Consider the case that dipatchAction is keep
  21865. // triggering when mouse move).
  21866. if (
  21867. // Although zr is dirty if initial animation is not finished
  21868. // and this checking is called on frame, we also check
  21869. // animation finished for robustness.
  21870. zr.animation.isFinished()
  21871. && !ecIns[OPTION_UPDATED]
  21872. && !ecIns._scheduler.unfinished
  21873. && !ecIns._pendingActions.length
  21874. ) {
  21875. ecIns.trigger('finished');
  21876. }
  21877. });
  21878. }
  21879. /**
  21880. * @param {Object} params
  21881. * @param {number} params.seriesIndex
  21882. * @param {Array|TypedArray} params.data
  21883. */
  21884. echartsProto.appendData = function (params) {
  21885. var seriesIndex = params.seriesIndex;
  21886. var ecModel = this.getModel();
  21887. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  21888. if (__DEV__) {
  21889. assert(params.data && seriesModel);
  21890. }
  21891. seriesModel.appendData(params);
  21892. // Note: `appendData` does not support that update extent of coordinate
  21893. // system, util some scenario require that. In the expected usage of
  21894. // `appendData`, the initial extent of coordinate system should better
  21895. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  21896. // the extent changed while `appendData`, the location of the painted
  21897. // graphic elements have to be changed, which make the usage of
  21898. // `appendData` meaningless.
  21899. this._scheduler.unfinished = true;
  21900. };
  21901. /**
  21902. * Register event
  21903. * @method
  21904. */
  21905. echartsProto.on = createRegisterEventWithLowercaseName('on');
  21906. echartsProto.off = createRegisterEventWithLowercaseName('off');
  21907. echartsProto.one = createRegisterEventWithLowercaseName('one');
  21908. /**
  21909. * Prepare view instances of charts and components
  21910. * @param {module:echarts/model/Global} ecModel
  21911. * @private
  21912. */
  21913. function prepareView(ecIns, type, ecModel, scheduler) {
  21914. var isComponent = type === 'component';
  21915. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  21916. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  21917. var zr = ecIns._zr;
  21918. var api = ecIns._api;
  21919. for (var i = 0; i < viewList.length; i++) {
  21920. viewList[i].__alive = false;
  21921. }
  21922. isComponent
  21923. ? ecModel.eachComponent(function (componentType, model) {
  21924. componentType !== 'series' && doPrepare(model);
  21925. })
  21926. : ecModel.eachSeries(doPrepare);
  21927. function doPrepare(model) {
  21928. // Consider: id same and type changed.
  21929. var viewId = '_ec_' + model.id + '_' + model.type;
  21930. var view = viewMap[viewId];
  21931. if (!view) {
  21932. var classType = parseClassType(model.type);
  21933. var Clazz = isComponent
  21934. ? Component.getClass(classType.main, classType.sub)
  21935. : Chart.getClass(classType.sub);
  21936. if (__DEV__) {
  21937. assert(Clazz, classType.sub + ' does not exist.');
  21938. }
  21939. view = new Clazz();
  21940. view.init(ecModel, api);
  21941. viewMap[viewId] = view;
  21942. viewList.push(view);
  21943. zr.add(view.group);
  21944. }
  21945. model.__viewId = view.__id = viewId;
  21946. view.__alive = true;
  21947. view.__model = model;
  21948. view.group.__ecComponentInfo = {
  21949. mainType: model.mainType,
  21950. index: model.componentIndex
  21951. };
  21952. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  21953. }
  21954. for (var i = 0; i < viewList.length;) {
  21955. var view = viewList[i];
  21956. if (!view.__alive) {
  21957. !isComponent && view.renderTask.dispose();
  21958. zr.remove(view.group);
  21959. view.dispose(ecModel, api);
  21960. viewList.splice(i, 1);
  21961. delete viewMap[view.__id];
  21962. view.__id = view.group.__ecComponentInfo = null;
  21963. }
  21964. else {
  21965. i++;
  21966. }
  21967. }
  21968. }
  21969. // /**
  21970. // * Encode visual infomation from data after data processing
  21971. // *
  21972. // * @param {module:echarts/model/Global} ecModel
  21973. // * @param {object} layout
  21974. // * @param {boolean} [layoutFilter] `true`: only layout,
  21975. // * `false`: only not layout,
  21976. // * `null`/`undefined`: all.
  21977. // * @param {string} taskBaseTag
  21978. // * @private
  21979. // */
  21980. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  21981. // each(visualFuncs, function (visual, index) {
  21982. // var isLayout = visual.isLayout;
  21983. // if (layoutFilter == null
  21984. // || (layoutFilter === false && !isLayout)
  21985. // || (layoutFilter === true && isLayout)
  21986. // ) {
  21987. // visual.func(ecModel, api, payload);
  21988. // }
  21989. // });
  21990. // }
  21991. function clearColorPalette(ecModel) {
  21992. ecModel.clearColorPalette();
  21993. ecModel.eachSeries(function (seriesModel) {
  21994. seriesModel.clearColorPalette();
  21995. });
  21996. }
  21997. function render(ecIns, ecModel, api, payload) {
  21998. renderComponents(ecIns, ecModel, api, payload);
  21999. each(ecIns._chartsViews, function (chart) {
  22000. chart.__alive = false;
  22001. });
  22002. renderSeries(ecIns, ecModel, api, payload);
  22003. // Remove groups of unrendered charts
  22004. each(ecIns._chartsViews, function (chart) {
  22005. if (!chart.__alive) {
  22006. chart.remove(ecModel, api);
  22007. }
  22008. });
  22009. }
  22010. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  22011. each(dirtyList || ecIns._componentsViews, function (componentView) {
  22012. var componentModel = componentView.__model;
  22013. componentView.render(componentModel, ecModel, api, payload);
  22014. updateZ(componentModel, componentView);
  22015. });
  22016. }
  22017. /**
  22018. * Render each chart and component
  22019. * @private
  22020. */
  22021. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  22022. // Render all charts
  22023. var scheduler = ecIns._scheduler;
  22024. var unfinished;
  22025. ecModel.eachSeries(function (seriesModel) {
  22026. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  22027. chartView.__alive = true;
  22028. var renderTask = chartView.renderTask;
  22029. scheduler.updatePayload(renderTask, payload);
  22030. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  22031. renderTask.dirty();
  22032. }
  22033. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  22034. chartView.group.silent = !!seriesModel.get('silent');
  22035. updateZ(seriesModel, chartView);
  22036. updateBlend(seriesModel, chartView);
  22037. });
  22038. scheduler.unfinished |= unfinished;
  22039. // If use hover layer
  22040. updateHoverLayerStatus(ecIns._zr, ecModel);
  22041. // Add aria
  22042. aria(ecIns._zr.dom, ecModel);
  22043. }
  22044. function performPostUpdateFuncs(ecModel, api) {
  22045. each(postUpdateFuncs, function (func) {
  22046. func(ecModel, api);
  22047. });
  22048. }
  22049. var MOUSE_EVENT_NAMES = [
  22050. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  22051. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  22052. ];
  22053. /**
  22054. * @private
  22055. */
  22056. echartsProto._initEvents = function () {
  22057. each(MOUSE_EVENT_NAMES, function (eveName) {
  22058. this._zr.on(eveName, function (e) {
  22059. var ecModel = this.getModel();
  22060. var el = e.target;
  22061. var params;
  22062. // no e.target when 'globalout'.
  22063. if (eveName === 'globalout') {
  22064. params = {};
  22065. }
  22066. else if (el && el.dataIndex != null) {
  22067. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  22068. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  22069. }
  22070. // If element has custom eventData of components
  22071. else if (el && el.eventData) {
  22072. params = extend({}, el.eventData);
  22073. }
  22074. if (params) {
  22075. params.event = e;
  22076. params.type = eveName;
  22077. this.trigger(eveName, params);
  22078. }
  22079. }, this);
  22080. }, this);
  22081. each(eventActionMap, function (actionType, eventType) {
  22082. this._messageCenter.on(eventType, function (event) {
  22083. this.trigger(eventType, event);
  22084. }, this);
  22085. }, this);
  22086. };
  22087. /**
  22088. * @return {boolean}
  22089. */
  22090. echartsProto.isDisposed = function () {
  22091. return this._disposed;
  22092. };
  22093. /**
  22094. * Clear
  22095. */
  22096. echartsProto.clear = function () {
  22097. this.setOption({ series: [] }, true);
  22098. };
  22099. /**
  22100. * Dispose instance
  22101. */
  22102. echartsProto.dispose = function () {
  22103. if (this._disposed) {
  22104. if (__DEV__) {
  22105. console.warn('Instance ' + this.id + ' has been disposed');
  22106. }
  22107. return;
  22108. }
  22109. this._disposed = true;
  22110. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  22111. var api = this._api;
  22112. var ecModel = this._model;
  22113. each(this._componentsViews, function (component) {
  22114. component.dispose(ecModel, api);
  22115. });
  22116. each(this._chartsViews, function (chart) {
  22117. chart.dispose(ecModel, api);
  22118. });
  22119. // Dispose after all views disposed
  22120. this._zr.dispose();
  22121. delete instances[this.id];
  22122. };
  22123. mixin(ECharts, Eventful);
  22124. function updateHoverLayerStatus(zr, ecModel) {
  22125. var storage = zr.storage;
  22126. var elCount = 0;
  22127. storage.traverse(function (el) {
  22128. if (!el.isGroup) {
  22129. elCount++;
  22130. }
  22131. });
  22132. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  22133. storage.traverse(function (el) {
  22134. if (!el.isGroup) {
  22135. // Don't switch back.
  22136. el.useHoverLayer = true;
  22137. }
  22138. });
  22139. }
  22140. }
  22141. /**
  22142. * Update chart progressive and blend.
  22143. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  22144. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  22145. */
  22146. function updateBlend(seriesModel, chartView) {
  22147. var blendMode = seriesModel.get('blendMode') || null;
  22148. if (__DEV__) {
  22149. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  22150. console.warn('Only canvas support blendMode');
  22151. }
  22152. }
  22153. chartView.group.traverse(function (el) {
  22154. // FIXME marker and other components
  22155. if (!el.isGroup) {
  22156. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  22157. if (el.style.blend !== blendMode) {
  22158. el.setStyle('blend', blendMode);
  22159. }
  22160. }
  22161. if (el.eachPendingDisplayable) {
  22162. el.eachPendingDisplayable(function (displayable) {
  22163. displayable.setStyle('blend', blendMode);
  22164. });
  22165. }
  22166. });
  22167. }
  22168. /**
  22169. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  22170. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  22171. */
  22172. function updateZ(model, view) {
  22173. var z = model.get('z');
  22174. var zlevel = model.get('zlevel');
  22175. // Set z and zlevel
  22176. view.group.traverse(function (el) {
  22177. if (el.type !== 'group') {
  22178. z != null && (el.z = z);
  22179. zlevel != null && (el.zlevel = zlevel);
  22180. }
  22181. });
  22182. }
  22183. function createExtensionAPI(ecInstance) {
  22184. var coordSysMgr = ecInstance._coordSysMgr;
  22185. return extend(new ExtensionAPI(ecInstance), {
  22186. // Inject methods
  22187. getCoordinateSystems: bind(
  22188. coordSysMgr.getCoordinateSystems, coordSysMgr
  22189. ),
  22190. getComponentByElement: function (el) {
  22191. while (el) {
  22192. var modelInfo = el.__ecComponentInfo;
  22193. if (modelInfo != null) {
  22194. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  22195. }
  22196. el = el.parent;
  22197. }
  22198. }
  22199. });
  22200. }
  22201. /**
  22202. * @type {Object} key: actionType.
  22203. * @inner
  22204. */
  22205. var actions = {};
  22206. /**
  22207. * Map eventType to actionType
  22208. * @type {Object}
  22209. */
  22210. var eventActionMap = {};
  22211. /**
  22212. * Data processor functions of each stage
  22213. * @type {Array.<Object.<string, Function>>}
  22214. * @inner
  22215. */
  22216. var dataProcessorFuncs = [];
  22217. /**
  22218. * @type {Array.<Function>}
  22219. * @inner
  22220. */
  22221. var optionPreprocessorFuncs = [];
  22222. /**
  22223. * @type {Array.<Function>}
  22224. * @inner
  22225. */
  22226. var postUpdateFuncs = [];
  22227. /**
  22228. * Visual encoding functions of each stage
  22229. * @type {Array.<Object.<string, Function>>}
  22230. */
  22231. var visualFuncs = [];
  22232. /**
  22233. * Theme storage
  22234. * @type {Object.<key, Object>}
  22235. */
  22236. var themeStorage = {};
  22237. /**
  22238. * Loading effects
  22239. */
  22240. var loadingEffects = {};
  22241. var instances = {};
  22242. var connectedGroups = {};
  22243. var idBase = new Date() - 0;
  22244. var groupIdBase = new Date() - 0;
  22245. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  22246. var mapDataStores = {};
  22247. function enableConnect(chart) {
  22248. var STATUS_PENDING = 0;
  22249. var STATUS_UPDATING = 1;
  22250. var STATUS_UPDATED = 2;
  22251. var STATUS_KEY = '__connectUpdateStatus';
  22252. function updateConnectedChartsStatus(charts, status) {
  22253. for (var i = 0; i < charts.length; i++) {
  22254. var otherChart = charts[i];
  22255. otherChart[STATUS_KEY] = status;
  22256. }
  22257. }
  22258. each(eventActionMap, function (actionType, eventType) {
  22259. chart._messageCenter.on(eventType, function (event) {
  22260. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  22261. if (event && event.escapeConnect) {
  22262. return;
  22263. }
  22264. var action = chart.makeActionFromEvent(event);
  22265. var otherCharts = [];
  22266. each(instances, function (otherChart) {
  22267. if (otherChart !== chart && otherChart.group === chart.group) {
  22268. otherCharts.push(otherChart);
  22269. }
  22270. });
  22271. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  22272. each(otherCharts, function (otherChart) {
  22273. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  22274. otherChart.dispatchAction(action);
  22275. }
  22276. });
  22277. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  22278. }
  22279. });
  22280. });
  22281. }
  22282. /**
  22283. * @param {HTMLElement} dom
  22284. * @param {Object} [theme]
  22285. * @param {Object} opts
  22286. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  22287. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  22288. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  22289. * Can be 'auto' (the same as null/undefined)
  22290. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  22291. * Can be 'auto' (the same as null/undefined)
  22292. */
  22293. function init(dom, theme$$1, opts) {
  22294. if (__DEV__) {
  22295. // Check version
  22296. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  22297. throw new Error(
  22298. 'zrender/src ' + version$1
  22299. + ' is too old for ECharts ' + version
  22300. + '. Current version need ZRender '
  22301. + dependencies.zrender + '+'
  22302. );
  22303. }
  22304. if (!dom) {
  22305. throw new Error('Initialize failed: invalid dom.');
  22306. }
  22307. }
  22308. var existInstance = getInstanceByDom(dom);
  22309. if (existInstance) {
  22310. if (__DEV__) {
  22311. console.warn('There is a chart instance already initialized on the dom.');
  22312. }
  22313. return existInstance;
  22314. }
  22315. if (__DEV__) {
  22316. if (isDom(dom)
  22317. && dom.nodeName.toUpperCase() !== 'CANVAS'
  22318. && (
  22319. (!dom.clientWidth && (!opts || opts.width == null))
  22320. || (!dom.clientHeight && (!opts || opts.height == null))
  22321. )
  22322. ) {
  22323. console.warn('Can\'t get dom width or height');
  22324. }
  22325. }
  22326. var chart = new ECharts(dom, theme$$1, opts);
  22327. chart.id = 'ec_' + idBase++;
  22328. instances[chart.id] = chart;
  22329. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  22330. enableConnect(chart);
  22331. return chart;
  22332. }
  22333. /**
  22334. * @return {string|Array.<module:echarts~ECharts>} groupId
  22335. */
  22336. function connect(groupId) {
  22337. // Is array of charts
  22338. if (isArray(groupId)) {
  22339. var charts = groupId;
  22340. groupId = null;
  22341. // If any chart has group
  22342. each(charts, function (chart) {
  22343. if (chart.group != null) {
  22344. groupId = chart.group;
  22345. }
  22346. });
  22347. groupId = groupId || ('g_' + groupIdBase++);
  22348. each(charts, function (chart) {
  22349. chart.group = groupId;
  22350. });
  22351. }
  22352. connectedGroups[groupId] = true;
  22353. return groupId;
  22354. }
  22355. /**
  22356. * @DEPRECATED
  22357. * @return {string} groupId
  22358. */
  22359. function disConnect(groupId) {
  22360. connectedGroups[groupId] = false;
  22361. }
  22362. /**
  22363. * @return {string} groupId
  22364. */
  22365. var disconnect = disConnect;
  22366. /**
  22367. * Dispose a chart instance
  22368. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  22369. */
  22370. function dispose(chart) {
  22371. if (typeof chart === 'string') {
  22372. chart = instances[chart];
  22373. }
  22374. else if (!(chart instanceof ECharts)){
  22375. // Try to treat as dom
  22376. chart = getInstanceByDom(chart);
  22377. }
  22378. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  22379. chart.dispose();
  22380. }
  22381. }
  22382. /**
  22383. * @param {HTMLElement} dom
  22384. * @return {echarts~ECharts}
  22385. */
  22386. function getInstanceByDom(dom) {
  22387. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  22388. }
  22389. /**
  22390. * @param {string} key
  22391. * @return {echarts~ECharts}
  22392. */
  22393. function getInstanceById(key) {
  22394. return instances[key];
  22395. }
  22396. /**
  22397. * Register theme
  22398. */
  22399. function registerTheme(name, theme$$1) {
  22400. themeStorage[name] = theme$$1;
  22401. }
  22402. /**
  22403. * Register option preprocessor
  22404. * @param {Function} preprocessorFunc
  22405. */
  22406. function registerPreprocessor(preprocessorFunc) {
  22407. optionPreprocessorFuncs.push(preprocessorFunc);
  22408. }
  22409. /**
  22410. * @param {number} [priority=1000]
  22411. * @param {Object|Function} processor
  22412. */
  22413. function registerProcessor(priority, processor) {
  22414. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  22415. }
  22416. /**
  22417. * Register postUpdater
  22418. * @param {Function} postUpdateFunc
  22419. */
  22420. function registerPostUpdate(postUpdateFunc) {
  22421. postUpdateFuncs.push(postUpdateFunc);
  22422. }
  22423. /**
  22424. * Usage:
  22425. * registerAction('someAction', 'someEvent', function () { ... });
  22426. * registerAction('someAction', function () { ... });
  22427. * registerAction(
  22428. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  22429. * function () { ... }
  22430. * );
  22431. *
  22432. * @param {(string|Object)} actionInfo
  22433. * @param {string} actionInfo.type
  22434. * @param {string} [actionInfo.event]
  22435. * @param {string} [actionInfo.update]
  22436. * @param {string} [eventName]
  22437. * @param {Function} action
  22438. */
  22439. function registerAction(actionInfo, eventName, action) {
  22440. if (typeof eventName === 'function') {
  22441. action = eventName;
  22442. eventName = '';
  22443. }
  22444. var actionType = isObject(actionInfo)
  22445. ? actionInfo.type
  22446. : ([actionInfo, actionInfo = {
  22447. event: eventName
  22448. }][0]);
  22449. // Event name is all lowercase
  22450. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  22451. eventName = actionInfo.event;
  22452. // Validate action type and event name.
  22453. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  22454. if (!actions[actionType]) {
  22455. actions[actionType] = {action: action, actionInfo: actionInfo};
  22456. }
  22457. eventActionMap[eventName] = actionType;
  22458. }
  22459. /**
  22460. * @param {string} type
  22461. * @param {*} CoordinateSystem
  22462. */
  22463. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  22464. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  22465. }
  22466. /**
  22467. * Get dimensions of specified coordinate system.
  22468. * @param {string} type
  22469. * @return {Array.<string|Object>}
  22470. */
  22471. function getCoordinateSystemDimensions(type) {
  22472. var coordSysCreator = CoordinateSystemManager.get(type);
  22473. if (coordSysCreator) {
  22474. return coordSysCreator.getDimensionsInfo
  22475. ? coordSysCreator.getDimensionsInfo()
  22476. : coordSysCreator.dimensions.slice();
  22477. }
  22478. }
  22479. /**
  22480. * Layout is a special stage of visual encoding
  22481. * Most visual encoding like color are common for different chart
  22482. * But each chart has it's own layout algorithm
  22483. *
  22484. * @param {number} [priority=1000]
  22485. * @param {Function} layoutTask
  22486. */
  22487. function registerLayout(priority, layoutTask) {
  22488. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  22489. }
  22490. /**
  22491. * @param {number} [priority=3000]
  22492. * @param {module:echarts/stream/Task} visualTask
  22493. */
  22494. function registerVisual(priority, visualTask) {
  22495. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  22496. }
  22497. /**
  22498. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  22499. */
  22500. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  22501. if (isFunction(priority) || isObject(priority)) {
  22502. fn = priority;
  22503. priority = defaultPriority;
  22504. }
  22505. if (__DEV__) {
  22506. if (isNaN(priority) || priority == null) {
  22507. throw new Error('Illegal priority');
  22508. }
  22509. // Check duplicate
  22510. each(targetList, function (wrap) {
  22511. assert(wrap.__raw !== fn);
  22512. });
  22513. }
  22514. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  22515. stageHandler.__prio = priority;
  22516. stageHandler.__raw = fn;
  22517. targetList.push(stageHandler);
  22518. return stageHandler;
  22519. }
  22520. /**
  22521. * @param {string} name
  22522. */
  22523. function registerLoading(name, loadingFx) {
  22524. loadingEffects[name] = loadingFx;
  22525. }
  22526. /**
  22527. * @param {Object} opts
  22528. * @param {string} [superClass]
  22529. */
  22530. function extendComponentModel(opts/*, superClass*/) {
  22531. // var Clazz = ComponentModel;
  22532. // if (superClass) {
  22533. // var classType = parseClassType(superClass);
  22534. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22535. // }
  22536. return ComponentModel.extend(opts);
  22537. }
  22538. /**
  22539. * @param {Object} opts
  22540. * @param {string} [superClass]
  22541. */
  22542. function extendComponentView(opts/*, superClass*/) {
  22543. // var Clazz = ComponentView;
  22544. // if (superClass) {
  22545. // var classType = parseClassType(superClass);
  22546. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  22547. // }
  22548. return Component.extend(opts);
  22549. }
  22550. /**
  22551. * @param {Object} opts
  22552. * @param {string} [superClass]
  22553. */
  22554. function extendSeriesModel(opts/*, superClass*/) {
  22555. // var Clazz = SeriesModel;
  22556. // if (superClass) {
  22557. // superClass = 'series.' + superClass.replace('series.', '');
  22558. // var classType = parseClassType(superClass);
  22559. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  22560. // }
  22561. return SeriesModel.extend(opts);
  22562. }
  22563. /**
  22564. * @param {Object} opts
  22565. * @param {string} [superClass]
  22566. */
  22567. function extendChartView(opts/*, superClass*/) {
  22568. // var Clazz = ChartView;
  22569. // if (superClass) {
  22570. // superClass = superClass.replace('series.', '');
  22571. // var classType = parseClassType(superClass);
  22572. // Clazz = ChartView.getClass(classType.main, true);
  22573. // }
  22574. return Chart.extend(opts);
  22575. }
  22576. /**
  22577. * ZRender need a canvas context to do measureText.
  22578. * But in node environment canvas may be created by node-canvas.
  22579. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  22580. *
  22581. * Be careful of using it in the browser.
  22582. *
  22583. * @param {Function} creator
  22584. * @example
  22585. * var Canvas = require('canvas');
  22586. * var echarts = require('echarts');
  22587. * echarts.setCanvasCreator(function () {
  22588. * // Small size is enough.
  22589. * return new Canvas(32, 32);
  22590. * });
  22591. */
  22592. function setCanvasCreator(creator) {
  22593. $override('createCanvas', creator);
  22594. }
  22595. /**
  22596. * @param {string} mapName
  22597. * @param {Object|string} geoJson
  22598. * @param {Object} [specialAreas]
  22599. *
  22600. * @example
  22601. * $.get('USA.json', function (geoJson) {
  22602. * echarts.registerMap('USA', geoJson);
  22603. * // Or
  22604. * echarts.registerMap('USA', {
  22605. * geoJson: geoJson,
  22606. * specialAreas: {}
  22607. * })
  22608. * });
  22609. */
  22610. function registerMap(mapName, geoJson, specialAreas) {
  22611. if (geoJson.geoJson && !geoJson.features) {
  22612. specialAreas = geoJson.specialAreas;
  22613. geoJson = geoJson.geoJson;
  22614. }
  22615. if (typeof geoJson === 'string') {
  22616. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  22617. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  22618. }
  22619. mapDataStores[mapName] = {
  22620. geoJson: geoJson,
  22621. specialAreas: specialAreas
  22622. };
  22623. }
  22624. /**
  22625. * @param {string} mapName
  22626. * @return {Object}
  22627. */
  22628. function getMap(mapName) {
  22629. return mapDataStores[mapName];
  22630. }
  22631. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  22632. registerPreprocessor(backwardCompat);
  22633. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  22634. registerLoading('default', loadingDefault);
  22635. // Default actions
  22636. registerAction({
  22637. type: 'highlight',
  22638. event: 'highlight',
  22639. update: 'highlight'
  22640. }, noop);
  22641. registerAction({
  22642. type: 'downplay',
  22643. event: 'downplay',
  22644. update: 'downplay'
  22645. }, noop);
  22646. // Default theme
  22647. registerTheme('light', lightTheme);
  22648. registerTheme('dark', theme);
  22649. // For backward compatibility, where the namespace `dataTool` will
  22650. // be mounted on `echarts` is the extension `dataTool` is imported.
  22651. var dataTool = {};
  22652. function defaultKeyGetter(item) {
  22653. return item;
  22654. }
  22655. /**
  22656. * @param {Array} oldArr
  22657. * @param {Array} newArr
  22658. * @param {Function} oldKeyGetter
  22659. * @param {Function} newKeyGetter
  22660. * @param {Object} [context] Can be visited by this.context in callback.
  22661. */
  22662. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  22663. this._old = oldArr;
  22664. this._new = newArr;
  22665. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  22666. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  22667. this.context = context;
  22668. }
  22669. DataDiffer.prototype = {
  22670. constructor: DataDiffer,
  22671. /**
  22672. * Callback function when add a data
  22673. */
  22674. add: function (func) {
  22675. this._add = func;
  22676. return this;
  22677. },
  22678. /**
  22679. * Callback function when update a data
  22680. */
  22681. update: function (func) {
  22682. this._update = func;
  22683. return this;
  22684. },
  22685. /**
  22686. * Callback function when remove a data
  22687. */
  22688. remove: function (func) {
  22689. this._remove = func;
  22690. return this;
  22691. },
  22692. execute: function () {
  22693. var oldArr = this._old;
  22694. var newArr = this._new;
  22695. var oldDataIndexMap = {};
  22696. var newDataIndexMap = {};
  22697. var oldDataKeyArr = [];
  22698. var newDataKeyArr = [];
  22699. var i;
  22700. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  22701. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  22702. // Travel by inverted order to make sure order consistency
  22703. // when duplicate keys exists (consider newDataIndex.pop() below).
  22704. // For performance consideration, these code below do not look neat.
  22705. for (i = 0; i < oldArr.length; i++) {
  22706. var key = oldDataKeyArr[i];
  22707. var idx = newDataIndexMap[key];
  22708. // idx can never be empty array here. see 'set null' logic below.
  22709. if (idx != null) {
  22710. // Consider there is duplicate key (for example, use dataItem.name as key).
  22711. // We should make sure every item in newArr and oldArr can be visited.
  22712. var len = idx.length;
  22713. if (len) {
  22714. len === 1 && (newDataIndexMap[key] = null);
  22715. idx = idx.unshift();
  22716. }
  22717. else {
  22718. newDataIndexMap[key] = null;
  22719. }
  22720. this._update && this._update(idx, i);
  22721. }
  22722. else {
  22723. this._remove && this._remove(i);
  22724. }
  22725. }
  22726. for (var i = 0; i < newDataKeyArr.length; i++) {
  22727. var key = newDataKeyArr[i];
  22728. if (newDataIndexMap.hasOwnProperty(key)) {
  22729. var idx = newDataIndexMap[key];
  22730. if (idx == null) {
  22731. continue;
  22732. }
  22733. // idx can never be empty array here. see 'set null' logic above.
  22734. if (!idx.length) {
  22735. this._add && this._add(idx);
  22736. }
  22737. else {
  22738. for (var j = 0, len = idx.length; j < len; j++) {
  22739. this._add && this._add(idx[j]);
  22740. }
  22741. }
  22742. }
  22743. }
  22744. }
  22745. };
  22746. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  22747. for (var i = 0; i < arr.length; i++) {
  22748. // Add prefix to avoid conflict with Object.prototype.
  22749. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  22750. var existence = map[key];
  22751. if (existence == null) {
  22752. keyArr.push(key);
  22753. map[key] = i;
  22754. }
  22755. else {
  22756. if (!existence.length) {
  22757. map[key] = existence = [existence];
  22758. }
  22759. existence.push(i);
  22760. }
  22761. }
  22762. }
  22763. var OTHER_DIMENSIONS = createHashMap([
  22764. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  22765. ]);
  22766. function summarizeDimensions(data) {
  22767. var summary = {};
  22768. var encode = summary.encode = {};
  22769. var notExtraCoordDimMap = createHashMap();
  22770. var defaultedLabel = [];
  22771. each$1(data.dimensions, function (dimName) {
  22772. var dimItem = data.getDimensionInfo(dimName);
  22773. var coordDim = dimItem.coordDim;
  22774. if (coordDim) {
  22775. if (__DEV__) {
  22776. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  22777. }
  22778. var coordDimArr = encode[coordDim];
  22779. if (!encode.hasOwnProperty(coordDim)) {
  22780. coordDimArr = encode[coordDim] = [];
  22781. }
  22782. coordDimArr[dimItem.coordDimIndex] = dimName;
  22783. if (!dimItem.isExtraCoord) {
  22784. notExtraCoordDimMap.set(coordDim, 1);
  22785. // Use the last coord dim (and label friendly) as default label,
  22786. // because when dataset is used, it is hard to guess which dimension
  22787. // can be value dimension. If both show x, y on label is not look good,
  22788. // and conventionally y axis is focused more.
  22789. if (mayLabelDimType(dimItem.type)) {
  22790. defaultedLabel[0] = dimName;
  22791. }
  22792. }
  22793. }
  22794. OTHER_DIMENSIONS.each(function (v, otherDim) {
  22795. var otherDimArr = encode[otherDim];
  22796. if (!encode.hasOwnProperty(otherDim)) {
  22797. otherDimArr = encode[otherDim] = [];
  22798. }
  22799. var dimIndex = dimItem.otherDims[otherDim];
  22800. if (dimIndex != null && dimIndex !== false) {
  22801. otherDimArr[dimIndex] = dimItem.name;
  22802. }
  22803. });
  22804. });
  22805. var dataDimsOnCoord = [];
  22806. var encodeFirstDimNotExtra = {};
  22807. notExtraCoordDimMap.each(function (v, coordDim) {
  22808. var dimArr = encode[coordDim];
  22809. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  22810. // But should fix the case that radar axes: simplify the logic
  22811. // of `completeDimension`, remove `extraPrefix`.
  22812. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  22813. // Not necessary to remove duplicate, because a data
  22814. // dim canot on more than one coordDim.
  22815. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  22816. });
  22817. summary.dataDimsOnCoord = dataDimsOnCoord;
  22818. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  22819. var encodeLabel = encode.label;
  22820. // FIXME `encode.label` is not recommanded, because formatter can not be set
  22821. // in this way. Use label.formatter instead. May be remove this approach someday.
  22822. if (encodeLabel && encodeLabel.length) {
  22823. defaultedLabel = encodeLabel.slice();
  22824. }
  22825. var defaultedTooltip = defaultedLabel.slice();
  22826. var encodeTooltip = encode.tooltip;
  22827. if (encodeTooltip && encodeTooltip.length) {
  22828. defaultedTooltip = encodeTooltip.slice();
  22829. }
  22830. encode.defaultedLabel = defaultedLabel;
  22831. encode.defaultedTooltip = defaultedTooltip;
  22832. return summary;
  22833. }
  22834. function getDimensionTypeByAxis(axisType) {
  22835. return axisType === 'category'
  22836. ? 'ordinal'
  22837. : axisType === 'time'
  22838. ? 'time'
  22839. : 'float';
  22840. }
  22841. function mayLabelDimType(dimType) {
  22842. // In most cases, ordinal and time do not suitable for label.
  22843. // Ordinal info can be displayed on axis. Time is too long.
  22844. return !(dimType === 'ordinal' || dimType === 'time');
  22845. }
  22846. // function findTheLastDimMayLabel(data) {
  22847. // // Get last value dim
  22848. // var dimensions = data.dimensions.slice();
  22849. // var valueType;
  22850. // var valueDim;
  22851. // while (dimensions.length && (
  22852. // valueDim = dimensions.pop(),
  22853. // valueType = data.getDimensionInfo(valueDim).type,
  22854. // valueType === 'ordinal' || valueType === 'time'
  22855. // )) {} // jshint ignore:line
  22856. // return valueDim;
  22857. // }
  22858. /**
  22859. * List for data storage
  22860. * @module echarts/data/List
  22861. */
  22862. var isObject$4 = isObject$1;
  22863. var UNDEFINED = 'undefined';
  22864. var globalObj = typeof window === UNDEFINED ? global : window;
  22865. // Use prefix to avoid index to be the same as otherIdList[idx],
  22866. // which will cause weird udpate animation.
  22867. var ID_PREFIX = 'e\0\0';
  22868. var dataCtors = {
  22869. 'float': typeof globalObj.Float64Array === UNDEFINED
  22870. ? Array : globalObj.Float64Array,
  22871. 'int': typeof globalObj.Int32Array === UNDEFINED
  22872. ? Array : globalObj.Int32Array,
  22873. // Ordinal data type can be string or int
  22874. 'ordinal': Array,
  22875. 'number': Array,
  22876. 'time': Array
  22877. };
  22878. var CtorUint32Array = typeof globalObj.Uint32Array === UNDEFINED ? Array : globalObj.Uint32Array;
  22879. var CtorUint16Array = typeof globalObj.Uint16Array === UNDEFINED ? Array : globalObj.Uint16Array;
  22880. function getIndicesCtor(list) {
  22881. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  22882. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  22883. }
  22884. function cloneChunk(originalChunk) {
  22885. var Ctor = originalChunk.constructor;
  22886. // Only shallow clone is enough when Array.
  22887. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  22888. }
  22889. var TRANSFERABLE_PROPERTIES = [
  22890. 'hasItemOption', '_nameList', '_idList', '_calculationInfo', '_invertedIndicesMap',
  22891. '_rawData', '_rawExtent', '_chunkSize', '_chunkCount',
  22892. '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  22893. ];
  22894. function transferProperties(a, b) {
  22895. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  22896. if (b.hasOwnProperty(propName)) {
  22897. a[propName] = b[propName];
  22898. }
  22899. });
  22900. a.__wrappedMethods = b.__wrappedMethods;
  22901. }
  22902. /**
  22903. * @constructor
  22904. * @alias module:echarts/data/List
  22905. *
  22906. * @param {Array.<string|Object>} dimensions
  22907. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  22908. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  22909. * Spetial fields: {
  22910. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  22911. * createInvertedIndices: <boolean>
  22912. * }
  22913. * @param {module:echarts/model/Model} hostModel
  22914. */
  22915. var List = function (dimensions, hostModel) {
  22916. dimensions = dimensions || ['x', 'y'];
  22917. var dimensionInfos = {};
  22918. var dimensionNames = [];
  22919. var invertedIndicesMap = {};
  22920. for (var i = 0; i < dimensions.length; i++) {
  22921. // Use the original dimensions[i], where other flag props may exists.
  22922. var dimensionInfo = dimensions[i];
  22923. if (isString(dimensionInfo)) {
  22924. dimensionInfo = {name: dimensionInfo};
  22925. }
  22926. var dimensionName = dimensionInfo.name;
  22927. dimensionInfo.type = dimensionInfo.type || 'float';
  22928. if (!dimensionInfo.coordDim) {
  22929. dimensionInfo.coordDim = dimensionName;
  22930. dimensionInfo.coordDimIndex = 0;
  22931. }
  22932. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  22933. dimensionNames.push(dimensionName);
  22934. dimensionInfos[dimensionName] = dimensionInfo;
  22935. dimensionInfo.index = i;
  22936. if (dimensionInfo.createInvertedIndices) {
  22937. invertedIndicesMap[dimensionName] = [];
  22938. }
  22939. }
  22940. /**
  22941. * @readOnly
  22942. * @type {Array.<string>}
  22943. */
  22944. this.dimensions = dimensionNames;
  22945. /**
  22946. * Infomation of each data dimension, like data type.
  22947. * @type {Object}
  22948. */
  22949. this._dimensionInfos = dimensionInfos;
  22950. /**
  22951. * @type {module:echarts/model/Model}
  22952. */
  22953. this.hostModel = hostModel;
  22954. /**
  22955. * @type {module:echarts/model/Model}
  22956. */
  22957. this.dataType;
  22958. /**
  22959. * Indices stores the indices of data subset after filtered.
  22960. * This data subset will be used in chart.
  22961. * @type {Array.<number>}
  22962. * @readOnly
  22963. */
  22964. this._indices = null;
  22965. this._count = 0;
  22966. this._rawCount = 0;
  22967. /**
  22968. * Data storage
  22969. * @type {Object.<key, Array.<TypedArray|Array>>}
  22970. * @private
  22971. */
  22972. this._storage = {};
  22973. /**
  22974. * @type {Array.<string>}
  22975. */
  22976. this._nameList = [];
  22977. /**
  22978. * @type {Array.<string>}
  22979. */
  22980. this._idList = [];
  22981. /**
  22982. * Models of data option is stored sparse for optimizing memory cost
  22983. * @type {Array.<module:echarts/model/Model>}
  22984. * @private
  22985. */
  22986. this._optionModels = [];
  22987. /**
  22988. * Global visual properties after visual coding
  22989. * @type {Object}
  22990. * @private
  22991. */
  22992. this._visual = {};
  22993. /**
  22994. * Globel layout properties.
  22995. * @type {Object}
  22996. * @private
  22997. */
  22998. this._layout = {};
  22999. /**
  23000. * Item visual properties after visual coding
  23001. * @type {Array.<Object>}
  23002. * @private
  23003. */
  23004. this._itemVisuals = [];
  23005. /**
  23006. * Key: visual type, Value: boolean
  23007. * @type {Object}
  23008. * @readOnly
  23009. */
  23010. this.hasItemVisual = {};
  23011. /**
  23012. * Item layout properties after layout
  23013. * @type {Array.<Object>}
  23014. * @private
  23015. */
  23016. this._itemLayouts = [];
  23017. /**
  23018. * Graphic elemnents
  23019. * @type {Array.<module:zrender/Element>}
  23020. * @private
  23021. */
  23022. this._graphicEls = [];
  23023. /**
  23024. * Max size of each chunk.
  23025. * @type {number}
  23026. * @private
  23027. */
  23028. this._chunkSize = 1e5;
  23029. /**
  23030. * @type {number}
  23031. * @private
  23032. */
  23033. this._chunkCount = 0;
  23034. /**
  23035. * @type {Array.<Array|Object>}
  23036. * @private
  23037. */
  23038. this._rawData;
  23039. /**
  23040. * Raw extent will not be cloned, but only transfered.
  23041. * It will not be calculated util needed.
  23042. * key: dim,
  23043. * value: {end: number, extent: Array.<number>}
  23044. * @type {Object}
  23045. * @private
  23046. */
  23047. this._rawExtent = {};
  23048. /**
  23049. * @type {Object}
  23050. * @private
  23051. */
  23052. this._extent = {};
  23053. /**
  23054. * key: dim
  23055. * value: extent
  23056. * @type {Object}
  23057. * @private
  23058. */
  23059. this._approximateExtent = {};
  23060. /**
  23061. * Cache summary info for fast visit. See "dimensionHelper".
  23062. * @type {Object}
  23063. * @private
  23064. */
  23065. this._dimensionsSummary = summarizeDimensions(this);
  23066. /**
  23067. * @type {Object.<Array|TypedArray>}
  23068. * @private
  23069. */
  23070. this._invertedIndicesMap = invertedIndicesMap;
  23071. /**
  23072. * @type {Object}
  23073. * @private
  23074. */
  23075. this._calculationInfo = {};
  23076. };
  23077. var listProto = List.prototype;
  23078. listProto.type = 'list';
  23079. /**
  23080. * If each data item has it's own option
  23081. * @type {boolean}
  23082. */
  23083. listProto.hasItemOption = true;
  23084. /**
  23085. * Get dimension name
  23086. * @param {string|number} dim
  23087. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  23088. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  23089. * @return {string} Concrete dim name.
  23090. */
  23091. listProto.getDimension = function (dim) {
  23092. if (!isNaN(dim)) {
  23093. dim = this.dimensions[dim] || dim;
  23094. }
  23095. return dim;
  23096. };
  23097. /**
  23098. * Get type and calculation info of particular dimension
  23099. * @param {string|number} dim
  23100. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  23101. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  23102. */
  23103. listProto.getDimensionInfo = function (dim) {
  23104. // Do not clone, because there may be categories in dimInfo.
  23105. return this._dimensionInfos[this.getDimension(dim)];
  23106. };
  23107. /**
  23108. * @return {Array.<string>} concrete dimension name list on coord.
  23109. */
  23110. listProto.getDimensionsOnCoord = function () {
  23111. return this._dimensionsSummary.dataDimsOnCoord.slice();
  23112. };
  23113. /**
  23114. * @param {string} coordDim
  23115. * @param {number} [idx] A coordDim may map to more than one data dim.
  23116. * If idx is `true`, return a array of all mapped dims.
  23117. * If idx is not specified, return the first dim not extra.
  23118. * @return {string|Array.<string>} concrete data dim.
  23119. * If idx is number, and not found, return null/undefined.
  23120. * If idx is `true`, and not found, return empty array (always return array).
  23121. */
  23122. listProto.mapDimension = function (coordDim, idx) {
  23123. var dimensionsSummary = this._dimensionsSummary;
  23124. if (idx == null) {
  23125. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  23126. }
  23127. var dims = dimensionsSummary.encode[coordDim];
  23128. return idx === true
  23129. // always return array if idx is `true`
  23130. ? (dims || []).slice()
  23131. : (dims && dims[idx]);
  23132. };
  23133. /**
  23134. * Initialize from data
  23135. * @param {Array.<Object|number|Array>} data source or data or data provider.
  23136. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  23137. * defualt label/tooltip.
  23138. * A name can be specified in encode.itemName,
  23139. * or dataItem.name (only for series option data),
  23140. * or provided in nameList from outside.
  23141. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  23142. */
  23143. listProto.initData = function (data, nameList, dimValueGetter) {
  23144. var notProvider = Source.isInstance(data) || isArrayLike(data);
  23145. if (notProvider) {
  23146. data = new DefaultDataProvider(data, this.dimensions.length);
  23147. }
  23148. if (__DEV__) {
  23149. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  23150. throw new Error('Inavlid data provider.');
  23151. }
  23152. }
  23153. this._rawData = data;
  23154. // Clear
  23155. this._storage = {};
  23156. this._indices = null;
  23157. this._nameList = nameList || [];
  23158. this._idList = [];
  23159. this._nameRepeatCount = {};
  23160. if (!dimValueGetter) {
  23161. this.hasItemOption = false;
  23162. }
  23163. /**
  23164. * @readOnly
  23165. */
  23166. this.defaultDimValueGetter = defaultDimValueGetters[
  23167. this._rawData.getSource().sourceFormat
  23168. ];
  23169. // Default dim value getter
  23170. this._dimValueGetter = dimValueGetter = dimValueGetter
  23171. || this.defaultDimValueGetter;
  23172. // Reset raw extent.
  23173. this._rawExtent = {};
  23174. this._initDataFromProvider(0, data.count());
  23175. // If data has no item option.
  23176. if (data.pure) {
  23177. this.hasItemOption = false;
  23178. }
  23179. };
  23180. listProto.getProvider = function () {
  23181. return this._rawData;
  23182. };
  23183. listProto.appendData = function (data) {
  23184. if (__DEV__) {
  23185. assert$1(!this._indices, 'appendData can only be called on raw data.');
  23186. }
  23187. var rawData = this._rawData;
  23188. var start = this.count();
  23189. rawData.appendData(data);
  23190. var end = rawData.count();
  23191. if (!rawData.persistent) {
  23192. end += start;
  23193. }
  23194. this._initDataFromProvider(start, end);
  23195. };
  23196. listProto._initDataFromProvider = function (start, end) {
  23197. // Optimize.
  23198. if (start >= end) {
  23199. return;
  23200. }
  23201. var chunkSize = this._chunkSize;
  23202. var rawData = this._rawData;
  23203. var storage = this._storage;
  23204. var dimensions = this.dimensions;
  23205. var dimensionInfoMap = this._dimensionInfos;
  23206. var nameList = this._nameList;
  23207. var idList = this._idList;
  23208. var rawExtent = this._rawExtent;
  23209. var nameRepeatCount = this._nameRepeatCount = {};
  23210. var nameDimIdx;
  23211. var chunkCount = this._chunkCount;
  23212. var lastChunkIndex = chunkCount - 1;
  23213. for (var i = 0; i < dimensions.length; i++) {
  23214. var dim = dimensions[i];
  23215. if (!rawExtent[dim]) {
  23216. rawExtent[dim] = getInitialExtent();
  23217. }
  23218. var dimInfo = dimensionInfoMap[dim];
  23219. if (dimInfo.otherDims.itemName === 0) {
  23220. nameDimIdx = this._nameDimIdx = i;
  23221. }
  23222. if (dimInfo.otherDims.itemId === 0) {
  23223. this._idDimIdx = i;
  23224. }
  23225. var DataCtor = dataCtors[dimInfo.type];
  23226. if (!storage[dim]) {
  23227. storage[dim] = [];
  23228. }
  23229. var resizeChunkArray = storage[dim][lastChunkIndex];
  23230. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  23231. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  23232. // The cost of the copy is probably inconsiderable
  23233. // within the initial chunkSize.
  23234. for (var j = 0; j < resizeChunkArray.length; j++) {
  23235. newStore[j] = resizeChunkArray[j];
  23236. }
  23237. storage[dim][lastChunkIndex] = newStore;
  23238. }
  23239. // Create new chunks.
  23240. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  23241. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  23242. }
  23243. this._chunkCount = storage[dim].length;
  23244. }
  23245. for (var idx = start; idx < end; idx++) {
  23246. // NOTICE: Try not to write things into dataItem
  23247. var dataItem = rawData.getItem(idx);
  23248. // Each data item is value
  23249. // [1, 2]
  23250. // 2
  23251. // Bar chart, line chart which uses category axis
  23252. // only gives the 'y' value. 'x' value is the indices of category
  23253. // Use a tempValue to normalize the value to be a (x, y) value
  23254. var chunkIndex = Math.floor(idx / chunkSize);
  23255. var chunkOffset = idx % chunkSize;
  23256. // Store the data by dimensions
  23257. for (var k = 0; k < dimensions.length; k++) {
  23258. var dim = dimensions[k];
  23259. var dimStorage = storage[dim][chunkIndex];
  23260. // PENDING NULL is empty or zero
  23261. var val = this._dimValueGetter(dataItem, dim, idx, k);
  23262. dimStorage[chunkOffset] = val;
  23263. if (val < rawExtent[dim][0]) {
  23264. rawExtent[dim][0] = val;
  23265. }
  23266. if (val > rawExtent[dim][1]) {
  23267. rawExtent[dim][1] = val;
  23268. }
  23269. }
  23270. // ??? FIXME not check by pure but sourceFormat?
  23271. // TODO refactor these logic.
  23272. if (!rawData.pure) {
  23273. var name = nameList[idx];
  23274. if (dataItem && !name) {
  23275. if (nameDimIdx != null) {
  23276. name = this._getNameFromStore(idx);
  23277. }
  23278. else if (dataItem.name != null) {
  23279. // There is no other place to persistent dataItem.name,
  23280. // so save it to nameList.
  23281. nameList[idx] = name = dataItem.name;
  23282. }
  23283. }
  23284. // Try using the id in option
  23285. // id or name is used on dynamical data, mapping old and new items.
  23286. var id = dataItem == null ? null : dataItem.id;
  23287. if (id == null && name != null) {
  23288. // Use name as id and add counter to avoid same name
  23289. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  23290. id = name;
  23291. if (nameRepeatCount[name] > 0) {
  23292. id += '__ec__' + nameRepeatCount[name];
  23293. }
  23294. nameRepeatCount[name]++;
  23295. }
  23296. id != null && (idList[idx] = id);
  23297. }
  23298. }
  23299. if (!rawData.persistent && rawData.clean) {
  23300. // Clean unused data if data source is typed array.
  23301. rawData.clean();
  23302. }
  23303. this._rawCount = this._count = end;
  23304. // Reset data extent
  23305. this._extent = {};
  23306. prepareInvertedIndex(this);
  23307. };
  23308. function prepareInvertedIndex(list) {
  23309. var invertedIndicesMap = list._invertedIndicesMap;
  23310. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  23311. var dimInfo = list._dimensionInfos[dim];
  23312. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  23313. var ordinalMeta = dimInfo.ordinalMeta;
  23314. if (ordinalMeta) {
  23315. invertedIndices = invertedIndicesMap[dim] = new CtorUint32Array(
  23316. ordinalMeta.categories.length
  23317. );
  23318. // The default value of TypedArray is 0. To avoid miss
  23319. // mapping to 0, we should set it as NaN.
  23320. for (var i = 0; i < invertedIndices.length; i++) {
  23321. invertedIndices[i] = NaN;
  23322. }
  23323. for (var i = 0; i < list._count; i++) {
  23324. // Only support the case that all values are distinct.
  23325. invertedIndices[list.get(dim, i)] = i;
  23326. }
  23327. }
  23328. });
  23329. }
  23330. // TODO refactor
  23331. listProto._getNameFromStore = function (rawIndex) {
  23332. var nameDimIdx = this._nameDimIdx;
  23333. if (nameDimIdx != null) {
  23334. var chunkSize = this._chunkSize;
  23335. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23336. var chunkOffset = rawIndex % chunkSize;
  23337. var dim = this.dimensions[nameDimIdx];
  23338. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23339. if (ordinalMeta) {
  23340. return ordinalMeta.categories[rawIndex];
  23341. }
  23342. else {
  23343. var chunk = this._storage[dim][chunkIndex];
  23344. return chunk && chunk[chunkOffset];
  23345. }
  23346. }
  23347. };
  23348. // TODO refactor
  23349. listProto._getIdFromStore = function (rawIndex) {
  23350. var idDimIdx = this._idDimIdx;
  23351. if (idDimIdx != null) {
  23352. var chunkSize = this._chunkSize;
  23353. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23354. var chunkOffset = rawIndex % chunkSize;
  23355. var dim = this.dimensions[idDimIdx];
  23356. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  23357. if (ordinalMeta) {
  23358. return ordinalMeta.categories[rawIndex];
  23359. }
  23360. else {
  23361. var chunk = this._storage[dim][chunkIndex];
  23362. return chunk && chunk[chunkOffset];
  23363. }
  23364. }
  23365. };
  23366. /**
  23367. * @return {number}
  23368. */
  23369. listProto.count = function () {
  23370. return this._count;
  23371. };
  23372. listProto.getIndices = function () {
  23373. if (this._indices) {
  23374. var Ctor = this._indices.constructor;
  23375. return new Ctor(this._indices.buffer, 0, this._count);
  23376. }
  23377. var Ctor = getIndicesCtor(this);
  23378. var arr = new Ctor(this.count());
  23379. for (var i = 0; i < arr.length; i++) {
  23380. arr[i] = i;
  23381. }
  23382. return arr;
  23383. };
  23384. /**
  23385. * Get value. Return NaN if idx is out of range.
  23386. * @param {string} dim Dim must be concrete name.
  23387. * @param {number} idx
  23388. * @param {boolean} stack
  23389. * @return {number}
  23390. */
  23391. listProto.get = function (dim, idx /*, stack */) {
  23392. if (!(idx >= 0 && idx < this._count)) {
  23393. return NaN;
  23394. }
  23395. var storage = this._storage;
  23396. if (!storage[dim]) {
  23397. // TODO Warn ?
  23398. return NaN;
  23399. }
  23400. idx = this.getRawIndex(idx);
  23401. var chunkIndex = Math.floor(idx / this._chunkSize);
  23402. var chunkOffset = idx % this._chunkSize;
  23403. var chunkStore = storage[dim][chunkIndex];
  23404. var value = chunkStore[chunkOffset];
  23405. // FIXME ordinal data type is not stackable
  23406. // if (stack) {
  23407. // var dimensionInfo = this._dimensionInfos[dim];
  23408. // if (dimensionInfo && dimensionInfo.stackable) {
  23409. // var stackedOn = this.stackedOn;
  23410. // while (stackedOn) {
  23411. // // Get no stacked data of stacked on
  23412. // var stackedValue = stackedOn.get(dim, idx);
  23413. // // Considering positive stack, negative stack and empty data
  23414. // if ((value >= 0 && stackedValue > 0) // Positive stack
  23415. // || (value <= 0 && stackedValue < 0) // Negative stack
  23416. // ) {
  23417. // value += stackedValue;
  23418. // }
  23419. // stackedOn = stackedOn.stackedOn;
  23420. // }
  23421. // }
  23422. // }
  23423. return value;
  23424. };
  23425. /**
  23426. * @param {string} dim concrete dim
  23427. * @param {number} rawIndex
  23428. * @return {number|string}
  23429. */
  23430. listProto.getByRawIndex = function (dim, rawIdx) {
  23431. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  23432. return NaN;
  23433. }
  23434. var dimStore = this._storage[dim];
  23435. if (!dimStore) {
  23436. // TODO Warn ?
  23437. return NaN;
  23438. }
  23439. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23440. var chunkOffset = rawIdx % this._chunkSize;
  23441. var chunkStore = dimStore[chunkIndex];
  23442. return chunkStore[chunkOffset];
  23443. };
  23444. /**
  23445. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  23446. * Hack a much simpler _getFast
  23447. * @private
  23448. */
  23449. listProto._getFast = function (dim, rawIdx) {
  23450. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  23451. var chunkOffset = rawIdx % this._chunkSize;
  23452. var chunkStore = this._storage[dim][chunkIndex];
  23453. return chunkStore[chunkOffset];
  23454. };
  23455. /**
  23456. * Get value for multi dimensions.
  23457. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  23458. * @param {number} idx
  23459. * @return {number}
  23460. */
  23461. listProto.getValues = function (dimensions, idx /*, stack */) {
  23462. var values = [];
  23463. if (!isArray(dimensions)) {
  23464. // stack = idx;
  23465. idx = dimensions;
  23466. dimensions = this.dimensions;
  23467. }
  23468. for (var i = 0, len = dimensions.length; i < len; i++) {
  23469. values.push(this.get(dimensions[i], idx /*, stack */));
  23470. }
  23471. return values;
  23472. };
  23473. /**
  23474. * If value is NaN. Inlcuding '-'
  23475. * Only check the coord dimensions.
  23476. * @param {string} dim
  23477. * @param {number} idx
  23478. * @return {number}
  23479. */
  23480. listProto.hasValue = function (idx) {
  23481. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  23482. var dimensionInfos = this._dimensionInfos;
  23483. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  23484. if (
  23485. // Ordinal type can be string or number
  23486. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  23487. // FIXME check ordinal when using index?
  23488. && isNaN(this.get(dataDimsOnCoord[i], idx))
  23489. ) {
  23490. return false;
  23491. }
  23492. }
  23493. return true;
  23494. };
  23495. /**
  23496. * Get extent of data in one dimension
  23497. * @param {string} dim
  23498. * @param {boolean} stack
  23499. */
  23500. listProto.getDataExtent = function (dim /*, stack */) {
  23501. // Make sure use concrete dim as cache name.
  23502. dim = this.getDimension(dim);
  23503. var dimData = this._storage[dim];
  23504. var initialExtent = getInitialExtent();
  23505. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  23506. if (!dimData) {
  23507. return initialExtent;
  23508. }
  23509. // Make more strict checkings to ensure hitting cache.
  23510. var currEnd = this.count();
  23511. // var cacheName = [dim, !!stack].join('_');
  23512. // var cacheName = dim;
  23513. // Consider the most cases when using data zoom, `getDataExtent`
  23514. // happened before filtering. We cache raw extent, which is not
  23515. // necessary to be cleared and recalculated when restore data.
  23516. var useRaw = !this._indices; // && !stack;
  23517. var dimExtent;
  23518. if (useRaw) {
  23519. return this._rawExtent[dim].slice();
  23520. }
  23521. dimExtent = this._extent[dim];
  23522. if (dimExtent) {
  23523. return dimExtent.slice();
  23524. }
  23525. dimExtent = initialExtent;
  23526. var min = dimExtent[0];
  23527. var max = dimExtent[1];
  23528. for (var i = 0; i < currEnd; i++) {
  23529. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  23530. var value = this._getFast(dim, this.getRawIndex(i));
  23531. value < min && (min = value);
  23532. value > max && (max = value);
  23533. }
  23534. dimExtent = [min, max];
  23535. this._extent[dim] = dimExtent;
  23536. return dimExtent;
  23537. };
  23538. /**
  23539. * Optimize for the scenario that data is filtered by a given extent.
  23540. * Consider that if data amount is more than hundreds of thousand,
  23541. * extent calculation will cost more than 10ms and the cache will
  23542. * be erased because of the filtering.
  23543. */
  23544. listProto.getApproximateExtent = function (dim /*, stack */) {
  23545. dim = this.getDimension(dim);
  23546. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  23547. };
  23548. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  23549. dim = this.getDimension(dim);
  23550. this._approximateExtent[dim] = extent.slice();
  23551. };
  23552. /**
  23553. * @param {string} key
  23554. * @return {*}
  23555. */
  23556. listProto.getCalculationInfo = function (key) {
  23557. return this._calculationInfo[key];
  23558. };
  23559. /**
  23560. * @param {string|Object} key or k-v object
  23561. * @param {*} [value]
  23562. */
  23563. listProto.setCalculationInfo = function (key, value) {
  23564. isObject$4(key)
  23565. ? extend(this._calculationInfo, key)
  23566. : (this._calculationInfo[key] = value);
  23567. };
  23568. /**
  23569. * Get sum of data in one dimension
  23570. * @param {string} dim
  23571. */
  23572. listProto.getSum = function (dim /*, stack */) {
  23573. var dimData = this._storage[dim];
  23574. var sum = 0;
  23575. if (dimData) {
  23576. for (var i = 0, len = this.count(); i < len; i++) {
  23577. var value = this.get(dim, i /*, stack */);
  23578. if (!isNaN(value)) {
  23579. sum += value;
  23580. }
  23581. }
  23582. }
  23583. return sum;
  23584. };
  23585. // /**
  23586. // * Retreive the index with given value
  23587. // * @param {string} dim Concrete dimension.
  23588. // * @param {number} value
  23589. // * @return {number}
  23590. // */
  23591. // Currently incorrect: should return dataIndex but not rawIndex.
  23592. // Do not fix it until this method is to be used somewhere.
  23593. // FIXME Precision of float value
  23594. // listProto.indexOf = function (dim, value) {
  23595. // var storage = this._storage;
  23596. // var dimData = storage[dim];
  23597. // var chunkSize = this._chunkSize;
  23598. // if (dimData) {
  23599. // for (var i = 0, len = this.count(); i < len; i++) {
  23600. // var chunkIndex = Math.floor(i / chunkSize);
  23601. // var chunkOffset = i % chunkSize;
  23602. // if (dimData[chunkIndex][chunkOffset] === value) {
  23603. // return i;
  23604. // }
  23605. // }
  23606. // }
  23607. // return -1;
  23608. // };
  23609. /**
  23610. * Only support the dimension which inverted index created.
  23611. * Do not support other cases until required.
  23612. * @param {string} concrete dim
  23613. * @param {number|string} value
  23614. * @return {number} rawIndex
  23615. */
  23616. listProto.rawIndexOf = function (dim, value) {
  23617. var invertedIndices = dim && this._invertedIndicesMap[dim];
  23618. if (__DEV__) {
  23619. if (!invertedIndices) {
  23620. throw new Error('Do not supported yet');
  23621. }
  23622. }
  23623. var rawIndex = invertedIndices[value];
  23624. if (rawIndex == null || isNaN(rawIndex)) {
  23625. return -1;
  23626. }
  23627. return rawIndex;
  23628. };
  23629. /**
  23630. * Retreive the index with given name
  23631. * @param {number} idx
  23632. * @param {number} name
  23633. * @return {number}
  23634. */
  23635. listProto.indexOfName = function (name) {
  23636. for (var i = 0, len = this.count(); i < len; i++) {
  23637. if (this.getName(i) === name) {
  23638. return i;
  23639. }
  23640. }
  23641. return -1;
  23642. };
  23643. /**
  23644. * Retreive the index with given raw data index
  23645. * @param {number} idx
  23646. * @param {number} name
  23647. * @return {number}
  23648. */
  23649. listProto.indexOfRawIndex = function (rawIndex) {
  23650. if (!this._indices) {
  23651. return rawIndex;
  23652. }
  23653. if (rawIndex >= this._rawCount || rawIndex < 0) {
  23654. return -1;
  23655. }
  23656. // Indices are ascending
  23657. var indices = this._indices;
  23658. // If rawIndex === dataIndex
  23659. var rawDataIndex = indices[rawIndex];
  23660. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  23661. return rawIndex;
  23662. }
  23663. var left = 0;
  23664. var right = this._count - 1;
  23665. while (left <= right) {
  23666. var mid = (left + right) / 2 | 0;
  23667. if (indices[mid] < rawIndex) {
  23668. left = mid + 1;
  23669. }
  23670. else if (indices[mid] > rawIndex) {
  23671. right = mid - 1;
  23672. }
  23673. else {
  23674. return mid;
  23675. }
  23676. }
  23677. return -1;
  23678. };
  23679. /**
  23680. * Retreive the index of nearest value
  23681. * @param {string} dim
  23682. * @param {number} value
  23683. * @param {number} [maxDistance=Infinity]
  23684. * @return {Array.<number>} Considere multiple points has the same value.
  23685. */
  23686. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  23687. var storage = this._storage;
  23688. var dimData = storage[dim];
  23689. var nearestIndices = [];
  23690. if (!dimData) {
  23691. return nearestIndices;
  23692. }
  23693. if (maxDistance == null) {
  23694. maxDistance = Infinity;
  23695. }
  23696. var minDist = Number.MAX_VALUE;
  23697. var minDiff = -1;
  23698. for (var i = 0, len = this.count(); i < len; i++) {
  23699. var diff = value - this.get(dim, i /*, stack */);
  23700. var dist = Math.abs(diff);
  23701. if (diff <= maxDistance && dist <= minDist) {
  23702. // For the case of two data are same on xAxis, which has sequence data.
  23703. // Show the nearest index
  23704. // https://github.com/ecomfe/echarts/issues/2869
  23705. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  23706. minDist = dist;
  23707. minDiff = diff;
  23708. nearestIndices.length = 0;
  23709. }
  23710. nearestIndices.push(i);
  23711. }
  23712. }
  23713. return nearestIndices;
  23714. };
  23715. /**
  23716. * Get raw data index
  23717. * @param {number} idx
  23718. * @return {number}
  23719. */
  23720. listProto.getRawIndex = getRawIndexWithoutIndices;
  23721. function getRawIndexWithoutIndices(idx) {
  23722. return idx;
  23723. }
  23724. function getRawIndexWithIndices(idx) {
  23725. if (idx < this._count && idx >= 0) {
  23726. return this._indices[idx];
  23727. }
  23728. return -1;
  23729. }
  23730. /**
  23731. * Get raw data item
  23732. * @param {number} idx
  23733. * @return {number}
  23734. */
  23735. listProto.getRawDataItem = function (idx) {
  23736. if (!this._rawData.persistent) {
  23737. var val = [];
  23738. for (var i = 0; i < this.dimensions.length; i++) {
  23739. var dim = this.dimensions[i];
  23740. val.push(this.get(dim, idx));
  23741. }
  23742. return val;
  23743. }
  23744. else {
  23745. return this._rawData.getItem(this.getRawIndex(idx));
  23746. }
  23747. };
  23748. /**
  23749. * @param {number} idx
  23750. * @param {boolean} [notDefaultIdx=false]
  23751. * @return {string}
  23752. */
  23753. listProto.getName = function (idx) {
  23754. var rawIndex = this.getRawIndex(idx);
  23755. return this._nameList[rawIndex]
  23756. || this._getNameFromStore(rawIndex)
  23757. || '';
  23758. };
  23759. /**
  23760. * @param {number} idx
  23761. * @param {boolean} [notDefaultIdx=false]
  23762. * @return {string}
  23763. */
  23764. listProto.getId = function (idx) {
  23765. return getId(this, this.getRawIndex(idx));
  23766. };
  23767. function getId(list, rawIndex) {
  23768. var id = list._idList[rawIndex];
  23769. if (id == null) {
  23770. id = list._getIdFromStore(rawIndex);
  23771. }
  23772. if (id == null) {
  23773. // FIXME Check the usage in graph, should not use prefix.
  23774. id = ID_PREFIX + rawIndex;
  23775. }
  23776. return id;
  23777. }
  23778. function normalizeDimensions(dimensions) {
  23779. if (!isArray(dimensions)) {
  23780. dimensions = [dimensions];
  23781. }
  23782. return dimensions;
  23783. }
  23784. function validateDimensions(list, dims) {
  23785. for (var i = 0; i < dims.length; i++) {
  23786. // stroage may be empty when no data, so use
  23787. // dimensionInfos to check.
  23788. if (!list._dimensionInfos[dims[i]]) {
  23789. console.error('Unkown dimension ' + dims[i]);
  23790. }
  23791. }
  23792. }
  23793. /**
  23794. * Data iteration
  23795. * @param {string|Array.<string>}
  23796. * @param {Function} cb
  23797. * @param {*} [context=this]
  23798. *
  23799. * @example
  23800. * list.each('x', function (x, idx) {});
  23801. * list.each(['x', 'y'], function (x, y, idx) {});
  23802. * list.each(function (idx) {})
  23803. */
  23804. listProto.each = function (dims, cb, context, contextCompat) {
  23805. 'use strict';
  23806. if (!this._count) {
  23807. return;
  23808. }
  23809. if (typeof dims === 'function') {
  23810. contextCompat = context;
  23811. context = cb;
  23812. cb = dims;
  23813. dims = [];
  23814. }
  23815. // contextCompat just for compat echarts3
  23816. context = context || contextCompat || this;
  23817. dims = map(normalizeDimensions(dims), this.getDimension, this);
  23818. if (__DEV__) {
  23819. validateDimensions(this, dims);
  23820. }
  23821. var dimSize = dims.length;
  23822. for (var i = 0; i < this.count(); i++) {
  23823. // Simple optimization
  23824. switch (dimSize) {
  23825. case 0:
  23826. cb.call(context, i);
  23827. break;
  23828. case 1:
  23829. cb.call(context, this.get(dims[0], i), i);
  23830. break;
  23831. case 2:
  23832. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  23833. break;
  23834. default:
  23835. var k = 0;
  23836. var value = [];
  23837. for (; k < dimSize; k++) {
  23838. value[k] = this.get(dims[k], i);
  23839. }
  23840. // Index
  23841. value[k] = i;
  23842. cb.apply(context, value);
  23843. }
  23844. }
  23845. };
  23846. /**
  23847. * Data filter
  23848. * @param {string|Array.<string>}
  23849. * @param {Function} cb
  23850. * @param {*} [context=this]
  23851. */
  23852. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  23853. 'use strict';
  23854. if (!this._count) {
  23855. return;
  23856. }
  23857. if (typeof dimensions === 'function') {
  23858. contextCompat = context;
  23859. context = cb;
  23860. cb = dimensions;
  23861. dimensions = [];
  23862. }
  23863. // contextCompat just for compat echarts3
  23864. context = context || contextCompat || this;
  23865. dimensions = map(
  23866. normalizeDimensions(dimensions), this.getDimension, this
  23867. );
  23868. if (__DEV__) {
  23869. validateDimensions(this, dimensions);
  23870. }
  23871. var count = this.count();
  23872. var Ctor = getIndicesCtor(this);
  23873. var newIndices = new Ctor(count);
  23874. var value = [];
  23875. var dimSize = dimensions.length;
  23876. var offset = 0;
  23877. var dim0 = dimensions[0];
  23878. for (var i = 0; i < count; i++) {
  23879. var keep;
  23880. var rawIdx = this.getRawIndex(i);
  23881. // Simple optimization
  23882. if (dimSize === 0) {
  23883. keep = cb.call(context, i);
  23884. }
  23885. else if (dimSize === 1) {
  23886. var val = this._getFast(dim0, rawIdx);
  23887. keep = cb.call(context, val, i);
  23888. }
  23889. else {
  23890. for (var k = 0; k < dimSize; k++) {
  23891. value[k] = this._getFast(dim0, rawIdx);
  23892. }
  23893. value[k] = i;
  23894. keep = cb.apply(context, value);
  23895. }
  23896. if (keep) {
  23897. newIndices[offset++] = rawIdx;
  23898. }
  23899. }
  23900. // Set indices after filtered.
  23901. if (offset < count) {
  23902. this._indices = newIndices;
  23903. }
  23904. this._count = offset;
  23905. // Reset data extent
  23906. this._extent = {};
  23907. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23908. return this;
  23909. };
  23910. /**
  23911. * Select data in range. (For optimization of filter)
  23912. * (Manually inline code, support 5 million data filtering in data zoom.)
  23913. */
  23914. listProto.selectRange = function (range /*, stack */) {
  23915. 'use strict';
  23916. if (!this._count) {
  23917. return;
  23918. }
  23919. // stack = stack || false;
  23920. var dimensions = [];
  23921. for (var dim in range) {
  23922. if (range.hasOwnProperty(dim)) {
  23923. dimensions.push(dim);
  23924. }
  23925. }
  23926. if (__DEV__) {
  23927. validateDimensions(this, dimensions);
  23928. }
  23929. var dimSize = dimensions.length;
  23930. if (!dimSize) {
  23931. return;
  23932. }
  23933. var originalCount = this.count();
  23934. var Ctor = getIndicesCtor(this);
  23935. var newIndices = new Ctor(originalCount);
  23936. var offset = 0;
  23937. var dim0 = dimensions[0];
  23938. var min = range[dim0][0];
  23939. var max = range[dim0][1];
  23940. var quickFinished = false;
  23941. if (!this._indices /* && !stack */) {
  23942. // Extreme optimization for common case. About 2x faster in chrome.
  23943. var idx = 0;
  23944. if (dimSize === 1) {
  23945. var dimStorage = this._storage[dimensions[0]];
  23946. for (var k = 0; k < this._chunkCount; k++) {
  23947. var chunkStorage = dimStorage[k];
  23948. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23949. for (var i = 0; i < len; i++) {
  23950. var val = chunkStorage[i];
  23951. if (val >= min && val <= max) {
  23952. newIndices[offset++] = idx;
  23953. }
  23954. idx++;
  23955. }
  23956. }
  23957. quickFinished = true;
  23958. }
  23959. else if (dimSize === 2) {
  23960. var dimStorage = this._storage[dim0];
  23961. var dimStorage2 = this._storage[dimensions[1]];
  23962. var min2 = range[dimensions[1]][0];
  23963. var max2 = range[dimensions[1]][1];
  23964. for (var k = 0; k < this._chunkCount; k++) {
  23965. var chunkStorage = dimStorage[k];
  23966. var chunkStorage2= dimStorage2[k];
  23967. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23968. for (var i = 0; i < len; i++) {
  23969. var val = chunkStorage[i];
  23970. var val2 = chunkStorage2[i];
  23971. if (val >= min && val <= max && val2 >= min2 && val2 <= max2) {
  23972. newIndices[offset++] = idx;
  23973. }
  23974. idx++;
  23975. }
  23976. }
  23977. quickFinished = true;
  23978. }
  23979. }
  23980. if (!quickFinished) {
  23981. if (dimSize === 1) {
  23982. // stack = stack || !!this.getCalculationInfo(dim0);
  23983. for (var i = 0; i < originalCount; i++) {
  23984. var rawIndex = this.getRawIndex(i);
  23985. // var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIndex);
  23986. var val = this._getFast(dim0, rawIndex);
  23987. if (val >= min && val <= max) {
  23988. newIndices[offset++] = rawIndex;
  23989. }
  23990. }
  23991. }
  23992. else {
  23993. for (var i = 0; i < originalCount; i++) {
  23994. var keep = true;
  23995. var rawIndex = this.getRawIndex(i);
  23996. for (var k = 0; k < dimSize; k++) {
  23997. var dimk = dimensions[k];
  23998. // var val = stack ? this.get(dimk, i, true) : this._getFast(dim, rawIndex);
  23999. var val = this._getFast(dim, rawIndex);
  24000. if (val < range[dimk][0] || val > range[dimk][1]) {
  24001. keep = false;
  24002. }
  24003. }
  24004. if (keep) {
  24005. newIndices[offset++] = this.getRawIndex(i);
  24006. }
  24007. }
  24008. }
  24009. }
  24010. // Set indices after filtered.
  24011. if (offset < originalCount) {
  24012. this._indices = newIndices;
  24013. }
  24014. this._count = offset;
  24015. // Reset data extent
  24016. this._extent = {};
  24017. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24018. return this;
  24019. };
  24020. /**
  24021. * Data mapping to a plain array
  24022. * @param {string|Array.<string>} [dimensions]
  24023. * @param {Function} cb
  24024. * @param {*} [context=this]
  24025. * @return {Array}
  24026. */
  24027. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  24028. 'use strict';
  24029. if (typeof dimensions === 'function') {
  24030. contextCompat = context;
  24031. context = cb;
  24032. cb = dimensions;
  24033. dimensions = [];
  24034. }
  24035. // contextCompat just for compat echarts3
  24036. context = context || contextCompat || this;
  24037. var result = [];
  24038. this.each(dimensions, function () {
  24039. result.push(cb && cb.apply(this, arguments));
  24040. }, context);
  24041. return result;
  24042. };
  24043. // Data in excludeDimensions is copied, otherwise transfered.
  24044. function cloneListForMapAndSample(original, excludeDimensions) {
  24045. var allDimensions = original.dimensions;
  24046. var list = new List(
  24047. map(allDimensions, original.getDimensionInfo, original),
  24048. original.hostModel
  24049. );
  24050. // FIXME If needs stackedOn, value may already been stacked
  24051. transferProperties(list, original);
  24052. var storage = list._storage = {};
  24053. var originalStorage = original._storage;
  24054. var rawExtent = extend({}, original._rawExtent);
  24055. // Init storage
  24056. for (var i = 0; i < allDimensions.length; i++) {
  24057. var dim = allDimensions[i];
  24058. if (originalStorage[dim]) {
  24059. if (indexOf(excludeDimensions, dim) >= 0) {
  24060. storage[dim] = cloneDimStore(originalStorage[dim]);
  24061. rawExtent[dim] = getInitialExtent();
  24062. }
  24063. else {
  24064. // Direct reference for other dimensions
  24065. storage[dim] = originalStorage[dim];
  24066. }
  24067. }
  24068. }
  24069. return list;
  24070. }
  24071. function cloneDimStore(originalDimStore) {
  24072. var newDimStore = new Array(originalDimStore.length);
  24073. for (var j = 0; j < originalDimStore.length; j++) {
  24074. newDimStore[j] = cloneChunk(originalDimStore[j]);
  24075. }
  24076. return newDimStore;
  24077. }
  24078. function getInitialExtent() {
  24079. return [Infinity, -Infinity];
  24080. }
  24081. /**
  24082. * Data mapping to a new List with given dimensions
  24083. * @param {string|Array.<string>} dimensions
  24084. * @param {Function} cb
  24085. * @param {*} [context=this]
  24086. * @return {Array}
  24087. */
  24088. listProto.map = function (dimensions, cb, context, contextCompat) {
  24089. 'use strict';
  24090. // contextCompat just for compat echarts3
  24091. context = context || contextCompat || this;
  24092. dimensions = map(
  24093. normalizeDimensions(dimensions), this.getDimension, this
  24094. );
  24095. if (__DEV__) {
  24096. validateDimensions(this, dimensions);
  24097. }
  24098. var list = cloneListForMapAndSample(this, dimensions);
  24099. // Following properties are all immutable.
  24100. // So we can reference to the same value
  24101. list._indices = this._indices;
  24102. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24103. var storage = list._storage;
  24104. var tmpRetValue = [];
  24105. var chunkSize = this._chunkSize;
  24106. var dimSize = dimensions.length;
  24107. var dataCount = this.count();
  24108. var values = [];
  24109. var rawExtent = list._rawExtent;
  24110. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  24111. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  24112. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  24113. }
  24114. values[dimSize] = dataIndex;
  24115. var retValue = cb && cb.apply(context, values);
  24116. if (retValue != null) {
  24117. // a number or string (in oridinal dimension)?
  24118. if (typeof retValue !== 'object') {
  24119. tmpRetValue[0] = retValue;
  24120. retValue = tmpRetValue;
  24121. }
  24122. var rawIndex = this.getRawIndex(dataIndex);
  24123. var chunkIndex = Math.floor(rawIndex / chunkSize);
  24124. var chunkOffset = rawIndex % chunkSize;
  24125. for (var i = 0; i < retValue.length; i++) {
  24126. var dim = dimensions[i];
  24127. var val = retValue[i];
  24128. var rawExtentOnDim = rawExtent[dim];
  24129. var dimStore = storage[dim];
  24130. if (dimStore) {
  24131. dimStore[chunkIndex][chunkOffset] = val;
  24132. }
  24133. if (val < rawExtentOnDim[0]) {
  24134. rawExtentOnDim[0] = val;
  24135. }
  24136. if (val > rawExtentOnDim[1]) {
  24137. rawExtentOnDim[1] = val;
  24138. }
  24139. }
  24140. }
  24141. }
  24142. return list;
  24143. };
  24144. /**
  24145. * Large data down sampling on given dimension
  24146. * @param {string} dimension
  24147. * @param {number} rate
  24148. * @param {Function} sampleValue
  24149. * @param {Function} sampleIndex Sample index for name and id
  24150. */
  24151. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  24152. var list = cloneListForMapAndSample(this, [dimension]);
  24153. var targetStorage = list._storage;
  24154. var frameValues = [];
  24155. var frameSize = Math.floor(1 / rate);
  24156. var dimStore = targetStorage[dimension];
  24157. var len = this.count();
  24158. var chunkSize = this._chunkSize;
  24159. var rawExtentOnDim = list._rawExtent[dimension];
  24160. var newIndices = new (getIndicesCtor(this))(len);
  24161. var offset = 0;
  24162. for (var i = 0; i < len; i += frameSize) {
  24163. // Last frame
  24164. if (frameSize > len - i) {
  24165. frameSize = len - i;
  24166. frameValues.length = frameSize;
  24167. }
  24168. for (var k = 0; k < frameSize; k++) {
  24169. var dataIdx = this.getRawIndex(i + k);
  24170. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  24171. var originalChunkOffset = dataIdx % chunkSize;
  24172. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  24173. }
  24174. var value = sampleValue(frameValues);
  24175. var sampleFrameIdx = this.getRawIndex(
  24176. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  24177. );
  24178. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  24179. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  24180. // Only write value on the filtered data
  24181. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  24182. if (value < rawExtentOnDim[0]) {
  24183. rawExtentOnDim[0] = value;
  24184. }
  24185. if (value > rawExtentOnDim[1]) {
  24186. rawExtentOnDim[1] = value;
  24187. }
  24188. newIndices[offset++] = sampleFrameIdx;
  24189. }
  24190. list._count = offset;
  24191. list._indices = newIndices;
  24192. list.getRawIndex = getRawIndexWithIndices;
  24193. return list;
  24194. };
  24195. /**
  24196. * Get model of one data item.
  24197. *
  24198. * @param {number} idx
  24199. */
  24200. // FIXME Model proxy ?
  24201. listProto.getItemModel = function (idx) {
  24202. var hostModel = this.hostModel;
  24203. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  24204. };
  24205. /**
  24206. * Create a data differ
  24207. * @param {module:echarts/data/List} otherList
  24208. * @return {module:echarts/data/DataDiffer}
  24209. */
  24210. listProto.diff = function (otherList) {
  24211. var thisList = this;
  24212. return new DataDiffer(
  24213. otherList ? otherList.getIndices() : [],
  24214. this.getIndices(),
  24215. function (idx) {
  24216. return getId(otherList, idx);
  24217. },
  24218. function (idx) {
  24219. return getId(thisList, idx);
  24220. }
  24221. );
  24222. };
  24223. /**
  24224. * Get visual property.
  24225. * @param {string} key
  24226. */
  24227. listProto.getVisual = function (key) {
  24228. var visual = this._visual;
  24229. return visual && visual[key];
  24230. };
  24231. /**
  24232. * Set visual property
  24233. * @param {string|Object} key
  24234. * @param {*} [value]
  24235. *
  24236. * @example
  24237. * setVisual('color', color);
  24238. * setVisual({
  24239. * 'color': color
  24240. * });
  24241. */
  24242. listProto.setVisual = function (key, val) {
  24243. if (isObject$4(key)) {
  24244. for (var name in key) {
  24245. if (key.hasOwnProperty(name)) {
  24246. this.setVisual(name, key[name]);
  24247. }
  24248. }
  24249. return;
  24250. }
  24251. this._visual = this._visual || {};
  24252. this._visual[key] = val;
  24253. };
  24254. /**
  24255. * Set layout property.
  24256. * @param {string|Object} key
  24257. * @param {*} [val]
  24258. */
  24259. listProto.setLayout = function (key, val) {
  24260. if (isObject$4(key)) {
  24261. for (var name in key) {
  24262. if (key.hasOwnProperty(name)) {
  24263. this.setLayout(name, key[name]);
  24264. }
  24265. }
  24266. return;
  24267. }
  24268. this._layout[key] = val;
  24269. };
  24270. /**
  24271. * Get layout property.
  24272. * @param {string} key.
  24273. * @return {*}
  24274. */
  24275. listProto.getLayout = function (key) {
  24276. return this._layout[key];
  24277. };
  24278. /**
  24279. * Get layout of single data item
  24280. * @param {number} idx
  24281. */
  24282. listProto.getItemLayout = function (idx) {
  24283. return this._itemLayouts[idx];
  24284. };
  24285. /**
  24286. * Set layout of single data item
  24287. * @param {number} idx
  24288. * @param {Object} layout
  24289. * @param {boolean=} [merge=false]
  24290. */
  24291. listProto.setItemLayout = function (idx, layout, merge$$1) {
  24292. this._itemLayouts[idx] = merge$$1
  24293. ? extend(this._itemLayouts[idx] || {}, layout)
  24294. : layout;
  24295. };
  24296. /**
  24297. * Clear all layout of single data item
  24298. */
  24299. listProto.clearItemLayouts = function () {
  24300. this._itemLayouts.length = 0;
  24301. };
  24302. /**
  24303. * Get visual property of single data item
  24304. * @param {number} idx
  24305. * @param {string} key
  24306. * @param {boolean} [ignoreParent=false]
  24307. */
  24308. listProto.getItemVisual = function (idx, key, ignoreParent) {
  24309. var itemVisual = this._itemVisuals[idx];
  24310. var val = itemVisual && itemVisual[key];
  24311. if (val == null && !ignoreParent) {
  24312. // Use global visual property
  24313. return this.getVisual(key);
  24314. }
  24315. return val;
  24316. };
  24317. /**
  24318. * Set visual property of single data item
  24319. *
  24320. * @param {number} idx
  24321. * @param {string|Object} key
  24322. * @param {*} [value]
  24323. *
  24324. * @example
  24325. * setItemVisual(0, 'color', color);
  24326. * setItemVisual(0, {
  24327. * 'color': color
  24328. * });
  24329. */
  24330. listProto.setItemVisual = function (idx, key, value) {
  24331. var itemVisual = this._itemVisuals[idx] || {};
  24332. var hasItemVisual = this.hasItemVisual;
  24333. this._itemVisuals[idx] = itemVisual;
  24334. if (isObject$4(key)) {
  24335. for (var name in key) {
  24336. if (key.hasOwnProperty(name)) {
  24337. itemVisual[name] = key[name];
  24338. hasItemVisual[name] = true;
  24339. }
  24340. }
  24341. return;
  24342. }
  24343. itemVisual[key] = value;
  24344. hasItemVisual[key] = true;
  24345. };
  24346. /**
  24347. * Clear itemVisuals and list visual.
  24348. */
  24349. listProto.clearAllVisual = function () {
  24350. this._visual = {};
  24351. this._itemVisuals = [];
  24352. this.hasItemVisual = {};
  24353. };
  24354. var setItemDataAndSeriesIndex = function (child) {
  24355. child.seriesIndex = this.seriesIndex;
  24356. child.dataIndex = this.dataIndex;
  24357. child.dataType = this.dataType;
  24358. };
  24359. /**
  24360. * Set graphic element relative to data. It can be set as null
  24361. * @param {number} idx
  24362. * @param {module:zrender/Element} [el]
  24363. */
  24364. listProto.setItemGraphicEl = function (idx, el) {
  24365. var hostModel = this.hostModel;
  24366. if (el) {
  24367. // Add data index and series index for indexing the data by element
  24368. // Useful in tooltip
  24369. el.dataIndex = idx;
  24370. el.dataType = this.dataType;
  24371. el.seriesIndex = hostModel && hostModel.seriesIndex;
  24372. if (el.type === 'group') {
  24373. el.traverse(setItemDataAndSeriesIndex, el);
  24374. }
  24375. }
  24376. this._graphicEls[idx] = el;
  24377. };
  24378. /**
  24379. * @param {number} idx
  24380. * @return {module:zrender/Element}
  24381. */
  24382. listProto.getItemGraphicEl = function (idx) {
  24383. return this._graphicEls[idx];
  24384. };
  24385. /**
  24386. * @param {Function} cb
  24387. * @param {*} context
  24388. */
  24389. listProto.eachItemGraphicEl = function (cb, context) {
  24390. each$1(this._graphicEls, function (el, idx) {
  24391. if (el) {
  24392. cb && cb.call(context, el, idx);
  24393. }
  24394. });
  24395. };
  24396. /**
  24397. * Shallow clone a new list except visual and layout properties, and graph elements.
  24398. * New list only change the indices.
  24399. */
  24400. listProto.cloneShallow = function (list) {
  24401. if (!list) {
  24402. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  24403. list = new List(dimensionInfoList, this.hostModel);
  24404. }
  24405. // FIXME
  24406. list._storage = this._storage;
  24407. transferProperties(list, this);
  24408. // Clone will not change the data extent and indices
  24409. if (this._indices) {
  24410. var Ctor = this._indices.constructor;
  24411. list._indices = new Ctor(this._indices);
  24412. }
  24413. else {
  24414. list._indices = null;
  24415. }
  24416. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  24417. list._extent = clone(this._extent);
  24418. list._approximateExtent = clone(this._approximateExtent);
  24419. return list;
  24420. };
  24421. /**
  24422. * Wrap some method to add more feature
  24423. * @param {string} methodName
  24424. * @param {Function} injectFunction
  24425. */
  24426. listProto.wrapMethod = function (methodName, injectFunction) {
  24427. var originalMethod = this[methodName];
  24428. if (typeof originalMethod !== 'function') {
  24429. return;
  24430. }
  24431. this.__wrappedMethods = this.__wrappedMethods || [];
  24432. this.__wrappedMethods.push(methodName);
  24433. this[methodName] = function () {
  24434. var res = originalMethod.apply(this, arguments);
  24435. return injectFunction.apply(this, [res].concat(slice(arguments)));
  24436. };
  24437. };
  24438. // Methods that create a new list based on this list should be listed here.
  24439. // Notice that those method should `RETURN` the new list.
  24440. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  24441. // Methods that change indices of this list should be listed here.
  24442. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  24443. /**
  24444. * @deprecated
  24445. * Use `echarts/data/helper/createDimensions` instead.
  24446. */
  24447. /**
  24448. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  24449. *
  24450. * Complete the dimensions array, by user defined `dimension` and `encode`,
  24451. * and guessing from the data structure.
  24452. * If no 'value' dimension specified, the first no-named dimension will be
  24453. * named as 'value'.
  24454. *
  24455. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  24456. * provides not only dim template, but also default order.
  24457. * properties: 'name', 'type', 'displayName'.
  24458. * `name` of each item provides default coord name.
  24459. * [{dimsDef: [string...]}, ...] dimsDef of sysDim item provides default dim name, and
  24460. * provide dims count that the sysDim required.
  24461. * [{ordinalMeta}] can be specified.
  24462. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  24463. * @param {Object} [opt]
  24464. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  24465. * For example: ['asdf', {name, type}, ...].
  24466. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  24467. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  24468. * If not specified, extra dim names will be:
  24469. * 'value', 'value0', 'value1', ...
  24470. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  24471. * If `generateCoordCount` specified, the generated dim names will be:
  24472. * `generateCoord` + 0, `generateCoord` + 1, ...
  24473. * can be Infinity, indicate that use all of the remain columns.
  24474. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  24475. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  24476. * @return {Array.<Object>} [{
  24477. * name: string mandatory,
  24478. * displayName: string, the origin name in dimsDef, see source helper.
  24479. * If displayName given, the tooltip will displayed vertically.
  24480. * coordDim: string mandatory,
  24481. * coordDimIndex: number mandatory,
  24482. * type: string optional,
  24483. * otherDims: { never null/undefined
  24484. * tooltip: number optional,
  24485. * label: number optional,
  24486. * itemName: number optional,
  24487. * seriesName: number optional,
  24488. * },
  24489. * isExtraCoord: boolean true if coord is generated
  24490. * (not specified in encode and not series specified)
  24491. * other props ...
  24492. * }]
  24493. */
  24494. function completeDimensions(sysDims, source, opt) {
  24495. if (!Source.isInstance(source)) {
  24496. source = Source.seriesDataToSource(source);
  24497. }
  24498. opt = opt || {};
  24499. sysDims = (sysDims || []).slice();
  24500. var dimsDef = (opt.dimsDef || []).slice();
  24501. var encodeDef = createHashMap(opt.encodeDef);
  24502. var dataDimNameMap = createHashMap();
  24503. var coordDimNameMap = createHashMap();
  24504. // var valueCandidate;
  24505. var result = [];
  24506. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  24507. // Apply user defined dims (`name` and `type`) and init result.
  24508. for (var i = 0; i < dimCount; i++) {
  24509. var dimDefItem = dimsDef[i] = extend(
  24510. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  24511. );
  24512. var userDimName = dimDefItem.name;
  24513. var resultItem = result[i] = {otherDims: {}};
  24514. // Name will be applied later for avoiding duplication.
  24515. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  24516. // Only if `series.dimensions` is defined in option
  24517. // displayName, will be set, and dimension will be diplayed vertically in
  24518. // tooltip by default.
  24519. resultItem.name = resultItem.displayName = userDimName;
  24520. dataDimNameMap.set(userDimName, i);
  24521. }
  24522. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  24523. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  24524. }
  24525. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  24526. encodeDef.each(function (dataDims, coordDim) {
  24527. dataDims = normalizeToArray(dataDims).slice();
  24528. var validDataDims = encodeDef.set(coordDim, []);
  24529. each$1(dataDims, function (resultDimIdx, idx) {
  24530. // The input resultDimIdx can be dim name or index.
  24531. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  24532. if (resultDimIdx != null && resultDimIdx < dimCount) {
  24533. validDataDims[idx] = resultDimIdx;
  24534. applyDim(result[resultDimIdx], coordDim, idx);
  24535. }
  24536. });
  24537. });
  24538. // Apply templetes and default order from `sysDims`.
  24539. var availDimIdx = 0;
  24540. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  24541. var coordDim;
  24542. var sysDimItem;
  24543. var sysDimItemDimsDef;
  24544. var sysDimItemOtherDims;
  24545. if (isString(sysDimItem)) {
  24546. coordDim = sysDimItem;
  24547. sysDimItem = {};
  24548. }
  24549. else {
  24550. coordDim = sysDimItem.name;
  24551. var ordinalMeta = sysDimItem.ordinalMeta;
  24552. sysDimItem.ordinalMeta = null;
  24553. sysDimItem = clone(sysDimItem);
  24554. sysDimItem.ordinalMeta = ordinalMeta;
  24555. // `coordDimIndex` should not be set directly.
  24556. sysDimItemDimsDef = sysDimItem.dimsDef;
  24557. sysDimItemOtherDims = sysDimItem.otherDims;
  24558. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  24559. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  24560. }
  24561. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  24562. // dimensions provides default dim sequences.
  24563. if (!dataDims.length) {
  24564. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  24565. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  24566. availDimIdx++;
  24567. }
  24568. availDimIdx < result.length && dataDims.push(availDimIdx++);
  24569. }
  24570. }
  24571. // Apply templates.
  24572. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  24573. var resultItem = result[resultDimIdx];
  24574. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  24575. if (resultItem.name == null && sysDimItemDimsDef) {
  24576. resultItem.name = resultItem.displayName = sysDimItemDimsDef[coordDimIndex];
  24577. }
  24578. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  24579. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  24580. });
  24581. });
  24582. function applyDim(resultItem, coordDim, coordDimIndex) {
  24583. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  24584. resultItem.otherDims[coordDim] = coordDimIndex;
  24585. }
  24586. else {
  24587. resultItem.coordDim = coordDim;
  24588. resultItem.coordDimIndex = coordDimIndex;
  24589. coordDimNameMap.set(coordDim, true);
  24590. }
  24591. }
  24592. // Make sure the first extra dim is 'value'.
  24593. var generateCoord = opt.generateCoord;
  24594. var generateCoordCount = opt.generateCoordCount;
  24595. var fromZero = generateCoordCount != null;
  24596. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  24597. var extra = generateCoord || 'value';
  24598. // Set dim `name` and other `coordDim` and other props.
  24599. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  24600. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  24601. var coordDim = resultItem.coordDim;
  24602. if (coordDim == null) {
  24603. resultItem.coordDim = genName(
  24604. extra, coordDimNameMap, fromZero
  24605. );
  24606. resultItem.coordDimIndex = 0;
  24607. if (!generateCoord || generateCoordCount <= 0) {
  24608. resultItem.isExtraCoord = true;
  24609. }
  24610. generateCoordCount--;
  24611. }
  24612. resultItem.name == null && (resultItem.name = genName(
  24613. resultItem.coordDim,
  24614. dataDimNameMap
  24615. ));
  24616. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  24617. resultItem.type = 'ordinal';
  24618. }
  24619. }
  24620. return result;
  24621. }
  24622. // ??? TODO
  24623. // Originally detect dimCount by data[0]. Should we
  24624. // optimize it to only by sysDims and dimensions and encode.
  24625. // So only necessary dims will be initialized.
  24626. // But
  24627. // (1) custom series should be considered. where other dims
  24628. // may be visited.
  24629. // (2) sometimes user need to calcualte bubble size or use visualMap
  24630. // on other dimensions besides coordSys needed.
  24631. // So, dims that is not used by system, should be shared in storage?
  24632. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  24633. // Note that the result dimCount should not small than columns count
  24634. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  24635. var dimCount = Math.max(
  24636. source.dimensionsDetectCount || 1,
  24637. sysDims.length,
  24638. dimsDef.length,
  24639. optDimCount || 0
  24640. );
  24641. each$1(sysDims, function (sysDimItem) {
  24642. var sysDimItemDimsDef = sysDimItem.dimsDef;
  24643. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  24644. });
  24645. return dimCount;
  24646. }
  24647. function genName(name, map$$1, fromZero) {
  24648. if (fromZero || map$$1.get(name) != null) {
  24649. var i = 0;
  24650. while (map$$1.get(name + i) != null) {
  24651. i++;
  24652. }
  24653. name += i;
  24654. }
  24655. map$$1.set(name, true);
  24656. return name;
  24657. }
  24658. /**
  24659. * Substitute `completeDimensions`.
  24660. * `completeDimensions` is to be deprecated.
  24661. */
  24662. /**
  24663. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  24664. * @param {Object|Array} [opt]
  24665. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  24666. * @param {number} [opt.dimensionsCount]
  24667. * @param {string} [opt.generateCoord]
  24668. * @param {string} [opt.generateCoordCount]
  24669. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  24670. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  24671. * @return {Array.<Object>} dimensionsInfo
  24672. */
  24673. var createDimensions = function (source, opt) {
  24674. opt = opt || {};
  24675. return completeDimensions(opt.coordDimensions || [], source, {
  24676. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  24677. encodeDef: opt.encodeDefine || source.encodeDefine,
  24678. dimCount: opt.dimensionsCount,
  24679. generateCoord: opt.generateCoord,
  24680. generateCoordCount: opt.generateCoordCount
  24681. });
  24682. };
  24683. /**
  24684. * Note that it is too complicated to support 3d stack by value
  24685. * (have to create two-dimension inverted index), so in 3d case
  24686. * we just support that stacked by index.
  24687. *
  24688. * @param {module:echarts/model/Series} seriesModel
  24689. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  24690. * The input dimensionInfoList will be modified.
  24691. * @param {Object} [opt]
  24692. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  24693. * @param {boolean} [opt.byIndex=false]
  24694. * @return {Object} calculationInfo
  24695. * {
  24696. * stackedDimension: string
  24697. * stackedByDimension: string
  24698. * isStackedByIndex: boolean
  24699. * stackedOverDimension: string
  24700. * stackResultDimension: string
  24701. * }
  24702. */
  24703. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  24704. opt = opt || {};
  24705. var byIndex = opt.byIndex;
  24706. var stackedCoordDimension = opt.stackedCoordDimension;
  24707. // Compatibal: when `stack` is set as '', do not stack.
  24708. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  24709. var stackedByDimInfo;
  24710. var stackedDimInfo;
  24711. var stackResultDimension;
  24712. var stackedOverDimension;
  24713. each$1(dimensionInfoList, function (dimensionInfo, index) {
  24714. if (isString(dimensionInfo)) {
  24715. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  24716. }
  24717. if (mayStack && !dimensionInfo.isExtraCoord) {
  24718. // Find the first ordinal dimension as the stackedByDimInfo.
  24719. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  24720. stackedByDimInfo = dimensionInfo;
  24721. }
  24722. // Find the first stackable dimension as the stackedDimInfo.
  24723. if (!stackedDimInfo
  24724. && dimensionInfo.type !== 'ordinal'
  24725. && dimensionInfo.type !== 'time'
  24726. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  24727. ) {
  24728. stackedDimInfo = dimensionInfo;
  24729. }
  24730. }
  24731. });
  24732. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  24733. // That put stack logic in List is for using conveniently in echarts extensions, but it
  24734. // might not be a good way.
  24735. if (stackedDimInfo && (byIndex || stackedByDimInfo)) {
  24736. // Use a weird name that not duplicated with other names.
  24737. stackResultDimension = '__\0ecstackresult';
  24738. stackedOverDimension = '__\0ecstackedover';
  24739. // Create inverted index to fast query index by value.
  24740. if (stackedByDimInfo) {
  24741. stackedByDimInfo.createInvertedIndices = true;
  24742. }
  24743. var stackedDimCoordDim = stackedDimInfo.coordDim;
  24744. var stackedDimType = stackedDimInfo.type;
  24745. var stackedDimCoordIndex = 0;
  24746. each$1(dimensionInfoList, function (dimensionInfo) {
  24747. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  24748. stackedDimCoordIndex++;
  24749. }
  24750. });
  24751. dimensionInfoList.push({
  24752. name: stackResultDimension,
  24753. coordDim: stackedDimCoordDim,
  24754. coordDimIndex: stackedDimCoordIndex,
  24755. type: stackedDimType,
  24756. isExtraCoord: true,
  24757. isCalculationCoord: true
  24758. });
  24759. stackedDimCoordIndex++;
  24760. dimensionInfoList.push({
  24761. name: stackedOverDimension,
  24762. // This dimension contains stack base (generally, 0), so do not set it as
  24763. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  24764. coordDim: stackedOverDimension,
  24765. coordDimIndex: stackedDimCoordIndex,
  24766. type: stackedDimType,
  24767. isExtraCoord: true,
  24768. isCalculationCoord: true
  24769. });
  24770. }
  24771. return {
  24772. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  24773. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  24774. isStackedByIndex: byIndex,
  24775. stackedOverDimension: stackedOverDimension,
  24776. stackResultDimension: stackResultDimension
  24777. };
  24778. }
  24779. /**
  24780. * @param {module:echarts/data/List} data
  24781. * @param {string} stackedDim
  24782. * @param {string} [stackedByDim] If not input this parameter, check whether
  24783. * stacked by index.
  24784. */
  24785. function isDimensionStacked(data, stackedDim, stackedByDim) {
  24786. return stackedDim
  24787. && stackedDim === data.getCalculationInfo('stackedDimension')
  24788. && (
  24789. stackedByDim != null
  24790. ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  24791. : data.getCalculationInfo('isStackedByIndex')
  24792. );
  24793. }
  24794. /**
  24795. * @param {module:echarts/data/Source|Array} source Or raw data.
  24796. * @param {module:echarts/model/Series} seriesModel
  24797. * @param {Object} [opt]
  24798. * @param {string} [opt.generateCoord]
  24799. */
  24800. function createListFromArray(source, seriesModel, opt) {
  24801. opt = opt || {};
  24802. if (!Source.isInstance(source)) {
  24803. source = Source.seriesDataToSource(source);
  24804. }
  24805. var coordSysName = seriesModel.get('coordinateSystem');
  24806. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  24807. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  24808. var coordSysDimDefs;
  24809. if (coordSysDefine) {
  24810. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  24811. var dimInfo = {name: dim};
  24812. var axisModel = coordSysDefine.axisMap.get(dim);
  24813. if (axisModel) {
  24814. var axisType = axisModel.get('type');
  24815. dimInfo.type = getDimensionTypeByAxis(axisType);
  24816. // dimInfo.stackable = isStackable(axisType);
  24817. }
  24818. return dimInfo;
  24819. });
  24820. }
  24821. if (!coordSysDimDefs) {
  24822. // Get dimensions from registered coordinate system
  24823. coordSysDimDefs = (registeredCoordSys && (
  24824. registeredCoordSys.getDimensionsInfo
  24825. ? registeredCoordSys.getDimensionsInfo()
  24826. : registeredCoordSys.dimensions.slice()
  24827. )) || ['x', 'y'];
  24828. }
  24829. var dimInfoList = createDimensions(source, {
  24830. coordDimensions: coordSysDimDefs,
  24831. generateCoord: opt.generateCoord
  24832. });
  24833. var firstCategoryDimIndex;
  24834. var hasNameEncode;
  24835. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  24836. var coordDim = dimInfo.coordDim;
  24837. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  24838. if (categoryAxisModel) {
  24839. if (firstCategoryDimIndex == null) {
  24840. firstCategoryDimIndex = dimIndex;
  24841. }
  24842. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  24843. }
  24844. if (dimInfo.otherDims.itemName != null) {
  24845. hasNameEncode = true;
  24846. }
  24847. });
  24848. if (!hasNameEncode && firstCategoryDimIndex != null) {
  24849. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  24850. }
  24851. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  24852. var list = new List(dimInfoList, seriesModel);
  24853. list.setCalculationInfo(stackCalculationInfo);
  24854. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  24855. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  24856. // Use dataIndex as ordinal value in categoryAxis
  24857. return dimIndex === firstCategoryDimIndex
  24858. ? dataIndex
  24859. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  24860. }
  24861. : null;
  24862. list.hasItemOption = false;
  24863. list.initData(source, null, dimValueGetter);
  24864. return list;
  24865. }
  24866. function isNeedCompleteOrdinalData(source) {
  24867. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  24868. var sampleItem = firstDataNotNull(source.data || []);
  24869. return sampleItem != null
  24870. && !isArray(getDataItemValue(sampleItem));
  24871. }
  24872. }
  24873. function firstDataNotNull(data) {
  24874. var i = 0;
  24875. while (i < data.length && data[i] == null) {
  24876. i++;
  24877. }
  24878. return data[i];
  24879. }
  24880. /**
  24881. * // Scale class management
  24882. * @module echarts/scale/Scale
  24883. */
  24884. /**
  24885. * @param {Object} [setting]
  24886. */
  24887. function Scale(setting) {
  24888. this._setting = setting || {};
  24889. /**
  24890. * Extent
  24891. * @type {Array.<number>}
  24892. * @protected
  24893. */
  24894. this._extent = [Infinity, -Infinity];
  24895. /**
  24896. * Step is calculated in adjustExtent
  24897. * @type {Array.<number>}
  24898. * @protected
  24899. */
  24900. this._interval = 0;
  24901. this.init && this.init.apply(this, arguments);
  24902. }
  24903. /**
  24904. * Parse input val to valid inner number.
  24905. * @param {*} val
  24906. * @return {number}
  24907. */
  24908. Scale.prototype.parse = function (val) {
  24909. // Notice: This would be a trap here, If the implementation
  24910. // of this method depends on extent, and this method is used
  24911. // before extent set (like in dataZoom), it would be wrong.
  24912. // Nevertheless, parse does not depend on extent generally.
  24913. return val;
  24914. };
  24915. Scale.prototype.getSetting = function (name) {
  24916. return this._setting[name];
  24917. };
  24918. Scale.prototype.contain = function (val) {
  24919. var extent = this._extent;
  24920. return val >= extent[0] && val <= extent[1];
  24921. };
  24922. /**
  24923. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  24924. * @param {number} val
  24925. * @return {number}
  24926. */
  24927. Scale.prototype.normalize = function (val) {
  24928. var extent = this._extent;
  24929. if (extent[1] === extent[0]) {
  24930. return 0.5;
  24931. }
  24932. return (val - extent[0]) / (extent[1] - extent[0]);
  24933. };
  24934. /**
  24935. * Scale normalized value
  24936. * @param {number} val
  24937. * @return {number}
  24938. */
  24939. Scale.prototype.scale = function (val) {
  24940. var extent = this._extent;
  24941. return val * (extent[1] - extent[0]) + extent[0];
  24942. };
  24943. /**
  24944. * Set extent from data
  24945. * @param {Array.<number>} other
  24946. */
  24947. Scale.prototype.unionExtent = function (other) {
  24948. var extent = this._extent;
  24949. other[0] < extent[0] && (extent[0] = other[0]);
  24950. other[1] > extent[1] && (extent[1] = other[1]);
  24951. // not setExtent because in log axis it may transformed to power
  24952. // this.setExtent(extent[0], extent[1]);
  24953. };
  24954. /**
  24955. * Set extent from data
  24956. * @param {module:echarts/data/List} data
  24957. * @param {string} dim
  24958. */
  24959. Scale.prototype.unionExtentFromData = function (data, dim) {
  24960. this.unionExtent(data.getApproximateExtent(dim));
  24961. };
  24962. /**
  24963. * Get extent
  24964. * @return {Array.<number>}
  24965. */
  24966. Scale.prototype.getExtent = function () {
  24967. return this._extent.slice();
  24968. };
  24969. /**
  24970. * Set extent
  24971. * @param {number} start
  24972. * @param {number} end
  24973. */
  24974. Scale.prototype.setExtent = function (start, end) {
  24975. var thisExtent = this._extent;
  24976. if (!isNaN(start)) {
  24977. thisExtent[0] = start;
  24978. }
  24979. if (!isNaN(end)) {
  24980. thisExtent[1] = end;
  24981. }
  24982. };
  24983. /**
  24984. * @return {Array.<string>}
  24985. */
  24986. Scale.prototype.getTicksLabels = function () {
  24987. var labels = [];
  24988. var ticks = this.getTicks();
  24989. for (var i = 0; i < ticks.length; i++) {
  24990. labels.push(this.getLabel(ticks[i]));
  24991. }
  24992. return labels;
  24993. };
  24994. /**
  24995. * When axis extent depends on data and no data exists,
  24996. * axis ticks should not be drawn, which is named 'blank'.
  24997. */
  24998. Scale.prototype.isBlank = function () {
  24999. return this._isBlank;
  25000. },
  25001. /**
  25002. * When axis extent depends on data and no data exists,
  25003. * axis ticks should not be drawn, which is named 'blank'.
  25004. */
  25005. Scale.prototype.setBlank = function (isBlank) {
  25006. this._isBlank = isBlank;
  25007. };
  25008. enableClassExtend(Scale);
  25009. enableClassManagement(Scale, {
  25010. registerWhenExtend: true
  25011. });
  25012. /**
  25013. * @constructor
  25014. * @param {Object} [opt]
  25015. * @param {Object} [opt.categories=[]]
  25016. * @param {Object} [opt.needCollect=false]
  25017. * @param {Object} [opt.deduplication=false]
  25018. */
  25019. function OrdinalMeta(opt) {
  25020. /**
  25021. * @readOnly
  25022. * @type {Array.<string>}
  25023. */
  25024. this.categories = opt.categories || [];
  25025. /**
  25026. * @private
  25027. * @type {boolean}
  25028. */
  25029. this._needCollect = opt.needCollect;
  25030. /**
  25031. * @private
  25032. * @type {boolean}
  25033. */
  25034. this._deduplication = opt.deduplication;
  25035. /**
  25036. * @private
  25037. * @type {boolean}
  25038. */
  25039. this._map;
  25040. }
  25041. /**
  25042. * @param {module:echarts/model/Model} axisModel
  25043. * @return {module:echarts/data/OrdinalMeta}
  25044. */
  25045. OrdinalMeta.createByAxisModel = function (axisModel) {
  25046. var option = axisModel.option;
  25047. var data = option.data;
  25048. var categories = data && map(data, getName);
  25049. return new OrdinalMeta({
  25050. categories: categories,
  25051. needCollect: !categories,
  25052. // deduplication is default in axis.
  25053. deduplication: option.dedplication !== false
  25054. });
  25055. };
  25056. var proto$1 = OrdinalMeta.prototype;
  25057. /**
  25058. * @param {string} category
  25059. * @return {number} ordinal
  25060. */
  25061. proto$1.getOrdinal = function (category) {
  25062. return getOrCreateMap(this).get(category);
  25063. };
  25064. /**
  25065. * @param {*} category
  25066. * @return {number} The ordinal. If not found, return NaN.
  25067. */
  25068. proto$1.parseAndCollect = function (category) {
  25069. var index;
  25070. var needCollect = this._needCollect;
  25071. // The value of category dim can be the index of the given category set.
  25072. // This feature is only supported when !needCollect, because we should
  25073. // consider a common case: a value is 2017, which is a number but is
  25074. // expected to be tread as a category. This case usually happen in dataset,
  25075. // where it happent to be no need of the index feature.
  25076. if (typeof category !== 'string' && !needCollect) {
  25077. return category;
  25078. }
  25079. // Optimize for the scenario:
  25080. // category is ['2012-01-01', '2012-01-02', ...], where the input
  25081. // data has been ensured not duplicate and is large data.
  25082. // Notice, if a dataset dimension provide categroies, usually echarts
  25083. // should remove duplication except user tell echarts dont do that
  25084. // (set axis.deduplication = false), because echarts do not know whether
  25085. // the values in the category dimension has duplication (consider the
  25086. // parallel-aqi example)
  25087. if (needCollect && !this._deduplication) {
  25088. index = this.categories.length;
  25089. this.categories[index] = category;
  25090. return index;
  25091. }
  25092. var map$$1 = getOrCreateMap(this);
  25093. index = map$$1.get(category);
  25094. if (index == null) {
  25095. if (needCollect) {
  25096. index = this.categories.length;
  25097. this.categories[index] = category;
  25098. map$$1.set(category, index);
  25099. }
  25100. else {
  25101. index = NaN;
  25102. }
  25103. }
  25104. return index;
  25105. };
  25106. // Consider big data, do not create map until needed.
  25107. function getOrCreateMap(ordinalMeta) {
  25108. return ordinalMeta._map || (
  25109. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  25110. );
  25111. }
  25112. function getName(obj) {
  25113. if (isObject$1(obj) && obj.value != null) {
  25114. return obj.value;
  25115. }
  25116. else {
  25117. return obj + '';
  25118. }
  25119. }
  25120. /**
  25121. * Linear continuous scale
  25122. * @module echarts/coord/scale/Ordinal
  25123. *
  25124. * http://en.wikipedia.org/wiki/Level_of_measurement
  25125. */
  25126. // FIXME only one data
  25127. var scaleProto = Scale.prototype;
  25128. var OrdinalScale = Scale.extend({
  25129. type: 'ordinal',
  25130. /**
  25131. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  25132. */
  25133. init: function (ordinalMeta, extent) {
  25134. // Caution: Should not use instanceof, consider ec-extensions using
  25135. // import approach to get OrdinalMeta class.
  25136. if (!ordinalMeta || isArray(ordinalMeta)) {
  25137. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  25138. }
  25139. this._ordinalMeta = ordinalMeta;
  25140. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  25141. },
  25142. parse: function (val) {
  25143. return typeof val === 'string'
  25144. ? this._ordinalMeta.getOrdinal(val)
  25145. // val might be float.
  25146. : Math.round(val);
  25147. },
  25148. contain: function (rank) {
  25149. rank = this.parse(rank);
  25150. return scaleProto.contain.call(this, rank)
  25151. && this._ordinalMeta.categories[rank] != null;
  25152. },
  25153. /**
  25154. * Normalize given rank or name to linear [0, 1]
  25155. * @param {number|string} [val]
  25156. * @return {number}
  25157. */
  25158. normalize: function (val) {
  25159. return scaleProto.normalize.call(this, this.parse(val));
  25160. },
  25161. scale: function (val) {
  25162. return Math.round(scaleProto.scale.call(this, val));
  25163. },
  25164. /**
  25165. * @return {Array}
  25166. */
  25167. getTicks: function () {
  25168. var ticks = [];
  25169. var extent = this._extent;
  25170. var rank = extent[0];
  25171. while (rank <= extent[1]) {
  25172. ticks.push(rank);
  25173. rank++;
  25174. }
  25175. return ticks;
  25176. },
  25177. /**
  25178. * Get item on rank n
  25179. * @param {number} n
  25180. * @return {string}
  25181. */
  25182. getLabel: function (n) {
  25183. return this._ordinalMeta.categories[n];
  25184. },
  25185. /**
  25186. * @return {number}
  25187. */
  25188. count: function () {
  25189. return this._extent[1] - this._extent[0] + 1;
  25190. },
  25191. /**
  25192. * @override
  25193. */
  25194. unionExtentFromData: function (data, dim) {
  25195. this.unionExtent(data.getApproximateExtent(dim));
  25196. },
  25197. niceTicks: noop,
  25198. niceExtent: noop
  25199. });
  25200. /**
  25201. * @return {module:echarts/scale/Time}
  25202. */
  25203. OrdinalScale.create = function () {
  25204. return new OrdinalScale();
  25205. };
  25206. /**
  25207. * For testable.
  25208. */
  25209. var roundNumber$1 = round$1;
  25210. /**
  25211. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  25212. * Should be extent[0] < extent[1].
  25213. * @param {number} splitNumber splitNumber should be >= 1.
  25214. * @param {number} [minInterval]
  25215. * @param {number} [maxInterval]
  25216. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  25217. */
  25218. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  25219. var result = {};
  25220. var span = extent[1] - extent[0];
  25221. var interval = result.interval = nice(span / splitNumber, true);
  25222. if (minInterval != null && interval < minInterval) {
  25223. interval = result.interval = minInterval;
  25224. }
  25225. if (maxInterval != null && interval > maxInterval) {
  25226. interval = result.interval = maxInterval;
  25227. }
  25228. // Tow more digital for tick.
  25229. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  25230. // Niced extent inside original extent
  25231. var niceTickExtent = result.niceTickExtent = [
  25232. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  25233. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  25234. ];
  25235. fixExtent(niceTickExtent, extent);
  25236. return result;
  25237. }
  25238. /**
  25239. * @param {number} interval
  25240. * @return {number} interval precision
  25241. */
  25242. function getIntervalPrecision(interval) {
  25243. // Tow more digital for tick.
  25244. return getPrecisionSafe(interval) + 2;
  25245. }
  25246. function clamp(niceTickExtent, idx, extent) {
  25247. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  25248. }
  25249. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  25250. function fixExtent(niceTickExtent, extent) {
  25251. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  25252. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  25253. clamp(niceTickExtent, 0, extent);
  25254. clamp(niceTickExtent, 1, extent);
  25255. if (niceTickExtent[0] > niceTickExtent[1]) {
  25256. niceTickExtent[0] = niceTickExtent[1];
  25257. }
  25258. }
  25259. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  25260. var ticks = [];
  25261. // If interval is 0, return [];
  25262. if (!interval) {
  25263. return ticks;
  25264. }
  25265. // Consider this case: using dataZoom toolbox, zoom and zoom.
  25266. var safeLimit = 10000;
  25267. if (extent[0] < niceTickExtent[0]) {
  25268. ticks.push(extent[0]);
  25269. }
  25270. var tick = niceTickExtent[0];
  25271. while (tick <= niceTickExtent[1]) {
  25272. ticks.push(tick);
  25273. // Avoid rounding error
  25274. tick = roundNumber$1(tick + interval, intervalPrecision);
  25275. if (tick === ticks[ticks.length - 1]) {
  25276. // Consider out of safe float point, e.g.,
  25277. // -3711126.9907707 + 2e-10 === -3711126.9907707
  25278. break;
  25279. }
  25280. if (ticks.length > safeLimit) {
  25281. return [];
  25282. }
  25283. }
  25284. // Consider this case: the last item of ticks is smaller
  25285. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  25286. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  25287. ticks.push(extent[1]);
  25288. }
  25289. return ticks;
  25290. }
  25291. /**
  25292. * Interval scale
  25293. * @module echarts/scale/Interval
  25294. */
  25295. var roundNumber = round$1;
  25296. /**
  25297. * @alias module:echarts/coord/scale/Interval
  25298. * @constructor
  25299. */
  25300. var IntervalScale = Scale.extend({
  25301. type: 'interval',
  25302. _interval: 0,
  25303. _intervalPrecision: 2,
  25304. setExtent: function (start, end) {
  25305. var thisExtent = this._extent;
  25306. //start,end may be a Number like '25',so...
  25307. if (!isNaN(start)) {
  25308. thisExtent[0] = parseFloat(start);
  25309. }
  25310. if (!isNaN(end)) {
  25311. thisExtent[1] = parseFloat(end);
  25312. }
  25313. },
  25314. unionExtent: function (other) {
  25315. var extent = this._extent;
  25316. other[0] < extent[0] && (extent[0] = other[0]);
  25317. other[1] > extent[1] && (extent[1] = other[1]);
  25318. // unionExtent may called by it's sub classes
  25319. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  25320. },
  25321. /**
  25322. * Get interval
  25323. */
  25324. getInterval: function () {
  25325. return this._interval;
  25326. },
  25327. /**
  25328. * Set interval
  25329. */
  25330. setInterval: function (interval) {
  25331. this._interval = interval;
  25332. // Dropped auto calculated niceExtent and use user setted extent
  25333. // We assume user wan't to set both interval, min, max to get a better result
  25334. this._niceExtent = this._extent.slice();
  25335. this._intervalPrecision = getIntervalPrecision(interval);
  25336. },
  25337. /**
  25338. * @return {Array.<number>}
  25339. */
  25340. getTicks: function () {
  25341. return intervalScaleGetTicks(
  25342. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  25343. );
  25344. },
  25345. /**
  25346. * @return {Array.<string>}
  25347. */
  25348. getTicksLabels: function () {
  25349. var labels = [];
  25350. var ticks = this.getTicks();
  25351. for (var i = 0; i < ticks.length; i++) {
  25352. labels.push(this.getLabel(ticks[i]));
  25353. }
  25354. return labels;
  25355. },
  25356. /**
  25357. * @param {number} data
  25358. * @param {Object} [opt]
  25359. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  25360. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  25361. * @return {string}
  25362. */
  25363. getLabel: function (data, opt) {
  25364. if (data == null) {
  25365. return '';
  25366. }
  25367. var precision = opt && opt.precision;
  25368. if (precision == null) {
  25369. precision = getPrecisionSafe(data) || 0;
  25370. }
  25371. else if (precision === 'auto') {
  25372. // Should be more precise then tick.
  25373. precision = this._intervalPrecision;
  25374. }
  25375. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  25376. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  25377. data = roundNumber(data, precision, true);
  25378. return addCommas(data);
  25379. },
  25380. /**
  25381. * Update interval and extent of intervals for nice ticks
  25382. *
  25383. * @param {number} [splitNumber = 5] Desired number of ticks
  25384. * @param {number} [minInterval]
  25385. * @param {number} [maxInterval]
  25386. */
  25387. niceTicks: function (splitNumber, minInterval, maxInterval) {
  25388. splitNumber = splitNumber || 5;
  25389. var extent = this._extent;
  25390. var span = extent[1] - extent[0];
  25391. if (!isFinite(span)) {
  25392. return;
  25393. }
  25394. // User may set axis min 0 and data are all negative
  25395. // FIXME If it needs to reverse ?
  25396. if (span < 0) {
  25397. span = -span;
  25398. extent.reverse();
  25399. }
  25400. var result = intervalScaleNiceTicks(
  25401. extent, splitNumber, minInterval, maxInterval
  25402. );
  25403. this._intervalPrecision = result.intervalPrecision;
  25404. this._interval = result.interval;
  25405. this._niceExtent = result.niceTickExtent;
  25406. },
  25407. /**
  25408. * Nice extent.
  25409. * @param {Object} opt
  25410. * @param {number} [opt.splitNumber = 5] Given approx tick number
  25411. * @param {boolean} [opt.fixMin=false]
  25412. * @param {boolean} [opt.fixMax=false]
  25413. * @param {boolean} [opt.minInterval]
  25414. * @param {boolean} [opt.maxInterval]
  25415. */
  25416. niceExtent: function (opt) {
  25417. var extent = this._extent;
  25418. // If extent start and end are same, expand them
  25419. if (extent[0] === extent[1]) {
  25420. if (extent[0] !== 0) {
  25421. // Expand extent
  25422. var expandSize = extent[0];
  25423. // In the fowllowing case
  25424. // Axis has been fixed max 100
  25425. // Plus data are all 100 and axis extent are [100, 100].
  25426. // Extend to the both side will cause expanded max is larger than fixed max.
  25427. // So only expand to the smaller side.
  25428. if (!opt.fixMax) {
  25429. extent[1] += expandSize / 2;
  25430. extent[0] -= expandSize / 2;
  25431. }
  25432. else {
  25433. extent[0] -= expandSize / 2;
  25434. }
  25435. }
  25436. else {
  25437. extent[1] = 1;
  25438. }
  25439. }
  25440. var span = extent[1] - extent[0];
  25441. // If there are no data and extent are [Infinity, -Infinity]
  25442. if (!isFinite(span)) {
  25443. extent[0] = 0;
  25444. extent[1] = 1;
  25445. }
  25446. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25447. // var extent = this._extent;
  25448. var interval = this._interval;
  25449. if (!opt.fixMin) {
  25450. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  25451. }
  25452. if (!opt.fixMax) {
  25453. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  25454. }
  25455. }
  25456. });
  25457. /**
  25458. * @return {module:echarts/scale/Time}
  25459. */
  25460. IntervalScale.create = function () {
  25461. return new IntervalScale();
  25462. };
  25463. var STACK_PREFIX = '__ec_stack_';
  25464. function getSeriesStackId(seriesModel) {
  25465. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  25466. }
  25467. function getAxisKey(axis) {
  25468. return axis.dim + axis.index;
  25469. }
  25470. /**
  25471. * @param {Object} opt
  25472. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  25473. * @param {number} opt.count Positive interger.
  25474. * @param {number} [opt.barWidth]
  25475. * @param {number} [opt.barMaxWidth]
  25476. * @param {number} [opt.barGap]
  25477. * @param {number} [opt.barCategoryGap]
  25478. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  25479. */
  25480. function getLayoutOnAxis(opt, api) {
  25481. var params = [];
  25482. var baseAxis = opt.axis;
  25483. var axisKey = 'axis0';
  25484. if (baseAxis.type !== 'category') {
  25485. return;
  25486. }
  25487. var bandWidth = baseAxis.getBandWidth();
  25488. for (var i = 0; i < opt.count || 0; i++) {
  25489. params.push(defaults({
  25490. bandWidth: bandWidth,
  25491. axisKey: axisKey,
  25492. stackId: STACK_PREFIX + i
  25493. }, opt));
  25494. }
  25495. var widthAndOffsets = doCalBarWidthAndOffset(params, api);
  25496. var result = [];
  25497. for (var i = 0; i < opt.count; i++) {
  25498. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  25499. item.offsetCenter = item.offset + item.width / 2;
  25500. result.push(item);
  25501. }
  25502. return result;
  25503. }
  25504. function calBarWidthAndOffset(barSeries, api) {
  25505. var seriesInfoList = map(barSeries, function (seriesModel) {
  25506. var data = seriesModel.getData();
  25507. var cartesian = seriesModel.coordinateSystem;
  25508. var baseAxis = cartesian.getBaseAxis();
  25509. var axisExtent = baseAxis.getExtent();
  25510. var bandWidth = baseAxis.type === 'category'
  25511. ? baseAxis.getBandWidth()
  25512. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  25513. var barWidth = parsePercent$1(
  25514. seriesModel.get('barWidth'), bandWidth
  25515. );
  25516. var barMaxWidth = parsePercent$1(
  25517. seriesModel.get('barMaxWidth'), bandWidth
  25518. );
  25519. var barGap = seriesModel.get('barGap');
  25520. var barCategoryGap = seriesModel.get('barCategoryGap');
  25521. return {
  25522. bandWidth: bandWidth,
  25523. barWidth: barWidth,
  25524. barMaxWidth: barMaxWidth,
  25525. barGap: barGap,
  25526. barCategoryGap: barCategoryGap,
  25527. axisKey: getAxisKey(baseAxis),
  25528. stackId: getSeriesStackId(seriesModel)
  25529. };
  25530. });
  25531. return doCalBarWidthAndOffset(seriesInfoList, api);
  25532. }
  25533. function doCalBarWidthAndOffset(seriesInfoList, api) {
  25534. // Columns info on each category axis. Key is cartesian name
  25535. var columnsMap = {};
  25536. each$1(seriesInfoList, function (seriesInfo, idx) {
  25537. var axisKey = seriesInfo.axisKey;
  25538. var bandWidth = seriesInfo.bandWidth;
  25539. var columnsOnAxis = columnsMap[axisKey] || {
  25540. bandWidth: bandWidth,
  25541. remainedWidth: bandWidth,
  25542. autoWidthCount: 0,
  25543. categoryGap: '20%',
  25544. gap: '30%',
  25545. stacks: {}
  25546. };
  25547. var stacks = columnsOnAxis.stacks;
  25548. columnsMap[axisKey] = columnsOnAxis;
  25549. var stackId = seriesInfo.stackId;
  25550. if (!stacks[stackId]) {
  25551. columnsOnAxis.autoWidthCount++;
  25552. }
  25553. stacks[stackId] = stacks[stackId] || {
  25554. width: 0,
  25555. maxWidth: 0
  25556. };
  25557. // Caution: In a single coordinate system, these barGrid attributes
  25558. // will be shared by series. Consider that they have default values,
  25559. // only the attributes set on the last series will work.
  25560. // Do not change this fact unless there will be a break change.
  25561. // TODO
  25562. var barWidth = seriesInfo.barWidth;
  25563. if (barWidth && !stacks[stackId].width) {
  25564. // See #6312, do not restrict width.
  25565. stacks[stackId].width = barWidth;
  25566. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  25567. columnsOnAxis.remainedWidth -= barWidth;
  25568. }
  25569. var barMaxWidth = seriesInfo.barMaxWidth;
  25570. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  25571. var barGap = seriesInfo.barGap;
  25572. (barGap != null) && (columnsOnAxis.gap = barGap);
  25573. var barCategoryGap = seriesInfo.barCategoryGap;
  25574. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  25575. });
  25576. var result = {};
  25577. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  25578. result[coordSysName] = {};
  25579. var stacks = columnsOnAxis.stacks;
  25580. var bandWidth = columnsOnAxis.bandWidth;
  25581. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  25582. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  25583. var remainedWidth = columnsOnAxis.remainedWidth;
  25584. var autoWidthCount = columnsOnAxis.autoWidthCount;
  25585. var autoWidth = (remainedWidth - categoryGap)
  25586. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25587. autoWidth = Math.max(autoWidth, 0);
  25588. // Find if any auto calculated bar exceeded maxBarWidth
  25589. each$1(stacks, function (column, stack) {
  25590. var maxWidth = column.maxWidth;
  25591. if (maxWidth && maxWidth < autoWidth) {
  25592. maxWidth = Math.min(maxWidth, remainedWidth);
  25593. if (column.width) {
  25594. maxWidth = Math.min(maxWidth, column.width);
  25595. }
  25596. remainedWidth -= maxWidth;
  25597. column.width = maxWidth;
  25598. autoWidthCount--;
  25599. }
  25600. });
  25601. // Recalculate width again
  25602. autoWidth = (remainedWidth - categoryGap)
  25603. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  25604. autoWidth = Math.max(autoWidth, 0);
  25605. var widthSum = 0;
  25606. var lastColumn;
  25607. each$1(stacks, function (column, idx) {
  25608. if (!column.width) {
  25609. column.width = autoWidth;
  25610. }
  25611. lastColumn = column;
  25612. widthSum += column.width * (1 + barGapPercent);
  25613. });
  25614. if (lastColumn) {
  25615. widthSum -= lastColumn.width * barGapPercent;
  25616. }
  25617. var offset = -widthSum / 2;
  25618. each$1(stacks, function (column, stackId) {
  25619. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  25620. offset: offset,
  25621. width: column.width
  25622. };
  25623. offset += column.width * (1 + barGapPercent);
  25624. });
  25625. });
  25626. return result;
  25627. }
  25628. /**
  25629. * @param {string} seriesType
  25630. * @param {module:echarts/model/Global} ecModel
  25631. * @param {module:echarts/ExtensionAPI} api
  25632. */
  25633. function layout(seriesType, ecModel, api) {
  25634. var seriesModels = [];
  25635. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  25636. // Check series coordinate, do layout for cartesian2d only
  25637. if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') {
  25638. seriesModels.push(seriesModel);
  25639. }
  25640. });
  25641. var barWidthAndOffset = calBarWidthAndOffset(seriesModels);
  25642. var lastStackCoords = {};
  25643. each$1(seriesModels, function (seriesModel) {
  25644. var data = seriesModel.getData();
  25645. var cartesian = seriesModel.coordinateSystem;
  25646. var baseAxis = cartesian.getBaseAxis();
  25647. var stackId = getSeriesStackId(seriesModel);
  25648. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  25649. var columnOffset = columnLayoutInfo.offset;
  25650. var columnWidth = columnLayoutInfo.width;
  25651. var valueAxis = cartesian.getOtherAxis(baseAxis);
  25652. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  25653. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  25654. data.setLayout({
  25655. offset: columnOffset,
  25656. size: columnWidth
  25657. });
  25658. var valueDim = data.mapDimension(valueAxis.dim);
  25659. var baseDim = data.mapDimension(baseAxis.dim);
  25660. var stacked = isDimensionStacked(data, valueDim, baseDim);
  25661. var isValueAxisH = valueAxis.isHorizontal();
  25662. var valueAxisStart = (baseAxis.onZero || stacked)
  25663. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  25664. : valueAxis.getGlobalExtent()[0];
  25665. for (var idx = 0, len = data.count(); idx < len; idx++) {
  25666. var value = data.get(valueDim, idx);
  25667. var baseValue = data.get(baseDim, idx);
  25668. if (isNaN(value)) {
  25669. continue;
  25670. }
  25671. var sign = value >= 0 ? 'p' : 'n';
  25672. var baseCoord = valueAxisStart;
  25673. // Because of the barMinHeight, we can not use the value in
  25674. // stackResultDimension directly.
  25675. if (stacked) {
  25676. // Only ordinal axis can be stacked.
  25677. if (!lastStackCoords[stackId][baseValue]) {
  25678. lastStackCoords[stackId][baseValue] = {
  25679. p: valueAxisStart, // Positive stack
  25680. n: valueAxisStart // Negative stack
  25681. };
  25682. }
  25683. // Should also consider #4243
  25684. baseCoord = lastStackCoords[stackId][baseValue][sign];
  25685. }
  25686. var x;
  25687. var y;
  25688. var width;
  25689. var height;
  25690. if (isValueAxisH) {
  25691. var coord = cartesian.dataToPoint([value, baseValue]);
  25692. x = baseCoord;
  25693. y = coord[1] + columnOffset;
  25694. width = coord[0] - valueAxisStart;
  25695. height = columnWidth;
  25696. if (Math.abs(width) < barMinHeight) {
  25697. width = (width < 0 ? -1 : 1) * barMinHeight;
  25698. }
  25699. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  25700. }
  25701. else {
  25702. var coord = cartesian.dataToPoint([baseValue, value]);
  25703. x = coord[0] + columnOffset;
  25704. y = baseCoord;
  25705. width = columnWidth;
  25706. height = coord[1] - valueAxisStart;
  25707. if (Math.abs(height) < barMinHeight) {
  25708. // Include zero to has a positive bar
  25709. height = (height <= 0 ? -1 : 1) * barMinHeight;
  25710. }
  25711. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  25712. }
  25713. data.setItemLayout(idx, {
  25714. x: x,
  25715. y: y,
  25716. width: width,
  25717. height: height
  25718. });
  25719. }
  25720. }, this);
  25721. }
  25722. // [About UTC and local time zone]:
  25723. // In most cases, `number.parseDate` will treat input data string as local time
  25724. // (except time zone is specified in time string). And `format.formateTime` returns
  25725. // local time by default. option.useUTC is false by default. This design have
  25726. // concidered these common case:
  25727. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  25728. // in local time by default.
  25729. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  25730. // as its original time, without any time difference.
  25731. var intervalScaleProto = IntervalScale.prototype;
  25732. var mathCeil = Math.ceil;
  25733. var mathFloor = Math.floor;
  25734. var ONE_SECOND = 1000;
  25735. var ONE_MINUTE = ONE_SECOND * 60;
  25736. var ONE_HOUR = ONE_MINUTE * 60;
  25737. var ONE_DAY = ONE_HOUR * 24;
  25738. // FIXME 公用?
  25739. var bisect = function (a, x, lo, hi) {
  25740. while (lo < hi) {
  25741. var mid = lo + hi >>> 1;
  25742. if (a[mid][1] < x) {
  25743. lo = mid + 1;
  25744. }
  25745. else {
  25746. hi = mid;
  25747. }
  25748. }
  25749. return lo;
  25750. };
  25751. /**
  25752. * @alias module:echarts/coord/scale/Time
  25753. * @constructor
  25754. */
  25755. var TimeScale = IntervalScale.extend({
  25756. type: 'time',
  25757. /**
  25758. * @override
  25759. */
  25760. getLabel: function (val) {
  25761. var stepLvl = this._stepLvl;
  25762. var date = new Date(val);
  25763. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  25764. },
  25765. /**
  25766. * @override
  25767. */
  25768. niceExtent: function (opt) {
  25769. var extent = this._extent;
  25770. // If extent start and end are same, expand them
  25771. if (extent[0] === extent[1]) {
  25772. // Expand extent
  25773. extent[0] -= ONE_DAY;
  25774. extent[1] += ONE_DAY;
  25775. }
  25776. // If there are no data and extent are [Infinity, -Infinity]
  25777. if (extent[1] === -Infinity && extent[0] === Infinity) {
  25778. var d = new Date();
  25779. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  25780. extent[0] = extent[1] - ONE_DAY;
  25781. }
  25782. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  25783. // var extent = this._extent;
  25784. var interval = this._interval;
  25785. if (!opt.fixMin) {
  25786. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  25787. }
  25788. if (!opt.fixMax) {
  25789. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  25790. }
  25791. },
  25792. /**
  25793. * @override
  25794. */
  25795. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  25796. approxTickNum = approxTickNum || 10;
  25797. var extent = this._extent;
  25798. var span = extent[1] - extent[0];
  25799. var approxInterval = span / approxTickNum;
  25800. if (minInterval != null && approxInterval < minInterval) {
  25801. approxInterval = minInterval;
  25802. }
  25803. if (maxInterval != null && approxInterval > maxInterval) {
  25804. approxInterval = maxInterval;
  25805. }
  25806. var scaleLevelsLen = scaleLevels.length;
  25807. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  25808. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  25809. var interval = level[1];
  25810. // Same with interval scale if span is much larger than 1 year
  25811. if (level[0] === 'year') {
  25812. var yearSpan = span / interval;
  25813. // From "Nice Numbers for Graph Labels" of Graphic Gems
  25814. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  25815. var yearStep = nice(yearSpan / approxTickNum, true);
  25816. interval *= yearStep;
  25817. }
  25818. var timezoneOffset = this.getSetting('useUTC')
  25819. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  25820. var niceExtent = [
  25821. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  25822. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  25823. ];
  25824. fixExtent(niceExtent, extent);
  25825. this._stepLvl = level;
  25826. // Interval will be used in getTicks
  25827. this._interval = interval;
  25828. this._niceExtent = niceExtent;
  25829. },
  25830. parse: function (val) {
  25831. // val might be float.
  25832. return +parseDate(val);
  25833. }
  25834. });
  25835. each$1(['contain', 'normalize'], function (methodName) {
  25836. TimeScale.prototype[methodName] = function (val) {
  25837. return intervalScaleProto[methodName].call(this, this.parse(val));
  25838. };
  25839. });
  25840. // Steps from d3
  25841. var scaleLevels = [
  25842. // Format interval
  25843. ['hh:mm:ss', ONE_SECOND], // 1s
  25844. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  25845. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  25846. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  25847. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  25848. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  25849. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  25850. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  25851. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  25852. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  25853. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  25854. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  25855. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  25856. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  25857. ['MM-dd\nyyyy', ONE_DAY], // 1d
  25858. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  25859. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  25860. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  25861. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  25862. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  25863. ['week', ONE_DAY * 7], // 7d
  25864. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  25865. ['week', ONE_DAY * 14], // 2w
  25866. ['week', ONE_DAY * 21], // 3w
  25867. ['month', ONE_DAY * 31], // 1M
  25868. ['week', ONE_DAY * 42], // 6w
  25869. ['month', ONE_DAY * 62], // 2M
  25870. ['week', ONE_DAY * 42], // 10w
  25871. ['quarter', ONE_DAY * 380 / 4], // 3M
  25872. ['month', ONE_DAY * 31 * 4], // 4M
  25873. ['month', ONE_DAY * 31 * 5], // 5M
  25874. ['half-year', ONE_DAY * 380 / 2], // 6M
  25875. ['month', ONE_DAY * 31 * 8], // 8M
  25876. ['month', ONE_DAY * 31 * 10], // 10M
  25877. ['year', ONE_DAY * 380] // 1Y
  25878. ];
  25879. /**
  25880. * @param {module:echarts/model/Model}
  25881. * @return {module:echarts/scale/Time}
  25882. */
  25883. TimeScale.create = function (model) {
  25884. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  25885. };
  25886. /**
  25887. * Log scale
  25888. * @module echarts/scale/Log
  25889. */
  25890. // Use some method of IntervalScale
  25891. var scaleProto$1 = Scale.prototype;
  25892. var intervalScaleProto$1 = IntervalScale.prototype;
  25893. var getPrecisionSafe$1 = getPrecisionSafe;
  25894. var roundingErrorFix = round$1;
  25895. var mathFloor$1 = Math.floor;
  25896. var mathCeil$1 = Math.ceil;
  25897. var mathPow$1 = Math.pow;
  25898. var mathLog = Math.log;
  25899. var LogScale = Scale.extend({
  25900. type: 'log',
  25901. base: 10,
  25902. $constructor: function () {
  25903. Scale.apply(this, arguments);
  25904. this._originalScale = new IntervalScale();
  25905. },
  25906. /**
  25907. * @return {Array.<number>}
  25908. */
  25909. getTicks: function () {
  25910. var originalScale = this._originalScale;
  25911. var extent = this._extent;
  25912. var originalExtent = originalScale.getExtent();
  25913. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  25914. var powVal = round$1(mathPow$1(this.base, val));
  25915. // Fix #4158
  25916. powVal = (val === extent[0] && originalScale.__fixMin)
  25917. ? fixRoundingError(powVal, originalExtent[0])
  25918. : powVal;
  25919. powVal = (val === extent[1] && originalScale.__fixMax)
  25920. ? fixRoundingError(powVal, originalExtent[1])
  25921. : powVal;
  25922. return powVal;
  25923. }, this);
  25924. },
  25925. /**
  25926. * @param {number} val
  25927. * @return {string}
  25928. */
  25929. getLabel: intervalScaleProto$1.getLabel,
  25930. /**
  25931. * @param {number} val
  25932. * @return {number}
  25933. */
  25934. scale: function (val) {
  25935. val = scaleProto$1.scale.call(this, val);
  25936. return mathPow$1(this.base, val);
  25937. },
  25938. /**
  25939. * @param {number} start
  25940. * @param {number} end
  25941. */
  25942. setExtent: function (start, end) {
  25943. var base = this.base;
  25944. start = mathLog(start) / mathLog(base);
  25945. end = mathLog(end) / mathLog(base);
  25946. intervalScaleProto$1.setExtent.call(this, start, end);
  25947. },
  25948. /**
  25949. * @return {number} end
  25950. */
  25951. getExtent: function () {
  25952. var base = this.base;
  25953. var extent = scaleProto$1.getExtent.call(this);
  25954. extent[0] = mathPow$1(base, extent[0]);
  25955. extent[1] = mathPow$1(base, extent[1]);
  25956. // Fix #4158
  25957. var originalScale = this._originalScale;
  25958. var originalExtent = originalScale.getExtent();
  25959. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  25960. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  25961. return extent;
  25962. },
  25963. /**
  25964. * @param {Array.<number>} extent
  25965. */
  25966. unionExtent: function (extent) {
  25967. this._originalScale.unionExtent(extent);
  25968. var base = this.base;
  25969. extent[0] = mathLog(extent[0]) / mathLog(base);
  25970. extent[1] = mathLog(extent[1]) / mathLog(base);
  25971. scaleProto$1.unionExtent.call(this, extent);
  25972. },
  25973. /**
  25974. * @override
  25975. */
  25976. unionExtentFromData: function (data, dim) {
  25977. // TODO
  25978. // filter value that <= 0
  25979. this.unionExtent(data.getApproximateExtent(dim));
  25980. },
  25981. /**
  25982. * Update interval and extent of intervals for nice ticks
  25983. * @param {number} [approxTickNum = 10] Given approx tick number
  25984. */
  25985. niceTicks: function (approxTickNum) {
  25986. approxTickNum = approxTickNum || 10;
  25987. var extent = this._extent;
  25988. var span = extent[1] - extent[0];
  25989. if (span === Infinity || span <= 0) {
  25990. return;
  25991. }
  25992. var interval = quantity(span);
  25993. var err = approxTickNum / span * interval;
  25994. // Filter ticks to get closer to the desired count.
  25995. if (err <= 0.5) {
  25996. interval *= 10;
  25997. }
  25998. // Interval should be integer
  25999. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  26000. interval *= 10;
  26001. }
  26002. var niceExtent = [
  26003. round$1(mathCeil$1(extent[0] / interval) * interval),
  26004. round$1(mathFloor$1(extent[1] / interval) * interval)
  26005. ];
  26006. this._interval = interval;
  26007. this._niceExtent = niceExtent;
  26008. },
  26009. /**
  26010. * Nice extent.
  26011. * @override
  26012. */
  26013. niceExtent: function (opt) {
  26014. intervalScaleProto$1.niceExtent.call(this, opt);
  26015. var originalScale = this._originalScale;
  26016. originalScale.__fixMin = opt.fixMin;
  26017. originalScale.__fixMax = opt.fixMax;
  26018. }
  26019. });
  26020. each$1(['contain', 'normalize'], function (methodName) {
  26021. LogScale.prototype[methodName] = function (val) {
  26022. val = mathLog(val) / mathLog(this.base);
  26023. return scaleProto$1[methodName].call(this, val);
  26024. };
  26025. });
  26026. LogScale.create = function () {
  26027. return new LogScale();
  26028. };
  26029. function fixRoundingError(val, originalVal) {
  26030. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  26031. }
  26032. /**
  26033. * Get axis scale extent before niced.
  26034. * Item of returned array can only be number (including Infinity and NaN).
  26035. */
  26036. function getScaleExtent(scale, model) {
  26037. var scaleType = scale.type;
  26038. var min = model.getMin();
  26039. var max = model.getMax();
  26040. var fixMin = min != null;
  26041. var fixMax = max != null;
  26042. var originalExtent = scale.getExtent();
  26043. var axisDataLen;
  26044. var boundaryGap;
  26045. var span;
  26046. if (scaleType === 'ordinal') {
  26047. axisDataLen = model.getCategories().length;
  26048. }
  26049. else {
  26050. boundaryGap = model.get('boundaryGap');
  26051. if (!isArray(boundaryGap)) {
  26052. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  26053. }
  26054. if (typeof boundaryGap[0] === 'boolean') {
  26055. if (__DEV__) {
  26056. console.warn('Boolean type for boundaryGap is only '
  26057. + 'allowed for ordinal axis. Please use string in '
  26058. + 'percentage instead, e.g., "20%". Currently, '
  26059. + 'boundaryGap is set to be 0.');
  26060. }
  26061. boundaryGap = [0, 0];
  26062. }
  26063. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  26064. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  26065. span = (originalExtent[1] - originalExtent[0])
  26066. || Math.abs(originalExtent[0]);
  26067. }
  26068. // Notice: When min/max is not set (that is, when there are null/undefined,
  26069. // which is the most common case), these cases should be ensured:
  26070. // (1) For 'ordinal', show all axis.data.
  26071. // (2) For others:
  26072. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  26073. // disabled).
  26074. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  26075. // be the result that originalExtent enlarged by boundaryGap.
  26076. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  26077. // FIXME
  26078. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  26079. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  26080. // that the results processed by boundaryGap are positive/negative?
  26081. if (min == null) {
  26082. min = scaleType === 'ordinal'
  26083. ? (axisDataLen ? 0 : NaN)
  26084. : originalExtent[0] - boundaryGap[0] * span;
  26085. }
  26086. if (max == null) {
  26087. max = scaleType === 'ordinal'
  26088. ? (axisDataLen ? axisDataLen - 1 : NaN)
  26089. : originalExtent[1] + boundaryGap[1] * span;
  26090. }
  26091. if (min === 'dataMin') {
  26092. min = originalExtent[0];
  26093. }
  26094. else if (typeof min === 'function') {
  26095. min = min({
  26096. min: originalExtent[0],
  26097. max: originalExtent[1]
  26098. });
  26099. }
  26100. if (max === 'dataMax') {
  26101. max = originalExtent[1];
  26102. }
  26103. else if (typeof max === 'function') {
  26104. max = max({
  26105. min: originalExtent[0],
  26106. max: originalExtent[1]
  26107. });
  26108. }
  26109. (min == null || !isFinite(min)) && (min = NaN);
  26110. (max == null || !isFinite(max)) && (max = NaN);
  26111. scale.setBlank(eqNaN(min) || eqNaN(max));
  26112. // Evaluate if axis needs cross zero
  26113. if (model.getNeedCrossZero()) {
  26114. // Axis is over zero and min is not set
  26115. if (min > 0 && max > 0 && !fixMin) {
  26116. min = 0;
  26117. }
  26118. // Axis is under zero and max is not set
  26119. if (min < 0 && max < 0 && !fixMax) {
  26120. max = 0;
  26121. }
  26122. }
  26123. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  26124. // is base axis
  26125. // FIXME
  26126. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  26127. // (2) Refactor the logic with `barGrid`. Is it not need to `calBarWidthAndOffset` twice with different extent?
  26128. // Should not depend on series type `bar`?
  26129. // (3) Fix that might overlap when using dataZoom.
  26130. // (4) Consider other chart types using `barGrid`?
  26131. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  26132. var ecModel = model.ecModel;
  26133. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  26134. var barSeriesModels = [];
  26135. var isBaseAxisAndHasBarSeries;
  26136. ecModel.eachSeriesByType('bar', function (seriesModel) {
  26137. if (seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d') {
  26138. barSeriesModels.push(seriesModel);
  26139. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  26140. }
  26141. });
  26142. if (isBaseAxisAndHasBarSeries) {
  26143. // Adjust axis min and max to account for overflow
  26144. var adjustedScale = adjustScaleForOverflow(min, max, model, barSeriesModels);
  26145. min = adjustedScale.min;
  26146. max = adjustedScale.max;
  26147. }
  26148. }
  26149. return [min, max];
  26150. }
  26151. function adjustScaleForOverflow(min, max, model, barSeriesModels) {
  26152. // Get Axis Length
  26153. var axisExtent = model.axis.getExtent();
  26154. var axisLength = axisExtent[1] - axisExtent[0];
  26155. // Calculate placement of bars on axis
  26156. var barWidthAndOffset = calBarWidthAndOffset(barSeriesModels);
  26157. // Get bars on current base axis and calculate min and max overflow
  26158. var baseAxisKey = model.axis.dim + model.axis.index;
  26159. var barsOnCurrentAxis = barWidthAndOffset[baseAxisKey];
  26160. if (barsOnCurrentAxis === undefined) {
  26161. return {min: min, max: max};
  26162. }
  26163. var minOverflow = Infinity;
  26164. each$1(barsOnCurrentAxis, function (item) {
  26165. minOverflow = Math.min(item.offset, minOverflow);
  26166. });
  26167. var maxOverflow = -Infinity;
  26168. each$1(barsOnCurrentAxis, function (item) {
  26169. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  26170. });
  26171. minOverflow = Math.abs(minOverflow);
  26172. maxOverflow = Math.abs(maxOverflow);
  26173. var totalOverFlow = minOverflow + maxOverflow;
  26174. // Calulate required buffer based on old range and overflow
  26175. var oldRange = max - min;
  26176. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  26177. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  26178. max += overflowBuffer * (maxOverflow / totalOverFlow);
  26179. min -= overflowBuffer * (minOverflow / totalOverFlow);
  26180. return {min: min, max: max};
  26181. }
  26182. function niceScaleExtent(scale, model) {
  26183. var extent = getScaleExtent(scale, model);
  26184. var fixMin = model.getMin() != null;
  26185. var fixMax = model.getMax() != null;
  26186. var splitNumber = model.get('splitNumber');
  26187. if (scale.type === 'log') {
  26188. scale.base = model.get('logBase');
  26189. }
  26190. var scaleType = scale.type;
  26191. scale.setExtent(extent[0], extent[1]);
  26192. scale.niceExtent({
  26193. splitNumber: splitNumber,
  26194. fixMin: fixMin,
  26195. fixMax: fixMax,
  26196. minInterval: (scaleType === 'interval' || scaleType === 'time')
  26197. ? model.get('minInterval') : null,
  26198. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  26199. ? model.get('maxInterval') : null
  26200. });
  26201. // If some one specified the min, max. And the default calculated interval
  26202. // is not good enough. He can specify the interval. It is often appeared
  26203. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  26204. // to be 60.
  26205. // FIXME
  26206. var interval = model.get('interval');
  26207. if (interval != null) {
  26208. scale.setInterval && scale.setInterval(interval);
  26209. }
  26210. }
  26211. /**
  26212. * @param {module:echarts/model/Model} model
  26213. * @param {string} [axisType] Default retrieve from model.type
  26214. * @return {module:echarts/scale/*}
  26215. */
  26216. function createScaleByModel(model, axisType) {
  26217. axisType = axisType || model.get('type');
  26218. if (axisType) {
  26219. switch (axisType) {
  26220. // Buildin scale
  26221. case 'category':
  26222. return new OrdinalScale(
  26223. model.getOrdinalMeta
  26224. ? model.getOrdinalMeta()
  26225. : model.getCategories(),
  26226. [Infinity, -Infinity]
  26227. );
  26228. case 'value':
  26229. return new IntervalScale();
  26230. // Extended scale, like time and log
  26231. default:
  26232. return (Scale.getClass(axisType) || IntervalScale).create(model);
  26233. }
  26234. }
  26235. }
  26236. /**
  26237. * Check if the axis corss 0
  26238. */
  26239. function ifAxisCrossZero(axis) {
  26240. var dataExtent = axis.scale.getExtent();
  26241. var min = dataExtent[0];
  26242. var max = dataExtent[1];
  26243. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  26244. }
  26245. /**
  26246. * @param {Array.<number>} tickCoords In axis self coordinate.
  26247. * @param {Array.<string>} labels
  26248. * @param {string} font
  26249. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  26250. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  26251. * @return {number}
  26252. */
  26253. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  26254. var textSpaceTakenRect;
  26255. var autoLabelInterval = 0;
  26256. var accumulatedLabelInterval = 0;
  26257. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  26258. var step = 1;
  26259. if (labels.length > 40) {
  26260. // Simple optimization for large amount of labels
  26261. step = Math.floor(labels.length / 40);
  26262. }
  26263. for (var i = 0; i < tickCoords.length; i += step) {
  26264. var tickCoord = tickCoords[i];
  26265. // Not precise, do not consider align and vertical align
  26266. // and each distance from axis line yet.
  26267. var rect = getBoundingRect(
  26268. labels[i], font, 'center', 'top'
  26269. );
  26270. rect.x += tickCoord * Math.cos(rotation);
  26271. rect.y += tickCoord * Math.sin(rotation);
  26272. // Magic number
  26273. rect.width *= 1.3;
  26274. rect.height *= 1.3;
  26275. if (!textSpaceTakenRect) {
  26276. textSpaceTakenRect = rect.clone();
  26277. }
  26278. // There is no space for current label;
  26279. else if (textSpaceTakenRect.intersect(rect)) {
  26280. accumulatedLabelInterval++;
  26281. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  26282. }
  26283. else {
  26284. textSpaceTakenRect.union(rect);
  26285. // Reset
  26286. accumulatedLabelInterval = 0;
  26287. }
  26288. }
  26289. if (autoLabelInterval === 0 && step > 1) {
  26290. return step;
  26291. }
  26292. return (autoLabelInterval + 1) * step - 1;
  26293. }
  26294. /**
  26295. * @param {Object} axis
  26296. * @param {Function} labelFormatter
  26297. * @return {Array.<string>}
  26298. */
  26299. function getFormattedLabels(axis, labelFormatter) {
  26300. var scale = axis.scale;
  26301. var labels = scale.getTicksLabels();
  26302. var ticks = scale.getTicks();
  26303. if (typeof labelFormatter === 'string') {
  26304. labelFormatter = (function (tpl) {
  26305. return function (val) {
  26306. return tpl.replace('{value}', val != null ? val : '');
  26307. };
  26308. })(labelFormatter);
  26309. // Consider empty array
  26310. return map(labels, labelFormatter);
  26311. }
  26312. else if (typeof labelFormatter === 'function') {
  26313. return map(ticks, function (tick, idx) {
  26314. return labelFormatter(
  26315. getAxisRawValue(axis, tick),
  26316. idx
  26317. );
  26318. }, this);
  26319. }
  26320. else {
  26321. return labels;
  26322. }
  26323. }
  26324. function getAxisRawValue(axis, value) {
  26325. // In category axis with data zoom, tick is not the original
  26326. // index of axis.data. So tick should not be exposed to user
  26327. // in category axis.
  26328. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  26329. }
  26330. var axisModelCommonMixin = {
  26331. /**
  26332. * Format labels
  26333. * @return {Array.<string>}
  26334. */
  26335. getFormattedLabels: function () {
  26336. return getFormattedLabels(
  26337. this.axis,
  26338. this.get('axisLabel.formatter')
  26339. );
  26340. },
  26341. /**
  26342. * @param {boolean} origin
  26343. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  26344. */
  26345. getMin: function (origin) {
  26346. var option = this.option;
  26347. var min = (!origin && option.rangeStart != null)
  26348. ? option.rangeStart : option.min;
  26349. if (this.axis
  26350. && min != null
  26351. && min !== 'dataMin'
  26352. && typeof min !== 'function'
  26353. && !eqNaN(min)
  26354. ) {
  26355. min = this.axis.scale.parse(min);
  26356. }
  26357. return min;
  26358. },
  26359. /**
  26360. * @param {boolean} origin
  26361. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  26362. */
  26363. getMax: function (origin) {
  26364. var option = this.option;
  26365. var max = (!origin && option.rangeEnd != null)
  26366. ? option.rangeEnd : option.max;
  26367. if (this.axis
  26368. && max != null
  26369. && max !== 'dataMax'
  26370. && typeof max !== 'function'
  26371. && !eqNaN(max)
  26372. ) {
  26373. max = this.axis.scale.parse(max);
  26374. }
  26375. return max;
  26376. },
  26377. /**
  26378. * @return {boolean}
  26379. */
  26380. getNeedCrossZero: function () {
  26381. var option = this.option;
  26382. return (option.rangeStart != null || option.rangeEnd != null)
  26383. ? false : !option.scale;
  26384. },
  26385. /**
  26386. * Should be implemented by each axis model if necessary.
  26387. * @return {module:echarts/model/Component} coordinate system model
  26388. */
  26389. getCoordSysModel: noop,
  26390. /**
  26391. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  26392. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  26393. */
  26394. setRange: function (rangeStart, rangeEnd) {
  26395. this.option.rangeStart = rangeStart;
  26396. this.option.rangeEnd = rangeEnd;
  26397. },
  26398. /**
  26399. * Reset range
  26400. */
  26401. resetRange: function () {
  26402. // rangeStart and rangeEnd is readonly.
  26403. this.option.rangeStart = this.option.rangeEnd = null;
  26404. }
  26405. };
  26406. // Symbol factory
  26407. /**
  26408. * Triangle shape
  26409. * @inner
  26410. */
  26411. var Triangle = extendShape({
  26412. type: 'triangle',
  26413. shape: {
  26414. cx: 0,
  26415. cy: 0,
  26416. width: 0,
  26417. height: 0
  26418. },
  26419. buildPath: function (path, shape) {
  26420. var cx = shape.cx;
  26421. var cy = shape.cy;
  26422. var width = shape.width / 2;
  26423. var height = shape.height / 2;
  26424. path.moveTo(cx, cy - height);
  26425. path.lineTo(cx + width, cy + height);
  26426. path.lineTo(cx - width, cy + height);
  26427. path.closePath();
  26428. }
  26429. });
  26430. /**
  26431. * Diamond shape
  26432. * @inner
  26433. */
  26434. var Diamond = extendShape({
  26435. type: 'diamond',
  26436. shape: {
  26437. cx: 0,
  26438. cy: 0,
  26439. width: 0,
  26440. height: 0
  26441. },
  26442. buildPath: function (path, shape) {
  26443. var cx = shape.cx;
  26444. var cy = shape.cy;
  26445. var width = shape.width / 2;
  26446. var height = shape.height / 2;
  26447. path.moveTo(cx, cy - height);
  26448. path.lineTo(cx + width, cy);
  26449. path.lineTo(cx, cy + height);
  26450. path.lineTo(cx - width, cy);
  26451. path.closePath();
  26452. }
  26453. });
  26454. /**
  26455. * Pin shape
  26456. * @inner
  26457. */
  26458. var Pin = extendShape({
  26459. type: 'pin',
  26460. shape: {
  26461. // x, y on the cusp
  26462. x: 0,
  26463. y: 0,
  26464. width: 0,
  26465. height: 0
  26466. },
  26467. buildPath: function (path, shape) {
  26468. var x = shape.x;
  26469. var y = shape.y;
  26470. var w = shape.width / 5 * 3;
  26471. // Height must be larger than width
  26472. var h = Math.max(w, shape.height);
  26473. var r = w / 2;
  26474. // Dist on y with tangent point and circle center
  26475. var dy = r * r / (h - r);
  26476. var cy = y - h + r + dy;
  26477. var angle = Math.asin(dy / r);
  26478. // Dist on x with tangent point and circle center
  26479. var dx = Math.cos(angle) * r;
  26480. var tanX = Math.sin(angle);
  26481. var tanY = Math.cos(angle);
  26482. var cpLen = r * 0.6;
  26483. var cpLen2 = r * 0.7;
  26484. path.moveTo(x - dx, cy + dy);
  26485. path.arc(
  26486. x, cy, r,
  26487. Math.PI - angle,
  26488. Math.PI * 2 + angle
  26489. );
  26490. path.bezierCurveTo(
  26491. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  26492. x, y - cpLen2,
  26493. x, y
  26494. );
  26495. path.bezierCurveTo(
  26496. x, y - cpLen2,
  26497. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  26498. x - dx, cy + dy
  26499. );
  26500. path.closePath();
  26501. }
  26502. });
  26503. /**
  26504. * Arrow shape
  26505. * @inner
  26506. */
  26507. var Arrow = extendShape({
  26508. type: 'arrow',
  26509. shape: {
  26510. x: 0,
  26511. y: 0,
  26512. width: 0,
  26513. height: 0
  26514. },
  26515. buildPath: function (ctx, shape) {
  26516. var height = shape.height;
  26517. var width = shape.width;
  26518. var x = shape.x;
  26519. var y = shape.y;
  26520. var dx = width / 3 * 2;
  26521. ctx.moveTo(x, y);
  26522. ctx.lineTo(x + dx, y + height);
  26523. ctx.lineTo(x, y + height / 4 * 3);
  26524. ctx.lineTo(x - dx, y + height);
  26525. ctx.lineTo(x, y);
  26526. ctx.closePath();
  26527. }
  26528. });
  26529. /**
  26530. * Map of path contructors
  26531. * @type {Object.<string, module:zrender/graphic/Path>}
  26532. */
  26533. var symbolCtors = {
  26534. line: Line,
  26535. rect: Rect,
  26536. roundRect: Rect,
  26537. square: Rect,
  26538. circle: Circle,
  26539. diamond: Diamond,
  26540. pin: Pin,
  26541. arrow: Arrow,
  26542. triangle: Triangle
  26543. };
  26544. var symbolShapeMakers = {
  26545. line: function (x, y, w, h, shape) {
  26546. // FIXME
  26547. shape.x1 = x;
  26548. shape.y1 = y + h / 2;
  26549. shape.x2 = x + w;
  26550. shape.y2 = y + h / 2;
  26551. },
  26552. rect: function (x, y, w, h, shape) {
  26553. shape.x = x;
  26554. shape.y = y;
  26555. shape.width = w;
  26556. shape.height = h;
  26557. },
  26558. roundRect: function (x, y, w, h, shape) {
  26559. shape.x = x;
  26560. shape.y = y;
  26561. shape.width = w;
  26562. shape.height = h;
  26563. shape.r = Math.min(w, h) / 4;
  26564. },
  26565. square: function (x, y, w, h, shape) {
  26566. var size = Math.min(w, h);
  26567. shape.x = x;
  26568. shape.y = y;
  26569. shape.width = size;
  26570. shape.height = size;
  26571. },
  26572. circle: function (x, y, w, h, shape) {
  26573. // Put circle in the center of square
  26574. shape.cx = x + w / 2;
  26575. shape.cy = y + h / 2;
  26576. shape.r = Math.min(w, h) / 2;
  26577. },
  26578. diamond: function (x, y, w, h, shape) {
  26579. shape.cx = x + w / 2;
  26580. shape.cy = y + h / 2;
  26581. shape.width = w;
  26582. shape.height = h;
  26583. },
  26584. pin: function (x, y, w, h, shape) {
  26585. shape.x = x + w / 2;
  26586. shape.y = y + h / 2;
  26587. shape.width = w;
  26588. shape.height = h;
  26589. },
  26590. arrow: function (x, y, w, h, shape) {
  26591. shape.x = x + w / 2;
  26592. shape.y = y + h / 2;
  26593. shape.width = w;
  26594. shape.height = h;
  26595. },
  26596. triangle: function (x, y, w, h, shape) {
  26597. shape.cx = x + w / 2;
  26598. shape.cy = y + h / 2;
  26599. shape.width = w;
  26600. shape.height = h;
  26601. }
  26602. };
  26603. var symbolBuildProxies = {};
  26604. each$1(symbolCtors, function (Ctor, name) {
  26605. symbolBuildProxies[name] = new Ctor();
  26606. });
  26607. var SymbolClz = extendShape({
  26608. type: 'symbol',
  26609. shape: {
  26610. symbolType: '',
  26611. x: 0,
  26612. y: 0,
  26613. width: 0,
  26614. height: 0
  26615. },
  26616. beforeBrush: function () {
  26617. var style = this.style;
  26618. var shape = this.shape;
  26619. // FIXME
  26620. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  26621. style.textPosition = ['50%', '40%'];
  26622. style.textAlign = 'center';
  26623. style.textVerticalAlign = 'middle';
  26624. }
  26625. },
  26626. buildPath: function (ctx, shape, inBundle) {
  26627. var symbolType = shape.symbolType;
  26628. var proxySymbol = symbolBuildProxies[symbolType];
  26629. if (shape.symbolType !== 'none') {
  26630. if (!proxySymbol) {
  26631. // Default rect
  26632. symbolType = 'rect';
  26633. proxySymbol = symbolBuildProxies[symbolType];
  26634. }
  26635. symbolShapeMakers[symbolType](
  26636. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  26637. );
  26638. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  26639. }
  26640. }
  26641. });
  26642. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  26643. function symbolPathSetColor(color, innerColor) {
  26644. if (this.type !== 'image') {
  26645. var symbolStyle = this.style;
  26646. var symbolShape = this.shape;
  26647. if (symbolShape && symbolShape.symbolType === 'line') {
  26648. symbolStyle.stroke = color;
  26649. }
  26650. else if (this.__isEmptyBrush) {
  26651. symbolStyle.stroke = color;
  26652. symbolStyle.fill = innerColor || '#fff';
  26653. }
  26654. else {
  26655. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  26656. symbolStyle.fill && (symbolStyle.fill = color);
  26657. symbolStyle.stroke && (symbolStyle.stroke = color);
  26658. }
  26659. this.dirty(false);
  26660. }
  26661. }
  26662. /**
  26663. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  26664. * @param {string} symbolType
  26665. * @param {number} x
  26666. * @param {number} y
  26667. * @param {number} w
  26668. * @param {number} h
  26669. * @param {string} color
  26670. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  26671. * for path and image only.
  26672. */
  26673. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  26674. // TODO Support image object, DynamicImage.
  26675. var isEmpty = symbolType.indexOf('empty') === 0;
  26676. if (isEmpty) {
  26677. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  26678. }
  26679. var symbolPath;
  26680. if (symbolType.indexOf('image://') === 0) {
  26681. symbolPath = makeImage(
  26682. symbolType.slice(8),
  26683. new BoundingRect(x, y, w, h),
  26684. keepAspect ? 'center' : 'cover'
  26685. );
  26686. }
  26687. else if (symbolType.indexOf('path://') === 0) {
  26688. symbolPath = makePath(
  26689. symbolType.slice(7),
  26690. {},
  26691. new BoundingRect(x, y, w, h),
  26692. keepAspect ? 'center' : 'cover'
  26693. );
  26694. }
  26695. else {
  26696. symbolPath = new SymbolClz({
  26697. shape: {
  26698. symbolType: symbolType,
  26699. x: x,
  26700. y: y,
  26701. width: w,
  26702. height: h
  26703. }
  26704. });
  26705. }
  26706. symbolPath.__isEmptyBrush = isEmpty;
  26707. symbolPath.setColor = symbolPathSetColor;
  26708. symbolPath.setColor(color);
  26709. return symbolPath;
  26710. }
  26711. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  26712. /**
  26713. * Create a muti dimension List structure from seriesModel.
  26714. * @param {module:echarts/model/Model} seriesModel
  26715. * @return {module:echarts/data/List} list
  26716. */
  26717. function createList(seriesModel) {
  26718. return createListFromArray(seriesModel.getSource(), seriesModel);
  26719. }
  26720. var dataStack$1 = {
  26721. isDimensionStacked: isDimensionStacked,
  26722. enableDataStack: enableDataStack
  26723. };
  26724. /**
  26725. * Create scale
  26726. * @param {Array.<number>} dataExtent
  26727. * @param {Object|module:echarts/Model} option
  26728. */
  26729. function createScale(dataExtent, option) {
  26730. var axisModel = option;
  26731. if (!Model.isInstance(option)) {
  26732. axisModel = new Model(option);
  26733. mixin(axisModel, axisModelCommonMixin);
  26734. }
  26735. var scale = createScaleByModel(axisModel);
  26736. scale.setExtent(dataExtent[0], dataExtent[1]);
  26737. niceScaleExtent(scale, axisModel);
  26738. return scale;
  26739. }
  26740. /**
  26741. * Mixin common methods to axis model,
  26742. *
  26743. * Inlcude methods
  26744. * `getFormattedLabels() => Array.<string>`
  26745. * `getCategories() => Array.<string>`
  26746. * `getMin(origin: boolean) => number`
  26747. * `getMax(origin: boolean) => number`
  26748. * `getNeedCrossZero() => boolean`
  26749. * `setRange(start: number, end: number)`
  26750. * `resetRange()`
  26751. */
  26752. function mixinAxisModelCommonMethods(Model$$1) {
  26753. mixin(Model$$1, axisModelCommonMixin);
  26754. }
  26755. var helper = (Object.freeze || Object)({
  26756. createList: createList,
  26757. getLayoutRect: getLayoutRect,
  26758. dataStack: dataStack$1,
  26759. createScale: createScale,
  26760. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  26761. completeDimensions: completeDimensions,
  26762. createDimensions: createDimensions,
  26763. createSymbol: createSymbol
  26764. });
  26765. var EPSILON$3 = 1e-8;
  26766. function isAroundEqual$1(a, b) {
  26767. return Math.abs(a - b) < EPSILON$3;
  26768. }
  26769. function contain$1(points, x, y) {
  26770. var w = 0;
  26771. var p = points[0];
  26772. if (!p) {
  26773. return false;
  26774. }
  26775. for (var i = 1; i < points.length; i++) {
  26776. var p2 = points[i];
  26777. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  26778. p = p2;
  26779. }
  26780. // Close polygon
  26781. var p0 = points[0];
  26782. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  26783. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  26784. }
  26785. return w !== 0;
  26786. }
  26787. /**
  26788. * @module echarts/coord/geo/Region
  26789. */
  26790. /**
  26791. * @param {string} name
  26792. * @param {Array} geometries
  26793. * @param {Array.<number>} cp
  26794. */
  26795. function Region(name, geometries, cp) {
  26796. /**
  26797. * @type {string}
  26798. * @readOnly
  26799. */
  26800. this.name = name;
  26801. /**
  26802. * @type {Array.<Array>}
  26803. * @readOnly
  26804. */
  26805. this.geometries = geometries;
  26806. if (!cp) {
  26807. var rect = this.getBoundingRect();
  26808. cp = [
  26809. rect.x + rect.width / 2,
  26810. rect.y + rect.height / 2
  26811. ];
  26812. }
  26813. else {
  26814. cp = [cp[0], cp[1]];
  26815. }
  26816. /**
  26817. * @type {Array.<number>}
  26818. */
  26819. this.center = cp;
  26820. }
  26821. Region.prototype = {
  26822. constructor: Region,
  26823. properties: null,
  26824. /**
  26825. * @return {module:zrender/core/BoundingRect}
  26826. */
  26827. getBoundingRect: function () {
  26828. var rect = this._rect;
  26829. if (rect) {
  26830. return rect;
  26831. }
  26832. var MAX_NUMBER = Number.MAX_VALUE;
  26833. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  26834. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  26835. var min2 = [];
  26836. var max2 = [];
  26837. var geometries = this.geometries;
  26838. for (var i = 0; i < geometries.length; i++) {
  26839. // Only support polygon
  26840. if (geometries[i].type !== 'polygon') {
  26841. continue;
  26842. }
  26843. // Doesn't consider hole
  26844. var exterior = geometries[i].exterior;
  26845. fromPoints(exterior, min2, max2);
  26846. min(min$$1, min$$1, min2);
  26847. max(max$$1, max$$1, max2);
  26848. }
  26849. // No data
  26850. if (i === 0) {
  26851. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  26852. }
  26853. return (this._rect = new BoundingRect(
  26854. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  26855. ));
  26856. },
  26857. /**
  26858. * @param {<Array.<number>} coord
  26859. * @return {boolean}
  26860. */
  26861. contain: function (coord) {
  26862. var rect = this.getBoundingRect();
  26863. var geometries = this.geometries;
  26864. if (!rect.contain(coord[0], coord[1])) {
  26865. return false;
  26866. }
  26867. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  26868. // Only support polygon.
  26869. if (geometries[i].type !== 'polygon') {
  26870. continue;
  26871. }
  26872. var exterior = geometries[i].exterior;
  26873. var interiors = geometries[i].interiors;
  26874. if (contain$1(exterior, coord[0], coord[1])) {
  26875. // Not in the region if point is in the hole.
  26876. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  26877. if (contain$1(interiors[k])) {
  26878. continue loopGeo;
  26879. }
  26880. }
  26881. return true;
  26882. }
  26883. }
  26884. return false;
  26885. },
  26886. transformTo: function (x, y, width, height) {
  26887. var rect = this.getBoundingRect();
  26888. var aspect = rect.width / rect.height;
  26889. if (!width) {
  26890. width = aspect * height;
  26891. }
  26892. else if (!height) {
  26893. height = width / aspect ;
  26894. }
  26895. var target = new BoundingRect(x, y, width, height);
  26896. var transform = rect.calculateTransform(target);
  26897. var geometries = this.geometries;
  26898. for (var i = 0; i < geometries.length; i++) {
  26899. // Only support polygon.
  26900. if (geometries[i].type !== 'polygon') {
  26901. continue;
  26902. }
  26903. var exterior = geometries[i].exterior;
  26904. var interiors = geometries[i].interiors;
  26905. for (var p = 0; p < exterior.length; p++) {
  26906. applyTransform(exterior[p], exterior[p], transform);
  26907. }
  26908. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  26909. for (var p = 0; p < interiors[h].length; p++) {
  26910. applyTransform(interiors[h][p], interiors[h][p], transform);
  26911. }
  26912. }
  26913. }
  26914. rect = this._rect;
  26915. rect.copy(target);
  26916. // Update center
  26917. this.center = [
  26918. rect.x + rect.width / 2,
  26919. rect.y + rect.height / 2
  26920. ];
  26921. }
  26922. };
  26923. /**
  26924. * Parse and decode geo json
  26925. * @module echarts/coord/geo/parseGeoJson
  26926. */
  26927. function decode(json) {
  26928. if (!json.UTF8Encoding) {
  26929. return json;
  26930. }
  26931. var encodeScale = json.UTF8Scale;
  26932. if (encodeScale == null) {
  26933. encodeScale = 1024;
  26934. }
  26935. var features = json.features;
  26936. for (var f = 0; f < features.length; f++) {
  26937. var feature = features[f];
  26938. var geometry = feature.geometry;
  26939. var coordinates = geometry.coordinates;
  26940. var encodeOffsets = geometry.encodeOffsets;
  26941. for (var c = 0; c < coordinates.length; c++) {
  26942. var coordinate = coordinates[c];
  26943. if (geometry.type === 'Polygon') {
  26944. coordinates[c] = decodePolygon(
  26945. coordinate,
  26946. encodeOffsets[c],
  26947. encodeScale
  26948. );
  26949. }
  26950. else if (geometry.type === 'MultiPolygon') {
  26951. for (var c2 = 0; c2 < coordinate.length; c2++) {
  26952. var polygon = coordinate[c2];
  26953. coordinate[c2] = decodePolygon(
  26954. polygon,
  26955. encodeOffsets[c][c2],
  26956. encodeScale
  26957. );
  26958. }
  26959. }
  26960. }
  26961. }
  26962. // Has been decoded
  26963. json.UTF8Encoding = false;
  26964. return json;
  26965. }
  26966. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  26967. var result = [];
  26968. var prevX = encodeOffsets[0];
  26969. var prevY = encodeOffsets[1];
  26970. for (var i = 0; i < coordinate.length; i += 2) {
  26971. var x = coordinate.charCodeAt(i) - 64;
  26972. var y = coordinate.charCodeAt(i + 1) - 64;
  26973. // ZigZag decoding
  26974. x = (x >> 1) ^ (-(x & 1));
  26975. y = (y >> 1) ^ (-(y & 1));
  26976. // Delta deocding
  26977. x += prevX;
  26978. y += prevY;
  26979. prevX = x;
  26980. prevY = y;
  26981. // Dequantize
  26982. result.push([x / encodeScale, y / encodeScale]);
  26983. }
  26984. return result;
  26985. }
  26986. /**
  26987. * @alias module:echarts/coord/geo/parseGeoJson
  26988. * @param {Object} geoJson
  26989. * @return {module:zrender/container/Group}
  26990. */
  26991. var parseGeoJson$1 = function (geoJson) {
  26992. decode(geoJson);
  26993. return map(filter(geoJson.features, function (featureObj) {
  26994. // Output of mapshaper may have geometry null
  26995. return featureObj.geometry
  26996. && featureObj.properties
  26997. && featureObj.geometry.coordinates.length > 0;
  26998. }), function (featureObj) {
  26999. var properties = featureObj.properties;
  27000. var geo = featureObj.geometry;
  27001. var coordinates = geo.coordinates;
  27002. var geometries = [];
  27003. if (geo.type === 'Polygon') {
  27004. geometries.push({
  27005. type: 'polygon',
  27006. // According to the GeoJSON specification.
  27007. // First must be exterior, and the rest are all interior(holes).
  27008. exterior: coordinates[0],
  27009. interiors: coordinates.slice(1)
  27010. });
  27011. }
  27012. if (geo.type === 'MultiPolygon') {
  27013. each$1(coordinates, function (item) {
  27014. if (item[0]) {
  27015. geometries.push({
  27016. type: 'polygon',
  27017. exterior: item[0],
  27018. interiors: item.slice(1)
  27019. });
  27020. }
  27021. });
  27022. }
  27023. var region = new Region(
  27024. properties.name,
  27025. geometries,
  27026. properties.cp
  27027. );
  27028. region.properties = properties;
  27029. return region;
  27030. });
  27031. };
  27032. var linearMap$1 = linearMap;
  27033. function fixExtentWithBands(extent, nTick) {
  27034. var size = extent[1] - extent[0];
  27035. var len = nTick;
  27036. var margin = size / len / 2;
  27037. extent[0] += margin;
  27038. extent[1] -= margin;
  27039. }
  27040. var normalizedExtent = [0, 1];
  27041. /**
  27042. * @name module:echarts/coord/CartesianAxis
  27043. * @constructor
  27044. */
  27045. var Axis = function (dim, scale, extent) {
  27046. /**
  27047. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  27048. * @type {string}
  27049. */
  27050. this.dim = dim;
  27051. /**
  27052. * Axis scale
  27053. * @type {module:echarts/coord/scale/*}
  27054. */
  27055. this.scale = scale;
  27056. /**
  27057. * @type {Array.<number>}
  27058. * @private
  27059. */
  27060. this._extent = extent || [0, 0];
  27061. /**
  27062. * @type {boolean}
  27063. */
  27064. this.inverse = false;
  27065. /**
  27066. * Usually true when axis has a ordinal scale
  27067. * @type {boolean}
  27068. */
  27069. this.onBand = false;
  27070. /**
  27071. * @private
  27072. * @type {number}
  27073. */
  27074. this._labelInterval;
  27075. };
  27076. Axis.prototype = {
  27077. constructor: Axis,
  27078. /**
  27079. * If axis extent contain given coord
  27080. * @param {number} coord
  27081. * @return {boolean}
  27082. */
  27083. contain: function (coord) {
  27084. var extent = this._extent;
  27085. var min = Math.min(extent[0], extent[1]);
  27086. var max = Math.max(extent[0], extent[1]);
  27087. return coord >= min && coord <= max;
  27088. },
  27089. /**
  27090. * If axis extent contain given data
  27091. * @param {number} data
  27092. * @return {boolean}
  27093. */
  27094. containData: function (data) {
  27095. return this.contain(this.dataToCoord(data));
  27096. },
  27097. /**
  27098. * Get coord extent.
  27099. * @return {Array.<number>}
  27100. */
  27101. getExtent: function () {
  27102. return this._extent.slice();
  27103. },
  27104. /**
  27105. * Get precision used for formatting
  27106. * @param {Array.<number>} [dataExtent]
  27107. * @return {number}
  27108. */
  27109. getPixelPrecision: function (dataExtent) {
  27110. return getPixelPrecision(
  27111. dataExtent || this.scale.getExtent(),
  27112. this._extent
  27113. );
  27114. },
  27115. /**
  27116. * Set coord extent
  27117. * @param {number} start
  27118. * @param {number} end
  27119. */
  27120. setExtent: function (start, end) {
  27121. var extent = this._extent;
  27122. extent[0] = start;
  27123. extent[1] = end;
  27124. },
  27125. /**
  27126. * Convert data to coord. Data is the rank if it has an ordinal scale
  27127. * @param {number} data
  27128. * @param {boolean} clamp
  27129. * @return {number}
  27130. */
  27131. dataToCoord: function (data, clamp) {
  27132. var extent = this._extent;
  27133. var scale = this.scale;
  27134. data = scale.normalize(data);
  27135. if (this.onBand && scale.type === 'ordinal') {
  27136. extent = extent.slice();
  27137. fixExtentWithBands(extent, scale.count());
  27138. }
  27139. return linearMap$1(data, normalizedExtent, extent, clamp);
  27140. },
  27141. /**
  27142. * Convert coord to data. Data is the rank if it has an ordinal scale
  27143. * @param {number} coord
  27144. * @param {boolean} clamp
  27145. * @return {number}
  27146. */
  27147. coordToData: function (coord, clamp) {
  27148. var extent = this._extent;
  27149. var scale = this.scale;
  27150. if (this.onBand && scale.type === 'ordinal') {
  27151. extent = extent.slice();
  27152. fixExtentWithBands(extent, scale.count());
  27153. }
  27154. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  27155. return this.scale.scale(t);
  27156. },
  27157. /**
  27158. * Convert pixel point to data in axis
  27159. * @param {Array.<number>} point
  27160. * @param {boolean} clamp
  27161. * @return {number} data
  27162. */
  27163. pointToData: function (point, clamp) {
  27164. // Should be implemented in derived class if necessary.
  27165. },
  27166. /**
  27167. * @return {Array.<number>}
  27168. */
  27169. getTicksCoords: function (alignWithLabel) {
  27170. if (this.onBand && !alignWithLabel) {
  27171. var bands = this.getBands();
  27172. var coords = [];
  27173. for (var i = 0; i < bands.length; i++) {
  27174. coords.push(bands[i][0]);
  27175. }
  27176. if (bands[i - 1]) {
  27177. coords.push(bands[i - 1][1]);
  27178. }
  27179. return coords;
  27180. }
  27181. else {
  27182. return map(this.scale.getTicks(), this.dataToCoord, this);
  27183. }
  27184. },
  27185. /**
  27186. * Coords of labels are on the ticks or on the middle of bands
  27187. * @return {Array.<number>}
  27188. */
  27189. getLabelsCoords: function () {
  27190. return map(this.scale.getTicks(), this.dataToCoord, this);
  27191. },
  27192. /**
  27193. * Get bands.
  27194. *
  27195. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  27196. * |---1---|---2---|---3---|---4---|.
  27197. *
  27198. * @return {Array}
  27199. */
  27200. // FIXME Situation when labels is on ticks
  27201. getBands: function () {
  27202. var extent = this.getExtent();
  27203. var bands = [];
  27204. var len = this.scale.count();
  27205. var start = extent[0];
  27206. var end = extent[1];
  27207. var span = end - start;
  27208. for (var i = 0; i < len; i++) {
  27209. bands.push([
  27210. span * i / len + start,
  27211. span * (i + 1) / len + start
  27212. ]);
  27213. }
  27214. return bands;
  27215. },
  27216. /**
  27217. * Get width of band
  27218. * @return {number}
  27219. */
  27220. getBandWidth: function () {
  27221. var axisExtent = this._extent;
  27222. var dataExtent = this.scale.getExtent();
  27223. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  27224. // Fix #2728, avoid NaN when only one data.
  27225. len === 0 && (len = 1);
  27226. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  27227. return Math.abs(size) / len;
  27228. },
  27229. /**
  27230. * @abstract
  27231. * @return {boolean} Is horizontal
  27232. */
  27233. isHorizontal: null,
  27234. /**
  27235. * @abstract
  27236. * @return {number} Get axis rotate, by degree.
  27237. */
  27238. getRotate: null,
  27239. /**
  27240. * Get interval of the axis label.
  27241. * To get precise result, at least one of `getRotate` and `isHorizontal`
  27242. * should be implemented.
  27243. * @return {number}
  27244. */
  27245. getLabelInterval: function () {
  27246. var labelInterval = this._labelInterval;
  27247. if (!labelInterval) {
  27248. var axisModel = this.model;
  27249. var labelModel = axisModel.getModel('axisLabel');
  27250. labelInterval = labelModel.get('interval');
  27251. if (this.type === 'category'
  27252. && (labelInterval == null || labelInterval === 'auto')
  27253. ) {
  27254. labelInterval = getAxisLabelInterval(
  27255. map(this.scale.getTicks(), this.dataToCoord, this),
  27256. axisModel.getFormattedLabels(),
  27257. labelModel.getFont(),
  27258. this.getRotate
  27259. ? this.getRotate()
  27260. : (this.isHorizontal && !this.isHorizontal())
  27261. ? 90
  27262. : 0,
  27263. labelModel.get('rotate')
  27264. );
  27265. }
  27266. this._labelInterval = labelInterval;
  27267. }
  27268. return labelInterval;
  27269. }
  27270. };
  27271. /**
  27272. * Do not mount those modules on 'src/echarts' for better tree shaking.
  27273. */
  27274. var parseGeoJson = parseGeoJson$1;
  27275. var ecUtil = {};
  27276. each$1([
  27277. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  27278. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  27279. 'extend', 'defaults', 'clone', 'merge'
  27280. ],
  27281. function (name) {
  27282. ecUtil[name] = zrUtil[name];
  27283. }
  27284. );
  27285. var DatasetModel = extendComponentModel({
  27286. type: 'dataset',
  27287. /**
  27288. * @protected
  27289. */
  27290. defaultOption: {
  27291. // 'row', 'column'
  27292. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  27293. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  27294. sourceHeader: null,
  27295. dimensions: null,
  27296. source: null
  27297. },
  27298. optionUpdated: function () {
  27299. detectSourceFormat(this);
  27300. }
  27301. });
  27302. extendComponentView({type: 'dataset'});
  27303. SeriesModel.extend({
  27304. type: 'series.line',
  27305. dependencies: ['grid', 'polar'],
  27306. getInitialData: function (option, ecModel) {
  27307. if (__DEV__) {
  27308. var coordSys = option.coordinateSystem;
  27309. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  27310. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  27311. }
  27312. }
  27313. return createListFromArray(this.getSource(), this);
  27314. },
  27315. defaultOption: {
  27316. zlevel: 0, // 一级层叠
  27317. z: 2, // 二级层叠
  27318. coordinateSystem: 'cartesian2d',
  27319. legendHoverLink: true,
  27320. hoverAnimation: true,
  27321. // stack: null
  27322. // xAxisIndex: 0,
  27323. // yAxisIndex: 0,
  27324. // polarIndex: 0,
  27325. // If clip the overflow value
  27326. clipOverflow: true,
  27327. // cursor: null,
  27328. label: {
  27329. position: 'top'
  27330. },
  27331. // itemStyle: {
  27332. // },
  27333. lineStyle: {
  27334. width: 2,
  27335. type: 'solid'
  27336. },
  27337. // areaStyle: {
  27338. // origin of areaStyle. Valid values:
  27339. // `'auto'/null/undefined`: from axisLine to data
  27340. // `'start'`: from min to data
  27341. // `'end'`: from data to max
  27342. // origin: 'auto'
  27343. // },
  27344. // false, 'start', 'end', 'middle'
  27345. step: false,
  27346. // Disabled if step is true
  27347. smooth: false,
  27348. smoothMonotone: null,
  27349. // 拐点图形类型
  27350. symbol: 'emptyCircle',
  27351. // 拐点图形大小
  27352. symbolSize: 4,
  27353. // 拐点图形旋转控制
  27354. symbolRotate: null,
  27355. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  27356. showSymbol: true,
  27357. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  27358. showAllSymbol: false,
  27359. // 是否连接断点
  27360. connectNulls: false,
  27361. // 数据过滤,'average', 'max', 'min', 'sum'
  27362. sampling: 'none',
  27363. animationEasing: 'linear',
  27364. // Disable progressive
  27365. progressive: 0,
  27366. hoverLayerThreshold: Infinity
  27367. }
  27368. });
  27369. /**
  27370. * @param {module:echarts/data/List} data
  27371. * @param {number} dataIndex
  27372. * @return {string} label string. Not null/undefined
  27373. */
  27374. function getDefaultLabel(data, dataIndex) {
  27375. var labelDims = data.mapDimension('defaultedLabel', true);
  27376. var len = labelDims.length;
  27377. // Simple optimization (in lots of cases, label dims length is 1)
  27378. if (len === 1) {
  27379. return retrieveRawValue(data, dataIndex, labelDims[0]);
  27380. }
  27381. else if (len) {
  27382. var vals = [];
  27383. for (var i = 0; i < labelDims.length; i++) {
  27384. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  27385. vals.push(val);
  27386. }
  27387. return vals.join(' ');
  27388. }
  27389. }
  27390. /**
  27391. * @module echarts/chart/helper/Symbol
  27392. */
  27393. function getSymbolSize(data, idx) {
  27394. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  27395. return symbolSize instanceof Array
  27396. ? symbolSize.slice()
  27397. : [+symbolSize, +symbolSize];
  27398. }
  27399. function getScale(symbolSize) {
  27400. return [symbolSize[0] / 2, symbolSize[1] / 2];
  27401. }
  27402. /**
  27403. * @constructor
  27404. * @alias {module:echarts/chart/helper/Symbol}
  27405. * @param {module:echarts/data/List} data
  27406. * @param {number} idx
  27407. * @extends {module:zrender/graphic/Group}
  27408. */
  27409. function SymbolClz$1(data, idx, seriesScope) {
  27410. Group.call(this);
  27411. this.updateData(data, idx, seriesScope);
  27412. }
  27413. var symbolProto = SymbolClz$1.prototype;
  27414. function driftSymbol(dx, dy) {
  27415. this.parent.drift(dx, dy);
  27416. }
  27417. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  27418. // Remove paths created before
  27419. this.removeAll();
  27420. var color = data.getItemVisual(idx, 'color');
  27421. // var symbolPath = createSymbol(
  27422. // symbolType, -0.5, -0.5, 1, 1, color
  27423. // );
  27424. // If width/height are set too small (e.g., set to 1) on ios10
  27425. // and macOS Sierra, a circle stroke become a rect, no matter what
  27426. // the scale is set. So we set width/height as 2. See #4150.
  27427. var symbolPath = createSymbol(
  27428. symbolType, -1, -1, 2, 2, color
  27429. );
  27430. symbolPath.attr({
  27431. z2: 100,
  27432. culling: true,
  27433. scale: getScale(symbolSize)
  27434. });
  27435. // Rewrite drift method
  27436. symbolPath.drift = driftSymbol;
  27437. this._symbolType = symbolType;
  27438. this.add(symbolPath);
  27439. };
  27440. /**
  27441. * Stop animation
  27442. * @param {boolean} toLastFrame
  27443. */
  27444. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  27445. this.childAt(0).stopAnimation(toLastFrame);
  27446. };
  27447. /**
  27448. * FIXME:
  27449. * Caution: This method breaks the encapsulation of this module,
  27450. * but it indeed brings convenience. So do not use the method
  27451. * unless you detailedly know all the implements of `Symbol`,
  27452. * especially animation.
  27453. *
  27454. * Get symbol path element.
  27455. */
  27456. symbolProto.getSymbolPath = function () {
  27457. return this.childAt(0);
  27458. };
  27459. /**
  27460. * Get scale(aka, current symbol size).
  27461. * Including the change caused by animation
  27462. */
  27463. symbolProto.getScale = function () {
  27464. return this.childAt(0).scale;
  27465. };
  27466. /**
  27467. * Highlight symbol
  27468. */
  27469. symbolProto.highlight = function () {
  27470. this.childAt(0).trigger('emphasis');
  27471. };
  27472. /**
  27473. * Downplay symbol
  27474. */
  27475. symbolProto.downplay = function () {
  27476. this.childAt(0).trigger('normal');
  27477. };
  27478. /**
  27479. * @param {number} zlevel
  27480. * @param {number} z
  27481. */
  27482. symbolProto.setZ = function (zlevel, z) {
  27483. var symbolPath = this.childAt(0);
  27484. symbolPath.zlevel = zlevel;
  27485. symbolPath.z = z;
  27486. };
  27487. symbolProto.setDraggable = function (draggable) {
  27488. var symbolPath = this.childAt(0);
  27489. symbolPath.draggable = draggable;
  27490. symbolPath.cursor = draggable ? 'move' : 'pointer';
  27491. };
  27492. /**
  27493. * Update symbol properties
  27494. * @param {module:echarts/data/List} data
  27495. * @param {number} idx
  27496. * @param {Object} [seriesScope]
  27497. * @param {Object} [seriesScope.itemStyle]
  27498. * @param {Object} [seriesScope.hoverItemStyle]
  27499. * @param {Object} [seriesScope.symbolRotate]
  27500. * @param {Object} [seriesScope.symbolOffset]
  27501. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  27502. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  27503. * @param {boolean} [seriesScope.hoverAnimation]
  27504. * @param {Object} [seriesScope.cursorStyle]
  27505. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  27506. * @param {string} [seriesScope.symbolInnerColor]
  27507. * @param {Object} [seriesScope.fadeIn=false]
  27508. */
  27509. symbolProto.updateData = function (data, idx, seriesScope) {
  27510. this.silent = false;
  27511. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  27512. var seriesModel = data.hostModel;
  27513. var symbolSize = getSymbolSize(data, idx);
  27514. var isInit = symbolType !== this._symbolType;
  27515. if (isInit) {
  27516. this._createSymbol(symbolType, data, idx, symbolSize);
  27517. }
  27518. else {
  27519. var symbolPath = this.childAt(0);
  27520. symbolPath.silent = false;
  27521. updateProps(symbolPath, {
  27522. scale: getScale(symbolSize)
  27523. }, seriesModel, idx);
  27524. }
  27525. this._updateCommon(data, idx, symbolSize, seriesScope);
  27526. if (isInit) {
  27527. var symbolPath = this.childAt(0);
  27528. var fadeIn = seriesScope && seriesScope.fadeIn;
  27529. var target = {scale: symbolPath.scale.slice()};
  27530. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  27531. symbolPath.scale = [0, 0];
  27532. fadeIn && (symbolPath.style.opacity = 0);
  27533. initProps(symbolPath, target, seriesModel, idx);
  27534. }
  27535. this._seriesModel = seriesModel;
  27536. };
  27537. // Update common properties
  27538. var normalStyleAccessPath = ['itemStyle'];
  27539. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  27540. var normalLabelAccessPath = ['label'];
  27541. var emphasisLabelAccessPath = ['emphasis', 'label'];
  27542. /**
  27543. * @param {module:echarts/data/List} data
  27544. * @param {number} idx
  27545. * @param {Array.<number>} symbolSize
  27546. * @param {Object} [seriesScope]
  27547. */
  27548. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  27549. var symbolPath = this.childAt(0);
  27550. var seriesModel = data.hostModel;
  27551. var color = data.getItemVisual(idx, 'color');
  27552. // Reset style
  27553. if (symbolPath.type !== 'image') {
  27554. symbolPath.useStyle({
  27555. strokeNoScale: true
  27556. });
  27557. }
  27558. var itemStyle = seriesScope && seriesScope.itemStyle;
  27559. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  27560. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  27561. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  27562. var labelModel = seriesScope && seriesScope.labelModel;
  27563. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  27564. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  27565. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  27566. if (!seriesScope || data.hasItemOption) {
  27567. var itemModel = (seriesScope && seriesScope.itemModel)
  27568. ? seriesScope.itemModel : data.getItemModel(idx);
  27569. // Color must be excluded.
  27570. // Because symbol provide setColor individually to set fill and stroke
  27571. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  27572. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  27573. symbolRotate = itemModel.getShallow('symbolRotate');
  27574. symbolOffset = itemModel.getShallow('symbolOffset');
  27575. labelModel = itemModel.getModel(normalLabelAccessPath);
  27576. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  27577. hoverAnimation = itemModel.getShallow('hoverAnimation');
  27578. cursorStyle = itemModel.getShallow('cursor');
  27579. }
  27580. else {
  27581. hoverItemStyle = extend({}, hoverItemStyle);
  27582. }
  27583. var elStyle = symbolPath.style;
  27584. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  27585. if (symbolOffset) {
  27586. symbolPath.attr('position', [
  27587. parsePercent$1(symbolOffset[0], symbolSize[0]),
  27588. parsePercent$1(symbolOffset[1], symbolSize[1])
  27589. ]);
  27590. }
  27591. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  27592. // PENDING setColor before setStyle!!!
  27593. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  27594. symbolPath.setStyle(itemStyle);
  27595. var opacity = data.getItemVisual(idx, 'opacity');
  27596. if (opacity != null) {
  27597. elStyle.opacity = opacity;
  27598. }
  27599. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  27600. setLabelStyle(
  27601. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  27602. {
  27603. labelFetcher: seriesModel,
  27604. labelDataIndex: idx,
  27605. defaultText: getLabelDefaultText,
  27606. isRectText: true,
  27607. autoColor: color
  27608. }
  27609. );
  27610. // Do not execute util needed.
  27611. function getLabelDefaultText(idx, opt) {
  27612. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  27613. }
  27614. symbolPath.off('mouseover')
  27615. .off('mouseout')
  27616. .off('emphasis')
  27617. .off('normal');
  27618. symbolPath.hoverStyle = hoverItemStyle;
  27619. // FIXME
  27620. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  27621. setHoverStyle(symbolPath);
  27622. var scale = getScale(symbolSize);
  27623. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  27624. var onEmphasis = function() {
  27625. // Do not support this hover animation util some scenario required.
  27626. // Animation can only be supported in hover layer when using `el.incremetal`.
  27627. if (this.incremental) {
  27628. return;
  27629. }
  27630. var ratio = scale[1] / scale[0];
  27631. this.animateTo({
  27632. scale: [
  27633. Math.max(scale[0] * 1.1, scale[0] + 3),
  27634. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  27635. ]
  27636. }, 400, 'elasticOut');
  27637. };
  27638. var onNormal = function() {
  27639. if (this.incremental) {
  27640. return;
  27641. }
  27642. this.animateTo({
  27643. scale: scale
  27644. }, 400, 'elasticOut');
  27645. };
  27646. symbolPath.on('mouseover', onEmphasis)
  27647. .on('mouseout', onNormal)
  27648. .on('emphasis', onEmphasis)
  27649. .on('normal', onNormal);
  27650. }
  27651. };
  27652. /**
  27653. * @param {Function} cb
  27654. * @param {Object} [opt]
  27655. * @param {Object} [opt.keepLabel=true]
  27656. */
  27657. symbolProto.fadeOut = function (cb, opt) {
  27658. var symbolPath = this.childAt(0);
  27659. // Avoid mistaken hover when fading out
  27660. this.silent = symbolPath.silent = true;
  27661. // Not show text when animating
  27662. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  27663. updateProps(
  27664. symbolPath,
  27665. {
  27666. style: {opacity: 0},
  27667. scale: [0, 0]
  27668. },
  27669. this._seriesModel,
  27670. this.dataIndex,
  27671. cb
  27672. );
  27673. };
  27674. inherits(SymbolClz$1, Group);
  27675. /**
  27676. * @module echarts/chart/helper/SymbolDraw
  27677. */
  27678. /**
  27679. * @constructor
  27680. * @alias module:echarts/chart/helper/SymbolDraw
  27681. * @param {module:zrender/graphic/Group} [symbolCtor]
  27682. */
  27683. function SymbolDraw(symbolCtor) {
  27684. this.group = new Group();
  27685. this._symbolCtor = symbolCtor || SymbolClz$1;
  27686. }
  27687. var symbolDrawProto = SymbolDraw.prototype;
  27688. function symbolNeedsDraw(data, point, idx, opt) {
  27689. return point && !isNaN(point[0]) && !isNaN(point[1])
  27690. && !(opt.isIgnore && opt.isIgnore(idx))
  27691. // We do not set clipShape on group, because it will
  27692. // cut part of the symbol element shape.
  27693. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  27694. && data.getItemVisual(idx, 'symbol') !== 'none';
  27695. }
  27696. /**
  27697. * Update symbols draw by new data
  27698. * @param {module:echarts/data/List} data
  27699. * @param {Object} [opt] Or isIgnore
  27700. * @param {Function} [opt.isIgnore]
  27701. * @param {Object} [opt.clipShape]
  27702. */
  27703. symbolDrawProto.updateData = function (data, opt) {
  27704. opt = normalizeUpdateOpt(opt);
  27705. var group = this.group;
  27706. var seriesModel = data.hostModel;
  27707. var oldData = this._data;
  27708. var SymbolCtor = this._symbolCtor;
  27709. var seriesScope = makeSeriesScope(data);
  27710. // There is no oldLineData only when first rendering or switching from
  27711. // stream mode to normal mode, where previous elements should be removed.
  27712. if (!oldData) {
  27713. group.removeAll();
  27714. }
  27715. data.diff(oldData)
  27716. .add(function (newIdx) {
  27717. var point = data.getItemLayout(newIdx);
  27718. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  27719. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  27720. symbolEl.attr('position', point);
  27721. data.setItemGraphicEl(newIdx, symbolEl);
  27722. group.add(symbolEl);
  27723. }
  27724. })
  27725. .update(function (newIdx, oldIdx) {
  27726. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  27727. var point = data.getItemLayout(newIdx);
  27728. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  27729. group.remove(symbolEl);
  27730. return;
  27731. }
  27732. if (!symbolEl) {
  27733. symbolEl = new SymbolCtor(data, newIdx);
  27734. symbolEl.attr('position', point);
  27735. }
  27736. else {
  27737. symbolEl.updateData(data, newIdx, seriesScope);
  27738. updateProps(symbolEl, {
  27739. position: point
  27740. }, seriesModel);
  27741. }
  27742. // Add back
  27743. group.add(symbolEl);
  27744. data.setItemGraphicEl(newIdx, symbolEl);
  27745. })
  27746. .remove(function (oldIdx) {
  27747. var el = oldData.getItemGraphicEl(oldIdx);
  27748. el && el.fadeOut(function () {
  27749. group.remove(el);
  27750. });
  27751. })
  27752. .execute();
  27753. this._data = data;
  27754. };
  27755. symbolDrawProto.isPersistent = function () {
  27756. return true;
  27757. };
  27758. symbolDrawProto.updateLayout = function () {
  27759. var data = this._data;
  27760. if (data) {
  27761. // Not use animation
  27762. data.eachItemGraphicEl(function (el, idx) {
  27763. var point = data.getItemLayout(idx);
  27764. el.attr('position', point);
  27765. });
  27766. }
  27767. };
  27768. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  27769. this._seriesScope = makeSeriesScope(data);
  27770. this._data = null;
  27771. this.group.removeAll();
  27772. };
  27773. /**
  27774. * Update symbols draw by new data
  27775. * @param {module:echarts/data/List} data
  27776. * @param {Object} [opt] Or isIgnore
  27777. * @param {Function} [opt.isIgnore]
  27778. * @param {Object} [opt.clipShape]
  27779. */
  27780. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  27781. opt = normalizeUpdateOpt(opt);
  27782. function updateIncrementalAndHover(el) {
  27783. if (!el.isGroup) {
  27784. el.incremental = el.useHoverLayer = true;
  27785. }
  27786. }
  27787. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  27788. var point = data.getItemLayout(idx);
  27789. if (symbolNeedsDraw(data, point, idx, opt)) {
  27790. var el = new this._symbolCtor(data, idx, this._seriesScope);
  27791. el.traverse(updateIncrementalAndHover);
  27792. el.attr('position', point);
  27793. this.group.add(el);
  27794. data.setItemGraphicEl(idx, el);
  27795. }
  27796. }
  27797. };
  27798. function normalizeUpdateOpt(opt) {
  27799. if (opt != null && !isObject$1(opt)) {
  27800. opt = {isIgnore: opt};
  27801. }
  27802. return opt || {};
  27803. }
  27804. symbolDrawProto.remove = function (enableAnimation) {
  27805. var group = this.group;
  27806. var data = this._data;
  27807. // Incremental model do not have this._data.
  27808. if (data && enableAnimation) {
  27809. data.eachItemGraphicEl(function (el) {
  27810. el.fadeOut(function () {
  27811. group.remove(el);
  27812. });
  27813. });
  27814. }
  27815. else {
  27816. group.removeAll();
  27817. }
  27818. };
  27819. function makeSeriesScope(data) {
  27820. var seriesModel = data.hostModel;
  27821. return {
  27822. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  27823. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  27824. symbolRotate: seriesModel.get('symbolRotate'),
  27825. symbolOffset: seriesModel.get('symbolOffset'),
  27826. hoverAnimation: seriesModel.get('hoverAnimation'),
  27827. labelModel: seriesModel.getModel('label'),
  27828. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  27829. cursorStyle: seriesModel.get('cursor')
  27830. };
  27831. }
  27832. /**
  27833. * @param {Object} coordSys
  27834. * @param {module:echarts/data/List} data
  27835. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  27836. */
  27837. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  27838. var baseAxis = coordSys.getBaseAxis();
  27839. var valueAxis = coordSys.getOtherAxis(baseAxis);
  27840. var valueStart = getValueStart(valueAxis, valueOrigin);
  27841. var baseAxisDim = baseAxis.dim;
  27842. var valueAxisDim = valueAxis.dim;
  27843. var valueDim = data.mapDimension(valueAxisDim);
  27844. var baseDim = data.mapDimension(baseAxisDim);
  27845. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  27846. var stacked = isDimensionStacked(data, valueDim, baseDim);
  27847. var dataDimsForPoint = map(coordSys.dimensions, function (coordDim) {
  27848. return data.mapDimension(coordDim);
  27849. });
  27850. return {
  27851. dataDimsForPoint: dataDimsForPoint,
  27852. valueStart: valueStart,
  27853. valueAxisDim: valueAxisDim,
  27854. baseAxisDim: baseAxisDim,
  27855. stacked: stacked,
  27856. valueDim: valueDim,
  27857. baseDim: baseDim,
  27858. baseDataOffset: baseDataOffset,
  27859. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  27860. };
  27861. }
  27862. function getValueStart(valueAxis, valueOrigin) {
  27863. var valueStart = 0;
  27864. var extent = valueAxis.scale.getExtent();
  27865. if (valueOrigin === 'start') {
  27866. valueStart = extent[0];
  27867. }
  27868. else if (valueOrigin === 'end') {
  27869. valueStart = extent[1];
  27870. }
  27871. // auto
  27872. else {
  27873. // Both positive
  27874. if (extent[0] > 0) {
  27875. valueStart = extent[0];
  27876. }
  27877. // Both negative
  27878. else if (extent[1] < 0) {
  27879. valueStart = extent[1];
  27880. }
  27881. // If is one positive, and one negative, onZero shall be true
  27882. }
  27883. return valueStart;
  27884. }
  27885. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  27886. var value = NaN;
  27887. if (dataCoordInfo.stacked) {
  27888. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  27889. }
  27890. if (isNaN(value)) {
  27891. value = dataCoordInfo.valueStart;
  27892. }
  27893. var baseDataOffset = dataCoordInfo.baseDataOffset;
  27894. var stackedData = [];
  27895. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  27896. stackedData[1 - baseDataOffset] = value;
  27897. return coordSys.dataToPoint(stackedData);
  27898. }
  27899. // var arrayDiff = require('zrender/src/core/arrayDiff');
  27900. // 'zrender/src/core/arrayDiff' has been used before, but it did
  27901. // not do well in performance when roam with fixed dataZoom window.
  27902. // function convertToIntId(newIdList, oldIdList) {
  27903. // // Generate int id instead of string id.
  27904. // // Compare string maybe slow in score function of arrDiff
  27905. // // Assume id in idList are all unique
  27906. // var idIndicesMap = {};
  27907. // var idx = 0;
  27908. // for (var i = 0; i < newIdList.length; i++) {
  27909. // idIndicesMap[newIdList[i]] = idx;
  27910. // newIdList[i] = idx++;
  27911. // }
  27912. // for (var i = 0; i < oldIdList.length; i++) {
  27913. // var oldId = oldIdList[i];
  27914. // // Same with newIdList
  27915. // if (idIndicesMap[oldId]) {
  27916. // oldIdList[i] = idIndicesMap[oldId];
  27917. // }
  27918. // else {
  27919. // oldIdList[i] = idx++;
  27920. // }
  27921. // }
  27922. // }
  27923. function diffData(oldData, newData) {
  27924. var diffResult = [];
  27925. newData.diff(oldData)
  27926. .add(function (idx) {
  27927. diffResult.push({cmd: '+', idx: idx});
  27928. })
  27929. .update(function (newIdx, oldIdx) {
  27930. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  27931. })
  27932. .remove(function (idx) {
  27933. diffResult.push({cmd: '-', idx: idx});
  27934. })
  27935. .execute();
  27936. return diffResult;
  27937. }
  27938. var lineAnimationDiff = function (
  27939. oldData, newData,
  27940. oldStackedOnPoints, newStackedOnPoints,
  27941. oldCoordSys, newCoordSys,
  27942. oldValueOrigin, newValueOrigin
  27943. ) {
  27944. var diff = diffData(oldData, newData);
  27945. // var newIdList = newData.mapArray(newData.getId);
  27946. // var oldIdList = oldData.mapArray(oldData.getId);
  27947. // convertToIntId(newIdList, oldIdList);
  27948. // // FIXME One data ?
  27949. // diff = arrayDiff(oldIdList, newIdList);
  27950. var currPoints = [];
  27951. var nextPoints = [];
  27952. // Points for stacking base line
  27953. var currStackedPoints = [];
  27954. var nextStackedPoints = [];
  27955. var status = [];
  27956. var sortedIndices = [];
  27957. var rawIndices = [];
  27958. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  27959. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  27960. for (var i = 0; i < diff.length; i++) {
  27961. var diffItem = diff[i];
  27962. var pointAdded = true;
  27963. // FIXME, animation is not so perfect when dataZoom window moves fast
  27964. // Which is in case remvoing or add more than one data in the tail or head
  27965. switch (diffItem.cmd) {
  27966. case '=':
  27967. var currentPt = oldData.getItemLayout(diffItem.idx);
  27968. var nextPt = newData.getItemLayout(diffItem.idx1);
  27969. // If previous data is NaN, use next point directly
  27970. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  27971. currentPt = nextPt.slice();
  27972. }
  27973. currPoints.push(currentPt);
  27974. nextPoints.push(nextPt);
  27975. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  27976. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  27977. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  27978. break;
  27979. case '+':
  27980. var idx = diffItem.idx;
  27981. currPoints.push(
  27982. oldCoordSys.dataToPoint([
  27983. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  27984. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  27985. ])
  27986. );
  27987. nextPoints.push(newData.getItemLayout(idx).slice());
  27988. currStackedPoints.push(
  27989. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  27990. );
  27991. nextStackedPoints.push(newStackedOnPoints[idx]);
  27992. rawIndices.push(newData.getRawIndex(idx));
  27993. break;
  27994. case '-':
  27995. var idx = diffItem.idx;
  27996. var rawIndex = oldData.getRawIndex(idx);
  27997. // Data is replaced. In the case of dynamic data queue
  27998. // FIXME FIXME FIXME
  27999. if (rawIndex !== idx) {
  28000. currPoints.push(oldData.getItemLayout(idx));
  28001. nextPoints.push(newCoordSys.dataToPoint([
  28002. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  28003. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  28004. ]));
  28005. currStackedPoints.push(oldStackedOnPoints[idx]);
  28006. nextStackedPoints.push(
  28007. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  28008. );
  28009. rawIndices.push(rawIndex);
  28010. }
  28011. else {
  28012. pointAdded = false;
  28013. }
  28014. }
  28015. // Original indices
  28016. if (pointAdded) {
  28017. status.push(diffItem);
  28018. sortedIndices.push(sortedIndices.length);
  28019. }
  28020. }
  28021. // Diff result may be crossed if all items are changed
  28022. // Sort by data index
  28023. sortedIndices.sort(function (a, b) {
  28024. return rawIndices[a] - rawIndices[b];
  28025. });
  28026. var sortedCurrPoints = [];
  28027. var sortedNextPoints = [];
  28028. var sortedCurrStackedPoints = [];
  28029. var sortedNextStackedPoints = [];
  28030. var sortedStatus = [];
  28031. for (var i = 0; i < sortedIndices.length; i++) {
  28032. var idx = sortedIndices[i];
  28033. sortedCurrPoints[i] = currPoints[idx];
  28034. sortedNextPoints[i] = nextPoints[idx];
  28035. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  28036. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  28037. sortedStatus[i] = status[idx];
  28038. }
  28039. return {
  28040. current: sortedCurrPoints,
  28041. next: sortedNextPoints,
  28042. stackedOnCurrent: sortedCurrStackedPoints,
  28043. stackedOnNext: sortedNextStackedPoints,
  28044. status: sortedStatus
  28045. };
  28046. };
  28047. // Poly path support NaN point
  28048. var vec2Min = min;
  28049. var vec2Max = max;
  28050. var scaleAndAdd$1 = scaleAndAdd;
  28051. var v2Copy = copy;
  28052. // Temporary variable
  28053. var v = [];
  28054. var cp0 = [];
  28055. var cp1 = [];
  28056. function isPointNull(p) {
  28057. return isNaN(p[0]) || isNaN(p[1]);
  28058. }
  28059. function drawSegment(
  28060. ctx, points, start, segLen, allLen,
  28061. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28062. ) {
  28063. if (smoothMonotone == null) {
  28064. if (isMono(points, 'x')) {
  28065. return drawMono(ctx, points, start, segLen, allLen,
  28066. dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  28067. }
  28068. else if (isMono(points, 'y')) {
  28069. return drawMono(ctx, points, start, segLen, allLen,
  28070. dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  28071. }
  28072. else {
  28073. return drawNonMono.apply(this, arguments);
  28074. }
  28075. }
  28076. else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  28077. return drawMono.apply(this, arguments);
  28078. }
  28079. else {
  28080. return drawNonMono.apply(this, arguments);
  28081. }
  28082. }
  28083. /**
  28084. * Check if points is in monotone.
  28085. *
  28086. * @param {number[][]} points Array of points which is in [x, y] form
  28087. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  28088. * dimension that is checking.
  28089. * If is 'none', `drawNonMono` should be
  28090. * called.
  28091. * If is undefined, either being monotone
  28092. * in 'x' or 'y' will call `drawMono`.
  28093. */
  28094. function isMono(points, smoothMonotone) {
  28095. if (points.length <= 1) {
  28096. return true;
  28097. }
  28098. var dim = smoothMonotone === 'x' ? 0 : 1;
  28099. var last = points[0][dim];
  28100. var lastDiff = 0;
  28101. for (var i = 1; i < points.length; ++i) {
  28102. var diff = points[i][dim] - last;
  28103. if (!isNaN(diff) && !isNaN(lastDiff)
  28104. && diff !== 0 && lastDiff !== 0
  28105. && ((diff >= 0) !== (lastDiff >= 0))
  28106. ) {
  28107. return false;
  28108. }
  28109. if (!isNaN(diff) && diff !== 0) {
  28110. lastDiff = diff;
  28111. last = points[i][dim];
  28112. }
  28113. }
  28114. return true;
  28115. }
  28116. /**
  28117. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  28118. * control points will be used. This should be used when points are monotone
  28119. * either in x or y dimension.
  28120. */
  28121. function drawMono(
  28122. ctx, points, start, segLen, allLen,
  28123. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28124. ) {
  28125. var prevIdx = 0;
  28126. var idx = start;
  28127. for (var k = 0; k < segLen; k++) {
  28128. var p = points[idx];
  28129. if (idx >= allLen || idx < 0) {
  28130. break;
  28131. }
  28132. if (isPointNull(p)) {
  28133. if (connectNulls) {
  28134. idx += dir;
  28135. continue;
  28136. }
  28137. break;
  28138. }
  28139. if (idx === start) {
  28140. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28141. }
  28142. else {
  28143. if (smooth > 0) {
  28144. var prevP = points[prevIdx];
  28145. var dim = smoothMonotone === 'y' ? 1 : 0;
  28146. // Length of control point to p, either in x or y, but not both
  28147. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  28148. v2Copy(cp0, prevP);
  28149. cp0[dim] = prevP[dim] + ctrlLen;
  28150. v2Copy(cp1, p);
  28151. cp1[dim] = p[dim] - ctrlLen;
  28152. ctx.bezierCurveTo(
  28153. cp0[0], cp0[1],
  28154. cp1[0], cp1[1],
  28155. p[0], p[1]
  28156. );
  28157. }
  28158. else {
  28159. ctx.lineTo(p[0], p[1]);
  28160. }
  28161. }
  28162. prevIdx = idx;
  28163. idx += dir;
  28164. }
  28165. return k;
  28166. }
  28167. /**
  28168. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  28169. * situations. This should be used when points are non-monotone neither in x or
  28170. * y dimension.
  28171. */
  28172. function drawNonMono(
  28173. ctx, points, start, segLen, allLen,
  28174. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28175. ) {
  28176. var prevIdx = 0;
  28177. var idx = start;
  28178. for (var k = 0; k < segLen; k++) {
  28179. var p = points[idx];
  28180. if (idx >= allLen || idx < 0) {
  28181. break;
  28182. }
  28183. if (isPointNull(p)) {
  28184. if (connectNulls) {
  28185. idx += dir;
  28186. continue;
  28187. }
  28188. break;
  28189. }
  28190. if (idx === start) {
  28191. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28192. v2Copy(cp0, p);
  28193. }
  28194. else {
  28195. if (smooth > 0) {
  28196. var nextIdx = idx + dir;
  28197. var nextP = points[nextIdx];
  28198. if (connectNulls) {
  28199. // Find next point not null
  28200. while (nextP && isPointNull(points[nextIdx])) {
  28201. nextIdx += dir;
  28202. nextP = points[nextIdx];
  28203. }
  28204. }
  28205. var ratioNextSeg = 0.5;
  28206. var prevP = points[prevIdx];
  28207. var nextP = points[nextIdx];
  28208. // Last point
  28209. if (!nextP || isPointNull(nextP)) {
  28210. v2Copy(cp1, p);
  28211. }
  28212. else {
  28213. // If next data is null in not connect case
  28214. if (isPointNull(nextP) && !connectNulls) {
  28215. nextP = p;
  28216. }
  28217. sub(v, nextP, prevP);
  28218. var lenPrevSeg;
  28219. var lenNextSeg;
  28220. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  28221. var dim = smoothMonotone === 'x' ? 0 : 1;
  28222. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  28223. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  28224. }
  28225. else {
  28226. lenPrevSeg = dist(p, prevP);
  28227. lenNextSeg = dist(p, nextP);
  28228. }
  28229. // Use ratio of seg length
  28230. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  28231. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  28232. }
  28233. // Smooth constraint
  28234. vec2Min(cp0, cp0, smoothMax);
  28235. vec2Max(cp0, cp0, smoothMin);
  28236. vec2Min(cp1, cp1, smoothMax);
  28237. vec2Max(cp1, cp1, smoothMin);
  28238. ctx.bezierCurveTo(
  28239. cp0[0], cp0[1],
  28240. cp1[0], cp1[1],
  28241. p[0], p[1]
  28242. );
  28243. // cp0 of next segment
  28244. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  28245. }
  28246. else {
  28247. ctx.lineTo(p[0], p[1]);
  28248. }
  28249. }
  28250. prevIdx = idx;
  28251. idx += dir;
  28252. }
  28253. return k;
  28254. }
  28255. function getBoundingBox(points, smoothConstraint) {
  28256. var ptMin = [Infinity, Infinity];
  28257. var ptMax = [-Infinity, -Infinity];
  28258. if (smoothConstraint) {
  28259. for (var i = 0; i < points.length; i++) {
  28260. var pt = points[i];
  28261. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  28262. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  28263. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  28264. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  28265. }
  28266. }
  28267. return {
  28268. min: smoothConstraint ? ptMin : ptMax,
  28269. max: smoothConstraint ? ptMax : ptMin
  28270. };
  28271. }
  28272. var Polyline$1 = Path.extend({
  28273. type: 'ec-polyline',
  28274. shape: {
  28275. points: [],
  28276. smooth: 0,
  28277. smoothConstraint: true,
  28278. smoothMonotone: null,
  28279. connectNulls: false
  28280. },
  28281. style: {
  28282. fill: null,
  28283. stroke: '#000'
  28284. },
  28285. brush: fixClipWithShadow(Path.prototype.brush),
  28286. buildPath: function (ctx, shape) {
  28287. var points = shape.points;
  28288. var i = 0;
  28289. var len$$1 = points.length;
  28290. var result = getBoundingBox(points, shape.smoothConstraint);
  28291. if (shape.connectNulls) {
  28292. // Must remove first and last null values avoid draw error in polygon
  28293. for (; len$$1 > 0; len$$1--) {
  28294. if (!isPointNull(points[len$$1 - 1])) {
  28295. break;
  28296. }
  28297. }
  28298. for (; i < len$$1; i++) {
  28299. if (!isPointNull(points[i])) {
  28300. break;
  28301. }
  28302. }
  28303. }
  28304. while (i < len$$1) {
  28305. i += drawSegment(
  28306. ctx, points, i, len$$1, len$$1,
  28307. 1, result.min, result.max, shape.smooth,
  28308. shape.smoothMonotone, shape.connectNulls
  28309. ) + 1;
  28310. }
  28311. }
  28312. });
  28313. var Polygon$1 = Path.extend({
  28314. type: 'ec-polygon',
  28315. shape: {
  28316. points: [],
  28317. // Offset between stacked base points and points
  28318. stackedOnPoints: [],
  28319. smooth: 0,
  28320. stackedOnSmooth: 0,
  28321. smoothConstraint: true,
  28322. smoothMonotone: null,
  28323. connectNulls: false
  28324. },
  28325. brush: fixClipWithShadow(Path.prototype.brush),
  28326. buildPath: function (ctx, shape) {
  28327. var points = shape.points;
  28328. var stackedOnPoints = shape.stackedOnPoints;
  28329. var i = 0;
  28330. var len$$1 = points.length;
  28331. var smoothMonotone = shape.smoothMonotone;
  28332. var bbox = getBoundingBox(points, shape.smoothConstraint);
  28333. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  28334. if (shape.connectNulls) {
  28335. // Must remove first and last null values avoid draw error in polygon
  28336. for (; len$$1 > 0; len$$1--) {
  28337. if (!isPointNull(points[len$$1 - 1])) {
  28338. break;
  28339. }
  28340. }
  28341. for (; i < len$$1; i++) {
  28342. if (!isPointNull(points[i])) {
  28343. break;
  28344. }
  28345. }
  28346. }
  28347. while (i < len$$1) {
  28348. var k = drawSegment(
  28349. ctx, points, i, len$$1, len$$1,
  28350. 1, bbox.min, bbox.max, shape.smooth,
  28351. smoothMonotone, shape.connectNulls
  28352. );
  28353. drawSegment(
  28354. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  28355. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  28356. smoothMonotone, shape.connectNulls
  28357. );
  28358. i += k + 1;
  28359. ctx.closePath();
  28360. }
  28361. }
  28362. });
  28363. // FIXME step not support polar
  28364. function isPointsSame(points1, points2) {
  28365. if (points1.length !== points2.length) {
  28366. return;
  28367. }
  28368. for (var i = 0; i < points1.length; i++) {
  28369. var p1 = points1[i];
  28370. var p2 = points2[i];
  28371. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  28372. return;
  28373. }
  28374. }
  28375. return true;
  28376. }
  28377. function getSmooth(smooth) {
  28378. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  28379. }
  28380. function getAxisExtentWithGap(axis) {
  28381. var extent = axis.getGlobalExtent();
  28382. if (axis.onBand) {
  28383. // Remove extra 1px to avoid line miter in clipped edge
  28384. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  28385. var dir = extent[1] > extent[0] ? 1 : -1;
  28386. extent[0] += dir * halfBandWidth;
  28387. extent[1] -= dir * halfBandWidth;
  28388. }
  28389. return extent;
  28390. }
  28391. /**
  28392. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  28393. * @param {module:echarts/data/List} data
  28394. * @param {Object} dataCoordInfo
  28395. * @param {Array.<Array.<number>>} points
  28396. */
  28397. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  28398. if (!dataCoordInfo.valueDim) {
  28399. return [];
  28400. }
  28401. var points = [];
  28402. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28403. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  28404. }
  28405. return points;
  28406. }
  28407. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  28408. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  28409. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  28410. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  28411. var x = Math.min(xExtent[0], xExtent[1]);
  28412. var y = Math.min(yExtent[0], yExtent[1]);
  28413. var width = Math.max(xExtent[0], xExtent[1]) - x;
  28414. var height = Math.max(yExtent[0], yExtent[1]) - y;
  28415. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  28416. // Expand clip shape to avoid clipping when line value exceeds axis
  28417. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  28418. if (isHorizontal) {
  28419. y -= expandSize;
  28420. height += expandSize * 2;
  28421. }
  28422. else {
  28423. x -= expandSize;
  28424. width += expandSize * 2;
  28425. }
  28426. var clipPath = new Rect({
  28427. shape: {
  28428. x: x,
  28429. y: y,
  28430. width: width,
  28431. height: height
  28432. }
  28433. });
  28434. if (hasAnimation) {
  28435. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  28436. initProps(clipPath, {
  28437. shape: {
  28438. width: width,
  28439. height: height
  28440. }
  28441. }, seriesModel);
  28442. }
  28443. return clipPath;
  28444. }
  28445. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  28446. var angleAxis = polar.getAngleAxis();
  28447. var radiusAxis = polar.getRadiusAxis();
  28448. var radiusExtent = radiusAxis.getExtent();
  28449. var angleExtent = angleAxis.getExtent();
  28450. var RADIAN = Math.PI / 180;
  28451. var clipPath = new Sector({
  28452. shape: {
  28453. cx: polar.cx,
  28454. cy: polar.cy,
  28455. r0: radiusExtent[0],
  28456. r: radiusExtent[1],
  28457. startAngle: -angleExtent[0] * RADIAN,
  28458. endAngle: -angleExtent[1] * RADIAN,
  28459. clockwise: angleAxis.inverse
  28460. }
  28461. });
  28462. if (hasAnimation) {
  28463. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  28464. initProps(clipPath, {
  28465. shape: {
  28466. endAngle: -angleExtent[1] * RADIAN
  28467. }
  28468. }, seriesModel);
  28469. }
  28470. return clipPath;
  28471. }
  28472. function createClipShape(coordSys, hasAnimation, seriesModel) {
  28473. return coordSys.type === 'polar'
  28474. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  28475. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  28476. }
  28477. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  28478. var baseAxis = coordSys.getBaseAxis();
  28479. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  28480. var stepPoints = [];
  28481. for (var i = 0; i < points.length - 1; i++) {
  28482. var nextPt = points[i + 1];
  28483. var pt = points[i];
  28484. stepPoints.push(pt);
  28485. var stepPt = [];
  28486. switch (stepTurnAt) {
  28487. case 'end':
  28488. stepPt[baseIndex] = nextPt[baseIndex];
  28489. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28490. // default is start
  28491. stepPoints.push(stepPt);
  28492. break;
  28493. case 'middle':
  28494. // default is start
  28495. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  28496. var stepPt2 = [];
  28497. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  28498. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28499. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  28500. stepPoints.push(stepPt);
  28501. stepPoints.push(stepPt2);
  28502. break;
  28503. default:
  28504. stepPt[baseIndex] = pt[baseIndex];
  28505. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  28506. // default is start
  28507. stepPoints.push(stepPt);
  28508. }
  28509. }
  28510. // Last points
  28511. points[i] && stepPoints.push(points[i]);
  28512. return stepPoints;
  28513. }
  28514. function getVisualGradient(data, coordSys) {
  28515. var visualMetaList = data.getVisual('visualMeta');
  28516. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  28517. // When data.count() is 0, gradient range can not be calculated.
  28518. return;
  28519. }
  28520. if (coordSys.type !== 'cartesian2d') {
  28521. if (__DEV__) {
  28522. console.warn('Visual map on line style is only supported on cartesian2d.');
  28523. }
  28524. return;
  28525. }
  28526. var coordDim;
  28527. var visualMeta;
  28528. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  28529. var dimIndex = visualMetaList[i].dimension;
  28530. var dimName = data.dimensions[dimIndex];
  28531. var dimInfo = data.getDimensionInfo(dimName);
  28532. coordDim = dimInfo && dimInfo.coordDim;
  28533. // Can only be x or y
  28534. if (coordDim === 'x' || coordDim === 'y') {
  28535. visualMeta = visualMetaList[i];
  28536. break;
  28537. }
  28538. }
  28539. if (!visualMeta) {
  28540. if (__DEV__) {
  28541. console.warn('Visual map on line style only support x or y dimension.');
  28542. }
  28543. return;
  28544. }
  28545. // If the area to be rendered is bigger than area defined by LinearGradient,
  28546. // the canvas spec prescribes that the color of the first stop and the last
  28547. // stop should be used. But if two stops are added at offset 0, in effect
  28548. // browsers use the color of the second stop to render area outside
  28549. // LinearGradient. So we can only infinitesimally extend area defined in
  28550. // LinearGradient to render `outerColors`.
  28551. var axis = coordSys.getAxis(coordDim);
  28552. // dataToCoor mapping may not be linear, but must be monotonic.
  28553. var colorStops = map(visualMeta.stops, function (stop) {
  28554. return {
  28555. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  28556. color: stop.color
  28557. };
  28558. });
  28559. var stopLen = colorStops.length;
  28560. var outerColors = visualMeta.outerColors.slice();
  28561. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  28562. colorStops.reverse();
  28563. outerColors.reverse();
  28564. }
  28565. var tinyExtent = 10; // Arbitrary value: 10px
  28566. var minCoord = colorStops[0].coord - tinyExtent;
  28567. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  28568. var coordSpan = maxCoord - minCoord;
  28569. if (coordSpan < 1e-3) {
  28570. return 'transparent';
  28571. }
  28572. each$1(colorStops, function (stop) {
  28573. stop.offset = (stop.coord - minCoord) / coordSpan;
  28574. });
  28575. colorStops.push({
  28576. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  28577. color: outerColors[1] || 'transparent'
  28578. });
  28579. colorStops.unshift({ // notice colorStops.length have been changed.
  28580. offset: stopLen ? colorStops[0].offset : 0.5,
  28581. color: outerColors[0] || 'transparent'
  28582. });
  28583. // zrUtil.each(colorStops, function (colorStop) {
  28584. // // Make sure each offset has rounded px to avoid not sharp edge
  28585. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  28586. // });
  28587. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  28588. gradient[coordDim] = minCoord;
  28589. gradient[coordDim + '2'] = maxCoord;
  28590. return gradient;
  28591. }
  28592. Chart.extend({
  28593. type: 'line',
  28594. init: function () {
  28595. var lineGroup = new Group();
  28596. var symbolDraw = new SymbolDraw();
  28597. this.group.add(symbolDraw.group);
  28598. this._symbolDraw = symbolDraw;
  28599. this._lineGroup = lineGroup;
  28600. },
  28601. render: function (seriesModel, ecModel, api) {
  28602. var coordSys = seriesModel.coordinateSystem;
  28603. var group = this.group;
  28604. var data = seriesModel.getData();
  28605. var lineStyleModel = seriesModel.getModel('lineStyle');
  28606. var areaStyleModel = seriesModel.getModel('areaStyle');
  28607. var points = data.mapArray(data.getItemLayout);
  28608. var isCoordSysPolar = coordSys.type === 'polar';
  28609. var prevCoordSys = this._coordSys;
  28610. var symbolDraw = this._symbolDraw;
  28611. var polyline = this._polyline;
  28612. var polygon = this._polygon;
  28613. var lineGroup = this._lineGroup;
  28614. var hasAnimation = seriesModel.get('animation');
  28615. var isAreaChart = !areaStyleModel.isEmpty();
  28616. var valueOrigin = areaStyleModel.get('origin');
  28617. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  28618. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  28619. var showSymbol = seriesModel.get('showSymbol');
  28620. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  28621. && this._getSymbolIgnoreFunc(data, coordSys);
  28622. // Remove temporary symbols
  28623. var oldData = this._data;
  28624. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28625. if (el.__temp) {
  28626. group.remove(el);
  28627. oldData.setItemGraphicEl(idx, null);
  28628. }
  28629. });
  28630. // Remove previous created symbols if showSymbol changed to false
  28631. if (!showSymbol) {
  28632. symbolDraw.remove();
  28633. }
  28634. group.add(lineGroup);
  28635. // FIXME step not support polar
  28636. var step = !isCoordSysPolar && seriesModel.get('step');
  28637. // Initialization animation or coordinate system changed
  28638. if (
  28639. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  28640. ) {
  28641. showSymbol && symbolDraw.updateData(data, {
  28642. isIgnore: isSymbolIgnore,
  28643. clipShape: createClipShape(coordSys, false, seriesModel)
  28644. });
  28645. if (step) {
  28646. // TODO If stacked series is not step
  28647. points = turnPointsIntoStep(points, coordSys, step);
  28648. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  28649. }
  28650. polyline = this._newPolyline(points, coordSys, hasAnimation);
  28651. if (isAreaChart) {
  28652. polygon = this._newPolygon(
  28653. points, stackedOnPoints,
  28654. coordSys, hasAnimation
  28655. );
  28656. }
  28657. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  28658. }
  28659. else {
  28660. if (isAreaChart && !polygon) {
  28661. // If areaStyle is added
  28662. polygon = this._newPolygon(
  28663. points, stackedOnPoints,
  28664. coordSys, hasAnimation
  28665. );
  28666. }
  28667. else if (polygon && !isAreaChart) {
  28668. // If areaStyle is removed
  28669. lineGroup.remove(polygon);
  28670. polygon = this._polygon = null;
  28671. }
  28672. var coordSysClipShape = createClipShape(coordSys, false, seriesModel);
  28673. // Update clipPath
  28674. lineGroup.setClipPath(coordSysClipShape);
  28675. // Always update, or it is wrong in the case turning on legend
  28676. // because points are not changed
  28677. showSymbol && symbolDraw.updateData(data, {
  28678. isIgnore: isSymbolIgnore,
  28679. clipShape: coordSysClipShape
  28680. });
  28681. // Stop symbol animation and sync with line points
  28682. // FIXME performance?
  28683. data.eachItemGraphicEl(function (el) {
  28684. el.stopAnimation(true);
  28685. });
  28686. // In the case data zoom triggerred refreshing frequently
  28687. // Data may not change if line has a category axis. So it should animate nothing
  28688. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  28689. || !isPointsSame(this._points, points)
  28690. ) {
  28691. if (hasAnimation) {
  28692. this._updateAnimation(
  28693. data, stackedOnPoints, coordSys, api, step, valueOrigin
  28694. );
  28695. }
  28696. else {
  28697. // Not do it in update with animation
  28698. if (step) {
  28699. // TODO If stacked series is not step
  28700. points = turnPointsIntoStep(points, coordSys, step);
  28701. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  28702. }
  28703. polyline.setShape({
  28704. points: points
  28705. });
  28706. polygon && polygon.setShape({
  28707. points: points,
  28708. stackedOnPoints: stackedOnPoints
  28709. });
  28710. }
  28711. }
  28712. }
  28713. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  28714. polyline.useStyle(defaults(
  28715. // Use color in lineStyle first
  28716. lineStyleModel.getLineStyle(),
  28717. {
  28718. fill: 'none',
  28719. stroke: visualColor,
  28720. lineJoin: 'bevel'
  28721. }
  28722. ));
  28723. var smooth = seriesModel.get('smooth');
  28724. smooth = getSmooth(seriesModel.get('smooth'));
  28725. polyline.setShape({
  28726. smooth: smooth,
  28727. smoothMonotone: seriesModel.get('smoothMonotone'),
  28728. connectNulls: seriesModel.get('connectNulls')
  28729. });
  28730. if (polygon) {
  28731. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  28732. var stackedOnSmooth = 0;
  28733. polygon.useStyle(defaults(
  28734. areaStyleModel.getAreaStyle(),
  28735. {
  28736. fill: visualColor,
  28737. opacity: 0.7,
  28738. lineJoin: 'bevel'
  28739. }
  28740. ));
  28741. if (stackedOnSeries) {
  28742. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  28743. }
  28744. polygon.setShape({
  28745. smooth: smooth,
  28746. stackedOnSmooth: stackedOnSmooth,
  28747. smoothMonotone: seriesModel.get('smoothMonotone'),
  28748. connectNulls: seriesModel.get('connectNulls')
  28749. });
  28750. }
  28751. this._data = data;
  28752. // Save the coordinate system for transition animation when data changed
  28753. this._coordSys = coordSys;
  28754. this._stackedOnPoints = stackedOnPoints;
  28755. this._points = points;
  28756. this._step = step;
  28757. this._valueOrigin = valueOrigin;
  28758. },
  28759. dispose: function () {},
  28760. highlight: function (seriesModel, ecModel, api, payload) {
  28761. var data = seriesModel.getData();
  28762. var dataIndex = queryDataIndex(data, payload);
  28763. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  28764. var symbol = data.getItemGraphicEl(dataIndex);
  28765. if (!symbol) {
  28766. // Create a temporary symbol if it is not exists
  28767. var pt = data.getItemLayout(dataIndex);
  28768. if (!pt) {
  28769. // Null data
  28770. return;
  28771. }
  28772. symbol = new SymbolClz$1(data, dataIndex);
  28773. symbol.position = pt;
  28774. symbol.setZ(
  28775. seriesModel.get('zlevel'),
  28776. seriesModel.get('z')
  28777. );
  28778. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  28779. symbol.__temp = true;
  28780. data.setItemGraphicEl(dataIndex, symbol);
  28781. // Stop scale animation
  28782. symbol.stopSymbolAnimation(true);
  28783. this.group.add(symbol);
  28784. }
  28785. symbol.highlight();
  28786. }
  28787. else {
  28788. // Highlight whole series
  28789. Chart.prototype.highlight.call(
  28790. this, seriesModel, ecModel, api, payload
  28791. );
  28792. }
  28793. },
  28794. downplay: function (seriesModel, ecModel, api, payload) {
  28795. var data = seriesModel.getData();
  28796. var dataIndex = queryDataIndex(data, payload);
  28797. if (dataIndex != null && dataIndex >= 0) {
  28798. var symbol = data.getItemGraphicEl(dataIndex);
  28799. if (symbol) {
  28800. if (symbol.__temp) {
  28801. data.setItemGraphicEl(dataIndex, null);
  28802. this.group.remove(symbol);
  28803. }
  28804. else {
  28805. symbol.downplay();
  28806. }
  28807. }
  28808. }
  28809. else {
  28810. // FIXME
  28811. // can not downplay completely.
  28812. // Downplay whole series
  28813. Chart.prototype.downplay.call(
  28814. this, seriesModel, ecModel, api, payload
  28815. );
  28816. }
  28817. },
  28818. /**
  28819. * @param {module:zrender/container/Group} group
  28820. * @param {Array.<Array.<number>>} points
  28821. * @private
  28822. */
  28823. _newPolyline: function (points) {
  28824. var polyline = this._polyline;
  28825. // Remove previous created polyline
  28826. if (polyline) {
  28827. this._lineGroup.remove(polyline);
  28828. }
  28829. polyline = new Polyline$1({
  28830. shape: {
  28831. points: points
  28832. },
  28833. silent: true,
  28834. z2: 10
  28835. });
  28836. this._lineGroup.add(polyline);
  28837. this._polyline = polyline;
  28838. return polyline;
  28839. },
  28840. /**
  28841. * @param {module:zrender/container/Group} group
  28842. * @param {Array.<Array.<number>>} stackedOnPoints
  28843. * @param {Array.<Array.<number>>} points
  28844. * @private
  28845. */
  28846. _newPolygon: function (points, stackedOnPoints) {
  28847. var polygon = this._polygon;
  28848. // Remove previous created polygon
  28849. if (polygon) {
  28850. this._lineGroup.remove(polygon);
  28851. }
  28852. polygon = new Polygon$1({
  28853. shape: {
  28854. points: points,
  28855. stackedOnPoints: stackedOnPoints
  28856. },
  28857. silent: true
  28858. });
  28859. this._lineGroup.add(polygon);
  28860. this._polygon = polygon;
  28861. return polygon;
  28862. },
  28863. /**
  28864. * @private
  28865. */
  28866. _getSymbolIgnoreFunc: function (data, coordSys) {
  28867. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  28868. // `getLabelInterval` is provided by echarts/component/axis
  28869. if (categoryAxis && categoryAxis.isLabelIgnored) {
  28870. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  28871. }
  28872. },
  28873. /**
  28874. * @private
  28875. */
  28876. // FIXME Two value axis
  28877. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  28878. var polyline = this._polyline;
  28879. var polygon = this._polygon;
  28880. var seriesModel = data.hostModel;
  28881. var diff = lineAnimationDiff(
  28882. this._data, data,
  28883. this._stackedOnPoints, stackedOnPoints,
  28884. this._coordSys, coordSys,
  28885. this._valueOrigin, valueOrigin
  28886. );
  28887. var current = diff.current;
  28888. var stackedOnCurrent = diff.stackedOnCurrent;
  28889. var next = diff.next;
  28890. var stackedOnNext = diff.stackedOnNext;
  28891. if (step) {
  28892. // TODO If stacked series is not step
  28893. current = turnPointsIntoStep(diff.current, coordSys, step);
  28894. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  28895. next = turnPointsIntoStep(diff.next, coordSys, step);
  28896. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  28897. }
  28898. // `diff.current` is subset of `current` (which should be ensured by
  28899. // turnPointsIntoStep), so points in `__points` can be updated when
  28900. // points in `current` are update during animation.
  28901. polyline.shape.__points = diff.current;
  28902. polyline.shape.points = current;
  28903. updateProps(polyline, {
  28904. shape: {
  28905. points: next
  28906. }
  28907. }, seriesModel);
  28908. if (polygon) {
  28909. polygon.setShape({
  28910. points: current,
  28911. stackedOnPoints: stackedOnCurrent
  28912. });
  28913. updateProps(polygon, {
  28914. shape: {
  28915. points: next,
  28916. stackedOnPoints: stackedOnNext
  28917. }
  28918. }, seriesModel);
  28919. }
  28920. var updatedDataInfo = [];
  28921. var diffStatus = diff.status;
  28922. for (var i = 0; i < diffStatus.length; i++) {
  28923. var cmd = diffStatus[i].cmd;
  28924. if (cmd === '=') {
  28925. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  28926. if (el) {
  28927. updatedDataInfo.push({
  28928. el: el,
  28929. ptIdx: i // Index of points
  28930. });
  28931. }
  28932. }
  28933. }
  28934. if (polyline.animators && polyline.animators.length) {
  28935. polyline.animators[0].during(function () {
  28936. for (var i = 0; i < updatedDataInfo.length; i++) {
  28937. var el = updatedDataInfo[i].el;
  28938. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  28939. }
  28940. });
  28941. }
  28942. },
  28943. remove: function (ecModel) {
  28944. var group = this.group;
  28945. var oldData = this._data;
  28946. this._lineGroup.removeAll();
  28947. this._symbolDraw.remove(true);
  28948. // Remove temporary created elements when highlighting
  28949. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  28950. if (el.__temp) {
  28951. group.remove(el);
  28952. oldData.setItemGraphicEl(idx, null);
  28953. }
  28954. });
  28955. this._polyline =
  28956. this._polygon =
  28957. this._coordSys =
  28958. this._points =
  28959. this._stackedOnPoints =
  28960. this._data = null;
  28961. }
  28962. });
  28963. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  28964. // Encoding visual for all series include which is filtered for legend drawing
  28965. return {
  28966. seriesType: seriesType,
  28967. performRawSeries: true,
  28968. reset: function (seriesModel, ecModel, api) {
  28969. var data = seriesModel.getData();
  28970. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  28971. var symbolSize = seriesModel.get('symbolSize');
  28972. data.setVisual({
  28973. legendSymbol: legendSymbol || symbolType,
  28974. symbol: symbolType,
  28975. symbolSize: symbolSize
  28976. });
  28977. // Only visible series has each data be visual encoded
  28978. if (ecModel.isSeriesFiltered(seriesModel)) {
  28979. return;
  28980. }
  28981. var hasCallback = typeof symbolSize === 'function';
  28982. function dataEach(data, idx) {
  28983. if (typeof symbolSize === 'function') {
  28984. var rawValue = seriesModel.getRawValue(idx);
  28985. // FIXME
  28986. var params = seriesModel.getDataParams(idx);
  28987. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  28988. }
  28989. if (data.hasItemOption) {
  28990. var itemModel = data.getItemModel(idx);
  28991. var itemSymbolType = itemModel.getShallow('symbol', true);
  28992. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  28993. // If has item symbol
  28994. if (itemSymbolType != null) {
  28995. data.setItemVisual(idx, 'symbol', itemSymbolType);
  28996. }
  28997. if (itemSymbolSize != null) {
  28998. // PENDING Transform symbolSize ?
  28999. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  29000. }
  29001. }
  29002. }
  29003. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  29004. }
  29005. };
  29006. };
  29007. var pointsLayout = function (seriesType) {
  29008. return {
  29009. seriesType: seriesType,
  29010. plan: createRenderPlanner(),
  29011. reset: function (seriesModel) {
  29012. var data = seriesModel.getData();
  29013. var coordSys = seriesModel.coordinateSystem;
  29014. var pipelineContext = seriesModel.pipelineContext;
  29015. var isLargeRender = pipelineContext.large;
  29016. if (!coordSys) {
  29017. return;
  29018. }
  29019. var dims = map(coordSys.dimensions, function (dim) {
  29020. return data.mapDimension(dim);
  29021. }).slice(0, 2);
  29022. var dimLen = dims.length;
  29023. if (isDimensionStacked(data, dims[0], dims[1])) {
  29024. dims[0] = data.getCalculationInfo('stackResultDimension');
  29025. }
  29026. if (isDimensionStacked(data, dims[1], dims[0])) {
  29027. dims[1] = data.getCalculationInfo('stackResultDimension');
  29028. }
  29029. function progress(params, data) {
  29030. var segCount = params.end - params.start;
  29031. var points = isLargeRender && new Float32Array(segCount * dimLen);
  29032. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  29033. var point;
  29034. if (dimLen === 1) {
  29035. var x = data.get(dims[0], i, true);
  29036. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  29037. }
  29038. else {
  29039. var x = tmpIn[0] = data.get(dims[0], i, true);
  29040. var y = tmpIn[1] = data.get(dims[1], i, true);
  29041. // Also {Array.<number>}, not undefined to avoid if...else... statement
  29042. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  29043. }
  29044. if (isLargeRender) {
  29045. points[offset++] = point ? point[0] : NaN;
  29046. points[offset++] = point ? point[1] : NaN;
  29047. }
  29048. else {
  29049. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  29050. }
  29051. }
  29052. isLargeRender && data.setLayout('symbolPoints', points);
  29053. }
  29054. return dimLen && {progress: progress};
  29055. }
  29056. };
  29057. };
  29058. var samplers = {
  29059. average: function (frame) {
  29060. var sum = 0;
  29061. var count = 0;
  29062. for (var i = 0; i < frame.length; i++) {
  29063. if (!isNaN(frame[i])) {
  29064. sum += frame[i];
  29065. count++;
  29066. }
  29067. }
  29068. // Return NaN if count is 0
  29069. return count === 0 ? NaN : sum / count;
  29070. },
  29071. sum: function (frame) {
  29072. var sum = 0;
  29073. for (var i = 0; i < frame.length; i++) {
  29074. // Ignore NaN
  29075. sum += frame[i] || 0;
  29076. }
  29077. return sum;
  29078. },
  29079. max: function (frame) {
  29080. var max = -Infinity;
  29081. for (var i = 0; i < frame.length; i++) {
  29082. frame[i] > max && (max = frame[i]);
  29083. }
  29084. return max;
  29085. },
  29086. min: function (frame) {
  29087. var min = Infinity;
  29088. for (var i = 0; i < frame.length; i++) {
  29089. frame[i] < min && (min = frame[i]);
  29090. }
  29091. return min;
  29092. },
  29093. // TODO
  29094. // Median
  29095. nearest: function (frame) {
  29096. return frame[0];
  29097. }
  29098. };
  29099. var indexSampler = function (frame, value) {
  29100. return Math.round(frame.length / 2);
  29101. };
  29102. var dataSample = function (seriesType) {
  29103. return {
  29104. seriesType: seriesType,
  29105. reset: function (seriesModel, ecModel, api) {
  29106. var data = seriesModel.getData();
  29107. var sampling = seriesModel.get('sampling');
  29108. var coordSys = seriesModel.coordinateSystem;
  29109. // Only cartesian2d support down sampling
  29110. if (coordSys.type === 'cartesian2d' && sampling) {
  29111. var baseAxis = coordSys.getBaseAxis();
  29112. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29113. var extent = baseAxis.getExtent();
  29114. // Coordinste system has been resized
  29115. var size = extent[1] - extent[0];
  29116. var rate = Math.round(data.count() / size);
  29117. if (rate > 1) {
  29118. var sampler;
  29119. if (typeof sampling === 'string') {
  29120. sampler = samplers[sampling];
  29121. }
  29122. else if (typeof sampling === 'function') {
  29123. sampler = sampling;
  29124. }
  29125. if (sampler) {
  29126. seriesModel.setData(data.downSample(
  29127. valueAxis.dim, 1 / rate, sampler, indexSampler
  29128. ));
  29129. }
  29130. }
  29131. }
  29132. }
  29133. };
  29134. };
  29135. /**
  29136. * Cartesian coordinate system
  29137. * @module echarts/coord/Cartesian
  29138. *
  29139. */
  29140. function dimAxisMapper(dim) {
  29141. return this._axes[dim];
  29142. }
  29143. /**
  29144. * @alias module:echarts/coord/Cartesian
  29145. * @constructor
  29146. */
  29147. var Cartesian = function (name) {
  29148. this._axes = {};
  29149. this._dimList = [];
  29150. /**
  29151. * @type {string}
  29152. */
  29153. this.name = name || '';
  29154. };
  29155. Cartesian.prototype = {
  29156. constructor: Cartesian,
  29157. type: 'cartesian',
  29158. /**
  29159. * Get axis
  29160. * @param {number|string} dim
  29161. * @return {module:echarts/coord/Cartesian~Axis}
  29162. */
  29163. getAxis: function (dim) {
  29164. return this._axes[dim];
  29165. },
  29166. /**
  29167. * Get axes list
  29168. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  29169. */
  29170. getAxes: function () {
  29171. return map(this._dimList, dimAxisMapper, this);
  29172. },
  29173. /**
  29174. * Get axes list by given scale type
  29175. */
  29176. getAxesByScale: function (scaleType) {
  29177. scaleType = scaleType.toLowerCase();
  29178. return filter(
  29179. this.getAxes(),
  29180. function (axis) {
  29181. return axis.scale.type === scaleType;
  29182. }
  29183. );
  29184. },
  29185. /**
  29186. * Add axis
  29187. * @param {module:echarts/coord/Cartesian.Axis}
  29188. */
  29189. addAxis: function (axis) {
  29190. var dim = axis.dim;
  29191. this._axes[dim] = axis;
  29192. this._dimList.push(dim);
  29193. },
  29194. /**
  29195. * Convert data to coord in nd space
  29196. * @param {Array.<number>|Object.<string, number>} val
  29197. * @return {Array.<number>|Object.<string, number>}
  29198. */
  29199. dataToCoord: function (val) {
  29200. return this._dataCoordConvert(val, 'dataToCoord');
  29201. },
  29202. /**
  29203. * Convert coord in nd space to data
  29204. * @param {Array.<number>|Object.<string, number>} val
  29205. * @return {Array.<number>|Object.<string, number>}
  29206. */
  29207. coordToData: function (val) {
  29208. return this._dataCoordConvert(val, 'coordToData');
  29209. },
  29210. _dataCoordConvert: function (input, method) {
  29211. var dimList = this._dimList;
  29212. var output = input instanceof Array ? [] : {};
  29213. for (var i = 0; i < dimList.length; i++) {
  29214. var dim = dimList[i];
  29215. var axis = this._axes[dim];
  29216. output[dim] = axis[method](input[dim]);
  29217. }
  29218. return output;
  29219. }
  29220. };
  29221. function Cartesian2D(name) {
  29222. Cartesian.call(this, name);
  29223. }
  29224. Cartesian2D.prototype = {
  29225. constructor: Cartesian2D,
  29226. type: 'cartesian2d',
  29227. /**
  29228. * @type {Array.<string>}
  29229. * @readOnly
  29230. */
  29231. dimensions: ['x', 'y'],
  29232. /**
  29233. * Base axis will be used on stacking.
  29234. *
  29235. * @return {module:echarts/coord/cartesian/Axis2D}
  29236. */
  29237. getBaseAxis: function () {
  29238. return this.getAxesByScale('ordinal')[0]
  29239. || this.getAxesByScale('time')[0]
  29240. || this.getAxis('x');
  29241. },
  29242. /**
  29243. * If contain point
  29244. * @param {Array.<number>} point
  29245. * @return {boolean}
  29246. */
  29247. containPoint: function (point) {
  29248. var axisX = this.getAxis('x');
  29249. var axisY = this.getAxis('y');
  29250. return axisX.contain(axisX.toLocalCoord(point[0]))
  29251. && axisY.contain(axisY.toLocalCoord(point[1]));
  29252. },
  29253. /**
  29254. * If contain data
  29255. * @param {Array.<number>} data
  29256. * @return {boolean}
  29257. */
  29258. containData: function (data) {
  29259. return this.getAxis('x').containData(data[0])
  29260. && this.getAxis('y').containData(data[1]);
  29261. },
  29262. /**
  29263. * @param {Array.<number>} data
  29264. * @param {Array.<number>} out
  29265. * @return {Array.<number>}
  29266. */
  29267. dataToPoint: function (data, reserved, out) {
  29268. var xAxis = this.getAxis('x');
  29269. var yAxis = this.getAxis('y');
  29270. out = out || [];
  29271. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  29272. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  29273. return out;
  29274. },
  29275. /**
  29276. * @param {Array.<number>} data
  29277. * @param {Array.<number>} out
  29278. * @return {Array.<number>}
  29279. */
  29280. clampData: function (data, out) {
  29281. var xAxisExtent = this.getAxis('x').scale.getExtent();
  29282. var yAxisExtent = this.getAxis('y').scale.getExtent();
  29283. out = out || [];
  29284. out[0] = Math.min(
  29285. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), data[0]),
  29286. Math.max(xAxisExtent[0], xAxisExtent[1])
  29287. );
  29288. out[1] = Math.min(
  29289. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), data[1]),
  29290. Math.max(yAxisExtent[0], yAxisExtent[1])
  29291. );
  29292. return out;
  29293. },
  29294. /**
  29295. * @param {Array.<number>} point
  29296. * @param {Array.<number>} out
  29297. * @return {Array.<number>}
  29298. */
  29299. pointToData: function (point, out) {
  29300. var xAxis = this.getAxis('x');
  29301. var yAxis = this.getAxis('y');
  29302. out = out || [];
  29303. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  29304. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  29305. return out;
  29306. },
  29307. /**
  29308. * Get other axis
  29309. * @param {module:echarts/coord/cartesian/Axis2D} axis
  29310. */
  29311. getOtherAxis: function (axis) {
  29312. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  29313. }
  29314. };
  29315. inherits(Cartesian2D, Cartesian);
  29316. /**
  29317. * Extend axis 2d
  29318. * @constructor module:echarts/coord/cartesian/Axis2D
  29319. * @extends {module:echarts/coord/cartesian/Axis}
  29320. * @param {string} dim
  29321. * @param {*} scale
  29322. * @param {Array.<number>} coordExtent
  29323. * @param {string} axisType
  29324. * @param {string} position
  29325. */
  29326. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  29327. Axis.call(this, dim, scale, coordExtent);
  29328. /**
  29329. * Axis type
  29330. * - 'category'
  29331. * - 'value'
  29332. * - 'time'
  29333. * - 'log'
  29334. * @type {string}
  29335. */
  29336. this.type = axisType || 'value';
  29337. /**
  29338. * Axis position
  29339. * - 'top'
  29340. * - 'bottom'
  29341. * - 'left'
  29342. * - 'right'
  29343. */
  29344. this.position = position || 'bottom';
  29345. };
  29346. Axis2D.prototype = {
  29347. constructor: Axis2D,
  29348. /**
  29349. * Index of axis, can be used as key
  29350. */
  29351. index: 0,
  29352. /**
  29353. * If axis is on the zero position of the other axis
  29354. * @type {boolean}
  29355. */
  29356. onZero: false,
  29357. /**
  29358. * Axis model
  29359. * @param {module:echarts/coord/cartesian/AxisModel}
  29360. */
  29361. model: null,
  29362. isHorizontal: function () {
  29363. var position = this.position;
  29364. return position === 'top' || position === 'bottom';
  29365. },
  29366. /**
  29367. * Each item cooresponds to this.getExtent(), which
  29368. * means globalExtent[0] may greater than globalExtent[1],
  29369. * unless `asc` is input.
  29370. *
  29371. * @param {boolean} [asc]
  29372. * @return {Array.<number>}
  29373. */
  29374. getGlobalExtent: function (asc) {
  29375. var ret = this.getExtent();
  29376. ret[0] = this.toGlobalCoord(ret[0]);
  29377. ret[1] = this.toGlobalCoord(ret[1]);
  29378. asc && ret[0] > ret[1] && ret.reverse();
  29379. return ret;
  29380. },
  29381. getOtherAxis: function () {
  29382. this.grid.getOtherAxis();
  29383. },
  29384. /**
  29385. * If label is ignored.
  29386. * Automatically used when axis is category and label can not be all shown
  29387. * @param {number} idx
  29388. * @return {boolean}
  29389. */
  29390. isLabelIgnored: function (idx) {
  29391. if (this.type === 'category') {
  29392. var labelInterval = this.getLabelInterval();
  29393. return ((typeof labelInterval === 'function')
  29394. && !labelInterval(idx, this.scale.getLabel(idx)))
  29395. || idx % (labelInterval + 1);
  29396. }
  29397. },
  29398. /**
  29399. * @override
  29400. */
  29401. pointToData: function (point, clamp) {
  29402. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  29403. },
  29404. /**
  29405. * Transform global coord to local coord,
  29406. * i.e. var localCoord = axis.toLocalCoord(80);
  29407. * designate by module:echarts/coord/cartesian/Grid.
  29408. * @type {Function}
  29409. */
  29410. toLocalCoord: null,
  29411. /**
  29412. * Transform global coord to local coord,
  29413. * i.e. var globalCoord = axis.toLocalCoord(40);
  29414. * designate by module:echarts/coord/cartesian/Grid.
  29415. * @type {Function}
  29416. */
  29417. toGlobalCoord: null
  29418. };
  29419. inherits(Axis2D, Axis);
  29420. var defaultOption = {
  29421. show: true,
  29422. zlevel: 0, // 一级层叠
  29423. z: 0, // 二级层叠
  29424. // 反向坐标轴
  29425. inverse: false,
  29426. // 坐标轴名字,默认为空
  29427. name: '',
  29428. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  29429. nameLocation: 'end',
  29430. // 坐标轴名字旋转,degree。
  29431. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  29432. nameTruncate: {
  29433. maxWidth: null,
  29434. ellipsis: '...',
  29435. placeholder: '.'
  29436. },
  29437. // 坐标轴文字样式,默认取全局样式
  29438. nameTextStyle: {},
  29439. // 文字与轴线距离
  29440. nameGap: 15,
  29441. silent: false, // Default false to support tooltip.
  29442. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  29443. tooltip: {
  29444. show: false
  29445. },
  29446. axisPointer: {},
  29447. // 坐标轴线
  29448. axisLine: {
  29449. // 默认显示,属性show控制显示与否
  29450. show: true,
  29451. onZero: true,
  29452. onZeroAxisIndex: null,
  29453. // 属性lineStyle控制线条样式
  29454. lineStyle: {
  29455. color: '#333',
  29456. width: 1,
  29457. type: 'solid'
  29458. },
  29459. // 坐标轴两端的箭头
  29460. symbol: ['none', 'none'],
  29461. symbolSize: [10, 15]
  29462. },
  29463. // 坐标轴小标记
  29464. axisTick: {
  29465. // 属性show控制显示与否,默认显示
  29466. show: true,
  29467. // 控制小标记是否在grid里
  29468. inside: false,
  29469. // 属性length控制线长
  29470. length: 5,
  29471. // 属性lineStyle控制线条样式
  29472. lineStyle: {
  29473. width: 1
  29474. }
  29475. },
  29476. // 坐标轴文本标签,详见axis.axisLabel
  29477. axisLabel: {
  29478. show: true,
  29479. // 控制文本标签是否在grid里
  29480. inside: false,
  29481. rotate: 0,
  29482. showMinLabel: null, // true | false | null (auto)
  29483. showMaxLabel: null, // true | false | null (auto)
  29484. margin: 8,
  29485. // formatter: null,
  29486. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  29487. fontSize: 12
  29488. },
  29489. // 分隔线
  29490. splitLine: {
  29491. // 默认显示,属性show控制显示与否
  29492. show: true,
  29493. // 属性lineStyle(详见lineStyle)控制线条样式
  29494. lineStyle: {
  29495. color: ['#ccc'],
  29496. width: 1,
  29497. type: 'solid'
  29498. }
  29499. },
  29500. // 分隔区域
  29501. splitArea: {
  29502. // 默认不显示,属性show控制显示与否
  29503. show: false,
  29504. // 属性areaStyle(详见areaStyle)控制区域样式
  29505. areaStyle: {
  29506. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  29507. }
  29508. }
  29509. };
  29510. var axisDefault = {};
  29511. axisDefault.categoryAxis = merge({
  29512. // 类目起始和结束两端空白策略
  29513. boundaryGap: true,
  29514. // Set false to faster category collection.
  29515. // Only usefull in the case like: category is
  29516. // ['2012-01-01', '2012-01-02', ...], where the input
  29517. // data has been ensured not duplicate and is large data.
  29518. // null means "auto":
  29519. // if axis.data provided, do not deduplication,
  29520. // else do deduplication.
  29521. deduplication: null,
  29522. // splitArea: {
  29523. // show: false
  29524. // },
  29525. splitLine: {
  29526. show: false
  29527. },
  29528. // 坐标轴小标记
  29529. axisTick: {
  29530. // If tick is align with label when boundaryGap is true
  29531. alignWithLabel: false,
  29532. interval: 'auto'
  29533. },
  29534. // 坐标轴文本标签,详见axis.axisLabel
  29535. axisLabel: {
  29536. interval: 'auto'
  29537. }
  29538. }, defaultOption);
  29539. axisDefault.valueAxis = merge({
  29540. // 数值起始和结束两端空白策略
  29541. boundaryGap: [0, 0],
  29542. // TODO
  29543. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  29544. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  29545. // min: null,
  29546. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  29547. // max: null,
  29548. // Readonly prop, specifies start value of the range when using data zoom.
  29549. // rangeStart: null
  29550. // Readonly prop, specifies end value of the range when using data zoom.
  29551. // rangeEnd: null
  29552. // 脱离0值比例,放大聚焦到最终_min,_max区间
  29553. // scale: false,
  29554. // 分割段数,默认为5
  29555. splitNumber: 5
  29556. // Minimum interval
  29557. // minInterval: null
  29558. // maxInterval: null
  29559. }, defaultOption);
  29560. // FIXME
  29561. axisDefault.timeAxis = defaults({
  29562. scale: true,
  29563. min: 'dataMin',
  29564. max: 'dataMax'
  29565. }, axisDefault.valueAxis);
  29566. axisDefault.logAxis = defaults({
  29567. scale: true,
  29568. logBase: 10
  29569. }, axisDefault.valueAxis);
  29570. // FIXME axisType is fixed ?
  29571. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  29572. /**
  29573. * Generate sub axis model class
  29574. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  29575. * @param {module:echarts/model/Component} BaseAxisModelClass
  29576. * @param {Function} axisTypeDefaulter
  29577. * @param {Object} [extraDefaultOption]
  29578. */
  29579. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  29580. each$1(AXIS_TYPES, function (axisType) {
  29581. BaseAxisModelClass.extend({
  29582. /**
  29583. * @readOnly
  29584. */
  29585. type: axisName + 'Axis.' + axisType,
  29586. mergeDefaultAndTheme: function (option, ecModel) {
  29587. var layoutMode = this.layoutMode;
  29588. var inputPositionParams = layoutMode
  29589. ? getLayoutParams(option) : {};
  29590. var themeModel = ecModel.getTheme();
  29591. merge(option, themeModel.get(axisType + 'Axis'));
  29592. merge(option, this.getDefaultOption());
  29593. option.type = axisTypeDefaulter(axisName, option);
  29594. if (layoutMode) {
  29595. mergeLayoutParam(option, inputPositionParams, layoutMode);
  29596. }
  29597. },
  29598. /**
  29599. * @override
  29600. */
  29601. optionUpdated: function () {
  29602. var thisOption = this.option;
  29603. if (thisOption.type === 'category') {
  29604. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  29605. }
  29606. },
  29607. /**
  29608. * Should not be called before all of 'getInitailData' finished.
  29609. * Because categories are collected during initializing data.
  29610. */
  29611. getCategories: function () {
  29612. // FIXME
  29613. // warning if called before all of 'getInitailData' finished.
  29614. if (this.option.type === 'category') {
  29615. return this.__ordinalMeta.categories;
  29616. }
  29617. },
  29618. getOrdinalMeta: function () {
  29619. return this.__ordinalMeta;
  29620. },
  29621. defaultOption: mergeAll(
  29622. [
  29623. {},
  29624. axisDefault[axisType + 'Axis'],
  29625. extraDefaultOption
  29626. ],
  29627. true
  29628. )
  29629. });
  29630. });
  29631. ComponentModel.registerSubTypeDefaulter(
  29632. axisName + 'Axis',
  29633. curry(axisTypeDefaulter, axisName)
  29634. );
  29635. };
  29636. var AxisModel = ComponentModel.extend({
  29637. type: 'cartesian2dAxis',
  29638. /**
  29639. * @type {module:echarts/coord/cartesian/Axis2D}
  29640. */
  29641. axis: null,
  29642. /**
  29643. * @override
  29644. */
  29645. init: function () {
  29646. AxisModel.superApply(this, 'init', arguments);
  29647. this.resetRange();
  29648. },
  29649. /**
  29650. * @override
  29651. */
  29652. mergeOption: function () {
  29653. AxisModel.superApply(this, 'mergeOption', arguments);
  29654. this.resetRange();
  29655. },
  29656. /**
  29657. * @override
  29658. */
  29659. restoreData: function () {
  29660. AxisModel.superApply(this, 'restoreData', arguments);
  29661. this.resetRange();
  29662. },
  29663. /**
  29664. * @override
  29665. * @return {module:echarts/model/Component}
  29666. */
  29667. getCoordSysModel: function () {
  29668. return this.ecModel.queryComponents({
  29669. mainType: 'grid',
  29670. index: this.option.gridIndex,
  29671. id: this.option.gridId
  29672. })[0];
  29673. }
  29674. });
  29675. function getAxisType(axisDim, option) {
  29676. // Default axis with data is category axis
  29677. return option.type || (option.data ? 'category' : 'value');
  29678. }
  29679. merge(AxisModel.prototype, axisModelCommonMixin);
  29680. var extraOption = {
  29681. // gridIndex: 0,
  29682. // gridId: '',
  29683. // Offset is for multiple axis on the same position
  29684. offset: 0
  29685. };
  29686. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  29687. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  29688. // Grid 是在有直角坐标系的时候必须要存在的
  29689. // 所以这里也要被 Cartesian2D 依赖
  29690. ComponentModel.extend({
  29691. type: 'grid',
  29692. dependencies: ['xAxis', 'yAxis'],
  29693. layoutMode: 'box',
  29694. /**
  29695. * @type {module:echarts/coord/cartesian/Grid}
  29696. */
  29697. coordinateSystem: null,
  29698. defaultOption: {
  29699. show: false,
  29700. zlevel: 0,
  29701. z: 0,
  29702. left: '10%',
  29703. top: 60,
  29704. right: '10%',
  29705. bottom: 60,
  29706. // If grid size contain label
  29707. containLabel: false,
  29708. // width: {totalWidth} - left - right,
  29709. // height: {totalHeight} - top - bottom,
  29710. backgroundColor: 'rgba(0,0,0,0)',
  29711. borderWidth: 1,
  29712. borderColor: '#ccc'
  29713. }
  29714. });
  29715. /**
  29716. * Grid is a region which contains at most 4 cartesian systems
  29717. *
  29718. * TODO Default cartesian
  29719. */
  29720. // Depends on GridModel, AxisModel, which performs preprocess.
  29721. var each$6 = each$1;
  29722. var ifAxisCrossZero$1 = ifAxisCrossZero;
  29723. var niceScaleExtent$1 = niceScaleExtent;
  29724. /**
  29725. * Check if the axis is used in the specified grid
  29726. * @inner
  29727. */
  29728. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  29729. return axisModel.getCoordSysModel() === gridModel;
  29730. }
  29731. function rotateTextRect(textRect, rotate) {
  29732. var rotateRadians = rotate * Math.PI / 180;
  29733. var boundingBox = textRect.plain();
  29734. var beforeWidth = boundingBox.width;
  29735. var beforeHeight = boundingBox.height;
  29736. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  29737. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  29738. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  29739. return rotatedRect;
  29740. }
  29741. function getLabelUnionRect(axis) {
  29742. var axisModel = axis.model;
  29743. var labels = axisModel.get('axisLabel.show') ? axisModel.getFormattedLabels() : [];
  29744. var axisLabelModel = axisModel.getModel('axisLabel');
  29745. var rect;
  29746. var step = 1;
  29747. var labelCount = labels.length;
  29748. if (labelCount > 40) {
  29749. // Simple optimization for large amount of labels
  29750. step = Math.ceil(labelCount / 40);
  29751. }
  29752. for (var i = 0; i < labelCount; i += step) {
  29753. if (!axis.isLabelIgnored(i)) {
  29754. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  29755. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  29756. rect ? rect.union(singleRect) : (rect = singleRect);
  29757. }
  29758. }
  29759. return rect;
  29760. }
  29761. function Grid(gridModel, ecModel, api) {
  29762. /**
  29763. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  29764. * @private
  29765. */
  29766. this._coordsMap = {};
  29767. /**
  29768. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  29769. * @private
  29770. */
  29771. this._coordsList = [];
  29772. /**
  29773. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  29774. * @private
  29775. */
  29776. this._axesMap = {};
  29777. /**
  29778. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  29779. * @private
  29780. */
  29781. this._axesList = [];
  29782. this._initCartesian(gridModel, ecModel, api);
  29783. this.model = gridModel;
  29784. }
  29785. var gridProto = Grid.prototype;
  29786. gridProto.type = 'grid';
  29787. gridProto.axisPointerEnabled = true;
  29788. gridProto.getRect = function () {
  29789. return this._rect;
  29790. };
  29791. gridProto.update = function (ecModel, api) {
  29792. var axesMap = this._axesMap;
  29793. this._updateScale(ecModel, this.model);
  29794. each$6(axesMap.x, function (xAxis) {
  29795. niceScaleExtent$1(xAxis.scale, xAxis.model);
  29796. });
  29797. each$6(axesMap.y, function (yAxis) {
  29798. niceScaleExtent$1(yAxis.scale, yAxis.model);
  29799. });
  29800. each$6(axesMap.x, function (xAxis) {
  29801. fixAxisOnZero(axesMap, 'y', xAxis);
  29802. });
  29803. each$6(axesMap.y, function (yAxis) {
  29804. fixAxisOnZero(axesMap, 'x', yAxis);
  29805. });
  29806. // Resize again if containLabel is enabled
  29807. // FIXME It may cause getting wrong grid size in data processing stage
  29808. this.resize(this.model, api);
  29809. };
  29810. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  29811. // onZero can not be enabled in these two situations:
  29812. // 1. When any other axis is a category axis.
  29813. // 2. When no axis is cross 0 point.
  29814. var axes = axesMap[otherAxisDim];
  29815. if (!axis.onZero) {
  29816. return;
  29817. }
  29818. var onZeroAxisIndex = axis.onZeroAxisIndex;
  29819. // If target axis is specified.
  29820. if (onZeroAxisIndex != null) {
  29821. var otherAxis = axes[onZeroAxisIndex];
  29822. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  29823. axis.onZero = false;
  29824. }
  29825. return;
  29826. }
  29827. for (var idx in axes) {
  29828. if (axes.hasOwnProperty(idx)) {
  29829. var otherAxis = axes[idx];
  29830. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  29831. onZeroAxisIndex = +idx;
  29832. break;
  29833. }
  29834. }
  29835. }
  29836. if (onZeroAxisIndex == null) {
  29837. axis.onZero = false;
  29838. }
  29839. axis.onZeroAxisIndex = onZeroAxisIndex;
  29840. }
  29841. function canNotOnZeroToAxis(axis) {
  29842. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero$1(axis);
  29843. }
  29844. /**
  29845. * Resize the grid
  29846. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  29847. * @param {module:echarts/ExtensionAPI} api
  29848. */
  29849. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  29850. var gridRect = getLayoutRect(
  29851. gridModel.getBoxLayoutParams(), {
  29852. width: api.getWidth(),
  29853. height: api.getHeight()
  29854. });
  29855. this._rect = gridRect;
  29856. var axesList = this._axesList;
  29857. adjustAxes();
  29858. // Minus label size
  29859. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  29860. each$6(axesList, function (axis) {
  29861. if (!axis.model.get('axisLabel.inside')) {
  29862. var labelUnionRect = getLabelUnionRect(axis);
  29863. if (labelUnionRect) {
  29864. var dim = axis.isHorizontal() ? 'height' : 'width';
  29865. var margin = axis.model.get('axisLabel.margin');
  29866. gridRect[dim] -= labelUnionRect[dim] + margin;
  29867. if (axis.position === 'top') {
  29868. gridRect.y += labelUnionRect.height + margin;
  29869. }
  29870. else if (axis.position === 'left') {
  29871. gridRect.x += labelUnionRect.width + margin;
  29872. }
  29873. }
  29874. }
  29875. });
  29876. adjustAxes();
  29877. }
  29878. function adjustAxes() {
  29879. each$6(axesList, function (axis) {
  29880. var isHorizontal = axis.isHorizontal();
  29881. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  29882. var idx = axis.inverse ? 1 : 0;
  29883. axis.setExtent(extent[idx], extent[1 - idx]);
  29884. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  29885. });
  29886. }
  29887. };
  29888. /**
  29889. * @param {string} axisType
  29890. * @param {number} [axisIndex]
  29891. */
  29892. gridProto.getAxis = function (axisType, axisIndex) {
  29893. var axesMapOnDim = this._axesMap[axisType];
  29894. if (axesMapOnDim != null) {
  29895. if (axisIndex == null) {
  29896. // Find first axis
  29897. for (var name in axesMapOnDim) {
  29898. if (axesMapOnDim.hasOwnProperty(name)) {
  29899. return axesMapOnDim[name];
  29900. }
  29901. }
  29902. }
  29903. return axesMapOnDim[axisIndex];
  29904. }
  29905. };
  29906. /**
  29907. * @return {Array.<module:echarts/coord/Axis>}
  29908. */
  29909. gridProto.getAxes = function () {
  29910. return this._axesList.slice();
  29911. };
  29912. /**
  29913. * Usage:
  29914. * grid.getCartesian(xAxisIndex, yAxisIndex);
  29915. * grid.getCartesian(xAxisIndex);
  29916. * grid.getCartesian(null, yAxisIndex);
  29917. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  29918. *
  29919. * @param {number|Object} [xAxisIndex]
  29920. * @param {number} [yAxisIndex]
  29921. */
  29922. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  29923. if (xAxisIndex != null && yAxisIndex != null) {
  29924. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  29925. return this._coordsMap[key];
  29926. }
  29927. if (isObject$1(xAxisIndex)) {
  29928. yAxisIndex = xAxisIndex.yAxisIndex;
  29929. xAxisIndex = xAxisIndex.xAxisIndex;
  29930. }
  29931. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  29932. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  29933. if (coordList[i].getAxis('x').index === xAxisIndex
  29934. || coordList[i].getAxis('y').index === yAxisIndex
  29935. ) {
  29936. return coordList[i];
  29937. }
  29938. }
  29939. };
  29940. gridProto.getCartesians = function () {
  29941. return this._coordsList.slice();
  29942. };
  29943. /**
  29944. * @implements
  29945. * see {module:echarts/CoodinateSystem}
  29946. */
  29947. gridProto.convertToPixel = function (ecModel, finder, value) {
  29948. var target = this._findConvertTarget(ecModel, finder);
  29949. return target.cartesian
  29950. ? target.cartesian.dataToPoint(value)
  29951. : target.axis
  29952. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  29953. : null;
  29954. };
  29955. /**
  29956. * @implements
  29957. * see {module:echarts/CoodinateSystem}
  29958. */
  29959. gridProto.convertFromPixel = function (ecModel, finder, value) {
  29960. var target = this._findConvertTarget(ecModel, finder);
  29961. return target.cartesian
  29962. ? target.cartesian.pointToData(value)
  29963. : target.axis
  29964. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  29965. : null;
  29966. };
  29967. /**
  29968. * @inner
  29969. */
  29970. gridProto._findConvertTarget = function (ecModel, finder) {
  29971. var seriesModel = finder.seriesModel;
  29972. var xAxisModel = finder.xAxisModel
  29973. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  29974. var yAxisModel = finder.yAxisModel
  29975. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  29976. var gridModel = finder.gridModel;
  29977. var coordsList = this._coordsList;
  29978. var cartesian;
  29979. var axis;
  29980. if (seriesModel) {
  29981. cartesian = seriesModel.coordinateSystem;
  29982. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  29983. }
  29984. else if (xAxisModel && yAxisModel) {
  29985. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  29986. }
  29987. else if (xAxisModel) {
  29988. axis = this.getAxis('x', xAxisModel.componentIndex);
  29989. }
  29990. else if (yAxisModel) {
  29991. axis = this.getAxis('y', yAxisModel.componentIndex);
  29992. }
  29993. // Lowest priority.
  29994. else if (gridModel) {
  29995. var grid = gridModel.coordinateSystem;
  29996. if (grid === this) {
  29997. cartesian = this._coordsList[0];
  29998. }
  29999. }
  30000. return {cartesian: cartesian, axis: axis};
  30001. };
  30002. /**
  30003. * @implements
  30004. * see {module:echarts/CoodinateSystem}
  30005. */
  30006. gridProto.containPoint = function (point) {
  30007. var coord = this._coordsList[0];
  30008. if (coord) {
  30009. return coord.containPoint(point);
  30010. }
  30011. };
  30012. /**
  30013. * Initialize cartesian coordinate systems
  30014. * @private
  30015. */
  30016. gridProto._initCartesian = function (gridModel, ecModel, api) {
  30017. var axisPositionUsed = {
  30018. left: false,
  30019. right: false,
  30020. top: false,
  30021. bottom: false
  30022. };
  30023. var axesMap = {
  30024. x: {},
  30025. y: {}
  30026. };
  30027. var axesCount = {
  30028. x: 0,
  30029. y: 0
  30030. };
  30031. /// Create axis
  30032. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  30033. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  30034. if (!axesCount.x || !axesCount.y) {
  30035. // Roll back when there no either x or y axis
  30036. this._axesMap = {};
  30037. this._axesList = [];
  30038. return;
  30039. }
  30040. this._axesMap = axesMap;
  30041. /// Create cartesian2d
  30042. each$6(axesMap.x, function (xAxis, xAxisIndex) {
  30043. each$6(axesMap.y, function (yAxis, yAxisIndex) {
  30044. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  30045. var cartesian = new Cartesian2D(key);
  30046. cartesian.grid = this;
  30047. cartesian.model = gridModel;
  30048. this._coordsMap[key] = cartesian;
  30049. this._coordsList.push(cartesian);
  30050. cartesian.addAxis(xAxis);
  30051. cartesian.addAxis(yAxis);
  30052. }, this);
  30053. }, this);
  30054. function createAxisCreator(axisType) {
  30055. return function (axisModel, idx) {
  30056. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  30057. return;
  30058. }
  30059. var axisPosition = axisModel.get('position');
  30060. if (axisType === 'x') {
  30061. // Fix position
  30062. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  30063. // Default bottom of X
  30064. axisPosition = 'bottom';
  30065. if (axisPositionUsed[axisPosition]) {
  30066. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  30067. }
  30068. }
  30069. }
  30070. else {
  30071. // Fix position
  30072. if (axisPosition !== 'left' && axisPosition !== 'right') {
  30073. // Default left of Y
  30074. axisPosition = 'left';
  30075. if (axisPositionUsed[axisPosition]) {
  30076. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  30077. }
  30078. }
  30079. }
  30080. axisPositionUsed[axisPosition] = true;
  30081. var axis = new Axis2D(
  30082. axisType, createScaleByModel(axisModel),
  30083. [0, 0],
  30084. axisModel.get('type'),
  30085. axisPosition
  30086. );
  30087. var isCategory = axis.type === 'category';
  30088. axis.onBand = isCategory && axisModel.get('boundaryGap');
  30089. axis.inverse = axisModel.get('inverse');
  30090. axis.onZero = axisModel.get('axisLine.onZero');
  30091. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  30092. // Inject axis into axisModel
  30093. axisModel.axis = axis;
  30094. // Inject axisModel into axis
  30095. axis.model = axisModel;
  30096. // Inject grid info axis
  30097. axis.grid = this;
  30098. // Index of axis, can be used as key
  30099. axis.index = idx;
  30100. this._axesList.push(axis);
  30101. axesMap[axisType][idx] = axis;
  30102. axesCount[axisType]++;
  30103. };
  30104. }
  30105. };
  30106. /**
  30107. * Update cartesian properties from series
  30108. * @param {module:echarts/model/Option} option
  30109. * @private
  30110. */
  30111. gridProto._updateScale = function (ecModel, gridModel) {
  30112. // Reset scale
  30113. each$1(this._axesList, function (axis) {
  30114. axis.scale.setExtent(Infinity, -Infinity);
  30115. });
  30116. ecModel.eachSeries(function (seriesModel) {
  30117. if (isCartesian2D(seriesModel)) {
  30118. var axesModels = findAxesModels(seriesModel, ecModel);
  30119. var xAxisModel = axesModels[0];
  30120. var yAxisModel = axesModels[1];
  30121. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  30122. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  30123. ) {
  30124. return;
  30125. }
  30126. var cartesian = this.getCartesian(
  30127. xAxisModel.componentIndex, yAxisModel.componentIndex
  30128. );
  30129. var data = seriesModel.getData();
  30130. var xAxis = cartesian.getAxis('x');
  30131. var yAxis = cartesian.getAxis('y');
  30132. if (data.type === 'list') {
  30133. unionExtent(data, xAxis, seriesModel);
  30134. unionExtent(data, yAxis, seriesModel);
  30135. }
  30136. }
  30137. }, this);
  30138. function unionExtent(data, axis, seriesModel) {
  30139. each$6(data.mapDimension(axis.dim, true), function (dim) {
  30140. axis.scale.unionExtentFromData(data, dim);
  30141. });
  30142. }
  30143. };
  30144. /**
  30145. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  30146. * @return {Object} {baseAxes: [], otherAxes: []}
  30147. */
  30148. gridProto.getTooltipAxes = function (dim) {
  30149. var baseAxes = [];
  30150. var otherAxes = [];
  30151. each$6(this.getCartesians(), function (cartesian) {
  30152. var baseAxis = (dim != null && dim !== 'auto')
  30153. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  30154. var otherAxis = cartesian.getOtherAxis(baseAxis);
  30155. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  30156. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  30157. });
  30158. return {baseAxes: baseAxes, otherAxes: otherAxes};
  30159. };
  30160. /**
  30161. * @inner
  30162. */
  30163. function updateAxisTransform(axis, coordBase) {
  30164. var axisExtent = axis.getExtent();
  30165. var axisExtentSum = axisExtent[0] + axisExtent[1];
  30166. // Fast transform
  30167. axis.toGlobalCoord = axis.dim === 'x'
  30168. ? function (coord) {
  30169. return coord + coordBase;
  30170. }
  30171. : function (coord) {
  30172. return axisExtentSum - coord + coordBase;
  30173. };
  30174. axis.toLocalCoord = axis.dim === 'x'
  30175. ? function (coord) {
  30176. return coord - coordBase;
  30177. }
  30178. : function (coord) {
  30179. return axisExtentSum - coord + coordBase;
  30180. };
  30181. }
  30182. var axesTypes = ['xAxis', 'yAxis'];
  30183. /**
  30184. * @inner
  30185. */
  30186. function findAxesModels(seriesModel, ecModel) {
  30187. return map(axesTypes, function (axisType) {
  30188. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  30189. if (__DEV__) {
  30190. if (!axisModel) {
  30191. throw new Error(axisType + ' "' + retrieve(
  30192. seriesModel.get(axisType + 'Index'),
  30193. seriesModel.get(axisType + 'Id'),
  30194. 0
  30195. ) + '" not found');
  30196. }
  30197. }
  30198. return axisModel;
  30199. });
  30200. }
  30201. /**
  30202. * @inner
  30203. */
  30204. function isCartesian2D(seriesModel) {
  30205. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  30206. }
  30207. Grid.create = function (ecModel, api) {
  30208. var grids = [];
  30209. ecModel.eachComponent('grid', function (gridModel, idx) {
  30210. var grid = new Grid(gridModel, ecModel, api);
  30211. grid.name = 'grid_' + idx;
  30212. // dataSampling requires axis extent, so resize
  30213. // should be performed in create stage.
  30214. grid.resize(gridModel, api, true);
  30215. gridModel.coordinateSystem = grid;
  30216. grids.push(grid);
  30217. });
  30218. // Inject the coordinateSystems into seriesModel
  30219. ecModel.eachSeries(function (seriesModel) {
  30220. if (!isCartesian2D(seriesModel)) {
  30221. return;
  30222. }
  30223. var axesModels = findAxesModels(seriesModel, ecModel);
  30224. var xAxisModel = axesModels[0];
  30225. var yAxisModel = axesModels[1];
  30226. var gridModel = xAxisModel.getCoordSysModel();
  30227. if (__DEV__) {
  30228. if (!gridModel) {
  30229. throw new Error(
  30230. 'Grid "' + retrieve(
  30231. xAxisModel.get('gridIndex'),
  30232. xAxisModel.get('gridId'),
  30233. 0
  30234. ) + '" not found'
  30235. );
  30236. }
  30237. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  30238. throw new Error('xAxis and yAxis must use the same grid');
  30239. }
  30240. }
  30241. var grid = gridModel.coordinateSystem;
  30242. seriesModel.coordinateSystem = grid.getCartesian(
  30243. xAxisModel.componentIndex, yAxisModel.componentIndex
  30244. );
  30245. });
  30246. return grids;
  30247. };
  30248. // For deciding which dimensions to use when creating list data
  30249. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  30250. CoordinateSystemManager.register('cartesian2d', Grid);
  30251. var PI$2 = Math.PI;
  30252. function makeAxisEventDataBase(axisModel) {
  30253. var eventData = {
  30254. componentType: axisModel.mainType
  30255. };
  30256. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  30257. return eventData;
  30258. }
  30259. /**
  30260. * A final axis is translated and rotated from a "standard axis".
  30261. * So opt.position and opt.rotation is required.
  30262. *
  30263. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  30264. * for example: (0, 0) ------------> (0, 50)
  30265. *
  30266. * nameDirection or tickDirection or labelDirection is 1 means tick
  30267. * or label is below the standard axis, whereas is -1 means above
  30268. * the standard axis. labelOffset means offset between label and axis,
  30269. * which is useful when 'onZero', where axisLabel is in the grid and
  30270. * label in outside grid.
  30271. *
  30272. * Tips: like always,
  30273. * positive rotation represents anticlockwise, and negative rotation
  30274. * represents clockwise.
  30275. * The direction of position coordinate is the same as the direction
  30276. * of screen coordinate.
  30277. *
  30278. * Do not need to consider axis 'inverse', which is auto processed by
  30279. * axis extent.
  30280. *
  30281. * @param {module:zrender/container/Group} group
  30282. * @param {Object} axisModel
  30283. * @param {Object} opt Standard axis parameters.
  30284. * @param {Array.<number>} opt.position [x, y]
  30285. * @param {number} opt.rotation by radian
  30286. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  30287. * @param {number} [opt.tickDirection=1] 1 or -1
  30288. * @param {number} [opt.labelDirection=1] 1 or -1
  30289. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  30290. * @param {string} [opt.axisLabelShow] default get from axisModel.
  30291. * @param {string} [opt.axisName] default get from axisModel.
  30292. * @param {number} [opt.axisNameAvailableWidth]
  30293. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  30294. * @param {number} [opt.labelInterval] Default label interval when label
  30295. * interval from model is null or 'auto'.
  30296. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  30297. * @param {number} [opt.nameTruncateMaxWidth]
  30298. */
  30299. var AxisBuilder = function (axisModel, opt) {
  30300. /**
  30301. * @readOnly
  30302. */
  30303. this.opt = opt;
  30304. /**
  30305. * @readOnly
  30306. */
  30307. this.axisModel = axisModel;
  30308. // Default value
  30309. defaults(
  30310. opt,
  30311. {
  30312. labelOffset: 0,
  30313. nameDirection: 1,
  30314. tickDirection: 1,
  30315. labelDirection: 1,
  30316. silent: true
  30317. }
  30318. );
  30319. /**
  30320. * @readOnly
  30321. */
  30322. this.group = new Group();
  30323. // FIXME Not use a seperate text group?
  30324. var dumbGroup = new Group({
  30325. position: opt.position.slice(),
  30326. rotation: opt.rotation
  30327. });
  30328. // this.group.add(dumbGroup);
  30329. // this._dumbGroup = dumbGroup;
  30330. dumbGroup.updateTransform();
  30331. this._transform = dumbGroup.transform;
  30332. this._dumbGroup = dumbGroup;
  30333. };
  30334. AxisBuilder.prototype = {
  30335. constructor: AxisBuilder,
  30336. hasBuilder: function (name) {
  30337. return !!builders[name];
  30338. },
  30339. add: function (name) {
  30340. builders[name].call(this);
  30341. },
  30342. getGroup: function () {
  30343. return this.group;
  30344. }
  30345. };
  30346. var builders = {
  30347. /**
  30348. * @private
  30349. */
  30350. axisLine: function () {
  30351. var opt = this.opt;
  30352. var axisModel = this.axisModel;
  30353. if (!axisModel.get('axisLine.show')) {
  30354. return;
  30355. }
  30356. var extent = this.axisModel.axis.getExtent();
  30357. var matrix = this._transform;
  30358. var pt1 = [extent[0], 0];
  30359. var pt2 = [extent[1], 0];
  30360. if (matrix) {
  30361. applyTransform(pt1, pt1, matrix);
  30362. applyTransform(pt2, pt2, matrix);
  30363. }
  30364. var lineStyle = extend(
  30365. {
  30366. lineCap: 'round'
  30367. },
  30368. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  30369. );
  30370. this.group.add(new Line(subPixelOptimizeLine({
  30371. // Id for animation
  30372. anid: 'line',
  30373. shape: {
  30374. x1: pt1[0],
  30375. y1: pt1[1],
  30376. x2: pt2[0],
  30377. y2: pt2[1]
  30378. },
  30379. style: lineStyle,
  30380. strokeContainThreshold: opt.strokeContainThreshold || 5,
  30381. silent: true,
  30382. z2: 1
  30383. })));
  30384. var arrows = axisModel.get('axisLine.symbol');
  30385. var arrowSize = axisModel.get('axisLine.symbolSize');
  30386. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  30387. if (typeof arrowOffset === 'number') {
  30388. arrowOffset = [arrowOffset, arrowOffset];
  30389. }
  30390. if (arrows != null) {
  30391. if (typeof arrows === 'string') {
  30392. // Use the same arrow for start and end point
  30393. arrows = [arrows, arrows];
  30394. }
  30395. if (typeof arrowSize === 'string'
  30396. || typeof arrowSize === 'number'
  30397. ) {
  30398. // Use the same size for width and height
  30399. arrowSize = [arrowSize, arrowSize];
  30400. }
  30401. var symbolWidth = arrowSize[0];
  30402. var symbolHeight = arrowSize[1];
  30403. each$1([{
  30404. rotate: opt.rotation + Math.PI / 2,
  30405. offset: arrowOffset[0],
  30406. r: 0
  30407. }, {
  30408. rotate: opt.rotation - Math.PI / 2,
  30409. offset: arrowOffset[1],
  30410. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  30411. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  30412. }], function (point, index) {
  30413. if (arrows[index] !== 'none' && arrows[index] != null) {
  30414. var symbol = createSymbol(
  30415. arrows[index],
  30416. -symbolWidth / 2,
  30417. -symbolHeight / 2,
  30418. symbolWidth,
  30419. symbolHeight,
  30420. lineStyle.stroke,
  30421. true
  30422. );
  30423. // Calculate arrow position with offset
  30424. var r = point.r + point.offset;
  30425. var pos = [
  30426. pt1[0] + r * Math.cos(opt.rotation),
  30427. pt1[1] - r * Math.sin(opt.rotation)
  30428. ];
  30429. symbol.attr({
  30430. rotation: point.rotate,
  30431. position: pos,
  30432. silent: true
  30433. });
  30434. this.group.add(symbol);
  30435. }
  30436. }, this);
  30437. }
  30438. },
  30439. /**
  30440. * @private
  30441. */
  30442. axisTickLabel: function () {
  30443. var axisModel = this.axisModel;
  30444. var opt = this.opt;
  30445. var tickEls = buildAxisTick(this, axisModel, opt);
  30446. var labelEls = buildAxisLabel(this, axisModel, opt);
  30447. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  30448. },
  30449. /**
  30450. * @private
  30451. */
  30452. axisName: function () {
  30453. var opt = this.opt;
  30454. var axisModel = this.axisModel;
  30455. var name = retrieve(opt.axisName, axisModel.get('name'));
  30456. if (!name) {
  30457. return;
  30458. }
  30459. var nameLocation = axisModel.get('nameLocation');
  30460. var nameDirection = opt.nameDirection;
  30461. var textStyleModel = axisModel.getModel('nameTextStyle');
  30462. var gap = axisModel.get('nameGap') || 0;
  30463. var extent = this.axisModel.axis.getExtent();
  30464. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  30465. var pos = [
  30466. nameLocation === 'start'
  30467. ? extent[0] - gapSignal * gap
  30468. : nameLocation === 'end'
  30469. ? extent[1] + gapSignal * gap
  30470. : (extent[0] + extent[1]) / 2, // 'middle'
  30471. // Reuse labelOffset.
  30472. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  30473. ];
  30474. var labelLayout;
  30475. var nameRotation = axisModel.get('nameRotate');
  30476. if (nameRotation != null) {
  30477. nameRotation = nameRotation * PI$2 / 180; // To radian.
  30478. }
  30479. var axisNameAvailableWidth;
  30480. if (isNameLocationCenter(nameLocation)) {
  30481. labelLayout = innerTextLayout(
  30482. opt.rotation,
  30483. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  30484. nameDirection
  30485. );
  30486. }
  30487. else {
  30488. labelLayout = endTextLayout(
  30489. opt, nameLocation, nameRotation || 0, extent
  30490. );
  30491. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  30492. if (axisNameAvailableWidth != null) {
  30493. axisNameAvailableWidth = Math.abs(
  30494. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  30495. );
  30496. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  30497. }
  30498. }
  30499. var textFont = textStyleModel.getFont();
  30500. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  30501. var ellipsis = truncateOpt.ellipsis;
  30502. var maxWidth = retrieve(
  30503. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  30504. );
  30505. // FIXME
  30506. // truncate rich text? (consider performance)
  30507. var truncatedText = (ellipsis != null && maxWidth != null)
  30508. ? truncateText$1(
  30509. name, maxWidth, textFont, ellipsis,
  30510. {minChar: 2, placeholder: truncateOpt.placeholder}
  30511. )
  30512. : name;
  30513. var tooltipOpt = axisModel.get('tooltip', true);
  30514. var mainType = axisModel.mainType;
  30515. var formatterParams = {
  30516. componentType: mainType,
  30517. name: name,
  30518. $vars: ['name']
  30519. };
  30520. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  30521. var textEl = new Text({
  30522. // Id for animation
  30523. anid: 'name',
  30524. __fullText: name,
  30525. __truncatedText: truncatedText,
  30526. position: pos,
  30527. rotation: labelLayout.rotation,
  30528. silent: isSilent(axisModel),
  30529. z2: 1,
  30530. tooltip: (tooltipOpt && tooltipOpt.show)
  30531. ? extend({
  30532. content: name,
  30533. formatter: function () {
  30534. return name;
  30535. },
  30536. formatterParams: formatterParams
  30537. }, tooltipOpt)
  30538. : null
  30539. });
  30540. setTextStyle(textEl.style, textStyleModel, {
  30541. text: truncatedText,
  30542. textFont: textFont,
  30543. textFill: textStyleModel.getTextColor()
  30544. || axisModel.get('axisLine.lineStyle.color'),
  30545. textAlign: labelLayout.textAlign,
  30546. textVerticalAlign: labelLayout.textVerticalAlign
  30547. });
  30548. if (axisModel.get('triggerEvent')) {
  30549. textEl.eventData = makeAxisEventDataBase(axisModel);
  30550. textEl.eventData.targetType = 'axisName';
  30551. textEl.eventData.name = name;
  30552. }
  30553. // FIXME
  30554. this._dumbGroup.add(textEl);
  30555. textEl.updateTransform();
  30556. this.group.add(textEl);
  30557. textEl.decomposeTransform();
  30558. }
  30559. };
  30560. /**
  30561. * @public
  30562. * @static
  30563. * @param {Object} opt
  30564. * @param {number} axisRotation in radian
  30565. * @param {number} textRotation in radian
  30566. * @param {number} direction
  30567. * @return {Object} {
  30568. * rotation, // according to axis
  30569. * textAlign,
  30570. * textVerticalAlign
  30571. * }
  30572. */
  30573. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  30574. var rotationDiff = remRadian(textRotation - axisRotation);
  30575. var textAlign;
  30576. var textVerticalAlign;
  30577. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  30578. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  30579. textAlign = 'center';
  30580. }
  30581. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  30582. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  30583. textAlign = 'center';
  30584. }
  30585. else {
  30586. textVerticalAlign = 'middle';
  30587. if (rotationDiff > 0 && rotationDiff < PI$2) {
  30588. textAlign = direction > 0 ? 'right' : 'left';
  30589. }
  30590. else {
  30591. textAlign = direction > 0 ? 'left' : 'right';
  30592. }
  30593. }
  30594. return {
  30595. rotation: rotationDiff,
  30596. textAlign: textAlign,
  30597. textVerticalAlign: textVerticalAlign
  30598. };
  30599. };
  30600. function endTextLayout(opt, textPosition, textRotate, extent) {
  30601. var rotationDiff = remRadian(textRotate - opt.rotation);
  30602. var textAlign;
  30603. var textVerticalAlign;
  30604. var inverse = extent[0] > extent[1];
  30605. var onLeft = (textPosition === 'start' && !inverse)
  30606. || (textPosition !== 'start' && inverse);
  30607. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  30608. textVerticalAlign = onLeft ? 'bottom' : 'top';
  30609. textAlign = 'center';
  30610. }
  30611. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  30612. textVerticalAlign = onLeft ? 'top' : 'bottom';
  30613. textAlign = 'center';
  30614. }
  30615. else {
  30616. textVerticalAlign = 'middle';
  30617. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  30618. textAlign = onLeft ? 'left' : 'right';
  30619. }
  30620. else {
  30621. textAlign = onLeft ? 'right' : 'left';
  30622. }
  30623. }
  30624. return {
  30625. rotation: rotationDiff,
  30626. textAlign: textAlign,
  30627. textVerticalAlign: textVerticalAlign
  30628. };
  30629. }
  30630. function isSilent(axisModel) {
  30631. var tooltipOpt = axisModel.get('tooltip');
  30632. return axisModel.get('silent')
  30633. // Consider mouse cursor, add these restrictions.
  30634. || !(
  30635. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  30636. );
  30637. }
  30638. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  30639. // If min or max are user set, we need to check
  30640. // If the tick on min(max) are overlap on their neighbour tick
  30641. // If they are overlapped, we need to hide the min(max) tick label
  30642. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30643. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30644. // FIXME
  30645. // Have not consider onBand yet, where tick els is more than label els.
  30646. labelEls = labelEls || [];
  30647. tickEls = tickEls || [];
  30648. var firstLabel = labelEls[0];
  30649. var nextLabel = labelEls[1];
  30650. var lastLabel = labelEls[labelEls.length - 1];
  30651. var prevLabel = labelEls[labelEls.length - 2];
  30652. var firstTick = tickEls[0];
  30653. var nextTick = tickEls[1];
  30654. var lastTick = tickEls[tickEls.length - 1];
  30655. var prevTick = tickEls[tickEls.length - 2];
  30656. if (showMinLabel === false) {
  30657. ignoreEl(firstLabel);
  30658. ignoreEl(firstTick);
  30659. }
  30660. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  30661. if (showMinLabel) {
  30662. ignoreEl(nextLabel);
  30663. ignoreEl(nextTick);
  30664. }
  30665. else {
  30666. ignoreEl(firstLabel);
  30667. ignoreEl(firstTick);
  30668. }
  30669. }
  30670. if (showMaxLabel === false) {
  30671. ignoreEl(lastLabel);
  30672. ignoreEl(lastTick);
  30673. }
  30674. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  30675. if (showMaxLabel) {
  30676. ignoreEl(prevLabel);
  30677. ignoreEl(prevTick);
  30678. }
  30679. else {
  30680. ignoreEl(lastLabel);
  30681. ignoreEl(lastTick);
  30682. }
  30683. }
  30684. }
  30685. function ignoreEl(el) {
  30686. el && (el.ignore = true);
  30687. }
  30688. function isTwoLabelOverlapped(current, next, labelLayout) {
  30689. // current and next has the same rotation.
  30690. var firstRect = current && current.getBoundingRect().clone();
  30691. var nextRect = next && next.getBoundingRect().clone();
  30692. if (!firstRect || !nextRect) {
  30693. return;
  30694. }
  30695. // When checking intersect of two rotated labels, we use mRotationBack
  30696. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  30697. var mRotationBack = identity([]);
  30698. rotate(mRotationBack, mRotationBack, -current.rotation);
  30699. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  30700. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  30701. return firstRect.intersect(nextRect);
  30702. }
  30703. function isNameLocationCenter(nameLocation) {
  30704. return nameLocation === 'middle' || nameLocation === 'center';
  30705. }
  30706. /**
  30707. * @static
  30708. */
  30709. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  30710. axis,
  30711. i,
  30712. interval,
  30713. ticksCnt,
  30714. showMinLabel,
  30715. showMaxLabel
  30716. ) {
  30717. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  30718. return false;
  30719. }
  30720. // FIXME
  30721. // Have not consider label overlap (if label is too long) yet.
  30722. var rawTick;
  30723. var scale$$1 = axis.scale;
  30724. return scale$$1.type === 'ordinal'
  30725. && (
  30726. typeof interval === 'function'
  30727. ? (
  30728. rawTick = scale$$1.getTicks()[i],
  30729. !interval(rawTick, scale$$1.getLabel(rawTick))
  30730. )
  30731. : i % (interval + 1)
  30732. );
  30733. };
  30734. /**
  30735. * @static
  30736. */
  30737. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  30738. var interval = model.get('interval');
  30739. if (interval == null || interval == 'auto') {
  30740. interval = labelInterval;
  30741. }
  30742. return interval;
  30743. };
  30744. function buildAxisTick(axisBuilder, axisModel, opt) {
  30745. var axis = axisModel.axis;
  30746. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  30747. return;
  30748. }
  30749. var tickModel = axisModel.getModel('axisTick');
  30750. var lineStyleModel = tickModel.getModel('lineStyle');
  30751. var tickLen = tickModel.get('length');
  30752. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  30753. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  30754. // FIXME
  30755. // Corresponds to ticksCoords ?
  30756. var ticks = axis.scale.getTicks();
  30757. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30758. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30759. var pt1 = [];
  30760. var pt2 = [];
  30761. var matrix = axisBuilder._transform;
  30762. var tickEls = [];
  30763. var ticksCnt = ticksCoords.length;
  30764. for (var i = 0; i < ticksCnt; i++) {
  30765. // Only ordinal scale support tick interval
  30766. if (ifIgnoreOnTick$1(
  30767. axis, i, tickInterval, ticksCnt,
  30768. showMinLabel, showMaxLabel
  30769. )) {
  30770. continue;
  30771. }
  30772. var tickCoord = ticksCoords[i];
  30773. pt1[0] = tickCoord;
  30774. pt1[1] = 0;
  30775. pt2[0] = tickCoord;
  30776. pt2[1] = opt.tickDirection * tickLen;
  30777. if (matrix) {
  30778. applyTransform(pt1, pt1, matrix);
  30779. applyTransform(pt2, pt2, matrix);
  30780. }
  30781. // Tick line, Not use group transform to have better line draw
  30782. var tickEl = new Line(subPixelOptimizeLine({
  30783. // Id for animation
  30784. anid: 'tick_' + ticks[i],
  30785. shape: {
  30786. x1: pt1[0],
  30787. y1: pt1[1],
  30788. x2: pt2[0],
  30789. y2: pt2[1]
  30790. },
  30791. style: defaults(
  30792. lineStyleModel.getLineStyle(),
  30793. {
  30794. stroke: axisModel.get('axisLine.lineStyle.color')
  30795. }
  30796. ),
  30797. z2: 2,
  30798. silent: true
  30799. }));
  30800. axisBuilder.group.add(tickEl);
  30801. tickEls.push(tickEl);
  30802. }
  30803. return tickEls;
  30804. }
  30805. function buildAxisLabel(axisBuilder, axisModel, opt) {
  30806. var axis = axisModel.axis;
  30807. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  30808. if (!show || axis.scale.isBlank()) {
  30809. return;
  30810. }
  30811. var labelModel = axisModel.getModel('axisLabel');
  30812. var labelMargin = labelModel.get('margin');
  30813. var ticks = axis.scale.getTicks();
  30814. var labels = axisModel.getFormattedLabels();
  30815. // Special label rotate.
  30816. var labelRotation = (
  30817. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  30818. ) * PI$2 / 180;
  30819. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  30820. var categoryData = axisModel.getCategories();
  30821. var labelEls = [];
  30822. var silent = isSilent(axisModel);
  30823. var triggerEvent = axisModel.get('triggerEvent');
  30824. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  30825. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  30826. each$1(ticks, function (tickVal, index) {
  30827. if (ifIgnoreOnTick$1(
  30828. axis, index, opt.labelInterval, ticks.length,
  30829. showMinLabel, showMaxLabel
  30830. )) {
  30831. return;
  30832. }
  30833. var itemLabelModel = labelModel;
  30834. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  30835. itemLabelModel = new Model(
  30836. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  30837. );
  30838. }
  30839. var textColor = itemLabelModel.getTextColor()
  30840. || axisModel.get('axisLine.lineStyle.color');
  30841. var tickCoord = axis.dataToCoord(tickVal);
  30842. var pos = [
  30843. tickCoord,
  30844. opt.labelOffset + opt.labelDirection * labelMargin
  30845. ];
  30846. var labelStr = axis.scale.getLabel(tickVal);
  30847. var textEl = new Text({
  30848. // Id for animation
  30849. anid: 'label_' + tickVal,
  30850. position: pos,
  30851. rotation: labelLayout.rotation,
  30852. silent: silent,
  30853. z2: 10
  30854. });
  30855. setTextStyle(textEl.style, itemLabelModel, {
  30856. text: labels[index],
  30857. textAlign: itemLabelModel.getShallow('align', true)
  30858. || labelLayout.textAlign,
  30859. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  30860. || itemLabelModel.getShallow('baseline', true)
  30861. || labelLayout.textVerticalAlign,
  30862. textFill: typeof textColor === 'function'
  30863. ? textColor(
  30864. // (1) In category axis with data zoom, tick is not the original
  30865. // index of axis.data. So tick should not be exposed to user
  30866. // in category axis.
  30867. // (2) Compatible with previous version, which always returns labelStr.
  30868. // But in interval scale labelStr is like '223,445', which maked
  30869. // user repalce ','. So we modify it to return original val but remain
  30870. // it as 'string' to avoid error in replacing.
  30871. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  30872. index
  30873. )
  30874. : textColor
  30875. });
  30876. // Pack data for mouse event
  30877. if (triggerEvent) {
  30878. textEl.eventData = makeAxisEventDataBase(axisModel);
  30879. textEl.eventData.targetType = 'axisLabel';
  30880. textEl.eventData.value = labelStr;
  30881. }
  30882. // FIXME
  30883. axisBuilder._dumbGroup.add(textEl);
  30884. textEl.updateTransform();
  30885. labelEls.push(textEl);
  30886. axisBuilder.group.add(textEl);
  30887. textEl.decomposeTransform();
  30888. });
  30889. return labelEls;
  30890. }
  30891. var each$7 = each$1;
  30892. var curry$1 = curry;
  30893. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  30894. // allAxesInfo should be updated when setOption performed.
  30895. function collect(ecModel, api) {
  30896. var result = {
  30897. /**
  30898. * key: makeKey(axis.model)
  30899. * value: {
  30900. * axis,
  30901. * coordSys,
  30902. * axisPointerModel,
  30903. * triggerTooltip,
  30904. * involveSeries,
  30905. * snap,
  30906. * seriesModels,
  30907. * seriesDataCount
  30908. * }
  30909. */
  30910. axesInfo: {},
  30911. seriesInvolved: false,
  30912. /**
  30913. * key: makeKey(coordSys.model)
  30914. * value: Object: key makeKey(axis.model), value: axisInfo
  30915. */
  30916. coordSysAxesInfo: {},
  30917. coordSysMap: {}
  30918. };
  30919. collectAxesInfo(result, ecModel, api);
  30920. // Check seriesInvolved for performance, in case too many series in some chart.
  30921. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  30922. return result;
  30923. }
  30924. function collectAxesInfo(result, ecModel, api) {
  30925. var globalTooltipModel = ecModel.getComponent('tooltip');
  30926. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  30927. // links can only be set on global.
  30928. var linksOption = globalAxisPointerModel.get('link', true) || [];
  30929. var linkGroups = [];
  30930. // Collect axes info.
  30931. each$7(api.getCoordinateSystems(), function (coordSys) {
  30932. // Some coordinate system do not support axes, like geo.
  30933. if (!coordSys.axisPointerEnabled) {
  30934. return;
  30935. }
  30936. var coordSysKey = makeKey(coordSys.model);
  30937. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  30938. result.coordSysMap[coordSysKey] = coordSys;
  30939. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  30940. // for user. So we enable seting tooltip on coordSys model.
  30941. var coordSysModel = coordSys.model;
  30942. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  30943. each$7(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  30944. // If axis tooltip used, choose tooltip axis for each coordSys.
  30945. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  30946. if (coordSys.getTooltipAxes
  30947. && globalTooltipModel
  30948. // If tooltip.showContent is set as false, tooltip will not
  30949. // show but axisPointer will show as normal.
  30950. && baseTooltipModel.get('show')
  30951. ) {
  30952. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  30953. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  30954. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  30955. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  30956. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  30957. if (triggerAxis || cross) {
  30958. each$7(tooltipAxes.baseAxes, curry$1(
  30959. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  30960. ));
  30961. }
  30962. if (cross) {
  30963. each$7(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  30964. }
  30965. }
  30966. // fromTooltip: true | false | 'cross'
  30967. // triggerTooltip: true | false | null
  30968. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  30969. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  30970. var axisPointerShow = axisPointerModel.get('show');
  30971. if (!axisPointerShow || (
  30972. axisPointerShow === 'auto'
  30973. && !fromTooltip
  30974. && !isHandleTrigger(axisPointerModel)
  30975. )) {
  30976. return;
  30977. }
  30978. if (triggerTooltip == null) {
  30979. triggerTooltip = axisPointerModel.get('triggerTooltip');
  30980. }
  30981. axisPointerModel = fromTooltip
  30982. ? makeAxisPointerModel(
  30983. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  30984. fromTooltip, triggerTooltip
  30985. )
  30986. : axisPointerModel;
  30987. var snap = axisPointerModel.get('snap');
  30988. var key = makeKey(axis.model);
  30989. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  30990. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  30991. var axisInfo = result.axesInfo[key] = {
  30992. key: key,
  30993. axis: axis,
  30994. coordSys: coordSys,
  30995. axisPointerModel: axisPointerModel,
  30996. triggerTooltip: triggerTooltip,
  30997. involveSeries: involveSeries,
  30998. snap: snap,
  30999. useHandle: isHandleTrigger(axisPointerModel),
  31000. seriesModels: []
  31001. };
  31002. axesInfoInCoordSys[key] = axisInfo;
  31003. result.seriesInvolved |= involveSeries;
  31004. var groupIndex = getLinkGroupIndex(linksOption, axis);
  31005. if (groupIndex != null) {
  31006. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  31007. linkGroup.axesInfo[key] = axisInfo;
  31008. linkGroup.mapper = linksOption[groupIndex].mapper;
  31009. axisInfo.linkGroup = linkGroup;
  31010. }
  31011. }
  31012. });
  31013. }
  31014. function makeAxisPointerModel(
  31015. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  31016. ) {
  31017. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  31018. var volatileOption = {};
  31019. each$7(
  31020. [
  31021. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  31022. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  31023. ],
  31024. function (field) {
  31025. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  31026. }
  31027. );
  31028. // category axis do not auto snap, otherwise some tick that do not
  31029. // has value can not be hovered. value/time/log axis default snap if
  31030. // triggered from tooltip and trigger tooltip.
  31031. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  31032. // Compatibel with previous behavior, tooltip axis do not show label by default.
  31033. // Only these properties can be overrided from tooltip to axisPointer.
  31034. if (tooltipAxisPointerModel.get('type') === 'cross') {
  31035. volatileOption.type = 'line';
  31036. }
  31037. var labelOption = volatileOption.label || (volatileOption.label = {});
  31038. // Follow the convention, do not show label when triggered by tooltip by default.
  31039. labelOption.show == null && (labelOption.show = false);
  31040. if (fromTooltip === 'cross') {
  31041. // When 'cross', both axes show labels.
  31042. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  31043. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  31044. // If triggerTooltip, this is a base axis, which should better not use cross style
  31045. // (cross style is dashed by default)
  31046. if (!triggerTooltip) {
  31047. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  31048. crossStyle && defaults(labelOption, crossStyle.textStyle);
  31049. }
  31050. }
  31051. return axis.model.getModel(
  31052. 'axisPointer',
  31053. new Model(volatileOption, globalAxisPointerModel, ecModel)
  31054. );
  31055. }
  31056. function collectSeriesInfo(result, ecModel) {
  31057. // Prepare data for axis trigger
  31058. ecModel.eachSeries(function (seriesModel) {
  31059. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  31060. var coordSys = seriesModel.coordinateSystem;
  31061. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  31062. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  31063. if (!coordSys
  31064. || seriesTooltipTrigger === 'none'
  31065. || seriesTooltipTrigger === false
  31066. || seriesTooltipTrigger === 'item'
  31067. || seriesTooltipShow === false
  31068. || seriesModel.get('axisPointer.show', true) === false
  31069. ) {
  31070. return;
  31071. }
  31072. each$7(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  31073. var axis = axisInfo.axis;
  31074. if (coordSys.getAxis(axis.dim) === axis) {
  31075. axisInfo.seriesModels.push(seriesModel);
  31076. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  31077. axisInfo.seriesDataCount += seriesModel.getData().count();
  31078. }
  31079. });
  31080. }, this);
  31081. }
  31082. /**
  31083. * For example:
  31084. * {
  31085. * axisPointer: {
  31086. * links: [{
  31087. * xAxisIndex: [2, 4],
  31088. * yAxisIndex: 'all'
  31089. * }, {
  31090. * xAxisId: ['a5', 'a7'],
  31091. * xAxisName: 'xxx'
  31092. * }]
  31093. * }
  31094. * }
  31095. */
  31096. function getLinkGroupIndex(linksOption, axis) {
  31097. var axisModel = axis.model;
  31098. var dim = axis.dim;
  31099. for (var i = 0; i < linksOption.length; i++) {
  31100. var linkOption = linksOption[i] || {};
  31101. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  31102. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  31103. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  31104. ) {
  31105. return i;
  31106. }
  31107. }
  31108. }
  31109. function checkPropInLink(linkPropValue, axisPropValue) {
  31110. return linkPropValue === 'all'
  31111. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  31112. || linkPropValue === axisPropValue;
  31113. }
  31114. function fixValue(axisModel) {
  31115. var axisInfo = getAxisInfo(axisModel);
  31116. if (!axisInfo) {
  31117. return;
  31118. }
  31119. var axisPointerModel = axisInfo.axisPointerModel;
  31120. var scale = axisInfo.axis.scale;
  31121. var option = axisPointerModel.option;
  31122. var status = axisPointerModel.get('status');
  31123. var value = axisPointerModel.get('value');
  31124. // Parse init value for category and time axis.
  31125. if (value != null) {
  31126. value = scale.parse(value);
  31127. }
  31128. var useHandle = isHandleTrigger(axisPointerModel);
  31129. // If `handle` used, `axisPointer` will always be displayed, so value
  31130. // and status should be initialized.
  31131. if (status == null) {
  31132. option.status = useHandle ? 'show' : 'hide';
  31133. }
  31134. var extent = scale.getExtent().slice();
  31135. extent[0] > extent[1] && extent.reverse();
  31136. if (// Pick a value on axis when initializing.
  31137. value == null
  31138. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  31139. // where we should re-pick a value to keep `handle` displaying normally.
  31140. || value > extent[1]
  31141. ) {
  31142. // Make handle displayed on the end of the axis when init, which looks better.
  31143. value = extent[1];
  31144. }
  31145. if (value < extent[0]) {
  31146. value = extent[0];
  31147. }
  31148. option.value = value;
  31149. if (useHandle) {
  31150. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  31151. }
  31152. }
  31153. function getAxisInfo(axisModel) {
  31154. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  31155. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  31156. }
  31157. function getAxisPointerModel(axisModel) {
  31158. var axisInfo = getAxisInfo(axisModel);
  31159. return axisInfo && axisInfo.axisPointerModel;
  31160. }
  31161. function isHandleTrigger(axisPointerModel) {
  31162. return !!axisPointerModel.get('handle.show');
  31163. }
  31164. /**
  31165. * @param {module:echarts/model/Model} model
  31166. * @return {string} unique key
  31167. */
  31168. function makeKey(model) {
  31169. return model.type + '||' + model.id;
  31170. }
  31171. /**
  31172. * Base class of AxisView.
  31173. */
  31174. var AxisView = extendComponentView({
  31175. type: 'axis',
  31176. /**
  31177. * @private
  31178. */
  31179. _axisPointer: null,
  31180. /**
  31181. * @protected
  31182. * @type {string}
  31183. */
  31184. axisPointerClass: null,
  31185. /**
  31186. * @override
  31187. */
  31188. render: function (axisModel, ecModel, api, payload) {
  31189. // FIXME
  31190. // This process should proformed after coordinate systems updated
  31191. // (axis scale updated), and should be performed each time update.
  31192. // So put it here temporarily, although it is not appropriate to
  31193. // put a model-writing procedure in `view`.
  31194. this.axisPointerClass && fixValue(axisModel);
  31195. AxisView.superApply(this, 'render', arguments);
  31196. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  31197. },
  31198. /**
  31199. * Action handler.
  31200. * @public
  31201. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31202. * @param {module:echarts/model/Global} ecModel
  31203. * @param {module:echarts/ExtensionAPI} api
  31204. * @param {Object} payload
  31205. */
  31206. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  31207. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  31208. },
  31209. /**
  31210. * @override
  31211. */
  31212. remove: function (ecModel, api) {
  31213. var axisPointer = this._axisPointer;
  31214. axisPointer && axisPointer.remove(api);
  31215. AxisView.superApply(this, 'remove', arguments);
  31216. },
  31217. /**
  31218. * @override
  31219. */
  31220. dispose: function (ecModel, api) {
  31221. disposeAxisPointer(this, api);
  31222. AxisView.superApply(this, 'dispose', arguments);
  31223. }
  31224. });
  31225. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  31226. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  31227. if (!Clazz) {
  31228. return;
  31229. }
  31230. var axisPointerModel = getAxisPointerModel(axisModel);
  31231. axisPointerModel
  31232. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  31233. .render(axisModel, axisPointerModel, api, forceRender)
  31234. : disposeAxisPointer(axisView, api);
  31235. }
  31236. function disposeAxisPointer(axisView, ecModel, api) {
  31237. var axisPointer = axisView._axisPointer;
  31238. axisPointer && axisPointer.dispose(ecModel, api);
  31239. axisView._axisPointer = null;
  31240. }
  31241. var axisPointerClazz = [];
  31242. AxisView.registerAxisPointerClass = function (type, clazz) {
  31243. if (__DEV__) {
  31244. if (axisPointerClazz[type]) {
  31245. throw new Error('axisPointer ' + type + ' exists');
  31246. }
  31247. }
  31248. axisPointerClazz[type] = clazz;
  31249. };
  31250. AxisView.getAxisPointerClass = function (type) {
  31251. return type && axisPointerClazz[type];
  31252. };
  31253. /**
  31254. * @param {Object} opt {labelInside}
  31255. * @return {Object} {
  31256. * position, rotation, labelDirection, labelOffset,
  31257. * tickDirection, labelRotate, labelInterval, z2
  31258. * }
  31259. */
  31260. function layout$1(gridModel, axisModel, opt) {
  31261. opt = opt || {};
  31262. var grid = gridModel.coordinateSystem;
  31263. var axis = axisModel.axis;
  31264. var layout = {};
  31265. var rawAxisPosition = axis.position;
  31266. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  31267. var axisDim = axis.dim;
  31268. var rect = grid.getRect();
  31269. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  31270. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  31271. var axisOffset = axisModel.get('offset') || 0;
  31272. var posBound = axisDim === 'x'
  31273. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  31274. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  31275. if (axis.onZero) {
  31276. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  31277. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  31278. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  31279. }
  31280. // Axis position
  31281. layout.position = [
  31282. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  31283. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  31284. ];
  31285. // Axis rotation
  31286. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  31287. // Tick and label direction, x y is axisDim
  31288. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  31289. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  31290. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  31291. if (axisModel.get('axisTick.inside')) {
  31292. layout.tickDirection = -layout.tickDirection;
  31293. }
  31294. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  31295. layout.labelDirection = -layout.labelDirection;
  31296. }
  31297. // Special label rotation
  31298. var labelRotate = axisModel.get('axisLabel.rotate');
  31299. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  31300. // label interval when auto mode.
  31301. layout.labelInterval = axis.getLabelInterval();
  31302. // Over splitLine and splitArea
  31303. layout.z2 = 1;
  31304. return layout;
  31305. }
  31306. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  31307. var getInterval = AxisBuilder.getInterval;
  31308. var axisBuilderAttrs = [
  31309. 'axisLine', 'axisTickLabel', 'axisName'
  31310. ];
  31311. var selfBuilderAttrs = [
  31312. 'splitArea', 'splitLine'
  31313. ];
  31314. // function getAlignWithLabel(model, axisModel) {
  31315. // var alignWithLabel = model.get('alignWithLabel');
  31316. // if (alignWithLabel === 'auto') {
  31317. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  31318. // }
  31319. // return alignWithLabel;
  31320. // }
  31321. var CartesianAxisView = AxisView.extend({
  31322. type: 'cartesianAxis',
  31323. axisPointerClass: 'CartesianAxisPointer',
  31324. /**
  31325. * @override
  31326. */
  31327. render: function (axisModel, ecModel, api, payload) {
  31328. this.group.removeAll();
  31329. var oldAxisGroup = this._axisGroup;
  31330. this._axisGroup = new Group();
  31331. this.group.add(this._axisGroup);
  31332. if (!axisModel.get('show')) {
  31333. return;
  31334. }
  31335. var gridModel = axisModel.getCoordSysModel();
  31336. var layout = layout$1(gridModel, axisModel);
  31337. var axisBuilder = new AxisBuilder(axisModel, layout);
  31338. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  31339. this._axisGroup.add(axisBuilder.getGroup());
  31340. each$1(selfBuilderAttrs, function (name) {
  31341. if (axisModel.get(name + '.show')) {
  31342. this['_' + name](axisModel, gridModel, layout.labelInterval);
  31343. }
  31344. }, this);
  31345. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  31346. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  31347. },
  31348. /**
  31349. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31350. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  31351. * @param {number|Function} labelInterval
  31352. * @private
  31353. */
  31354. _splitLine: function (axisModel, gridModel, labelInterval) {
  31355. var axis = axisModel.axis;
  31356. if (axis.scale.isBlank()) {
  31357. return;
  31358. }
  31359. var splitLineModel = axisModel.getModel('splitLine');
  31360. var lineStyleModel = splitLineModel.getModel('lineStyle');
  31361. var lineColors = lineStyleModel.get('color');
  31362. var lineInterval = getInterval(splitLineModel, labelInterval);
  31363. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  31364. var gridRect = gridModel.coordinateSystem.getRect();
  31365. var isHorizontal = axis.isHorizontal();
  31366. var lineCount = 0;
  31367. var ticksCoords = axis.getTicksCoords(
  31368. // splitLineModel.get('alignWithLabel')
  31369. );
  31370. var ticks = axis.scale.getTicks();
  31371. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  31372. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  31373. var p1 = [];
  31374. var p2 = [];
  31375. // Simple optimization
  31376. // Batching the lines if color are the same
  31377. var lineStyle = lineStyleModel.getLineStyle();
  31378. for (var i = 0; i < ticksCoords.length; i++) {
  31379. if (ifIgnoreOnTick(
  31380. axis, i, lineInterval, ticksCoords.length,
  31381. showMinLabel, showMaxLabel
  31382. )) {
  31383. continue;
  31384. }
  31385. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  31386. if (isHorizontal) {
  31387. p1[0] = tickCoord;
  31388. p1[1] = gridRect.y;
  31389. p2[0] = tickCoord;
  31390. p2[1] = gridRect.y + gridRect.height;
  31391. }
  31392. else {
  31393. p1[0] = gridRect.x;
  31394. p1[1] = tickCoord;
  31395. p2[0] = gridRect.x + gridRect.width;
  31396. p2[1] = tickCoord;
  31397. }
  31398. var colorIndex = (lineCount++) % lineColors.length;
  31399. this._axisGroup.add(new Line(subPixelOptimizeLine({
  31400. anid: 'line_' + ticks[i],
  31401. shape: {
  31402. x1: p1[0],
  31403. y1: p1[1],
  31404. x2: p2[0],
  31405. y2: p2[1]
  31406. },
  31407. style: defaults({
  31408. stroke: lineColors[colorIndex]
  31409. }, lineStyle),
  31410. silent: true
  31411. })));
  31412. }
  31413. },
  31414. /**
  31415. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  31416. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  31417. * @param {number|Function} labelInterval
  31418. * @private
  31419. */
  31420. _splitArea: function (axisModel, gridModel, labelInterval) {
  31421. var axis = axisModel.axis;
  31422. if (axis.scale.isBlank()) {
  31423. return;
  31424. }
  31425. var splitAreaModel = axisModel.getModel('splitArea');
  31426. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  31427. var areaColors = areaStyleModel.get('color');
  31428. var gridRect = gridModel.coordinateSystem.getRect();
  31429. var ticksCoords = axis.getTicksCoords(
  31430. // splitAreaModel.get('alignWithLabel')
  31431. );
  31432. var ticks = axis.scale.getTicks();
  31433. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  31434. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  31435. var count = 0;
  31436. var areaInterval = getInterval(splitAreaModel, labelInterval);
  31437. var areaStyle = areaStyleModel.getAreaStyle();
  31438. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  31439. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  31440. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  31441. for (var i = 1; i < ticksCoords.length; i++) {
  31442. if (ifIgnoreOnTick(
  31443. axis, i, areaInterval, ticksCoords.length,
  31444. showMinLabel, showMaxLabel
  31445. ) && (i < ticksCoords.length - 1)) {
  31446. continue;
  31447. }
  31448. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  31449. var x;
  31450. var y;
  31451. var width;
  31452. var height;
  31453. if (axis.isHorizontal()) {
  31454. x = prevX;
  31455. y = gridRect.y;
  31456. width = tickCoord - x;
  31457. height = gridRect.height;
  31458. }
  31459. else {
  31460. x = gridRect.x;
  31461. y = prevY;
  31462. width = gridRect.width;
  31463. height = tickCoord - y;
  31464. }
  31465. var colorIndex = (count++) % areaColors.length;
  31466. this._axisGroup.add(new Rect({
  31467. anid: 'area_' + ticks[i],
  31468. shape: {
  31469. x: x,
  31470. y: y,
  31471. width: width,
  31472. height: height
  31473. },
  31474. style: defaults({
  31475. fill: areaColors[colorIndex]
  31476. }, areaStyle),
  31477. silent: true
  31478. }));
  31479. prevX = x + width;
  31480. prevY = y + height;
  31481. }
  31482. }
  31483. });
  31484. CartesianAxisView.extend({
  31485. type: 'xAxis'
  31486. });
  31487. CartesianAxisView.extend({
  31488. type: 'yAxis'
  31489. });
  31490. // Grid view
  31491. extendComponentView({
  31492. type: 'grid',
  31493. render: function (gridModel, ecModel) {
  31494. this.group.removeAll();
  31495. if (gridModel.get('show')) {
  31496. this.group.add(new Rect({
  31497. shape: gridModel.coordinateSystem.getRect(),
  31498. style: defaults({
  31499. fill: gridModel.get('backgroundColor')
  31500. }, gridModel.getItemStyle()),
  31501. silent: true,
  31502. z2: -1
  31503. }));
  31504. }
  31505. }
  31506. });
  31507. registerPreprocessor(function (option) {
  31508. // Only create grid when need
  31509. if (option.xAxis && option.yAxis && !option.grid) {
  31510. option.grid = {};
  31511. }
  31512. });
  31513. // In case developer forget to include grid component
  31514. registerVisual(visualSymbol('line', 'circle', 'line'));
  31515. registerLayout(pointsLayout('line'));
  31516. // Down sample after filter
  31517. registerProcessor(
  31518. PRIORITY.PROCESSOR.STATISTIC,
  31519. dataSample('line')
  31520. );
  31521. var BaseBarSeries = SeriesModel.extend({
  31522. type: 'series.__base_bar__',
  31523. getInitialData: function (option, ecModel) {
  31524. return createListFromArray(this.getSource(), this);
  31525. },
  31526. getMarkerPosition: function (value) {
  31527. var coordSys = this.coordinateSystem;
  31528. if (coordSys) {
  31529. // PENDING if clamp ?
  31530. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  31531. var data = this.getData();
  31532. var offset = data.getLayout('offset');
  31533. var size = data.getLayout('size');
  31534. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  31535. pt[offsetIndex] += offset + size / 2;
  31536. return pt;
  31537. }
  31538. return [NaN, NaN];
  31539. },
  31540. defaultOption: {
  31541. zlevel: 0, // 一级层叠
  31542. z: 2, // 二级层叠
  31543. coordinateSystem: 'cartesian2d',
  31544. legendHoverLink: true,
  31545. // stack: null
  31546. // Cartesian coordinate system
  31547. // xAxisIndex: 0,
  31548. // yAxisIndex: 0,
  31549. // 最小高度改为0
  31550. barMinHeight: 0,
  31551. // 最小角度为0,仅对极坐标系下的柱状图有效
  31552. barMinAngle: 0,
  31553. // cursor: null,
  31554. // barMaxWidth: null,
  31555. // 默认自适应
  31556. // barWidth: null,
  31557. // 柱间距离,默认为柱形宽度的30%,可设固定值
  31558. // barGap: '30%',
  31559. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  31560. // barCategoryGap: '20%',
  31561. // label: {
  31562. // show: false
  31563. // },
  31564. itemStyle: {},
  31565. emphasis: {}
  31566. }
  31567. });
  31568. BaseBarSeries.extend({
  31569. type: 'series.bar',
  31570. dependencies: ['grid', 'polar'],
  31571. brushSelector: 'rect'
  31572. });
  31573. function setLabel(
  31574. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  31575. ) {
  31576. var labelModel = itemModel.getModel('label');
  31577. var hoverLabelModel = itemModel.getModel('emphasis.label');
  31578. setLabelStyle(
  31579. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  31580. {
  31581. labelFetcher: seriesModel,
  31582. labelDataIndex: dataIndex,
  31583. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  31584. isRectText: true,
  31585. autoColor: color
  31586. }
  31587. );
  31588. fixPosition(normalStyle);
  31589. fixPosition(hoverStyle);
  31590. }
  31591. function fixPosition(style, labelPositionOutside) {
  31592. if (style.textPosition === 'outside') {
  31593. style.textPosition = labelPositionOutside;
  31594. }
  31595. }
  31596. var getBarItemStyle = makeStyleMapper(
  31597. [
  31598. ['fill', 'color'],
  31599. ['stroke', 'borderColor'],
  31600. ['lineWidth', 'borderWidth'],
  31601. // Compatitable with 2
  31602. ['stroke', 'barBorderColor'],
  31603. ['lineWidth', 'barBorderWidth'],
  31604. ['opacity'],
  31605. ['shadowBlur'],
  31606. ['shadowOffsetX'],
  31607. ['shadowOffsetY'],
  31608. ['shadowColor']
  31609. ]
  31610. );
  31611. var barItemStyle = {
  31612. getBarItemStyle: function (excludes) {
  31613. var style = getBarItemStyle(this, excludes);
  31614. if (this.getBorderLineDash) {
  31615. var lineDash = this.getBorderLineDash();
  31616. lineDash && (style.lineDash = lineDash);
  31617. }
  31618. return style;
  31619. }
  31620. };
  31621. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  31622. // FIXME
  31623. // Just for compatible with ec2.
  31624. extend(Model.prototype, barItemStyle);
  31625. extendChartView({
  31626. type: 'bar',
  31627. render: function (seriesModel, ecModel, api) {
  31628. var coordinateSystemType = seriesModel.get('coordinateSystem');
  31629. if (coordinateSystemType === 'cartesian2d'
  31630. || coordinateSystemType === 'polar'
  31631. ) {
  31632. this._render(seriesModel, ecModel, api);
  31633. }
  31634. else if (__DEV__) {
  31635. console.warn('Only cartesian2d and polar supported for bar.');
  31636. }
  31637. return this.group;
  31638. },
  31639. dispose: noop,
  31640. _render: function (seriesModel, ecModel, api) {
  31641. var group = this.group;
  31642. var data = seriesModel.getData();
  31643. var oldData = this._data;
  31644. var coord = seriesModel.coordinateSystem;
  31645. var baseAxis = coord.getBaseAxis();
  31646. var isHorizontalOrRadial;
  31647. if (coord.type === 'cartesian2d') {
  31648. isHorizontalOrRadial = baseAxis.isHorizontal();
  31649. }
  31650. else if (coord.type === 'polar') {
  31651. isHorizontalOrRadial = baseAxis.dim === 'angle';
  31652. }
  31653. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  31654. data.diff(oldData)
  31655. .add(function (dataIndex) {
  31656. if (!data.hasValue(dataIndex)) {
  31657. return;
  31658. }
  31659. var itemModel = data.getItemModel(dataIndex);
  31660. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  31661. var el = elementCreator[coord.type](
  31662. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  31663. );
  31664. data.setItemGraphicEl(dataIndex, el);
  31665. group.add(el);
  31666. updateStyle(
  31667. el, data, dataIndex, itemModel, layout,
  31668. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  31669. );
  31670. })
  31671. .update(function (newIndex, oldIndex) {
  31672. var el = oldData.getItemGraphicEl(oldIndex);
  31673. if (!data.hasValue(newIndex)) {
  31674. group.remove(el);
  31675. return;
  31676. }
  31677. var itemModel = data.getItemModel(newIndex);
  31678. var layout = getLayout[coord.type](data, newIndex, itemModel);
  31679. if (el) {
  31680. updateProps(el, {shape: layout}, animationModel, newIndex);
  31681. }
  31682. else {
  31683. el = elementCreator[coord.type](
  31684. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  31685. );
  31686. }
  31687. data.setItemGraphicEl(newIndex, el);
  31688. // Add back
  31689. group.add(el);
  31690. updateStyle(
  31691. el, data, newIndex, itemModel, layout,
  31692. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  31693. );
  31694. })
  31695. .remove(function (dataIndex) {
  31696. var el = oldData.getItemGraphicEl(dataIndex);
  31697. if (coord.type === 'cartesian2d') {
  31698. el && removeRect(dataIndex, animationModel, el);
  31699. }
  31700. else {
  31701. el && removeSector(dataIndex, animationModel, el);
  31702. }
  31703. })
  31704. .execute();
  31705. this._data = data;
  31706. },
  31707. remove: function (ecModel, api) {
  31708. var group = this.group;
  31709. var data = this._data;
  31710. if (ecModel.get('animation')) {
  31711. if (data) {
  31712. data.eachItemGraphicEl(function (el) {
  31713. if (el.type === 'sector') {
  31714. removeSector(el.dataIndex, ecModel, el);
  31715. }
  31716. else {
  31717. removeRect(el.dataIndex, ecModel, el);
  31718. }
  31719. });
  31720. }
  31721. }
  31722. else {
  31723. group.removeAll();
  31724. }
  31725. }
  31726. });
  31727. var elementCreator = {
  31728. cartesian2d: function (
  31729. data, dataIndex, itemModel, layout, isHorizontal,
  31730. animationModel, isUpdate
  31731. ) {
  31732. var rect = new Rect({shape: extend({}, layout)});
  31733. // Animation
  31734. if (animationModel) {
  31735. var rectShape = rect.shape;
  31736. var animateProperty = isHorizontal ? 'height' : 'width';
  31737. var animateTarget = {};
  31738. rectShape[animateProperty] = 0;
  31739. animateTarget[animateProperty] = layout[animateProperty];
  31740. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  31741. shape: animateTarget
  31742. }, animationModel, dataIndex);
  31743. }
  31744. return rect;
  31745. },
  31746. polar: function (
  31747. data, dataIndex, itemModel, layout, isRadial,
  31748. animationModel, isUpdate
  31749. ) {
  31750. // Keep the same logic with bar in catesion: use end value to control
  31751. // direction. Notice that if clockwise is true (by default), the sector
  31752. // will always draw clockwisely, no matter whether endAngle is greater
  31753. // or less than startAngle.
  31754. var clockwise = layout.startAngle < layout.endAngle;
  31755. var sector = new Sector({
  31756. shape: defaults({clockwise: clockwise}, layout)
  31757. });
  31758. // Animation
  31759. if (animationModel) {
  31760. var sectorShape = sector.shape;
  31761. var animateProperty = isRadial ? 'r' : 'endAngle';
  31762. var animateTarget = {};
  31763. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  31764. animateTarget[animateProperty] = layout[animateProperty];
  31765. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  31766. shape: animateTarget
  31767. }, animationModel, dataIndex);
  31768. }
  31769. return sector;
  31770. }
  31771. };
  31772. function removeRect(dataIndex, animationModel, el) {
  31773. // Not show text when animating
  31774. el.style.text = null;
  31775. updateProps(el, {
  31776. shape: {
  31777. width: 0
  31778. }
  31779. }, animationModel, dataIndex, function () {
  31780. el.parent && el.parent.remove(el);
  31781. });
  31782. }
  31783. function removeSector(dataIndex, animationModel, el) {
  31784. // Not show text when animating
  31785. el.style.text = null;
  31786. updateProps(el, {
  31787. shape: {
  31788. r: el.shape.r0
  31789. }
  31790. }, animationModel, dataIndex, function () {
  31791. el.parent && el.parent.remove(el);
  31792. });
  31793. }
  31794. var getLayout = {
  31795. cartesian2d: function (data, dataIndex, itemModel) {
  31796. var layout = data.getItemLayout(dataIndex);
  31797. var fixedLineWidth = getLineWidth(itemModel, layout);
  31798. // fix layout with lineWidth
  31799. var signX = layout.width > 0 ? 1 : -1;
  31800. var signY = layout.height > 0 ? 1 : -1;
  31801. return {
  31802. x: layout.x + signX * fixedLineWidth / 2,
  31803. y: layout.y + signY * fixedLineWidth / 2,
  31804. width: layout.width - signX * fixedLineWidth,
  31805. height: layout.height - signY * fixedLineWidth
  31806. };
  31807. },
  31808. polar: function (data, dataIndex, itemModel) {
  31809. var layout = data.getItemLayout(dataIndex);
  31810. return {
  31811. cx: layout.cx,
  31812. cy: layout.cy,
  31813. r0: layout.r0,
  31814. r: layout.r,
  31815. startAngle: layout.startAngle,
  31816. endAngle: layout.endAngle
  31817. };
  31818. }
  31819. };
  31820. function updateStyle(
  31821. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  31822. ) {
  31823. var color = data.getItemVisual(dataIndex, 'color');
  31824. var opacity = data.getItemVisual(dataIndex, 'opacity');
  31825. var itemStyleModel = itemModel.getModel('itemStyle');
  31826. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  31827. if (!isPolar) {
  31828. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  31829. }
  31830. el.useStyle(defaults(
  31831. {
  31832. fill: color,
  31833. opacity: opacity
  31834. },
  31835. itemStyleModel.getBarItemStyle()
  31836. ));
  31837. var cursorStyle = itemModel.getShallow('cursor');
  31838. cursorStyle && el.attr('cursor', cursorStyle);
  31839. var labelPositionOutside = isHorizontal
  31840. ? (layout.height > 0 ? 'bottom' : 'top')
  31841. : (layout.width > 0 ? 'left' : 'right');
  31842. if (!isPolar) {
  31843. setLabel(
  31844. el.style, hoverStyle, itemModel, color,
  31845. seriesModel, dataIndex, labelPositionOutside
  31846. );
  31847. }
  31848. setHoverStyle(el, hoverStyle);
  31849. }
  31850. // In case width or height are too small.
  31851. function getLineWidth(itemModel, rawLayout) {
  31852. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  31853. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  31854. }
  31855. // In case developer forget to include grid component
  31856. registerLayout(curry(layout, 'bar'));
  31857. // Visual coding for legend
  31858. registerVisual(function (ecModel) {
  31859. ecModel.eachSeriesByType('bar', function (seriesModel) {
  31860. var data = seriesModel.getData();
  31861. data.setVisual('legendSymbol', 'roundRect');
  31862. });
  31863. });
  31864. /**
  31865. * [Usage]:
  31866. * (1)
  31867. * createListSimply(seriesModel, ['value']);
  31868. * (2)
  31869. * createListSimply(seriesModel, {
  31870. * coordDimensions: ['value'],
  31871. * dimensionsCount: 5
  31872. * });
  31873. *
  31874. * @param {module:echarts/model/Series} seriesModel
  31875. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  31876. * The options in opt, see `echarts/data/helper/createDimensions`
  31877. * @param {Array.<string>} [nameList]
  31878. * @return {module:echarts/data/List}
  31879. */
  31880. var createListSimply = function (seriesModel, opt, nameList) {
  31881. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  31882. var source = seriesModel.getSource();
  31883. var dimensionsInfo = createDimensions(source, opt);
  31884. var list = new List(dimensionsInfo, seriesModel);
  31885. list.initData(source, nameList);
  31886. return list;
  31887. };
  31888. /**
  31889. * Data selectable mixin for chart series.
  31890. * To eanble data select, option of series must have `selectedMode`.
  31891. * And each data item will use `selected` to toggle itself selected status
  31892. */
  31893. var selectableMixin = {
  31894. /**
  31895. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  31896. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  31897. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  31898. */
  31899. updateSelectedMap: function (targetList) {
  31900. this._targetList = isArray(targetList) ? targetList.slice() : [];
  31901. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  31902. targetMap.set(target.name, target);
  31903. return targetMap;
  31904. }, createHashMap());
  31905. },
  31906. /**
  31907. * Either name or id should be passed as input here.
  31908. * If both of them are defined, id is used.
  31909. *
  31910. * @param {string|undefined} name name of data
  31911. * @param {number|undefined} id dataIndex of data
  31912. */
  31913. // PENGING If selectedMode is null ?
  31914. select: function (name, id) {
  31915. var target = id != null
  31916. ? this._targetList[id]
  31917. : this._selectTargetMap.get(name);
  31918. var selectedMode = this.get('selectedMode');
  31919. if (selectedMode === 'single') {
  31920. this._selectTargetMap.each(function (target) {
  31921. target.selected = false;
  31922. });
  31923. }
  31924. target && (target.selected = true);
  31925. },
  31926. /**
  31927. * Either name or id should be passed as input here.
  31928. * If both of them are defined, id is used.
  31929. *
  31930. * @param {string|undefined} name name of data
  31931. * @param {number|undefined} id dataIndex of data
  31932. */
  31933. unSelect: function (name, id) {
  31934. var target = id != null
  31935. ? this._targetList[id]
  31936. : this._selectTargetMap.get(name);
  31937. // var selectedMode = this.get('selectedMode');
  31938. // selectedMode !== 'single' && target && (target.selected = false);
  31939. target && (target.selected = false);
  31940. },
  31941. /**
  31942. * Either name or id should be passed as input here.
  31943. * If both of them are defined, id is used.
  31944. *
  31945. * @param {string|undefined} name name of data
  31946. * @param {number|undefined} id dataIndex of data
  31947. */
  31948. toggleSelected: function (name, id) {
  31949. var target = id != null
  31950. ? this._targetList[id]
  31951. : this._selectTargetMap.get(name);
  31952. if (target != null) {
  31953. this[target.selected ? 'unSelect' : 'select'](name, id);
  31954. return target.selected;
  31955. }
  31956. },
  31957. /**
  31958. * Either name or id should be passed as input here.
  31959. * If both of them are defined, id is used.
  31960. *
  31961. * @param {string|undefined} name name of data
  31962. * @param {number|undefined} id dataIndex of data
  31963. */
  31964. isSelected: function (name, id) {
  31965. var target = id != null
  31966. ? this._targetList[id]
  31967. : this._selectTargetMap.get(name);
  31968. return target && target.selected;
  31969. }
  31970. };
  31971. var PieSeries = extendSeriesModel({
  31972. type: 'series.pie',
  31973. // Overwrite
  31974. init: function (option) {
  31975. PieSeries.superApply(this, 'init', arguments);
  31976. // Enable legend selection for each data item
  31977. // Use a function instead of direct access because data reference may changed
  31978. this.legendDataProvider = function () {
  31979. return this.getRawData();
  31980. };
  31981. this.updateSelectedMap(this._createSelectableList());
  31982. this._defaultLabelLine(option);
  31983. },
  31984. // Overwrite
  31985. mergeOption: function (newOption) {
  31986. PieSeries.superCall(this, 'mergeOption', newOption);
  31987. this.updateSelectedMap(this._createSelectableList());
  31988. },
  31989. getInitialData: function (option, ecModel) {
  31990. return createListSimply(this, ['value']);
  31991. },
  31992. _createSelectableList: function () {
  31993. var data = this.getRawData();
  31994. var valueDim = data.mapDimension('value');
  31995. var targetList = [];
  31996. for (var i = 0, len = data.count(); i < len; i++) {
  31997. targetList.push({
  31998. name: data.getName(i),
  31999. value: data.get(valueDim, i),
  32000. selected: retrieveRawAttr(data, i, 'selected')
  32001. });
  32002. }
  32003. return targetList;
  32004. },
  32005. // Overwrite
  32006. getDataParams: function (dataIndex) {
  32007. var data = this.getData();
  32008. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  32009. // FIXME toFixed?
  32010. var valueList = [];
  32011. data.each(data.mapDimension('value'), function (value) {
  32012. valueList.push(value);
  32013. });
  32014. params.percent = getPercentWithPrecision(
  32015. valueList,
  32016. dataIndex,
  32017. data.hostModel.get('percentPrecision')
  32018. );
  32019. params.$vars.push('percent');
  32020. return params;
  32021. },
  32022. _defaultLabelLine: function (option) {
  32023. // Extend labelLine emphasis
  32024. defaultEmphasis(option, 'labelLine', ['show']);
  32025. var labelLineNormalOpt = option.labelLine;
  32026. var labelLineEmphasisOpt = option.emphasis.labelLine;
  32027. // Not show label line if `label.normal.show = false`
  32028. labelLineNormalOpt.show = labelLineNormalOpt.show
  32029. && option.label.show;
  32030. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  32031. && option.emphasis.label.show;
  32032. },
  32033. defaultOption: {
  32034. zlevel: 0,
  32035. z: 2,
  32036. legendHoverLink: true,
  32037. hoverAnimation: true,
  32038. // 默认全局居中
  32039. center: ['50%', '50%'],
  32040. radius: [0, '75%'],
  32041. // 默认顺时针
  32042. clockwise: true,
  32043. startAngle: 90,
  32044. // 最小角度改为0
  32045. minAngle: 0,
  32046. // 选中时扇区偏移量
  32047. selectedOffset: 10,
  32048. // 高亮扇区偏移量
  32049. hoverOffset: 10,
  32050. // If use strategy to avoid label overlapping
  32051. avoidLabelOverlap: true,
  32052. // 选择模式,默认关闭,可选single,multiple
  32053. // selectedMode: false,
  32054. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  32055. // roseType: null,
  32056. percentPrecision: 2,
  32057. // If still show when all data zero.
  32058. stillShowZeroSum: true,
  32059. // cursor: null,
  32060. label: {
  32061. // If rotate around circle
  32062. rotate: false,
  32063. show: true,
  32064. // 'outer', 'inside', 'center'
  32065. position: 'outer'
  32066. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32067. // 默认使用全局文本样式,详见TEXTSTYLE
  32068. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  32069. },
  32070. // Enabled when label.normal.position is 'outer'
  32071. labelLine: {
  32072. show: true,
  32073. // 引导线两段中的第一段长度
  32074. length: 15,
  32075. // 引导线两段中的第二段长度
  32076. length2: 15,
  32077. smooth: false,
  32078. lineStyle: {
  32079. // color: 各异,
  32080. width: 1,
  32081. type: 'solid'
  32082. }
  32083. },
  32084. itemStyle: {
  32085. borderWidth: 1
  32086. },
  32087. // Animation type canbe expansion, scale
  32088. animationType: 'expansion',
  32089. animationEasing: 'cubicOut'
  32090. }
  32091. });
  32092. mixin(PieSeries, selectableMixin);
  32093. /**
  32094. * @param {module:echarts/model/Series} seriesModel
  32095. * @param {boolean} hasAnimation
  32096. * @inner
  32097. */
  32098. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  32099. var data = seriesModel.getData();
  32100. var dataIndex = this.dataIndex;
  32101. var name = data.getName(dataIndex);
  32102. var selectedOffset = seriesModel.get('selectedOffset');
  32103. api.dispatchAction({
  32104. type: 'pieToggleSelect',
  32105. from: uid,
  32106. name: name,
  32107. seriesId: seriesModel.id
  32108. });
  32109. data.each(function (idx) {
  32110. toggleItemSelected(
  32111. data.getItemGraphicEl(idx),
  32112. data.getItemLayout(idx),
  32113. seriesModel.isSelected(data.getName(idx)),
  32114. selectedOffset,
  32115. hasAnimation
  32116. );
  32117. });
  32118. }
  32119. /**
  32120. * @param {module:zrender/graphic/Sector} el
  32121. * @param {Object} layout
  32122. * @param {boolean} isSelected
  32123. * @param {number} selectedOffset
  32124. * @param {boolean} hasAnimation
  32125. * @inner
  32126. */
  32127. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  32128. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  32129. var dx = Math.cos(midAngle);
  32130. var dy = Math.sin(midAngle);
  32131. var offset = isSelected ? selectedOffset : 0;
  32132. var position = [dx * offset, dy * offset];
  32133. hasAnimation
  32134. // animateTo will stop revious animation like update transition
  32135. ? el.animate()
  32136. .when(200, {
  32137. position: position
  32138. })
  32139. .start('bounceOut')
  32140. : el.attr('position', position);
  32141. }
  32142. /**
  32143. * Piece of pie including Sector, Label, LabelLine
  32144. * @constructor
  32145. * @extends {module:zrender/graphic/Group}
  32146. */
  32147. function PiePiece(data, idx) {
  32148. Group.call(this);
  32149. var sector = new Sector({
  32150. z2: 2
  32151. });
  32152. var polyline = new Polyline();
  32153. var text = new Text();
  32154. this.add(sector);
  32155. this.add(polyline);
  32156. this.add(text);
  32157. this.updateData(data, idx, true);
  32158. // Hover to change label and labelLine
  32159. function onEmphasis() {
  32160. polyline.ignore = polyline.hoverIgnore;
  32161. text.ignore = text.hoverIgnore;
  32162. }
  32163. function onNormal() {
  32164. polyline.ignore = polyline.normalIgnore;
  32165. text.ignore = text.normalIgnore;
  32166. }
  32167. this.on('emphasis', onEmphasis)
  32168. .on('normal', onNormal)
  32169. .on('mouseover', onEmphasis)
  32170. .on('mouseout', onNormal);
  32171. }
  32172. var piePieceProto = PiePiece.prototype;
  32173. piePieceProto.updateData = function (data, idx, firstCreate) {
  32174. var sector = this.childAt(0);
  32175. var seriesModel = data.hostModel;
  32176. var itemModel = data.getItemModel(idx);
  32177. var layout = data.getItemLayout(idx);
  32178. var sectorShape = extend({}, layout);
  32179. sectorShape.label = null;
  32180. if (firstCreate) {
  32181. sector.setShape(sectorShape);
  32182. var animationType = seriesModel.getShallow('animationType');
  32183. if (animationType === 'scale') {
  32184. sector.shape.r = layout.r0;
  32185. initProps(sector, {
  32186. shape: {
  32187. r: layout.r
  32188. }
  32189. }, seriesModel, idx);
  32190. }
  32191. // Expansion
  32192. else {
  32193. sector.shape.endAngle = layout.startAngle;
  32194. updateProps(sector, {
  32195. shape: {
  32196. endAngle: layout.endAngle
  32197. }
  32198. }, seriesModel, idx);
  32199. }
  32200. }
  32201. else {
  32202. updateProps(sector, {
  32203. shape: sectorShape
  32204. }, seriesModel, idx);
  32205. }
  32206. // Update common style
  32207. var visualColor = data.getItemVisual(idx, 'color');
  32208. sector.useStyle(
  32209. defaults(
  32210. {
  32211. lineJoin: 'bevel',
  32212. fill: visualColor
  32213. },
  32214. itemModel.getModel('itemStyle').getItemStyle()
  32215. )
  32216. );
  32217. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  32218. var cursorStyle = itemModel.getShallow('cursor');
  32219. cursorStyle && sector.attr('cursor', cursorStyle);
  32220. // Toggle selected
  32221. toggleItemSelected(
  32222. this,
  32223. data.getItemLayout(idx),
  32224. seriesModel.isSelected(null, idx),
  32225. seriesModel.get('selectedOffset'),
  32226. seriesModel.get('animation')
  32227. );
  32228. function onEmphasis() {
  32229. // Sector may has animation of updating data. Force to move to the last frame
  32230. // Or it may stopped on the wrong shape
  32231. sector.stopAnimation(true);
  32232. sector.animateTo({
  32233. shape: {
  32234. r: layout.r + seriesModel.get('hoverOffset')
  32235. }
  32236. }, 300, 'elasticOut');
  32237. }
  32238. function onNormal() {
  32239. sector.stopAnimation(true);
  32240. sector.animateTo({
  32241. shape: {
  32242. r: layout.r
  32243. }
  32244. }, 300, 'elasticOut');
  32245. }
  32246. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  32247. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  32248. sector
  32249. .on('mouseover', onEmphasis)
  32250. .on('mouseout', onNormal)
  32251. .on('emphasis', onEmphasis)
  32252. .on('normal', onNormal);
  32253. }
  32254. this._updateLabel(data, idx);
  32255. setHoverStyle(this);
  32256. };
  32257. piePieceProto._updateLabel = function (data, idx) {
  32258. var labelLine = this.childAt(1);
  32259. var labelText = this.childAt(2);
  32260. var seriesModel = data.hostModel;
  32261. var itemModel = data.getItemModel(idx);
  32262. var layout = data.getItemLayout(idx);
  32263. var labelLayout = layout.label;
  32264. var visualColor = data.getItemVisual(idx, 'color');
  32265. updateProps(labelLine, {
  32266. shape: {
  32267. points: labelLayout.linePoints || [
  32268. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  32269. ]
  32270. }
  32271. }, seriesModel, idx);
  32272. updateProps(labelText, {
  32273. style: {
  32274. x: labelLayout.x,
  32275. y: labelLayout.y
  32276. }
  32277. }, seriesModel, idx);
  32278. labelText.attr({
  32279. rotation: labelLayout.rotation,
  32280. origin: [labelLayout.x, labelLayout.y],
  32281. z2: 10
  32282. });
  32283. var labelModel = itemModel.getModel('label');
  32284. var labelHoverModel = itemModel.getModel('emphasis.label');
  32285. var labelLineModel = itemModel.getModel('labelLine');
  32286. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  32287. var visualColor = data.getItemVisual(idx, 'color');
  32288. setLabelStyle(
  32289. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  32290. {
  32291. labelFetcher: data.hostModel,
  32292. labelDataIndex: idx,
  32293. defaultText: data.getName(idx),
  32294. autoColor: visualColor,
  32295. useInsideStyle: !!labelLayout.inside
  32296. },
  32297. {
  32298. textAlign: labelLayout.textAlign,
  32299. textVerticalAlign: labelLayout.verticalAlign,
  32300. opacity: data.getItemVisual(idx, 'opacity')
  32301. }
  32302. );
  32303. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  32304. labelText.hoverIgnore = !labelHoverModel.get('show');
  32305. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  32306. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  32307. // Default use item visual color
  32308. labelLine.setStyle({
  32309. stroke: visualColor,
  32310. opacity: data.getItemVisual(idx, 'opacity')
  32311. });
  32312. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  32313. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  32314. var smooth = labelLineModel.get('smooth');
  32315. if (smooth && smooth === true) {
  32316. smooth = 0.4;
  32317. }
  32318. labelLine.setShape({
  32319. smooth: smooth
  32320. });
  32321. };
  32322. inherits(PiePiece, Group);
  32323. // Pie view
  32324. var PieView = Chart.extend({
  32325. type: 'pie',
  32326. init: function () {
  32327. var sectorGroup = new Group();
  32328. this._sectorGroup = sectorGroup;
  32329. },
  32330. render: function (seriesModel, ecModel, api, payload) {
  32331. if (payload && (payload.from === this.uid)) {
  32332. return;
  32333. }
  32334. var data = seriesModel.getData();
  32335. var oldData = this._data;
  32336. var group = this.group;
  32337. var hasAnimation = ecModel.get('animation');
  32338. var isFirstRender = !oldData;
  32339. var animationType = seriesModel.get('animationType');
  32340. var onSectorClick = curry(
  32341. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  32342. );
  32343. var selectedMode = seriesModel.get('selectedMode');
  32344. data.diff(oldData)
  32345. .add(function (idx) {
  32346. var piePiece = new PiePiece(data, idx);
  32347. // Default expansion animation
  32348. if (isFirstRender && animationType !== 'scale') {
  32349. piePiece.eachChild(function (child) {
  32350. child.stopAnimation(true);
  32351. });
  32352. }
  32353. selectedMode && piePiece.on('click', onSectorClick);
  32354. data.setItemGraphicEl(idx, piePiece);
  32355. group.add(piePiece);
  32356. })
  32357. .update(function (newIdx, oldIdx) {
  32358. var piePiece = oldData.getItemGraphicEl(oldIdx);
  32359. piePiece.updateData(data, newIdx);
  32360. piePiece.off('click');
  32361. selectedMode && piePiece.on('click', onSectorClick);
  32362. group.add(piePiece);
  32363. data.setItemGraphicEl(newIdx, piePiece);
  32364. })
  32365. .remove(function (idx) {
  32366. var piePiece = oldData.getItemGraphicEl(idx);
  32367. group.remove(piePiece);
  32368. })
  32369. .execute();
  32370. if (
  32371. hasAnimation && isFirstRender && data.count() > 0
  32372. // Default expansion animation
  32373. && animationType !== 'scale'
  32374. ) {
  32375. var shape = data.getItemLayout(0);
  32376. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  32377. var removeClipPath = bind(group.removeClipPath, group);
  32378. group.setClipPath(this._createClipPath(
  32379. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  32380. ));
  32381. }
  32382. this._data = data;
  32383. },
  32384. dispose: function () {},
  32385. _createClipPath: function (
  32386. cx, cy, r, startAngle, clockwise, cb, seriesModel
  32387. ) {
  32388. var clipPath = new Sector({
  32389. shape: {
  32390. cx: cx,
  32391. cy: cy,
  32392. r0: 0,
  32393. r: r,
  32394. startAngle: startAngle,
  32395. endAngle: startAngle,
  32396. clockwise: clockwise
  32397. }
  32398. });
  32399. initProps(clipPath, {
  32400. shape: {
  32401. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  32402. }
  32403. }, seriesModel, cb);
  32404. return clipPath;
  32405. },
  32406. /**
  32407. * @implement
  32408. */
  32409. containPoint: function (point, seriesModel) {
  32410. var data = seriesModel.getData();
  32411. var itemLayout = data.getItemLayout(0);
  32412. if (itemLayout) {
  32413. var dx = point[0] - itemLayout.cx;
  32414. var dy = point[1] - itemLayout.cy;
  32415. var radius = Math.sqrt(dx * dx + dy * dy);
  32416. return radius <= itemLayout.r && radius >= itemLayout.r0;
  32417. }
  32418. }
  32419. });
  32420. var createDataSelectAction = function (seriesType, actionInfos) {
  32421. each$1(actionInfos, function (actionInfo) {
  32422. actionInfo.update = 'updateView';
  32423. /**
  32424. * @payload
  32425. * @property {string} seriesName
  32426. * @property {string} name
  32427. */
  32428. registerAction(actionInfo, function (payload, ecModel) {
  32429. var selected = {};
  32430. ecModel.eachComponent(
  32431. {mainType: 'series', subType: seriesType, query: payload},
  32432. function (seriesModel) {
  32433. if (seriesModel[actionInfo.method]) {
  32434. seriesModel[actionInfo.method](
  32435. payload.name,
  32436. payload.dataIndex
  32437. );
  32438. }
  32439. var data = seriesModel.getData();
  32440. // Create selected map
  32441. data.each(function (idx) {
  32442. var name = data.getName(idx);
  32443. selected[name] = seriesModel.isSelected(name)
  32444. || false;
  32445. });
  32446. }
  32447. );
  32448. return {
  32449. name: payload.name,
  32450. selected: selected
  32451. };
  32452. });
  32453. });
  32454. };
  32455. // Pick color from palette for each data item.
  32456. // Applicable for charts that require applying color palette
  32457. // in data level (like pie, funnel, chord).
  32458. var dataColor = function (seriesType) {
  32459. return {
  32460. getTargetSeries: function (ecModel) {
  32461. // Pie and funnel may use diferrent scope
  32462. var paletteScope = {};
  32463. var seiresModelMap = createHashMap();
  32464. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  32465. seriesModel.__paletteScope = paletteScope;
  32466. seiresModelMap.set(seriesModel.uid, seriesModel);
  32467. });
  32468. return seiresModelMap;
  32469. },
  32470. reset: function (seriesModel, ecModel) {
  32471. var dataAll = seriesModel.getRawData();
  32472. var idxMap = {};
  32473. var data = seriesModel.getData();
  32474. data.each(function (idx) {
  32475. var rawIdx = data.getRawIndex(idx);
  32476. idxMap[rawIdx] = idx;
  32477. });
  32478. dataAll.each(function (rawIdx) {
  32479. var filteredIdx = idxMap[rawIdx];
  32480. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  32481. var singleDataColor = filteredIdx != null
  32482. && data.getItemVisual(filteredIdx, 'color', true);
  32483. if (!singleDataColor) {
  32484. // FIXME Performance
  32485. var itemModel = dataAll.getItemModel(rawIdx);
  32486. var color = itemModel.get('itemStyle.color')
  32487. || seriesModel.getColorFromPalette(
  32488. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  32489. dataAll.count()
  32490. );
  32491. // Legend may use the visual info in data before processed
  32492. dataAll.setItemVisual(rawIdx, 'color', color);
  32493. // Data is not filtered
  32494. if (filteredIdx != null) {
  32495. data.setItemVisual(filteredIdx, 'color', color);
  32496. }
  32497. }
  32498. else {
  32499. // Set data all color for legend
  32500. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  32501. }
  32502. });
  32503. }
  32504. };
  32505. };
  32506. // FIXME emphasis label position is not same with normal label position
  32507. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  32508. list.sort(function (a, b) {
  32509. return a.y - b.y;
  32510. });
  32511. // 压
  32512. function shiftDown(start, end, delta, dir) {
  32513. for (var j = start; j < end; j++) {
  32514. list[j].y += delta;
  32515. if (j > start
  32516. && j + 1 < end
  32517. && list[j + 1].y > list[j].y + list[j].height
  32518. ) {
  32519. shiftUp(j, delta / 2);
  32520. return;
  32521. }
  32522. }
  32523. shiftUp(end - 1, delta / 2);
  32524. }
  32525. // 弹
  32526. function shiftUp(end, delta) {
  32527. for (var j = end; j >= 0; j--) {
  32528. list[j].y -= delta;
  32529. if (j > 0
  32530. && list[j].y > list[j - 1].y + list[j - 1].height
  32531. ) {
  32532. break;
  32533. }
  32534. }
  32535. }
  32536. function changeX(list, isDownList, cx, cy, r, dir) {
  32537. var lastDeltaX = dir > 0
  32538. ? isDownList // 右侧
  32539. ? Number.MAX_VALUE // 下
  32540. : 0 // 上
  32541. : isDownList // 左侧
  32542. ? Number.MAX_VALUE // 下
  32543. : 0; // 上
  32544. for (var i = 0, l = list.length; i < l; i++) {
  32545. // Not change x for center label
  32546. if (list[i].position === 'center') {
  32547. continue;
  32548. }
  32549. var deltaY = Math.abs(list[i].y - cy);
  32550. var length = list[i].len;
  32551. var length2 = list[i].len2;
  32552. var deltaX = (deltaY < r + length)
  32553. ? Math.sqrt(
  32554. (r + length + length2) * (r + length + length2)
  32555. - deltaY * deltaY
  32556. )
  32557. : Math.abs(list[i].x - cx);
  32558. if (isDownList && deltaX >= lastDeltaX) {
  32559. // 右下,左下
  32560. deltaX = lastDeltaX - 10;
  32561. }
  32562. if (!isDownList && deltaX <= lastDeltaX) {
  32563. // 右上,左上
  32564. deltaX = lastDeltaX + 10;
  32565. }
  32566. list[i].x = cx + deltaX * dir;
  32567. lastDeltaX = deltaX;
  32568. }
  32569. }
  32570. var lastY = 0;
  32571. var delta;
  32572. var len = list.length;
  32573. var upList = [];
  32574. var downList = [];
  32575. for (var i = 0; i < len; i++) {
  32576. delta = list[i].y - lastY;
  32577. if (delta < 0) {
  32578. shiftDown(i, len, -delta, dir);
  32579. }
  32580. lastY = list[i].y + list[i].height;
  32581. }
  32582. if (viewHeight - lastY < 0) {
  32583. shiftUp(len - 1, lastY - viewHeight);
  32584. }
  32585. for (var i = 0; i < len; i++) {
  32586. if (list[i].y >= cy) {
  32587. downList.push(list[i]);
  32588. }
  32589. else {
  32590. upList.push(list[i]);
  32591. }
  32592. }
  32593. changeX(upList, false, cx, cy, r, dir);
  32594. changeX(downList, true, cx, cy, r, dir);
  32595. }
  32596. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  32597. var leftList = [];
  32598. var rightList = [];
  32599. for (var i = 0; i < labelLayoutList.length; i++) {
  32600. if (labelLayoutList[i].x < cx) {
  32601. leftList.push(labelLayoutList[i]);
  32602. }
  32603. else {
  32604. rightList.push(labelLayoutList[i]);
  32605. }
  32606. }
  32607. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  32608. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  32609. for (var i = 0; i < labelLayoutList.length; i++) {
  32610. var linePoints = labelLayoutList[i].linePoints;
  32611. if (linePoints) {
  32612. var dist = linePoints[1][0] - linePoints[2][0];
  32613. if (labelLayoutList[i].x < cx) {
  32614. linePoints[2][0] = labelLayoutList[i].x + 3;
  32615. }
  32616. else {
  32617. linePoints[2][0] = labelLayoutList[i].x - 3;
  32618. }
  32619. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  32620. linePoints[1][0] = linePoints[2][0] + dist;
  32621. }
  32622. }
  32623. }
  32624. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  32625. var data = seriesModel.getData();
  32626. var labelLayoutList = [];
  32627. var cx;
  32628. var cy;
  32629. var hasLabelRotate = false;
  32630. data.each(function (idx) {
  32631. var layout = data.getItemLayout(idx);
  32632. var itemModel = data.getItemModel(idx);
  32633. var labelModel = itemModel.getModel('label');
  32634. // Use position in normal or emphasis
  32635. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  32636. var labelLineModel = itemModel.getModel('labelLine');
  32637. var labelLineLen = labelLineModel.get('length');
  32638. var labelLineLen2 = labelLineModel.get('length2');
  32639. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  32640. var dx = Math.cos(midAngle);
  32641. var dy = Math.sin(midAngle);
  32642. var textX;
  32643. var textY;
  32644. var linePoints;
  32645. var textAlign;
  32646. cx = layout.cx;
  32647. cy = layout.cy;
  32648. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  32649. if (labelPosition === 'center') {
  32650. textX = layout.cx;
  32651. textY = layout.cy;
  32652. textAlign = 'center';
  32653. }
  32654. else {
  32655. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  32656. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  32657. textX = x1 + dx * 3;
  32658. textY = y1 + dy * 3;
  32659. if (!isLabelInside) {
  32660. // For roseType
  32661. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  32662. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  32663. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  32664. var y3 = y2;
  32665. textX = x3 + (dx < 0 ? -5 : 5);
  32666. textY = y3;
  32667. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  32668. }
  32669. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  32670. }
  32671. var font = labelModel.getFont();
  32672. var labelRotate = labelModel.get('rotate')
  32673. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  32674. var text = seriesModel.getFormattedLabel(idx, 'normal')
  32675. || data.getName(idx);
  32676. var textRect = getBoundingRect(
  32677. text, font, textAlign, 'top'
  32678. );
  32679. hasLabelRotate = !!labelRotate;
  32680. layout.label = {
  32681. x: textX,
  32682. y: textY,
  32683. position: labelPosition,
  32684. height: textRect.height,
  32685. len: labelLineLen,
  32686. len2: labelLineLen2,
  32687. linePoints: linePoints,
  32688. textAlign: textAlign,
  32689. verticalAlign: 'middle',
  32690. rotation: labelRotate,
  32691. inside: isLabelInside
  32692. };
  32693. // Not layout the inside label
  32694. if (!isLabelInside) {
  32695. labelLayoutList.push(layout.label);
  32696. }
  32697. });
  32698. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  32699. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  32700. }
  32701. };
  32702. var PI2$4 = Math.PI * 2;
  32703. var RADIAN = Math.PI / 180;
  32704. var pieLayout = function (seriesType, ecModel, api, payload) {
  32705. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  32706. var data = seriesModel.getData();
  32707. var valueDim = data.mapDimension('value');
  32708. var center = seriesModel.get('center');
  32709. var radius = seriesModel.get('radius');
  32710. if (!isArray(radius)) {
  32711. radius = [0, radius];
  32712. }
  32713. if (!isArray(center)) {
  32714. center = [center, center];
  32715. }
  32716. var width = api.getWidth();
  32717. var height = api.getHeight();
  32718. var size = Math.min(width, height);
  32719. var cx = parsePercent$1(center[0], width);
  32720. var cy = parsePercent$1(center[1], height);
  32721. var r0 = parsePercent$1(radius[0], size / 2);
  32722. var r = parsePercent$1(radius[1], size / 2);
  32723. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  32724. var minAngle = seriesModel.get('minAngle') * RADIAN;
  32725. var validDataCount = 0;
  32726. data.each(valueDim, function (value) {
  32727. !isNaN(value) && validDataCount++;
  32728. });
  32729. var sum = data.getSum(valueDim);
  32730. // Sum may be 0
  32731. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  32732. var clockwise = seriesModel.get('clockwise');
  32733. var roseType = seriesModel.get('roseType');
  32734. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  32735. // [0...max]
  32736. var extent = data.getDataExtent(valueDim);
  32737. extent[0] = 0;
  32738. // In the case some sector angle is smaller than minAngle
  32739. var restAngle = PI2$4;
  32740. var valueSumLargerThanMinAngle = 0;
  32741. var currentAngle = startAngle;
  32742. var dir = clockwise ? 1 : -1;
  32743. data.each(valueDim, function (value, idx) {
  32744. var angle;
  32745. if (isNaN(value)) {
  32746. data.setItemLayout(idx, {
  32747. angle: NaN,
  32748. startAngle: NaN,
  32749. endAngle: NaN,
  32750. clockwise: clockwise,
  32751. cx: cx,
  32752. cy: cy,
  32753. r0: r0,
  32754. r: roseType
  32755. ? NaN
  32756. : r
  32757. });
  32758. return;
  32759. }
  32760. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  32761. if (roseType !== 'area') {
  32762. angle = (sum === 0 && stillShowZeroSum)
  32763. ? unitRadian : (value * unitRadian);
  32764. }
  32765. else {
  32766. angle = PI2$4 / validDataCount;
  32767. }
  32768. if (angle < minAngle) {
  32769. angle = minAngle;
  32770. restAngle -= minAngle;
  32771. }
  32772. else {
  32773. valueSumLargerThanMinAngle += value;
  32774. }
  32775. var endAngle = currentAngle + dir * angle;
  32776. data.setItemLayout(idx, {
  32777. angle: angle,
  32778. startAngle: currentAngle,
  32779. endAngle: endAngle,
  32780. clockwise: clockwise,
  32781. cx: cx,
  32782. cy: cy,
  32783. r0: r0,
  32784. r: roseType
  32785. ? linearMap(value, extent, [r0, r])
  32786. : r
  32787. });
  32788. currentAngle = endAngle;
  32789. });
  32790. // Some sector is constrained by minAngle
  32791. // Rest sectors needs recalculate angle
  32792. if (restAngle < PI2$4 && validDataCount) {
  32793. // Average the angle if rest angle is not enough after all angles is
  32794. // Constrained by minAngle
  32795. if (restAngle <= 1e-3) {
  32796. var angle = PI2$4 / validDataCount;
  32797. data.each(valueDim, function (value, idx) {
  32798. if (!isNaN(value)) {
  32799. var layout = data.getItemLayout(idx);
  32800. layout.angle = angle;
  32801. layout.startAngle = startAngle + dir * idx * angle;
  32802. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  32803. }
  32804. });
  32805. }
  32806. else {
  32807. unitRadian = restAngle / valueSumLargerThanMinAngle;
  32808. currentAngle = startAngle;
  32809. data.each(valueDim, function (value, idx) {
  32810. if (!isNaN(value)) {
  32811. var layout = data.getItemLayout(idx);
  32812. var angle = layout.angle === minAngle
  32813. ? minAngle : value * unitRadian;
  32814. layout.startAngle = currentAngle;
  32815. layout.endAngle = currentAngle + dir * angle;
  32816. currentAngle += dir * angle;
  32817. }
  32818. });
  32819. }
  32820. }
  32821. labelLayout(seriesModel, r, width, height);
  32822. });
  32823. };
  32824. var dataFilter = function (seriesType) {
  32825. return {
  32826. seriesType: seriesType,
  32827. reset: function (seriesModel, ecModel) {
  32828. var legendModels = ecModel.findComponents({
  32829. mainType: 'legend'
  32830. });
  32831. if (!legendModels || !legendModels.length) {
  32832. return;
  32833. }
  32834. var data = seriesModel.getData();
  32835. data.filterSelf(function (idx) {
  32836. var name = data.getName(idx);
  32837. // If in any legend component the status is not selected.
  32838. for (var i = 0; i < legendModels.length; i++) {
  32839. if (!legendModels[i].isSelected(name)) {
  32840. return false;
  32841. }
  32842. }
  32843. return true;
  32844. });
  32845. }
  32846. };
  32847. };
  32848. createDataSelectAction('pie', [{
  32849. type: 'pieToggleSelect',
  32850. event: 'pieselectchanged',
  32851. method: 'toggleSelected'
  32852. }, {
  32853. type: 'pieSelect',
  32854. event: 'pieselected',
  32855. method: 'select'
  32856. }, {
  32857. type: 'pieUnSelect',
  32858. event: 'pieunselected',
  32859. method: 'unSelect'
  32860. }]);
  32861. registerVisual(dataColor('pie'));
  32862. registerLayout(curry(pieLayout, 'pie'));
  32863. registerProcessor(dataFilter('pie'));
  32864. SeriesModel.extend({
  32865. type: 'series.scatter',
  32866. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  32867. getInitialData: function (option, ecModel) {
  32868. return createListFromArray(this.getSource(), this);
  32869. },
  32870. brushSelector: 'point',
  32871. getProgressive: function () {
  32872. var progressive = this.option.progressive;
  32873. if (progressive == null) {
  32874. // PENDING
  32875. return this.option.large ? 5e3 : this.get('progressive');
  32876. }
  32877. return progressive;
  32878. },
  32879. getProgressiveThreshold: function () {
  32880. var progressiveThreshold = this.option.progressiveThreshold;
  32881. if (progressiveThreshold == null) {
  32882. // PENDING
  32883. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  32884. }
  32885. return progressiveThreshold;
  32886. },
  32887. defaultOption: {
  32888. coordinateSystem: 'cartesian2d',
  32889. zlevel: 0,
  32890. z: 2,
  32891. legendHoverLink: true,
  32892. hoverAnimation: true,
  32893. // Cartesian coordinate system
  32894. // xAxisIndex: 0,
  32895. // yAxisIndex: 0,
  32896. // Polar coordinate system
  32897. // polarIndex: 0,
  32898. // Geo coordinate system
  32899. // geoIndex: 0,
  32900. // symbol: null, // 图形类型
  32901. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  32902. // symbolRotate: null, // 图形旋转控制
  32903. large: false,
  32904. // Available when large is true
  32905. largeThreshold: 2000,
  32906. // cursor: null,
  32907. // label: {
  32908. // show: false
  32909. // distance: 5,
  32910. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  32911. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  32912. // 'inside'|'left'|'right'|'top'|'bottom'
  32913. // 默认使用全局文本样式,详见TEXTSTYLE
  32914. // },
  32915. itemStyle: {
  32916. opacity: 0.8
  32917. // color: 各异
  32918. },
  32919. progressive: null
  32920. }
  32921. });
  32922. // TODO Batch by color
  32923. var BOOST_SIZE_THRESHOLD = 4;
  32924. var LargeSymbolPath = extendShape({
  32925. shape: {
  32926. points: null
  32927. },
  32928. symbolProxy: null,
  32929. buildPath: function (path, shape) {
  32930. var points = shape.points;
  32931. var size = shape.size;
  32932. var symbolProxy = this.symbolProxy;
  32933. var symbolProxyShape = symbolProxy.shape;
  32934. var ctx = path.getContext ? path.getContext() : path;
  32935. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  32936. // Do draw in afterBrush.
  32937. if (canBoost) {
  32938. return;
  32939. }
  32940. for (var i = 0; i < points.length;) {
  32941. var x = points[i++];
  32942. var y = points[i++];
  32943. if (isNaN(x) || isNaN(y)) {
  32944. continue;
  32945. }
  32946. symbolProxyShape.x = x - size[0] / 2;
  32947. symbolProxyShape.y = y - size[1] / 2;
  32948. symbolProxyShape.width = size[0];
  32949. symbolProxyShape.height = size[1];
  32950. symbolProxy.buildPath(path, symbolProxyShape, true);
  32951. }
  32952. },
  32953. afterBrush: function (ctx) {
  32954. var shape = this.shape;
  32955. var points = shape.points;
  32956. var size = shape.size;
  32957. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  32958. if (!canBoost) {
  32959. return;
  32960. }
  32961. this.setTransform(ctx);
  32962. // PENDING If style or other canvas status changed?
  32963. for (var i = 0; i < points.length;) {
  32964. var x = points[i++];
  32965. var y = points[i++];
  32966. if (isNaN(x) || isNaN(y)) {
  32967. continue;
  32968. }
  32969. // fillRect is faster than building a rect path and draw.
  32970. // And it support light globalCompositeOperation.
  32971. ctx.fillRect(
  32972. x - size[0] / 2, y - size[1] / 2,
  32973. size[0], size[1]
  32974. );
  32975. }
  32976. this.restoreTransform(ctx);
  32977. },
  32978. findDataIndex: function (x, y) {
  32979. // TODO ???
  32980. // Consider transform
  32981. var shape = this.shape;
  32982. var points = shape.points;
  32983. var size = shape.size;
  32984. var w = Math.max(size[0], 4);
  32985. var h = Math.max(size[1], 4);
  32986. // Not consider transform
  32987. // Treat each element as a rect
  32988. // top down traverse
  32989. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  32990. var i = idx * 2;
  32991. var x0 = points[i] - w / 2;
  32992. var y0 = points[i + 1] - h / 2;
  32993. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  32994. return idx;
  32995. }
  32996. }
  32997. return -1;
  32998. }
  32999. });
  33000. function LargeSymbolDraw() {
  33001. this.group = new Group();
  33002. }
  33003. var largeSymbolProto = LargeSymbolDraw.prototype;
  33004. largeSymbolProto.isPersistent = function () {
  33005. return !this._incremental;
  33006. };
  33007. /**
  33008. * Update symbols draw by new data
  33009. * @param {module:echarts/data/List} data
  33010. */
  33011. largeSymbolProto.updateData = function (data) {
  33012. this.group.removeAll();
  33013. var symbolEl = new LargeSymbolPath({
  33014. rectHover: true,
  33015. cursor: 'default'
  33016. });
  33017. symbolEl.setShape({
  33018. points: data.getLayout('symbolPoints')
  33019. });
  33020. this._setCommon(symbolEl, data);
  33021. this.group.add(symbolEl);
  33022. this._incremental = null;
  33023. };
  33024. largeSymbolProto.updateLayout = function (data) {
  33025. if (this._incremental) {
  33026. return;
  33027. }
  33028. var points = data.getLayout('symbolPoints');
  33029. this.group.eachChild(function (child) {
  33030. if (child.startIndex != null) {
  33031. var len = (child.endIndex - child.startIndex) * 2;
  33032. var byteOffset = child.startIndex * 4 * 2;
  33033. points = new Float32Array(points.buffer, byteOffset, len);
  33034. }
  33035. child.setShape('points', points);
  33036. });
  33037. };
  33038. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  33039. this.group.removeAll();
  33040. this._clearIncremental();
  33041. // Only use incremental displayables when data amount is larger than 2 million.
  33042. // PENDING Incremental data?
  33043. if (data.count() > 2e6) {
  33044. if (!this._incremental) {
  33045. this._incremental = new IncrementalDisplayble({
  33046. silent: true
  33047. });
  33048. }
  33049. this.group.add(this._incremental);
  33050. }
  33051. else {
  33052. this._incremental = null;
  33053. }
  33054. };
  33055. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  33056. var symbolEl;
  33057. if (this._incremental) {
  33058. symbolEl = new LargeSymbolPath();
  33059. this._incremental.addDisplayable(symbolEl, true);
  33060. }
  33061. else {
  33062. symbolEl = new LargeSymbolPath({
  33063. rectHover: true,
  33064. cursor: 'default',
  33065. startIndex: taskParams.start,
  33066. endIndex: taskParams.end
  33067. });
  33068. symbolEl.incremental = true;
  33069. this.group.add(symbolEl);
  33070. }
  33071. symbolEl.setShape({
  33072. points: data.getLayout('symbolPoints')
  33073. });
  33074. this._setCommon(symbolEl, data, !!this._incremental);
  33075. };
  33076. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  33077. var hostModel = data.hostModel;
  33078. // TODO
  33079. // if (data.hasItemVisual.symbolSize) {
  33080. // // TODO typed array?
  33081. // symbolEl.setShape('sizes', data.mapArray(
  33082. // function (idx) {
  33083. // var size = data.getItemVisual(idx, 'symbolSize');
  33084. // return (size instanceof Array) ? size : [size, size];
  33085. // }
  33086. // ));
  33087. // }
  33088. // else {
  33089. var size = data.getVisual('symbolSize');
  33090. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  33091. // }
  33092. // Create symbolProxy to build path for each data
  33093. symbolEl.symbolProxy = createSymbol(
  33094. data.getVisual('symbol'), 0, 0, 0, 0
  33095. );
  33096. // Use symbolProxy setColor method
  33097. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  33098. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  33099. symbolEl.useStyle(
  33100. // Draw shadow when doing fillRect is extremely slow.
  33101. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  33102. );
  33103. var visualColor = data.getVisual('color');
  33104. if (visualColor) {
  33105. symbolEl.setColor(visualColor);
  33106. }
  33107. if (!isIncremental) {
  33108. // Enable tooltip
  33109. // PENDING May have performance issue when path is extremely large
  33110. symbolEl.seriesIndex = hostModel.seriesIndex;
  33111. symbolEl.on('mousemove', function (e) {
  33112. symbolEl.dataIndex = null;
  33113. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  33114. if (dataIndex >= 0) {
  33115. // Provide dataIndex for tooltip
  33116. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  33117. }
  33118. });
  33119. }
  33120. };
  33121. largeSymbolProto.remove = function () {
  33122. this._clearIncremental();
  33123. this._incremental = null;
  33124. this.group.removeAll();
  33125. };
  33126. largeSymbolProto._clearIncremental = function () {
  33127. var incremental = this._incremental;
  33128. if (incremental) {
  33129. incremental.clearDisplaybles();
  33130. }
  33131. };
  33132. extendChartView({
  33133. type: 'scatter',
  33134. render: function (seriesModel, ecModel, api) {
  33135. var data = seriesModel.getData();
  33136. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  33137. symbolDraw.updateData(data);
  33138. this._finished = true;
  33139. },
  33140. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  33141. var data = seriesModel.getData();
  33142. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  33143. symbolDraw.incrementalPrepareUpdate(data);
  33144. this._finished = false;
  33145. },
  33146. incrementalRender: function (taskParams, seriesModel, ecModel) {
  33147. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  33148. this._finished = taskParams.end === seriesModel.getData().count();
  33149. },
  33150. updateTransform: function (seriesModel, ecModel, api) {
  33151. var data = seriesModel.getData();
  33152. // Must mark group dirty and make sure the incremental layer will be cleared
  33153. // PENDING
  33154. this.group.dirty();
  33155. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  33156. return {
  33157. update: true
  33158. };
  33159. }
  33160. else {
  33161. var res = pointsLayout().reset(seriesModel);
  33162. if (res.progress) {
  33163. res.progress({ start: 0, end: data.count() }, data);
  33164. }
  33165. this._symbolDraw.updateLayout(data);
  33166. }
  33167. },
  33168. _updateSymbolDraw: function (data, seriesModel) {
  33169. var symbolDraw = this._symbolDraw;
  33170. var pipelineContext = seriesModel.pipelineContext;
  33171. var isLargeDraw = pipelineContext.large;
  33172. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  33173. symbolDraw && symbolDraw.remove();
  33174. symbolDraw = this._symbolDraw = isLargeDraw
  33175. ? new LargeSymbolDraw()
  33176. : new SymbolDraw();
  33177. this._isLargeDraw = isLargeDraw;
  33178. this.group.removeAll();
  33179. }
  33180. this.group.add(symbolDraw.group);
  33181. return symbolDraw;
  33182. },
  33183. remove: function (ecModel, api) {
  33184. this._symbolDraw && this._symbolDraw.remove(true);
  33185. this._symbolDraw = null;
  33186. },
  33187. dispose: function () {}
  33188. });
  33189. // import * as zrUtil from 'zrender/src/core/util';
  33190. // In case developer forget to include grid component
  33191. registerVisual(visualSymbol('scatter', 'circle'));
  33192. registerLayout(pointsLayout('scatter'));
  33193. // echarts.registerProcessor(function (ecModel, api) {
  33194. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  33195. // var data = seriesModel.getData();
  33196. // var coordSys = seriesModel.coordinateSystem;
  33197. // if (coordSys.type !== 'geo') {
  33198. // return;
  33199. // }
  33200. // var startPt = coordSys.pointToData([0, 0]);
  33201. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  33202. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  33203. // return data.mapDimension(dim);
  33204. // });
  33205. // var range = {};
  33206. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  33207. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  33208. // data.selectRange(range);
  33209. // });
  33210. // });
  33211. function IndicatorAxis(dim, scale, radiusExtent) {
  33212. Axis.call(this, dim, scale, radiusExtent);
  33213. /**
  33214. * Axis type
  33215. * - 'category'
  33216. * - 'value'
  33217. * - 'time'
  33218. * - 'log'
  33219. * @type {string}
  33220. */
  33221. this.type = 'value';
  33222. this.angle = 0;
  33223. /**
  33224. * Indicator name
  33225. * @type {string}
  33226. */
  33227. this.name = '';
  33228. /**
  33229. * @type {module:echarts/model/Model}
  33230. */
  33231. this.model;
  33232. }
  33233. inherits(IndicatorAxis, Axis);
  33234. // TODO clockwise
  33235. function Radar(radarModel, ecModel, api) {
  33236. this._model = radarModel;
  33237. /**
  33238. * Radar dimensions
  33239. * @type {Array.<string>}
  33240. */
  33241. this.dimensions = [];
  33242. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  33243. var dim = 'indicator_' + idx;
  33244. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  33245. indicatorAxis.name = indicatorModel.get('name');
  33246. // Inject model and axis
  33247. indicatorAxis.model = indicatorModel;
  33248. indicatorModel.axis = indicatorAxis;
  33249. this.dimensions.push(dim);
  33250. return indicatorAxis;
  33251. }, this);
  33252. this.resize(radarModel, api);
  33253. /**
  33254. * @type {number}
  33255. * @readOnly
  33256. */
  33257. this.cx;
  33258. /**
  33259. * @type {number}
  33260. * @readOnly
  33261. */
  33262. this.cy;
  33263. /**
  33264. * @type {number}
  33265. * @readOnly
  33266. */
  33267. this.r;
  33268. /**
  33269. * @type {number}
  33270. * @readOnly
  33271. */
  33272. this.startAngle;
  33273. }
  33274. Radar.prototype.getIndicatorAxes = function () {
  33275. return this._indicatorAxes;
  33276. };
  33277. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  33278. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  33279. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  33280. };
  33281. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  33282. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  33283. var angle = indicatorAxis.angle;
  33284. var x = this.cx + coord * Math.cos(angle);
  33285. var y = this.cy - coord * Math.sin(angle);
  33286. return [x, y];
  33287. };
  33288. Radar.prototype.pointToData = function (pt) {
  33289. var dx = pt[0] - this.cx;
  33290. var dy = pt[1] - this.cy;
  33291. var radius = Math.sqrt(dx * dx + dy * dy);
  33292. dx /= radius;
  33293. dy /= radius;
  33294. var radian = Math.atan2(-dy, dx);
  33295. // Find the closest angle
  33296. // FIXME index can calculated directly
  33297. var minRadianDiff = Infinity;
  33298. var closestAxis;
  33299. var closestAxisIdx = -1;
  33300. for (var i = 0; i < this._indicatorAxes.length; i++) {
  33301. var indicatorAxis = this._indicatorAxes[i];
  33302. var diff = Math.abs(radian - indicatorAxis.angle);
  33303. if (diff < minRadianDiff) {
  33304. closestAxis = indicatorAxis;
  33305. closestAxisIdx = i;
  33306. minRadianDiff = diff;
  33307. }
  33308. }
  33309. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  33310. };
  33311. Radar.prototype.resize = function (radarModel, api) {
  33312. var center = radarModel.get('center');
  33313. var viewWidth = api.getWidth();
  33314. var viewHeight = api.getHeight();
  33315. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  33316. this.cx = parsePercent$1(center[0], viewWidth);
  33317. this.cy = parsePercent$1(center[1], viewHeight);
  33318. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  33319. this.r = parsePercent$1(radarModel.get('radius'), viewSize);
  33320. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  33321. indicatorAxis.setExtent(0, this.r);
  33322. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  33323. // Normalize to [-PI, PI]
  33324. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  33325. indicatorAxis.angle = angle;
  33326. }, this);
  33327. };
  33328. Radar.prototype.update = function (ecModel, api) {
  33329. var indicatorAxes = this._indicatorAxes;
  33330. var radarModel = this._model;
  33331. each$1(indicatorAxes, function (indicatorAxis) {
  33332. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  33333. });
  33334. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  33335. if (radarSeries.get('coordinateSystem') !== 'radar'
  33336. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  33337. ) {
  33338. return;
  33339. }
  33340. var data = radarSeries.getData();
  33341. each$1(indicatorAxes, function (indicatorAxis) {
  33342. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  33343. });
  33344. }, this);
  33345. var splitNumber = radarModel.get('splitNumber');
  33346. function increaseInterval(interval) {
  33347. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  33348. // Increase interval
  33349. var f = interval / exp10;
  33350. if (f === 2) {
  33351. f = 5;
  33352. }
  33353. else { // f is 2 or 5
  33354. f *= 2;
  33355. }
  33356. return f * exp10;
  33357. }
  33358. // Force all the axis fixing the maxSplitNumber.
  33359. each$1(indicatorAxes, function (indicatorAxis, idx) {
  33360. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  33361. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  33362. var axisModel = indicatorAxis.model;
  33363. var scale = indicatorAxis.scale;
  33364. var fixedMin = axisModel.getMin();
  33365. var fixedMax = axisModel.getMax();
  33366. var interval = scale.getInterval();
  33367. if (fixedMin != null && fixedMax != null) {
  33368. // User set min, max, divide to get new interval
  33369. scale.setExtent(+fixedMin, +fixedMax);
  33370. scale.setInterval(
  33371. (fixedMax - fixedMin) / splitNumber
  33372. );
  33373. }
  33374. else if (fixedMin != null) {
  33375. var max;
  33376. // User set min, expand extent on the other side
  33377. do {
  33378. max = fixedMin + interval * splitNumber;
  33379. scale.setExtent(+fixedMin, max);
  33380. // Interval must been set after extent
  33381. // FIXME
  33382. scale.setInterval(interval);
  33383. interval = increaseInterval(interval);
  33384. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  33385. }
  33386. else if (fixedMax != null) {
  33387. var min;
  33388. // User set min, expand extent on the other side
  33389. do {
  33390. min = fixedMax - interval * splitNumber;
  33391. scale.setExtent(min, +fixedMax);
  33392. scale.setInterval(interval);
  33393. interval = increaseInterval(interval);
  33394. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  33395. }
  33396. else {
  33397. var nicedSplitNumber = scale.getTicks().length - 1;
  33398. if (nicedSplitNumber > splitNumber) {
  33399. interval = increaseInterval(interval);
  33400. }
  33401. // PENDING
  33402. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  33403. var halfSplitNumber = Math.round(splitNumber / 2);
  33404. scale.setExtent(
  33405. round$1(center - halfSplitNumber * interval),
  33406. round$1(center + (splitNumber - halfSplitNumber) * interval)
  33407. );
  33408. scale.setInterval(interval);
  33409. }
  33410. });
  33411. };
  33412. /**
  33413. * Radar dimensions is based on the data
  33414. * @type {Array}
  33415. */
  33416. Radar.dimensions = [];
  33417. Radar.create = function (ecModel, api) {
  33418. var radarList = [];
  33419. ecModel.eachComponent('radar', function (radarModel) {
  33420. var radar = new Radar(radarModel, ecModel, api);
  33421. radarList.push(radar);
  33422. radarModel.coordinateSystem = radar;
  33423. });
  33424. ecModel.eachSeriesByType('radar', function (radarSeries) {
  33425. if (radarSeries.get('coordinateSystem') === 'radar') {
  33426. // Inject coordinate system
  33427. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  33428. }
  33429. });
  33430. return radarList;
  33431. };
  33432. CoordinateSystemManager.register('radar', Radar);
  33433. var valueAxisDefault = axisDefault.valueAxis;
  33434. function defaultsShow(opt, show) {
  33435. return defaults({
  33436. show: show
  33437. }, opt);
  33438. }
  33439. var RadarModel = extendComponentModel({
  33440. type: 'radar',
  33441. optionUpdated: function () {
  33442. var boundaryGap = this.get('boundaryGap');
  33443. var splitNumber = this.get('splitNumber');
  33444. var scale = this.get('scale');
  33445. var axisLine = this.get('axisLine');
  33446. var axisTick = this.get('axisTick');
  33447. var axisLabel = this.get('axisLabel');
  33448. var nameTextStyle = this.get('name');
  33449. var showName = this.get('name.show');
  33450. var nameFormatter = this.get('name.formatter');
  33451. var nameGap = this.get('nameGap');
  33452. var triggerEvent = this.get('triggerEvent');
  33453. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  33454. // PENDING
  33455. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  33456. indicatorOpt.min = 0;
  33457. }
  33458. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  33459. indicatorOpt.max = 0;
  33460. }
  33461. var iNameTextStyle = nameTextStyle;
  33462. if(indicatorOpt.color != null) {
  33463. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  33464. }
  33465. // Use same configuration
  33466. indicatorOpt = merge(clone(indicatorOpt), {
  33467. boundaryGap: boundaryGap,
  33468. splitNumber: splitNumber,
  33469. scale: scale,
  33470. axisLine: axisLine,
  33471. axisTick: axisTick,
  33472. axisLabel: axisLabel,
  33473. // Competitable with 2 and use text
  33474. name: indicatorOpt.text,
  33475. nameLocation: 'end',
  33476. nameGap: nameGap,
  33477. // min: 0,
  33478. nameTextStyle: iNameTextStyle,
  33479. triggerEvent: triggerEvent
  33480. }, false);
  33481. if (!showName) {
  33482. indicatorOpt.name = '';
  33483. }
  33484. if (typeof nameFormatter === 'string') {
  33485. var indName = indicatorOpt.name;
  33486. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  33487. }
  33488. else if (typeof nameFormatter === 'function') {
  33489. indicatorOpt.name = nameFormatter(
  33490. indicatorOpt.name, indicatorOpt
  33491. );
  33492. }
  33493. var model = extend(
  33494. new Model(indicatorOpt, null, this.ecModel),
  33495. axisModelCommonMixin
  33496. );
  33497. // For triggerEvent.
  33498. model.mainType = 'radar';
  33499. model.componentIndex = this.componentIndex;
  33500. return model;
  33501. }, this);
  33502. this.getIndicatorModels = function () {
  33503. return indicatorModels;
  33504. };
  33505. },
  33506. defaultOption: {
  33507. zlevel: 0,
  33508. z: 0,
  33509. center: ['50%', '50%'],
  33510. radius: '75%',
  33511. startAngle: 90,
  33512. name: {
  33513. show: true
  33514. // formatter: null
  33515. // textStyle: {}
  33516. },
  33517. boundaryGap: [0, 0],
  33518. splitNumber: 5,
  33519. nameGap: 15,
  33520. scale: false,
  33521. // Polygon or circle
  33522. shape: 'polygon',
  33523. axisLine: merge(
  33524. {
  33525. lineStyle: {
  33526. color: '#bbb'
  33527. }
  33528. },
  33529. valueAxisDefault.axisLine
  33530. ),
  33531. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  33532. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  33533. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  33534. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  33535. // {text, min, max}
  33536. indicator: []
  33537. }
  33538. });
  33539. var axisBuilderAttrs$1 = [
  33540. 'axisLine', 'axisTickLabel', 'axisName'
  33541. ];
  33542. extendComponentView({
  33543. type: 'radar',
  33544. render: function (radarModel, ecModel, api) {
  33545. var group = this.group;
  33546. group.removeAll();
  33547. this._buildAxes(radarModel);
  33548. this._buildSplitLineAndArea(radarModel);
  33549. },
  33550. _buildAxes: function (radarModel) {
  33551. var radar = radarModel.coordinateSystem;
  33552. var indicatorAxes = radar.getIndicatorAxes();
  33553. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  33554. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  33555. position: [radar.cx, radar.cy],
  33556. rotation: indicatorAxis.angle,
  33557. labelDirection: -1,
  33558. tickDirection: -1,
  33559. nameDirection: 1
  33560. });
  33561. return axisBuilder;
  33562. });
  33563. each$1(axisBuilders, function (axisBuilder) {
  33564. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  33565. this.group.add(axisBuilder.getGroup());
  33566. }, this);
  33567. },
  33568. _buildSplitLineAndArea: function (radarModel) {
  33569. var radar = radarModel.coordinateSystem;
  33570. var indicatorAxes = radar.getIndicatorAxes();
  33571. if (!indicatorAxes.length) {
  33572. return;
  33573. }
  33574. var shape = radarModel.get('shape');
  33575. var splitLineModel = radarModel.getModel('splitLine');
  33576. var splitAreaModel = radarModel.getModel('splitArea');
  33577. var lineStyleModel = splitLineModel.getModel('lineStyle');
  33578. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  33579. var showSplitLine = splitLineModel.get('show');
  33580. var showSplitArea = splitAreaModel.get('show');
  33581. var splitLineColors = lineStyleModel.get('color');
  33582. var splitAreaColors = areaStyleModel.get('color');
  33583. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  33584. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  33585. var splitLines = [];
  33586. var splitAreas = [];
  33587. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  33588. var colorIndex = idx % areaOrLineColorList.length;
  33589. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  33590. return colorIndex;
  33591. }
  33592. if (shape === 'circle') {
  33593. var ticksRadius = indicatorAxes[0].getTicksCoords();
  33594. var cx = radar.cx;
  33595. var cy = radar.cy;
  33596. for (var i = 0; i < ticksRadius.length; i++) {
  33597. if (showSplitLine) {
  33598. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  33599. splitLines[colorIndex].push(new Circle({
  33600. shape: {
  33601. cx: cx,
  33602. cy: cy,
  33603. r: ticksRadius[i]
  33604. }
  33605. }));
  33606. }
  33607. if (showSplitArea && i < ticksRadius.length - 1) {
  33608. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  33609. splitAreas[colorIndex].push(new Ring({
  33610. shape: {
  33611. cx: cx,
  33612. cy: cy,
  33613. r0: ticksRadius[i],
  33614. r: ticksRadius[i + 1]
  33615. }
  33616. }));
  33617. }
  33618. }
  33619. }
  33620. // Polyyon
  33621. else {
  33622. var realSplitNumber;
  33623. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  33624. var ticksCoords = indicatorAxis.getTicksCoords();
  33625. realSplitNumber = realSplitNumber == null
  33626. ? ticksCoords.length - 1
  33627. : Math.min(ticksCoords.length - 1, realSplitNumber);
  33628. return map(ticksCoords, function (tickCoord) {
  33629. return radar.coordToPoint(tickCoord, idx);
  33630. });
  33631. });
  33632. var prevPoints = [];
  33633. for (var i = 0; i <= realSplitNumber; i++) {
  33634. var points = [];
  33635. for (var j = 0; j < indicatorAxes.length; j++) {
  33636. points.push(axesTicksPoints[j][i]);
  33637. }
  33638. // Close
  33639. if (points[0]) {
  33640. points.push(points[0].slice());
  33641. }
  33642. else {
  33643. if (__DEV__) {
  33644. console.error('Can\'t draw value axis ' + i);
  33645. }
  33646. }
  33647. if (showSplitLine) {
  33648. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  33649. splitLines[colorIndex].push(new Polyline({
  33650. shape: {
  33651. points: points
  33652. }
  33653. }));
  33654. }
  33655. if (showSplitArea && prevPoints) {
  33656. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  33657. splitAreas[colorIndex].push(new Polygon({
  33658. shape: {
  33659. points: points.concat(prevPoints)
  33660. }
  33661. }));
  33662. }
  33663. prevPoints = points.slice().reverse();
  33664. }
  33665. }
  33666. var lineStyle = lineStyleModel.getLineStyle();
  33667. var areaStyle = areaStyleModel.getAreaStyle();
  33668. // Add splitArea before splitLine
  33669. each$1(splitAreas, function (splitAreas, idx) {
  33670. this.group.add(mergePath(
  33671. splitAreas, {
  33672. style: defaults({
  33673. stroke: 'none',
  33674. fill: splitAreaColors[idx % splitAreaColors.length]
  33675. }, areaStyle),
  33676. silent: true
  33677. }
  33678. ));
  33679. }, this);
  33680. each$1(splitLines, function (splitLines, idx) {
  33681. this.group.add(mergePath(
  33682. splitLines, {
  33683. style: defaults({
  33684. fill: 'none',
  33685. stroke: splitLineColors[idx % splitLineColors.length]
  33686. }, lineStyle),
  33687. silent: true
  33688. }
  33689. ));
  33690. }, this);
  33691. }
  33692. });
  33693. var RadarSeries = SeriesModel.extend({
  33694. type: 'series.radar',
  33695. dependencies: ['radar'],
  33696. // Overwrite
  33697. init: function (option) {
  33698. RadarSeries.superApply(this, 'init', arguments);
  33699. // Enable legend selection for each data item
  33700. // Use a function instead of direct access because data reference may changed
  33701. this.legendDataProvider = function () {
  33702. return this.getRawData();
  33703. };
  33704. },
  33705. getInitialData: function (option, ecModel) {
  33706. return createListSimply(this, {
  33707. generateCoord: 'indicator_',
  33708. generateCoordCount: Infinity
  33709. });
  33710. },
  33711. formatTooltip: function (dataIndex) {
  33712. var data = this.getData();
  33713. var coordSys = this.coordinateSystem;
  33714. var indicatorAxes = coordSys.getIndicatorAxes();
  33715. var name = this.getData().getName(dataIndex);
  33716. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  33717. + map(indicatorAxes, function (axis, idx) {
  33718. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  33719. return encodeHTML(axis.name + ' : ' + val);
  33720. }).join('<br />');
  33721. },
  33722. defaultOption: {
  33723. zlevel: 0,
  33724. z: 2,
  33725. coordinateSystem: 'radar',
  33726. legendHoverLink: true,
  33727. radarIndex: 0,
  33728. lineStyle: {
  33729. width: 2,
  33730. type: 'solid'
  33731. },
  33732. label: {
  33733. position: 'top'
  33734. },
  33735. // areaStyle: {
  33736. // },
  33737. // itemStyle: {}
  33738. symbol: 'emptyCircle',
  33739. symbolSize: 4
  33740. // symbolRotate: null
  33741. }
  33742. });
  33743. function normalizeSymbolSize(symbolSize) {
  33744. if (!isArray(symbolSize)) {
  33745. symbolSize = [+symbolSize, +symbolSize];
  33746. }
  33747. return symbolSize;
  33748. }
  33749. extendChartView({
  33750. type: 'radar',
  33751. render: function (seriesModel, ecModel, api) {
  33752. var polar = seriesModel.coordinateSystem;
  33753. var group = this.group;
  33754. var data = seriesModel.getData();
  33755. var oldData = this._data;
  33756. function createSymbol$$1(data, idx) {
  33757. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  33758. var color = data.getItemVisual(idx, 'color');
  33759. if (symbolType === 'none') {
  33760. return;
  33761. }
  33762. var symbolSize = normalizeSymbolSize(
  33763. data.getItemVisual(idx, 'symbolSize')
  33764. );
  33765. var symbolPath = createSymbol(
  33766. symbolType, -1, -1, 2, 2, color
  33767. );
  33768. symbolPath.attr({
  33769. style: {
  33770. strokeNoScale: true
  33771. },
  33772. z2: 100,
  33773. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  33774. });
  33775. return symbolPath;
  33776. }
  33777. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  33778. // Simply rerender all
  33779. symbolGroup.removeAll();
  33780. for (var i = 0; i < newPoints.length - 1; i++) {
  33781. var symbolPath = createSymbol$$1(data, idx);
  33782. if (symbolPath) {
  33783. symbolPath.__dimIdx = i;
  33784. if (oldPoints[i]) {
  33785. symbolPath.attr('position', oldPoints[i]);
  33786. graphic[isInit ? 'initProps' : 'updateProps'](
  33787. symbolPath, {
  33788. position: newPoints[i]
  33789. }, seriesModel, idx
  33790. );
  33791. }
  33792. else {
  33793. symbolPath.attr('position', newPoints[i]);
  33794. }
  33795. symbolGroup.add(symbolPath);
  33796. }
  33797. }
  33798. }
  33799. function getInitialPoints(points) {
  33800. return map(points, function (pt) {
  33801. return [polar.cx, polar.cy];
  33802. });
  33803. }
  33804. data.diff(oldData)
  33805. .add(function (idx) {
  33806. var points = data.getItemLayout(idx);
  33807. if (!points) {
  33808. return;
  33809. }
  33810. var polygon = new Polygon();
  33811. var polyline = new Polyline();
  33812. var target = {
  33813. shape: {
  33814. points: points
  33815. }
  33816. };
  33817. polygon.shape.points = getInitialPoints(points);
  33818. polyline.shape.points = getInitialPoints(points);
  33819. initProps(polygon, target, seriesModel, idx);
  33820. initProps(polyline, target, seriesModel, idx);
  33821. var itemGroup = new Group();
  33822. var symbolGroup = new Group();
  33823. itemGroup.add(polyline);
  33824. itemGroup.add(polygon);
  33825. itemGroup.add(symbolGroup);
  33826. updateSymbols(
  33827. polyline.shape.points, points, symbolGroup, data, idx, true
  33828. );
  33829. data.setItemGraphicEl(idx, itemGroup);
  33830. })
  33831. .update(function (newIdx, oldIdx) {
  33832. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  33833. var polyline = itemGroup.childAt(0);
  33834. var polygon = itemGroup.childAt(1);
  33835. var symbolGroup = itemGroup.childAt(2);
  33836. var target = {
  33837. shape: {
  33838. points: data.getItemLayout(newIdx)
  33839. }
  33840. };
  33841. if (!target.shape.points) {
  33842. return;
  33843. }
  33844. updateSymbols(
  33845. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  33846. );
  33847. updateProps(polyline, target, seriesModel);
  33848. updateProps(polygon, target, seriesModel);
  33849. data.setItemGraphicEl(newIdx, itemGroup);
  33850. })
  33851. .remove(function (idx) {
  33852. group.remove(oldData.getItemGraphicEl(idx));
  33853. })
  33854. .execute();
  33855. data.eachItemGraphicEl(function (itemGroup, idx) {
  33856. var itemModel = data.getItemModel(idx);
  33857. var polyline = itemGroup.childAt(0);
  33858. var polygon = itemGroup.childAt(1);
  33859. var symbolGroup = itemGroup.childAt(2);
  33860. var color = data.getItemVisual(idx, 'color');
  33861. group.add(itemGroup);
  33862. polyline.useStyle(
  33863. defaults(
  33864. itemModel.getModel('lineStyle').getLineStyle(),
  33865. {
  33866. fill: 'none',
  33867. stroke: color
  33868. }
  33869. )
  33870. );
  33871. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  33872. var areaStyleModel = itemModel.getModel('areaStyle');
  33873. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  33874. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  33875. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  33876. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  33877. polygon.ignore = polygonIgnore;
  33878. polygon.useStyle(
  33879. defaults(
  33880. areaStyleModel.getAreaStyle(),
  33881. {
  33882. fill: color,
  33883. opacity: 0.7
  33884. }
  33885. )
  33886. );
  33887. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  33888. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  33889. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  33890. var labelModel = itemModel.getModel('label');
  33891. var labelHoverModel = itemModel.getModel('emphasis.label');
  33892. symbolGroup.eachChild(function (symbolPath) {
  33893. symbolPath.setStyle(itemStyle);
  33894. symbolPath.hoverStyle = clone(itemHoverStyle);
  33895. setLabelStyle(
  33896. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  33897. {
  33898. labelFetcher: data.hostModel,
  33899. labelDataIndex: idx,
  33900. labelDimIndex: symbolPath.__dimIdx,
  33901. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  33902. autoColor: color,
  33903. isRectText: true
  33904. }
  33905. );
  33906. });
  33907. function onEmphasis() {
  33908. polygon.attr('ignore', hoverPolygonIgnore);
  33909. }
  33910. function onNormal() {
  33911. polygon.attr('ignore', polygonIgnore);
  33912. }
  33913. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  33914. itemGroup.on('emphasis', onEmphasis)
  33915. .on('mouseover', onEmphasis)
  33916. .on('normal', onNormal)
  33917. .on('mouseout', onNormal);
  33918. setHoverStyle(itemGroup);
  33919. });
  33920. this._data = data;
  33921. },
  33922. remove: function () {
  33923. this.group.removeAll();
  33924. this._data = null;
  33925. },
  33926. dispose: function () {}
  33927. });
  33928. var radarLayout = function (ecModel) {
  33929. ecModel.eachSeriesByType('radar', function (seriesModel) {
  33930. var data = seriesModel.getData();
  33931. var points = [];
  33932. var coordSys = seriesModel.coordinateSystem;
  33933. if (!coordSys) {
  33934. return;
  33935. }
  33936. function pointsConverter(val, idx) {
  33937. points[idx] = points[idx] || [];
  33938. points[idx][i] = coordSys.dataToPoint(val, i);
  33939. }
  33940. var axes = coordSys.getIndicatorAxes();
  33941. for (var i = 0; i < coordSys.getIndicatorAxes().length; i++) {
  33942. data.each(data.mapDimension(axes[i].dim), pointsConverter);
  33943. }
  33944. data.each(function (idx) {
  33945. // Close polygon
  33946. points[idx][0] && points[idx].push(points[idx][0].slice());
  33947. data.setItemLayout(idx, points[idx]);
  33948. });
  33949. });
  33950. };
  33951. // Backward compat for radar chart in 2
  33952. var backwardCompat$1 = function (option) {
  33953. var polarOptArr = option.polar;
  33954. if (polarOptArr) {
  33955. if (!isArray(polarOptArr)) {
  33956. polarOptArr = [polarOptArr];
  33957. }
  33958. var polarNotRadar = [];
  33959. each$1(polarOptArr, function (polarOpt, idx) {
  33960. if (polarOpt.indicator) {
  33961. if (polarOpt.type && !polarOpt.shape) {
  33962. polarOpt.shape = polarOpt.type;
  33963. }
  33964. option.radar = option.radar || [];
  33965. if (!isArray(option.radar)) {
  33966. option.radar = [option.radar];
  33967. }
  33968. option.radar.push(polarOpt);
  33969. }
  33970. else {
  33971. polarNotRadar.push(polarOpt);
  33972. }
  33973. });
  33974. option.polar = polarNotRadar;
  33975. }
  33976. each$1(option.series, function (seriesOpt) {
  33977. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  33978. seriesOpt.radarIndex = seriesOpt.polarIndex;
  33979. }
  33980. });
  33981. };
  33982. // Must use radar component
  33983. registerVisual(dataColor('radar'));
  33984. registerVisual(visualSymbol('radar', 'circle'));
  33985. registerLayout(radarLayout);
  33986. registerProcessor(dataFilter('radar'));
  33987. registerPreprocessor(backwardCompat$1);
  33988. /**
  33989. * Simple view coordinate system
  33990. * Mapping given x, y to transformd view x, y
  33991. */
  33992. var v2ApplyTransform$1 = applyTransform;
  33993. // Dummy transform node
  33994. function TransformDummy() {
  33995. Transformable.call(this);
  33996. }
  33997. mixin(TransformDummy, Transformable);
  33998. function View(name) {
  33999. /**
  34000. * @type {string}
  34001. */
  34002. this.name = name;
  34003. /**
  34004. * @type {Object}
  34005. */
  34006. this.zoomLimit;
  34007. Transformable.call(this);
  34008. this._roamTransformable = new TransformDummy();
  34009. this._rawTransformable = new TransformDummy();
  34010. this._center;
  34011. this._zoom;
  34012. }
  34013. View.prototype = {
  34014. constructor: View,
  34015. type: 'view',
  34016. /**
  34017. * @param {Array.<string>}
  34018. * @readOnly
  34019. */
  34020. dimensions: ['x', 'y'],
  34021. /**
  34022. * Set bounding rect
  34023. * @param {number} x
  34024. * @param {number} y
  34025. * @param {number} width
  34026. * @param {number} height
  34027. */
  34028. // PENDING to getRect
  34029. setBoundingRect: function (x, y, width, height) {
  34030. this._rect = new BoundingRect(x, y, width, height);
  34031. return this._rect;
  34032. },
  34033. /**
  34034. * @return {module:zrender/core/BoundingRect}
  34035. */
  34036. // PENDING to getRect
  34037. getBoundingRect: function () {
  34038. return this._rect;
  34039. },
  34040. /**
  34041. * @param {number} x
  34042. * @param {number} y
  34043. * @param {number} width
  34044. * @param {number} height
  34045. */
  34046. setViewRect: function (x, y, width, height) {
  34047. this.transformTo(x, y, width, height);
  34048. this._viewRect = new BoundingRect(x, y, width, height);
  34049. },
  34050. /**
  34051. * Transformed to particular position and size
  34052. * @param {number} x
  34053. * @param {number} y
  34054. * @param {number} width
  34055. * @param {number} height
  34056. */
  34057. transformTo: function (x, y, width, height) {
  34058. var rect = this.getBoundingRect();
  34059. var rawTransform = this._rawTransformable;
  34060. rawTransform.transform = rect.calculateTransform(
  34061. new BoundingRect(x, y, width, height)
  34062. );
  34063. rawTransform.decomposeTransform();
  34064. this._updateTransform();
  34065. },
  34066. /**
  34067. * Set center of view
  34068. * @param {Array.<number>} [centerCoord]
  34069. */
  34070. setCenter: function (centerCoord) {
  34071. if (!centerCoord) {
  34072. return;
  34073. }
  34074. this._center = centerCoord;
  34075. this._updateCenterAndZoom();
  34076. },
  34077. /**
  34078. * @param {number} zoom
  34079. */
  34080. setZoom: function (zoom) {
  34081. zoom = zoom || 1;
  34082. var zoomLimit = this.zoomLimit;
  34083. if (zoomLimit) {
  34084. if (zoomLimit.max != null) {
  34085. zoom = Math.min(zoomLimit.max, zoom);
  34086. }
  34087. if (zoomLimit.min != null) {
  34088. zoom = Math.max(zoomLimit.min, zoom);
  34089. }
  34090. }
  34091. this._zoom = zoom;
  34092. this._updateCenterAndZoom();
  34093. },
  34094. /**
  34095. * Get default center without roam
  34096. */
  34097. getDefaultCenter: function () {
  34098. // Rect before any transform
  34099. var rawRect = this.getBoundingRect();
  34100. var cx = rawRect.x + rawRect.width / 2;
  34101. var cy = rawRect.y + rawRect.height / 2;
  34102. return [cx, cy];
  34103. },
  34104. getCenter: function () {
  34105. return this._center || this.getDefaultCenter();
  34106. },
  34107. getZoom: function () {
  34108. return this._zoom || 1;
  34109. },
  34110. /**
  34111. * @return {Array.<number}
  34112. */
  34113. getRoamTransform: function () {
  34114. return this._roamTransformable.getLocalTransform();
  34115. },
  34116. /**
  34117. * Remove roam
  34118. */
  34119. _updateCenterAndZoom: function () {
  34120. // Must update after view transform updated
  34121. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  34122. var roamTransform = this._roamTransformable;
  34123. var defaultCenter = this.getDefaultCenter();
  34124. var center = this.getCenter();
  34125. var zoom = this.getZoom();
  34126. center = applyTransform([], center, rawTransformMatrix);
  34127. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  34128. roamTransform.origin = center;
  34129. roamTransform.position = [
  34130. defaultCenter[0] - center[0],
  34131. defaultCenter[1] - center[1]
  34132. ];
  34133. roamTransform.scale = [zoom, zoom];
  34134. this._updateTransform();
  34135. },
  34136. /**
  34137. * Update transform from roam and mapLocation
  34138. * @private
  34139. */
  34140. _updateTransform: function () {
  34141. var roamTransformable = this._roamTransformable;
  34142. var rawTransformable = this._rawTransformable;
  34143. rawTransformable.parent = roamTransformable;
  34144. roamTransformable.updateTransform();
  34145. rawTransformable.updateTransform();
  34146. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  34147. this._rawTransform = rawTransformable.getLocalTransform();
  34148. this.invTransform = this.invTransform || [];
  34149. invert(this.invTransform, this.transform);
  34150. this.decomposeTransform();
  34151. },
  34152. /**
  34153. * @return {module:zrender/core/BoundingRect}
  34154. */
  34155. getViewRect: function () {
  34156. return this._viewRect;
  34157. },
  34158. /**
  34159. * Get view rect after roam transform
  34160. * @return {module:zrender/core/BoundingRect}
  34161. */
  34162. getViewRectAfterRoam: function () {
  34163. var rect = this.getBoundingRect().clone();
  34164. rect.applyTransform(this.transform);
  34165. return rect;
  34166. },
  34167. /**
  34168. * Convert a single (lon, lat) data item to (x, y) point.
  34169. * @param {Array.<number>} data
  34170. * @param {boolean} noRoam
  34171. * @param {Array.<number>} [out]
  34172. * @return {Array.<number>}
  34173. */
  34174. dataToPoint: function (data, noRoam, out) {
  34175. var transform = noRoam ? this._rawTransform : this.transform;
  34176. out = out || [];
  34177. return transform
  34178. ? v2ApplyTransform$1(out, data, transform)
  34179. : copy(out, data);
  34180. },
  34181. /**
  34182. * Convert a (x, y) point to (lon, lat) data
  34183. * @param {Array.<number>} point
  34184. * @return {Array.<number>}
  34185. */
  34186. pointToData: function (point) {
  34187. var invTransform = this.invTransform;
  34188. return invTransform
  34189. ? v2ApplyTransform$1([], point, invTransform)
  34190. : [point[0], point[1]];
  34191. },
  34192. /**
  34193. * @implements
  34194. * see {module:echarts/CoodinateSystem}
  34195. */
  34196. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  34197. /**
  34198. * @implements
  34199. * see {module:echarts/CoodinateSystem}
  34200. */
  34201. convertFromPixel: curry(doConvert$1, 'pointToData'),
  34202. /**
  34203. * @implements
  34204. * see {module:echarts/CoodinateSystem}
  34205. */
  34206. containPoint: function (point) {
  34207. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  34208. }
  34209. /**
  34210. * @return {number}
  34211. */
  34212. // getScalarScale: function () {
  34213. // // Use determinant square root of transform to mutiply scalar
  34214. // var m = this.transform;
  34215. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  34216. // return det;
  34217. // }
  34218. };
  34219. mixin(View, Transformable);
  34220. function doConvert$1(methodName, ecModel, finder, value) {
  34221. var seriesModel = finder.seriesModel;
  34222. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  34223. return coordSys === this ? coordSys[methodName](value) : null;
  34224. }
  34225. // Fix for 南海诸岛
  34226. var geoCoord = [126, 25];
  34227. var points$1 = [
  34228. [[0,3.5],[7,11.2],[15,11.9],[30,7],[42,0.7],[52,0.7],
  34229. [56,7.7],[59,0.7],[64,0.7],[64,0],[5,0],[0,3.5]],
  34230. [[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],
  34231. [[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],
  34232. [[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],
  34233. [[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],
  34234. [[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],
  34235. [[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],
  34236. [[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],
  34237. [[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],
  34238. [[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],
  34239. [[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],
  34240. [[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],
  34241. [1,92.4],[1,3.5],[0,3.5]]
  34242. ];
  34243. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  34244. for (var k = 0; k < points$1[i$1].length; k++) {
  34245. points$1[i$1][k][0] /= 10.5;
  34246. points$1[i$1][k][1] /= -10.5 / 0.75;
  34247. points$1[i$1][k][0] += geoCoord[0];
  34248. points$1[i$1][k][1] += geoCoord[1];
  34249. }
  34250. }
  34251. var fixNanhai = function (geo) {
  34252. if (geo.map === 'china') {
  34253. geo.regions.push(new Region(
  34254. '南海诸岛',
  34255. map(points$1, function (exterior) {
  34256. return {
  34257. type: 'polygon',
  34258. exterior: exterior
  34259. };
  34260. }), geoCoord
  34261. ));
  34262. }
  34263. };
  34264. var coordsOffsetMap = {
  34265. '南海诸岛' : [32, 80],
  34266. // 全国
  34267. '广东': [0, -10],
  34268. '香港': [10, 5],
  34269. '澳门': [-10, 10],
  34270. //'北京': [-10, 0],
  34271. '天津': [5, 5]
  34272. };
  34273. var fixTextCoord = function (geo) {
  34274. each$1(geo.regions, function (region) {
  34275. var coordFix = coordsOffsetMap[region.name];
  34276. if (coordFix) {
  34277. var cp = region.center;
  34278. cp[0] += coordFix[0] / 10.5;
  34279. cp[1] += -coordFix[1] / (10.5 / 0.75);
  34280. }
  34281. });
  34282. };
  34283. var geoCoordMap = {
  34284. 'Russia': [100, 60],
  34285. 'United States': [-99, 38],
  34286. 'United States of America': [-99, 38]
  34287. };
  34288. var fixGeoCoord = function (geo) {
  34289. each$1(geo.regions, function (region) {
  34290. var geoCoord = geoCoordMap[region.name];
  34291. if (geoCoord) {
  34292. var cp = region.center;
  34293. cp[0] = geoCoord[0];
  34294. cp[1] = geoCoord[1];
  34295. }
  34296. });
  34297. };
  34298. // Fix for 钓鱼岛
  34299. // var Region = require('../Region');
  34300. // var zrUtil = require('zrender/src/core/util');
  34301. // var geoCoord = [126, 25];
  34302. var points$2 = [
  34303. [
  34304. [123.45165252685547, 25.73527164402261],
  34305. [123.49731445312499, 25.73527164402261],
  34306. [123.49731445312499, 25.750734064600884],
  34307. [123.45165252685547, 25.750734064600884],
  34308. [123.45165252685547, 25.73527164402261]
  34309. ]
  34310. ];
  34311. var fixDiaoyuIsland = function (geo) {
  34312. if (geo.map === 'china') {
  34313. for (var i = 0, len = geo.regions.length; i < len; ++i) {
  34314. if (geo.regions[i].name === '台湾') {
  34315. geo.regions[i].geometries.push({
  34316. type: 'polygon',
  34317. exterior: points$2[0]
  34318. });
  34319. }
  34320. }
  34321. }
  34322. };
  34323. // Geo fix functions
  34324. var geoFixFuncs = [
  34325. fixNanhai,
  34326. fixTextCoord,
  34327. fixGeoCoord,
  34328. fixDiaoyuIsland
  34329. ];
  34330. /**
  34331. * [Geo description]
  34332. * @param {string} name Geo name
  34333. * @param {string} map Map type
  34334. * @param {Object} geoJson
  34335. * @param {Object} [specialAreas]
  34336. * Specify the positioned areas by left, top, width, height
  34337. * @param {Object.<string, string>} [nameMap]
  34338. * Specify name alias
  34339. */
  34340. function Geo(name, map$$1, geoJson, specialAreas, nameMap) {
  34341. View.call(this, name);
  34342. /**
  34343. * Map type
  34344. * @type {string}
  34345. */
  34346. this.map = map$$1;
  34347. this._nameCoordMap = createHashMap();
  34348. this.loadGeoJson(geoJson, specialAreas, nameMap);
  34349. }
  34350. Geo.prototype = {
  34351. constructor: Geo,
  34352. type: 'geo',
  34353. /**
  34354. * @param {Array.<string>}
  34355. * @readOnly
  34356. */
  34357. dimensions: ['lng', 'lat'],
  34358. /**
  34359. * If contain given lng,lat coord
  34360. * @param {Array.<number>}
  34361. * @readOnly
  34362. */
  34363. containCoord: function (coord) {
  34364. var regions = this.regions;
  34365. for (var i = 0; i < regions.length; i++) {
  34366. if (regions[i].contain(coord)) {
  34367. return true;
  34368. }
  34369. }
  34370. return false;
  34371. },
  34372. /**
  34373. * @param {Object} geoJson
  34374. * @param {Object} [specialAreas]
  34375. * Specify the positioned areas by left, top, width, height
  34376. * @param {Object.<string, string>} [nameMap]
  34377. * Specify name alias
  34378. */
  34379. loadGeoJson: function (geoJson, specialAreas, nameMap) {
  34380. // https://jsperf.com/try-catch-performance-overhead
  34381. try {
  34382. this.regions = geoJson ? parseGeoJson$1(geoJson) : [];
  34383. }
  34384. catch (e) {
  34385. throw 'Invalid geoJson format\n' + e.message;
  34386. }
  34387. specialAreas = specialAreas || {};
  34388. nameMap = nameMap || {};
  34389. var regions = this.regions;
  34390. var regionsMap = createHashMap();
  34391. for (var i = 0; i < regions.length; i++) {
  34392. var regionName = regions[i].name;
  34393. // Try use the alias in nameMap
  34394. regionName = nameMap.hasOwnProperty(regionName) ? nameMap[regionName] : regionName;
  34395. regions[i].name = regionName;
  34396. regionsMap.set(regionName, regions[i]);
  34397. // Add geoJson
  34398. this.addGeoCoord(regionName, regions[i].center);
  34399. // Some area like Alaska in USA map needs to be tansformed
  34400. // to look better
  34401. var specialArea = specialAreas[regionName];
  34402. if (specialArea) {
  34403. regions[i].transformTo(
  34404. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  34405. );
  34406. }
  34407. }
  34408. this._regionsMap = regionsMap;
  34409. this._rect = null;
  34410. each$1(geoFixFuncs, function (fixFunc) {
  34411. fixFunc(this);
  34412. }, this);
  34413. },
  34414. // Overwrite
  34415. transformTo: function (x, y, width, height) {
  34416. var rect = this.getBoundingRect();
  34417. rect = rect.clone();
  34418. // Longitute is inverted
  34419. rect.y = -rect.y - rect.height;
  34420. var rawTransformable = this._rawTransformable;
  34421. rawTransformable.transform = rect.calculateTransform(
  34422. new BoundingRect(x, y, width, height)
  34423. );
  34424. rawTransformable.decomposeTransform();
  34425. var scale = rawTransformable.scale;
  34426. scale[1] = -scale[1];
  34427. rawTransformable.updateTransform();
  34428. this._updateTransform();
  34429. },
  34430. /**
  34431. * @param {string} name
  34432. * @return {module:echarts/coord/geo/Region}
  34433. */
  34434. getRegion: function (name) {
  34435. return this._regionsMap.get(name);
  34436. },
  34437. getRegionByCoord: function (coord) {
  34438. var regions = this.regions;
  34439. for (var i = 0; i < regions.length; i++) {
  34440. if (regions[i].contain(coord)) {
  34441. return regions[i];
  34442. }
  34443. }
  34444. },
  34445. /**
  34446. * Add geoCoord for indexing by name
  34447. * @param {string} name
  34448. * @param {Array.<number>} geoCoord
  34449. */
  34450. addGeoCoord: function (name, geoCoord) {
  34451. this._nameCoordMap.set(name, geoCoord);
  34452. },
  34453. /**
  34454. * Get geoCoord by name
  34455. * @param {string} name
  34456. * @return {Array.<number>}
  34457. */
  34458. getGeoCoord: function (name) {
  34459. return this._nameCoordMap.get(name);
  34460. },
  34461. // Overwrite
  34462. getBoundingRect: function () {
  34463. if (this._rect) {
  34464. return this._rect;
  34465. }
  34466. var rect;
  34467. var regions = this.regions;
  34468. for (var i = 0; i < regions.length; i++) {
  34469. var regionRect = regions[i].getBoundingRect();
  34470. rect = rect || regionRect.clone();
  34471. rect.union(regionRect);
  34472. }
  34473. // FIXME Always return new ?
  34474. return (this._rect = rect || new BoundingRect(0, 0, 0, 0));
  34475. },
  34476. /**
  34477. * @param {string|Array.<number>} data
  34478. * @param {boolean} noRoam
  34479. * @param {Array.<number>} [out]
  34480. * @return {Array.<number>}
  34481. */
  34482. dataToPoint: function (data, noRoam, out) {
  34483. if (typeof data === 'string') {
  34484. // Map area name to geoCoord
  34485. data = this.getGeoCoord(data);
  34486. }
  34487. if (data) {
  34488. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  34489. }
  34490. },
  34491. /**
  34492. * @inheritDoc
  34493. */
  34494. convertToPixel: curry(doConvert, 'dataToPoint'),
  34495. /**
  34496. * @inheritDoc
  34497. */
  34498. convertFromPixel: curry(doConvert, 'pointToData')
  34499. };
  34500. mixin(Geo, View);
  34501. function doConvert(methodName, ecModel, finder, value) {
  34502. var geoModel = finder.geoModel;
  34503. var seriesModel = finder.seriesModel;
  34504. var coordSys = geoModel
  34505. ? geoModel.coordinateSystem
  34506. : seriesModel
  34507. ? (
  34508. seriesModel.coordinateSystem // For map.
  34509. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  34510. )
  34511. : null;
  34512. return coordSys === this ? coordSys[methodName](value) : null;
  34513. }
  34514. /**
  34515. * Resize method bound to the geo
  34516. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  34517. * @param {module:echarts/ExtensionAPI} api
  34518. */
  34519. function resizeGeo(geoModel, api) {
  34520. var boundingCoords = geoModel.get('boundingCoords');
  34521. if (boundingCoords != null) {
  34522. var leftTop = boundingCoords[0];
  34523. var rightBottom = boundingCoords[1];
  34524. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  34525. if (__DEV__) {
  34526. console.error('Invalid boundingCoords');
  34527. }
  34528. }
  34529. else {
  34530. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  34531. }
  34532. }
  34533. var rect = this.getBoundingRect();
  34534. var boxLayoutOption;
  34535. var center = geoModel.get('layoutCenter');
  34536. var size = geoModel.get('layoutSize');
  34537. var viewWidth = api.getWidth();
  34538. var viewHeight = api.getHeight();
  34539. var aspectScale = geoModel.get('aspectScale') || 0.75;
  34540. var aspect = rect.width / rect.height * aspectScale;
  34541. var useCenterAndSize = false;
  34542. if (center && size) {
  34543. center = [
  34544. parsePercent$1(center[0], viewWidth),
  34545. parsePercent$1(center[1], viewHeight)
  34546. ];
  34547. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  34548. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  34549. useCenterAndSize = true;
  34550. }
  34551. else {
  34552. if (__DEV__) {
  34553. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  34554. }
  34555. }
  34556. }
  34557. var viewRect;
  34558. if (useCenterAndSize) {
  34559. var viewRect = {};
  34560. if (aspect > 1) {
  34561. // Width is same with size
  34562. viewRect.width = size;
  34563. viewRect.height = size / aspect;
  34564. }
  34565. else {
  34566. viewRect.height = size;
  34567. viewRect.width = size * aspect;
  34568. }
  34569. viewRect.y = center[1] - viewRect.height / 2;
  34570. viewRect.x = center[0] - viewRect.width / 2;
  34571. }
  34572. else {
  34573. // Use left/top/width/height
  34574. boxLayoutOption = geoModel.getBoxLayoutParams();
  34575. // 0.75 rate
  34576. boxLayoutOption.aspect = aspect;
  34577. viewRect = getLayoutRect(boxLayoutOption, {
  34578. width: viewWidth,
  34579. height: viewHeight
  34580. });
  34581. }
  34582. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  34583. this.setCenter(geoModel.get('center'));
  34584. this.setZoom(geoModel.get('zoom'));
  34585. }
  34586. /**
  34587. * @param {module:echarts/coord/Geo} geo
  34588. * @param {module:echarts/model/Model} model
  34589. * @inner
  34590. */
  34591. function setGeoCoords(geo, model) {
  34592. each$1(model.get('geoCoord'), function (geoCoord, name) {
  34593. geo.addGeoCoord(name, geoCoord);
  34594. });
  34595. }
  34596. if (__DEV__) {
  34597. var mapNotExistsError = function (name) {
  34598. console.error('Map ' + name + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html');
  34599. };
  34600. }
  34601. var geoCreator = {
  34602. // For deciding which dimensions to use when creating list data
  34603. dimensions: Geo.prototype.dimensions,
  34604. create: function (ecModel, api) {
  34605. var geoList = [];
  34606. // FIXME Create each time may be slow
  34607. ecModel.eachComponent('geo', function (geoModel, idx) {
  34608. var name = geoModel.get('map');
  34609. var mapData = getMap(name);
  34610. if (__DEV__) {
  34611. if (!mapData) {
  34612. mapNotExistsError(name);
  34613. }
  34614. }
  34615. var geo = new Geo(
  34616. name + idx, name,
  34617. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  34618. geoModel.get('nameMap')
  34619. );
  34620. geo.zoomLimit = geoModel.get('scaleLimit');
  34621. geoList.push(geo);
  34622. setGeoCoords(geo, geoModel);
  34623. geoModel.coordinateSystem = geo;
  34624. geo.model = geoModel;
  34625. // Inject resize method
  34626. geo.resize = resizeGeo;
  34627. geo.resize(geoModel, api);
  34628. });
  34629. ecModel.eachSeries(function (seriesModel) {
  34630. var coordSys = seriesModel.get('coordinateSystem');
  34631. if (coordSys === 'geo') {
  34632. var geoIndex = seriesModel.get('geoIndex') || 0;
  34633. seriesModel.coordinateSystem = geoList[geoIndex];
  34634. }
  34635. });
  34636. // If has map series
  34637. var mapModelGroupBySeries = {};
  34638. ecModel.eachSeriesByType('map', function (seriesModel) {
  34639. if (!seriesModel.getHostGeoModel()) {
  34640. var mapType = seriesModel.getMapType();
  34641. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  34642. mapModelGroupBySeries[mapType].push(seriesModel);
  34643. }
  34644. });
  34645. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  34646. var mapData = getMap(mapType);
  34647. if (__DEV__) {
  34648. if (!mapData) {
  34649. mapNotExistsError(mapSeries[0].get('map'));
  34650. }
  34651. }
  34652. var nameMapList = map(mapSeries, function (singleMapSeries) {
  34653. return singleMapSeries.get('nameMap');
  34654. });
  34655. var geo = new Geo(
  34656. mapType, mapType,
  34657. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  34658. mergeAll(nameMapList)
  34659. );
  34660. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  34661. return singleMapSeries.get('scaleLimit');
  34662. }));
  34663. geoList.push(geo);
  34664. // Inject resize method
  34665. geo.resize = resizeGeo;
  34666. geo.resize(mapSeries[0], api);
  34667. each$1(mapSeries, function (singleMapSeries) {
  34668. singleMapSeries.coordinateSystem = geo;
  34669. setGeoCoords(geo, singleMapSeries);
  34670. });
  34671. });
  34672. return geoList;
  34673. },
  34674. /**
  34675. * Fill given regions array
  34676. * @param {Array.<Object>} originRegionArr
  34677. * @param {string} mapName
  34678. * @param {Object} [nameMap]
  34679. * @return {Array}
  34680. */
  34681. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  34682. // Not use the original
  34683. var regionsArr = (originRegionArr || []).slice();
  34684. nameMap = nameMap || {};
  34685. var map$$1 = getMap(mapName);
  34686. var geoJson = map$$1 && map$$1.geoJson;
  34687. if (!geoJson) {
  34688. if (__DEV__) {
  34689. mapNotExistsError(mapName);
  34690. }
  34691. return originRegionArr;
  34692. }
  34693. var dataNameMap = createHashMap();
  34694. var features = geoJson.features;
  34695. for (var i = 0; i < regionsArr.length; i++) {
  34696. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  34697. }
  34698. for (var i = 0; i < features.length; i++) {
  34699. var name = features[i].properties.name;
  34700. if (!dataNameMap.get(name)) {
  34701. if (nameMap.hasOwnProperty(name)) {
  34702. name = nameMap[name];
  34703. }
  34704. regionsArr.push({
  34705. name: name
  34706. });
  34707. }
  34708. }
  34709. return regionsArr;
  34710. }
  34711. };
  34712. registerCoordinateSystem('geo', geoCreator);
  34713. var MapSeries = SeriesModel.extend({
  34714. type: 'series.map',
  34715. dependencies: ['geo'],
  34716. layoutMode: 'box',
  34717. /**
  34718. * Only first map series of same mapType will drawMap
  34719. * @type {boolean}
  34720. */
  34721. needsDrawMap: false,
  34722. /**
  34723. * Group of all map series with same mapType
  34724. * @type {boolean}
  34725. */
  34726. seriesGroup: [],
  34727. init: function (option) {
  34728. // this._fillOption(option, this.getMapType());
  34729. // this.option = option;
  34730. MapSeries.superApply(this, 'init', arguments);
  34731. this.updateSelectedMap(this._createSelectableList());
  34732. },
  34733. getInitialData: function (option) {
  34734. return createListSimply(this, ['value']);
  34735. },
  34736. mergeOption: function (newOption) {
  34737. // this._fillOption(newOption, this.getMapType());
  34738. MapSeries.superApply(this, 'mergeOption', arguments);
  34739. this.updateSelectedMap(this._createSelectableList());
  34740. },
  34741. _createSelectableList: function () {
  34742. var data = this.getRawData();
  34743. var valueDim = data.mapDimension('value');
  34744. var targetList = [];
  34745. for (var i = 0, len = data.count(); i < len; i++) {
  34746. targetList.push({
  34747. name: data.getName(i),
  34748. value: data.get(valueDim, i),
  34749. selected: retrieveRawAttr(data, i, 'selected')
  34750. });
  34751. }
  34752. targetList = geoCreator.getFilledRegions(targetList, this.getMapType(), this.option.nameMap);
  34753. return targetList;
  34754. },
  34755. /**
  34756. * If no host geo model, return null, which means using a
  34757. * inner exclusive geo model.
  34758. */
  34759. getHostGeoModel: function () {
  34760. var geoIndex = this.option.geoIndex;
  34761. return geoIndex != null
  34762. ? this.dependentModels.geo[geoIndex]
  34763. : null;
  34764. },
  34765. getMapType: function () {
  34766. return (this.getHostGeoModel() || this).option.map;
  34767. },
  34768. _fillOption: function (option, mapName) {
  34769. // Shallow clone
  34770. // option = zrUtil.extend({}, option);
  34771. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  34772. // return option;
  34773. },
  34774. getRawValue: function (dataIndex) {
  34775. // Use value stored in data instead because it is calculated from multiple series
  34776. // FIXME Provide all value of multiple series ?
  34777. var data = this.getData();
  34778. return data.get(data.mapDimension('value'), dataIndex);
  34779. },
  34780. /**
  34781. * Get model of region
  34782. * @param {string} name
  34783. * @return {module:echarts/model/Model}
  34784. */
  34785. getRegionModel: function (regionName) {
  34786. var data = this.getData();
  34787. return data.getItemModel(data.indexOfName(regionName));
  34788. },
  34789. /**
  34790. * Map tooltip formatter
  34791. *
  34792. * @param {number} dataIndex
  34793. */
  34794. formatTooltip: function (dataIndex) {
  34795. // FIXME orignalData and data is a bit confusing
  34796. var data = this.getData();
  34797. var formattedValue = addCommas(this.getRawValue(dataIndex));
  34798. var name = data.getName(dataIndex);
  34799. var seriesGroup = this.seriesGroup;
  34800. var seriesNames = [];
  34801. for (var i = 0; i < seriesGroup.length; i++) {
  34802. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  34803. var valueDim = data.mapDimension('value');
  34804. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  34805. seriesNames.push(
  34806. encodeHTML(seriesGroup[i].name)
  34807. );
  34808. }
  34809. }
  34810. return seriesNames.join(', ') + '<br />'
  34811. + encodeHTML(name + ' : ' + formattedValue);
  34812. },
  34813. /**
  34814. * @implement
  34815. */
  34816. getTooltipPosition: function (dataIndex) {
  34817. if (dataIndex != null) {
  34818. var name = this.getData().getName(dataIndex);
  34819. var geo = this.coordinateSystem;
  34820. var region = geo.getRegion(name);
  34821. return region && geo.dataToPoint(region.center);
  34822. }
  34823. },
  34824. setZoom: function (zoom) {
  34825. this.option.zoom = zoom;
  34826. },
  34827. setCenter: function (center) {
  34828. this.option.center = center;
  34829. },
  34830. defaultOption: {
  34831. // 一级层叠
  34832. zlevel: 0,
  34833. // 二级层叠
  34834. z: 2,
  34835. coordinateSystem: 'geo',
  34836. // map should be explicitly specified since ec3.
  34837. map: '',
  34838. // If `geoIndex` is not specified, a exclusive geo will be
  34839. // created. Otherwise use the specified geo component, and
  34840. // `map` and `mapType` are ignored.
  34841. // geoIndex: 0,
  34842. // 'center' | 'left' | 'right' | 'x%' | {number}
  34843. left: 'center',
  34844. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  34845. top: 'center',
  34846. // right
  34847. // bottom
  34848. // width:
  34849. // height
  34850. // Aspect is width / height. Inited to be geoJson bbox aspect
  34851. // This parameter is used for scale this aspect
  34852. aspectScale: 0.75,
  34853. ///// Layout with center and size
  34854. // If you wan't to put map in a fixed size box with right aspect ratio
  34855. // This two properties may more conveninet
  34856. // layoutCenter: [50%, 50%]
  34857. // layoutSize: 100
  34858. // 数值合并方式,默认加和,可选为:
  34859. // 'sum' | 'average' | 'max' | 'min'
  34860. // mapValueCalculation: 'sum',
  34861. // 地图数值计算结果小数精度
  34862. // mapValuePrecision: 0,
  34863. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  34864. showLegendSymbol: true,
  34865. // 选择模式,默认关闭,可选single,multiple
  34866. // selectedMode: false,
  34867. dataRangeHoverLink: true,
  34868. // 是否开启缩放及漫游模式
  34869. // roam: false,
  34870. // Define left-top, right-bottom coords to control view
  34871. // For example, [ [180, 90], [-180, -90] ],
  34872. // higher priority than center and zoom
  34873. boundingCoords: null,
  34874. // Default on center of map
  34875. center: null,
  34876. zoom: 1,
  34877. scaleLimit: null,
  34878. label: {
  34879. show: false,
  34880. color: '#000'
  34881. },
  34882. // scaleLimit: null,
  34883. itemStyle: {
  34884. borderWidth: 0.5,
  34885. borderColor: '#444',
  34886. areaColor: '#eee'
  34887. },
  34888. emphasis: {
  34889. label: {
  34890. show: true,
  34891. color: 'rgb(100,0,0)'
  34892. },
  34893. itemStyle: {
  34894. areaColor: 'rgba(255,215,0,0.8)'
  34895. }
  34896. }
  34897. }
  34898. });
  34899. mixin(MapSeries, selectableMixin);
  34900. var ATTR = '\0_ec_interaction_mutex';
  34901. function take(zr, resourceKey, userKey) {
  34902. var store = getStore(zr);
  34903. store[resourceKey] = userKey;
  34904. }
  34905. function release(zr, resourceKey, userKey) {
  34906. var store = getStore(zr);
  34907. var uKey = store[resourceKey];
  34908. if (uKey === userKey) {
  34909. store[resourceKey] = null;
  34910. }
  34911. }
  34912. function isTaken(zr, resourceKey) {
  34913. return !!getStore(zr)[resourceKey];
  34914. }
  34915. function getStore(zr) {
  34916. return zr[ATTR] || (zr[ATTR] = {});
  34917. }
  34918. /**
  34919. * payload: {
  34920. * type: 'takeGlobalCursor',
  34921. * key: 'dataZoomSelect', or 'brush', or ...,
  34922. * If no userKey, release global cursor.
  34923. * }
  34924. */
  34925. registerAction(
  34926. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  34927. function () {}
  34928. );
  34929. /**
  34930. * @alias module:echarts/component/helper/RoamController
  34931. * @constructor
  34932. * @mixin {module:zrender/mixin/Eventful}
  34933. *
  34934. * @param {module:zrender/zrender~ZRender} zr
  34935. */
  34936. function RoamController(zr) {
  34937. /**
  34938. * @type {Function}
  34939. */
  34940. this.pointerChecker;
  34941. /**
  34942. * @type {module:zrender}
  34943. */
  34944. this._zr = zr;
  34945. /**
  34946. * @type {Object}
  34947. */
  34948. this._opt = {};
  34949. // Avoid two roamController bind the same handler
  34950. var bind$$1 = bind;
  34951. var mousedownHandler = bind$$1(mousedown, this);
  34952. var mousemoveHandler = bind$$1(mousemove, this);
  34953. var mouseupHandler = bind$$1(mouseup, this);
  34954. var mousewheelHandler = bind$$1(mousewheel, this);
  34955. var pinchHandler = bind$$1(pinch, this);
  34956. Eventful.call(this);
  34957. /**
  34958. * @param {Function} pointerChecker
  34959. * input: x, y
  34960. * output: boolean
  34961. */
  34962. this.setPointerChecker = function (pointerChecker) {
  34963. this.pointerChecker = pointerChecker;
  34964. };
  34965. /**
  34966. * Notice: only enable needed types. For example, if 'zoom'
  34967. * is not needed, 'zoom' should not be enabled, otherwise
  34968. * default mousewheel behaviour (scroll page) will be disabled.
  34969. *
  34970. * @param {boolean|string} [controlType=true] Specify the control type,
  34971. * which can be null/undefined or true/false
  34972. * or 'pan/move' or 'zoom'/'scale'
  34973. * @param {Object} [opt]
  34974. * @param {Object} [opt.zoomOnMouseWheel=true]
  34975. * @param {Object} [opt.moveOnMouseMove=true]
  34976. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  34977. */
  34978. this.enable = function (controlType, opt) {
  34979. // Disable previous first
  34980. this.disable();
  34981. this._opt = defaults(clone(opt) || {}, {
  34982. zoomOnMouseWheel: true,
  34983. moveOnMouseMove: true,
  34984. preventDefaultMouseMove: true
  34985. });
  34986. if (controlType == null) {
  34987. controlType = true;
  34988. }
  34989. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  34990. zr.on('mousedown', mousedownHandler);
  34991. zr.on('mousemove', mousemoveHandler);
  34992. zr.on('mouseup', mouseupHandler);
  34993. }
  34994. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  34995. zr.on('mousewheel', mousewheelHandler);
  34996. zr.on('pinch', pinchHandler);
  34997. }
  34998. };
  34999. this.disable = function () {
  35000. zr.off('mousedown', mousedownHandler);
  35001. zr.off('mousemove', mousemoveHandler);
  35002. zr.off('mouseup', mouseupHandler);
  35003. zr.off('mousewheel', mousewheelHandler);
  35004. zr.off('pinch', pinchHandler);
  35005. };
  35006. this.dispose = this.disable;
  35007. this.isDragging = function () {
  35008. return this._dragging;
  35009. };
  35010. this.isPinching = function () {
  35011. return this._pinching;
  35012. };
  35013. }
  35014. mixin(RoamController, Eventful);
  35015. function mousedown(e) {
  35016. if (notLeftMouse(e)
  35017. || (e.target && e.target.draggable)
  35018. ) {
  35019. return;
  35020. }
  35021. var x = e.offsetX;
  35022. var y = e.offsetY;
  35023. // Only check on mosedown, but not mousemove.
  35024. // Mouse can be out of target when mouse moving.
  35025. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  35026. this._x = x;
  35027. this._y = y;
  35028. this._dragging = true;
  35029. }
  35030. }
  35031. function mousemove(e) {
  35032. if (notLeftMouse(e)
  35033. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  35034. || !this._dragging
  35035. || e.gestureEvent === 'pinch'
  35036. || isTaken(this._zr, 'globalPan')
  35037. ) {
  35038. return;
  35039. }
  35040. var x = e.offsetX;
  35041. var y = e.offsetY;
  35042. var oldX = this._x;
  35043. var oldY = this._y;
  35044. var dx = x - oldX;
  35045. var dy = y - oldY;
  35046. this._x = x;
  35047. this._y = y;
  35048. this._opt.preventDefaultMouseMove && stop(e.event);
  35049. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  35050. }
  35051. function mouseup(e) {
  35052. if (!notLeftMouse(e)) {
  35053. this._dragging = false;
  35054. }
  35055. }
  35056. function mousewheel(e) {
  35057. // wheelDelta maybe -0 in chrome mac.
  35058. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  35059. return;
  35060. }
  35061. // Convenience:
  35062. // Mac and VM Windows on Mac: scroll up: zoom out.
  35063. // Windows: scroll up: zoom in.
  35064. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  35065. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  35066. }
  35067. function pinch(e) {
  35068. if (isTaken(this._zr, 'globalPan')) {
  35069. return;
  35070. }
  35071. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  35072. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  35073. }
  35074. function zoom(e, zoomDelta, zoomX, zoomY) {
  35075. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  35076. // When mouse is out of roamController rect,
  35077. // default befavoius should not be be disabled, otherwise
  35078. // page sliding is disabled, contrary to expectation.
  35079. stop(e.event);
  35080. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  35081. }
  35082. }
  35083. function checkKeyBinding(roamController, prop, e) {
  35084. var setting = roamController._opt[prop];
  35085. return setting
  35086. && (!isString(setting) || e.event[setting + 'Key']);
  35087. }
  35088. /**
  35089. * For geo and graph.
  35090. *
  35091. * @param {Object} controllerHost
  35092. * @param {module:zrender/Element} controllerHost.target
  35093. */
  35094. function updateViewOnPan(controllerHost, dx, dy) {
  35095. var target = controllerHost.target;
  35096. var pos = target.position;
  35097. pos[0] += dx;
  35098. pos[1] += dy;
  35099. target.dirty();
  35100. }
  35101. /**
  35102. * For geo and graph.
  35103. *
  35104. * @param {Object} controllerHost
  35105. * @param {module:zrender/Element} controllerHost.target
  35106. * @param {number} controllerHost.zoom
  35107. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  35108. */
  35109. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  35110. var target = controllerHost.target;
  35111. var zoomLimit = controllerHost.zoomLimit;
  35112. var pos = target.position;
  35113. var scale = target.scale;
  35114. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  35115. newZoom *= zoomDelta;
  35116. if (zoomLimit) {
  35117. var zoomMin = zoomLimit.min || 0;
  35118. var zoomMax = zoomLimit.max || Infinity;
  35119. newZoom = Math.max(
  35120. Math.min(zoomMax, newZoom),
  35121. zoomMin
  35122. );
  35123. }
  35124. var zoomScale = newZoom / controllerHost.zoom;
  35125. controllerHost.zoom = newZoom;
  35126. // Keep the mouse center when scaling
  35127. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  35128. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  35129. scale[0] *= zoomScale;
  35130. scale[1] *= zoomScale;
  35131. target.dirty();
  35132. }
  35133. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  35134. /**
  35135. * Avoid that: mouse click on a elements that is over geo or graph,
  35136. * but roam is triggered.
  35137. */
  35138. function onIrrelevantElement(e, api, targetCoordSysModel) {
  35139. var model = api.getComponentByElement(e.topTarget);
  35140. // If model is axisModel, it works only if it is injected with coordinateSystem.
  35141. var coordSys = model && model.coordinateSystem;
  35142. return model
  35143. && model !== targetCoordSysModel
  35144. && !IRRELEVANT_EXCLUDES[model.mainType]
  35145. && (coordSys && coordSys.model !== targetCoordSysModel);
  35146. }
  35147. function getFixedItemStyle(model, scale) {
  35148. var itemStyle = model.getItemStyle();
  35149. var areaColor = model.get('areaColor');
  35150. // If user want the color not to be changed when hover,
  35151. // they should both set areaColor and color to be null.
  35152. if (areaColor != null) {
  35153. itemStyle.fill = areaColor;
  35154. }
  35155. return itemStyle;
  35156. }
  35157. function updateMapSelectHandler(mapDraw, mapOrGeoModel, group, api, fromView) {
  35158. group.off('click');
  35159. group.off('mousedown');
  35160. if (mapOrGeoModel.get('selectedMode')) {
  35161. group.on('mousedown', function () {
  35162. mapDraw._mouseDownFlag = true;
  35163. });
  35164. group.on('click', function (e) {
  35165. if (!mapDraw._mouseDownFlag) {
  35166. return;
  35167. }
  35168. mapDraw._mouseDownFlag = false;
  35169. var el = e.target;
  35170. while (!el.__regions) {
  35171. el = el.parent;
  35172. }
  35173. if (!el) {
  35174. return;
  35175. }
  35176. var action = {
  35177. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  35178. batch: map(el.__regions, function (region) {
  35179. return {
  35180. name: region.name,
  35181. from: fromView.uid
  35182. };
  35183. })
  35184. };
  35185. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  35186. api.dispatchAction(action);
  35187. updateMapSelected(mapOrGeoModel, group);
  35188. });
  35189. }
  35190. }
  35191. function updateMapSelected(mapOrGeoModel, group) {
  35192. // FIXME
  35193. group.eachChild(function (otherRegionEl) {
  35194. each$1(otherRegionEl.__regions, function (region) {
  35195. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  35196. });
  35197. });
  35198. }
  35199. /**
  35200. * @alias module:echarts/component/helper/MapDraw
  35201. * @param {module:echarts/ExtensionAPI} api
  35202. * @param {boolean} updateGroup
  35203. */
  35204. function MapDraw(api, updateGroup) {
  35205. var group = new Group();
  35206. /**
  35207. * @type {module:echarts/component/helper/RoamController}
  35208. * @private
  35209. */
  35210. this._controller = new RoamController(api.getZr());
  35211. /**
  35212. * @type {Object} {target, zoom, zoomLimit}
  35213. * @private
  35214. */
  35215. this._controllerHost = {target: updateGroup ? group : null};
  35216. /**
  35217. * @type {module:zrender/container/Group}
  35218. * @readOnly
  35219. */
  35220. this.group = group;
  35221. /**
  35222. * @type {boolean}
  35223. * @private
  35224. */
  35225. this._updateGroup = updateGroup;
  35226. /**
  35227. * This flag is used to make sure that only one among
  35228. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  35229. * action may be triggered when `pan`, which is unexpected.
  35230. * @type {booelan}
  35231. */
  35232. this._mouseDownFlag;
  35233. }
  35234. MapDraw.prototype = {
  35235. constructor: MapDraw,
  35236. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  35237. var isGeo = mapOrGeoModel.mainType === 'geo';
  35238. // Map series has data. GEO model that controlled by map series
  35239. // will be assigned with map data. Other GEO model has no data.
  35240. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  35241. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  35242. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  35243. data = mapSeries.getData();
  35244. }
  35245. });
  35246. var geo = mapOrGeoModel.coordinateSystem;
  35247. var group = this.group;
  35248. var scale = geo.scale;
  35249. var groupNewProp = {
  35250. position: geo.position,
  35251. scale: scale
  35252. };
  35253. // No animation when first draw or in action
  35254. if (!group.childAt(0) || payload) {
  35255. group.attr(groupNewProp);
  35256. }
  35257. else {
  35258. updateProps(group, groupNewProp, mapOrGeoModel);
  35259. }
  35260. group.removeAll();
  35261. var itemStyleAccessPath = ['itemStyle'];
  35262. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  35263. var labelAccessPath = ['label'];
  35264. var hoverLabelAccessPath = ['emphasis', 'label'];
  35265. var nameMap = createHashMap();
  35266. each$1(geo.regions, function (region) {
  35267. // Consider in GeoJson properties.name may be duplicated, for example,
  35268. // there is multiple region named "United Kindom" or "France" (so many
  35269. // colonies). And it is not appropriate to merge them in geo, which
  35270. // will make them share the same label and bring trouble in label
  35271. // location calculation.
  35272. var regionGroup = nameMap.get(region.name)
  35273. || nameMap.set(region.name, new Group());
  35274. var compoundPath = new CompoundPath({
  35275. shape: {
  35276. paths: []
  35277. }
  35278. });
  35279. regionGroup.add(compoundPath);
  35280. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  35281. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  35282. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  35283. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  35284. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  35285. var labelModel = regionModel.getModel(labelAccessPath);
  35286. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  35287. var dataIdx;
  35288. // Use the itemStyle in data if has data
  35289. if (data) {
  35290. dataIdx = data.indexOfName(region.name);
  35291. // Only visual color of each item will be used. It can be encoded by dataRange
  35292. // But visual color of series is used in symbol drawing
  35293. //
  35294. // Visual color for each series is for the symbol draw
  35295. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  35296. if (visualColor) {
  35297. itemStyle.fill = visualColor;
  35298. }
  35299. }
  35300. each$1(region.geometries, function (geometry) {
  35301. if (geometry.type !== 'polygon') {
  35302. return;
  35303. }
  35304. compoundPath.shape.paths.push(new Polygon({
  35305. shape: {
  35306. points: geometry.exterior
  35307. }
  35308. }));
  35309. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  35310. compoundPath.shape.paths.push(new Polygon({
  35311. shape: {
  35312. points: geometry.interiors[i]
  35313. }
  35314. }));
  35315. }
  35316. });
  35317. compoundPath.setStyle(itemStyle);
  35318. compoundPath.style.strokeNoScale = true;
  35319. compoundPath.culling = true;
  35320. // Label
  35321. var showLabel = labelModel.get('show');
  35322. var hoverShowLabel = hoverLabelModel.get('show');
  35323. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  35324. var itemLayout = data && data.getItemLayout(dataIdx);
  35325. // In the following cases label will be drawn
  35326. // 1. In map series and data value is NaN
  35327. // 2. In geo component
  35328. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  35329. if (
  35330. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  35331. || (itemLayout && itemLayout.showLabel)
  35332. ) {
  35333. var query = !isGeo ? dataIdx : region.name;
  35334. var labelFetcher;
  35335. // Consider dataIdx not found.
  35336. if (!data || dataIdx >= 0) {
  35337. labelFetcher = mapOrGeoModel;
  35338. }
  35339. var textEl = new Text({
  35340. position: region.center.slice(),
  35341. scale: [1 / scale[0], 1 / scale[1]],
  35342. z2: 10,
  35343. silent: true
  35344. });
  35345. setLabelStyle(
  35346. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  35347. {
  35348. labelFetcher: labelFetcher,
  35349. labelDataIndex: query,
  35350. defaultText: region.name,
  35351. useInsideStyle: false
  35352. },
  35353. {
  35354. textAlign: 'center',
  35355. textVerticalAlign: 'middle'
  35356. }
  35357. );
  35358. regionGroup.add(textEl);
  35359. }
  35360. // setItemGraphicEl, setHoverStyle after all polygons and labels
  35361. // are added to the rigionGroup
  35362. if (data) {
  35363. data.setItemGraphicEl(dataIdx, regionGroup);
  35364. }
  35365. else {
  35366. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  35367. // Package custom mouse event for geo component
  35368. compoundPath.eventData = {
  35369. componentType: 'geo',
  35370. geoIndex: mapOrGeoModel.componentIndex,
  35371. name: region.name,
  35372. region: (regionModel && regionModel.option) || {}
  35373. };
  35374. }
  35375. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  35376. groupRegions.push(region);
  35377. setHoverStyle(
  35378. regionGroup,
  35379. hoverItemStyle,
  35380. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  35381. );
  35382. group.add(regionGroup);
  35383. });
  35384. this._updateController(mapOrGeoModel, ecModel, api);
  35385. updateMapSelectHandler(this, mapOrGeoModel, group, api, fromView);
  35386. updateMapSelected(mapOrGeoModel, group);
  35387. },
  35388. remove: function () {
  35389. this.group.removeAll();
  35390. this._controller.dispose();
  35391. this._controllerHost = {};
  35392. },
  35393. _updateController: function (mapOrGeoModel, ecModel, api) {
  35394. var geo = mapOrGeoModel.coordinateSystem;
  35395. var controller = this._controller;
  35396. var controllerHost = this._controllerHost;
  35397. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  35398. controllerHost.zoom = geo.getZoom();
  35399. // roamType is will be set default true if it is null
  35400. controller.enable(mapOrGeoModel.get('roam') || false);
  35401. var mainType = mapOrGeoModel.mainType;
  35402. function makeActionBase() {
  35403. var action = {
  35404. type: 'geoRoam',
  35405. componentType: mainType
  35406. };
  35407. action[mainType + 'Id'] = mapOrGeoModel.id;
  35408. return action;
  35409. }
  35410. controller.off('pan').on('pan', function (dx, dy) {
  35411. this._mouseDownFlag = false;
  35412. updateViewOnPan(controllerHost, dx, dy);
  35413. api.dispatchAction(extend(makeActionBase(), {
  35414. dx: dx,
  35415. dy: dy
  35416. }));
  35417. }, this);
  35418. controller.off('zoom').on('zoom', function (zoom, mouseX, mouseY) {
  35419. this._mouseDownFlag = false;
  35420. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  35421. api.dispatchAction(extend(makeActionBase(), {
  35422. zoom: zoom,
  35423. originX: mouseX,
  35424. originY: mouseY
  35425. }));
  35426. if (this._updateGroup) {
  35427. var group = this.group;
  35428. var scale = group.scale;
  35429. group.traverse(function (el) {
  35430. if (el.type === 'text') {
  35431. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  35432. }
  35433. });
  35434. }
  35435. }, this);
  35436. controller.setPointerChecker(function (e, x, y) {
  35437. return geo.getViewRectAfterRoam().contain(x, y)
  35438. && !onIrrelevantElement(e, api, mapOrGeoModel);
  35439. });
  35440. }
  35441. };
  35442. extendChartView({
  35443. type: 'map',
  35444. render: function (mapModel, ecModel, api, payload) {
  35445. // Not render if it is an toggleSelect action from self
  35446. if (payload && payload.type === 'mapToggleSelect'
  35447. && payload.from === this.uid
  35448. ) {
  35449. return;
  35450. }
  35451. var group = this.group;
  35452. group.removeAll();
  35453. if (mapModel.getHostGeoModel()) {
  35454. return;
  35455. }
  35456. // Not update map if it is an roam action from self
  35457. if (!(payload && payload.type === 'geoRoam'
  35458. && payload.componentType === 'series'
  35459. && payload.seriesId === mapModel.id
  35460. )
  35461. ) {
  35462. if (mapModel.needsDrawMap) {
  35463. var mapDraw = this._mapDraw || new MapDraw(api, true);
  35464. group.add(mapDraw.group);
  35465. mapDraw.draw(mapModel, ecModel, api, this, payload);
  35466. this._mapDraw = mapDraw;
  35467. }
  35468. else {
  35469. // Remove drawed map
  35470. this._mapDraw && this._mapDraw.remove();
  35471. this._mapDraw = null;
  35472. }
  35473. }
  35474. else {
  35475. var mapDraw = this._mapDraw;
  35476. mapDraw && group.add(mapDraw.group);
  35477. }
  35478. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  35479. && this._renderSymbols(mapModel, ecModel, api);
  35480. },
  35481. remove: function () {
  35482. this._mapDraw && this._mapDraw.remove();
  35483. this._mapDraw = null;
  35484. this.group.removeAll();
  35485. },
  35486. dispose: function () {
  35487. this._mapDraw && this._mapDraw.remove();
  35488. this._mapDraw = null;
  35489. },
  35490. _renderSymbols: function (mapModel, ecModel, api) {
  35491. var originalData = mapModel.originalData;
  35492. var group = this.group;
  35493. originalData.each(originalData.mapDimension('value'), function (value, idx) {
  35494. if (isNaN(value)) {
  35495. return;
  35496. }
  35497. var layout = originalData.getItemLayout(idx);
  35498. if (!layout || !layout.point) {
  35499. // Not exists in map
  35500. return;
  35501. }
  35502. var point = layout.point;
  35503. var offset = layout.offset;
  35504. var circle = new Circle({
  35505. style: {
  35506. // Because the special of map draw.
  35507. // Which needs statistic of multiple series and draw on one map.
  35508. // And each series also need a symbol with legend color
  35509. //
  35510. // Layout and visual are put one the different data
  35511. fill: mapModel.getData().getVisual('color')
  35512. },
  35513. shape: {
  35514. cx: point[0] + offset * 9,
  35515. cy: point[1],
  35516. r: 3
  35517. },
  35518. silent: true,
  35519. // Do not overlap the first series, on which labels are displayed.
  35520. z2: !offset ? 10 : 8
  35521. });
  35522. // First data on the same region
  35523. if (!offset) {
  35524. var fullData = mapModel.mainSeries.getData();
  35525. var name = originalData.getName(idx);
  35526. var fullIndex = fullData.indexOfName(name);
  35527. var itemModel = originalData.getItemModel(idx);
  35528. var labelModel = itemModel.getModel('label');
  35529. var hoverLabelModel = itemModel.getModel('emphasis.label');
  35530. var polygonGroups = fullData.getItemGraphicEl(fullIndex);
  35531. var normalText = retrieve2(
  35532. mapModel.getFormattedLabel(idx, 'normal'),
  35533. name
  35534. );
  35535. var emphasisText = retrieve2(
  35536. mapModel.getFormattedLabel(idx, 'emphasis'),
  35537. normalText
  35538. );
  35539. var onEmphasis = function () {
  35540. var hoverStyle = setTextStyle({}, hoverLabelModel, {
  35541. text: hoverLabelModel.get('show') ? emphasisText : null
  35542. }, {isRectText: true, useInsideStyle: false}, true);
  35543. circle.style.extendFrom(hoverStyle);
  35544. // Make label upper than others if overlaps.
  35545. circle.__mapOriginalZ2 = circle.z2;
  35546. circle.z2 += 1;
  35547. };
  35548. var onNormal = function () {
  35549. setTextStyle(circle.style, labelModel, {
  35550. text: labelModel.get('show') ? normalText : null,
  35551. textPosition: labelModel.getShallow('position') || 'bottom'
  35552. }, {isRectText: true, useInsideStyle: false});
  35553. if (circle.__mapOriginalZ2 != null) {
  35554. circle.z2 = circle.__mapOriginalZ2;
  35555. circle.__mapOriginalZ2 = null;
  35556. }
  35557. };
  35558. polygonGroups.on('mouseover', onEmphasis)
  35559. .on('mouseout', onNormal)
  35560. .on('emphasis', onEmphasis)
  35561. .on('normal', onNormal);
  35562. onNormal();
  35563. }
  35564. group.add(circle);
  35565. });
  35566. }
  35567. });
  35568. /**
  35569. * @param {module:echarts/coord/View} view
  35570. * @param {Object} payload
  35571. * @param {Object} [zoomLimit]
  35572. */
  35573. function updateCenterAndZoom(
  35574. view, payload, zoomLimit
  35575. ) {
  35576. var previousZoom = view.getZoom();
  35577. var center = view.getCenter();
  35578. var zoom = payload.zoom;
  35579. var point = view.dataToPoint(center);
  35580. if (payload.dx != null && payload.dy != null) {
  35581. point[0] -= payload.dx;
  35582. point[1] -= payload.dy;
  35583. var center = view.pointToData(point);
  35584. view.setCenter(center);
  35585. }
  35586. if (zoom != null) {
  35587. if (zoomLimit) {
  35588. var zoomMin = zoomLimit.min || 0;
  35589. var zoomMax = zoomLimit.max || Infinity;
  35590. zoom = Math.max(
  35591. Math.min(previousZoom * zoom, zoomMax),
  35592. zoomMin
  35593. ) / previousZoom;
  35594. }
  35595. // Zoom on given point(originX, originY)
  35596. view.scale[0] *= zoom;
  35597. view.scale[1] *= zoom;
  35598. var position = view.position;
  35599. var fixX = (payload.originX - position[0]) * (zoom - 1);
  35600. var fixY = (payload.originY - position[1]) * (zoom - 1);
  35601. position[0] -= fixX;
  35602. position[1] -= fixY;
  35603. view.updateTransform();
  35604. // Get the new center
  35605. var center = view.pointToData(point);
  35606. view.setCenter(center);
  35607. view.setZoom(zoom * previousZoom);
  35608. }
  35609. return {
  35610. center: view.getCenter(),
  35611. zoom: view.getZoom()
  35612. };
  35613. }
  35614. /**
  35615. * @payload
  35616. * @property {string} [componentType=series]
  35617. * @property {number} [dx]
  35618. * @property {number} [dy]
  35619. * @property {number} [zoom]
  35620. * @property {number} [originX]
  35621. * @property {number} [originY]
  35622. */
  35623. registerAction({
  35624. type: 'geoRoam',
  35625. event: 'geoRoam',
  35626. update: 'updateTransform'
  35627. }, function (payload, ecModel) {
  35628. var componentType = payload.componentType || 'series';
  35629. ecModel.eachComponent(
  35630. { mainType: componentType, query: payload },
  35631. function (componentModel) {
  35632. var geo = componentModel.coordinateSystem;
  35633. if (geo.type !== 'geo') {
  35634. return;
  35635. }
  35636. var res = updateCenterAndZoom(
  35637. geo, payload, componentModel.get('scaleLimit')
  35638. );
  35639. componentModel.setCenter
  35640. && componentModel.setCenter(res.center);
  35641. componentModel.setZoom
  35642. && componentModel.setZoom(res.zoom);
  35643. // All map series with same `map` use the same geo coordinate system
  35644. // So the center and zoom must be in sync. Include the series not selected by legend
  35645. if (componentType === 'series') {
  35646. each$1(componentModel.seriesGroup, function (seriesModel) {
  35647. seriesModel.setCenter(res.center);
  35648. seriesModel.setZoom(res.zoom);
  35649. });
  35650. }
  35651. }
  35652. );
  35653. });
  35654. var mapSymbolLayout = function (ecModel) {
  35655. var processedMapType = {};
  35656. ecModel.eachSeriesByType('map', function (mapSeries) {
  35657. var mapType = mapSeries.getMapType();
  35658. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  35659. return;
  35660. }
  35661. var mapSymbolOffsets = {};
  35662. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  35663. var geo = subMapSeries.coordinateSystem;
  35664. var data = subMapSeries.originalData;
  35665. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  35666. data.each(data.mapDimension('value'), function (value, idx) {
  35667. var name = data.getName(idx);
  35668. var region = geo.getRegion(name);
  35669. // If input series.data is [11, 22, '-'/null/undefined, 44],
  35670. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  35671. // not be drawn. So here must validate if value is NaN.
  35672. if (!region || isNaN(value)) {
  35673. return;
  35674. }
  35675. var offset = mapSymbolOffsets[name] || 0;
  35676. var point = geo.dataToPoint(region.center);
  35677. mapSymbolOffsets[name] = offset + 1;
  35678. data.setItemLayout(idx, {
  35679. point: point,
  35680. offset: offset
  35681. });
  35682. });
  35683. }
  35684. });
  35685. // Show label of those region not has legendSymbol(which is offset 0)
  35686. var data = mapSeries.getData();
  35687. data.each(function (idx) {
  35688. var name = data.getName(idx);
  35689. var layout = data.getItemLayout(idx) || {};
  35690. layout.showLabel = !mapSymbolOffsets[name];
  35691. data.setItemLayout(idx, layout);
  35692. });
  35693. processedMapType[mapType] = true;
  35694. });
  35695. };
  35696. var mapVisual = function (ecModel) {
  35697. ecModel.eachSeriesByType('map', function (seriesModel) {
  35698. var colorList = seriesModel.get('color');
  35699. var itemStyleModel = seriesModel.getModel('itemStyle');
  35700. var areaColor = itemStyleModel.get('areaColor');
  35701. var color = itemStyleModel.get('color')
  35702. || colorList[seriesModel.seriesIndex % colorList.length];
  35703. seriesModel.getData().setVisual({
  35704. 'areaColor': areaColor,
  35705. 'color': color
  35706. });
  35707. });
  35708. };
  35709. // FIXME 公用?
  35710. /**
  35711. * @param {Array.<module:echarts/data/List>} datas
  35712. * @param {string} statisticType 'average' 'sum'
  35713. * @inner
  35714. */
  35715. function dataStatistics(datas, statisticType) {
  35716. var dataNameMap = {};
  35717. each$1(datas, function (data) {
  35718. data.each(data.mapDimension('value'), function (value, idx) {
  35719. // Add prefix to avoid conflict with Object.prototype.
  35720. var mapKey = 'ec-' + data.getName(idx);
  35721. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  35722. if (!isNaN(value)) {
  35723. dataNameMap[mapKey].push(value);
  35724. }
  35725. });
  35726. });
  35727. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  35728. var mapKey = 'ec-' + datas[0].getName(idx);
  35729. var sum = 0;
  35730. var min = Infinity;
  35731. var max = -Infinity;
  35732. var len = dataNameMap[mapKey].length;
  35733. for (var i = 0; i < len; i++) {
  35734. min = Math.min(min, dataNameMap[mapKey][i]);
  35735. max = Math.max(max, dataNameMap[mapKey][i]);
  35736. sum += dataNameMap[mapKey][i];
  35737. }
  35738. var result;
  35739. if (statisticType === 'min') {
  35740. result = min;
  35741. }
  35742. else if (statisticType === 'max') {
  35743. result = max;
  35744. }
  35745. else if (statisticType === 'average') {
  35746. result = sum / len;
  35747. }
  35748. else {
  35749. result = sum;
  35750. }
  35751. return len === 0 ? NaN : result;
  35752. });
  35753. }
  35754. var mapDataStatistic = function (ecModel) {
  35755. var seriesGroups = {};
  35756. ecModel.eachSeriesByType('map', function (seriesModel) {
  35757. var hostGeoModel = seriesModel.getHostGeoModel();
  35758. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  35759. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  35760. });
  35761. each$1(seriesGroups, function (seriesList, key) {
  35762. var data = dataStatistics(
  35763. map(seriesList, function (seriesModel) {
  35764. return seriesModel.getData();
  35765. }),
  35766. seriesList[0].get('mapValueCalculation')
  35767. );
  35768. for (var i = 0; i < seriesList.length; i++) {
  35769. seriesList[i].originalData = seriesList[i].getData();
  35770. }
  35771. // FIXME Put where?
  35772. for (var i = 0; i < seriesList.length; i++) {
  35773. seriesList[i].seriesGroup = seriesList;
  35774. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  35775. seriesList[i].setData(data.cloneShallow());
  35776. seriesList[i].mainSeries = seriesList[0];
  35777. }
  35778. });
  35779. };
  35780. var backwardCompat$2 = function (option) {
  35781. // Save geoCoord
  35782. var mapSeries = [];
  35783. each$1(option.series, function (seriesOpt) {
  35784. if (seriesOpt && seriesOpt.type === 'map') {
  35785. mapSeries.push(seriesOpt);
  35786. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  35787. // Put x, y, width, height, x2, y2 in the top level
  35788. defaults(seriesOpt, seriesOpt.mapLocation);
  35789. }
  35790. });
  35791. };
  35792. registerLayout(mapSymbolLayout);
  35793. registerVisual(mapVisual);
  35794. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  35795. registerPreprocessor(backwardCompat$2);
  35796. createDataSelectAction('map', [{
  35797. type: 'mapToggleSelect',
  35798. event: 'mapselectchanged',
  35799. method: 'toggleSelected'
  35800. }, {
  35801. type: 'mapSelect',
  35802. event: 'mapselected',
  35803. method: 'select'
  35804. }, {
  35805. type: 'mapUnSelect',
  35806. event: 'mapunselected',
  35807. method: 'unSelect'
  35808. }]);
  35809. /**
  35810. * Link lists and struct (graph or tree)
  35811. */
  35812. var each$8 = each$1;
  35813. var DATAS = '\0__link_datas';
  35814. var MAIN_DATA = '\0__link_mainData';
  35815. // Caution:
  35816. // In most case, either list or its shallow clones (see list.cloneShallow)
  35817. // is active in echarts process. So considering heap memory consumption,
  35818. // we do not clone tree or graph, but share them among list and its shallow clones.
  35819. // But in some rare case, we have to keep old list (like do animation in chart). So
  35820. // please take care that both the old list and the new list share the same tree/graph.
  35821. /**
  35822. * @param {Object} opt
  35823. * @param {module:echarts/data/List} opt.mainData
  35824. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  35825. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  35826. * @param {Object} [opt.datas] {dataType: data},
  35827. * like: {node: nodeList, edge: edgeList}.
  35828. * Should contain mainData.
  35829. * @param {Object} [opt.datasAttr] {dataType: attr},
  35830. * designation: struct[datasAttr[dataType]] = list;
  35831. */
  35832. function linkList(opt) {
  35833. var mainData = opt.mainData;
  35834. var datas = opt.datas;
  35835. if (!datas) {
  35836. datas = {main: mainData};
  35837. opt.datasAttr = {main: 'data'};
  35838. }
  35839. opt.datas = opt.mainData = null;
  35840. linkAll(mainData, datas, opt);
  35841. // Porxy data original methods.
  35842. each$8(datas, function (data) {
  35843. each$8(mainData.TRANSFERABLE_METHODS, function (methodName) {
  35844. data.wrapMethod(methodName, curry(transferInjection, opt));
  35845. });
  35846. });
  35847. // Beyond transfer, additional features should be added to `cloneShallow`.
  35848. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  35849. // Only mainData trigger change, because struct.update may trigger
  35850. // another changable methods, which may bring about dead lock.
  35851. each$8(mainData.CHANGABLE_METHODS, function (methodName) {
  35852. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  35853. });
  35854. // Make sure datas contains mainData.
  35855. assert$1(datas[mainData.dataType] === mainData);
  35856. }
  35857. function transferInjection(opt, res) {
  35858. if (isMainData(this)) {
  35859. // Transfer datas to new main data.
  35860. var datas = extend({}, this[DATAS]);
  35861. datas[this.dataType] = res;
  35862. linkAll(res, datas, opt);
  35863. }
  35864. else {
  35865. // Modify the reference in main data to point newData.
  35866. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  35867. }
  35868. return res;
  35869. }
  35870. function changeInjection(opt, res) {
  35871. opt.struct && opt.struct.update(this);
  35872. return res;
  35873. }
  35874. function cloneShallowInjection(opt, res) {
  35875. // cloneShallow, which brings about some fragilities, may be inappropriate
  35876. // to be exposed as an API. So for implementation simplicity we can make
  35877. // the restriction that cloneShallow of not-mainData should not be invoked
  35878. // outside, but only be invoked here.
  35879. each$8(res[DATAS], function (data, dataType) {
  35880. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  35881. });
  35882. return res;
  35883. }
  35884. /**
  35885. * Supplement method to List.
  35886. *
  35887. * @public
  35888. * @param {string} [dataType] If not specified, return mainData.
  35889. * @return {module:echarts/data/List}
  35890. */
  35891. function getLinkedData(dataType) {
  35892. var mainData = this[MAIN_DATA];
  35893. return (dataType == null || mainData == null)
  35894. ? mainData
  35895. : mainData[DATAS][dataType];
  35896. }
  35897. function isMainData(data) {
  35898. return data[MAIN_DATA] === data;
  35899. }
  35900. function linkAll(mainData, datas, opt) {
  35901. mainData[DATAS] = {};
  35902. each$8(datas, function (data, dataType) {
  35903. linkSingle(data, dataType, mainData, opt);
  35904. });
  35905. }
  35906. function linkSingle(data, dataType, mainData, opt) {
  35907. mainData[DATAS][dataType] = data;
  35908. data[MAIN_DATA] = mainData;
  35909. data.dataType = dataType;
  35910. if (opt.struct) {
  35911. data[opt.structAttr] = opt.struct;
  35912. opt.struct[opt.datasAttr[dataType]] = data;
  35913. }
  35914. // Supplement method.
  35915. data.getLinkedData = getLinkedData;
  35916. }
  35917. /**
  35918. * Tree data structure
  35919. *
  35920. * @module echarts/data/Tree
  35921. */
  35922. /**
  35923. * @constructor module:echarts/data/Tree~TreeNode
  35924. * @param {string} name
  35925. * @param {module:echarts/data/Tree} hostTree
  35926. */
  35927. var TreeNode = function (name, hostTree) {
  35928. /**
  35929. * @type {string}
  35930. */
  35931. this.name = name || '';
  35932. /**
  35933. * Depth of node
  35934. *
  35935. * @type {number}
  35936. * @readOnly
  35937. */
  35938. this.depth = 0;
  35939. /**
  35940. * Height of the subtree rooted at this node.
  35941. * @type {number}
  35942. * @readOnly
  35943. */
  35944. this.height = 0;
  35945. /**
  35946. * @type {module:echarts/data/Tree~TreeNode}
  35947. * @readOnly
  35948. */
  35949. this.parentNode = null;
  35950. /**
  35951. * Reference to list item.
  35952. * Do not persistent dataIndex outside,
  35953. * besause it may be changed by list.
  35954. * If dataIndex -1,
  35955. * this node is logical deleted (filtered) in list.
  35956. *
  35957. * @type {Object}
  35958. * @readOnly
  35959. */
  35960. this.dataIndex = -1;
  35961. /**
  35962. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  35963. * @readOnly
  35964. */
  35965. this.children = [];
  35966. /**
  35967. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  35968. * @pubilc
  35969. */
  35970. this.viewChildren = [];
  35971. /**
  35972. * @type {moduel:echarts/data/Tree}
  35973. * @readOnly
  35974. */
  35975. this.hostTree = hostTree;
  35976. };
  35977. TreeNode.prototype = {
  35978. constructor: TreeNode,
  35979. /**
  35980. * The node is removed.
  35981. * @return {boolean} is removed.
  35982. */
  35983. isRemoved: function () {
  35984. return this.dataIndex < 0;
  35985. },
  35986. /**
  35987. * Travel this subtree (include this node).
  35988. * Usage:
  35989. * node.eachNode(function () { ... }); // preorder
  35990. * node.eachNode('preorder', function () { ... }); // preorder
  35991. * node.eachNode('postorder', function () { ... }); // postorder
  35992. * node.eachNode(
  35993. * {order: 'postorder', attr: 'viewChildren'},
  35994. * function () { ... }
  35995. * ); // postorder
  35996. *
  35997. * @param {(Object|string)} options If string, means order.
  35998. * @param {string=} options.order 'preorder' or 'postorder'
  35999. * @param {string=} options.attr 'children' or 'viewChildren'
  36000. * @param {Function} cb If in preorder and return false,
  36001. * its subtree will not be visited.
  36002. * @param {Object} [context]
  36003. */
  36004. eachNode: function (options, cb, context) {
  36005. if (typeof options === 'function') {
  36006. context = cb;
  36007. cb = options;
  36008. options = null;
  36009. }
  36010. options = options || {};
  36011. if (isString(options)) {
  36012. options = {order: options};
  36013. }
  36014. var order = options.order || 'preorder';
  36015. var children = this[options.attr || 'children'];
  36016. var suppressVisitSub;
  36017. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  36018. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  36019. children[i].eachNode(options, cb, context);
  36020. }
  36021. order === 'postorder' && cb.call(context, this);
  36022. },
  36023. /**
  36024. * Update depth and height of this subtree.
  36025. *
  36026. * @param {number} depth
  36027. */
  36028. updateDepthAndHeight: function (depth) {
  36029. var height = 0;
  36030. this.depth = depth;
  36031. for (var i = 0; i < this.children.length; i++) {
  36032. var child = this.children[i];
  36033. child.updateDepthAndHeight(depth + 1);
  36034. if (child.height > height) {
  36035. height = child.height;
  36036. }
  36037. }
  36038. this.height = height + 1;
  36039. },
  36040. /**
  36041. * @param {string} id
  36042. * @return {module:echarts/data/Tree~TreeNode}
  36043. */
  36044. getNodeById: function (id) {
  36045. if (this.getId() === id) {
  36046. return this;
  36047. }
  36048. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  36049. var res = children[i].getNodeById(id);
  36050. if (res) {
  36051. return res;
  36052. }
  36053. }
  36054. },
  36055. /**
  36056. * @param {module:echarts/data/Tree~TreeNode} node
  36057. * @return {boolean}
  36058. */
  36059. contains: function (node) {
  36060. if (node === this) {
  36061. return true;
  36062. }
  36063. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  36064. var res = children[i].contains(node);
  36065. if (res) {
  36066. return res;
  36067. }
  36068. }
  36069. },
  36070. /**
  36071. * @param {boolean} includeSelf Default false.
  36072. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  36073. */
  36074. getAncestors: function (includeSelf) {
  36075. var ancestors = [];
  36076. var node = includeSelf ? this : this.parentNode;
  36077. while (node) {
  36078. ancestors.push(node);
  36079. node = node.parentNode;
  36080. }
  36081. ancestors.reverse();
  36082. return ancestors;
  36083. },
  36084. /**
  36085. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  36086. * @return {number} Value.
  36087. */
  36088. getValue: function (dimension) {
  36089. var data = this.hostTree.data;
  36090. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  36091. },
  36092. /**
  36093. * @param {Object} layout
  36094. * @param {boolean=} [merge=false]
  36095. */
  36096. setLayout: function (layout, merge$$1) {
  36097. this.dataIndex >= 0
  36098. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  36099. },
  36100. /**
  36101. * @return {Object} layout
  36102. */
  36103. getLayout: function () {
  36104. return this.hostTree.data.getItemLayout(this.dataIndex);
  36105. },
  36106. /**
  36107. * @param {string} [path]
  36108. * @return {module:echarts/model/Model}
  36109. */
  36110. getModel: function (path) {
  36111. if (this.dataIndex < 0) {
  36112. return;
  36113. }
  36114. var hostTree = this.hostTree;
  36115. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  36116. var levelModel = this.getLevelModel();
  36117. var leavesModel;
  36118. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  36119. leavesModel = this.getLeavesModel();
  36120. }
  36121. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  36122. },
  36123. /**
  36124. * @return {module:echarts/model/Model}
  36125. */
  36126. getLevelModel: function () {
  36127. return (this.hostTree.levelModels || [])[this.depth];
  36128. },
  36129. /**
  36130. * @return {module:echarts/model/Model}
  36131. */
  36132. getLeavesModel: function () {
  36133. return this.hostTree.leavesModel;
  36134. },
  36135. /**
  36136. * @example
  36137. * setItemVisual('color', color);
  36138. * setItemVisual({
  36139. * 'color': color
  36140. * });
  36141. */
  36142. setVisual: function (key, value) {
  36143. this.dataIndex >= 0
  36144. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  36145. },
  36146. /**
  36147. * Get item visual
  36148. */
  36149. getVisual: function (key, ignoreParent) {
  36150. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  36151. },
  36152. /**
  36153. * @public
  36154. * @return {number}
  36155. */
  36156. getRawIndex: function () {
  36157. return this.hostTree.data.getRawIndex(this.dataIndex);
  36158. },
  36159. /**
  36160. * @public
  36161. * @return {string}
  36162. */
  36163. getId: function () {
  36164. return this.hostTree.data.getId(this.dataIndex);
  36165. },
  36166. /**
  36167. * if this is an ancestor of another node
  36168. *
  36169. * @public
  36170. * @param {TreeNode} node another node
  36171. * @return {boolean} if is ancestor
  36172. */
  36173. isAncestorOf: function (node) {
  36174. var parent = node.parentNode;
  36175. while (parent) {
  36176. if (parent === this) {
  36177. return true;
  36178. }
  36179. parent = parent.parentNode;
  36180. }
  36181. return false;
  36182. },
  36183. /**
  36184. * if this is an descendant of another node
  36185. *
  36186. * @public
  36187. * @param {TreeNode} node another node
  36188. * @return {boolean} if is descendant
  36189. */
  36190. isDescendantOf: function (node) {
  36191. return node !== this && node.isAncestorOf(this);
  36192. }
  36193. };
  36194. /**
  36195. * @constructor
  36196. * @alias module:echarts/data/Tree
  36197. * @param {module:echarts/model/Model} hostModel
  36198. * @param {Array.<Object>} levelOptions
  36199. * @param {Object} leavesOption
  36200. */
  36201. function Tree(hostModel, levelOptions, leavesOption) {
  36202. /**
  36203. * @type {module:echarts/data/Tree~TreeNode}
  36204. * @readOnly
  36205. */
  36206. this.root;
  36207. /**
  36208. * @type {module:echarts/data/List}
  36209. * @readOnly
  36210. */
  36211. this.data;
  36212. /**
  36213. * Index of each item is the same as the raw index of coresponding list item.
  36214. * @private
  36215. * @type {Array.<module:echarts/data/Tree~TreeNode}
  36216. */
  36217. this._nodes = [];
  36218. /**
  36219. * @private
  36220. * @readOnly
  36221. * @type {module:echarts/model/Model}
  36222. */
  36223. this.hostModel = hostModel;
  36224. /**
  36225. * @private
  36226. * @readOnly
  36227. * @type {Array.<module:echarts/model/Model}
  36228. */
  36229. this.levelModels = map(levelOptions || [], function (levelDefine) {
  36230. return new Model(levelDefine, hostModel, hostModel.ecModel);
  36231. });
  36232. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  36233. }
  36234. Tree.prototype = {
  36235. constructor: Tree,
  36236. type: 'tree',
  36237. /**
  36238. * Travel this subtree (include this node).
  36239. * Usage:
  36240. * node.eachNode(function () { ... }); // preorder
  36241. * node.eachNode('preorder', function () { ... }); // preorder
  36242. * node.eachNode('postorder', function () { ... }); // postorder
  36243. * node.eachNode(
  36244. * {order: 'postorder', attr: 'viewChildren'},
  36245. * function () { ... }
  36246. * ); // postorder
  36247. *
  36248. * @param {(Object|string)} options If string, means order.
  36249. * @param {string=} options.order 'preorder' or 'postorder'
  36250. * @param {string=} options.attr 'children' or 'viewChildren'
  36251. * @param {Function} cb
  36252. * @param {Object} [context]
  36253. */
  36254. eachNode: function(options, cb, context) {
  36255. this.root.eachNode(options, cb, context);
  36256. },
  36257. /**
  36258. * @param {number} dataIndex
  36259. * @return {module:echarts/data/Tree~TreeNode}
  36260. */
  36261. getNodeByDataIndex: function (dataIndex) {
  36262. var rawIndex = this.data.getRawIndex(dataIndex);
  36263. return this._nodes[rawIndex];
  36264. },
  36265. /**
  36266. * @param {string} name
  36267. * @return {module:echarts/data/Tree~TreeNode}
  36268. */
  36269. getNodeByName: function (name) {
  36270. return this.root.getNodeByName(name);
  36271. },
  36272. /**
  36273. * Update item available by list,
  36274. * when list has been performed options like 'filterSelf' or 'map'.
  36275. */
  36276. update: function () {
  36277. var data = this.data;
  36278. var nodes = this._nodes;
  36279. for (var i = 0, len = nodes.length; i < len; i++) {
  36280. nodes[i].dataIndex = -1;
  36281. }
  36282. for (var i = 0, len = data.count(); i < len; i++) {
  36283. nodes[data.getRawIndex(i)].dataIndex = i;
  36284. }
  36285. },
  36286. /**
  36287. * Clear all layouts
  36288. */
  36289. clearLayouts: function () {
  36290. this.data.clearItemLayouts();
  36291. }
  36292. };
  36293. /**
  36294. * data node format:
  36295. * {
  36296. * name: ...
  36297. * value: ...
  36298. * children: [
  36299. * {
  36300. * name: ...
  36301. * value: ...
  36302. * children: ...
  36303. * },
  36304. * ...
  36305. * ]
  36306. * }
  36307. *
  36308. * @static
  36309. * @param {Object} dataRoot Root node.
  36310. * @param {module:echarts/model/Model} hostModel
  36311. * @param {Object} treeOptions
  36312. * @param {Array.<Object>} treeOptions.levels
  36313. * @param {Array.<Object>} treeOptions.leaves
  36314. * @return module:echarts/data/Tree
  36315. */
  36316. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  36317. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  36318. var listData = [];
  36319. var dimMax = 1;
  36320. buildHierarchy(dataRoot);
  36321. function buildHierarchy(dataNode, parentNode) {
  36322. var value = dataNode.value;
  36323. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  36324. listData.push(dataNode);
  36325. var node = new TreeNode(dataNode.name, tree);
  36326. parentNode
  36327. ? addChild(node, parentNode)
  36328. : (tree.root = node);
  36329. tree._nodes.push(node);
  36330. var children = dataNode.children;
  36331. if (children) {
  36332. for (var i = 0; i < children.length; i++) {
  36333. buildHierarchy(children[i], node);
  36334. }
  36335. }
  36336. }
  36337. tree.root.updateDepthAndHeight(0);
  36338. var dimensionsInfo = createDimensions(listData, {
  36339. coordDimensions: ['value'],
  36340. dimensionsCount: dimMax
  36341. });
  36342. var list = new List(dimensionsInfo, hostModel);
  36343. list.initData(listData);
  36344. linkList({
  36345. mainData: list,
  36346. struct: tree,
  36347. structAttr: 'tree'
  36348. });
  36349. tree.update();
  36350. return tree;
  36351. };
  36352. /**
  36353. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  36354. * so this function is not ready and not necessary to be public.
  36355. *
  36356. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  36357. */
  36358. function addChild(child, node) {
  36359. var children = node.children;
  36360. if (child.parentNode === node) {
  36361. return;
  36362. }
  36363. children.push(child);
  36364. child.parentNode = node;
  36365. }
  36366. /**
  36367. * @file Create data struct and define tree view's series model
  36368. */
  36369. SeriesModel.extend({
  36370. type: 'series.tree',
  36371. layoutInfo: null,
  36372. // can support the position parameters 'left', 'top','right','bottom', 'width',
  36373. // 'height' in the setOption() with 'merge' mode normal.
  36374. layoutMode: 'box',
  36375. /**
  36376. * Init a tree data structure from data in option series
  36377. * @param {Object} option the object used to config echarts view
  36378. * @return {module:echarts/data/List} storage initial data
  36379. */
  36380. getInitialData: function (option) {
  36381. //create an virtual root
  36382. var root = {name: option.name, children: option.data};
  36383. var leaves = option.leaves || {};
  36384. var treeOption = {};
  36385. treeOption.leaves = leaves;
  36386. var tree = Tree.createTree(root, this, treeOption);
  36387. var treeDepth = 0;
  36388. tree.eachNode('preorder', function (node) {
  36389. if (node.depth > treeDepth) {
  36390. treeDepth = node.depth;
  36391. }
  36392. });
  36393. var expandAndCollapse = option.expandAndCollapse;
  36394. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  36395. ? option.initialTreeDepth : treeDepth;
  36396. tree.root.eachNode('preorder', function (node) {
  36397. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  36398. node.isExpand = (item && item.collapsed != null)
  36399. ? !item.collapsed
  36400. : node.depth <= expandTreeDepth;
  36401. });
  36402. return tree.data;
  36403. },
  36404. /**
  36405. * @override
  36406. * @param {number} dataIndex
  36407. */
  36408. formatTooltip: function (dataIndex) {
  36409. var tree = this.getData().tree;
  36410. var realRoot = tree.root.children[0];
  36411. var node = tree.getNodeByDataIndex(dataIndex);
  36412. var value = node.getValue();
  36413. var name = node.name;
  36414. while (node && (node !== realRoot)) {
  36415. name = node.parentNode.name + '.' + name;
  36416. node = node.parentNode;
  36417. }
  36418. return encodeHTML(name + (
  36419. (isNaN(value) || value == null) ? '' : ' : ' + value
  36420. ));
  36421. },
  36422. defaultOption: {
  36423. zlevel: 0,
  36424. z: 2,
  36425. // the position of the whole view
  36426. left: '12%',
  36427. top: '12%',
  36428. right: '12%',
  36429. bottom: '12%',
  36430. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  36431. layout: 'orthogonal',
  36432. // the orient of orthoginal layout, can be setted to 'horizontal' or 'vertical'
  36433. orient: 'horizontal',
  36434. symbol: 'emptyCircle',
  36435. symbolSize: 7,
  36436. expandAndCollapse: true,
  36437. initialTreeDepth: 2,
  36438. lineStyle: {
  36439. color: '#ccc',
  36440. width: 1.5,
  36441. curveness: 0.5
  36442. },
  36443. itemStyle: {
  36444. color: 'lightsteelblue',
  36445. borderColor: '#c23531',
  36446. borderWidth: 1.5
  36447. },
  36448. label: {
  36449. show: true,
  36450. color: '#555'
  36451. },
  36452. leaves: {
  36453. label: {
  36454. show: true
  36455. }
  36456. },
  36457. animationEasing: 'linear',
  36458. animationDuration: 700,
  36459. animationDurationUpdate: 1000
  36460. }
  36461. });
  36462. /**
  36463. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  36464. * the tree.
  36465. * @see https://github.com/d3/d3-hierarchy
  36466. */
  36467. /**
  36468. * Initialize all computational message for following algorithm
  36469. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  36470. */
  36471. function init$2(root) {
  36472. root.hierNode = {
  36473. defaultAncestor: null,
  36474. ancestor: root,
  36475. prelim: 0,
  36476. modifier: 0,
  36477. change: 0,
  36478. shift: 0,
  36479. i: 0,
  36480. thread: null
  36481. };
  36482. var nodes = [root];
  36483. var node;
  36484. var children;
  36485. while (node = nodes.pop()) { // jshint ignore:line
  36486. children = node.children;
  36487. if (node.isExpand && children.length) {
  36488. var n = children.length;
  36489. for (var i = n - 1; i >= 0; i--) {
  36490. var child = children[i];
  36491. child.hierNode = {
  36492. defaultAncestor: null,
  36493. ancestor: child,
  36494. prelim: 0,
  36495. modifier: 0,
  36496. change: 0,
  36497. shift: 0,
  36498. i: i,
  36499. thread: null
  36500. };
  36501. nodes.push(child);
  36502. }
  36503. }
  36504. }
  36505. }
  36506. /**
  36507. * Computes a preliminary x coordinate for node. Before that, this function is
  36508. * applied recursively to the children of node, as well as the function
  36509. * apportion(). After spacing out the children by calling executeShifts(), the
  36510. * node is placed to the midpoint of its outermost children.
  36511. * @param {module:echarts/data/Tree~TreeNode} node
  36512. * @param {Function} separation
  36513. */
  36514. function firstWalk(node, separation) {
  36515. var children = node.isExpand ? node.children : [];
  36516. var siblings = node.parentNode.children;
  36517. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i -1] : null;
  36518. if (children.length) {
  36519. executeShifts(node);
  36520. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  36521. if (subtreeW) {
  36522. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  36523. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  36524. }
  36525. else {
  36526. node.hierNode.prelim = midPoint;
  36527. }
  36528. }
  36529. else if (subtreeW) {
  36530. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  36531. }
  36532. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  36533. }
  36534. /**
  36535. * Computes all real x-coordinates by summing up the modifiers recursively.
  36536. * @param {module:echarts/data/Tree~TreeNode} node
  36537. */
  36538. function secondWalk(node) {
  36539. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  36540. node.setLayout({x: nodeX}, true);
  36541. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  36542. }
  36543. function separation(cb) {
  36544. return arguments.length ? cb : defaultSeparation;
  36545. }
  36546. /**
  36547. * Transform the common coordinate to radial coordinate
  36548. * @param {number} x
  36549. * @param {number} y
  36550. * @return {Object}
  36551. */
  36552. function radialCoordinate(x, y) {
  36553. var radialCoor = {};
  36554. x -= Math.PI / 2;
  36555. radialCoor.x = y * Math.cos(x);
  36556. radialCoor.y = y * Math.sin(x);
  36557. return radialCoor;
  36558. }
  36559. /**
  36560. * Get the layout position of the whole view
  36561. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  36562. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  36563. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  36564. */
  36565. function getViewRect(seriesModel, api) {
  36566. return getLayoutRect(
  36567. seriesModel.getBoxLayoutParams(), {
  36568. width: api.getWidth(),
  36569. height: api.getHeight()
  36570. }
  36571. );
  36572. }
  36573. /**
  36574. * All other shifts, applied to the smaller subtrees between w- and w+, are
  36575. * performed by this function.
  36576. * @param {module:echarts/data/Tree~TreeNode} node
  36577. */
  36578. function executeShifts(node) {
  36579. var children = node.children;
  36580. var n = children.length;
  36581. var shift = 0;
  36582. var change = 0;
  36583. while (--n >= 0) {
  36584. var child = children[n];
  36585. child.hierNode.prelim += shift;
  36586. child.hierNode.modifier += shift;
  36587. change += child.hierNode.change;
  36588. shift += child.hierNode.shift + change;
  36589. }
  36590. }
  36591. /**
  36592. * The core of the algorithm. Here, a new subtree is combined with the
  36593. * previous subtrees. Threads are used to traverse the inside and outside
  36594. * contours of the left and right subtree up to the highest common level.
  36595. * Whenever two nodes of the inside contours conflict, we compute the left
  36596. * one of the greatest uncommon ancestors using the function nextAncestor()
  36597. * and call moveSubtree() to shift the subtree and prepare the shifts of
  36598. * smaller subtrees. Finally, we add a new thread (if necessary).
  36599. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  36600. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  36601. * @param {module:echarts/data/Tree~TreeNode} ancestor
  36602. * @param {Function} separation
  36603. * @return {module:echarts/data/Tree~TreeNode}
  36604. */
  36605. function apportion(subtreeV, subtreeW, ancestor, separation) {
  36606. if (subtreeW) {
  36607. var nodeOutRight = subtreeV;
  36608. var nodeInRight = subtreeV;
  36609. var nodeOutLeft = nodeInRight.parentNode.children[0];
  36610. var nodeInLeft = subtreeW;
  36611. var sumOutRight = nodeOutRight.hierNode.modifier;
  36612. var sumInRight = nodeInRight.hierNode.modifier;
  36613. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  36614. var sumInLeft = nodeInLeft.hierNode.modifier;
  36615. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  36616. nodeOutRight = nextRight(nodeOutRight);
  36617. nodeOutLeft = nextLeft(nodeOutLeft);
  36618. nodeOutRight.hierNode.ancestor = subtreeV;
  36619. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  36620. - sumInRight + separation(nodeInLeft, nodeInRight);
  36621. if (shift > 0) {
  36622. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  36623. sumInRight += shift;
  36624. sumOutRight += shift;
  36625. }
  36626. sumInLeft += nodeInLeft.hierNode.modifier;
  36627. sumInRight += nodeInRight.hierNode.modifier;
  36628. sumOutRight += nodeOutRight.hierNode.modifier;
  36629. sumOutLeft += nodeOutLeft.hierNode.modifier;
  36630. }
  36631. if (nodeInLeft && !nextRight(nodeOutRight)) {
  36632. nodeOutRight.hierNode.thread = nodeInLeft;
  36633. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  36634. }
  36635. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  36636. nodeOutLeft.hierNode.thread = nodeInRight;
  36637. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  36638. ancestor = subtreeV;
  36639. }
  36640. }
  36641. return ancestor;
  36642. }
  36643. /**
  36644. * This function is used to traverse the right contour of a subtree.
  36645. * It returns the rightmost child of node or the thread of node. The function
  36646. * returns null if and only if node is on the highest depth of its subtree.
  36647. * @param {module:echarts/data/Tree~TreeNode} node
  36648. * @return {module:echarts/data/Tree~TreeNode}
  36649. */
  36650. function nextRight(node) {
  36651. var children = node.children;
  36652. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  36653. }
  36654. /**
  36655. * This function is used to traverse the left contour of a subtree (or a subforest).
  36656. * It returns the leftmost child of node or the thread of node. The function
  36657. * returns null if and only if node is on the highest depth of its subtree.
  36658. * @param {module:echarts/data/Tree~TreeNode} node
  36659. * @return {module:echarts/data/Tree~TreeNode}
  36660. */
  36661. function nextLeft(node) {
  36662. var children = node.children;
  36663. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  36664. }
  36665. /**
  36666. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  36667. * Otherwise, returns the specified ancestor.
  36668. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  36669. * @param {module:echarts/data/Tree~TreeNode} node
  36670. * @param {module:echarts/data/Tree~TreeNode} ancestor
  36671. * @return {module:echarts/data/Tree~TreeNode}
  36672. */
  36673. function nextAncestor(nodeInLeft, node, ancestor) {
  36674. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  36675. ? nodeInLeft.hierNode.ancestor : ancestor;
  36676. }
  36677. /**
  36678. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  36679. * @param {module:echarts/data/Tree~TreeNode} wl
  36680. * @param {module:echarts/data/Tree~TreeNode} wr
  36681. * @param {number} shift [description]
  36682. */
  36683. function moveSubtree(wl, wr,shift) {
  36684. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  36685. wr.hierNode.change -= change;
  36686. wr.hierNode.shift += shift;
  36687. wr.hierNode.modifier += shift;
  36688. wr.hierNode.prelim += shift;
  36689. wl.hierNode.change += change;
  36690. }
  36691. function defaultSeparation(node1, node2) {
  36692. return node1.parentNode === node2.parentNode ? 1 : 2;
  36693. }
  36694. /**
  36695. * @file This file used to draw tree view
  36696. */
  36697. extendChartView({
  36698. type: 'tree',
  36699. /**
  36700. * Init the chart
  36701. * @override
  36702. * @param {module:echarts/model/Global} ecModel
  36703. * @param {module:echarts/ExtensionAPI} api
  36704. */
  36705. init: function (ecModel, api) {
  36706. /**
  36707. * @private
  36708. * @type {module:echarts/data/Tree}
  36709. */
  36710. this._oldTree;
  36711. /**
  36712. * @private
  36713. * @type {module:zrender/container/Group}
  36714. */
  36715. this._mainGroup = new Group();
  36716. this.group.add(this._mainGroup);
  36717. },
  36718. render: function (seriesModel, ecModel, api, payload) {
  36719. var data = seriesModel.getData();
  36720. var layoutInfo = seriesModel.layoutInfo;
  36721. var group = this._mainGroup;
  36722. var layout = seriesModel.get('layout');
  36723. if (layout === 'radial') {
  36724. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  36725. }
  36726. else {
  36727. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  36728. }
  36729. var oldData = this._data;
  36730. var seriesScope = {
  36731. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  36732. layout: layout,
  36733. orient: seriesModel.get('orient'),
  36734. curvature: seriesModel.get('lineStyle.curveness'),
  36735. symbolRotate: seriesModel.get('symbolRotate'),
  36736. symbolOffset: seriesModel.get('symbolOffset'),
  36737. hoverAnimation: seriesModel.get('hoverAnimation'),
  36738. useNameLabel: true,
  36739. fadeIn: true
  36740. };
  36741. data.diff(oldData)
  36742. .add(function (newIdx) {
  36743. if (symbolNeedsDraw$1(data, newIdx)) {
  36744. // create node and edge
  36745. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  36746. }
  36747. })
  36748. .update(function (newIdx, oldIdx) {
  36749. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36750. if (!symbolNeedsDraw$1(data, newIdx)) {
  36751. symbolEl && removeNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  36752. return;
  36753. }
  36754. // update node and edge
  36755. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  36756. })
  36757. .remove(function (oldIdx) {
  36758. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36759. removeNode(data, oldIdx, symbolEl, group, seriesModel, seriesScope);
  36760. })
  36761. .execute();
  36762. if (seriesScope.expandAndCollapse === true) {
  36763. data.eachItemGraphicEl(function (el, dataIndex) {
  36764. el.off('click').on('click', function () {
  36765. api.dispatchAction({
  36766. type: 'treeExpandAndCollapse',
  36767. seriesId: seriesModel.id,
  36768. dataIndex: dataIndex
  36769. });
  36770. });
  36771. });
  36772. }
  36773. this._data = data;
  36774. },
  36775. dispose: function () {},
  36776. remove: function () {
  36777. this._mainGroup.removeAll();
  36778. this._data = null;
  36779. }
  36780. });
  36781. function symbolNeedsDraw$1(data, dataIndex) {
  36782. var layout = data.getItemLayout(dataIndex);
  36783. return layout
  36784. && !isNaN(layout.x) && !isNaN(layout.y)
  36785. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  36786. }
  36787. function getTreeNodeStyle(node, itemModel, seriesScope) {
  36788. seriesScope.itemModel = itemModel;
  36789. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  36790. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36791. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  36792. seriesScope.labelModel = itemModel.getModel('label');
  36793. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  36794. if (node.isExpand === false && node.children.length !== 0) {
  36795. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  36796. }
  36797. else {
  36798. seriesScope.symbolInnerColor = '#fff';
  36799. }
  36800. return seriesScope;
  36801. }
  36802. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  36803. var isInit = !symbolEl;
  36804. var node = data.tree.getNodeByDataIndex(dataIndex);
  36805. var itemModel = node.getModel();
  36806. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  36807. var virtualRoot = data.tree.root;
  36808. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  36809. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  36810. var sourceLayout = source.getLayout();
  36811. var sourceOldLayout = sourceSymbolEl
  36812. ? {
  36813. x: sourceSymbolEl.position[0],
  36814. y: sourceSymbolEl.position[1],
  36815. rawX: sourceSymbolEl.__radialOldRawX,
  36816. rawY: sourceSymbolEl.__radialOldRawY
  36817. }
  36818. : sourceLayout;
  36819. var targetLayout = node.getLayout();
  36820. if (isInit) {
  36821. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  36822. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  36823. }
  36824. else {
  36825. symbolEl.updateData(data, dataIndex, seriesScope);
  36826. }
  36827. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  36828. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  36829. symbolEl.__radialRawX = targetLayout.rawX;
  36830. symbolEl.__radialRawY = targetLayout.rawY;
  36831. group.add(symbolEl);
  36832. data.setItemGraphicEl(dataIndex, symbolEl);
  36833. updateProps(symbolEl, {
  36834. position: [targetLayout.x, targetLayout.y]
  36835. }, seriesModel);
  36836. var symbolPath = symbolEl.getSymbolPath();
  36837. if (seriesScope.layout === 'radial') {
  36838. var realRoot = virtualRoot.children[0];
  36839. var rootLayout = realRoot.getLayout();
  36840. var length = realRoot.children.length;
  36841. var rad;
  36842. var isLeft;
  36843. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  36844. var center = {};
  36845. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  36846. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  36847. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  36848. if (rad < 0) {
  36849. rad = Math.PI * 2 + rad;
  36850. }
  36851. isLeft = center.x < rootLayout.x;
  36852. if (isLeft) {
  36853. rad = rad - Math.PI;
  36854. }
  36855. }
  36856. else {
  36857. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  36858. if (rad < 0) {
  36859. rad = Math.PI * 2 + rad;
  36860. }
  36861. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  36862. isLeft = targetLayout.x < rootLayout.x;
  36863. if (isLeft) {
  36864. rad = rad - Math.PI;
  36865. }
  36866. }
  36867. else {
  36868. isLeft = targetLayout.x > rootLayout.x;
  36869. if (!isLeft) {
  36870. rad = rad - Math.PI;
  36871. }
  36872. }
  36873. }
  36874. var textPosition = isLeft ? 'left' : 'right';
  36875. symbolPath.setStyle({
  36876. textPosition: textPosition,
  36877. textRotation: -rad,
  36878. textOrigin: 'center',
  36879. verticalAlign: 'middle'
  36880. });
  36881. }
  36882. if (node.parentNode && node.parentNode !== virtualRoot) {
  36883. var edge = symbolEl.__edge;
  36884. if (!edge) {
  36885. edge = symbolEl.__edge = new BezierCurve({
  36886. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  36887. style: defaults({opacity: 0}, seriesScope.lineStyle)
  36888. });
  36889. }
  36890. updateProps(edge, {
  36891. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  36892. style: {opacity: 1}
  36893. }, seriesModel);
  36894. group.add(edge);
  36895. }
  36896. }
  36897. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  36898. var node = data.tree.getNodeByDataIndex(dataIndex);
  36899. var virtualRoot = data.tree.root;
  36900. var itemModel = node.getModel();
  36901. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  36902. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  36903. var sourceLayout;
  36904. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  36905. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  36906. }
  36907. updateProps(symbolEl, {
  36908. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  36909. }, seriesModel, function () {
  36910. group.remove(symbolEl);
  36911. data.setItemGraphicEl(dataIndex, null);
  36912. });
  36913. symbolEl.fadeOut(null, {keepLabel: true});
  36914. var edge = symbolEl.__edge;
  36915. if (edge) {
  36916. updateProps(edge, {
  36917. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  36918. style: {
  36919. opacity: 0
  36920. }
  36921. }, seriesModel, function () {
  36922. group.remove(edge);
  36923. });
  36924. }
  36925. }
  36926. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  36927. var cpx1;
  36928. var cpy1;
  36929. var cpx2;
  36930. var cpy2;
  36931. var orient = seriesScope.orient;
  36932. if (seriesScope.layout === 'radial') {
  36933. var x1 = sourceLayout.rawX;
  36934. var y1 = sourceLayout.rawY;
  36935. var x2 = targetLayout.rawX;
  36936. var y2 = targetLayout.rawY;
  36937. var radialCoor1 = radialCoordinate(x1, y1);
  36938. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  36939. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  36940. var radialCoor4 = radialCoordinate(x2, y2);
  36941. return {
  36942. x1: radialCoor1.x,
  36943. y1: radialCoor1.y,
  36944. x2: radialCoor4.x,
  36945. y2: radialCoor4.y,
  36946. cpx1: radialCoor2.x,
  36947. cpy1: radialCoor2.y,
  36948. cpx2: radialCoor3.x,
  36949. cpy2: radialCoor3.y
  36950. };
  36951. }
  36952. else {
  36953. var x1 = sourceLayout.x;
  36954. var y1 = sourceLayout.y;
  36955. var x2 = targetLayout.x;
  36956. var y2 = targetLayout.y;
  36957. if (orient === 'horizontal') {
  36958. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  36959. cpy1 = y1;
  36960. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  36961. cpy2 = y2;
  36962. }
  36963. if (orient === 'vertical') {
  36964. cpx1 = x1;
  36965. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  36966. cpx2 = x2;
  36967. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  36968. }
  36969. return {
  36970. x1: x1,
  36971. y1: y1,
  36972. x2: x2,
  36973. y2: y2,
  36974. cpx1: cpx1,
  36975. cpy1: cpy1,
  36976. cpx2: cpx2,
  36977. cpy2: cpy2
  36978. };
  36979. }
  36980. }
  36981. registerAction({
  36982. type: 'treeExpandAndCollapse',
  36983. event: 'treeExpandAndCollapse',
  36984. update: 'update'
  36985. }, function (payload, ecModel) {
  36986. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  36987. var dataIndex = payload.dataIndex;
  36988. var tree = seriesModel.getData().tree;
  36989. var node = tree.getNodeByDataIndex(dataIndex);
  36990. node.isExpand = !node.isExpand;
  36991. });
  36992. });
  36993. /**
  36994. * Traverse the tree from bottom to top and do something
  36995. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  36996. * @param {Function} callback
  36997. */
  36998. function eachAfter (root, callback, separation) {
  36999. var nodes = [root];
  37000. var next = [];
  37001. var node;
  37002. while (node = nodes.pop()) { // jshint ignore:line
  37003. next.push(node);
  37004. if (node.isExpand) {
  37005. var children = node.children;
  37006. if (children.length) {
  37007. for (var i = 0; i < children.length; i++) {
  37008. nodes.push(children[i]);
  37009. }
  37010. }
  37011. }
  37012. }
  37013. while (node = next.pop()) { // jshint ignore:line
  37014. callback(node, separation);
  37015. }
  37016. }
  37017. /**
  37018. * Traverse the tree from top to bottom and do something
  37019. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  37020. * @param {Function} callback
  37021. */
  37022. function eachBefore (root, callback) {
  37023. var nodes = [root];
  37024. var node;
  37025. while (node = nodes.pop()) { // jshint ignore:line
  37026. callback(node);
  37027. if (node.isExpand) {
  37028. var children = node.children;
  37029. if (children.length) {
  37030. for (var i = children.length - 1; i >= 0; i--) {
  37031. nodes.push(children[i]);
  37032. }
  37033. }
  37034. }
  37035. }
  37036. }
  37037. var commonLayout = function (seriesModel, api) {
  37038. var layoutInfo = getViewRect(seriesModel, api);
  37039. seriesModel.layoutInfo = layoutInfo;
  37040. var layout = seriesModel.get('layout');
  37041. var width = 0;
  37042. var height = 0;
  37043. var separation$$1 = null;
  37044. if (layout === 'radial') {
  37045. width = 2 * Math.PI;
  37046. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  37047. separation$$1 = separation(function (node1, node2) {
  37048. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  37049. });
  37050. }
  37051. else {
  37052. width = layoutInfo.width;
  37053. height = layoutInfo.height;
  37054. separation$$1 = separation();
  37055. }
  37056. var virtualRoot = seriesModel.getData().tree.root;
  37057. var realRoot = virtualRoot.children[0];
  37058. init$2(virtualRoot);
  37059. eachAfter(realRoot, firstWalk, separation$$1);
  37060. virtualRoot.hierNode.modifier = - realRoot.hierNode.prelim;
  37061. eachBefore(realRoot, secondWalk);
  37062. var left = realRoot;
  37063. var right = realRoot;
  37064. var bottom = realRoot;
  37065. eachBefore(realRoot, function (node) {
  37066. var x = node.getLayout().x;
  37067. if (x < left.getLayout().x) {
  37068. left = node;
  37069. }
  37070. if (x > right.getLayout().x) {
  37071. right = node;
  37072. }
  37073. if (node.depth > bottom.depth) {
  37074. bottom = node;
  37075. }
  37076. });
  37077. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  37078. var tx = delta - left.getLayout().x;
  37079. var kx = 0;
  37080. var ky = 0;
  37081. var coorX = 0;
  37082. var coorY = 0;
  37083. if (layout === 'radial') {
  37084. kx = width / (right.getLayout().x + delta + tx);
  37085. // here we use (node.depth - 1), bucause the real root's depth is 1
  37086. ky = height/ ((bottom.depth - 1) || 1);
  37087. eachBefore(realRoot, function (node) {
  37088. coorX = (node.getLayout().x + tx) * kx;
  37089. coorY = (node.depth - 1) * ky;
  37090. var finalCoor = radialCoordinate(coorX, coorY);
  37091. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  37092. });
  37093. }
  37094. else {
  37095. if (seriesModel.get('orient') === 'horizontal') {
  37096. ky = height / (right.getLayout().x + delta + tx);
  37097. kx = width / ((bottom.depth - 1) || 1);
  37098. eachBefore(realRoot, function (node) {
  37099. coorY = (node.getLayout().x + tx) * ky;
  37100. coorX = (node.depth - 1) * kx;
  37101. node.setLayout({x: coorX, y: coorY}, true);
  37102. });
  37103. }
  37104. else {
  37105. kx = width / (right.getLayout().x + delta + tx);
  37106. ky = height / ((bottom.depth - 1) || 1);
  37107. eachBefore(realRoot, function (node) {
  37108. coorX = (node.getLayout().x + tx) * kx;
  37109. coorY = (node.depth - 1) * ky;
  37110. node.setLayout({x: coorX, y: coorY}, true);
  37111. });
  37112. }
  37113. }
  37114. };
  37115. var orthogonalLayout = function (ecModel, api) {
  37116. ecModel.eachSeriesByType('tree', function (seriesModel) {
  37117. commonLayout(seriesModel, api);
  37118. });
  37119. };
  37120. var radialLayout = function (ecModel, api) {
  37121. ecModel.eachSeriesByType('tree', function (seriesModel) {
  37122. commonLayout(seriesModel, api);
  37123. });
  37124. };
  37125. registerVisual(visualSymbol('tree', 'circle'));
  37126. registerLayout(orthogonalLayout);
  37127. registerLayout(radialLayout);
  37128. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  37129. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  37130. var root = seriesModel.getData().tree.root;
  37131. var targetNode = payload.targetNode;
  37132. if (targetNode && root.contains(targetNode)) {
  37133. return {node: targetNode};
  37134. }
  37135. var targetNodeId = payload.targetNodeId;
  37136. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  37137. return {node: targetNode};
  37138. }
  37139. }
  37140. }
  37141. // Not includes the given node at the last item.
  37142. function getPathToRoot(node) {
  37143. var path = [];
  37144. while (node) {
  37145. node = node.parentNode;
  37146. node && path.push(node);
  37147. }
  37148. return path.reverse();
  37149. }
  37150. function aboveViewRoot(viewRoot, node) {
  37151. var viewPath = getPathToRoot(viewRoot);
  37152. return indexOf(viewPath, node) >= 0;
  37153. }
  37154. // From root to the input node (the input node will be included).
  37155. function wrapTreePathInfo(node, seriesModel) {
  37156. var treePathInfo = [];
  37157. while (node) {
  37158. var nodeDataIndex = node.dataIndex;
  37159. treePathInfo.push({
  37160. name: node.name,
  37161. dataIndex: nodeDataIndex,
  37162. value: seriesModel.getRawValue(nodeDataIndex)
  37163. });
  37164. node = node.parentNode;
  37165. }
  37166. treePathInfo.reverse();
  37167. return treePathInfo;
  37168. }
  37169. SeriesModel.extend({
  37170. type: 'series.treemap',
  37171. layoutMode: 'box',
  37172. dependencies: ['grid', 'polar'],
  37173. /**
  37174. * @type {module:echarts/data/Tree~Node}
  37175. */
  37176. _viewRoot: null,
  37177. defaultOption: {
  37178. // Disable progressive rendering
  37179. progressive: 0,
  37180. hoverLayerThreshold: Infinity,
  37181. // center: ['50%', '50%'], // not supported in ec3.
  37182. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  37183. left: 'center',
  37184. top: 'middle',
  37185. right: null,
  37186. bottom: null,
  37187. width: '80%',
  37188. height: '80%',
  37189. sort: true, // Can be null or false or true
  37190. // (order by desc default, asc not supported yet (strange effect))
  37191. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  37192. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  37193. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  37194. // Count from zero (zero represents only view root).
  37195. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  37196. // to align specialized icon. ▷▶❒❐▼✚
  37197. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  37198. // target node area in the view area.
  37199. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  37200. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  37201. // If leafDepth is set and clicking a node which has children but
  37202. // be on left depth, the behaviour would be changing root. Otherwise
  37203. // use behavious defined above.
  37204. animation: true,
  37205. animationDurationUpdate: 900,
  37206. animationEasing: 'quinticInOut',
  37207. breadcrumb: {
  37208. show: true,
  37209. height: 22,
  37210. left: 'center',
  37211. top: 'bottom',
  37212. // right
  37213. // bottom
  37214. emptyItemWidth: 25, // Width of empty node.
  37215. itemStyle: {
  37216. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  37217. borderColor: 'rgba(255,255,255,0.7)',
  37218. borderWidth: 1,
  37219. shadowColor: 'rgba(150,150,150,1)',
  37220. shadowBlur: 3,
  37221. shadowOffsetX: 0,
  37222. shadowOffsetY: 0,
  37223. textStyle: {
  37224. color: '#fff'
  37225. }
  37226. },
  37227. emphasis: {
  37228. textStyle: {}
  37229. }
  37230. },
  37231. label: {
  37232. show: true,
  37233. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  37234. distance: 0,
  37235. padding: 5,
  37236. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  37237. // formatter: null,
  37238. color: '#fff',
  37239. ellipsis: true
  37240. // align
  37241. // verticalAlign
  37242. },
  37243. upperLabel: { // Label when node is parent.
  37244. show: false,
  37245. position: [0, '50%'],
  37246. height: 20,
  37247. // formatter: null,
  37248. color: '#fff',
  37249. ellipsis: true,
  37250. // align: null,
  37251. verticalAlign: 'middle'
  37252. },
  37253. itemStyle: {
  37254. color: null, // Can be 'none' if not necessary.
  37255. colorAlpha: null, // Can be 'none' if not necessary.
  37256. colorSaturation: null, // Can be 'none' if not necessary.
  37257. borderWidth: 0,
  37258. gapWidth: 0,
  37259. borderColor: '#fff',
  37260. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  37261. // border color is evaluated by color of current node and
  37262. // borderColorSaturation.
  37263. },
  37264. emphasis: {
  37265. upperLabel: {
  37266. show: true,
  37267. position: [0, '50%'],
  37268. color: '#fff',
  37269. ellipsis: true,
  37270. verticalAlign: 'middle'
  37271. }
  37272. },
  37273. visualDimension: 0, // Can be 0, 1, 2, 3.
  37274. visualMin: null,
  37275. visualMax: null,
  37276. color: [], // + treemapSeries.color should not be modified. Please only modified
  37277. // level[n].color (if necessary).
  37278. // + Specify color list of each level. level[0].color would be global
  37279. // color list if not specified. (see method `setDefault`).
  37280. // + But set as a empty array to forbid fetch color from global palette
  37281. // when using nodeModel.get('color'), otherwise nodes on deep level
  37282. // will always has color palette set and are not able to inherit color
  37283. // from parent node.
  37284. // + TreemapSeries.color can not be set as 'none', otherwise effect
  37285. // legend color fetching (see seriesColor.js).
  37286. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  37287. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  37288. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  37289. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  37290. // be rendered. Only works when sort is 'asc' or 'desc'.
  37291. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  37292. // grandchildren will not show.
  37293. // Why grandchildren? If not grandchildren but children,
  37294. // some siblings show children and some not,
  37295. // the appearance may be mess and not consistent,
  37296. levels: [] // Each item: {
  37297. // visibleMin, itemStyle, visualDimension, label
  37298. // }
  37299. // data: {
  37300. // value: [],
  37301. // children: [],
  37302. // link: 'http://xxx.xxx.xxx',
  37303. // target: 'blank' or 'self'
  37304. // }
  37305. },
  37306. /**
  37307. * @override
  37308. */
  37309. getInitialData: function (option, ecModel) {
  37310. // Create a virtual root.
  37311. var root = {name: option.name, children: option.data};
  37312. completeTreeValue(root);
  37313. var levels = option.levels || [];
  37314. levels = option.levels = setDefault(levels, ecModel);
  37315. var treeOption = {};
  37316. treeOption.levels = levels;
  37317. // Make sure always a new tree is created when setOption,
  37318. // in TreemapView, we check whether oldTree === newTree
  37319. // to choose mappings approach among old shapes and new shapes.
  37320. return Tree.createTree(root, this, treeOption).data;
  37321. },
  37322. optionUpdated: function () {
  37323. this.resetViewRoot();
  37324. },
  37325. /**
  37326. * @override
  37327. * @param {number} dataIndex
  37328. * @param {boolean} [mutipleSeries=false]
  37329. */
  37330. formatTooltip: function (dataIndex) {
  37331. var data = this.getData();
  37332. var value = this.getRawValue(dataIndex);
  37333. var formattedValue = isArray(value)
  37334. ? addCommas(value[0]) : addCommas(value);
  37335. var name = data.getName(dataIndex);
  37336. return encodeHTML(name + ': ' + formattedValue);
  37337. },
  37338. /**
  37339. * Add tree path to tooltip param
  37340. *
  37341. * @override
  37342. * @param {number} dataIndex
  37343. * @return {Object}
  37344. */
  37345. getDataParams: function (dataIndex) {
  37346. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  37347. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  37348. params.treePathInfo = wrapTreePathInfo(node, this);
  37349. return params;
  37350. },
  37351. /**
  37352. * @public
  37353. * @param {Object} layoutInfo {
  37354. * x: containerGroup x
  37355. * y: containerGroup y
  37356. * width: containerGroup width
  37357. * height: containerGroup height
  37358. * }
  37359. */
  37360. setLayoutInfo: function (layoutInfo) {
  37361. /**
  37362. * @readOnly
  37363. * @type {Object}
  37364. */
  37365. this.layoutInfo = this.layoutInfo || {};
  37366. extend(this.layoutInfo, layoutInfo);
  37367. },
  37368. /**
  37369. * @param {string} id
  37370. * @return {number} index
  37371. */
  37372. mapIdToIndex: function (id) {
  37373. // A feature is implemented:
  37374. // index is monotone increasing with the sequence of
  37375. // input id at the first time.
  37376. // This feature can make sure that each data item and its
  37377. // mapped color have the same index between data list and
  37378. // color list at the beginning, which is useful for user
  37379. // to adjust data-color mapping.
  37380. /**
  37381. * @private
  37382. * @type {Object}
  37383. */
  37384. var idIndexMap = this._idIndexMap;
  37385. if (!idIndexMap) {
  37386. idIndexMap = this._idIndexMap = createHashMap();
  37387. /**
  37388. * @private
  37389. * @type {number}
  37390. */
  37391. this._idIndexMapCount = 0;
  37392. }
  37393. var index = idIndexMap.get(id);
  37394. if (index == null) {
  37395. idIndexMap.set(id, index = this._idIndexMapCount++);
  37396. }
  37397. return index;
  37398. },
  37399. getViewRoot: function () {
  37400. return this._viewRoot;
  37401. },
  37402. /**
  37403. * @param {module:echarts/data/Tree~Node} [viewRoot]
  37404. */
  37405. resetViewRoot: function (viewRoot) {
  37406. viewRoot
  37407. ? (this._viewRoot = viewRoot)
  37408. : (viewRoot = this._viewRoot);
  37409. var root = this.getRawData().tree.root;
  37410. if (!viewRoot
  37411. || (viewRoot !== root && !root.contains(viewRoot))
  37412. ) {
  37413. this._viewRoot = root;
  37414. }
  37415. }
  37416. });
  37417. /**
  37418. * @param {Object} dataNode
  37419. */
  37420. function completeTreeValue(dataNode) {
  37421. // Postorder travel tree.
  37422. // If value of none-leaf node is not set,
  37423. // calculate it by suming up the value of all children.
  37424. var sum = 0;
  37425. each$1(dataNode.children, function (child) {
  37426. completeTreeValue(child);
  37427. var childValue = child.value;
  37428. isArray(childValue) && (childValue = childValue[0]);
  37429. sum += childValue;
  37430. });
  37431. var thisValue = dataNode.value;
  37432. if (isArray(thisValue)) {
  37433. thisValue = thisValue[0];
  37434. }
  37435. if (thisValue == null || isNaN(thisValue)) {
  37436. thisValue = sum;
  37437. }
  37438. // Value should not less than 0.
  37439. if (thisValue < 0) {
  37440. thisValue = 0;
  37441. }
  37442. isArray(dataNode.value)
  37443. ? (dataNode.value[0] = thisValue)
  37444. : (dataNode.value = thisValue);
  37445. }
  37446. /**
  37447. * set default to level configuration
  37448. */
  37449. function setDefault(levels, ecModel) {
  37450. var globalColorList = ecModel.get('color');
  37451. if (!globalColorList) {
  37452. return;
  37453. }
  37454. levels = levels || [];
  37455. var hasColorDefine;
  37456. each$1(levels, function (levelDefine) {
  37457. var model = new Model(levelDefine);
  37458. var modelColor = model.get('color');
  37459. if (model.get('itemStyle.color')
  37460. || (modelColor && modelColor !== 'none')
  37461. ) {
  37462. hasColorDefine = true;
  37463. }
  37464. });
  37465. if (!hasColorDefine) {
  37466. var level0 = levels[0] || (levels[0] = {});
  37467. level0.color = globalColorList.slice();
  37468. }
  37469. return levels;
  37470. }
  37471. var TEXT_PADDING = 8;
  37472. var ITEM_GAP = 8;
  37473. var ARRAY_LENGTH = 5;
  37474. function Breadcrumb(containerGroup) {
  37475. /**
  37476. * @private
  37477. * @type {module:zrender/container/Group}
  37478. */
  37479. this.group = new Group();
  37480. containerGroup.add(this.group);
  37481. }
  37482. Breadcrumb.prototype = {
  37483. constructor: Breadcrumb,
  37484. render: function (seriesModel, api, targetNode, onSelect) {
  37485. var model = seriesModel.getModel('breadcrumb');
  37486. var thisGroup = this.group;
  37487. thisGroup.removeAll();
  37488. if (!model.get('show') || !targetNode) {
  37489. return;
  37490. }
  37491. var normalStyleModel = model.getModel('itemStyle');
  37492. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  37493. var textStyleModel = normalStyleModel.getModel('textStyle');
  37494. var layoutParam = {
  37495. pos: {
  37496. left: model.get('left'),
  37497. right: model.get('right'),
  37498. top: model.get('top'),
  37499. bottom: model.get('bottom')
  37500. },
  37501. box: {
  37502. width: api.getWidth(),
  37503. height: api.getHeight()
  37504. },
  37505. emptyItemWidth: model.get('emptyItemWidth'),
  37506. totalWidth: 0,
  37507. renderList: []
  37508. };
  37509. this._prepare(targetNode, layoutParam, textStyleModel);
  37510. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  37511. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  37512. },
  37513. /**
  37514. * Prepare render list and total width
  37515. * @private
  37516. */
  37517. _prepare: function (targetNode, layoutParam, textStyleModel) {
  37518. for (var node = targetNode; node; node = node.parentNode) {
  37519. var text = node.getModel().get('name');
  37520. var textRect = textStyleModel.getTextRect(text);
  37521. var itemWidth = Math.max(
  37522. textRect.width + TEXT_PADDING * 2,
  37523. layoutParam.emptyItemWidth
  37524. );
  37525. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  37526. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  37527. }
  37528. },
  37529. /**
  37530. * @private
  37531. */
  37532. _renderContent: function (
  37533. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  37534. ) {
  37535. // Start rendering.
  37536. var lastX = 0;
  37537. var emptyItemWidth = layoutParam.emptyItemWidth;
  37538. var height = seriesModel.get('breadcrumb.height');
  37539. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  37540. var totalWidth = layoutParam.totalWidth;
  37541. var renderList = layoutParam.renderList;
  37542. for (var i = renderList.length - 1; i >= 0; i--) {
  37543. var item = renderList[i];
  37544. var itemNode = item.node;
  37545. var itemWidth = item.width;
  37546. var text = item.text;
  37547. // Hdie text and shorten width if necessary.
  37548. if (totalWidth > availableSize.width) {
  37549. totalWidth -= itemWidth - emptyItemWidth;
  37550. itemWidth = emptyItemWidth;
  37551. text = null;
  37552. }
  37553. var el = new Polygon({
  37554. shape: {
  37555. points: makeItemPoints(
  37556. lastX, 0, itemWidth, height,
  37557. i === renderList.length - 1, i === 0
  37558. )
  37559. },
  37560. style: defaults(
  37561. normalStyleModel.getItemStyle(),
  37562. {
  37563. lineJoin: 'bevel',
  37564. text: text,
  37565. textFill: textStyleModel.getTextColor(),
  37566. textFont: textStyleModel.getFont()
  37567. }
  37568. ),
  37569. z: 10,
  37570. onclick: curry(onSelect, itemNode)
  37571. });
  37572. this.group.add(el);
  37573. packEventData(el, seriesModel, itemNode);
  37574. lastX += itemWidth + ITEM_GAP;
  37575. }
  37576. },
  37577. /**
  37578. * @override
  37579. */
  37580. remove: function () {
  37581. this.group.removeAll();
  37582. }
  37583. };
  37584. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  37585. var points = [
  37586. [head ? x : x - ARRAY_LENGTH, y],
  37587. [x + itemWidth, y],
  37588. [x + itemWidth, y + itemHeight],
  37589. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  37590. ];
  37591. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  37592. !head && points.push([x, y + itemHeight / 2]);
  37593. return points;
  37594. }
  37595. // Package custom mouse event.
  37596. function packEventData(el, seriesModel, itemNode) {
  37597. el.eventData = {
  37598. componentType: 'series',
  37599. componentSubType: 'treemap',
  37600. seriesIndex: seriesModel.componentIndex,
  37601. seriesName: seriesModel.name,
  37602. seriesType: 'treemap',
  37603. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  37604. nodeData: {
  37605. dataIndex: itemNode && itemNode.dataIndex,
  37606. name: itemNode && itemNode.name
  37607. },
  37608. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  37609. };
  37610. }
  37611. /**
  37612. * @param {number} [time=500] Time in ms
  37613. * @param {string} [easing='linear']
  37614. * @param {number} [delay=0]
  37615. * @param {Function} [callback]
  37616. *
  37617. * @example
  37618. * // Animate position
  37619. * animation
  37620. * .createWrap()
  37621. * .add(el1, {position: [10, 10]})
  37622. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  37623. * .done(function () { // done })
  37624. * .start('cubicOut');
  37625. */
  37626. function createWrap() {
  37627. var storage = [];
  37628. var elExistsMap = {};
  37629. var doneCallback;
  37630. return {
  37631. /**
  37632. * Caution: a el can only be added once, otherwise 'done'
  37633. * might not be called. This method checks this (by el.id),
  37634. * suppresses adding and returns false when existing el found.
  37635. *
  37636. * @param {modele:zrender/Element} el
  37637. * @param {Object} target
  37638. * @param {number} [time=500]
  37639. * @param {number} [delay=0]
  37640. * @param {string} [easing='linear']
  37641. * @return {boolean} Whether adding succeeded.
  37642. *
  37643. * @example
  37644. * add(el, target, time, delay, easing);
  37645. * add(el, target, time, easing);
  37646. * add(el, target, time);
  37647. * add(el, target);
  37648. */
  37649. add: function (el, target, time, delay, easing) {
  37650. if (isString(delay)) {
  37651. easing = delay;
  37652. delay = 0;
  37653. }
  37654. if (elExistsMap[el.id]) {
  37655. return false;
  37656. }
  37657. elExistsMap[el.id] = 1;
  37658. storage.push(
  37659. {el: el, target: target, time: time, delay: delay, easing: easing}
  37660. );
  37661. return true;
  37662. },
  37663. /**
  37664. * Only execute when animation finished. Will not execute when any
  37665. * of 'stop' or 'stopAnimation' called.
  37666. *
  37667. * @param {Function} callback
  37668. */
  37669. done: function (callback) {
  37670. doneCallback = callback;
  37671. return this;
  37672. },
  37673. /**
  37674. * Will stop exist animation firstly.
  37675. */
  37676. start: function () {
  37677. var count = storage.length;
  37678. for (var i = 0, len = storage.length; i < len; i++) {
  37679. var item = storage[i];
  37680. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  37681. }
  37682. return this;
  37683. function done() {
  37684. count--;
  37685. if (!count) {
  37686. storage.length = 0;
  37687. elExistsMap = {};
  37688. doneCallback && doneCallback();
  37689. }
  37690. }
  37691. }
  37692. };
  37693. }
  37694. var bind$1 = bind;
  37695. var Group$2 = Group;
  37696. var Rect$1 = Rect;
  37697. var each$9 = each$1;
  37698. var DRAG_THRESHOLD = 3;
  37699. var PATH_LABEL_NOAMAL = ['label'];
  37700. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  37701. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  37702. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  37703. var Z_BASE = 10; // Should bigger than every z.
  37704. var Z_BG = 1;
  37705. var Z_CONTENT = 2;
  37706. var getItemStyleEmphasis = makeStyleMapper([
  37707. ['fill', 'color'],
  37708. // `borderColor` and `borderWidth` has been occupied,
  37709. // so use `stroke` to indicate the stroke of the rect.
  37710. ['stroke', 'strokeColor'],
  37711. ['lineWidth', 'strokeWidth'],
  37712. ['shadowBlur'],
  37713. ['shadowOffsetX'],
  37714. ['shadowOffsetY'],
  37715. ['shadowColor']
  37716. ]);
  37717. var getItemStyleNormal = function (model) {
  37718. // Normal style props should include emphasis style props.
  37719. var itemStyle = getItemStyleEmphasis(model);
  37720. // Clear styles set by emphasis.
  37721. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  37722. return itemStyle;
  37723. };
  37724. extendChartView({
  37725. type: 'treemap',
  37726. /**
  37727. * @override
  37728. */
  37729. init: function (o, api) {
  37730. /**
  37731. * @private
  37732. * @type {module:zrender/container/Group}
  37733. */
  37734. this._containerGroup;
  37735. /**
  37736. * @private
  37737. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  37738. */
  37739. this._storage = createStorage();
  37740. /**
  37741. * @private
  37742. * @type {module:echarts/data/Tree}
  37743. */
  37744. this._oldTree;
  37745. /**
  37746. * @private
  37747. * @type {module:echarts/chart/treemap/Breadcrumb}
  37748. */
  37749. this._breadcrumb;
  37750. /**
  37751. * @private
  37752. * @type {module:echarts/component/helper/RoamController}
  37753. */
  37754. this._controller;
  37755. /**
  37756. * 'ready', 'animating'
  37757. * @private
  37758. */
  37759. this._state = 'ready';
  37760. },
  37761. /**
  37762. * @override
  37763. */
  37764. render: function (seriesModel, ecModel, api, payload) {
  37765. var models = ecModel.findComponents({
  37766. mainType: 'series', subType: 'treemap', query: payload
  37767. });
  37768. if (indexOf(models, seriesModel) < 0) {
  37769. return;
  37770. }
  37771. this.seriesModel = seriesModel;
  37772. this.api = api;
  37773. this.ecModel = ecModel;
  37774. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  37775. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  37776. var payloadType = payload && payload.type;
  37777. var layoutInfo = seriesModel.layoutInfo;
  37778. var isInit = !this._oldTree;
  37779. var thisStorage = this._storage;
  37780. // Mark new root when action is treemapRootToNode.
  37781. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  37782. ? {
  37783. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  37784. direction: payload.direction
  37785. }
  37786. : null;
  37787. var containerGroup = this._giveContainerGroup(layoutInfo);
  37788. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  37789. (
  37790. !isInit && (
  37791. !payloadType
  37792. || payloadType === 'treemapZoomToNode'
  37793. || payloadType === 'treemapRootToNode'
  37794. )
  37795. )
  37796. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  37797. : renderResult.renderFinally();
  37798. this._resetController(api);
  37799. this._renderBreadcrumb(seriesModel, api, targetInfo);
  37800. },
  37801. /**
  37802. * @private
  37803. */
  37804. _giveContainerGroup: function (layoutInfo) {
  37805. var containerGroup = this._containerGroup;
  37806. if (!containerGroup) {
  37807. // FIXME
  37808. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  37809. containerGroup = this._containerGroup = new Group$2();
  37810. this._initEvents(containerGroup);
  37811. this.group.add(containerGroup);
  37812. }
  37813. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  37814. return containerGroup;
  37815. },
  37816. /**
  37817. * @private
  37818. */
  37819. _doRender: function (containerGroup, seriesModel, reRoot) {
  37820. var thisTree = seriesModel.getData().tree;
  37821. var oldTree = this._oldTree;
  37822. // Clear last shape records.
  37823. var lastsForAnimation = createStorage();
  37824. var thisStorage = createStorage();
  37825. var oldStorage = this._storage;
  37826. var willInvisibleEls = [];
  37827. var doRenderNode = curry(
  37828. renderNode, seriesModel,
  37829. thisStorage, oldStorage, reRoot,
  37830. lastsForAnimation, willInvisibleEls
  37831. );
  37832. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  37833. // the oldTree is actually losted, so we can not find all of the old graphic
  37834. // elements from tree. So we use this stragegy: make element storage, move
  37835. // from old storage to new storage, clear old storage.
  37836. dualTravel(
  37837. thisTree.root ? [thisTree.root] : [],
  37838. (oldTree && oldTree.root) ? [oldTree.root] : [],
  37839. containerGroup,
  37840. thisTree === oldTree || !oldTree,
  37841. 0
  37842. );
  37843. // Process all removing.
  37844. var willDeleteEls = clearStorage(oldStorage);
  37845. this._oldTree = thisTree;
  37846. this._storage = thisStorage;
  37847. return {
  37848. lastsForAnimation: lastsForAnimation,
  37849. willDeleteEls: willDeleteEls,
  37850. renderFinally: renderFinally
  37851. };
  37852. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  37853. // When 'render' is triggered by action,
  37854. // 'this' and 'old' may be the same tree,
  37855. // we use rawIndex in that case.
  37856. if (sameTree) {
  37857. oldViewChildren = thisViewChildren;
  37858. each$9(thisViewChildren, function (child, index) {
  37859. !child.isRemoved() && processNode(index, index);
  37860. });
  37861. }
  37862. // Diff hierarchically (diff only in each subtree, but not whole).
  37863. // because, consistency of view is important.
  37864. else {
  37865. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  37866. .add(processNode)
  37867. .update(processNode)
  37868. .remove(curry(processNode, null))
  37869. .execute();
  37870. }
  37871. function getKey(node) {
  37872. // Identify by name or raw index.
  37873. return node.getId();
  37874. }
  37875. function processNode(newIndex, oldIndex) {
  37876. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  37877. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  37878. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  37879. group && dualTravel(
  37880. thisNode && thisNode.viewChildren || [],
  37881. oldNode && oldNode.viewChildren || [],
  37882. group,
  37883. sameTree,
  37884. depth + 1
  37885. );
  37886. }
  37887. }
  37888. function clearStorage(storage) {
  37889. var willDeleteEls = createStorage();
  37890. storage && each$9(storage, function (store, storageName) {
  37891. var delEls = willDeleteEls[storageName];
  37892. each$9(store, function (el) {
  37893. el && (delEls.push(el), el.__tmWillDelete = 1);
  37894. });
  37895. });
  37896. return willDeleteEls;
  37897. }
  37898. function renderFinally() {
  37899. each$9(willDeleteEls, function (els) {
  37900. each$9(els, function (el) {
  37901. el.parent && el.parent.remove(el);
  37902. });
  37903. });
  37904. each$9(willInvisibleEls, function (el) {
  37905. el.invisible = true;
  37906. // Setting invisible is for optimizing, so no need to set dirty,
  37907. // just mark as invisible.
  37908. el.dirty();
  37909. });
  37910. }
  37911. },
  37912. /**
  37913. * @private
  37914. */
  37915. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  37916. if (!seriesModel.get('animation')) {
  37917. return;
  37918. }
  37919. var duration = seriesModel.get('animationDurationUpdate');
  37920. var easing = seriesModel.get('animationEasing');
  37921. var animationWrap = createWrap();
  37922. // Make delete animations.
  37923. each$9(renderResult.willDeleteEls, function (store, storageName) {
  37924. each$9(store, function (el, rawIndex) {
  37925. if (el.invisible) {
  37926. return;
  37927. }
  37928. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  37929. var target;
  37930. if (reRoot && reRoot.direction === 'drillDown') {
  37931. target = parent === reRoot.rootNodeGroup
  37932. // This is the content element of view root.
  37933. // Only `content` will enter this branch, because
  37934. // `background` and `nodeGroup` will not be deleted.
  37935. ? {
  37936. shape: {
  37937. x: 0,
  37938. y: 0,
  37939. width: parent.__tmNodeWidth,
  37940. height: parent.__tmNodeHeight
  37941. },
  37942. style: {
  37943. opacity: 0
  37944. }
  37945. }
  37946. // Others.
  37947. : {style: {opacity: 0}};
  37948. }
  37949. else {
  37950. var targetX = 0;
  37951. var targetY = 0;
  37952. if (!parent.__tmWillDelete) {
  37953. // Let node animate to right-bottom corner, cooperating with fadeout,
  37954. // which is appropriate for user understanding.
  37955. // Divided by 2 for reRoot rolling up effect.
  37956. targetX = parent.__tmNodeWidth / 2;
  37957. targetY = parent.__tmNodeHeight / 2;
  37958. }
  37959. target = storageName === 'nodeGroup'
  37960. ? {position: [targetX, targetY], style: {opacity: 0}}
  37961. : {
  37962. shape: {x: targetX, y: targetY, width: 0, height: 0},
  37963. style: {opacity: 0}
  37964. };
  37965. }
  37966. target && animationWrap.add(el, target, duration, easing);
  37967. });
  37968. });
  37969. // Make other animations
  37970. each$9(this._storage, function (store, storageName) {
  37971. each$9(store, function (el, rawIndex) {
  37972. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  37973. var target = {};
  37974. if (!last) {
  37975. return;
  37976. }
  37977. if (storageName === 'nodeGroup') {
  37978. if (last.old) {
  37979. target.position = el.position.slice();
  37980. el.attr('position', last.old);
  37981. }
  37982. }
  37983. else {
  37984. if (last.old) {
  37985. target.shape = extend({}, el.shape);
  37986. el.setShape(last.old);
  37987. }
  37988. if (last.fadein) {
  37989. el.setStyle('opacity', 0);
  37990. target.style = {opacity: 1};
  37991. }
  37992. // When animation is stopped for succedent animation starting,
  37993. // el.style.opacity might not be 1
  37994. else if (el.style.opacity !== 1) {
  37995. target.style = {opacity: 1};
  37996. }
  37997. }
  37998. animationWrap.add(el, target, duration, easing);
  37999. });
  38000. }, this);
  38001. this._state = 'animating';
  38002. animationWrap
  38003. .done(bind$1(function () {
  38004. this._state = 'ready';
  38005. renderResult.renderFinally();
  38006. }, this))
  38007. .start();
  38008. },
  38009. /**
  38010. * @private
  38011. */
  38012. _resetController: function (api) {
  38013. var controller = this._controller;
  38014. // Init controller.
  38015. if (!controller) {
  38016. controller = this._controller = new RoamController(api.getZr());
  38017. controller.enable(this.seriesModel.get('roam'));
  38018. controller.on('pan', bind$1(this._onPan, this));
  38019. controller.on('zoom', bind$1(this._onZoom, this));
  38020. }
  38021. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  38022. controller.setPointerChecker(function (e, x, y) {
  38023. return rect.contain(x, y);
  38024. });
  38025. },
  38026. /**
  38027. * @private
  38028. */
  38029. _clearController: function () {
  38030. var controller = this._controller;
  38031. if (controller) {
  38032. controller.dispose();
  38033. controller = null;
  38034. }
  38035. },
  38036. /**
  38037. * @private
  38038. */
  38039. _onPan: function (dx, dy) {
  38040. if (this._state !== 'animating'
  38041. && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
  38042. ) {
  38043. // These param must not be cached.
  38044. var root = this.seriesModel.getData().tree.root;
  38045. if (!root) {
  38046. return;
  38047. }
  38048. var rootLayout = root.getLayout();
  38049. if (!rootLayout) {
  38050. return;
  38051. }
  38052. this.api.dispatchAction({
  38053. type: 'treemapMove',
  38054. from: this.uid,
  38055. seriesId: this.seriesModel.id,
  38056. rootRect: {
  38057. x: rootLayout.x + dx, y: rootLayout.y + dy,
  38058. width: rootLayout.width, height: rootLayout.height
  38059. }
  38060. });
  38061. }
  38062. },
  38063. /**
  38064. * @private
  38065. */
  38066. _onZoom: function (scale, mouseX, mouseY) {
  38067. if (this._state !== 'animating') {
  38068. // These param must not be cached.
  38069. var root = this.seriesModel.getData().tree.root;
  38070. if (!root) {
  38071. return;
  38072. }
  38073. var rootLayout = root.getLayout();
  38074. if (!rootLayout) {
  38075. return;
  38076. }
  38077. var rect = new BoundingRect(
  38078. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  38079. );
  38080. var layoutInfo = this.seriesModel.layoutInfo;
  38081. // Transform mouse coord from global to containerGroup.
  38082. mouseX -= layoutInfo.x;
  38083. mouseY -= layoutInfo.y;
  38084. // Scale root bounding rect.
  38085. var m = create$1();
  38086. translate(m, m, [-mouseX, -mouseY]);
  38087. scale$1(m, m, [scale, scale]);
  38088. translate(m, m, [mouseX, mouseY]);
  38089. rect.applyTransform(m);
  38090. this.api.dispatchAction({
  38091. type: 'treemapRender',
  38092. from: this.uid,
  38093. seriesId: this.seriesModel.id,
  38094. rootRect: {
  38095. x: rect.x, y: rect.y,
  38096. width: rect.width, height: rect.height
  38097. }
  38098. });
  38099. }
  38100. },
  38101. /**
  38102. * @private
  38103. */
  38104. _initEvents: function (containerGroup) {
  38105. containerGroup.on('click', function (e) {
  38106. if (this._state !== 'ready') {
  38107. return;
  38108. }
  38109. var nodeClick = this.seriesModel.get('nodeClick', true);
  38110. if (!nodeClick) {
  38111. return;
  38112. }
  38113. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  38114. if (!targetInfo) {
  38115. return;
  38116. }
  38117. var node = targetInfo.node;
  38118. if (node.getLayout().isLeafRoot) {
  38119. this._rootToNode(targetInfo);
  38120. }
  38121. else {
  38122. if (nodeClick === 'zoomToNode') {
  38123. this._zoomToNode(targetInfo);
  38124. }
  38125. else if (nodeClick === 'link') {
  38126. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  38127. var link = itemModel.get('link', true);
  38128. var linkTarget = itemModel.get('target', true) || 'blank';
  38129. link && window.open(link, linkTarget);
  38130. }
  38131. }
  38132. }, this);
  38133. },
  38134. /**
  38135. * @private
  38136. */
  38137. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  38138. if (!targetInfo) {
  38139. targetInfo = seriesModel.get('leafDepth', true) != null
  38140. ? {node: seriesModel.getViewRoot()}
  38141. // FIXME
  38142. // better way?
  38143. // Find breadcrumb tail on center of containerGroup.
  38144. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  38145. if (!targetInfo) {
  38146. targetInfo = {node: seriesModel.getData().tree.root};
  38147. }
  38148. }
  38149. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  38150. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  38151. function onSelect(node) {
  38152. if (this._state !== 'animating') {
  38153. aboveViewRoot(seriesModel.getViewRoot(), node)
  38154. ? this._rootToNode({node: node})
  38155. : this._zoomToNode({node: node});
  38156. }
  38157. }
  38158. },
  38159. /**
  38160. * @override
  38161. */
  38162. remove: function () {
  38163. this._clearController();
  38164. this._containerGroup && this._containerGroup.removeAll();
  38165. this._storage = createStorage();
  38166. this._state = 'ready';
  38167. this._breadcrumb && this._breadcrumb.remove();
  38168. },
  38169. dispose: function () {
  38170. this._clearController();
  38171. },
  38172. /**
  38173. * @private
  38174. */
  38175. _zoomToNode: function (targetInfo) {
  38176. this.api.dispatchAction({
  38177. type: 'treemapZoomToNode',
  38178. from: this.uid,
  38179. seriesId: this.seriesModel.id,
  38180. targetNode: targetInfo.node
  38181. });
  38182. },
  38183. /**
  38184. * @private
  38185. */
  38186. _rootToNode: function (targetInfo) {
  38187. this.api.dispatchAction({
  38188. type: 'treemapRootToNode',
  38189. from: this.uid,
  38190. seriesId: this.seriesModel.id,
  38191. targetNode: targetInfo.node
  38192. });
  38193. },
  38194. /**
  38195. * @public
  38196. * @param {number} x Global coord x.
  38197. * @param {number} y Global coord y.
  38198. * @return {Object} info If not found, return undefined;
  38199. * @return {number} info.node Target node.
  38200. * @return {number} info.offsetX x refer to target node.
  38201. * @return {number} info.offsetY y refer to target node.
  38202. */
  38203. findTarget: function (x, y) {
  38204. var targetInfo;
  38205. var viewRoot = this.seriesModel.getViewRoot();
  38206. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  38207. var bgEl = this._storage.background[node.getRawIndex()];
  38208. // If invisible, there might be no element.
  38209. if (bgEl) {
  38210. var point = bgEl.transformCoordToLocal(x, y);
  38211. var shape = bgEl.shape;
  38212. // For performance consideration, dont use 'getBoundingRect'.
  38213. if (shape.x <= point[0]
  38214. && point[0] <= shape.x + shape.width
  38215. && shape.y <= point[1]
  38216. && point[1] <= shape.y + shape.height
  38217. ) {
  38218. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  38219. }
  38220. else {
  38221. return false; // Suppress visit subtree.
  38222. }
  38223. }
  38224. }, this);
  38225. return targetInfo;
  38226. }
  38227. });
  38228. /**
  38229. * @inner
  38230. */
  38231. function createStorage() {
  38232. return {nodeGroup: [], background: [], content: []};
  38233. }
  38234. /**
  38235. * @inner
  38236. * @return Return undefined means do not travel further.
  38237. */
  38238. function renderNode(
  38239. seriesModel, thisStorage, oldStorage, reRoot,
  38240. lastsForAnimation, willInvisibleEls,
  38241. thisNode, oldNode, parentGroup, depth
  38242. ) {
  38243. // Whether under viewRoot.
  38244. if (!thisNode) {
  38245. // Deleting nodes will be performed finally. This method just find
  38246. // element from old storage, or create new element, set them to new
  38247. // storage, and set styles.
  38248. return;
  38249. }
  38250. // -------------------------------------------------------------------
  38251. // Start of closure variables available in "Procedures in renderNode".
  38252. var thisLayout = thisNode.getLayout();
  38253. if (!thisLayout || !thisLayout.isInView) {
  38254. return;
  38255. }
  38256. var thisWidth = thisLayout.width;
  38257. var thisHeight = thisLayout.height;
  38258. var borderWidth = thisLayout.borderWidth;
  38259. var thisInvisible = thisLayout.invisible;
  38260. var thisRawIndex = thisNode.getRawIndex();
  38261. var oldRawIndex = oldNode && oldNode.getRawIndex();
  38262. var thisViewChildren = thisNode.viewChildren;
  38263. var upperHeight = thisLayout.upperHeight;
  38264. var isParent = thisViewChildren && thisViewChildren.length;
  38265. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  38266. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  38267. // End of closure ariables available in "Procedures in renderNode".
  38268. // -----------------------------------------------------------------
  38269. // Node group
  38270. var group = giveGraphic('nodeGroup', Group$2);
  38271. if (!group) {
  38272. return;
  38273. }
  38274. parentGroup.add(group);
  38275. // x,y are not set when el is above view root.
  38276. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  38277. group.__tmNodeWidth = thisWidth;
  38278. group.__tmNodeHeight = thisHeight;
  38279. if (thisLayout.isAboveViewRoot) {
  38280. return group;
  38281. }
  38282. // Background
  38283. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  38284. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  38285. // No children, render content.
  38286. if (!isParent) {
  38287. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  38288. content && renderContent(group, content);
  38289. }
  38290. return group;
  38291. // ----------------------------
  38292. // | Procedures in renderNode |
  38293. // ----------------------------
  38294. function renderBackground(group, bg, useUpperLabel) {
  38295. // For tooltip.
  38296. bg.dataIndex = thisNode.dataIndex;
  38297. bg.seriesIndex = seriesModel.seriesIndex;
  38298. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  38299. var visualBorderColor = thisNode.getVisual('borderColor', true);
  38300. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  38301. updateStyle(bg, function () {
  38302. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  38303. normalStyle.fill = visualBorderColor;
  38304. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  38305. emphasisStyle.fill = emphasisBorderColor;
  38306. if (useUpperLabel) {
  38307. var upperLabelWidth = thisWidth - 2 * borderWidth;
  38308. prepareText(
  38309. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  38310. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  38311. );
  38312. }
  38313. // For old bg.
  38314. else {
  38315. normalStyle.text = emphasisStyle.text = null;
  38316. }
  38317. bg.setStyle(normalStyle);
  38318. setHoverStyle(bg, emphasisStyle);
  38319. });
  38320. group.add(bg);
  38321. }
  38322. function renderContent(group, content) {
  38323. // For tooltip.
  38324. content.dataIndex = thisNode.dataIndex;
  38325. content.seriesIndex = seriesModel.seriesIndex;
  38326. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  38327. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  38328. content.culling = true;
  38329. content.setShape({
  38330. x: borderWidth,
  38331. y: borderWidth,
  38332. width: contentWidth,
  38333. height: contentHeight
  38334. });
  38335. var visualColor = thisNode.getVisual('color', true);
  38336. updateStyle(content, function () {
  38337. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  38338. normalStyle.fill = visualColor;
  38339. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  38340. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  38341. content.setStyle(normalStyle);
  38342. setHoverStyle(content, emphasisStyle);
  38343. });
  38344. group.add(content);
  38345. }
  38346. function updateStyle(element, cb) {
  38347. if (!thisInvisible) {
  38348. // If invisible, do not set visual, otherwise the element will
  38349. // change immediately before animation. We think it is OK to
  38350. // remain its origin color when moving out of the view window.
  38351. cb();
  38352. if (!element.__tmWillVisible) {
  38353. element.invisible = false;
  38354. }
  38355. }
  38356. else {
  38357. // Delay invisible setting utill animation finished,
  38358. // avoid element vanish suddenly before animation.
  38359. !element.invisible && willInvisibleEls.push(element);
  38360. }
  38361. }
  38362. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  38363. var nodeModel = thisNode.getModel();
  38364. var text = retrieve(
  38365. seriesModel.getFormattedLabel(
  38366. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  38367. ),
  38368. nodeModel.get('name')
  38369. );
  38370. if (!upperLabelRect && thisLayout.isLeafRoot) {
  38371. var iconChar = seriesModel.get('drillDownIcon', true);
  38372. text = iconChar ? iconChar + ' ' + text : text;
  38373. }
  38374. var normalLabelModel = nodeModel.getModel(
  38375. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  38376. );
  38377. var emphasisLabelModel = nodeModel.getModel(
  38378. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  38379. );
  38380. var isShow = normalLabelModel.getShallow('show');
  38381. setLabelStyle(
  38382. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  38383. {
  38384. defaultText: isShow ? text : null,
  38385. autoColor: visualColor,
  38386. isRectText: true
  38387. }
  38388. );
  38389. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  38390. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  38391. ? {
  38392. outerWidth: width,
  38393. outerHeight: height,
  38394. minChar: 2
  38395. }
  38396. : null;
  38397. }
  38398. function giveGraphic(storageName, Ctor, depth, z) {
  38399. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  38400. var lasts = lastsForAnimation[storageName];
  38401. if (element) {
  38402. // Remove from oldStorage
  38403. oldStorage[storageName][oldRawIndex] = null;
  38404. prepareAnimationWhenHasOld(lasts, element, storageName);
  38405. }
  38406. // If invisible and no old element, do not create new element (for optimizing).
  38407. else if (!thisInvisible) {
  38408. element = new Ctor({z: calculateZ(depth, z)});
  38409. element.__tmDepth = depth;
  38410. element.__tmStorageName = storageName;
  38411. prepareAnimationWhenNoOld(lasts, element, storageName);
  38412. }
  38413. // Set to thisStorage
  38414. return (thisStorage[storageName][thisRawIndex] = element);
  38415. }
  38416. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  38417. var lastCfg = lasts[thisRawIndex] = {};
  38418. lastCfg.old = storageName === 'nodeGroup'
  38419. ? element.position.slice()
  38420. : extend({}, element.shape);
  38421. }
  38422. // If a element is new, we need to find the animation start point carefully,
  38423. // otherwise it will looks strange when 'zoomToNode'.
  38424. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  38425. var lastCfg = lasts[thisRawIndex] = {};
  38426. var parentNode = thisNode.parentNode;
  38427. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  38428. var parentOldX = 0;
  38429. var parentOldY = 0;
  38430. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  38431. // For convenience, get old bounding rect from background.
  38432. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  38433. if (!reRoot && parentOldBg && parentOldBg.old) {
  38434. parentOldX = parentOldBg.old.width;
  38435. parentOldY = parentOldBg.old.height;
  38436. }
  38437. // When no parent old shape found, its parent is new too,
  38438. // so we can just use {x:0, y:0}.
  38439. lastCfg.old = storageName === 'nodeGroup'
  38440. ? [0, parentOldY]
  38441. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  38442. }
  38443. // Fade in, user can be aware that these nodes are new.
  38444. lastCfg.fadein = storageName !== 'nodeGroup';
  38445. }
  38446. }
  38447. // We can not set all backgroud with the same z, Because the behaviour of
  38448. // drill down and roll up differ background creation sequence from tree
  38449. // hierarchy sequence, which cause that lowser background element overlap
  38450. // upper ones. So we calculate z based on depth.
  38451. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  38452. // treemap with large z overlaps other components.
  38453. function calculateZ(depth, zInLevel) {
  38454. var zb = depth * Z_BASE + zInLevel;
  38455. return (zb - 1) / zb;
  38456. }
  38457. /**
  38458. * @file Treemap action
  38459. */
  38460. var noop$1 = function () {};
  38461. var actionTypes = [
  38462. 'treemapZoomToNode',
  38463. 'treemapRender',
  38464. 'treemapMove'
  38465. ];
  38466. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  38467. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  38468. }
  38469. registerAction(
  38470. {type: 'treemapRootToNode', update: 'updateView'},
  38471. function (payload, ecModel) {
  38472. ecModel.eachComponent(
  38473. {mainType: 'series', subType: 'treemap', query: payload},
  38474. handleRootToNode
  38475. );
  38476. function handleRootToNode(model, index) {
  38477. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  38478. var targetInfo = retrieveTargetInfo(payload, types, model);
  38479. if (targetInfo) {
  38480. var originViewRoot = model.getViewRoot();
  38481. if (originViewRoot) {
  38482. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  38483. ? 'rollUp' : 'drillDown';
  38484. }
  38485. model.resetViewRoot(targetInfo.node);
  38486. }
  38487. }
  38488. }
  38489. );
  38490. var each$10 = each$1;
  38491. var isObject$5 = isObject$1;
  38492. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  38493. /**
  38494. * @param {Object} option
  38495. * @param {string} [option.type] See visualHandlers.
  38496. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  38497. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  38498. * required when mappingMethod is 'linear'
  38499. * @param {Array.<Object>=} [option.pieceList] [
  38500. * {value: someValue},
  38501. * {interval: [min1, max1], visual: {...}},
  38502. * {interval: [min2, max2]}
  38503. * ],
  38504. * required when mappingMethod is 'piecewise'.
  38505. * Visual for only each piece can be specified.
  38506. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  38507. * required when mappingMethod is 'category'.
  38508. * If no option.categories, categories is set
  38509. * as [0, 1, 2, ...].
  38510. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  38511. * @param {(Array|Object|*)} [option.visual] Visual data.
  38512. * when mappingMethod is 'category',
  38513. * visual data can be array or object
  38514. * (like: {cate1: '#222', none: '#fff'})
  38515. * or primary types (which represents
  38516. * defualt category visual), otherwise visual
  38517. * can be array or primary (which will be
  38518. * normalized to array).
  38519. *
  38520. */
  38521. var VisualMapping = function (option) {
  38522. var mappingMethod = option.mappingMethod;
  38523. var visualType = option.type;
  38524. /**
  38525. * @readOnly
  38526. * @type {Object}
  38527. */
  38528. var thisOption = this.option = clone(option);
  38529. /**
  38530. * @readOnly
  38531. * @type {string}
  38532. */
  38533. this.type = visualType;
  38534. /**
  38535. * @readOnly
  38536. * @type {string}
  38537. */
  38538. this.mappingMethod = mappingMethod;
  38539. /**
  38540. * @private
  38541. * @type {Function}
  38542. */
  38543. this._normalizeData = normalizers[mappingMethod];
  38544. var visualHandler = visualHandlers[visualType];
  38545. /**
  38546. * @public
  38547. * @type {Function}
  38548. */
  38549. this.applyVisual = visualHandler.applyVisual;
  38550. /**
  38551. * @public
  38552. * @type {Function}
  38553. */
  38554. this.getColorMapper = visualHandler.getColorMapper;
  38555. /**
  38556. * @private
  38557. * @type {Function}
  38558. */
  38559. this._doMap = visualHandler._doMap[mappingMethod];
  38560. if (mappingMethod === 'piecewise') {
  38561. normalizeVisualRange(thisOption);
  38562. preprocessForPiecewise(thisOption);
  38563. }
  38564. else if (mappingMethod === 'category') {
  38565. thisOption.categories
  38566. ? preprocessForSpecifiedCategory(thisOption)
  38567. // categories is ordinal when thisOption.categories not specified,
  38568. // which need no more preprocess except normalize visual.
  38569. : normalizeVisualRange(thisOption, true);
  38570. }
  38571. else { // mappingMethod === 'linear' or 'fixed'
  38572. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  38573. normalizeVisualRange(thisOption);
  38574. }
  38575. };
  38576. VisualMapping.prototype = {
  38577. constructor: VisualMapping,
  38578. mapValueToVisual: function (value) {
  38579. var normalized = this._normalizeData(value);
  38580. return this._doMap(normalized, value);
  38581. },
  38582. getNormalizer: function () {
  38583. return bind(this._normalizeData, this);
  38584. }
  38585. };
  38586. var visualHandlers = VisualMapping.visualHandlers = {
  38587. color: {
  38588. applyVisual: makeApplyVisual('color'),
  38589. /**
  38590. * Create a mapper function
  38591. * @return {Function}
  38592. */
  38593. getColorMapper: function () {
  38594. var thisOption = this.option;
  38595. return bind(
  38596. thisOption.mappingMethod === 'category'
  38597. ? function (value, isNormalized) {
  38598. !isNormalized && (value = this._normalizeData(value));
  38599. return doMapCategory.call(this, value);
  38600. }
  38601. : function (value, isNormalized, out) {
  38602. // If output rgb array
  38603. // which will be much faster and useful in pixel manipulation
  38604. var returnRGBArray = !!out;
  38605. !isNormalized && (value = this._normalizeData(value));
  38606. out = fastLerp(value, thisOption.parsedVisual, out);
  38607. return returnRGBArray ? out : stringify(out, 'rgba');
  38608. },
  38609. this
  38610. );
  38611. },
  38612. _doMap: {
  38613. linear: function (normalized) {
  38614. return stringify(
  38615. fastLerp(normalized, this.option.parsedVisual),
  38616. 'rgba'
  38617. );
  38618. },
  38619. category: doMapCategory,
  38620. piecewise: function (normalized, value) {
  38621. var result = getSpecifiedVisual.call(this, value);
  38622. if (result == null) {
  38623. result = stringify(
  38624. fastLerp(normalized, this.option.parsedVisual),
  38625. 'rgba'
  38626. );
  38627. }
  38628. return result;
  38629. },
  38630. fixed: doMapFixed
  38631. }
  38632. },
  38633. colorHue: makePartialColorVisualHandler(function (color, value) {
  38634. return modifyHSL(color, value);
  38635. }),
  38636. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  38637. return modifyHSL(color, null, value);
  38638. }),
  38639. colorLightness: makePartialColorVisualHandler(function (color, value) {
  38640. return modifyHSL(color, null, null, value);
  38641. }),
  38642. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  38643. return modifyAlpha(color, value);
  38644. }),
  38645. opacity: {
  38646. applyVisual: makeApplyVisual('opacity'),
  38647. _doMap: makeDoMap([0, 1])
  38648. },
  38649. symbol: {
  38650. applyVisual: function (value, getter, setter) {
  38651. var symbolCfg = this.mapValueToVisual(value);
  38652. if (isString(symbolCfg)) {
  38653. setter('symbol', symbolCfg);
  38654. }
  38655. else if (isObject$5(symbolCfg)) {
  38656. for (var name in symbolCfg) {
  38657. if (symbolCfg.hasOwnProperty(name)) {
  38658. setter(name, symbolCfg[name]);
  38659. }
  38660. }
  38661. }
  38662. },
  38663. _doMap: {
  38664. linear: doMapToArray,
  38665. category: doMapCategory,
  38666. piecewise: function (normalized, value) {
  38667. var result = getSpecifiedVisual.call(this, value);
  38668. if (result == null) {
  38669. result = doMapToArray.call(this, normalized);
  38670. }
  38671. return result;
  38672. },
  38673. fixed: doMapFixed
  38674. }
  38675. },
  38676. symbolSize: {
  38677. applyVisual: makeApplyVisual('symbolSize'),
  38678. _doMap: makeDoMap([0, 1])
  38679. }
  38680. };
  38681. function preprocessForPiecewise(thisOption) {
  38682. var pieceList = thisOption.pieceList;
  38683. thisOption.hasSpecialVisual = false;
  38684. each$1(pieceList, function (piece, index) {
  38685. piece.originIndex = index;
  38686. // piece.visual is "result visual value" but not
  38687. // a visual range, so it does not need to be normalized.
  38688. if (piece.visual != null) {
  38689. thisOption.hasSpecialVisual = true;
  38690. }
  38691. });
  38692. }
  38693. function preprocessForSpecifiedCategory(thisOption) {
  38694. // Hash categories.
  38695. var categories = thisOption.categories;
  38696. var visual = thisOption.visual;
  38697. var categoryMap = thisOption.categoryMap = {};
  38698. each$10(categories, function (cate, index) {
  38699. categoryMap[cate] = index;
  38700. });
  38701. // Process visual map input.
  38702. if (!isArray(visual)) {
  38703. var visualArr = [];
  38704. if (isObject$1(visual)) {
  38705. each$10(visual, function (v, cate) {
  38706. var index = categoryMap[cate];
  38707. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  38708. });
  38709. }
  38710. else { // Is primary type, represents default visual.
  38711. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  38712. }
  38713. visual = setVisualToOption(thisOption, visualArr);
  38714. }
  38715. // Remove categories that has no visual,
  38716. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  38717. for (var i = categories.length - 1; i >= 0; i--) {
  38718. if (visual[i] == null) {
  38719. delete categoryMap[categories[i]];
  38720. categories.pop();
  38721. }
  38722. }
  38723. }
  38724. function normalizeVisualRange(thisOption, isCategory) {
  38725. var visual = thisOption.visual;
  38726. var visualArr = [];
  38727. if (isObject$1(visual)) {
  38728. each$10(visual, function (v) {
  38729. visualArr.push(v);
  38730. });
  38731. }
  38732. else if (visual != null) {
  38733. visualArr.push(visual);
  38734. }
  38735. var doNotNeedPair = {color: 1, symbol: 1};
  38736. if (!isCategory
  38737. && visualArr.length === 1
  38738. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  38739. ) {
  38740. // Do not care visualArr.length === 0, which is illegal.
  38741. visualArr[1] = visualArr[0];
  38742. }
  38743. setVisualToOption(thisOption, visualArr);
  38744. }
  38745. function makePartialColorVisualHandler(applyValue) {
  38746. return {
  38747. applyVisual: function (value, getter, setter) {
  38748. value = this.mapValueToVisual(value);
  38749. // Must not be array value
  38750. setter('color', applyValue(getter('color'), value));
  38751. },
  38752. _doMap: makeDoMap([0, 1])
  38753. };
  38754. }
  38755. function doMapToArray(normalized) {
  38756. var visual = this.option.visual;
  38757. return visual[
  38758. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  38759. ] || {};
  38760. }
  38761. function makeApplyVisual(visualType) {
  38762. return function (value, getter, setter) {
  38763. setter(visualType, this.mapValueToVisual(value));
  38764. };
  38765. }
  38766. function doMapCategory(normalized) {
  38767. var visual = this.option.visual;
  38768. return visual[
  38769. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  38770. ? normalized % visual.length
  38771. : normalized
  38772. ];
  38773. }
  38774. function doMapFixed() {
  38775. return this.option.visual[0];
  38776. }
  38777. function makeDoMap(sourceExtent) {
  38778. return {
  38779. linear: function (normalized) {
  38780. return linearMap(normalized, sourceExtent, this.option.visual, true);
  38781. },
  38782. category: doMapCategory,
  38783. piecewise: function (normalized, value) {
  38784. var result = getSpecifiedVisual.call(this, value);
  38785. if (result == null) {
  38786. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  38787. }
  38788. return result;
  38789. },
  38790. fixed: doMapFixed
  38791. };
  38792. }
  38793. function getSpecifiedVisual(value) {
  38794. var thisOption = this.option;
  38795. var pieceList = thisOption.pieceList;
  38796. if (thisOption.hasSpecialVisual) {
  38797. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  38798. var piece = pieceList[pieceIndex];
  38799. if (piece && piece.visual) {
  38800. return piece.visual[this.type];
  38801. }
  38802. }
  38803. }
  38804. function setVisualToOption(thisOption, visualArr) {
  38805. thisOption.visual = visualArr;
  38806. if (thisOption.type === 'color') {
  38807. thisOption.parsedVisual = map(visualArr, function (item) {
  38808. return parse(item);
  38809. });
  38810. }
  38811. return visualArr;
  38812. }
  38813. /**
  38814. * Normalizers by mapping methods.
  38815. */
  38816. var normalizers = {
  38817. linear: function (value) {
  38818. return linearMap(value, this.option.dataExtent, [0, 1], true);
  38819. },
  38820. piecewise: function (value) {
  38821. var pieceList = this.option.pieceList;
  38822. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  38823. if (pieceIndex != null) {
  38824. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  38825. }
  38826. },
  38827. category: function (value) {
  38828. var index = this.option.categories
  38829. ? this.option.categoryMap[value]
  38830. : value; // ordinal
  38831. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  38832. },
  38833. fixed: noop
  38834. };
  38835. /**
  38836. * List available visual types.
  38837. *
  38838. * @public
  38839. * @return {Array.<string>}
  38840. */
  38841. VisualMapping.listVisualTypes = function () {
  38842. var visualTypes = [];
  38843. each$1(visualHandlers, function (handler, key) {
  38844. visualTypes.push(key);
  38845. });
  38846. return visualTypes;
  38847. };
  38848. /**
  38849. * @public
  38850. */
  38851. VisualMapping.addVisualHandler = function (name, handler) {
  38852. visualHandlers[name] = handler;
  38853. };
  38854. /**
  38855. * @public
  38856. */
  38857. VisualMapping.isValidType = function (visualType) {
  38858. return visualHandlers.hasOwnProperty(visualType);
  38859. };
  38860. /**
  38861. * Convinent method.
  38862. * Visual can be Object or Array or primary type.
  38863. *
  38864. * @public
  38865. */
  38866. VisualMapping.eachVisual = function (visual, callback, context) {
  38867. if (isObject$1(visual)) {
  38868. each$1(visual, callback, context);
  38869. }
  38870. else {
  38871. callback.call(context, visual);
  38872. }
  38873. };
  38874. VisualMapping.mapVisual = function (visual, callback, context) {
  38875. var isPrimary;
  38876. var newVisual = isArray(visual)
  38877. ? []
  38878. : isObject$1(visual)
  38879. ? {}
  38880. : (isPrimary = true, null);
  38881. VisualMapping.eachVisual(visual, function (v, key) {
  38882. var newVal = callback.call(context, v, key);
  38883. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  38884. });
  38885. return newVisual;
  38886. };
  38887. /**
  38888. * @public
  38889. * @param {Object} obj
  38890. * @return {Object} new object containers visual values.
  38891. * If no visuals, return null.
  38892. */
  38893. VisualMapping.retrieveVisuals = function (obj) {
  38894. var ret = {};
  38895. var hasVisual;
  38896. obj && each$10(visualHandlers, function (h, visualType) {
  38897. if (obj.hasOwnProperty(visualType)) {
  38898. ret[visualType] = obj[visualType];
  38899. hasVisual = true;
  38900. }
  38901. });
  38902. return hasVisual ? ret : null;
  38903. };
  38904. /**
  38905. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  38906. *
  38907. * @public
  38908. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  38909. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  38910. * @return {Array.<string>} Sorted visual types.
  38911. */
  38912. VisualMapping.prepareVisualTypes = function (visualTypes) {
  38913. if (isObject$5(visualTypes)) {
  38914. var types = [];
  38915. each$10(visualTypes, function (item, type) {
  38916. types.push(type);
  38917. });
  38918. visualTypes = types;
  38919. }
  38920. else if (isArray(visualTypes)) {
  38921. visualTypes = visualTypes.slice();
  38922. }
  38923. else {
  38924. return [];
  38925. }
  38926. visualTypes.sort(function (type1, type2) {
  38927. // color should be front of colorSaturation, colorAlpha, ...
  38928. // symbol and symbolSize do not matter.
  38929. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  38930. ? 1 : -1;
  38931. });
  38932. return visualTypes;
  38933. };
  38934. /**
  38935. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  38936. * Other visuals are only depends on themself.
  38937. *
  38938. * @public
  38939. * @param {string} visualType1
  38940. * @param {string} visualType2
  38941. * @return {boolean}
  38942. */
  38943. VisualMapping.dependsOn = function (visualType1, visualType2) {
  38944. return visualType2 === 'color'
  38945. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  38946. : visualType1 === visualType2;
  38947. };
  38948. /**
  38949. * @param {number} value
  38950. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  38951. * Always from small to big.
  38952. * @param {boolean} [findClosestWhenOutside=false]
  38953. * @return {number} index
  38954. */
  38955. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  38956. var possibleI;
  38957. var abs = Infinity;
  38958. // value has the higher priority.
  38959. for (var i = 0, len = pieceList.length; i < len; i++) {
  38960. var pieceValue = pieceList[i].value;
  38961. if (pieceValue != null) {
  38962. if (pieceValue === value
  38963. // FIXME
  38964. // It is supposed to compare value according to value type of dimension,
  38965. // but currently value type can exactly be string or number.
  38966. // Compromise for numeric-like string (like '12'), especially
  38967. // in the case that visualMap.categories is ['22', '33'].
  38968. || (typeof pieceValue === 'string' && pieceValue === value + '')
  38969. ) {
  38970. return i;
  38971. }
  38972. findClosestWhenOutside && updatePossible(pieceValue, i);
  38973. }
  38974. }
  38975. for (var i = 0, len = pieceList.length; i < len; i++) {
  38976. var piece = pieceList[i];
  38977. var interval = piece.interval;
  38978. var close = piece.close;
  38979. if (interval) {
  38980. if (interval[0] === -Infinity) {
  38981. if (littleThan(close[1], value, interval[1])) {
  38982. return i;
  38983. }
  38984. }
  38985. else if (interval[1] === Infinity) {
  38986. if (littleThan(close[0], interval[0], value)) {
  38987. return i;
  38988. }
  38989. }
  38990. else if (
  38991. littleThan(close[0], interval[0], value)
  38992. && littleThan(close[1], value, interval[1])
  38993. ) {
  38994. return i;
  38995. }
  38996. findClosestWhenOutside && updatePossible(interval[0], i);
  38997. findClosestWhenOutside && updatePossible(interval[1], i);
  38998. }
  38999. }
  39000. if (findClosestWhenOutside) {
  39001. return value === Infinity
  39002. ? pieceList.length - 1
  39003. : value === -Infinity
  39004. ? 0
  39005. : possibleI;
  39006. }
  39007. function updatePossible(val, index) {
  39008. var newAbs = Math.abs(val - value);
  39009. if (newAbs < abs) {
  39010. abs = newAbs;
  39011. possibleI = index;
  39012. }
  39013. }
  39014. };
  39015. function littleThan(close, a, b) {
  39016. return close ? a <= b : a < b;
  39017. }
  39018. var isArray$2 = isArray;
  39019. var ITEM_STYLE_NORMAL = 'itemStyle';
  39020. var treemapVisual = {
  39021. seriesType: 'treemap',
  39022. reset: function (seriesModel, ecModel, api, payload) {
  39023. var tree = seriesModel.getData().tree;
  39024. var root = tree.root;
  39025. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  39026. if (root.isRemoved()) {
  39027. return;
  39028. }
  39029. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  39030. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  39031. });
  39032. travelTree(
  39033. root, // Visual should calculate from tree root but not view root.
  39034. {},
  39035. levelItemStyles,
  39036. seriesItemStyleModel,
  39037. seriesModel.getViewRoot().getAncestors(),
  39038. seriesModel
  39039. );
  39040. }
  39041. };
  39042. function travelTree(
  39043. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  39044. viewRootAncestors, seriesModel
  39045. ) {
  39046. var nodeModel = node.getModel();
  39047. var nodeLayout = node.getLayout();
  39048. // Optimize
  39049. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  39050. return;
  39051. }
  39052. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  39053. var levelItemStyle = levelItemStyles[node.depth];
  39054. var visuals = buildVisuals(
  39055. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  39056. );
  39057. // calculate border color
  39058. var borderColor = nodeItemStyleModel.get('borderColor');
  39059. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  39060. var thisNodeColor;
  39061. if (borderColorSaturation != null) {
  39062. // For performance, do not always execute 'calculateColor'.
  39063. thisNodeColor = calculateColor(visuals, node);
  39064. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  39065. }
  39066. node.setVisual('borderColor', borderColor);
  39067. var viewChildren = node.viewChildren;
  39068. if (!viewChildren || !viewChildren.length) {
  39069. thisNodeColor = calculateColor(visuals, node);
  39070. // Apply visual to this node.
  39071. node.setVisual('color', thisNodeColor);
  39072. }
  39073. else {
  39074. var mapping = buildVisualMapping(
  39075. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  39076. );
  39077. // Designate visual to children.
  39078. each$1(viewChildren, function (child, index) {
  39079. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  39080. if (child.depth >= viewRootAncestors.length
  39081. || child === viewRootAncestors[child.depth]
  39082. ) {
  39083. var childVisual = mapVisual$1(
  39084. nodeModel, visuals, child, index, mapping, seriesModel
  39085. );
  39086. travelTree(
  39087. child, childVisual, levelItemStyles, seriesItemStyleModel,
  39088. viewRootAncestors, seriesModel
  39089. );
  39090. }
  39091. });
  39092. }
  39093. }
  39094. function buildVisuals(
  39095. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  39096. ) {
  39097. var visuals = extend({}, designatedVisual);
  39098. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  39099. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  39100. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  39101. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  39102. val == null && (val = designatedVisual[visualName]);
  39103. val == null && (val = seriesItemStyleModel.get(visualName));
  39104. val != null && (visuals[visualName] = val);
  39105. });
  39106. return visuals;
  39107. }
  39108. function calculateColor(visuals) {
  39109. var color = getValueVisualDefine(visuals, 'color');
  39110. if (color) {
  39111. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  39112. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  39113. if (colorSaturation) {
  39114. color = modifyHSL(color, null, null, colorSaturation);
  39115. }
  39116. if (colorAlpha) {
  39117. color = modifyAlpha(color, colorAlpha);
  39118. }
  39119. return color;
  39120. }
  39121. }
  39122. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  39123. return thisNodeColor != null
  39124. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  39125. : null;
  39126. }
  39127. function getValueVisualDefine(visuals, name) {
  39128. var value = visuals[name];
  39129. if (value != null && value !== 'none') {
  39130. return value;
  39131. }
  39132. }
  39133. function buildVisualMapping(
  39134. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  39135. ) {
  39136. if (!viewChildren || !viewChildren.length) {
  39137. return;
  39138. }
  39139. var rangeVisual = getRangeVisual(nodeModel, 'color')
  39140. || (
  39141. visuals.color != null
  39142. && visuals.color !== 'none'
  39143. && (
  39144. getRangeVisual(nodeModel, 'colorAlpha')
  39145. || getRangeVisual(nodeModel, 'colorSaturation')
  39146. )
  39147. );
  39148. if (!rangeVisual) {
  39149. return;
  39150. }
  39151. var visualMin = nodeModel.get('visualMin');
  39152. var visualMax = nodeModel.get('visualMax');
  39153. var dataExtent = nodeLayout.dataExtent.slice();
  39154. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  39155. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  39156. var colorMappingBy = nodeModel.get('colorMappingBy');
  39157. var opt = {
  39158. type: rangeVisual.name,
  39159. dataExtent: dataExtent,
  39160. visual: rangeVisual.range
  39161. };
  39162. if (opt.type === 'color'
  39163. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  39164. ) {
  39165. opt.mappingMethod = 'category';
  39166. opt.loop = true;
  39167. // categories is ordinal, so do not set opt.categories.
  39168. }
  39169. else {
  39170. opt.mappingMethod = 'linear';
  39171. }
  39172. var mapping = new VisualMapping(opt);
  39173. mapping.__drColorMappingBy = colorMappingBy;
  39174. return mapping;
  39175. }
  39176. // Notice: If we dont have the attribute 'colorRange', but only use
  39177. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  39178. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  39179. // this problem will be encountered:
  39180. // If a level-1 node dont have children, and its siblings has children,
  39181. // and colorRange is set on level-1, then the node can not be colored.
  39182. // So we separate 'colorRange' and 'color' to different attributes.
  39183. function getRangeVisual(nodeModel, name) {
  39184. // 'colorRange', 'colorARange', 'colorSRange'.
  39185. // If not exsits on this node, fetch from levels and series.
  39186. var range = nodeModel.get(name);
  39187. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  39188. }
  39189. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  39190. var childVisuals = extend({}, visuals);
  39191. if (mapping) {
  39192. var mappingType = mapping.type;
  39193. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  39194. var value =
  39195. colorMappingBy === 'index'
  39196. ? index
  39197. : colorMappingBy === 'id'
  39198. ? seriesModel.mapIdToIndex(child.getId())
  39199. : child.getValue(nodeModel.get('visualDimension'));
  39200. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  39201. }
  39202. return childVisuals;
  39203. }
  39204. var mathMax$4 = Math.max;
  39205. var mathMin$4 = Math.min;
  39206. var retrieveValue = retrieve;
  39207. var each$11 = each$1;
  39208. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  39209. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  39210. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  39211. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  39212. /**
  39213. * @public
  39214. */
  39215. var treemapLayout = {
  39216. seriesType: 'treemap',
  39217. reset: function (seriesModel, ecModel, api, payload) {
  39218. // Layout result in each node:
  39219. // {x, y, width, height, area, borderWidth}
  39220. var ecWidth = api.getWidth();
  39221. var ecHeight = api.getHeight();
  39222. var seriesOption = seriesModel.option;
  39223. var layoutInfo = getLayoutRect(
  39224. seriesModel.getBoxLayoutParams(),
  39225. {
  39226. width: api.getWidth(),
  39227. height: api.getHeight()
  39228. }
  39229. );
  39230. var size = seriesOption.size || []; // Compatible with ec2.
  39231. var containerWidth = parsePercent$1(
  39232. retrieveValue(layoutInfo.width, size[0]),
  39233. ecWidth
  39234. );
  39235. var containerHeight = parsePercent$1(
  39236. retrieveValue(layoutInfo.height, size[1]),
  39237. ecHeight
  39238. );
  39239. // Fetch payload info.
  39240. var payloadType = payload && payload.type;
  39241. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  39242. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  39243. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  39244. ? payload.rootRect : null;
  39245. var viewRoot = seriesModel.getViewRoot();
  39246. var viewAbovePath = getPathToRoot(viewRoot);
  39247. if (payloadType !== 'treemapMove') {
  39248. var rootSize = payloadType === 'treemapZoomToNode'
  39249. ? estimateRootSize(
  39250. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  39251. )
  39252. : rootRect
  39253. ? [rootRect.width, rootRect.height]
  39254. : [containerWidth, containerHeight];
  39255. var sort = seriesOption.sort;
  39256. if (sort && sort !== 'asc' && sort !== 'desc') {
  39257. sort = 'desc';
  39258. }
  39259. var options = {
  39260. squareRatio: seriesOption.squareRatio,
  39261. sort: sort,
  39262. leafDepth: seriesOption.leafDepth
  39263. };
  39264. // layout should be cleared because using updateView but not update.
  39265. viewRoot.hostTree.clearLayouts();
  39266. // TODO
  39267. // optimize: if out of view clip, do not layout.
  39268. // But take care that if do not render node out of view clip,
  39269. // how to calculate start po
  39270. var viewRootLayout = {
  39271. x: 0, y: 0,
  39272. width: rootSize[0], height: rootSize[1],
  39273. area: rootSize[0] * rootSize[1]
  39274. };
  39275. viewRoot.setLayout(viewRootLayout);
  39276. squarify(viewRoot, options, false, 0);
  39277. // Supplement layout.
  39278. var viewRootLayout = viewRoot.getLayout();
  39279. each$11(viewAbovePath, function (node, index) {
  39280. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  39281. node.setLayout(extend(
  39282. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  39283. viewRootLayout
  39284. ));
  39285. });
  39286. }
  39287. var treeRoot = seriesModel.getData().tree.root;
  39288. treeRoot.setLayout(
  39289. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  39290. true
  39291. );
  39292. seriesModel.setLayoutInfo(layoutInfo);
  39293. // FIXME
  39294. // 现在没有clip功能,暂时取ec高宽。
  39295. prunning(
  39296. treeRoot,
  39297. // Transform to base element coordinate system.
  39298. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  39299. viewAbovePath,
  39300. viewRoot,
  39301. 0
  39302. );
  39303. }
  39304. };
  39305. /**
  39306. * Layout treemap with squarify algorithm.
  39307. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  39308. * @see https://github.com/mbostock/d3/blob/master/src/layout/treemap.js
  39309. *
  39310. * @protected
  39311. * @param {module:echarts/data/Tree~TreeNode} node
  39312. * @param {Object} options
  39313. * @param {string} options.sort 'asc' or 'desc'
  39314. * @param {number} options.squareRatio
  39315. * @param {boolean} hideChildren
  39316. * @param {number} depth
  39317. */
  39318. function squarify(node, options, hideChildren, depth) {
  39319. var width;
  39320. var height;
  39321. if (node.isRemoved()) {
  39322. return;
  39323. }
  39324. var thisLayout = node.getLayout();
  39325. width = thisLayout.width;
  39326. height = thisLayout.height;
  39327. // Considering border and gap
  39328. var nodeModel = node.getModel();
  39329. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  39330. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  39331. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  39332. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  39333. var layoutOffset = borderWidth - halfGapWidth;
  39334. var layoutOffsetUpper = upperHeight - halfGapWidth;
  39335. var nodeModel = node.getModel();
  39336. node.setLayout({
  39337. borderWidth: borderWidth,
  39338. upperHeight: upperHeight,
  39339. upperLabelHeight: upperLabelHeight
  39340. }, true);
  39341. width = mathMax$4(width - 2 * layoutOffset, 0);
  39342. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  39343. var totalArea = width * height;
  39344. var viewChildren = initChildren(
  39345. node, nodeModel, totalArea, options, hideChildren, depth
  39346. );
  39347. if (!viewChildren.length) {
  39348. return;
  39349. }
  39350. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  39351. var rowFixedLength = mathMin$4(width, height);
  39352. var best = Infinity; // the best row score so far
  39353. var row = [];
  39354. row.area = 0;
  39355. for (var i = 0, len = viewChildren.length; i < len;) {
  39356. var child = viewChildren[i];
  39357. row.push(child);
  39358. row.area += child.getLayout().area;
  39359. var score = worst(row, rowFixedLength, options.squareRatio);
  39360. // continue with this orientation
  39361. if (score <= best) {
  39362. i++;
  39363. best = score;
  39364. }
  39365. // abort, and try a different orientation
  39366. else {
  39367. row.area -= row.pop().getLayout().area;
  39368. position(row, rowFixedLength, rect, halfGapWidth, false);
  39369. rowFixedLength = mathMin$4(rect.width, rect.height);
  39370. row.length = row.area = 0;
  39371. best = Infinity;
  39372. }
  39373. }
  39374. if (row.length) {
  39375. position(row, rowFixedLength, rect, halfGapWidth, true);
  39376. }
  39377. if (!hideChildren) {
  39378. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  39379. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  39380. hideChildren = true;
  39381. }
  39382. }
  39383. for (var i = 0, len = viewChildren.length; i < len; i++) {
  39384. squarify(viewChildren[i], options, hideChildren, depth + 1);
  39385. }
  39386. }
  39387. /**
  39388. * Set area to each child, and calculate data extent for visual coding.
  39389. */
  39390. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  39391. var viewChildren = node.children || [];
  39392. var orderBy = options.sort;
  39393. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  39394. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  39395. // leafDepth has higher priority.
  39396. if (hideChildren && !overLeafDepth) {
  39397. return (node.viewChildren = []);
  39398. }
  39399. // Sort children, order by desc.
  39400. viewChildren = filter(viewChildren, function (child) {
  39401. return !child.isRemoved();
  39402. });
  39403. sort$1(viewChildren, orderBy);
  39404. var info = statistic(nodeModel, viewChildren, orderBy);
  39405. if (info.sum === 0) {
  39406. return (node.viewChildren = []);
  39407. }
  39408. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  39409. if (info.sum === 0) {
  39410. return (node.viewChildren = []);
  39411. }
  39412. // Set area to each child.
  39413. for (var i = 0, len = viewChildren.length; i < len; i++) {
  39414. var area = viewChildren[i].getValue() / info.sum * totalArea;
  39415. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  39416. viewChildren[i].setLayout({area: area});
  39417. }
  39418. if (overLeafDepth) {
  39419. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  39420. viewChildren.length = 0;
  39421. }
  39422. node.viewChildren = viewChildren;
  39423. node.setLayout({dataExtent: info.dataExtent}, true);
  39424. return viewChildren;
  39425. }
  39426. /**
  39427. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  39428. */
  39429. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  39430. // visibleMin is not supported yet when no option.sort.
  39431. if (!orderBy) {
  39432. return sum;
  39433. }
  39434. var visibleMin = nodeModel.get('visibleMin');
  39435. var len = orderedChildren.length;
  39436. var deletePoint = len;
  39437. // Always travel from little value to big value.
  39438. for (var i = len - 1; i >= 0; i--) {
  39439. var value = orderedChildren[
  39440. orderBy === 'asc' ? len - i - 1 : i
  39441. ].getValue();
  39442. if (value / sum * totalArea < visibleMin) {
  39443. deletePoint = i;
  39444. sum -= value;
  39445. }
  39446. }
  39447. orderBy === 'asc'
  39448. ? orderedChildren.splice(0, len - deletePoint)
  39449. : orderedChildren.splice(deletePoint, len - deletePoint);
  39450. return sum;
  39451. }
  39452. /**
  39453. * Sort
  39454. */
  39455. function sort$1(viewChildren, orderBy) {
  39456. if (orderBy) {
  39457. viewChildren.sort(function (a, b) {
  39458. var diff = orderBy === 'asc'
  39459. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  39460. return diff === 0
  39461. ? (orderBy === 'asc'
  39462. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  39463. )
  39464. : diff;
  39465. });
  39466. }
  39467. return viewChildren;
  39468. }
  39469. /**
  39470. * Statistic
  39471. */
  39472. function statistic(nodeModel, children, orderBy) {
  39473. // Calculate sum.
  39474. var sum = 0;
  39475. for (var i = 0, len = children.length; i < len; i++) {
  39476. sum += children[i].getValue();
  39477. }
  39478. // Statistic data extent for latter visual coding.
  39479. // Notice: data extent should be calculate based on raw children
  39480. // but not filtered view children, otherwise visual mapping will not
  39481. // be stable when zoom (where children is filtered by visibleMin).
  39482. var dimension = nodeModel.get('visualDimension');
  39483. var dataExtent;
  39484. // The same as area dimension.
  39485. if (!children || !children.length) {
  39486. dataExtent = [NaN, NaN];
  39487. }
  39488. else if (dimension === 'value' && orderBy) {
  39489. dataExtent = [
  39490. children[children.length - 1].getValue(),
  39491. children[0].getValue()
  39492. ];
  39493. orderBy === 'asc' && dataExtent.reverse();
  39494. }
  39495. // Other dimension.
  39496. else {
  39497. var dataExtent = [Infinity, -Infinity];
  39498. each$11(children, function (child) {
  39499. var value = child.getValue(dimension);
  39500. value < dataExtent[0] && (dataExtent[0] = value);
  39501. value > dataExtent[1] && (dataExtent[1] = value);
  39502. });
  39503. }
  39504. return {sum: sum, dataExtent: dataExtent};
  39505. }
  39506. /**
  39507. * Computes the score for the specified row,
  39508. * as the worst aspect ratio.
  39509. */
  39510. function worst(row, rowFixedLength, ratio) {
  39511. var areaMax = 0;
  39512. var areaMin = Infinity;
  39513. for (var i = 0, area, len = row.length; i < len; i++) {
  39514. area = row[i].getLayout().area;
  39515. if (area) {
  39516. area < areaMin && (areaMin = area);
  39517. area > areaMax && (areaMax = area);
  39518. }
  39519. }
  39520. var squareArea = row.area * row.area;
  39521. var f = rowFixedLength * rowFixedLength * ratio;
  39522. return squareArea
  39523. ? mathMax$4(
  39524. (f * areaMax) / squareArea,
  39525. squareArea / (f * areaMin)
  39526. )
  39527. : Infinity;
  39528. }
  39529. /**
  39530. * Positions the specified row of nodes. Modifies `rect`.
  39531. */
  39532. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  39533. // When rowFixedLength === rect.width,
  39534. // it is horizontal subdivision,
  39535. // rowFixedLength is the width of the subdivision,
  39536. // rowOtherLength is the height of the subdivision,
  39537. // and nodes will be positioned from left to right.
  39538. // wh[idx0WhenH] means: when horizontal,
  39539. // wh[idx0WhenH] => wh[0] => 'width'.
  39540. // xy[idx1WhenH] => xy[1] => 'y'.
  39541. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  39542. var idx1WhenH = 1 - idx0WhenH;
  39543. var xy = ['x', 'y'];
  39544. var wh = ['width', 'height'];
  39545. var last = rect[xy[idx0WhenH]];
  39546. var rowOtherLength = rowFixedLength
  39547. ? row.area / rowFixedLength : 0;
  39548. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  39549. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  39550. }
  39551. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  39552. var node = row[i];
  39553. var nodeLayout = {};
  39554. var step = rowOtherLength
  39555. ? node.getLayout().area / rowOtherLength : 0;
  39556. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  39557. // We use Math.max/min to avoid negative width/height when considering gap width.
  39558. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  39559. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  39560. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  39561. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  39562. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  39563. last += modWH;
  39564. node.setLayout(nodeLayout, true);
  39565. }
  39566. rect[xy[idx1WhenH]] += rowOtherLength;
  39567. rect[wh[idx1WhenH]] -= rowOtherLength;
  39568. }
  39569. // Return [containerWidth, containerHeight] as defualt.
  39570. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  39571. // If targetInfo.node exists, we zoom to the node,
  39572. // so estimate whold width and heigth by target node.
  39573. var currNode = (targetInfo || {}).node;
  39574. var defaultSize = [containerWidth, containerHeight];
  39575. if (!currNode || currNode === viewRoot) {
  39576. return defaultSize;
  39577. }
  39578. var parent;
  39579. var viewArea = containerWidth * containerHeight;
  39580. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  39581. while (parent = currNode.parentNode) { // jshint ignore:line
  39582. var sum = 0;
  39583. var siblings = parent.children;
  39584. for (var i = 0, len = siblings.length; i < len; i++) {
  39585. sum += siblings[i].getValue();
  39586. }
  39587. var currNodeValue = currNode.getValue();
  39588. if (currNodeValue === 0) {
  39589. return defaultSize;
  39590. }
  39591. area *= sum / currNodeValue;
  39592. // Considering border, suppose aspect ratio is 1.
  39593. var parentModel = parent.getModel();
  39594. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  39595. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  39596. area += 4 * borderWidth * borderWidth
  39597. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  39598. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  39599. currNode = parent;
  39600. }
  39601. area < viewArea && (area = viewArea);
  39602. var scale = Math.pow(area / viewArea, 0.5);
  39603. return [containerWidth * scale, containerHeight * scale];
  39604. }
  39605. // Root postion base on coord of containerGroup
  39606. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  39607. if (rootRect) {
  39608. return {x: rootRect.x, y: rootRect.y};
  39609. }
  39610. var defaultPosition = {x: 0, y: 0};
  39611. if (!targetInfo) {
  39612. return defaultPosition;
  39613. }
  39614. // If targetInfo is fetched by 'retrieveTargetInfo',
  39615. // old tree and new tree are the same tree,
  39616. // so the node still exists and we can visit it.
  39617. var targetNode = targetInfo.node;
  39618. var layout = targetNode.getLayout();
  39619. if (!layout) {
  39620. return defaultPosition;
  39621. }
  39622. // Transform coord from local to container.
  39623. var targetCenter = [layout.width / 2, layout.height / 2];
  39624. var node = targetNode;
  39625. while (node) {
  39626. var nodeLayout = node.getLayout();
  39627. targetCenter[0] += nodeLayout.x;
  39628. targetCenter[1] += nodeLayout.y;
  39629. node = node.parentNode;
  39630. }
  39631. return {
  39632. x: layoutInfo.width / 2 - targetCenter[0],
  39633. y: layoutInfo.height / 2 - targetCenter[1]
  39634. };
  39635. }
  39636. // Mark nodes visible for prunning when visual coding and rendering.
  39637. // Prunning depends on layout and root position, so we have to do it after layout.
  39638. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  39639. var nodeLayout = node.getLayout();
  39640. var nodeInViewAbovePath = viewAbovePath[depth];
  39641. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  39642. if (
  39643. (nodeInViewAbovePath && !isAboveViewRoot)
  39644. || (depth === viewAbovePath.length && node !== viewRoot)
  39645. ) {
  39646. return;
  39647. }
  39648. node.setLayout({
  39649. // isInView means: viewRoot sub tree + viewAbovePath
  39650. isInView: true,
  39651. // invisible only means: outside view clip so that the node can not
  39652. // see but still layout for animation preparation but not render.
  39653. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  39654. isAboveViewRoot: isAboveViewRoot
  39655. }, true);
  39656. // Transform to child coordinate.
  39657. var childClipRect = new BoundingRect(
  39658. clipRect.x - nodeLayout.x,
  39659. clipRect.y - nodeLayout.y,
  39660. clipRect.width,
  39661. clipRect.height
  39662. );
  39663. each$11(node.viewChildren || [], function (child) {
  39664. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  39665. });
  39666. }
  39667. function getUpperLabelHeight(model) {
  39668. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  39669. }
  39670. registerVisual(treemapVisual);
  39671. registerLayout(treemapLayout);
  39672. /**
  39673. * Graph data structure
  39674. *
  39675. * @module echarts/data/Graph
  39676. * @author Yi Shen(https://www.github.com/pissang)
  39677. */
  39678. // id may be function name of Object, add a prefix to avoid this problem.
  39679. function generateNodeKey (id) {
  39680. return '_EC_' + id;
  39681. }
  39682. /**
  39683. * @alias module:echarts/data/Graph
  39684. * @constructor
  39685. * @param {boolean} directed
  39686. */
  39687. var Graph = function(directed) {
  39688. /**
  39689. * 是否是有向图
  39690. * @type {boolean}
  39691. * @private
  39692. */
  39693. this._directed = directed || false;
  39694. /**
  39695. * @type {Array.<module:echarts/data/Graph.Node>}
  39696. * @readOnly
  39697. */
  39698. this.nodes = [];
  39699. /**
  39700. * @type {Array.<module:echarts/data/Graph.Edge>}
  39701. * @readOnly
  39702. */
  39703. this.edges = [];
  39704. /**
  39705. * @type {Object.<string, module:echarts/data/Graph.Node>}
  39706. * @private
  39707. */
  39708. this._nodesMap = {};
  39709. /**
  39710. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  39711. * @private
  39712. */
  39713. this._edgesMap = {};
  39714. /**
  39715. * @type {module:echarts/data/List}
  39716. * @readOnly
  39717. */
  39718. this.data;
  39719. /**
  39720. * @type {module:echarts/data/List}
  39721. * @readOnly
  39722. */
  39723. this.edgeData;
  39724. };
  39725. var graphProto = Graph.prototype;
  39726. /**
  39727. * @type {string}
  39728. */
  39729. graphProto.type = 'graph';
  39730. /**
  39731. * If is directed graph
  39732. * @return {boolean}
  39733. */
  39734. graphProto.isDirected = function () {
  39735. return this._directed;
  39736. };
  39737. /**
  39738. * Add a new node
  39739. * @param {string} id
  39740. * @param {number} [dataIndex]
  39741. */
  39742. graphProto.addNode = function (id, dataIndex) {
  39743. id = id || ('' + dataIndex);
  39744. var nodesMap = this._nodesMap;
  39745. if (nodesMap[generateNodeKey(id)]) {
  39746. if (__DEV__) {
  39747. console.error('Graph nodes have duplicate name or id');
  39748. }
  39749. return;
  39750. }
  39751. var node = new Node(id, dataIndex);
  39752. node.hostGraph = this;
  39753. this.nodes.push(node);
  39754. nodesMap[generateNodeKey(id)] = node;
  39755. return node;
  39756. };
  39757. /**
  39758. * Get node by data index
  39759. * @param {number} dataIndex
  39760. * @return {module:echarts/data/Graph~Node}
  39761. */
  39762. graphProto.getNodeByIndex = function (dataIndex) {
  39763. var rawIdx = this.data.getRawIndex(dataIndex);
  39764. return this.nodes[rawIdx];
  39765. };
  39766. /**
  39767. * Get node by id
  39768. * @param {string} id
  39769. * @return {module:echarts/data/Graph.Node}
  39770. */
  39771. graphProto.getNodeById = function (id) {
  39772. return this._nodesMap[generateNodeKey(id)];
  39773. };
  39774. /**
  39775. * Add a new edge
  39776. * @param {number|string|module:echarts/data/Graph.Node} n1
  39777. * @param {number|string|module:echarts/data/Graph.Node} n2
  39778. * @param {number} [dataIndex=-1]
  39779. * @return {module:echarts/data/Graph.Edge}
  39780. */
  39781. graphProto.addEdge = function (n1, n2, dataIndex) {
  39782. var nodesMap = this._nodesMap;
  39783. var edgesMap = this._edgesMap;
  39784. // PNEDING
  39785. if (typeof n1 === 'number') {
  39786. n1 = this.nodes[n1];
  39787. }
  39788. if (typeof n2 === 'number') {
  39789. n2 = this.nodes[n2];
  39790. }
  39791. if (!Node.isInstance(n1)) {
  39792. n1 = nodesMap[generateNodeKey(n1)];
  39793. }
  39794. if (!Node.isInstance(n2)) {
  39795. n2 = nodesMap[generateNodeKey(n2)];
  39796. }
  39797. if (!n1 || !n2) {
  39798. return;
  39799. }
  39800. var key = n1.id + '-' + n2.id;
  39801. // PENDING
  39802. if (edgesMap[key]) {
  39803. return;
  39804. }
  39805. var edge = new Edge(n1, n2, dataIndex);
  39806. edge.hostGraph = this;
  39807. if (this._directed) {
  39808. n1.outEdges.push(edge);
  39809. n2.inEdges.push(edge);
  39810. }
  39811. n1.edges.push(edge);
  39812. if (n1 !== n2) {
  39813. n2.edges.push(edge);
  39814. }
  39815. this.edges.push(edge);
  39816. edgesMap[key] = edge;
  39817. return edge;
  39818. };
  39819. /**
  39820. * Get edge by data index
  39821. * @param {number} dataIndex
  39822. * @return {module:echarts/data/Graph~Node}
  39823. */
  39824. graphProto.getEdgeByIndex = function (dataIndex) {
  39825. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  39826. return this.edges[rawIdx];
  39827. };
  39828. /**
  39829. * Get edge by two linked nodes
  39830. * @param {module:echarts/data/Graph.Node|string} n1
  39831. * @param {module:echarts/data/Graph.Node|string} n2
  39832. * @return {module:echarts/data/Graph.Edge}
  39833. */
  39834. graphProto.getEdge = function (n1, n2) {
  39835. if (Node.isInstance(n1)) {
  39836. n1 = n1.id;
  39837. }
  39838. if (Node.isInstance(n2)) {
  39839. n2 = n2.id;
  39840. }
  39841. var edgesMap = this._edgesMap;
  39842. if (this._directed) {
  39843. return edgesMap[n1 + '-' + n2];
  39844. } else {
  39845. return edgesMap[n1 + '-' + n2]
  39846. || edgesMap[n2 + '-' + n1];
  39847. }
  39848. };
  39849. /**
  39850. * Iterate all nodes
  39851. * @param {Function} cb
  39852. * @param {*} [context]
  39853. */
  39854. graphProto.eachNode = function (cb, context) {
  39855. var nodes = this.nodes;
  39856. var len = nodes.length;
  39857. for (var i = 0; i < len; i++) {
  39858. if (nodes[i].dataIndex >= 0) {
  39859. cb.call(context, nodes[i], i);
  39860. }
  39861. }
  39862. };
  39863. /**
  39864. * Iterate all edges
  39865. * @param {Function} cb
  39866. * @param {*} [context]
  39867. */
  39868. graphProto.eachEdge = function (cb, context) {
  39869. var edges = this.edges;
  39870. var len = edges.length;
  39871. for (var i = 0; i < len; i++) {
  39872. if (edges[i].dataIndex >= 0
  39873. && edges[i].node1.dataIndex >= 0
  39874. && edges[i].node2.dataIndex >= 0
  39875. ) {
  39876. cb.call(context, edges[i], i);
  39877. }
  39878. }
  39879. };
  39880. /**
  39881. * Breadth first traverse
  39882. * @param {Function} cb
  39883. * @param {module:echarts/data/Graph.Node} startNode
  39884. * @param {string} [direction='none'] 'none'|'in'|'out'
  39885. * @param {*} [context]
  39886. */
  39887. graphProto.breadthFirstTraverse = function (
  39888. cb, startNode, direction, context
  39889. ) {
  39890. if (!Node.isInstance(startNode)) {
  39891. startNode = this._nodesMap[generateNodeKey(startNode)];
  39892. }
  39893. if (!startNode) {
  39894. return;
  39895. }
  39896. var edgeType = direction === 'out'
  39897. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  39898. for (var i = 0; i < this.nodes.length; i++) {
  39899. this.nodes[i].__visited = false;
  39900. }
  39901. if (cb.call(context, startNode, null)) {
  39902. return;
  39903. }
  39904. var queue = [startNode];
  39905. while (queue.length) {
  39906. var currentNode = queue.shift();
  39907. var edges = currentNode[edgeType];
  39908. for (var i = 0; i < edges.length; i++) {
  39909. var e = edges[i];
  39910. var otherNode = e.node1 === currentNode
  39911. ? e.node2 : e.node1;
  39912. if (!otherNode.__visited) {
  39913. if (cb.call(context, otherNode, currentNode)) {
  39914. // Stop traversing
  39915. return;
  39916. }
  39917. queue.push(otherNode);
  39918. otherNode.__visited = true;
  39919. }
  39920. }
  39921. }
  39922. };
  39923. // TODO
  39924. // graphProto.depthFirstTraverse = function (
  39925. // cb, startNode, direction, context
  39926. // ) {
  39927. // };
  39928. // Filter update
  39929. graphProto.update = function () {
  39930. var data = this.data;
  39931. var edgeData = this.edgeData;
  39932. var nodes = this.nodes;
  39933. var edges = this.edges;
  39934. for (var i = 0, len = nodes.length; i < len; i++) {
  39935. nodes[i].dataIndex = -1;
  39936. }
  39937. for (var i = 0, len = data.count(); i < len; i++) {
  39938. nodes[data.getRawIndex(i)].dataIndex = i;
  39939. }
  39940. edgeData.filterSelf(function (idx) {
  39941. var edge = edges[edgeData.getRawIndex(idx)];
  39942. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  39943. });
  39944. // Update edge
  39945. for (var i = 0, len = edges.length; i < len; i++) {
  39946. edges[i].dataIndex = -1;
  39947. }
  39948. for (var i = 0, len = edgeData.count(); i < len; i++) {
  39949. edges[edgeData.getRawIndex(i)].dataIndex = i;
  39950. }
  39951. };
  39952. /**
  39953. * @return {module:echarts/data/Graph}
  39954. */
  39955. graphProto.clone = function () {
  39956. var graph = new Graph(this._directed);
  39957. var nodes = this.nodes;
  39958. var edges = this.edges;
  39959. for (var i = 0; i < nodes.length; i++) {
  39960. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  39961. }
  39962. for (var i = 0; i < edges.length; i++) {
  39963. var e = edges[i];
  39964. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  39965. }
  39966. return graph;
  39967. };
  39968. /**
  39969. * @alias module:echarts/data/Graph.Node
  39970. */
  39971. function Node(id, dataIndex) {
  39972. /**
  39973. * @type {string}
  39974. */
  39975. this.id = id == null ? '' : id;
  39976. /**
  39977. * @type {Array.<module:echarts/data/Graph.Edge>}
  39978. */
  39979. this.inEdges = [];
  39980. /**
  39981. * @type {Array.<module:echarts/data/Graph.Edge>}
  39982. */
  39983. this.outEdges = [];
  39984. /**
  39985. * @type {Array.<module:echarts/data/Graph.Edge>}
  39986. */
  39987. this.edges = [];
  39988. /**
  39989. * @type {module:echarts/data/Graph}
  39990. */
  39991. this.hostGraph;
  39992. /**
  39993. * @type {number}
  39994. */
  39995. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  39996. }
  39997. Node.prototype = {
  39998. constructor: Node,
  39999. /**
  40000. * @return {number}
  40001. */
  40002. degree: function () {
  40003. return this.edges.length;
  40004. },
  40005. /**
  40006. * @return {number}
  40007. */
  40008. inDegree: function () {
  40009. return this.inEdges.length;
  40010. },
  40011. /**
  40012. * @return {number}
  40013. */
  40014. outDegree: function () {
  40015. return this.outEdges.length;
  40016. },
  40017. /**
  40018. * @param {string} [path]
  40019. * @return {module:echarts/model/Model}
  40020. */
  40021. getModel: function (path) {
  40022. if (this.dataIndex < 0) {
  40023. return;
  40024. }
  40025. var graph = this.hostGraph;
  40026. var itemModel = graph.data.getItemModel(this.dataIndex);
  40027. return itemModel.getModel(path);
  40028. }
  40029. };
  40030. /**
  40031. * 图边
  40032. * @alias module:echarts/data/Graph.Edge
  40033. * @param {module:echarts/data/Graph.Node} n1
  40034. * @param {module:echarts/data/Graph.Node} n2
  40035. * @param {number} [dataIndex=-1]
  40036. */
  40037. function Edge(n1, n2, dataIndex) {
  40038. /**
  40039. * 节点1,如果是有向图则为源节点
  40040. * @type {module:echarts/data/Graph.Node}
  40041. */
  40042. this.node1 = n1;
  40043. /**
  40044. * 节点2,如果是有向图则为目标节点
  40045. * @type {module:echarts/data/Graph.Node}
  40046. */
  40047. this.node2 = n2;
  40048. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  40049. }
  40050. /**
  40051. * @param {string} [path]
  40052. * @return {module:echarts/model/Model}
  40053. */
  40054. Edge.prototype.getModel = function (path) {
  40055. if (this.dataIndex < 0) {
  40056. return;
  40057. }
  40058. var graph = this.hostGraph;
  40059. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  40060. return itemModel.getModel(path);
  40061. };
  40062. var createGraphDataProxyMixin = function (hostName, dataName) {
  40063. return {
  40064. /**
  40065. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  40066. * @return {number}
  40067. */
  40068. getValue: function (dimension) {
  40069. var data = this[hostName][dataName];
  40070. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  40071. },
  40072. /**
  40073. * @param {Object|string} key
  40074. * @param {*} [value]
  40075. */
  40076. setVisual: function (key, value) {
  40077. this.dataIndex >= 0
  40078. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  40079. },
  40080. /**
  40081. * @param {string} key
  40082. * @return {boolean}
  40083. */
  40084. getVisual: function (key, ignoreParent) {
  40085. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  40086. },
  40087. /**
  40088. * @param {Object} layout
  40089. * @return {boolean} [merge=false]
  40090. */
  40091. setLayout: function (layout, merge$$1) {
  40092. this.dataIndex >= 0
  40093. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  40094. },
  40095. /**
  40096. * @return {Object}
  40097. */
  40098. getLayout: function () {
  40099. return this[hostName][dataName].getItemLayout(this.dataIndex);
  40100. },
  40101. /**
  40102. * @return {module:zrender/Element}
  40103. */
  40104. getGraphicEl: function () {
  40105. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  40106. },
  40107. /**
  40108. * @return {number}
  40109. */
  40110. getRawIndex: function () {
  40111. return this[hostName][dataName].getRawIndex(this.dataIndex);
  40112. }
  40113. };
  40114. };
  40115. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  40116. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  40117. Graph.Node = Node;
  40118. Graph.Edge = Edge;
  40119. enableClassCheck(Node);
  40120. enableClassCheck(Edge);
  40121. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  40122. // ??? TODO
  40123. // support dataset?
  40124. var graph = new Graph(directed);
  40125. for (var i = 0; i < nodes.length; i++) {
  40126. graph.addNode(retrieve(
  40127. // Id, name, dataIndex
  40128. nodes[i].id, nodes[i].name, i
  40129. ), i);
  40130. }
  40131. var linkNameList = [];
  40132. var validEdges = [];
  40133. var linkCount = 0;
  40134. for (var i = 0; i < edges.length; i++) {
  40135. var link = edges[i];
  40136. var source = link.source;
  40137. var target = link.target;
  40138. // addEdge may fail when source or target not exists
  40139. if (graph.addEdge(source, target, linkCount)) {
  40140. validEdges.push(link);
  40141. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  40142. linkCount++;
  40143. }
  40144. }
  40145. var coordSys = seriesModel.get('coordinateSystem');
  40146. var nodeData;
  40147. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  40148. nodeData = createListFromArray(nodes, seriesModel);
  40149. }
  40150. else {
  40151. // FIXME
  40152. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  40153. // FIXME
  40154. var dimensionNames = createDimensions(nodes, {
  40155. coordDimensions: (
  40156. (coordSysCtor && coordSysCtor.type !== 'view')
  40157. ? (coordSysCtor.dimensions || []) : []
  40158. ).concat(['value'])
  40159. });
  40160. nodeData = new List(dimensionNames, seriesModel);
  40161. nodeData.initData(nodes);
  40162. }
  40163. var edgeData = new List(['value'], seriesModel);
  40164. edgeData.initData(validEdges, linkNameList);
  40165. beforeLink && beforeLink(nodeData, edgeData);
  40166. linkList({
  40167. mainData: nodeData,
  40168. struct: graph,
  40169. structAttr: 'graph',
  40170. datas: {node: nodeData, edge: edgeData},
  40171. datasAttr: {node: 'data', edge: 'edgeData'}
  40172. });
  40173. // Update dataIndex of nodes and edges because invalid edge may be removed
  40174. graph.update();
  40175. return graph;
  40176. };
  40177. var GraphSeries = extendSeriesModel({
  40178. type: 'series.graph',
  40179. init: function (option) {
  40180. GraphSeries.superApply(this, 'init', arguments);
  40181. // Provide data for legend select
  40182. this.legendDataProvider = function () {
  40183. return this._categoriesData;
  40184. };
  40185. this.fillDataTextStyle(option.edges || option.links);
  40186. this._updateCategoriesData();
  40187. },
  40188. mergeOption: function (option) {
  40189. GraphSeries.superApply(this, 'mergeOption', arguments);
  40190. this.fillDataTextStyle(option.edges || option.links);
  40191. this._updateCategoriesData();
  40192. },
  40193. mergeDefaultAndTheme: function (option) {
  40194. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  40195. defaultEmphasis(option, ['edgeLabel'], ['show']);
  40196. },
  40197. getInitialData: function (option, ecModel) {
  40198. var edges = option.edges || option.links || [];
  40199. var nodes = option.data || option.nodes || [];
  40200. var self = this;
  40201. if (nodes && edges) {
  40202. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  40203. }
  40204. function beforeLink(nodeData, edgeData) {
  40205. // Overwrite nodeData.getItemModel to
  40206. nodeData.wrapMethod('getItemModel', function (model) {
  40207. var categoriesModels = self._categoriesModels;
  40208. var categoryIdx = model.getShallow('category');
  40209. var categoryModel = categoriesModels[categoryIdx];
  40210. if (categoryModel) {
  40211. categoryModel.parentModel = model.parentModel;
  40212. model.parentModel = categoryModel;
  40213. }
  40214. return model;
  40215. });
  40216. var edgeLabelModel = self.getModel('edgeLabel');
  40217. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  40218. var fakeSeriesModel = new Model(
  40219. {label: edgeLabelModel.option},
  40220. edgeLabelModel.parentModel,
  40221. ecModel
  40222. );
  40223. edgeData.wrapMethod('getItemModel', function (model) {
  40224. model.customizeGetParent(edgeGetParent);
  40225. return model;
  40226. });
  40227. function edgeGetParent(path) {
  40228. path = this.parsePath(path);
  40229. return (path && path[0] === 'label')
  40230. ? fakeSeriesModel
  40231. : this.parentModel;
  40232. }
  40233. }
  40234. },
  40235. /**
  40236. * @return {module:echarts/data/Graph}
  40237. */
  40238. getGraph: function () {
  40239. return this.getData().graph;
  40240. },
  40241. /**
  40242. * @return {module:echarts/data/List}
  40243. */
  40244. getEdgeData: function () {
  40245. return this.getGraph().edgeData;
  40246. },
  40247. /**
  40248. * @return {module:echarts/data/List}
  40249. */
  40250. getCategoriesData: function () {
  40251. return this._categoriesData;
  40252. },
  40253. /**
  40254. * @override
  40255. */
  40256. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  40257. if (dataType === 'edge') {
  40258. var nodeData = this.getData();
  40259. var params = this.getDataParams(dataIndex, dataType);
  40260. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  40261. var sourceName = nodeData.getName(edge.node1.dataIndex);
  40262. var targetName = nodeData.getName(edge.node2.dataIndex);
  40263. var html = [];
  40264. sourceName != null && html.push(sourceName);
  40265. targetName != null && html.push(targetName);
  40266. html = encodeHTML(html.join(' > '));
  40267. if (params.value) {
  40268. html += ' : ' + encodeHTML(params.value);
  40269. }
  40270. return html;
  40271. }
  40272. else { // dataType === 'node' or empty
  40273. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  40274. }
  40275. },
  40276. _updateCategoriesData: function () {
  40277. var categories = map(this.option.categories || [], function (category) {
  40278. // Data must has value
  40279. return category.value != null ? category : extend({
  40280. value: 0
  40281. }, category);
  40282. });
  40283. var categoriesData = new List(['value'], this);
  40284. categoriesData.initData(categories);
  40285. this._categoriesData = categoriesData;
  40286. this._categoriesModels = categoriesData.mapArray(function (idx) {
  40287. return categoriesData.getItemModel(idx, true);
  40288. });
  40289. },
  40290. setZoom: function (zoom) {
  40291. this.option.zoom = zoom;
  40292. },
  40293. setCenter: function (center) {
  40294. this.option.center = center;
  40295. },
  40296. isAnimationEnabled: function () {
  40297. return GraphSeries.superCall(this, 'isAnimationEnabled')
  40298. // Not enable animation when do force layout
  40299. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  40300. },
  40301. defaultOption: {
  40302. zlevel: 0,
  40303. z: 2,
  40304. coordinateSystem: 'view',
  40305. // Default option for all coordinate systems
  40306. // xAxisIndex: 0,
  40307. // yAxisIndex: 0,
  40308. // polarIndex: 0,
  40309. // geoIndex: 0,
  40310. legendHoverLink: true,
  40311. hoverAnimation: true,
  40312. layout: null,
  40313. focusNodeAdjacency: false,
  40314. // Configuration of circular layout
  40315. circular: {
  40316. rotateLabel: false
  40317. },
  40318. // Configuration of force directed layout
  40319. force: {
  40320. initLayout: null,
  40321. // Node repulsion. Can be an array to represent range.
  40322. repulsion: [0, 50],
  40323. gravity: 0.1,
  40324. // Edge length. Can be an array to represent range.
  40325. edgeLength: 30,
  40326. layoutAnimation: true
  40327. },
  40328. left: 'center',
  40329. top: 'center',
  40330. // right: null,
  40331. // bottom: null,
  40332. // width: '80%',
  40333. // height: '80%',
  40334. symbol: 'circle',
  40335. symbolSize: 10,
  40336. edgeSymbol: ['none', 'none'],
  40337. edgeSymbolSize: 10,
  40338. edgeLabel: {
  40339. position: 'middle'
  40340. },
  40341. draggable: false,
  40342. roam: false,
  40343. // Default on center of graph
  40344. center: null,
  40345. zoom: 1,
  40346. // Symbol size scale ratio in roam
  40347. nodeScaleRatio: 0.6,
  40348. // cursor: null,
  40349. // categories: [],
  40350. // data: []
  40351. // Or
  40352. // nodes: []
  40353. //
  40354. // links: []
  40355. // Or
  40356. // edges: []
  40357. label: {
  40358. show: false,
  40359. formatter: '{b}'
  40360. },
  40361. itemStyle: {},
  40362. lineStyle: {
  40363. color: '#aaa',
  40364. width: 1,
  40365. curveness: 0,
  40366. opacity: 0.5
  40367. },
  40368. emphasis: {
  40369. label: {
  40370. show: true
  40371. }
  40372. }
  40373. }
  40374. });
  40375. /**
  40376. * Line path for bezier and straight line draw
  40377. */
  40378. var straightLineProto = Line.prototype;
  40379. var bezierCurveProto = BezierCurve.prototype;
  40380. function isLine(shape) {
  40381. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  40382. }
  40383. var LinePath = extendShape({
  40384. type: 'ec-line',
  40385. style: {
  40386. stroke: '#000',
  40387. fill: null
  40388. },
  40389. shape: {
  40390. x1: 0,
  40391. y1: 0,
  40392. x2: 0,
  40393. y2: 0,
  40394. percent: 1,
  40395. cpx1: null,
  40396. cpy1: null
  40397. },
  40398. buildPath: function (ctx, shape) {
  40399. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  40400. },
  40401. pointAt: function (t) {
  40402. return isLine(this.shape)
  40403. ? straightLineProto.pointAt.call(this, t)
  40404. : bezierCurveProto.pointAt.call(this, t);
  40405. },
  40406. tangentAt: function (t) {
  40407. var shape = this.shape;
  40408. var p = isLine(shape)
  40409. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  40410. : bezierCurveProto.tangentAt.call(this, t);
  40411. return normalize(p, p);
  40412. }
  40413. });
  40414. /**
  40415. * @module echarts/chart/helper/Line
  40416. */
  40417. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  40418. function makeSymbolTypeKey(symbolCategory) {
  40419. return '_' + symbolCategory + 'Type';
  40420. }
  40421. /**
  40422. * @inner
  40423. */
  40424. function createSymbol$1(name, lineData, idx) {
  40425. var color = lineData.getItemVisual(idx, 'color');
  40426. var symbolType = lineData.getItemVisual(idx, name);
  40427. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  40428. if (!symbolType || symbolType === 'none') {
  40429. return;
  40430. }
  40431. if (!isArray(symbolSize)) {
  40432. symbolSize = [symbolSize, symbolSize];
  40433. }
  40434. var symbolPath = createSymbol(
  40435. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  40436. symbolSize[0], symbolSize[1], color
  40437. );
  40438. symbolPath.name = name;
  40439. return symbolPath;
  40440. }
  40441. function createLine(points) {
  40442. var line = new LinePath({
  40443. name: 'line'
  40444. });
  40445. setLinePoints(line.shape, points);
  40446. return line;
  40447. }
  40448. function setLinePoints(targetShape, points) {
  40449. var p1 = points[0];
  40450. var p2 = points[1];
  40451. var cp1 = points[2];
  40452. targetShape.x1 = p1[0];
  40453. targetShape.y1 = p1[1];
  40454. targetShape.x2 = p2[0];
  40455. targetShape.y2 = p2[1];
  40456. targetShape.percent = 1;
  40457. if (cp1) {
  40458. targetShape.cpx1 = cp1[0];
  40459. targetShape.cpy1 = cp1[1];
  40460. }
  40461. else {
  40462. targetShape.cpx1 = NaN;
  40463. targetShape.cpy1 = NaN;
  40464. }
  40465. }
  40466. function updateSymbolAndLabelBeforeLineUpdate () {
  40467. var lineGroup = this;
  40468. var symbolFrom = lineGroup.childOfName('fromSymbol');
  40469. var symbolTo = lineGroup.childOfName('toSymbol');
  40470. var label = lineGroup.childOfName('label');
  40471. // Quick reject
  40472. if (!symbolFrom && !symbolTo && label.ignore) {
  40473. return;
  40474. }
  40475. var invScale = 1;
  40476. var parentNode = this.parent;
  40477. while (parentNode) {
  40478. if (parentNode.scale) {
  40479. invScale /= parentNode.scale[0];
  40480. }
  40481. parentNode = parentNode.parent;
  40482. }
  40483. var line = lineGroup.childOfName('line');
  40484. // If line not changed
  40485. // FIXME Parent scale changed
  40486. if (!this.__dirty && !line.__dirty) {
  40487. return;
  40488. }
  40489. var percent = line.shape.percent;
  40490. var fromPos = line.pointAt(0);
  40491. var toPos = line.pointAt(percent);
  40492. var d = sub([], toPos, fromPos);
  40493. normalize(d, d);
  40494. if (symbolFrom) {
  40495. symbolFrom.attr('position', fromPos);
  40496. var tangent = line.tangentAt(0);
  40497. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  40498. tangent[1], tangent[0]
  40499. ));
  40500. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  40501. }
  40502. if (symbolTo) {
  40503. symbolTo.attr('position', toPos);
  40504. var tangent = line.tangentAt(1);
  40505. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  40506. tangent[1], tangent[0]
  40507. ));
  40508. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  40509. }
  40510. if (!label.ignore) {
  40511. label.attr('position', toPos);
  40512. var textPosition;
  40513. var textAlign;
  40514. var textVerticalAlign;
  40515. var distance$$1 = 5 * invScale;
  40516. // End
  40517. if (label.__position === 'end') {
  40518. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  40519. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  40520. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  40521. }
  40522. // Middle
  40523. else if (label.__position === 'middle') {
  40524. var halfPercent = percent / 2;
  40525. var tangent = line.tangentAt(halfPercent);
  40526. var n = [tangent[1], -tangent[0]];
  40527. var cp = line.pointAt(halfPercent);
  40528. if (n[1] > 0) {
  40529. n[0] = -n[0];
  40530. n[1] = -n[1];
  40531. }
  40532. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  40533. textAlign = 'center';
  40534. textVerticalAlign = 'bottom';
  40535. var rotation = -Math.atan2(tangent[1], tangent[0]);
  40536. if (toPos[0] < fromPos[0]) {
  40537. rotation = Math.PI + rotation;
  40538. }
  40539. label.attr('rotation', rotation);
  40540. }
  40541. // Start
  40542. else {
  40543. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  40544. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  40545. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  40546. }
  40547. label.attr({
  40548. style: {
  40549. // Use the user specified text align and baseline first
  40550. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  40551. textAlign: label.__textAlign || textAlign
  40552. },
  40553. position: textPosition,
  40554. scale: [invScale, invScale]
  40555. });
  40556. }
  40557. }
  40558. /**
  40559. * @constructor
  40560. * @extends {module:zrender/graphic/Group}
  40561. * @alias {module:echarts/chart/helper/Line}
  40562. */
  40563. function Line$1(lineData, idx, seriesScope) {
  40564. Group.call(this);
  40565. this._createLine(lineData, idx, seriesScope);
  40566. }
  40567. var lineProto = Line$1.prototype;
  40568. // Update symbol position and rotation
  40569. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  40570. lineProto._createLine = function (lineData, idx, seriesScope) {
  40571. var seriesModel = lineData.hostModel;
  40572. var linePoints = lineData.getItemLayout(idx);
  40573. var line = createLine(linePoints);
  40574. line.shape.percent = 0;
  40575. initProps(line, {
  40576. shape: {
  40577. percent: 1
  40578. }
  40579. }, seriesModel, idx);
  40580. this.add(line);
  40581. var label = new Text({
  40582. name: 'label'
  40583. });
  40584. this.add(label);
  40585. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  40586. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  40587. // symbols must added after line to make sure
  40588. // it will be updated after line#update.
  40589. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  40590. this.add(symbol);
  40591. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  40592. }, this);
  40593. this._updateCommonStl(lineData, idx, seriesScope);
  40594. };
  40595. lineProto.updateData = function (lineData, idx, seriesScope) {
  40596. var seriesModel = lineData.hostModel;
  40597. var line = this.childOfName('line');
  40598. var linePoints = lineData.getItemLayout(idx);
  40599. var target = {
  40600. shape: {}
  40601. };
  40602. setLinePoints(target.shape, linePoints);
  40603. updateProps(line, target, seriesModel, idx);
  40604. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  40605. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  40606. var key = makeSymbolTypeKey(symbolCategory);
  40607. // Symbol changed
  40608. if (this[key] !== symbolType) {
  40609. this.remove(this.childOfName(symbolCategory));
  40610. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  40611. this.add(symbol);
  40612. }
  40613. this[key] = symbolType;
  40614. }, this);
  40615. this._updateCommonStl(lineData, idx, seriesScope);
  40616. };
  40617. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  40618. var seriesModel = lineData.hostModel;
  40619. var line = this.childOfName('line');
  40620. var lineStyle = seriesScope && seriesScope.lineStyle;
  40621. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  40622. var labelModel = seriesScope && seriesScope.labelModel;
  40623. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  40624. // Optimization for large dataset
  40625. if (!seriesScope || lineData.hasItemOption) {
  40626. var itemModel = lineData.getItemModel(idx);
  40627. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  40628. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  40629. labelModel = itemModel.getModel('label');
  40630. hoverLabelModel = itemModel.getModel('emphasis.label');
  40631. }
  40632. var visualColor = lineData.getItemVisual(idx, 'color');
  40633. var visualOpacity = retrieve3(
  40634. lineData.getItemVisual(idx, 'opacity'),
  40635. lineStyle.opacity,
  40636. 1
  40637. );
  40638. line.useStyle(defaults(
  40639. {
  40640. strokeNoScale: true,
  40641. fill: 'none',
  40642. stroke: visualColor,
  40643. opacity: visualOpacity
  40644. },
  40645. lineStyle
  40646. ));
  40647. line.hoverStyle = hoverLineStyle;
  40648. // Update symbol
  40649. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  40650. var symbol = this.childOfName(symbolCategory);
  40651. if (symbol) {
  40652. symbol.setColor(visualColor);
  40653. symbol.setStyle({
  40654. opacity: visualOpacity
  40655. });
  40656. }
  40657. }, this);
  40658. var showLabel = labelModel.getShallow('show');
  40659. var hoverShowLabel = hoverLabelModel.getShallow('show');
  40660. var label = this.childOfName('label');
  40661. var defaultLabelColor;
  40662. var normalText;
  40663. var emphasisText;
  40664. if (showLabel || hoverShowLabel) {
  40665. defaultLabelColor = visualColor || '#000';
  40666. normalText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  40667. if (normalText == null) {
  40668. var rawVal = seriesModel.getRawValue(idx);
  40669. normalText = rawVal == null
  40670. ? lineData.getName(idx)
  40671. : isFinite(rawVal)
  40672. ? round$1(rawVal)
  40673. : rawVal;
  40674. }
  40675. emphasisText = retrieve2(
  40676. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  40677. normalText
  40678. );
  40679. }
  40680. // label.afterUpdate = lineAfterUpdate;
  40681. if (showLabel) {
  40682. var labelStyle = setTextStyle(label.style, labelModel, {
  40683. text: normalText
  40684. }, {
  40685. autoColor: defaultLabelColor
  40686. });
  40687. label.__textAlign = labelStyle.textAlign;
  40688. label.__verticalAlign = labelStyle.textVerticalAlign;
  40689. // 'start', 'middle', 'end'
  40690. label.__position = labelModel.get('position') || 'middle';
  40691. }
  40692. else {
  40693. label.setStyle('text', null);
  40694. }
  40695. if (hoverShowLabel) {
  40696. // Only these properties supported in this emphasis style here.
  40697. label.hoverStyle = {
  40698. text: emphasisText,
  40699. textFill: hoverLabelModel.getTextColor(true),
  40700. // For merging hover style to normal style, do not use
  40701. // `hoverLabelModel.getFont()` here.
  40702. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  40703. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  40704. fontSize: hoverLabelModel.getShallow('fontSize'),
  40705. fontFamily: hoverLabelModel.getShallow('fontFamily')
  40706. };
  40707. }
  40708. else {
  40709. label.hoverStyle = {
  40710. text: null
  40711. };
  40712. }
  40713. label.ignore = !showLabel && !hoverShowLabel;
  40714. setHoverStyle(this);
  40715. };
  40716. lineProto.highlight = function () {
  40717. this.trigger('emphasis');
  40718. };
  40719. lineProto.downplay = function () {
  40720. this.trigger('normal');
  40721. };
  40722. lineProto.updateLayout = function (lineData, idx) {
  40723. this.setLinePoints(lineData.getItemLayout(idx));
  40724. };
  40725. lineProto.setLinePoints = function (points) {
  40726. var linePath = this.childOfName('line');
  40727. setLinePoints(linePath.shape, points);
  40728. linePath.dirty();
  40729. };
  40730. inherits(Line$1, Group);
  40731. /**
  40732. * @module echarts/chart/helper/LineDraw
  40733. */
  40734. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  40735. /**
  40736. * @alias module:echarts/component/marker/LineDraw
  40737. * @constructor
  40738. */
  40739. function LineDraw(ctor) {
  40740. this._ctor = ctor || Line$1;
  40741. this.group = new Group();
  40742. }
  40743. var lineDrawProto = LineDraw.prototype;
  40744. lineDrawProto.isPersistent = function () {
  40745. return true;
  40746. };
  40747. /**
  40748. * @param {module:echarts/data/List} lineData
  40749. */
  40750. lineDrawProto.updateData = function (lineData) {
  40751. var lineDraw = this;
  40752. var group = lineDraw.group;
  40753. var oldLineData = lineDraw._lineData;
  40754. lineDraw._lineData = lineData;
  40755. // There is no oldLineData only when first rendering or switching from
  40756. // stream mode to normal mode, where previous elements should be removed.
  40757. if (!oldLineData) {
  40758. group.removeAll();
  40759. }
  40760. var seriesScope = makeSeriesScope$1(lineData);
  40761. lineData.diff(oldLineData)
  40762. .add(function (idx) {
  40763. doAdd(lineDraw, lineData, idx, seriesScope);
  40764. })
  40765. .update(function (newIdx, oldIdx) {
  40766. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  40767. })
  40768. .remove(function (idx) {
  40769. group.remove(oldLineData.getItemGraphicEl(idx));
  40770. })
  40771. .execute();
  40772. };
  40773. function doAdd(lineDraw, lineData, idx, seriesScope) {
  40774. var itemLayout = lineData.getItemLayout(idx);
  40775. if (!lineNeedsDraw(itemLayout)) {
  40776. return;
  40777. }
  40778. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  40779. lineData.setItemGraphicEl(idx, el);
  40780. lineDraw.group.add(el);
  40781. }
  40782. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  40783. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  40784. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  40785. lineDraw.group.remove(itemEl);
  40786. return;
  40787. }
  40788. if (!itemEl) {
  40789. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  40790. }
  40791. else {
  40792. itemEl.updateData(newLineData, newIdx, seriesScope);
  40793. }
  40794. newLineData.setItemGraphicEl(newIdx, itemEl);
  40795. lineDraw.group.add(itemEl);
  40796. }
  40797. lineDrawProto.updateLayout = function () {
  40798. var lineData = this._lineData;
  40799. lineData.eachItemGraphicEl(function (el, idx) {
  40800. el.updateLayout(lineData, idx);
  40801. }, this);
  40802. };
  40803. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  40804. this._seriesScope = makeSeriesScope$1(lineData);
  40805. this._lineData = null;
  40806. this.group.removeAll();
  40807. };
  40808. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  40809. function updateIncrementalAndHover(el) {
  40810. if (!el.isGroup) {
  40811. el.incremental = el.useHoverLayer = true;
  40812. }
  40813. }
  40814. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  40815. var itemLayout = lineData.getItemLayout(idx);
  40816. if (lineNeedsDraw(itemLayout)) {
  40817. var el = new this._ctor(lineData, idx, this._seriesScope);
  40818. el.traverse(updateIncrementalAndHover);
  40819. this.group.add(el);
  40820. }
  40821. }
  40822. };
  40823. function makeSeriesScope$1(lineData) {
  40824. var hostModel = lineData.hostModel;
  40825. return {
  40826. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  40827. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  40828. labelModel: hostModel.getModel('label'),
  40829. hoverLabelModel: hostModel.getModel('emphasis.label')
  40830. };
  40831. }
  40832. lineDrawProto.remove = function () {
  40833. this._clearIncremental();
  40834. this._incremental = null;
  40835. this.group.removeAll();
  40836. };
  40837. lineDrawProto._clearIncremental = function () {
  40838. var incremental = this._incremental;
  40839. if (incremental) {
  40840. incremental.clearDisplaybles();
  40841. }
  40842. };
  40843. function isPointNaN(pt) {
  40844. return isNaN(pt[0]) || isNaN(pt[1]);
  40845. }
  40846. function lineNeedsDraw(pts) {
  40847. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  40848. }
  40849. var v1 = [];
  40850. var v2 = [];
  40851. var v3 = [];
  40852. var quadraticAt$1 = quadraticAt;
  40853. var v2DistSquare = distSquare;
  40854. var mathAbs$1 = Math.abs;
  40855. function intersectCurveCircle(curvePoints, center, radius) {
  40856. var p0 = curvePoints[0];
  40857. var p1 = curvePoints[1];
  40858. var p2 = curvePoints[2];
  40859. var d = Infinity;
  40860. var t;
  40861. var radiusSquare = radius * radius;
  40862. var interval = 0.1;
  40863. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  40864. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  40865. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  40866. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  40867. if (diff < d) {
  40868. d = diff;
  40869. t = _t;
  40870. }
  40871. }
  40872. // Assume the segment is monotone,Find root through Bisection method
  40873. // At most 32 iteration
  40874. for (var i = 0; i < 32; i++) {
  40875. // var prev = t - interval;
  40876. var next = t + interval;
  40877. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  40878. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  40879. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  40880. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  40881. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  40882. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  40883. var diff = v2DistSquare(v2, center) - radiusSquare;
  40884. if (mathAbs$1(diff) < 1e-2) {
  40885. break;
  40886. }
  40887. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  40888. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  40889. interval /= 2;
  40890. if (diff < 0) {
  40891. if (nextDiff >= 0) {
  40892. t = t + interval;
  40893. }
  40894. else {
  40895. t = t - interval;
  40896. }
  40897. }
  40898. else {
  40899. if (nextDiff >= 0) {
  40900. t = t - interval;
  40901. }
  40902. else {
  40903. t = t + interval;
  40904. }
  40905. }
  40906. }
  40907. return t;
  40908. }
  40909. // Adjust edge to avoid
  40910. var adjustEdge = function (graph, scale$$1) {
  40911. var tmp0 = [];
  40912. var quadraticSubdivide$$1 = quadraticSubdivide;
  40913. var pts = [[], [], []];
  40914. var pts2 = [[], []];
  40915. var v = [];
  40916. scale$$1 /= 2;
  40917. function getSymbolSize(node) {
  40918. var symbolSize = node.getVisual('symbolSize');
  40919. if (symbolSize instanceof Array) {
  40920. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  40921. }
  40922. return symbolSize;
  40923. }
  40924. graph.eachEdge(function (edge, idx) {
  40925. var linePoints = edge.getLayout();
  40926. var fromSymbol = edge.getVisual('fromSymbol');
  40927. var toSymbol = edge.getVisual('toSymbol');
  40928. if (!linePoints.__original) {
  40929. linePoints.__original = [
  40930. clone$1(linePoints[0]),
  40931. clone$1(linePoints[1])
  40932. ];
  40933. if (linePoints[2]) {
  40934. linePoints.__original.push(clone$1(linePoints[2]));
  40935. }
  40936. }
  40937. var originalPoints = linePoints.__original;
  40938. // Quadratic curve
  40939. if (linePoints[2] != null) {
  40940. copy(pts[0], originalPoints[0]);
  40941. copy(pts[1], originalPoints[2]);
  40942. copy(pts[2], originalPoints[1]);
  40943. if (fromSymbol && fromSymbol != 'none') {
  40944. var symbolSize = getSymbolSize(edge.node1);
  40945. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  40946. // Subdivide and get the second
  40947. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  40948. pts[0][0] = tmp0[3];
  40949. pts[1][0] = tmp0[4];
  40950. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  40951. pts[0][1] = tmp0[3];
  40952. pts[1][1] = tmp0[4];
  40953. }
  40954. if (toSymbol && toSymbol != 'none') {
  40955. var symbolSize = getSymbolSize(edge.node2);
  40956. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  40957. // Subdivide and get the first
  40958. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  40959. pts[1][0] = tmp0[1];
  40960. pts[2][0] = tmp0[2];
  40961. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  40962. pts[1][1] = tmp0[1];
  40963. pts[2][1] = tmp0[2];
  40964. }
  40965. // Copy back to layout
  40966. copy(linePoints[0], pts[0]);
  40967. copy(linePoints[1], pts[2]);
  40968. copy(linePoints[2], pts[1]);
  40969. }
  40970. // Line
  40971. else {
  40972. copy(pts2[0], originalPoints[0]);
  40973. copy(pts2[1], originalPoints[1]);
  40974. sub(v, pts2[1], pts2[0]);
  40975. normalize(v, v);
  40976. if (fromSymbol && fromSymbol != 'none') {
  40977. var symbolSize = getSymbolSize(edge.node1);
  40978. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  40979. }
  40980. if (toSymbol && toSymbol != 'none') {
  40981. var symbolSize = getSymbolSize(edge.node2);
  40982. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  40983. }
  40984. copy(linePoints[0], pts2[0]);
  40985. copy(linePoints[1], pts2[1]);
  40986. }
  40987. });
  40988. };
  40989. var nodeOpacityPath = ['itemStyle', 'opacity'];
  40990. var lineOpacityPath = ['lineStyle', 'opacity'];
  40991. function getItemOpacity(item, opacityPath) {
  40992. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  40993. }
  40994. function fadeOutItem(item, opacityPath, opacityRatio) {
  40995. var el = item.getGraphicEl();
  40996. var opacity = getItemOpacity(item, opacityPath);
  40997. if (opacityRatio != null) {
  40998. opacity == null && (opacity = 1);
  40999. opacity *= opacityRatio;
  41000. }
  41001. el.downplay && el.downplay();
  41002. el.traverse(function (child) {
  41003. if (child.type !== 'group') {
  41004. child.setStyle('opacity', opacity);
  41005. }
  41006. });
  41007. }
  41008. function fadeInItem(item, opacityPath) {
  41009. var opacity = getItemOpacity(item, opacityPath);
  41010. var el = item.getGraphicEl();
  41011. el.highlight && el.highlight();
  41012. el.traverse(function (child) {
  41013. if (child.type !== 'group') {
  41014. child.setStyle('opacity', opacity);
  41015. }
  41016. });
  41017. }
  41018. extendChartView({
  41019. type: 'graph',
  41020. init: function (ecModel, api) {
  41021. var symbolDraw = new SymbolDraw();
  41022. var lineDraw = new LineDraw();
  41023. var group = this.group;
  41024. this._controller = new RoamController(api.getZr());
  41025. this._controllerHost = {target: group};
  41026. group.add(symbolDraw.group);
  41027. group.add(lineDraw.group);
  41028. this._symbolDraw = symbolDraw;
  41029. this._lineDraw = lineDraw;
  41030. this._firstRender = true;
  41031. },
  41032. render: function (seriesModel, ecModel, api) {
  41033. var coordSys = seriesModel.coordinateSystem;
  41034. this._model = seriesModel;
  41035. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  41036. var symbolDraw = this._symbolDraw;
  41037. var lineDraw = this._lineDraw;
  41038. var group = this.group;
  41039. if (coordSys.type === 'view') {
  41040. var groupNewProp = {
  41041. position: coordSys.position,
  41042. scale: coordSys.scale
  41043. };
  41044. if (this._firstRender) {
  41045. group.attr(groupNewProp);
  41046. }
  41047. else {
  41048. updateProps(group, groupNewProp, seriesModel);
  41049. }
  41050. }
  41051. // Fix edge contact point with node
  41052. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  41053. var data = seriesModel.getData();
  41054. symbolDraw.updateData(data);
  41055. var edgeData = seriesModel.getEdgeData();
  41056. lineDraw.updateData(edgeData);
  41057. this._updateNodeAndLinkScale();
  41058. this._updateController(seriesModel, ecModel, api);
  41059. clearTimeout(this._layoutTimeout);
  41060. var forceLayout = seriesModel.forceLayout;
  41061. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  41062. if (forceLayout) {
  41063. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  41064. }
  41065. data.eachItemGraphicEl(function (el, idx) {
  41066. var itemModel = data.getItemModel(idx);
  41067. // Update draggable
  41068. el.off('drag').off('dragend');
  41069. var draggable = data.getItemModel(idx).get('draggable');
  41070. if (draggable) {
  41071. el.on('drag', function () {
  41072. if (forceLayout) {
  41073. forceLayout.warmUp();
  41074. !this._layouting
  41075. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  41076. forceLayout.setFixed(idx);
  41077. // Write position back to layout
  41078. data.setItemLayout(idx, el.position);
  41079. }
  41080. }, this).on('dragend', function () {
  41081. if (forceLayout) {
  41082. forceLayout.setUnfixed(idx);
  41083. }
  41084. }, this);
  41085. }
  41086. el.setDraggable(draggable && forceLayout);
  41087. el.off('mouseover', el.__focusNodeAdjacency);
  41088. el.off('mouseout', el.__unfocusNodeAdjacency);
  41089. if (itemModel.get('focusNodeAdjacency')) {
  41090. el.on('mouseover', el.__focusNodeAdjacency = function () {
  41091. api.dispatchAction({
  41092. type: 'focusNodeAdjacency',
  41093. seriesId: seriesModel.id,
  41094. dataIndex: el.dataIndex
  41095. });
  41096. });
  41097. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  41098. api.dispatchAction({
  41099. type: 'unfocusNodeAdjacency',
  41100. seriesId: seriesModel.id
  41101. });
  41102. });
  41103. }
  41104. }, this);
  41105. data.graph.eachEdge(function (edge) {
  41106. var el = edge.getGraphicEl();
  41107. el.off('mouseover', el.__focusNodeAdjacency);
  41108. el.off('mouseout', el.__unfocusNodeAdjacency);
  41109. if (edge.getModel().get('focusNodeAdjacency')) {
  41110. el.on('mouseover', el.__focusNodeAdjacency = function () {
  41111. api.dispatchAction({
  41112. type: 'focusNodeAdjacency',
  41113. seriesId: seriesModel.id,
  41114. edgeDataIndex: edge.dataIndex
  41115. });
  41116. });
  41117. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  41118. api.dispatchAction({
  41119. type: 'unfocusNodeAdjacency',
  41120. seriesId: seriesModel.id
  41121. });
  41122. });
  41123. }
  41124. });
  41125. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  41126. && seriesModel.get('circular.rotateLabel');
  41127. var cx = data.getLayout('cx');
  41128. var cy = data.getLayout('cy');
  41129. data.eachItemGraphicEl(function (el, idx) {
  41130. var symbolPath = el.getSymbolPath();
  41131. if (circularRotateLabel) {
  41132. var pos = data.getItemLayout(idx);
  41133. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  41134. if (rad < 0) {
  41135. rad = Math.PI * 2 + rad;
  41136. }
  41137. var isLeft = pos[0] < cx;
  41138. if (isLeft) {
  41139. rad = rad - Math.PI;
  41140. }
  41141. var textPosition = isLeft ? 'left' : 'right';
  41142. symbolPath.setStyle({
  41143. textRotation: -rad,
  41144. textPosition: textPosition,
  41145. textOrigin: 'center'
  41146. });
  41147. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  41148. }
  41149. else {
  41150. symbolPath.setStyle({
  41151. textRotation: 0
  41152. });
  41153. }
  41154. });
  41155. this._firstRender = false;
  41156. },
  41157. dispose: function () {
  41158. this._controller && this._controller.dispose();
  41159. this._controllerHost = {};
  41160. },
  41161. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  41162. var data = this._model.getData();
  41163. var graph = data.graph;
  41164. var dataIndex = payload.dataIndex;
  41165. var edgeDataIndex = payload.edgeDataIndex;
  41166. var node = graph.getNodeByIndex(dataIndex);
  41167. var edge = graph.getEdgeByIndex(edgeDataIndex);
  41168. if (!node && !edge) {
  41169. return;
  41170. }
  41171. graph.eachNode(function (node) {
  41172. fadeOutItem(node, nodeOpacityPath, 0.1);
  41173. });
  41174. graph.eachEdge(function (edge) {
  41175. fadeOutItem(edge, lineOpacityPath, 0.1);
  41176. });
  41177. if (node) {
  41178. fadeInItem(node, nodeOpacityPath);
  41179. each$1(node.edges, function (adjacentEdge) {
  41180. if (adjacentEdge.dataIndex < 0) {
  41181. return;
  41182. }
  41183. fadeInItem(adjacentEdge, lineOpacityPath);
  41184. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  41185. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  41186. });
  41187. }
  41188. if (edge) {
  41189. fadeInItem(edge, lineOpacityPath);
  41190. fadeInItem(edge.node1, nodeOpacityPath);
  41191. fadeInItem(edge.node2, nodeOpacityPath);
  41192. }
  41193. },
  41194. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  41195. var graph = this._model.getData().graph;
  41196. graph.eachNode(function (node) {
  41197. fadeOutItem(node, nodeOpacityPath);
  41198. });
  41199. graph.eachEdge(function (edge) {
  41200. fadeOutItem(edge, lineOpacityPath);
  41201. });
  41202. },
  41203. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  41204. var self = this;
  41205. (function step() {
  41206. forceLayout.step(function (stopped) {
  41207. self.updateLayout(self._model);
  41208. (self._layouting = !stopped) && (
  41209. layoutAnimation
  41210. ? (self._layoutTimeout = setTimeout(step, 16))
  41211. : step()
  41212. );
  41213. });
  41214. })();
  41215. },
  41216. _updateController: function (seriesModel, ecModel, api) {
  41217. var controller = this._controller;
  41218. var controllerHost = this._controllerHost;
  41219. var group = this.group;
  41220. controller.setPointerChecker(function (e, x, y) {
  41221. var rect = group.getBoundingRect();
  41222. rect.applyTransform(group.transform);
  41223. return rect.contain(x, y)
  41224. && !onIrrelevantElement(e, api, seriesModel);
  41225. });
  41226. if (seriesModel.coordinateSystem.type !== 'view') {
  41227. controller.disable();
  41228. return;
  41229. }
  41230. controller.enable(seriesModel.get('roam'));
  41231. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  41232. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  41233. controller
  41234. .off('pan')
  41235. .off('zoom')
  41236. .on('pan', function (dx, dy) {
  41237. updateViewOnPan(controllerHost, dx, dy);
  41238. api.dispatchAction({
  41239. seriesId: seriesModel.id,
  41240. type: 'graphRoam',
  41241. dx: dx,
  41242. dy: dy
  41243. });
  41244. })
  41245. .on('zoom', function (zoom, mouseX, mouseY) {
  41246. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  41247. api.dispatchAction({
  41248. seriesId: seriesModel.id,
  41249. type: 'graphRoam',
  41250. zoom: zoom,
  41251. originX: mouseX,
  41252. originY: mouseY
  41253. });
  41254. this._updateNodeAndLinkScale();
  41255. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  41256. this._lineDraw.updateLayout();
  41257. }, this);
  41258. },
  41259. _updateNodeAndLinkScale: function () {
  41260. var seriesModel = this._model;
  41261. var data = seriesModel.getData();
  41262. var nodeScale = this._getNodeGlobalScale(seriesModel);
  41263. var invScale = [nodeScale, nodeScale];
  41264. data.eachItemGraphicEl(function (el, idx) {
  41265. el.attr('scale', invScale);
  41266. });
  41267. },
  41268. _getNodeGlobalScale: function (seriesModel) {
  41269. var coordSys = seriesModel.coordinateSystem;
  41270. if (coordSys.type !== 'view') {
  41271. return 1;
  41272. }
  41273. var nodeScaleRatio = this._nodeScaleRatio;
  41274. var groupScale = coordSys.scale;
  41275. var groupZoom = (groupScale && groupScale[0]) || 1;
  41276. // Scale node when zoom changes
  41277. var roamZoom = coordSys.getZoom();
  41278. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  41279. return nodeScale / groupZoom;
  41280. },
  41281. updateLayout: function (seriesModel) {
  41282. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  41283. this._symbolDraw.updateLayout();
  41284. this._lineDraw.updateLayout();
  41285. },
  41286. remove: function (ecModel, api) {
  41287. this._symbolDraw && this._symbolDraw.remove();
  41288. this._lineDraw && this._lineDraw.remove();
  41289. }
  41290. });
  41291. var actionInfo = {
  41292. type: 'graphRoam',
  41293. event: 'graphRoam',
  41294. update: 'none'
  41295. };
  41296. /**
  41297. * @payload
  41298. * @property {string} name Series name
  41299. * @property {number} [dx]
  41300. * @property {number} [dy]
  41301. * @property {number} [zoom]
  41302. * @property {number} [originX]
  41303. * @property {number} [originY]
  41304. */
  41305. registerAction(actionInfo, function (payload, ecModel) {
  41306. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  41307. var coordSys = seriesModel.coordinateSystem;
  41308. var res = updateCenterAndZoom(coordSys, payload);
  41309. seriesModel.setCenter
  41310. && seriesModel.setCenter(res.center);
  41311. seriesModel.setZoom
  41312. && seriesModel.setZoom(res.zoom);
  41313. });
  41314. });
  41315. /**
  41316. * @payload
  41317. * @property {number} [seriesIndex]
  41318. * @property {string} [seriesId]
  41319. * @property {string} [seriesName]
  41320. * @property {number} [dataIndex]
  41321. */
  41322. registerAction({
  41323. type: 'focusNodeAdjacency',
  41324. event: 'focusNodeAdjacency',
  41325. update: 'series.graph:focusNodeAdjacency'
  41326. }, function () {});
  41327. /**
  41328. * @payload
  41329. * @property {number} [seriesIndex]
  41330. * @property {string} [seriesId]
  41331. * @property {string} [seriesName]
  41332. */
  41333. registerAction({
  41334. type: 'unfocusNodeAdjacency',
  41335. event: 'unfocusNodeAdjacency',
  41336. update: 'series.graph:unfocusNodeAdjacency'
  41337. }, function () {});
  41338. var categoryFilter = function (ecModel) {
  41339. var legendModels = ecModel.findComponents({
  41340. mainType: 'legend'
  41341. });
  41342. if (!legendModels || !legendModels.length) {
  41343. return;
  41344. }
  41345. ecModel.eachSeriesByType('graph', function (graphSeries) {
  41346. var categoriesData = graphSeries.getCategoriesData();
  41347. var graph = graphSeries.getGraph();
  41348. var data = graph.data;
  41349. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  41350. data.filterSelf(function (idx) {
  41351. var model = data.getItemModel(idx);
  41352. var category = model.getShallow('category');
  41353. if (category != null) {
  41354. if (typeof category === 'number') {
  41355. category = categoryNames[category];
  41356. }
  41357. // If in any legend component the status is not selected.
  41358. for (var i = 0; i < legendModels.length; i++) {
  41359. if (!legendModels[i].isSelected(category)) {
  41360. return false;
  41361. }
  41362. }
  41363. }
  41364. return true;
  41365. });
  41366. }, this);
  41367. };
  41368. var categoryVisual = function (ecModel) {
  41369. var paletteScope = {};
  41370. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41371. var categoriesData = seriesModel.getCategoriesData();
  41372. var data = seriesModel.getData();
  41373. var categoryNameIdxMap = {};
  41374. categoriesData.each(function (idx) {
  41375. var name = categoriesData.getName(idx);
  41376. // Add prefix to avoid conflict with Object.prototype.
  41377. categoryNameIdxMap['ec-' + name] = idx;
  41378. var itemModel = categoriesData.getItemModel(idx);
  41379. var color = itemModel.get('itemStyle.color')
  41380. || seriesModel.getColorFromPalette(name, paletteScope);
  41381. categoriesData.setItemVisual(idx, 'color', color);
  41382. });
  41383. // Assign category color to visual
  41384. if (categoriesData.count()) {
  41385. data.each(function (idx) {
  41386. var model = data.getItemModel(idx);
  41387. var category = model.getShallow('category');
  41388. if (category != null) {
  41389. if (typeof category === 'string') {
  41390. category = categoryNameIdxMap['ec-' + category];
  41391. }
  41392. if (!data.getItemVisual(idx, 'color', true)) {
  41393. data.setItemVisual(
  41394. idx, 'color',
  41395. categoriesData.getItemVisual(category, 'color')
  41396. );
  41397. }
  41398. }
  41399. });
  41400. }
  41401. });
  41402. };
  41403. function normalize$1(a) {
  41404. if (!(a instanceof Array)) {
  41405. a = [a, a];
  41406. }
  41407. return a;
  41408. }
  41409. var edgeVisual = function (ecModel) {
  41410. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41411. var graph = seriesModel.getGraph();
  41412. var edgeData = seriesModel.getEdgeData();
  41413. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  41414. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  41415. var colorQuery = 'lineStyle.color'.split('.');
  41416. var opacityQuery = 'lineStyle.opacity'.split('.');
  41417. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  41418. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  41419. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  41420. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  41421. edgeData.setVisual('color', seriesModel.get(colorQuery));
  41422. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  41423. edgeData.each(function (idx) {
  41424. var itemModel = edgeData.getItemModel(idx);
  41425. var edge = graph.getEdgeByIndex(idx);
  41426. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  41427. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  41428. // Edge visual must after node visual
  41429. var color = itemModel.get(colorQuery);
  41430. var opacity = itemModel.get(opacityQuery);
  41431. switch (color) {
  41432. case 'source':
  41433. color = edge.node1.getVisual('color');
  41434. break;
  41435. case 'target':
  41436. color = edge.node2.getVisual('color');
  41437. break;
  41438. }
  41439. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  41440. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  41441. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  41442. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  41443. edge.setVisual('color', color);
  41444. edge.setVisual('opacity', opacity);
  41445. });
  41446. });
  41447. };
  41448. function simpleLayout$1(seriesModel) {
  41449. var coordSys = seriesModel.coordinateSystem;
  41450. if (coordSys && coordSys.type !== 'view') {
  41451. return;
  41452. }
  41453. var graph = seriesModel.getGraph();
  41454. graph.eachNode(function (node) {
  41455. var model = node.getModel();
  41456. node.setLayout([+model.get('x'), +model.get('y')]);
  41457. });
  41458. simpleLayoutEdge(graph);
  41459. }
  41460. function simpleLayoutEdge(graph) {
  41461. graph.eachEdge(function (edge) {
  41462. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  41463. var p1 = clone$1(edge.node1.getLayout());
  41464. var p2 = clone$1(edge.node2.getLayout());
  41465. var points = [p1, p2];
  41466. if (+curveness) {
  41467. points.push([
  41468. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  41469. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  41470. ]);
  41471. }
  41472. edge.setLayout(points);
  41473. });
  41474. }
  41475. var simpleLayout = function (ecModel, api) {
  41476. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41477. var layout = seriesModel.get('layout');
  41478. var coordSys = seriesModel.coordinateSystem;
  41479. if (coordSys && coordSys.type !== 'view') {
  41480. var data = seriesModel.getData();
  41481. var dimensions = [];
  41482. each$1(coordSys.dimensions, function (coordDim) {
  41483. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  41484. });
  41485. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  41486. var value = [];
  41487. var hasValue = false;
  41488. for (var i = 0; i < dimensions.length; i++) {
  41489. var val = data.get(dimensions[i], dataIndex);
  41490. if (!isNaN(val)) {
  41491. hasValue = true;
  41492. }
  41493. value.push(val);
  41494. }
  41495. if (hasValue) {
  41496. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  41497. }
  41498. else {
  41499. // Also {Array.<number>}, not undefined to avoid if...else... statement
  41500. data.setItemLayout(dataIndex, [NaN, NaN]);
  41501. }
  41502. }
  41503. simpleLayoutEdge(data.graph);
  41504. }
  41505. else if (!layout || layout === 'none') {
  41506. simpleLayout$1(seriesModel);
  41507. }
  41508. });
  41509. };
  41510. function circularLayout$1(seriesModel) {
  41511. var coordSys = seriesModel.coordinateSystem;
  41512. if (coordSys && coordSys.type !== 'view') {
  41513. return;
  41514. }
  41515. var rect = coordSys.getBoundingRect();
  41516. var nodeData = seriesModel.getData();
  41517. var graph = nodeData.graph;
  41518. var angle = 0;
  41519. var sum = nodeData.getSum('value');
  41520. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  41521. var cx = rect.width / 2 + rect.x;
  41522. var cy = rect.height / 2 + rect.y;
  41523. var r = Math.min(rect.width, rect.height) / 2;
  41524. graph.eachNode(function (node) {
  41525. var value = node.getValue('value');
  41526. angle += unitAngle * (sum ? value : 1) / 2;
  41527. node.setLayout([
  41528. r * Math.cos(angle) + cx,
  41529. r * Math.sin(angle) + cy
  41530. ]);
  41531. angle += unitAngle * (sum ? value : 1) / 2;
  41532. });
  41533. nodeData.setLayout({
  41534. cx: cx,
  41535. cy: cy
  41536. });
  41537. graph.eachEdge(function (edge) {
  41538. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  41539. var p1 = clone$1(edge.node1.getLayout());
  41540. var p2 = clone$1(edge.node2.getLayout());
  41541. var cp1;
  41542. var x12 = (p1[0] + p2[0]) / 2;
  41543. var y12 = (p1[1] + p2[1]) / 2;
  41544. if (+curveness) {
  41545. curveness *= 3;
  41546. cp1 = [
  41547. cx * curveness + x12 * (1 - curveness),
  41548. cy * curveness + y12 * (1 - curveness)
  41549. ];
  41550. }
  41551. edge.setLayout([p1, p2, cp1]);
  41552. });
  41553. }
  41554. var circularLayout = function (ecModel) {
  41555. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41556. if (seriesModel.get('layout') === 'circular') {
  41557. circularLayout$1(seriesModel);
  41558. }
  41559. });
  41560. };
  41561. var scaleAndAdd$2 = scaleAndAdd;
  41562. // function adjacentNode(n, e) {
  41563. // return e.n1 === n ? e.n2 : e.n1;
  41564. // }
  41565. function forceLayout$1(nodes, edges, opts) {
  41566. var rect = opts.rect;
  41567. var width = rect.width;
  41568. var height = rect.height;
  41569. var center = [rect.x + width / 2, rect.y + height / 2];
  41570. // var scale = opts.scale || 1;
  41571. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  41572. // for (var i = 0; i < edges.length; i++) {
  41573. // var e = edges[i];
  41574. // var n1 = e.n1;
  41575. // var n2 = e.n2;
  41576. // n1.edges = n1.edges || [];
  41577. // n2.edges = n2.edges || [];
  41578. // n1.edges.push(e);
  41579. // n2.edges.push(e);
  41580. // }
  41581. // Init position
  41582. for (var i = 0; i < nodes.length; i++) {
  41583. var n = nodes[i];
  41584. if (!n.p) {
  41585. // Use the position from first adjecent node with defined position
  41586. // Or use a random position
  41587. // From d3
  41588. // if (n.edges) {
  41589. // var j = -1;
  41590. // while (++j < n.edges.length) {
  41591. // var e = n.edges[j];
  41592. // var other = adjacentNode(n, e);
  41593. // if (other.p) {
  41594. // n.p = vec2.clone(other.p);
  41595. // break;
  41596. // }
  41597. // }
  41598. // }
  41599. // if (!n.p) {
  41600. n.p = create(
  41601. width * (Math.random() - 0.5) + center[0],
  41602. height * (Math.random() - 0.5) + center[1]
  41603. );
  41604. // }
  41605. }
  41606. n.pp = clone$1(n.p);
  41607. n.edges = null;
  41608. }
  41609. // Formula in 'Graph Drawing by Force-directed Placement'
  41610. // var k = scale * Math.sqrt(width * height / nodes.length);
  41611. // var k2 = k * k;
  41612. var friction = 0.6;
  41613. return {
  41614. warmUp: function () {
  41615. friction = 0.5;
  41616. },
  41617. setFixed: function (idx) {
  41618. nodes[idx].fixed = true;
  41619. },
  41620. setUnfixed: function (idx) {
  41621. nodes[idx].fixed = false;
  41622. },
  41623. step: function (cb) {
  41624. var v12 = [];
  41625. var nLen = nodes.length;
  41626. for (var i = 0; i < edges.length; i++) {
  41627. var e = edges[i];
  41628. var n1 = e.n1;
  41629. var n2 = e.n2;
  41630. sub(v12, n2.p, n1.p);
  41631. var d = len(v12) - e.d;
  41632. var w = n2.w / (n1.w + n2.w);
  41633. if (isNaN(w)) {
  41634. w = 0;
  41635. }
  41636. normalize(v12, v12);
  41637. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  41638. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  41639. }
  41640. // Gravity
  41641. for (var i = 0; i < nLen; i++) {
  41642. var n = nodes[i];
  41643. if (!n.fixed) {
  41644. sub(v12, center, n.p);
  41645. // var d = vec2.len(v12);
  41646. // vec2.scale(v12, v12, 1 / d);
  41647. // var gravityFactor = gravity;
  41648. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  41649. }
  41650. }
  41651. // Repulsive
  41652. // PENDING
  41653. for (var i = 0; i < nLen; i++) {
  41654. var n1 = nodes[i];
  41655. for (var j = i + 1; j < nLen; j++) {
  41656. var n2 = nodes[j];
  41657. sub(v12, n2.p, n1.p);
  41658. var d = len(v12);
  41659. if (d === 0) {
  41660. // Random repulse
  41661. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  41662. d = 1;
  41663. }
  41664. var repFact = (n1.rep + n2.rep) / d / d;
  41665. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  41666. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  41667. }
  41668. }
  41669. var v = [];
  41670. for (var i = 0; i < nLen; i++) {
  41671. var n = nodes[i];
  41672. if (!n.fixed) {
  41673. sub(v, n.p, n.pp);
  41674. scaleAndAdd$2(n.p, n.p, v, friction);
  41675. copy(n.pp, n.p);
  41676. }
  41677. }
  41678. friction = friction * 0.992;
  41679. cb && cb(nodes, edges, friction < 0.01);
  41680. }
  41681. };
  41682. }
  41683. var forceLayout = function (ecModel) {
  41684. ecModel.eachSeriesByType('graph', function (graphSeries) {
  41685. var coordSys = graphSeries.coordinateSystem;
  41686. if (coordSys && coordSys.type !== 'view') {
  41687. return;
  41688. }
  41689. if (graphSeries.get('layout') === 'force') {
  41690. var preservedPoints = graphSeries.preservedPoints || {};
  41691. var graph = graphSeries.getGraph();
  41692. var nodeData = graph.data;
  41693. var edgeData = graph.edgeData;
  41694. var forceModel = graphSeries.getModel('force');
  41695. var initLayout = forceModel.get('initLayout');
  41696. if (graphSeries.preservedPoints) {
  41697. nodeData.each(function (idx) {
  41698. var id = nodeData.getId(idx);
  41699. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  41700. });
  41701. }
  41702. else if (!initLayout || initLayout === 'none') {
  41703. simpleLayout$1(graphSeries);
  41704. }
  41705. else if (initLayout === 'circular') {
  41706. circularLayout$1(graphSeries);
  41707. }
  41708. var nodeDataExtent = nodeData.getDataExtent('value');
  41709. var edgeDataExtent = edgeData.getDataExtent('value');
  41710. // var edgeDataExtent = edgeData.getDataExtent('value');
  41711. var repulsion = forceModel.get('repulsion');
  41712. var edgeLength = forceModel.get('edgeLength');
  41713. if (!isArray(repulsion)) {
  41714. repulsion = [repulsion, repulsion];
  41715. }
  41716. if (!isArray(edgeLength)) {
  41717. edgeLength = [edgeLength, edgeLength];
  41718. }
  41719. // Larger value has smaller length
  41720. edgeLength = [edgeLength[1], edgeLength[0]];
  41721. var nodes = nodeData.mapArray('value', function (value, idx) {
  41722. var point = nodeData.getItemLayout(idx);
  41723. var rep = linearMap(value, nodeDataExtent, repulsion);
  41724. if (isNaN(rep)) {
  41725. rep = (repulsion[0] + repulsion[1]) / 2;
  41726. }
  41727. return {
  41728. w: rep,
  41729. rep: rep,
  41730. fixed: nodeData.getItemModel(idx).get('fixed'),
  41731. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  41732. };
  41733. });
  41734. var edges = edgeData.mapArray('value', function (value, idx) {
  41735. var edge = graph.getEdgeByIndex(idx);
  41736. var d = linearMap(value, edgeDataExtent, edgeLength);
  41737. if (isNaN(d)) {
  41738. d = (edgeLength[0] + edgeLength[1]) / 2;
  41739. }
  41740. return {
  41741. n1: nodes[edge.node1.dataIndex],
  41742. n2: nodes[edge.node2.dataIndex],
  41743. d: d,
  41744. curveness: edge.getModel().get('lineStyle.curveness') || 0
  41745. };
  41746. });
  41747. var coordSys = graphSeries.coordinateSystem;
  41748. var rect = coordSys.getBoundingRect();
  41749. var forceInstance = forceLayout$1(nodes, edges, {
  41750. rect: rect,
  41751. gravity: forceModel.get('gravity')
  41752. });
  41753. var oldStep = forceInstance.step;
  41754. forceInstance.step = function (cb) {
  41755. for (var i = 0, l = nodes.length; i < l; i++) {
  41756. if (nodes[i].fixed) {
  41757. // Write back to layout instance
  41758. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  41759. }
  41760. }
  41761. oldStep(function (nodes, edges, stopped) {
  41762. for (var i = 0, l = nodes.length; i < l; i++) {
  41763. if (!nodes[i].fixed) {
  41764. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  41765. }
  41766. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  41767. }
  41768. for (var i = 0, l = edges.length; i < l; i++) {
  41769. var e = edges[i];
  41770. var edge = graph.getEdgeByIndex(i);
  41771. var p1 = e.n1.p;
  41772. var p2 = e.n2.p;
  41773. var points = edge.getLayout();
  41774. points = points ? points.slice() : [];
  41775. points[0] = points[0] || [];
  41776. points[1] = points[1] || [];
  41777. copy(points[0], p1);
  41778. copy(points[1], p2);
  41779. if (+e.curveness) {
  41780. points[2] = [
  41781. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  41782. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  41783. ];
  41784. }
  41785. edge.setLayout(points);
  41786. }
  41787. // Update layout
  41788. cb && cb(stopped);
  41789. });
  41790. };
  41791. graphSeries.forceLayout = forceInstance;
  41792. graphSeries.preservedPoints = preservedPoints;
  41793. // Step to get the layout
  41794. forceInstance.step();
  41795. }
  41796. else {
  41797. // Remove prev injected forceLayout instance
  41798. graphSeries.forceLayout = null;
  41799. }
  41800. });
  41801. };
  41802. // FIXME Where to create the simple view coordinate system
  41803. function getViewRect$1(seriesModel, api, aspect) {
  41804. var option = seriesModel.getBoxLayoutParams();
  41805. option.aspect = aspect;
  41806. return getLayoutRect(option, {
  41807. width: api.getWidth(),
  41808. height: api.getHeight()
  41809. });
  41810. }
  41811. var createView = function (ecModel, api) {
  41812. var viewList = [];
  41813. ecModel.eachSeriesByType('graph', function (seriesModel) {
  41814. var coordSysType = seriesModel.get('coordinateSystem');
  41815. if (!coordSysType || coordSysType === 'view') {
  41816. var data = seriesModel.getData();
  41817. var positions = data.mapArray(function (idx) {
  41818. var itemModel = data.getItemModel(idx);
  41819. return [+itemModel.get('x'), +itemModel.get('y')];
  41820. });
  41821. var min = [];
  41822. var max = [];
  41823. fromPoints(positions, min, max);
  41824. // If width or height is 0
  41825. if (max[0] - min[0] === 0) {
  41826. max[0] += 1;
  41827. min[0] -= 1;
  41828. }
  41829. if (max[1] - min[1] === 0) {
  41830. max[1] += 1;
  41831. min[1] -= 1;
  41832. }
  41833. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  41834. // FIXME If get view rect after data processed?
  41835. var viewRect = getViewRect$1(seriesModel, api, aspect);
  41836. // Position may be NaN, use view rect instead
  41837. if (isNaN(aspect)) {
  41838. min = [viewRect.x, viewRect.y];
  41839. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  41840. }
  41841. var bbWidth = max[0] - min[0];
  41842. var bbHeight = max[1] - min[1];
  41843. var viewWidth = viewRect.width;
  41844. var viewHeight = viewRect.height;
  41845. var viewCoordSys = seriesModel.coordinateSystem = new View();
  41846. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  41847. viewCoordSys.setBoundingRect(
  41848. min[0], min[1], bbWidth, bbHeight
  41849. );
  41850. viewCoordSys.setViewRect(
  41851. viewRect.x, viewRect.y, viewWidth, viewHeight
  41852. );
  41853. // Update roam info
  41854. viewCoordSys.setCenter(seriesModel.get('center'));
  41855. viewCoordSys.setZoom(seriesModel.get('zoom'));
  41856. viewList.push(viewCoordSys);
  41857. }
  41858. });
  41859. return viewList;
  41860. };
  41861. registerProcessor(categoryFilter);
  41862. registerVisual(visualSymbol('graph', 'circle', null));
  41863. registerVisual(categoryVisual);
  41864. registerVisual(edgeVisual);
  41865. registerLayout(simpleLayout);
  41866. registerLayout(circularLayout);
  41867. registerLayout(forceLayout);
  41868. // Graph view coordinate system
  41869. registerCoordinateSystem('graphView', {
  41870. create: createView
  41871. });
  41872. var GaugeSeries = SeriesModel.extend({
  41873. type: 'series.gauge',
  41874. getInitialData: function (option, ecModel) {
  41875. var dataOpt = option.data || [];
  41876. if (!isArray(dataOpt)) {
  41877. dataOpt = [dataOpt];
  41878. }
  41879. option.data = dataOpt;
  41880. return createListSimply(this, ['value']);
  41881. },
  41882. defaultOption: {
  41883. zlevel: 0,
  41884. z: 2,
  41885. // 默认全局居中
  41886. center: ['50%', '50%'],
  41887. legendHoverLink: true,
  41888. radius: '75%',
  41889. startAngle: 225,
  41890. endAngle: -45,
  41891. clockwise: true,
  41892. // 最小值
  41893. min: 0,
  41894. // 最大值
  41895. max: 100,
  41896. // 分割段数,默认为10
  41897. splitNumber: 10,
  41898. // 坐标轴线
  41899. axisLine: {
  41900. // 默认显示,属性show控制显示与否
  41901. show: true,
  41902. lineStyle: { // 属性lineStyle控制线条样式
  41903. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  41904. width: 30
  41905. }
  41906. },
  41907. // 分隔线
  41908. splitLine: {
  41909. // 默认显示,属性show控制显示与否
  41910. show: true,
  41911. // 属性length控制线长
  41912. length: 30,
  41913. // 属性lineStyle(详见lineStyle)控制线条样式
  41914. lineStyle: {
  41915. color: '#eee',
  41916. width: 2,
  41917. type: 'solid'
  41918. }
  41919. },
  41920. // 坐标轴小标记
  41921. axisTick: {
  41922. // 属性show控制显示与否,默认不显示
  41923. show: true,
  41924. // 每份split细分多少段
  41925. splitNumber: 5,
  41926. // 属性length控制线长
  41927. length: 8,
  41928. // 属性lineStyle控制线条样式
  41929. lineStyle: {
  41930. color: '#eee',
  41931. width: 1,
  41932. type: 'solid'
  41933. }
  41934. },
  41935. axisLabel: {
  41936. show: true,
  41937. distance: 5,
  41938. // formatter: null,
  41939. color: 'auto'
  41940. },
  41941. pointer: {
  41942. show: true,
  41943. length: '80%',
  41944. width: 8
  41945. },
  41946. itemStyle: {
  41947. color: 'auto'
  41948. },
  41949. title: {
  41950. show: true,
  41951. // x, y,单位px
  41952. offsetCenter: [0, '-40%'],
  41953. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  41954. color: '#333',
  41955. fontSize: 15
  41956. },
  41957. detail: {
  41958. show: true,
  41959. backgroundColor: 'rgba(0,0,0,0)',
  41960. borderWidth: 0,
  41961. borderColor: '#ccc',
  41962. width: 100,
  41963. height: null, // self-adaption
  41964. padding: [5, 10],
  41965. // x, y,单位px
  41966. offsetCenter: [0, '40%'],
  41967. // formatter: null,
  41968. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  41969. color: 'auto',
  41970. fontSize: 30
  41971. }
  41972. }
  41973. });
  41974. var PointerPath = Path.extend({
  41975. type: 'echartsGaugePointer',
  41976. shape: {
  41977. angle: 0,
  41978. width: 10,
  41979. r: 10,
  41980. x: 0,
  41981. y: 0
  41982. },
  41983. buildPath: function (ctx, shape) {
  41984. var mathCos = Math.cos;
  41985. var mathSin = Math.sin;
  41986. var r = shape.r;
  41987. var width = shape.width;
  41988. var angle = shape.angle;
  41989. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  41990. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  41991. angle = shape.angle - Math.PI / 2;
  41992. ctx.moveTo(x, y);
  41993. ctx.lineTo(
  41994. shape.x + mathCos(angle) * width,
  41995. shape.y + mathSin(angle) * width
  41996. );
  41997. ctx.lineTo(
  41998. shape.x + mathCos(shape.angle) * r,
  41999. shape.y + mathSin(shape.angle) * r
  42000. );
  42001. ctx.lineTo(
  42002. shape.x - mathCos(angle) * width,
  42003. shape.y - mathSin(angle) * width
  42004. );
  42005. ctx.lineTo(x, y);
  42006. return;
  42007. }
  42008. });
  42009. function parsePosition(seriesModel, api) {
  42010. var center = seriesModel.get('center');
  42011. var width = api.getWidth();
  42012. var height = api.getHeight();
  42013. var size = Math.min(width, height);
  42014. var cx = parsePercent$1(center[0], api.getWidth());
  42015. var cy = parsePercent$1(center[1], api.getHeight());
  42016. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  42017. return {
  42018. cx: cx,
  42019. cy: cy,
  42020. r: r
  42021. };
  42022. }
  42023. function formatLabel(label, labelFormatter) {
  42024. if (labelFormatter) {
  42025. if (typeof labelFormatter === 'string') {
  42026. label = labelFormatter.replace('{value}', label != null ? label : '');
  42027. }
  42028. else if (typeof labelFormatter === 'function') {
  42029. label = labelFormatter(label);
  42030. }
  42031. }
  42032. return label;
  42033. }
  42034. var PI2$5 = Math.PI * 2;
  42035. var GaugeView = Chart.extend({
  42036. type: 'gauge',
  42037. render: function (seriesModel, ecModel, api) {
  42038. this.group.removeAll();
  42039. var colorList = seriesModel.get('axisLine.lineStyle.color');
  42040. var posInfo = parsePosition(seriesModel, api);
  42041. this._renderMain(
  42042. seriesModel, ecModel, api, colorList, posInfo
  42043. );
  42044. },
  42045. dispose: function () {},
  42046. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  42047. var group = this.group;
  42048. var axisLineModel = seriesModel.getModel('axisLine');
  42049. var lineStyleModel = axisLineModel.getModel('lineStyle');
  42050. var clockwise = seriesModel.get('clockwise');
  42051. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  42052. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  42053. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  42054. var prevEndAngle = startAngle;
  42055. var axisLineWidth = lineStyleModel.get('width');
  42056. for (var i = 0; i < colorList.length; i++) {
  42057. // Clamp
  42058. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  42059. var endAngle = startAngle + angleRangeSpan * percent;
  42060. var sector = new Sector({
  42061. shape: {
  42062. startAngle: prevEndAngle,
  42063. endAngle: endAngle,
  42064. cx: posInfo.cx,
  42065. cy: posInfo.cy,
  42066. clockwise: clockwise,
  42067. r0: posInfo.r - axisLineWidth,
  42068. r: posInfo.r
  42069. },
  42070. silent: true
  42071. });
  42072. sector.setStyle({
  42073. fill: colorList[i][1]
  42074. });
  42075. sector.setStyle(lineStyleModel.getLineStyle(
  42076. // Because we use sector to simulate arc
  42077. // so the properties for stroking are useless
  42078. ['color', 'borderWidth', 'borderColor']
  42079. ));
  42080. group.add(sector);
  42081. prevEndAngle = endAngle;
  42082. }
  42083. var getColor = function (percent) {
  42084. // Less than 0
  42085. if (percent <= 0) {
  42086. return colorList[0][1];
  42087. }
  42088. for (var i = 0; i < colorList.length; i++) {
  42089. if (colorList[i][0] >= percent
  42090. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  42091. ) {
  42092. return colorList[i][1];
  42093. }
  42094. }
  42095. // More than 1
  42096. return colorList[i - 1][1];
  42097. };
  42098. if (!clockwise) {
  42099. var tmp = startAngle;
  42100. startAngle = endAngle;
  42101. endAngle = tmp;
  42102. }
  42103. this._renderTicks(
  42104. seriesModel, ecModel, api, getColor, posInfo,
  42105. startAngle, endAngle, clockwise
  42106. );
  42107. this._renderPointer(
  42108. seriesModel, ecModel, api, getColor, posInfo,
  42109. startAngle, endAngle, clockwise
  42110. );
  42111. this._renderTitle(
  42112. seriesModel, ecModel, api, getColor, posInfo
  42113. );
  42114. this._renderDetail(
  42115. seriesModel, ecModel, api, getColor, posInfo
  42116. );
  42117. },
  42118. _renderTicks: function (
  42119. seriesModel, ecModel, api, getColor, posInfo,
  42120. startAngle, endAngle, clockwise
  42121. ) {
  42122. var group = this.group;
  42123. var cx = posInfo.cx;
  42124. var cy = posInfo.cy;
  42125. var r = posInfo.r;
  42126. var minVal = +seriesModel.get('min');
  42127. var maxVal = +seriesModel.get('max');
  42128. var splitLineModel = seriesModel.getModel('splitLine');
  42129. var tickModel = seriesModel.getModel('axisTick');
  42130. var labelModel = seriesModel.getModel('axisLabel');
  42131. var splitNumber = seriesModel.get('splitNumber');
  42132. var subSplitNumber = tickModel.get('splitNumber');
  42133. var splitLineLen = parsePercent$1(
  42134. splitLineModel.get('length'), r
  42135. );
  42136. var tickLen = parsePercent$1(
  42137. tickModel.get('length'), r
  42138. );
  42139. var angle = startAngle;
  42140. var step = (endAngle - startAngle) / splitNumber;
  42141. var subStep = step / subSplitNumber;
  42142. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  42143. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  42144. for (var i = 0; i <= splitNumber; i++) {
  42145. var unitX = Math.cos(angle);
  42146. var unitY = Math.sin(angle);
  42147. // Split line
  42148. if (splitLineModel.get('show')) {
  42149. var splitLine = new Line({
  42150. shape: {
  42151. x1: unitX * r + cx,
  42152. y1: unitY * r + cy,
  42153. x2: unitX * (r - splitLineLen) + cx,
  42154. y2: unitY * (r - splitLineLen) + cy
  42155. },
  42156. style: splitLineStyle,
  42157. silent: true
  42158. });
  42159. if (splitLineStyle.stroke === 'auto') {
  42160. splitLine.setStyle({
  42161. stroke: getColor(i / splitNumber)
  42162. });
  42163. }
  42164. group.add(splitLine);
  42165. }
  42166. // Label
  42167. if (labelModel.get('show')) {
  42168. var label = formatLabel(
  42169. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  42170. labelModel.get('formatter')
  42171. );
  42172. var distance = labelModel.get('distance');
  42173. var autoColor = getColor(i / splitNumber);
  42174. group.add(new Text({
  42175. style: setTextStyle({}, labelModel, {
  42176. text: label,
  42177. x: unitX * (r - splitLineLen - distance) + cx,
  42178. y: unitY * (r - splitLineLen - distance) + cy,
  42179. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  42180. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  42181. }, {autoColor: autoColor}),
  42182. silent: true
  42183. }));
  42184. }
  42185. // Axis tick
  42186. if (tickModel.get('show') && i !== splitNumber) {
  42187. for (var j = 0; j <= subSplitNumber; j++) {
  42188. var unitX = Math.cos(angle);
  42189. var unitY = Math.sin(angle);
  42190. var tickLine = new Line({
  42191. shape: {
  42192. x1: unitX * r + cx,
  42193. y1: unitY * r + cy,
  42194. x2: unitX * (r - tickLen) + cx,
  42195. y2: unitY * (r - tickLen) + cy
  42196. },
  42197. silent: true,
  42198. style: tickLineStyle
  42199. });
  42200. if (tickLineStyle.stroke === 'auto') {
  42201. tickLine.setStyle({
  42202. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  42203. });
  42204. }
  42205. group.add(tickLine);
  42206. angle += subStep;
  42207. }
  42208. angle -= subStep;
  42209. }
  42210. else {
  42211. angle += step;
  42212. }
  42213. }
  42214. },
  42215. _renderPointer: function (
  42216. seriesModel, ecModel, api, getColor, posInfo,
  42217. startAngle, endAngle, clockwise
  42218. ) {
  42219. var group = this.group;
  42220. var oldData = this._data;
  42221. if (!seriesModel.get('pointer.show')) {
  42222. // Remove old element
  42223. oldData && oldData.eachItemGraphicEl(function (el) {
  42224. group.remove(el);
  42225. });
  42226. return;
  42227. }
  42228. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  42229. var angleExtent = [startAngle, endAngle];
  42230. var data = seriesModel.getData();
  42231. var valueDim = data.mapDimension('value');
  42232. data.diff(oldData)
  42233. .add(function (idx) {
  42234. var pointer = new PointerPath({
  42235. shape: {
  42236. angle: startAngle
  42237. }
  42238. });
  42239. initProps(pointer, {
  42240. shape: {
  42241. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  42242. }
  42243. }, seriesModel);
  42244. group.add(pointer);
  42245. data.setItemGraphicEl(idx, pointer);
  42246. })
  42247. .update(function (newIdx, oldIdx) {
  42248. var pointer = oldData.getItemGraphicEl(oldIdx);
  42249. updateProps(pointer, {
  42250. shape: {
  42251. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  42252. }
  42253. }, seriesModel);
  42254. group.add(pointer);
  42255. data.setItemGraphicEl(newIdx, pointer);
  42256. })
  42257. .remove(function (idx) {
  42258. var pointer = oldData.getItemGraphicEl(idx);
  42259. group.remove(pointer);
  42260. })
  42261. .execute();
  42262. data.eachItemGraphicEl(function (pointer, idx) {
  42263. var itemModel = data.getItemModel(idx);
  42264. var pointerModel = itemModel.getModel('pointer');
  42265. pointer.setShape({
  42266. x: posInfo.cx,
  42267. y: posInfo.cy,
  42268. width: parsePercent$1(
  42269. pointerModel.get('width'), posInfo.r
  42270. ),
  42271. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  42272. });
  42273. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  42274. if (pointer.style.fill === 'auto') {
  42275. pointer.setStyle('fill', getColor(
  42276. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  42277. ));
  42278. }
  42279. setHoverStyle(
  42280. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  42281. );
  42282. });
  42283. this._data = data;
  42284. },
  42285. _renderTitle: function (
  42286. seriesModel, ecModel, api, getColor, posInfo
  42287. ) {
  42288. var data = seriesModel.getData();
  42289. var valueDim = data.mapDimension('value');
  42290. var titleModel = seriesModel.getModel('title');
  42291. if (titleModel.get('show')) {
  42292. var offsetCenter = titleModel.get('offsetCenter');
  42293. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  42294. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  42295. var minVal = +seriesModel.get('min');
  42296. var maxVal = +seriesModel.get('max');
  42297. var value = seriesModel.getData().get(valueDim, 0);
  42298. var autoColor = getColor(
  42299. linearMap(value, [minVal, maxVal], [0, 1], true)
  42300. );
  42301. this.group.add(new Text({
  42302. silent: true,
  42303. style: setTextStyle({}, titleModel, {
  42304. x: x,
  42305. y: y,
  42306. // FIXME First data name ?
  42307. text: data.getName(0),
  42308. textAlign: 'center',
  42309. textVerticalAlign: 'middle'
  42310. }, {autoColor: autoColor, forceRich: true})
  42311. }));
  42312. }
  42313. },
  42314. _renderDetail: function (
  42315. seriesModel, ecModel, api, getColor, posInfo
  42316. ) {
  42317. var detailModel = seriesModel.getModel('detail');
  42318. var minVal = +seriesModel.get('min');
  42319. var maxVal = +seriesModel.get('max');
  42320. if (detailModel.get('show')) {
  42321. var offsetCenter = detailModel.get('offsetCenter');
  42322. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  42323. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  42324. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  42325. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  42326. var data = seriesModel.getData();
  42327. var value = data.get(data.mapDimension('value'), 0);
  42328. var autoColor = getColor(
  42329. linearMap(value, [minVal, maxVal], [0, 1], true)
  42330. );
  42331. this.group.add(new Text({
  42332. silent: true,
  42333. style: setTextStyle({}, detailModel, {
  42334. x: x,
  42335. y: y,
  42336. text: formatLabel(
  42337. // FIXME First data name ?
  42338. value, detailModel.get('formatter')
  42339. ),
  42340. textWidth: isNaN(width) ? null : width,
  42341. textHeight: isNaN(height) ? null : height,
  42342. textAlign: 'center',
  42343. textVerticalAlign: 'middle'
  42344. }, {autoColor: autoColor, forceRich: true})
  42345. }));
  42346. }
  42347. }
  42348. });
  42349. var FunnelSeries = extendSeriesModel({
  42350. type: 'series.funnel',
  42351. init: function (option) {
  42352. FunnelSeries.superApply(this, 'init', arguments);
  42353. // Enable legend selection for each data item
  42354. // Use a function instead of direct access because data reference may changed
  42355. this.legendDataProvider = function () {
  42356. return this.getRawData();
  42357. };
  42358. // Extend labelLine emphasis
  42359. this._defaultLabelLine(option);
  42360. },
  42361. getInitialData: function (option, ecModel) {
  42362. return createListSimply(this, ['value']);
  42363. },
  42364. _defaultLabelLine: function (option) {
  42365. // Extend labelLine emphasis
  42366. defaultEmphasis(option, 'labelLine', ['show']);
  42367. var labelLineNormalOpt = option.labelLine;
  42368. var labelLineEmphasisOpt = option.emphasis.labelLine;
  42369. // Not show label line if `label.normal.show = false`
  42370. labelLineNormalOpt.show = labelLineNormalOpt.show
  42371. && option.label.show;
  42372. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  42373. && option.emphasis.label.show;
  42374. },
  42375. // Overwrite
  42376. getDataParams: function (dataIndex) {
  42377. var data = this.getData();
  42378. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  42379. var valueDim = data.mapDimension('value');
  42380. var sum = data.getSum(valueDim);
  42381. // Percent is 0 if sum is 0
  42382. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  42383. params.$vars.push('percent');
  42384. return params;
  42385. },
  42386. defaultOption: {
  42387. zlevel: 0, // 一级层叠
  42388. z: 2, // 二级层叠
  42389. legendHoverLink: true,
  42390. left: 80,
  42391. top: 60,
  42392. right: 80,
  42393. bottom: 60,
  42394. // width: {totalWidth} - left - right,
  42395. // height: {totalHeight} - top - bottom,
  42396. // 默认取数据最小最大值
  42397. // min: 0,
  42398. // max: 100,
  42399. minSize: '0%',
  42400. maxSize: '100%',
  42401. sort: 'descending', // 'ascending', 'descending'
  42402. gap: 0,
  42403. funnelAlign: 'center',
  42404. label: {
  42405. show: true,
  42406. position: 'outer'
  42407. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  42408. },
  42409. labelLine: {
  42410. show: true,
  42411. length: 20,
  42412. lineStyle: {
  42413. // color: 各异,
  42414. width: 1,
  42415. type: 'solid'
  42416. }
  42417. },
  42418. itemStyle: {
  42419. // color: 各异,
  42420. borderColor: '#fff',
  42421. borderWidth: 1
  42422. },
  42423. emphasis: {
  42424. label: {
  42425. show: true
  42426. }
  42427. }
  42428. }
  42429. });
  42430. /**
  42431. * Piece of pie including Sector, Label, LabelLine
  42432. * @constructor
  42433. * @extends {module:zrender/graphic/Group}
  42434. */
  42435. function FunnelPiece(data, idx) {
  42436. Group.call(this);
  42437. var polygon = new Polygon();
  42438. var labelLine = new Polyline();
  42439. var text = new Text();
  42440. this.add(polygon);
  42441. this.add(labelLine);
  42442. this.add(text);
  42443. this.updateData(data, idx, true);
  42444. // Hover to change label and labelLine
  42445. function onEmphasis() {
  42446. labelLine.ignore = labelLine.hoverIgnore;
  42447. text.ignore = text.hoverIgnore;
  42448. }
  42449. function onNormal() {
  42450. labelLine.ignore = labelLine.normalIgnore;
  42451. text.ignore = text.normalIgnore;
  42452. }
  42453. this.on('emphasis', onEmphasis)
  42454. .on('normal', onNormal)
  42455. .on('mouseover', onEmphasis)
  42456. .on('mouseout', onNormal);
  42457. }
  42458. var funnelPieceProto = FunnelPiece.prototype;
  42459. var opacityAccessPath = ['itemStyle', 'opacity'];
  42460. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  42461. var polygon = this.childAt(0);
  42462. var seriesModel = data.hostModel;
  42463. var itemModel = data.getItemModel(idx);
  42464. var layout = data.getItemLayout(idx);
  42465. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  42466. opacity = opacity == null ? 1 : opacity;
  42467. // Reset style
  42468. polygon.useStyle({});
  42469. if (firstCreate) {
  42470. polygon.setShape({
  42471. points: layout.points
  42472. });
  42473. polygon.setStyle({ opacity : 0 });
  42474. initProps(polygon, {
  42475. style: {
  42476. opacity: opacity
  42477. }
  42478. }, seriesModel, idx);
  42479. }
  42480. else {
  42481. updateProps(polygon, {
  42482. style: {
  42483. opacity: opacity
  42484. },
  42485. shape: {
  42486. points: layout.points
  42487. }
  42488. }, seriesModel, idx);
  42489. }
  42490. // Update common style
  42491. var itemStyleModel = itemModel.getModel('itemStyle');
  42492. var visualColor = data.getItemVisual(idx, 'color');
  42493. polygon.setStyle(
  42494. defaults(
  42495. {
  42496. lineJoin: 'round',
  42497. fill: visualColor
  42498. },
  42499. itemStyleModel.getItemStyle(['opacity'])
  42500. )
  42501. );
  42502. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  42503. this._updateLabel(data, idx);
  42504. setHoverStyle(this);
  42505. };
  42506. funnelPieceProto._updateLabel = function (data, idx) {
  42507. var labelLine = this.childAt(1);
  42508. var labelText = this.childAt(2);
  42509. var seriesModel = data.hostModel;
  42510. var itemModel = data.getItemModel(idx);
  42511. var layout = data.getItemLayout(idx);
  42512. var labelLayout = layout.label;
  42513. var visualColor = data.getItemVisual(idx, 'color');
  42514. updateProps(labelLine, {
  42515. shape: {
  42516. points: labelLayout.linePoints || labelLayout.linePoints
  42517. }
  42518. }, seriesModel, idx);
  42519. updateProps(labelText, {
  42520. style: {
  42521. x: labelLayout.x,
  42522. y: labelLayout.y
  42523. }
  42524. }, seriesModel, idx);
  42525. labelText.attr({
  42526. rotation: labelLayout.rotation,
  42527. origin: [labelLayout.x, labelLayout.y],
  42528. z2: 10
  42529. });
  42530. var labelModel = itemModel.getModel('label');
  42531. var labelHoverModel = itemModel.getModel('emphasis.label');
  42532. var labelLineModel = itemModel.getModel('labelLine');
  42533. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  42534. var visualColor = data.getItemVisual(idx, 'color');
  42535. setLabelStyle(
  42536. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  42537. {
  42538. labelFetcher: data.hostModel,
  42539. labelDataIndex: idx,
  42540. defaultText: data.getName(idx),
  42541. autoColor: visualColor,
  42542. useInsideStyle: !!labelLayout.inside
  42543. },
  42544. {
  42545. textAlign: labelLayout.textAlign,
  42546. textVerticalAlign: labelLayout.verticalAlign
  42547. }
  42548. );
  42549. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  42550. labelText.hoverIgnore = !labelHoverModel.get('show');
  42551. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  42552. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  42553. // Default use item visual color
  42554. labelLine.setStyle({
  42555. stroke: visualColor
  42556. });
  42557. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  42558. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  42559. };
  42560. inherits(FunnelPiece, Group);
  42561. var FunnelView = Chart.extend({
  42562. type: 'funnel',
  42563. render: function (seriesModel, ecModel, api) {
  42564. var data = seriesModel.getData();
  42565. var oldData = this._data;
  42566. var group = this.group;
  42567. data.diff(oldData)
  42568. .add(function (idx) {
  42569. var funnelPiece = new FunnelPiece(data, idx);
  42570. data.setItemGraphicEl(idx, funnelPiece);
  42571. group.add(funnelPiece);
  42572. })
  42573. .update(function (newIdx, oldIdx) {
  42574. var piePiece = oldData.getItemGraphicEl(oldIdx);
  42575. piePiece.updateData(data, newIdx);
  42576. group.add(piePiece);
  42577. data.setItemGraphicEl(newIdx, piePiece);
  42578. })
  42579. .remove(function (idx) {
  42580. var piePiece = oldData.getItemGraphicEl(idx);
  42581. group.remove(piePiece);
  42582. })
  42583. .execute();
  42584. this._data = data;
  42585. },
  42586. remove: function () {
  42587. this.group.removeAll();
  42588. this._data = null;
  42589. },
  42590. dispose: function () {}
  42591. });
  42592. function getViewRect$2(seriesModel, api) {
  42593. return getLayoutRect(
  42594. seriesModel.getBoxLayoutParams(), {
  42595. width: api.getWidth(),
  42596. height: api.getHeight()
  42597. }
  42598. );
  42599. }
  42600. function getSortedIndices(data, sort) {
  42601. var valueDim = data.mapDimension('value');
  42602. var valueArr = data.mapArray(valueDim, function (val) {
  42603. return val;
  42604. });
  42605. var indices = [];
  42606. var isAscending = sort === 'ascending';
  42607. for (var i = 0, len = data.count(); i < len; i++) {
  42608. indices[i] = i;
  42609. }
  42610. // Add custom sortable function & none sortable opetion by "options.sort"
  42611. if (typeof sort === 'function') {
  42612. indices.sort(sort);
  42613. } else if (sort !== 'none') {
  42614. indices.sort(function (a, b) {
  42615. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  42616. });
  42617. }
  42618. return indices;
  42619. }
  42620. function labelLayout$1(data) {
  42621. data.each(function (idx) {
  42622. var itemModel = data.getItemModel(idx);
  42623. var labelModel = itemModel.getModel('label');
  42624. var labelPosition = labelModel.get('position');
  42625. var labelLineModel = itemModel.getModel('labelLine');
  42626. var layout = data.getItemLayout(idx);
  42627. var points = layout.points;
  42628. var isLabelInside = labelPosition === 'inner'
  42629. || labelPosition === 'inside' || labelPosition === 'center';
  42630. var textAlign;
  42631. var textX;
  42632. var textY;
  42633. var linePoints;
  42634. if (isLabelInside) {
  42635. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  42636. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  42637. textAlign = 'center';
  42638. linePoints = [
  42639. [textX, textY], [textX, textY]
  42640. ];
  42641. }
  42642. else {
  42643. var x1;
  42644. var y1;
  42645. var x2;
  42646. var labelLineLen = labelLineModel.get('length');
  42647. if (labelPosition === 'left') {
  42648. // Left side
  42649. x1 = (points[3][0] + points[0][0]) / 2;
  42650. y1 = (points[3][1] + points[0][1]) / 2;
  42651. x2 = x1 - labelLineLen;
  42652. textX = x2 - 5;
  42653. textAlign = 'right';
  42654. }
  42655. else {
  42656. // Right side
  42657. x1 = (points[1][0] + points[2][0]) / 2;
  42658. y1 = (points[1][1] + points[2][1]) / 2;
  42659. x2 = x1 + labelLineLen;
  42660. textX = x2 + 5;
  42661. textAlign = 'left';
  42662. }
  42663. var y2 = y1;
  42664. linePoints = [[x1, y1], [x2, y2]];
  42665. textY = y2;
  42666. }
  42667. layout.label = {
  42668. linePoints: linePoints,
  42669. x: textX,
  42670. y: textY,
  42671. verticalAlign: 'middle',
  42672. textAlign: textAlign,
  42673. inside: isLabelInside
  42674. };
  42675. });
  42676. }
  42677. var funnelLayout = function (ecModel, api, payload) {
  42678. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  42679. var data = seriesModel.getData();
  42680. var valueDim = data.mapDimension('value');
  42681. var sort = seriesModel.get('sort');
  42682. var viewRect = getViewRect$2(seriesModel, api);
  42683. var indices = getSortedIndices(data, sort);
  42684. var sizeExtent = [
  42685. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  42686. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  42687. ];
  42688. var dataExtent = data.getDataExtent(valueDim);
  42689. var min = seriesModel.get('min');
  42690. var max = seriesModel.get('max');
  42691. if (min == null) {
  42692. min = Math.min(dataExtent[0], 0);
  42693. }
  42694. if (max == null) {
  42695. max = dataExtent[1];
  42696. }
  42697. var funnelAlign = seriesModel.get('funnelAlign');
  42698. var gap = seriesModel.get('gap');
  42699. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  42700. var y = viewRect.y;
  42701. var getLinePoints = function (idx, offY) {
  42702. // End point index is data.count() and we assign it 0
  42703. var val = data.get(valueDim, idx) || 0;
  42704. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  42705. var x0;
  42706. switch (funnelAlign) {
  42707. case 'left':
  42708. x0 = viewRect.x;
  42709. break;
  42710. case 'center':
  42711. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  42712. break;
  42713. case 'right':
  42714. x0 = viewRect.x + viewRect.width - itemWidth;
  42715. break;
  42716. }
  42717. return [
  42718. [x0, offY],
  42719. [x0 + itemWidth, offY]
  42720. ];
  42721. };
  42722. if (sort === 'ascending') {
  42723. // From bottom to top
  42724. itemHeight = -itemHeight;
  42725. gap = -gap;
  42726. y += viewRect.height;
  42727. indices = indices.reverse();
  42728. }
  42729. for (var i = 0; i < indices.length; i++) {
  42730. var idx = indices[i];
  42731. var nextIdx = indices[i + 1];
  42732. var itemModel = data.getItemModel(idx);
  42733. var height = itemModel.get('itemStyle.height');
  42734. if (height == null) {
  42735. height = itemHeight;
  42736. }
  42737. else {
  42738. height = parsePercent$1(height, viewRect.height);
  42739. if (sort === 'ascending') {
  42740. height = -height;
  42741. }
  42742. }
  42743. var start = getLinePoints(idx, y);
  42744. var end = getLinePoints(nextIdx, y + height);
  42745. y += height + gap;
  42746. data.setItemLayout(idx, {
  42747. points: start.concat(end.slice().reverse())
  42748. });
  42749. }
  42750. labelLayout$1(data);
  42751. });
  42752. };
  42753. registerVisual(dataColor('funnel'));
  42754. registerLayout(funnelLayout);
  42755. registerProcessor(dataFilter('funnel'));
  42756. var parallelPreprocessor = function (option) {
  42757. createParallelIfNeeded(option);
  42758. mergeAxisOptionFromParallel(option);
  42759. };
  42760. /**
  42761. * Create a parallel coordinate if not exists.
  42762. * @inner
  42763. */
  42764. function createParallelIfNeeded(option) {
  42765. if (option.parallel) {
  42766. return;
  42767. }
  42768. var hasParallelSeries = false;
  42769. each$1(option.series, function (seriesOpt) {
  42770. if (seriesOpt && seriesOpt.type === 'parallel') {
  42771. hasParallelSeries = true;
  42772. }
  42773. });
  42774. if (hasParallelSeries) {
  42775. option.parallel = [{}];
  42776. }
  42777. }
  42778. /**
  42779. * Merge aixs definition from parallel option (if exists) to axis option.
  42780. * @inner
  42781. */
  42782. function mergeAxisOptionFromParallel(option) {
  42783. var axes = normalizeToArray(option.parallelAxis);
  42784. each$1(axes, function (axisOption) {
  42785. if (!isObject$1(axisOption)) {
  42786. return;
  42787. }
  42788. var parallelIndex = axisOption.parallelIndex || 0;
  42789. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  42790. if (parallelOption && parallelOption.parallelAxisDefault) {
  42791. merge(axisOption, parallelOption.parallelAxisDefault, false);
  42792. }
  42793. });
  42794. }
  42795. /**
  42796. * @constructor module:echarts/coord/parallel/ParallelAxis
  42797. * @extends {module:echarts/coord/Axis}
  42798. * @param {string} dim
  42799. * @param {*} scale
  42800. * @param {Array.<number>} coordExtent
  42801. * @param {string} axisType
  42802. */
  42803. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  42804. Axis.call(this, dim, scale, coordExtent);
  42805. /**
  42806. * Axis type
  42807. * - 'category'
  42808. * - 'value'
  42809. * - 'time'
  42810. * - 'log'
  42811. * @type {string}
  42812. */
  42813. this.type = axisType || 'value';
  42814. /**
  42815. * @type {number}
  42816. * @readOnly
  42817. */
  42818. this.axisIndex = axisIndex;
  42819. };
  42820. ParallelAxis.prototype = {
  42821. constructor: ParallelAxis,
  42822. /**
  42823. * Axis model
  42824. * @param {module:echarts/coord/parallel/AxisModel}
  42825. */
  42826. model: null,
  42827. /**
  42828. * @override
  42829. */
  42830. isHorizontal: function () {
  42831. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  42832. }
  42833. };
  42834. inherits(ParallelAxis, Axis);
  42835. /**
  42836. * Calculate slider move result.
  42837. * Usage:
  42838. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  42839. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  42840. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  42841. *
  42842. * @param {number} delta Move length.
  42843. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  42844. * handleEnds will be modified in this method.
  42845. * @param {Array.<number>} extent handleEnds is restricted by extent.
  42846. * extent[0] should less or equals than extent[1].
  42847. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  42848. * where the input minSpan and maxSpan will not work.
  42849. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  42850. * If not set, handle0 and cross handle1. If set as a non-negative
  42851. * number (including `0`), handles will push each other when reaching
  42852. * the minSpan.
  42853. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  42854. * @return {Array.<number>} The input handleEnds.
  42855. */
  42856. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  42857. // Normalize firstly.
  42858. handleEnds[0] = restrict$1(handleEnds[0], extent);
  42859. handleEnds[1] = restrict$1(handleEnds[1], extent);
  42860. delta = delta || 0;
  42861. var extentSpan = extent[1] - extent[0];
  42862. // Notice maxSpan and minSpan can be null/undefined.
  42863. if (minSpan != null) {
  42864. minSpan = restrict$1(minSpan, [0, extentSpan]);
  42865. }
  42866. if (maxSpan != null) {
  42867. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  42868. }
  42869. if (handleIndex === 'all') {
  42870. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  42871. handleIndex = 0;
  42872. }
  42873. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  42874. handleEnds[handleIndex] += delta;
  42875. // Restrict in extent.
  42876. var extentMinSpan = minSpan || 0;
  42877. var realExtent = extent.slice();
  42878. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  42879. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  42880. // Expand span.
  42881. var currDistSign = getSpanSign(handleEnds, handleIndex);
  42882. if (minSpan != null && (
  42883. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  42884. )) {
  42885. // If minSpan exists, 'cross' is forbinden.
  42886. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  42887. }
  42888. // Shrink span.
  42889. var currDistSign = getSpanSign(handleEnds, handleIndex);
  42890. if (maxSpan != null && currDistSign.span > maxSpan) {
  42891. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  42892. }
  42893. return handleEnds;
  42894. };
  42895. function getSpanSign(handleEnds, handleIndex) {
  42896. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  42897. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  42898. // is at left of handleEnds[1] for non-cross case.
  42899. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  42900. }
  42901. function restrict$1(value, extend) {
  42902. return Math.min(extend[1], Math.max(extend[0], value));
  42903. }
  42904. /**
  42905. * Parallel Coordinates
  42906. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  42907. */
  42908. var each$12 = each$1;
  42909. var mathMin$5 = Math.min;
  42910. var mathMax$5 = Math.max;
  42911. var mathFloor$2 = Math.floor;
  42912. var mathCeil$2 = Math.ceil;
  42913. var round$2 = round$1;
  42914. var PI$3 = Math.PI;
  42915. function Parallel(parallelModel, ecModel, api) {
  42916. /**
  42917. * key: dimension
  42918. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  42919. * @private
  42920. */
  42921. this._axesMap = createHashMap();
  42922. /**
  42923. * key: dimension
  42924. * value: {position: [], rotation, }
  42925. * @type {Object.<string, Object>}
  42926. * @private
  42927. */
  42928. this._axesLayout = {};
  42929. /**
  42930. * Always follow axis order.
  42931. * @type {Array.<string>}
  42932. * @readOnly
  42933. */
  42934. this.dimensions = parallelModel.dimensions;
  42935. /**
  42936. * @type {module:zrender/core/BoundingRect}
  42937. */
  42938. this._rect;
  42939. /**
  42940. * @type {module:echarts/coord/parallel/ParallelModel}
  42941. */
  42942. this._model = parallelModel;
  42943. this._init(parallelModel, ecModel, api);
  42944. }
  42945. Parallel.prototype = {
  42946. type: 'parallel',
  42947. constructor: Parallel,
  42948. /**
  42949. * Initialize cartesian coordinate systems
  42950. * @private
  42951. */
  42952. _init: function (parallelModel, ecModel, api) {
  42953. var dimensions = parallelModel.dimensions;
  42954. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  42955. each$12(dimensions, function (dim, idx) {
  42956. var axisIndex = parallelAxisIndex[idx];
  42957. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  42958. var axis = this._axesMap.set(dim, new ParallelAxis(
  42959. dim,
  42960. createScaleByModel(axisModel),
  42961. [0, 0],
  42962. axisModel.get('type'),
  42963. axisIndex
  42964. ));
  42965. var isCategory = axis.type === 'category';
  42966. axis.onBand = isCategory && axisModel.get('boundaryGap');
  42967. axis.inverse = axisModel.get('inverse');
  42968. // Injection
  42969. axisModel.axis = axis;
  42970. axis.model = axisModel;
  42971. axis.coordinateSystem = axisModel.coordinateSystem = this;
  42972. }, this);
  42973. },
  42974. /**
  42975. * Update axis scale after data processed
  42976. * @param {module:echarts/model/Global} ecModel
  42977. * @param {module:echarts/ExtensionAPI} api
  42978. */
  42979. update: function (ecModel, api) {
  42980. this._updateAxesFromSeries(this._model, ecModel);
  42981. },
  42982. /**
  42983. * @override
  42984. */
  42985. containPoint: function (point) {
  42986. var layoutInfo = this._makeLayoutInfo();
  42987. var axisBase = layoutInfo.axisBase;
  42988. var layoutBase = layoutInfo.layoutBase;
  42989. var pixelDimIndex = layoutInfo.pixelDimIndex;
  42990. var pAxis = point[1 - pixelDimIndex];
  42991. var pLayout = point[pixelDimIndex];
  42992. return pAxis >= axisBase
  42993. && pAxis <= axisBase + layoutInfo.axisLength
  42994. && pLayout >= layoutBase
  42995. && pLayout <= layoutBase + layoutInfo.layoutLength;
  42996. },
  42997. getModel: function () {
  42998. return this._model;
  42999. },
  43000. /**
  43001. * Update properties from series
  43002. * @private
  43003. */
  43004. _updateAxesFromSeries: function (parallelModel, ecModel) {
  43005. ecModel.eachSeries(function (seriesModel) {
  43006. if (!parallelModel.contains(seriesModel, ecModel)) {
  43007. return;
  43008. }
  43009. var data = seriesModel.getData();
  43010. each$12(this.dimensions, function (dim) {
  43011. var axis = this._axesMap.get(dim);
  43012. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  43013. niceScaleExtent(axis.scale, axis.model);
  43014. }, this);
  43015. }, this);
  43016. },
  43017. /**
  43018. * Resize the parallel coordinate system.
  43019. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  43020. * @param {module:echarts/ExtensionAPI} api
  43021. */
  43022. resize: function (parallelModel, api) {
  43023. this._rect = getLayoutRect(
  43024. parallelModel.getBoxLayoutParams(),
  43025. {
  43026. width: api.getWidth(),
  43027. height: api.getHeight()
  43028. }
  43029. );
  43030. this._layoutAxes();
  43031. },
  43032. /**
  43033. * @return {module:zrender/core/BoundingRect}
  43034. */
  43035. getRect: function () {
  43036. return this._rect;
  43037. },
  43038. /**
  43039. * @private
  43040. */
  43041. _makeLayoutInfo: function () {
  43042. var parallelModel = this._model;
  43043. var rect = this._rect;
  43044. var xy = ['x', 'y'];
  43045. var wh = ['width', 'height'];
  43046. var layout = parallelModel.get('layout');
  43047. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  43048. var layoutLength = rect[wh[pixelDimIndex]];
  43049. var layoutExtent = [0, layoutLength];
  43050. var axisCount = this.dimensions.length;
  43051. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  43052. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  43053. var axisExpandable = parallelModel.get('axisExpandable')
  43054. && axisCount > 3
  43055. && axisCount > axisExpandCount
  43056. && axisExpandCount > 1
  43057. && axisExpandWidth > 0
  43058. && layoutLength > 0;
  43059. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  43060. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  43061. // where collapsed axes should be overlapped.
  43062. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  43063. var winSize;
  43064. if (!axisExpandWindow) {
  43065. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  43066. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  43067. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  43068. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  43069. }
  43070. else {
  43071. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  43072. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  43073. }
  43074. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  43075. // Avoid axisCollapseWidth is too small.
  43076. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  43077. // Find the first and last indices > ewin[0] and < ewin[1].
  43078. var winInnerIndices = [
  43079. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  43080. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  43081. ];
  43082. // Pos in ec coordinates.
  43083. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  43084. return {
  43085. layout: layout,
  43086. pixelDimIndex: pixelDimIndex,
  43087. layoutBase: rect[xy[pixelDimIndex]],
  43088. layoutLength: layoutLength,
  43089. axisBase: rect[xy[1 - pixelDimIndex]],
  43090. axisLength: rect[wh[1 - pixelDimIndex]],
  43091. axisExpandable: axisExpandable,
  43092. axisExpandWidth: axisExpandWidth,
  43093. axisCollapseWidth: axisCollapseWidth,
  43094. axisExpandWindow: axisExpandWindow,
  43095. axisCount: axisCount,
  43096. winInnerIndices: winInnerIndices,
  43097. axisExpandWindow0Pos: axisExpandWindow0Pos
  43098. };
  43099. },
  43100. /**
  43101. * @private
  43102. */
  43103. _layoutAxes: function () {
  43104. var rect = this._rect;
  43105. var axes = this._axesMap;
  43106. var dimensions = this.dimensions;
  43107. var layoutInfo = this._makeLayoutInfo();
  43108. var layout = layoutInfo.layout;
  43109. axes.each(function (axis) {
  43110. var axisExtent = [0, layoutInfo.axisLength];
  43111. var idx = axis.inverse ? 1 : 0;
  43112. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  43113. });
  43114. each$12(dimensions, function (dim, idx) {
  43115. var posInfo = (layoutInfo.axisExpandable
  43116. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  43117. )(idx, layoutInfo);
  43118. var positionTable = {
  43119. horizontal: {
  43120. x: posInfo.position,
  43121. y: layoutInfo.axisLength
  43122. },
  43123. vertical: {
  43124. x: 0,
  43125. y: posInfo.position
  43126. }
  43127. };
  43128. var rotationTable = {
  43129. horizontal: PI$3 / 2,
  43130. vertical: 0
  43131. };
  43132. var position = [
  43133. positionTable[layout].x + rect.x,
  43134. positionTable[layout].y + rect.y
  43135. ];
  43136. var rotation = rotationTable[layout];
  43137. var transform = create$1();
  43138. rotate(transform, transform, rotation);
  43139. translate(transform, transform, position);
  43140. // TODO
  43141. // tick等排布信息。
  43142. // TODO
  43143. // 根据axis order 更新 dimensions顺序。
  43144. this._axesLayout[dim] = {
  43145. position: position,
  43146. rotation: rotation,
  43147. transform: transform,
  43148. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  43149. axisLabelShow: posInfo.axisLabelShow,
  43150. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  43151. tickDirection: 1,
  43152. labelDirection: 1,
  43153. labelInterval: axes.get(dim).getLabelInterval()
  43154. };
  43155. }, this);
  43156. },
  43157. /**
  43158. * Get axis by dim.
  43159. * @param {string} dim
  43160. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  43161. */
  43162. getAxis: function (dim) {
  43163. return this._axesMap.get(dim);
  43164. },
  43165. /**
  43166. * Convert a dim value of a single item of series data to Point.
  43167. * @param {*} value
  43168. * @param {string} dim
  43169. * @return {Array}
  43170. */
  43171. dataToPoint: function (value, dim) {
  43172. return this.axisCoordToPoint(
  43173. this._axesMap.get(dim).dataToCoord(value),
  43174. dim
  43175. );
  43176. },
  43177. /**
  43178. * Travel data for one time, get activeState of each data item.
  43179. * @param {module:echarts/data/List} data
  43180. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  43181. * {number} dataIndex
  43182. * @param {Object} context
  43183. */
  43184. eachActiveState: function (data, callback, context) {
  43185. var dimensions = this.dimensions;
  43186. var dataDimensions = map(dimensions, function (axisDim) {
  43187. return data.mapDimension(axisDim);
  43188. });
  43189. var axesMap = this._axesMap;
  43190. var hasActiveSet = this.hasAxisBrushed();
  43191. for (var i = 0, len = data.count(); i < len; i++) {
  43192. var values = data.getValues(dataDimensions, i);
  43193. var activeState;
  43194. if (!hasActiveSet) {
  43195. activeState = 'normal';
  43196. }
  43197. else {
  43198. activeState = 'active';
  43199. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  43200. var dimName = dimensions[j];
  43201. var state = axesMap.get(dimName).model.getActiveState(values[j], j);
  43202. if (state === 'inactive') {
  43203. activeState = 'inactive';
  43204. break;
  43205. }
  43206. }
  43207. }
  43208. callback.call(context, activeState, i);
  43209. }
  43210. },
  43211. /**
  43212. * Whether has any activeSet.
  43213. * @return {boolean}
  43214. */
  43215. hasAxisBrushed: function () {
  43216. var dimensions = this.dimensions;
  43217. var axesMap = this._axesMap;
  43218. var hasActiveSet = false;
  43219. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  43220. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  43221. hasActiveSet = true;
  43222. }
  43223. }
  43224. return hasActiveSet;
  43225. },
  43226. /**
  43227. * Convert coords of each axis to Point.
  43228. * Return point. For example: [10, 20]
  43229. * @param {Array.<number>} coords
  43230. * @param {string} dim
  43231. * @return {Array.<number>}
  43232. */
  43233. axisCoordToPoint: function (coord, dim) {
  43234. var axisLayout = this._axesLayout[dim];
  43235. return applyTransform$1([coord, 0], axisLayout.transform);
  43236. },
  43237. /**
  43238. * Get axis layout.
  43239. */
  43240. getAxisLayout: function (dim) {
  43241. return clone(this._axesLayout[dim]);
  43242. },
  43243. /**
  43244. * @param {Array.<number>} point
  43245. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  43246. */
  43247. getSlidedAxisExpandWindow: function (point) {
  43248. var layoutInfo = this._makeLayoutInfo();
  43249. var pixelDimIndex = layoutInfo.pixelDimIndex;
  43250. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  43251. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  43252. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  43253. // Out of the area of coordinate system.
  43254. if (!this.containPoint(point)) {
  43255. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  43256. }
  43257. // Conver the point from global to expand coordinates.
  43258. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  43259. // For dragging operation convenience, the window should not be
  43260. // slided when mouse is the center area of the window.
  43261. var delta;
  43262. var behavior = 'slide';
  43263. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  43264. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  43265. // But consider touch device, jump is necessary.
  43266. var useJump = triggerArea[0] != null;
  43267. if (axisCollapseWidth) {
  43268. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  43269. behavior = 'jump';
  43270. delta = pointCoord - winSize * triggerArea[2];
  43271. }
  43272. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  43273. behavior = 'jump';
  43274. delta = pointCoord - winSize * (1 - triggerArea[2]);
  43275. }
  43276. else {
  43277. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  43278. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  43279. && (delta = 0);
  43280. }
  43281. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  43282. delta
  43283. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  43284. // Avoid nonsense triger on mousemove.
  43285. : (behavior = 'none');
  43286. }
  43287. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  43288. else {
  43289. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  43290. var pos = extent[1] * pointCoord / winSize;
  43291. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  43292. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  43293. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  43294. }
  43295. return {
  43296. axisExpandWindow: axisExpandWindow,
  43297. behavior: behavior
  43298. };
  43299. }
  43300. };
  43301. function restrict(len, extent) {
  43302. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  43303. }
  43304. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  43305. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  43306. return {
  43307. position: step * axisIndex,
  43308. axisNameAvailableWidth: step,
  43309. axisLabelShow: true
  43310. };
  43311. }
  43312. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  43313. var layoutLength = layoutInfo.layoutLength;
  43314. var axisExpandWidth = layoutInfo.axisExpandWidth;
  43315. var axisCount = layoutInfo.axisCount;
  43316. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  43317. var winInnerIndices = layoutInfo.winInnerIndices;
  43318. var position;
  43319. var axisNameAvailableWidth = axisCollapseWidth;
  43320. var axisLabelShow = false;
  43321. var nameTruncateMaxWidth;
  43322. if (axisIndex < winInnerIndices[0]) {
  43323. position = axisIndex * axisCollapseWidth;
  43324. nameTruncateMaxWidth = axisCollapseWidth;
  43325. }
  43326. else if (axisIndex <= winInnerIndices[1]) {
  43327. position = layoutInfo.axisExpandWindow0Pos
  43328. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  43329. axisNameAvailableWidth = axisExpandWidth;
  43330. axisLabelShow = true;
  43331. }
  43332. else {
  43333. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  43334. nameTruncateMaxWidth = axisCollapseWidth;
  43335. }
  43336. return {
  43337. position: position,
  43338. axisNameAvailableWidth: axisNameAvailableWidth,
  43339. axisLabelShow: axisLabelShow,
  43340. nameTruncateMaxWidth: nameTruncateMaxWidth
  43341. };
  43342. }
  43343. /**
  43344. * Parallel coordinate system creater.
  43345. */
  43346. function create$2(ecModel, api) {
  43347. var coordSysList = [];
  43348. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  43349. var coordSys = new Parallel(parallelModel, ecModel, api);
  43350. coordSys.name = 'parallel_' + idx;
  43351. coordSys.resize(parallelModel, api);
  43352. parallelModel.coordinateSystem = coordSys;
  43353. coordSys.model = parallelModel;
  43354. coordSysList.push(coordSys);
  43355. });
  43356. // Inject the coordinateSystems into seriesModel
  43357. ecModel.eachSeries(function (seriesModel) {
  43358. if (seriesModel.get('coordinateSystem') === 'parallel') {
  43359. var parallelModel = ecModel.queryComponents({
  43360. mainType: 'parallel',
  43361. index: seriesModel.get('parallelIndex'),
  43362. id: seriesModel.get('parallelId')
  43363. })[0];
  43364. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  43365. }
  43366. });
  43367. return coordSysList;
  43368. }
  43369. CoordinateSystemManager.register('parallel', {create: create$2});
  43370. var AxisModel$2 = ComponentModel.extend({
  43371. type: 'baseParallelAxis',
  43372. /**
  43373. * @type {module:echarts/coord/parallel/Axis}
  43374. */
  43375. axis: null,
  43376. /**
  43377. * @type {Array.<Array.<number>}
  43378. * @readOnly
  43379. */
  43380. activeIntervals: [],
  43381. /**
  43382. * @return {Object}
  43383. */
  43384. getAreaSelectStyle: function () {
  43385. return makeStyleMapper(
  43386. [
  43387. ['fill', 'color'],
  43388. ['lineWidth', 'borderWidth'],
  43389. ['stroke', 'borderColor'],
  43390. ['width', 'width'],
  43391. ['opacity', 'opacity']
  43392. ]
  43393. )(this.getModel('areaSelectStyle'));
  43394. },
  43395. /**
  43396. * The code of this feature is put on AxisModel but not ParallelAxis,
  43397. * because axisModel can be alive after echarts updating but instance of
  43398. * ParallelAxis having been disposed. this._activeInterval should be kept
  43399. * when action dispatched (i.e. legend click).
  43400. *
  43401. * @param {Array.<Array<number>>} intervals interval.length === 0
  43402. * means set all active.
  43403. * @public
  43404. */
  43405. setActiveIntervals: function (intervals) {
  43406. var activeIntervals = this.activeIntervals = clone(intervals);
  43407. // Normalize
  43408. if (activeIntervals) {
  43409. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  43410. asc(activeIntervals[i]);
  43411. }
  43412. }
  43413. },
  43414. /**
  43415. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  43416. * value can not be input.
  43417. * @return {string} 'normal': no activeIntervals set,
  43418. * 'active',
  43419. * 'inactive'.
  43420. * @public
  43421. */
  43422. getActiveState: function (value) {
  43423. var activeIntervals = this.activeIntervals;
  43424. if (!activeIntervals.length) {
  43425. return 'normal';
  43426. }
  43427. if (value == null) {
  43428. return 'inactive';
  43429. }
  43430. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  43431. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  43432. return 'active';
  43433. }
  43434. }
  43435. return 'inactive';
  43436. }
  43437. });
  43438. var defaultOption$1 = {
  43439. type: 'value',
  43440. /**
  43441. * @type {Array.<number>}
  43442. */
  43443. dim: null, // 0, 1, 2, ...
  43444. // parallelIndex: null,
  43445. areaSelectStyle: {
  43446. width: 20,
  43447. borderWidth: 1,
  43448. borderColor: 'rgba(160,197,232)',
  43449. color: 'rgba(160,197,232)',
  43450. opacity: 0.3
  43451. },
  43452. realtime: true, // Whether realtime update view when select.
  43453. z: 10
  43454. };
  43455. merge(AxisModel$2.prototype, axisModelCommonMixin);
  43456. function getAxisType$1(axisName, option) {
  43457. return option.type || (option.data ? 'category' : 'value');
  43458. }
  43459. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  43460. ComponentModel.extend({
  43461. type: 'parallel',
  43462. dependencies: ['parallelAxis'],
  43463. /**
  43464. * @type {module:echarts/coord/parallel/Parallel}
  43465. */
  43466. coordinateSystem: null,
  43467. /**
  43468. * Each item like: 'dim0', 'dim1', 'dim2', ...
  43469. * @type {Array.<string>}
  43470. * @readOnly
  43471. */
  43472. dimensions: null,
  43473. /**
  43474. * Coresponding to dimensions.
  43475. * @type {Array.<number>}
  43476. * @readOnly
  43477. */
  43478. parallelAxisIndex: null,
  43479. layoutMode: 'box',
  43480. defaultOption: {
  43481. zlevel: 0,
  43482. z: 0,
  43483. left: 80,
  43484. top: 60,
  43485. right: 80,
  43486. bottom: 60,
  43487. // width: {totalWidth} - left - right,
  43488. // height: {totalHeight} - top - bottom,
  43489. layout: 'horizontal', // 'horizontal' or 'vertical'
  43490. // FIXME
  43491. // naming?
  43492. axisExpandable: false,
  43493. axisExpandCenter: null,
  43494. axisExpandCount: 0,
  43495. axisExpandWidth: 50, // FIXME '10%' ?
  43496. axisExpandRate: 17,
  43497. axisExpandDebounce: 50,
  43498. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  43499. // Do not doc to user until necessary.
  43500. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  43501. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  43502. parallelAxisDefault: null
  43503. },
  43504. /**
  43505. * @override
  43506. */
  43507. init: function () {
  43508. ComponentModel.prototype.init.apply(this, arguments);
  43509. this.mergeOption({});
  43510. },
  43511. /**
  43512. * @override
  43513. */
  43514. mergeOption: function (newOption) {
  43515. var thisOption = this.option;
  43516. newOption && merge(thisOption, newOption, true);
  43517. this._initDimensions();
  43518. },
  43519. /**
  43520. * Whether series or axis is in this coordinate system.
  43521. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  43522. * @param {module:echarts/model/Global} ecModel
  43523. */
  43524. contains: function (model, ecModel) {
  43525. var parallelIndex = model.get('parallelIndex');
  43526. return parallelIndex != null
  43527. && ecModel.getComponent('parallel', parallelIndex) === this;
  43528. },
  43529. setAxisExpand: function (opt) {
  43530. each$1(
  43531. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  43532. function (name) {
  43533. if (opt.hasOwnProperty(name)) {
  43534. this.option[name] = opt[name];
  43535. }
  43536. },
  43537. this
  43538. );
  43539. },
  43540. /**
  43541. * @private
  43542. */
  43543. _initDimensions: function () {
  43544. var dimensions = this.dimensions = [];
  43545. var parallelAxisIndex = this.parallelAxisIndex = [];
  43546. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  43547. // Can not use this.contains here, because
  43548. // initialization has not been completed yet.
  43549. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  43550. }, this);
  43551. each$1(axisModels, function (axisModel) {
  43552. dimensions.push('dim' + axisModel.get('dim'));
  43553. parallelAxisIndex.push(axisModel.componentIndex);
  43554. });
  43555. }
  43556. });
  43557. /**
  43558. * @payload
  43559. * @property {string} parallelAxisId
  43560. * @property {Array.<Array.<number>>} intervals
  43561. */
  43562. var actionInfo$1 = {
  43563. type: 'axisAreaSelect',
  43564. event: 'axisAreaSelected'
  43565. // update: 'updateVisual'
  43566. };
  43567. registerAction(actionInfo$1, function (payload, ecModel) {
  43568. ecModel.eachComponent(
  43569. {mainType: 'parallelAxis', query: payload},
  43570. function (parallelAxisModel) {
  43571. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  43572. }
  43573. );
  43574. });
  43575. /**
  43576. * @payload
  43577. */
  43578. registerAction('parallelAxisExpand', function (payload, ecModel) {
  43579. ecModel.eachComponent(
  43580. {mainType: 'parallel', query: payload},
  43581. function (parallelModel) {
  43582. parallelModel.setAxisExpand(payload);
  43583. }
  43584. );
  43585. });
  43586. var curry$2 = curry;
  43587. var each$13 = each$1;
  43588. var map$2 = map;
  43589. var mathMin$6 = Math.min;
  43590. var mathMax$6 = Math.max;
  43591. var mathPow$2 = Math.pow;
  43592. var COVER_Z = 10000;
  43593. var UNSELECT_THRESHOLD = 6;
  43594. var MIN_RESIZE_LINE_WIDTH = 6;
  43595. var MUTEX_RESOURCE_KEY = 'globalPan';
  43596. var DIRECTION_MAP = {
  43597. w: [0, 0],
  43598. e: [0, 1],
  43599. n: [1, 0],
  43600. s: [1, 1]
  43601. };
  43602. var CURSOR_MAP = {
  43603. w: 'ew',
  43604. e: 'ew',
  43605. n: 'ns',
  43606. s: 'ns',
  43607. ne: 'nesw',
  43608. sw: 'nesw',
  43609. nw: 'nwse',
  43610. se: 'nwse'
  43611. };
  43612. var DEFAULT_BRUSH_OPT = {
  43613. brushStyle: {
  43614. lineWidth: 2,
  43615. stroke: 'rgba(0,0,0,0.3)',
  43616. fill: 'rgba(0,0,0,0.1)'
  43617. },
  43618. transformable: true,
  43619. brushMode: 'single',
  43620. removeOnClick: false
  43621. };
  43622. var baseUID = 0;
  43623. /**
  43624. * @alias module:echarts/component/helper/BrushController
  43625. * @constructor
  43626. * @mixin {module:zrender/mixin/Eventful}
  43627. * @event module:echarts/component/helper/BrushController#brush
  43628. * params:
  43629. * areas: Array.<Array>, coord relates to container group,
  43630. * If no container specified, to global.
  43631. * opt {
  43632. * isEnd: boolean,
  43633. * removeOnClick: boolean
  43634. * }
  43635. *
  43636. * @param {module:zrender/zrender~ZRender} zr
  43637. */
  43638. function BrushController(zr) {
  43639. if (__DEV__) {
  43640. assert$1(zr);
  43641. }
  43642. Eventful.call(this);
  43643. /**
  43644. * @type {module:zrender/zrender~ZRender}
  43645. * @private
  43646. */
  43647. this._zr = zr;
  43648. /**
  43649. * @type {module:zrender/container/Group}
  43650. * @readOnly
  43651. */
  43652. this.group = new Group();
  43653. /**
  43654. * Only for drawing (after enabledBrush).
  43655. * 'line', 'rect', 'polygon' or false
  43656. * If passing false/null/undefined, disable brush.
  43657. * If passing 'auto', determined by panel.defaultBrushType
  43658. * @private
  43659. * @type {string}
  43660. */
  43661. this._brushType;
  43662. /**
  43663. * Only for drawing (after enabledBrush).
  43664. *
  43665. * @private
  43666. * @type {Object}
  43667. */
  43668. this._brushOption;
  43669. /**
  43670. * @private
  43671. * @type {Object}
  43672. */
  43673. this._panels;
  43674. /**
  43675. * @private
  43676. * @type {Array.<nubmer>}
  43677. */
  43678. this._track = [];
  43679. /**
  43680. * @private
  43681. * @type {boolean}
  43682. */
  43683. this._dragging;
  43684. /**
  43685. * @private
  43686. * @type {Array}
  43687. */
  43688. this._covers = [];
  43689. /**
  43690. * @private
  43691. * @type {moudule:zrender/container/Group}
  43692. */
  43693. this._creatingCover;
  43694. /**
  43695. * `true` means global panel
  43696. * @private
  43697. * @type {module:zrender/container/Group|boolean}
  43698. */
  43699. this._creatingPanel;
  43700. /**
  43701. * @private
  43702. * @type {boolean}
  43703. */
  43704. this._enableGlobalPan;
  43705. /**
  43706. * @private
  43707. * @type {boolean}
  43708. */
  43709. if (__DEV__) {
  43710. this._mounted;
  43711. }
  43712. /**
  43713. * @private
  43714. * @type {string}
  43715. */
  43716. this._uid = 'brushController_' + baseUID++;
  43717. /**
  43718. * @private
  43719. * @type {Object}
  43720. */
  43721. this._handlers = {};
  43722. each$13(mouseHandlers, function (handler, eventName) {
  43723. this._handlers[eventName] = bind(handler, this);
  43724. }, this);
  43725. }
  43726. BrushController.prototype = {
  43727. constructor: BrushController,
  43728. /**
  43729. * If set to null/undefined/false, select disabled.
  43730. * @param {Object} brushOption
  43731. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  43732. * If passing false/null/undefined, disable brush.
  43733. * If passing 'auto', determined by panel.defaultBrushType.
  43734. * ('auto' can not be used in global panel)
  43735. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  43736. * @param {boolean} [brushOption.transformable=true]
  43737. * @param {boolean} [brushOption.removeOnClick=false]
  43738. * @param {Object} [brushOption.brushStyle]
  43739. * @param {number} [brushOption.brushStyle.width]
  43740. * @param {number} [brushOption.brushStyle.lineWidth]
  43741. * @param {string} [brushOption.brushStyle.stroke]
  43742. * @param {string} [brushOption.brushStyle.fill]
  43743. * @param {number} [brushOption.z]
  43744. */
  43745. enableBrush: function (brushOption) {
  43746. if (__DEV__) {
  43747. assert$1(this._mounted);
  43748. }
  43749. this._brushType && doDisableBrush(this);
  43750. brushOption.brushType && doEnableBrush(this, brushOption);
  43751. return this;
  43752. },
  43753. /**
  43754. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  43755. * Each items: {
  43756. * panelId, // mandatory.
  43757. * clipPath, // mandatory. function.
  43758. * isTargetByCursor, // mandatory. function.
  43759. * defaultBrushType, // optional, only used when brushType is 'auto'.
  43760. * getLinearBrushOtherExtent, // optional. function.
  43761. * }
  43762. */
  43763. setPanels: function (panelOpts) {
  43764. if (panelOpts && panelOpts.length) {
  43765. var panels = this._panels = {};
  43766. each$1(panelOpts, function (panelOpts) {
  43767. panels[panelOpts.panelId] = clone(panelOpts);
  43768. });
  43769. }
  43770. else {
  43771. this._panels = null;
  43772. }
  43773. return this;
  43774. },
  43775. /**
  43776. * @param {Object} [opt]
  43777. * @return {boolean} [opt.enableGlobalPan=false]
  43778. */
  43779. mount: function (opt) {
  43780. opt = opt || {};
  43781. if (__DEV__) {
  43782. this._mounted = true; // should be at first.
  43783. }
  43784. this._enableGlobalPan = opt.enableGlobalPan;
  43785. var thisGroup = this.group;
  43786. this._zr.add(thisGroup);
  43787. thisGroup.attr({
  43788. position: opt.position || [0, 0],
  43789. rotation: opt.rotation || 0,
  43790. scale: opt.scale || [1, 1]
  43791. });
  43792. this._transform = thisGroup.getLocalTransform();
  43793. return this;
  43794. },
  43795. eachCover: function (cb, context) {
  43796. each$13(this._covers, cb, context);
  43797. },
  43798. /**
  43799. * Update covers.
  43800. * @param {Array.<Object>} brushOptionList Like:
  43801. * [
  43802. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  43803. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  43804. * ...
  43805. * ]
  43806. * `brushType` is required in each cover info. (can not be 'auto')
  43807. * `id` is not mandatory.
  43808. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  43809. * If brushOptionList is null/undefined, all covers removed.
  43810. */
  43811. updateCovers: function (brushOptionList) {
  43812. if (__DEV__) {
  43813. assert$1(this._mounted);
  43814. }
  43815. brushOptionList = map(brushOptionList, function (brushOption) {
  43816. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  43817. });
  43818. var tmpIdPrefix = '\0-brush-index-';
  43819. var oldCovers = this._covers;
  43820. var newCovers = this._covers = [];
  43821. var controller = this;
  43822. var creatingCover = this._creatingCover;
  43823. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  43824. .add(addOrUpdate)
  43825. .update(addOrUpdate)
  43826. .remove(remove)
  43827. .execute();
  43828. return this;
  43829. function getKey(brushOption, index) {
  43830. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  43831. + '-' + brushOption.brushType;
  43832. }
  43833. function oldGetKey(cover, index) {
  43834. return getKey(cover.__brushOption, index);
  43835. }
  43836. function addOrUpdate(newIndex, oldIndex) {
  43837. var newBrushOption = brushOptionList[newIndex];
  43838. // Consider setOption in event listener of brushSelect,
  43839. // where updating cover when creating should be forbiden.
  43840. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  43841. newCovers[newIndex] = oldCovers[oldIndex];
  43842. }
  43843. else {
  43844. var cover = newCovers[newIndex] = oldIndex != null
  43845. ? (
  43846. oldCovers[oldIndex].__brushOption = newBrushOption,
  43847. oldCovers[oldIndex]
  43848. )
  43849. : endCreating(controller, createCover(controller, newBrushOption));
  43850. updateCoverAfterCreation(controller, cover);
  43851. }
  43852. }
  43853. function remove(oldIndex) {
  43854. if (oldCovers[oldIndex] !== creatingCover) {
  43855. controller.group.remove(oldCovers[oldIndex]);
  43856. }
  43857. }
  43858. },
  43859. unmount: function () {
  43860. if (__DEV__) {
  43861. if (!this._mounted) {
  43862. return;
  43863. }
  43864. }
  43865. this.enableBrush(false);
  43866. // container may 'removeAll' outside.
  43867. clearCovers(this);
  43868. this._zr.remove(this.group);
  43869. if (__DEV__) {
  43870. this._mounted = false; // should be at last.
  43871. }
  43872. return this;
  43873. },
  43874. dispose: function () {
  43875. this.unmount();
  43876. this.off();
  43877. }
  43878. };
  43879. mixin(BrushController, Eventful);
  43880. function doEnableBrush(controller, brushOption) {
  43881. var zr = controller._zr;
  43882. // Consider roam, which takes globalPan too.
  43883. if (!controller._enableGlobalPan) {
  43884. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  43885. }
  43886. each$13(controller._handlers, function (handler, eventName) {
  43887. zr.on(eventName, handler);
  43888. });
  43889. controller._brushType = brushOption.brushType;
  43890. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  43891. }
  43892. function doDisableBrush(controller) {
  43893. var zr = controller._zr;
  43894. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  43895. each$13(controller._handlers, function (handler, eventName) {
  43896. zr.off(eventName, handler);
  43897. });
  43898. controller._brushType = controller._brushOption = null;
  43899. }
  43900. function createCover(controller, brushOption) {
  43901. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  43902. cover.__brushOption = brushOption;
  43903. updateZ$1(cover, brushOption);
  43904. controller.group.add(cover);
  43905. return cover;
  43906. }
  43907. function endCreating(controller, creatingCover) {
  43908. var coverRenderer = getCoverRenderer(creatingCover);
  43909. if (coverRenderer.endCreating) {
  43910. coverRenderer.endCreating(controller, creatingCover);
  43911. updateZ$1(creatingCover, creatingCover.__brushOption);
  43912. }
  43913. return creatingCover;
  43914. }
  43915. function updateCoverShape(controller, cover) {
  43916. var brushOption = cover.__brushOption;
  43917. getCoverRenderer(cover).updateCoverShape(
  43918. controller, cover, brushOption.range, brushOption
  43919. );
  43920. }
  43921. function updateZ$1(cover, brushOption) {
  43922. var z = brushOption.z;
  43923. z == null && (z = COVER_Z);
  43924. cover.traverse(function (el) {
  43925. el.z = z;
  43926. el.z2 = z; // Consider in given container.
  43927. });
  43928. }
  43929. function updateCoverAfterCreation(controller, cover) {
  43930. getCoverRenderer(cover).updateCommon(controller, cover);
  43931. updateCoverShape(controller, cover);
  43932. }
  43933. function getCoverRenderer(cover) {
  43934. return coverRenderers[cover.__brushOption.brushType];
  43935. }
  43936. // return target panel or `true` (means global panel)
  43937. function getPanelByPoint(controller, e, localCursorPoint) {
  43938. var panels = controller._panels;
  43939. if (!panels) {
  43940. return true; // Global panel
  43941. }
  43942. var panel;
  43943. var transform = controller._transform;
  43944. each$13(panels, function (pn) {
  43945. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  43946. });
  43947. return panel;
  43948. }
  43949. // Return a panel or true
  43950. function getPanelByCover(controller, cover) {
  43951. var panels = controller._panels;
  43952. if (!panels) {
  43953. return true; // Global panel
  43954. }
  43955. var panelId = cover.__brushOption.panelId;
  43956. // User may give cover without coord sys info,
  43957. // which is then treated as global panel.
  43958. return panelId != null ? panels[panelId] : true;
  43959. }
  43960. function clearCovers(controller) {
  43961. var covers = controller._covers;
  43962. var originalLength = covers.length;
  43963. each$13(covers, function (cover) {
  43964. controller.group.remove(cover);
  43965. }, controller);
  43966. covers.length = 0;
  43967. return !!originalLength;
  43968. }
  43969. function trigger(controller, opt) {
  43970. var areas = map$2(controller._covers, function (cover) {
  43971. var brushOption = cover.__brushOption;
  43972. var range = clone(brushOption.range);
  43973. return {
  43974. brushType: brushOption.brushType,
  43975. panelId: brushOption.panelId,
  43976. range: range
  43977. };
  43978. });
  43979. controller.trigger('brush', areas, {
  43980. isEnd: !!opt.isEnd,
  43981. removeOnClick: !!opt.removeOnClick
  43982. });
  43983. }
  43984. function shouldShowCover(controller) {
  43985. var track = controller._track;
  43986. if (!track.length) {
  43987. return false;
  43988. }
  43989. var p2 = track[track.length - 1];
  43990. var p1 = track[0];
  43991. var dx = p2[0] - p1[0];
  43992. var dy = p2[1] - p1[1];
  43993. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  43994. return dist > UNSELECT_THRESHOLD;
  43995. }
  43996. function getTrackEnds(track) {
  43997. var tail = track.length - 1;
  43998. tail < 0 && (tail = 0);
  43999. return [track[0], track[tail]];
  44000. }
  44001. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  44002. var cover = new Group();
  44003. cover.add(new Rect({
  44004. name: 'main',
  44005. style: makeStyle(brushOption),
  44006. silent: true,
  44007. draggable: true,
  44008. cursor: 'move',
  44009. drift: curry$2(doDrift, controller, cover, 'nswe'),
  44010. ondragend: curry$2(trigger, controller, {isEnd: true})
  44011. }));
  44012. each$13(
  44013. edgeNames,
  44014. function (name) {
  44015. cover.add(new Rect({
  44016. name: name,
  44017. style: {opacity: 0},
  44018. draggable: true,
  44019. silent: true,
  44020. invisible: true,
  44021. drift: curry$2(doDrift, controller, cover, name),
  44022. ondragend: curry$2(trigger, controller, {isEnd: true})
  44023. }));
  44024. }
  44025. );
  44026. return cover;
  44027. }
  44028. function updateBaseRect(controller, cover, localRange, brushOption) {
  44029. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  44030. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  44031. var x = localRange[0][0];
  44032. var y = localRange[1][0];
  44033. var xa = x - lineWidth / 2;
  44034. var ya = y - lineWidth / 2;
  44035. var x2 = localRange[0][1];
  44036. var y2 = localRange[1][1];
  44037. var x2a = x2 - handleSize + lineWidth / 2;
  44038. var y2a = y2 - handleSize + lineWidth / 2;
  44039. var width = x2 - x;
  44040. var height = y2 - y;
  44041. var widtha = width + lineWidth;
  44042. var heighta = height + lineWidth;
  44043. updateRectShape(controller, cover, 'main', x, y, width, height);
  44044. if (brushOption.transformable) {
  44045. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  44046. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  44047. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  44048. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  44049. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  44050. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  44051. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  44052. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  44053. }
  44054. }
  44055. function updateCommon(controller, cover) {
  44056. var brushOption = cover.__brushOption;
  44057. var transformable = brushOption.transformable;
  44058. var mainEl = cover.childAt(0);
  44059. mainEl.useStyle(makeStyle(brushOption));
  44060. mainEl.attr({
  44061. silent: !transformable,
  44062. cursor: transformable ? 'move' : 'default'
  44063. });
  44064. each$13(
  44065. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  44066. function (name) {
  44067. var el = cover.childOfName(name);
  44068. var globalDir = getGlobalDirection(controller, name);
  44069. el && el.attr({
  44070. silent: !transformable,
  44071. invisible: !transformable,
  44072. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  44073. });
  44074. }
  44075. );
  44076. }
  44077. function updateRectShape(controller, cover, name, x, y, w, h) {
  44078. var el = cover.childOfName(name);
  44079. el && el.setShape(pointsToRect(
  44080. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  44081. ));
  44082. }
  44083. function makeStyle(brushOption) {
  44084. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  44085. }
  44086. function formatRectRange(x, y, x2, y2) {
  44087. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  44088. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  44089. return [
  44090. [min[0], max[0]], // x range
  44091. [min[1], max[1]] // y range
  44092. ];
  44093. }
  44094. function getTransform$1(controller) {
  44095. return getTransform(controller.group);
  44096. }
  44097. function getGlobalDirection(controller, localDirection) {
  44098. if (localDirection.length > 1) {
  44099. localDirection = localDirection.split('');
  44100. var globalDir = [
  44101. getGlobalDirection(controller, localDirection[0]),
  44102. getGlobalDirection(controller, localDirection[1])
  44103. ];
  44104. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  44105. return globalDir.join('');
  44106. }
  44107. else {
  44108. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  44109. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  44110. var globalDir = transformDirection(
  44111. map$$1[localDirection], getTransform$1(controller)
  44112. );
  44113. return inverseMap[globalDir];
  44114. }
  44115. }
  44116. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  44117. var brushOption = cover.__brushOption;
  44118. var rectRange = toRectRange(brushOption.range);
  44119. var localDelta = toLocalDelta(controller, dx, dy);
  44120. each$13(name.split(''), function (namePart) {
  44121. var ind = DIRECTION_MAP[namePart];
  44122. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  44123. });
  44124. brushOption.range = fromRectRange(formatRectRange(
  44125. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  44126. ));
  44127. updateCoverAfterCreation(controller, cover);
  44128. trigger(controller, {isEnd: false});
  44129. }
  44130. function driftPolygon(controller, cover, dx, dy, e) {
  44131. var range = cover.__brushOption.range;
  44132. var localDelta = toLocalDelta(controller, dx, dy);
  44133. each$13(range, function (point) {
  44134. point[0] += localDelta[0];
  44135. point[1] += localDelta[1];
  44136. });
  44137. updateCoverAfterCreation(controller, cover);
  44138. trigger(controller, {isEnd: false});
  44139. }
  44140. function toLocalDelta(controller, dx, dy) {
  44141. var thisGroup = controller.group;
  44142. var localD = thisGroup.transformCoordToLocal(dx, dy);
  44143. var localZero = thisGroup.transformCoordToLocal(0, 0);
  44144. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  44145. }
  44146. function clipByPanel(controller, cover, data) {
  44147. var panel = getPanelByCover(controller, cover);
  44148. return (panel && panel !== true)
  44149. ? panel.clipPath(data, controller._transform)
  44150. : clone(data);
  44151. }
  44152. function pointsToRect(points) {
  44153. var xmin = mathMin$6(points[0][0], points[1][0]);
  44154. var ymin = mathMin$6(points[0][1], points[1][1]);
  44155. var xmax = mathMax$6(points[0][0], points[1][0]);
  44156. var ymax = mathMax$6(points[0][1], points[1][1]);
  44157. return {
  44158. x: xmin,
  44159. y: ymin,
  44160. width: xmax - xmin,
  44161. height: ymax - ymin
  44162. };
  44163. }
  44164. function resetCursor(controller, e, localCursorPoint) {
  44165. // Check active
  44166. if (!controller._brushType) {
  44167. return;
  44168. }
  44169. var zr = controller._zr;
  44170. var covers = controller._covers;
  44171. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  44172. // Check whether in covers.
  44173. if (!controller._dragging) {
  44174. for (var i = 0; i < covers.length; i++) {
  44175. var brushOption = covers[i].__brushOption;
  44176. if (currPanel
  44177. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  44178. && coverRenderers[brushOption.brushType].contain(
  44179. covers[i], localCursorPoint[0], localCursorPoint[1]
  44180. )
  44181. ) {
  44182. // Use cursor style set on cover.
  44183. return;
  44184. }
  44185. }
  44186. }
  44187. currPanel && zr.setCursorStyle('crosshair');
  44188. }
  44189. function preventDefault(e) {
  44190. var rawE = e.event;
  44191. rawE.preventDefault && rawE.preventDefault();
  44192. }
  44193. function mainShapeContain(cover, x, y) {
  44194. return cover.childOfName('main').contain(x, y);
  44195. }
  44196. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  44197. var creatingCover = controller._creatingCover;
  44198. var panel = controller._creatingPanel;
  44199. var thisBrushOption = controller._brushOption;
  44200. var eventParams;
  44201. controller._track.push(localCursorPoint.slice());
  44202. if (shouldShowCover(controller) || creatingCover) {
  44203. if (panel && !creatingCover) {
  44204. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  44205. var brushOption = clone(thisBrushOption);
  44206. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  44207. brushOption.panelId = panel === true ? null : panel.panelId;
  44208. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  44209. controller._covers.push(creatingCover);
  44210. }
  44211. if (creatingCover) {
  44212. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  44213. var coverBrushOption = creatingCover.__brushOption;
  44214. coverBrushOption.range = coverRenderer.getCreatingRange(
  44215. clipByPanel(controller, creatingCover, controller._track)
  44216. );
  44217. if (isEnd) {
  44218. endCreating(controller, creatingCover);
  44219. coverRenderer.updateCommon(controller, creatingCover);
  44220. }
  44221. updateCoverShape(controller, creatingCover);
  44222. eventParams = {isEnd: isEnd};
  44223. }
  44224. }
  44225. else if (
  44226. isEnd
  44227. && thisBrushOption.brushMode === 'single'
  44228. && thisBrushOption.removeOnClick
  44229. ) {
  44230. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  44231. // But a single click do not clear covers, because user may have casual
  44232. // clicks (for example, click on other component and do not expect covers
  44233. // disappear).
  44234. // Only some cover removed, trigger action, but not every click trigger action.
  44235. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  44236. eventParams = {isEnd: isEnd, removeOnClick: true};
  44237. }
  44238. }
  44239. return eventParams;
  44240. }
  44241. function determineBrushType(brushType, panel) {
  44242. if (brushType === 'auto') {
  44243. if (__DEV__) {
  44244. assert$1(
  44245. panel && panel.defaultBrushType,
  44246. 'MUST have defaultBrushType when brushType is "atuo"'
  44247. );
  44248. }
  44249. return panel.defaultBrushType;
  44250. }
  44251. return brushType;
  44252. }
  44253. var mouseHandlers = {
  44254. mousedown: function (e) {
  44255. if (this._dragging) {
  44256. // In case some browser do not support globalOut,
  44257. // and release mose out side the browser.
  44258. handleDragEnd.call(this, e);
  44259. }
  44260. else if (!e.target || !e.target.draggable) {
  44261. preventDefault(e);
  44262. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  44263. this._creatingCover = null;
  44264. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  44265. if (panel) {
  44266. this._dragging = true;
  44267. this._track = [localCursorPoint.slice()];
  44268. }
  44269. }
  44270. },
  44271. mousemove: function (e) {
  44272. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  44273. resetCursor(this, e, localCursorPoint);
  44274. if (this._dragging) {
  44275. preventDefault(e);
  44276. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  44277. eventParams && trigger(this, eventParams);
  44278. }
  44279. },
  44280. mouseup: handleDragEnd //,
  44281. // FIXME
  44282. // in tooltip, globalout should not be triggered.
  44283. // globalout: handleDragEnd
  44284. };
  44285. function handleDragEnd(e) {
  44286. if (this._dragging) {
  44287. preventDefault(e);
  44288. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  44289. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  44290. this._dragging = false;
  44291. this._track = [];
  44292. this._creatingCover = null;
  44293. // trigger event shoule be at final, after procedure will be nested.
  44294. eventParams && trigger(this, eventParams);
  44295. }
  44296. }
  44297. /**
  44298. * key: brushType
  44299. * @type {Object}
  44300. */
  44301. var coverRenderers = {
  44302. lineX: getLineRenderer(0),
  44303. lineY: getLineRenderer(1),
  44304. rect: {
  44305. createCover: function (controller, brushOption) {
  44306. return createBaseRectCover(
  44307. curry$2(
  44308. driftRect,
  44309. function (range) {
  44310. return range;
  44311. },
  44312. function (range) {
  44313. return range;
  44314. }
  44315. ),
  44316. controller,
  44317. brushOption,
  44318. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  44319. );
  44320. },
  44321. getCreatingRange: function (localTrack) {
  44322. var ends = getTrackEnds(localTrack);
  44323. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  44324. },
  44325. updateCoverShape: function (controller, cover, localRange, brushOption) {
  44326. updateBaseRect(controller, cover, localRange, brushOption);
  44327. },
  44328. updateCommon: updateCommon,
  44329. contain: mainShapeContain
  44330. },
  44331. polygon: {
  44332. createCover: function (controller, brushOption) {
  44333. var cover = new Group();
  44334. // Do not use graphic.Polygon because graphic.Polyline do not close the
  44335. // border of the shape when drawing, which is a better experience for user.
  44336. cover.add(new Polyline({
  44337. name: 'main',
  44338. style: makeStyle(brushOption),
  44339. silent: true
  44340. }));
  44341. return cover;
  44342. },
  44343. getCreatingRange: function (localTrack) {
  44344. return localTrack;
  44345. },
  44346. endCreating: function (controller, cover) {
  44347. cover.remove(cover.childAt(0));
  44348. // Use graphic.Polygon close the shape.
  44349. cover.add(new Polygon({
  44350. name: 'main',
  44351. draggable: true,
  44352. drift: curry$2(driftPolygon, controller, cover),
  44353. ondragend: curry$2(trigger, controller, {isEnd: true})
  44354. }));
  44355. },
  44356. updateCoverShape: function (controller, cover, localRange, brushOption) {
  44357. cover.childAt(0).setShape({
  44358. points: clipByPanel(controller, cover, localRange)
  44359. });
  44360. },
  44361. updateCommon: updateCommon,
  44362. contain: mainShapeContain
  44363. }
  44364. };
  44365. function getLineRenderer(xyIndex) {
  44366. return {
  44367. createCover: function (controller, brushOption) {
  44368. return createBaseRectCover(
  44369. curry$2(
  44370. driftRect,
  44371. function (range) {
  44372. var rectRange = [range, [0, 100]];
  44373. xyIndex && rectRange.reverse();
  44374. return rectRange;
  44375. },
  44376. function (rectRange) {
  44377. return rectRange[xyIndex];
  44378. }
  44379. ),
  44380. controller,
  44381. brushOption,
  44382. [['w', 'e'], ['n', 's']][xyIndex]
  44383. );
  44384. },
  44385. getCreatingRange: function (localTrack) {
  44386. var ends = getTrackEnds(localTrack);
  44387. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  44388. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  44389. return [min, max];
  44390. },
  44391. updateCoverShape: function (controller, cover, localRange, brushOption) {
  44392. var otherExtent;
  44393. // If brushWidth not specified, fit the panel.
  44394. var panel = getPanelByCover(controller, cover);
  44395. if (panel !== true && panel.getLinearBrushOtherExtent) {
  44396. otherExtent = panel.getLinearBrushOtherExtent(
  44397. xyIndex, controller._transform
  44398. );
  44399. }
  44400. else {
  44401. var zr = controller._zr;
  44402. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  44403. }
  44404. var rectRange = [localRange, otherExtent];
  44405. xyIndex && rectRange.reverse();
  44406. updateBaseRect(controller, cover, rectRange, brushOption);
  44407. },
  44408. updateCommon: updateCommon,
  44409. contain: mainShapeContain
  44410. };
  44411. }
  44412. function makeRectPanelClipPath(rect) {
  44413. rect = normalizeRect(rect);
  44414. return function (localPoints, transform) {
  44415. return clipPointsByRect(localPoints, rect);
  44416. };
  44417. }
  44418. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  44419. rect = normalizeRect(rect);
  44420. return function (xyIndex) {
  44421. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  44422. var brushWidth = idx ? rect.width : rect.height;
  44423. var base = idx ? rect.x : rect.y;
  44424. return [base, base + (brushWidth || 0)];
  44425. };
  44426. }
  44427. function makeRectIsTargetByCursor(rect, api, targetModel) {
  44428. rect = normalizeRect(rect);
  44429. return function (e, localCursorPoint, transform) {
  44430. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  44431. && !onIrrelevantElement(e, api, targetModel);
  44432. };
  44433. }
  44434. // Consider width/height is negative.
  44435. function normalizeRect(rect) {
  44436. return BoundingRect.create(rect);
  44437. }
  44438. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  44439. var AxisView$2 = extendComponentView({
  44440. type: 'parallelAxis',
  44441. /**
  44442. * @override
  44443. */
  44444. init: function (ecModel, api) {
  44445. AxisView$2.superApply(this, 'init', arguments);
  44446. /**
  44447. * @type {module:echarts/component/helper/BrushController}
  44448. */
  44449. (this._brushController = new BrushController(api.getZr()))
  44450. .on('brush', bind(this._onBrush, this));
  44451. },
  44452. /**
  44453. * @override
  44454. */
  44455. render: function (axisModel, ecModel, api, payload) {
  44456. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  44457. return;
  44458. }
  44459. this.axisModel = axisModel;
  44460. this.api = api;
  44461. this.group.removeAll();
  44462. var oldAxisGroup = this._axisGroup;
  44463. this._axisGroup = new Group();
  44464. this.group.add(this._axisGroup);
  44465. if (!axisModel.get('show')) {
  44466. return;
  44467. }
  44468. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  44469. var coordSys = coordSysModel.coordinateSystem;
  44470. var areaSelectStyle = axisModel.getAreaSelectStyle();
  44471. var areaWidth = areaSelectStyle.width;
  44472. var dim = axisModel.axis.dim;
  44473. var axisLayout = coordSys.getAxisLayout(dim);
  44474. var builderOpt = extend(
  44475. {strokeContainThreshold: areaWidth},
  44476. axisLayout
  44477. );
  44478. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  44479. each$1(elementList, axisBuilder.add, axisBuilder);
  44480. this._axisGroup.add(axisBuilder.getGroup());
  44481. this._refreshBrushController(
  44482. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  44483. );
  44484. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  44485. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  44486. },
  44487. // /**
  44488. // * @override
  44489. // */
  44490. // updateVisual: function (axisModel, ecModel, api, payload) {
  44491. // this._brushController && this._brushController
  44492. // .updateCovers(getCoverInfoList(axisModel));
  44493. // },
  44494. _refreshBrushController: function (
  44495. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  44496. ) {
  44497. // After filtering, axis may change, select area needs to be update.
  44498. var extent = axisModel.axis.getExtent();
  44499. var extentLen = extent[1] - extent[0];
  44500. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  44501. // width/height might be negative, which will be
  44502. // normalized in BoundingRect.
  44503. var rect = BoundingRect.create({
  44504. x: extent[0],
  44505. y: -areaWidth / 2,
  44506. width: extentLen,
  44507. height: areaWidth
  44508. });
  44509. rect.x -= extra;
  44510. rect.width += 2 * extra;
  44511. this._brushController
  44512. .mount({
  44513. enableGlobalPan: true,
  44514. rotation: builderOpt.rotation,
  44515. position: builderOpt.position
  44516. })
  44517. .setPanels([{
  44518. panelId: 'pl',
  44519. clipPath: makeRectPanelClipPath(rect),
  44520. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  44521. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  44522. }])
  44523. .enableBrush({
  44524. brushType: 'lineX',
  44525. brushStyle: areaSelectStyle,
  44526. removeOnClick: true
  44527. })
  44528. .updateCovers(getCoverInfoList(axisModel));
  44529. },
  44530. _onBrush: function (coverInfoList, opt) {
  44531. // Do not cache these object, because the mey be changed.
  44532. var axisModel = this.axisModel;
  44533. var axis = axisModel.axis;
  44534. var intervals = map(coverInfoList, function (coverInfo) {
  44535. return [
  44536. axis.coordToData(coverInfo.range[0], true),
  44537. axis.coordToData(coverInfo.range[1], true)
  44538. ];
  44539. });
  44540. // If realtime is true, action is not dispatched on drag end, because
  44541. // the drag end emits the same params with the last drag move event,
  44542. // and may have some delay when using touch pad.
  44543. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  44544. this.api.dispatchAction({
  44545. type: 'axisAreaSelect',
  44546. parallelAxisId: axisModel.id,
  44547. intervals: intervals
  44548. });
  44549. }
  44550. },
  44551. /**
  44552. * @override
  44553. */
  44554. dispose: function () {
  44555. this._brushController.dispose();
  44556. }
  44557. });
  44558. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  44559. return payload
  44560. && payload.type === 'axisAreaSelect'
  44561. && ecModel.findComponents(
  44562. {mainType: 'parallelAxis', query: payload}
  44563. )[0] === axisModel;
  44564. }
  44565. function getCoverInfoList(axisModel) {
  44566. var axis = axisModel.axis;
  44567. return map(axisModel.activeIntervals, function (interval) {
  44568. return {
  44569. brushType: 'lineX',
  44570. panelId: 'pl',
  44571. range: [
  44572. axis.dataToCoord(interval[0], true),
  44573. axis.dataToCoord(interval[1], true)
  44574. ]
  44575. };
  44576. });
  44577. }
  44578. function getCoordSysModel(axisModel, ecModel) {
  44579. return ecModel.getComponent(
  44580. 'parallel', axisModel.get('parallelIndex')
  44581. );
  44582. }
  44583. var CLICK_THRESHOLD = 5; // > 4
  44584. // Parallel view
  44585. extendComponentView({
  44586. type: 'parallel',
  44587. render: function (parallelModel, ecModel, api) {
  44588. this._model = parallelModel;
  44589. this._api = api;
  44590. if (!this._handlers) {
  44591. this._handlers = {};
  44592. each$1(handlers, function (handler, eventName) {
  44593. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  44594. }, this);
  44595. }
  44596. createOrUpdate(
  44597. this,
  44598. '_throttledDispatchExpand',
  44599. parallelModel.get('axisExpandRate'),
  44600. 'fixRate'
  44601. );
  44602. },
  44603. dispose: function (ecModel, api) {
  44604. each$1(this._handlers, function (handler, eventName) {
  44605. api.getZr().off(eventName, handler);
  44606. });
  44607. this._handlers = null;
  44608. },
  44609. /**
  44610. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  44611. */
  44612. _throttledDispatchExpand: function (opt) {
  44613. this._dispatchExpand(opt);
  44614. },
  44615. _dispatchExpand: function (opt) {
  44616. opt && this._api.dispatchAction(
  44617. extend({type: 'parallelAxisExpand'}, opt)
  44618. );
  44619. }
  44620. });
  44621. var handlers = {
  44622. mousedown: function (e) {
  44623. if (checkTrigger(this, 'click')) {
  44624. this._mouseDownPoint = [e.offsetX, e.offsetY];
  44625. }
  44626. },
  44627. mouseup: function (e) {
  44628. var mouseDownPoint = this._mouseDownPoint;
  44629. if (checkTrigger(this, 'click') && mouseDownPoint) {
  44630. var point = [e.offsetX, e.offsetY];
  44631. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  44632. + Math.pow(mouseDownPoint[1] - point[1], 2);
  44633. if (dist > CLICK_THRESHOLD) {
  44634. return;
  44635. }
  44636. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  44637. [e.offsetX, e.offsetY]
  44638. );
  44639. result.behavior !== 'none' && this._dispatchExpand({
  44640. axisExpandWindow: result.axisExpandWindow
  44641. });
  44642. }
  44643. this._mouseDownPoint = null;
  44644. },
  44645. mousemove: function (e) {
  44646. // Should do nothing when brushing.
  44647. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  44648. return;
  44649. }
  44650. var model = this._model;
  44651. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  44652. [e.offsetX, e.offsetY]
  44653. );
  44654. var behavior = result.behavior;
  44655. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  44656. this._throttledDispatchExpand(
  44657. behavior === 'none'
  44658. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  44659. : {
  44660. axisExpandWindow: result.axisExpandWindow,
  44661. // Jumping uses animation, and sliding suppresses animation.
  44662. animation: behavior === 'jump' ? null : false
  44663. }
  44664. );
  44665. }
  44666. };
  44667. function checkTrigger(view, triggerOn) {
  44668. var model = view._model;
  44669. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  44670. }
  44671. registerPreprocessor(parallelPreprocessor);
  44672. SeriesModel.extend({
  44673. type: 'series.parallel',
  44674. dependencies: ['parallel'],
  44675. visualColorAccessPath: 'lineStyle.color',
  44676. getInitialData: function (option, ecModel) {
  44677. // Anication is forbiden in progressive data mode.
  44678. if (this.option.progressive) {
  44679. this.option.animation = false;
  44680. }
  44681. var source = this.getSource();
  44682. setEncodeAndDimensions(source, this);
  44683. return createListFromArray(source, this);
  44684. },
  44685. /**
  44686. * User can get data raw indices on 'axisAreaSelected' event received.
  44687. *
  44688. * @public
  44689. * @param {string} activeState 'active' or 'inactive' or 'normal'
  44690. * @return {Array.<number>} Raw indices
  44691. */
  44692. getRawIndicesByActiveState: function (activeState) {
  44693. var coordSys = this.coordinateSystem;
  44694. var data = this.getData();
  44695. var indices = [];
  44696. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  44697. if (activeState === theActiveState) {
  44698. indices.push(data.getRawIndex(dataIndex));
  44699. }
  44700. });
  44701. return indices;
  44702. },
  44703. defaultOption: {
  44704. zlevel: 0, // 一级层叠
  44705. z: 2, // 二级层叠
  44706. coordinateSystem: 'parallel',
  44707. parallelIndex: 0,
  44708. label: {
  44709. show: false
  44710. },
  44711. inactiveOpacity: 0.05,
  44712. activeOpacity: 1,
  44713. lineStyle: {
  44714. width: 1,
  44715. opacity: 0.45,
  44716. type: 'solid'
  44717. },
  44718. emphasis: {
  44719. label: {
  44720. show: false
  44721. }
  44722. },
  44723. progressive: false, // 100
  44724. smooth: false,
  44725. animationEasing: 'linear'
  44726. }
  44727. });
  44728. function setEncodeAndDimensions(source, seriesModel) {
  44729. // The mapping of parallelAxis dimension to data dimension can
  44730. // be specified in parallelAxis.option.dim. For example, if
  44731. // parallelAxis.option.dim is 'dim3', it mapping to the third
  44732. // dimension of data. But `data.encode` has higher priority.
  44733. // Moreover, parallelModel.dimension should not be regarded as data
  44734. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  44735. if (source.encodeDefine) {
  44736. return;
  44737. }
  44738. var parallelModel = seriesModel.ecModel.getComponent(
  44739. 'parallel', seriesModel.get('parallelIndex')
  44740. );
  44741. if (!parallelModel) {
  44742. return;
  44743. }
  44744. var encodeDefine = source.encodeDefine = createHashMap();
  44745. each$1(parallelModel.dimensions, function (axisDim) {
  44746. var dataDimIndex = convertDimNameToNumber(axisDim);
  44747. encodeDefine.set(axisDim, dataDimIndex);
  44748. });
  44749. }
  44750. function convertDimNameToNumber(dimName) {
  44751. return +dimName.replace('dim', '');
  44752. }
  44753. var SMOOTH = 0.3;
  44754. var ParallelView = Chart.extend({
  44755. type: 'parallel',
  44756. init: function () {
  44757. /**
  44758. * @type {module:zrender/container/Group}
  44759. * @private
  44760. */
  44761. this._dataGroup = new Group();
  44762. this.group.add(this._dataGroup);
  44763. /**
  44764. * @type {module:echarts/data/List}
  44765. */
  44766. this._data;
  44767. },
  44768. /**
  44769. * @override
  44770. */
  44771. render: function (seriesModel, ecModel, api, payload) {
  44772. this._renderForNormal(seriesModel, payload);
  44773. // this[
  44774. // seriesModel.option.progressive
  44775. // ? '_renderForProgressive'
  44776. // : '_renderForNormal'
  44777. // ](seriesModel);
  44778. },
  44779. dispose: function () {},
  44780. /**
  44781. * @private
  44782. */
  44783. _renderForNormal: function (seriesModel, payload) {
  44784. var dataGroup = this._dataGroup;
  44785. var data = seriesModel.getData();
  44786. var oldData = this._data;
  44787. var coordSys = seriesModel.coordinateSystem;
  44788. var dimensions = coordSys.dimensions;
  44789. var option = seriesModel.option;
  44790. var smooth = option.smooth ? SMOOTH : null;
  44791. // Consider switch between progressive and not.
  44792. // oldData && oldData.__plProgressive && dataGroup.removeAll();
  44793. data.diff(oldData)
  44794. .add(add)
  44795. .update(update)
  44796. .remove(remove)
  44797. .execute();
  44798. // Update style
  44799. updateElCommon(data, smooth);
  44800. // First create
  44801. if (!this._data) {
  44802. var clipPath = createGridClipShape$1(
  44803. coordSys, seriesModel, function () {
  44804. // Callback will be invoked immediately if there is no animation
  44805. setTimeout(function () {
  44806. dataGroup.removeClipPath();
  44807. });
  44808. }
  44809. );
  44810. dataGroup.setClipPath(clipPath);
  44811. }
  44812. this._data = data;
  44813. function add(newDataIndex) {
  44814. addEl(data, dataGroup, newDataIndex, dimensions, coordSys, null, smooth);
  44815. }
  44816. function update(newDataIndex, oldDataIndex) {
  44817. var line = oldData.getItemGraphicEl(oldDataIndex);
  44818. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  44819. data.setItemGraphicEl(newDataIndex, line);
  44820. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  44821. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  44822. }
  44823. function remove(oldDataIndex) {
  44824. var line = oldData.getItemGraphicEl(oldDataIndex);
  44825. dataGroup.remove(line);
  44826. }
  44827. },
  44828. /**
  44829. * @private
  44830. */
  44831. // _renderForProgressive: function (seriesModel) {
  44832. // var dataGroup = this._dataGroup;
  44833. // var data = seriesModel.getData();
  44834. // var oldData = this._data;
  44835. // var coordSys = seriesModel.coordinateSystem;
  44836. // var dimensions = coordSys.dimensions;
  44837. // var option = seriesModel.option;
  44838. // var progressive = option.progressive;
  44839. // var smooth = option.smooth ? SMOOTH : null;
  44840. // // In progressive animation is disabled, so use simple data diff,
  44841. // // which effects performance less.
  44842. // // (Typically performance for data with length 7000+ like:
  44843. // // simpleDiff: 60ms, addEl: 184ms,
  44844. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  44845. // if (simpleDiff(oldData, data, dimensions)) {
  44846. // dataGroup.removeAll();
  44847. // data.each(function (dataIndex) {
  44848. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  44849. // });
  44850. // }
  44851. // updateElCommon(data, progressive, smooth);
  44852. // // Consider switch between progressive and not.
  44853. // data.__plProgressive = true;
  44854. // this._data = data;
  44855. // },
  44856. /**
  44857. * @override
  44858. */
  44859. remove: function () {
  44860. this._dataGroup && this._dataGroup.removeAll();
  44861. this._data = null;
  44862. }
  44863. });
  44864. function createGridClipShape$1(coordSys, seriesModel, cb) {
  44865. var parallelModel = coordSys.model;
  44866. var rect = coordSys.getRect();
  44867. var rectEl = new Rect({
  44868. shape: {
  44869. x: rect.x,
  44870. y: rect.y,
  44871. width: rect.width,
  44872. height: rect.height
  44873. }
  44874. });
  44875. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  44876. rectEl.setShape(dim, 0);
  44877. initProps(rectEl, {
  44878. shape: {
  44879. width: rect.width,
  44880. height: rect.height
  44881. }
  44882. }, seriesModel, cb);
  44883. return rectEl;
  44884. }
  44885. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  44886. var points = [];
  44887. for (var i = 0; i < dimensions.length; i++) {
  44888. var dimName = dimensions[i];
  44889. var value = data.get(data.mapDimension(dimName), dataIndex);
  44890. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  44891. points.push(coordSys.dataToPoint(value, dimName));
  44892. }
  44893. }
  44894. return points;
  44895. }
  44896. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  44897. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  44898. var line = new Polyline({
  44899. shape: {points: points},
  44900. silent: true,
  44901. z2: 10
  44902. });
  44903. dataGroup.add(line);
  44904. data.setItemGraphicEl(dataIndex, line);
  44905. }
  44906. function updateElCommon(data, smooth) {
  44907. var seriesStyleModel = data.hostModel.getModel('lineStyle');
  44908. var lineStyle = seriesStyleModel.getLineStyle();
  44909. data.eachItemGraphicEl(function (line, dataIndex) {
  44910. if (data.hasItemOption) {
  44911. var itemModel = data.getItemModel(dataIndex);
  44912. var lineStyleModel = itemModel.getModel('lineStyle', seriesStyleModel);
  44913. lineStyle = lineStyleModel.getLineStyle(['color', 'stroke']);
  44914. }
  44915. line.useStyle(extend(lineStyle, {
  44916. fill: null,
  44917. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  44918. stroke: data.getItemVisual(dataIndex, 'color'),
  44919. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  44920. opacity: data.getItemVisual(dataIndex, 'opacity')
  44921. }));
  44922. line.shape.smooth = smooth;
  44923. });
  44924. }
  44925. // function simpleDiff(oldData, newData, dimensions) {
  44926. // var oldLen;
  44927. // if (!oldData
  44928. // || !oldData.__plProgressive
  44929. // || (oldLen = oldData.count()) !== newData.count()
  44930. // ) {
  44931. // return true;
  44932. // }
  44933. // var dimLen = dimensions.length;
  44934. // for (var i = 0; i < oldLen; i++) {
  44935. // for (var j = 0; j < dimLen; j++) {
  44936. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  44937. // return true;
  44938. // }
  44939. // }
  44940. // }
  44941. // return false;
  44942. // }
  44943. // FIXME
  44944. // 公用方法?
  44945. function isEmptyValue(val, axisType) {
  44946. return axisType === 'category'
  44947. ? val == null
  44948. : (val == null || isNaN(val)); // axisType === 'value'
  44949. }
  44950. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  44951. var parallelVisual = function (ecModel) {
  44952. ecModel.eachSeriesByType('parallel', function (seriesModel) {
  44953. var itemStyleModel = seriesModel.getModel('itemStyle');
  44954. var lineStyleModel = seriesModel.getModel('lineStyle');
  44955. var globalColors = ecModel.get('color');
  44956. var color = lineStyleModel.get('color')
  44957. || itemStyleModel.get('color')
  44958. || globalColors[seriesModel.seriesIndex % globalColors.length];
  44959. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  44960. var activeOpacity = seriesModel.get('activeOpacity');
  44961. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  44962. var coordSys = seriesModel.coordinateSystem;
  44963. var data = seriesModel.getData();
  44964. var opacityMap = {
  44965. normal: lineStyle.opacity,
  44966. active: activeOpacity,
  44967. inactive: inactiveOpacity
  44968. };
  44969. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  44970. var itemModel = data.getItemModel(dataIndex);
  44971. var opacity = opacityMap[activeState];
  44972. if (activeState === 'normal') {
  44973. var itemOpacity = itemModel.get(opacityAccessPath$1, true);
  44974. itemOpacity != null && (opacity = itemOpacity);
  44975. }
  44976. data.setItemVisual(dataIndex, 'opacity', opacity);
  44977. });
  44978. data.setVisual('color', color);
  44979. });
  44980. };
  44981. registerVisual(parallelVisual);
  44982. /**
  44983. * @file Get initial data and define sankey view's series model
  44984. * @author Deqing Li(annong035@gmail.com)
  44985. */
  44986. var SankeySeries = SeriesModel.extend({
  44987. type: 'series.sankey',
  44988. layoutInfo: null,
  44989. /**
  44990. * Init a graph data structure from data in option series
  44991. *
  44992. * @param {Object} option the object used to config echarts view
  44993. * @return {module:echarts/data/List} storage initial data
  44994. */
  44995. getInitialData: function (option) {
  44996. var links = option.edges || option.links;
  44997. var nodes = option.data || option.nodes;
  44998. if (nodes && links) {
  44999. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  45000. return graph.data;
  45001. }
  45002. },
  45003. /**
  45004. * Return the graphic data structure
  45005. *
  45006. * @return {module:echarts/data/Graph} graphic data structure
  45007. */
  45008. getGraph: function () {
  45009. return this.getData().graph;
  45010. },
  45011. /**
  45012. * Get edge data of graphic data structure
  45013. *
  45014. * @return {module:echarts/data/List} data structure of list
  45015. */
  45016. getEdgeData: function () {
  45017. return this.getGraph().edgeData;
  45018. },
  45019. /**
  45020. * @override
  45021. */
  45022. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  45023. // dataType === 'node' or empty do not show tooltip by default
  45024. if (dataType === 'edge') {
  45025. var params = this.getDataParams(dataIndex, dataType);
  45026. var rawDataOpt = params.data;
  45027. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  45028. if (params.value) {
  45029. html += ' : ' + params.value;
  45030. }
  45031. return encodeHTML(html);
  45032. }
  45033. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  45034. },
  45035. defaultOption: {
  45036. zlevel: 0,
  45037. z: 2,
  45038. coordinateSystem: 'view',
  45039. layout: null,
  45040. // the position of the whole view
  45041. left: '5%',
  45042. top: '5%',
  45043. right: '20%',
  45044. bottom: '5%',
  45045. // the dx of the node
  45046. nodeWidth: 20,
  45047. // the vertical distance between two nodes
  45048. nodeGap: 8,
  45049. // the number of iterations to change the position of the node
  45050. layoutIterations: 32,
  45051. label: {
  45052. show: true,
  45053. position: 'right',
  45054. color: '#000',
  45055. fontSize: 12
  45056. },
  45057. itemStyle: {
  45058. borderWidth: 1,
  45059. borderColor: '#333'
  45060. },
  45061. lineStyle: {
  45062. color: '#314656',
  45063. opacity: 0.2,
  45064. curveness: 0.5
  45065. },
  45066. emphasis: {
  45067. label: {
  45068. show: true
  45069. },
  45070. lineStyle: {
  45071. opacity: 0.6
  45072. }
  45073. },
  45074. animationEasing: 'linear',
  45075. animationDuration: 1000
  45076. }
  45077. });
  45078. /**
  45079. * @file The file used to draw sankey view
  45080. * @author Deqing Li(annong035@gmail.com)
  45081. */
  45082. var SankeyShape = extendShape({
  45083. shape: {
  45084. x1: 0, y1: 0,
  45085. x2: 0, y2: 0,
  45086. cpx1: 0, cpy1: 0,
  45087. cpx2: 0, cpy2: 0,
  45088. extent: 0
  45089. },
  45090. buildPath: function (ctx, shape) {
  45091. var halfExtent = shape.extent / 2;
  45092. ctx.moveTo(shape.x1, shape.y1 - halfExtent);
  45093. ctx.bezierCurveTo(
  45094. shape.cpx1, shape.cpy1 - halfExtent,
  45095. shape.cpx2, shape.cpy2 - halfExtent,
  45096. shape.x2, shape.y2 - halfExtent
  45097. );
  45098. ctx.lineTo(shape.x2, shape.y2 + halfExtent);
  45099. ctx.bezierCurveTo(
  45100. shape.cpx2, shape.cpy2 + halfExtent,
  45101. shape.cpx1, shape.cpy1 + halfExtent,
  45102. shape.x1, shape.y1 + halfExtent
  45103. );
  45104. ctx.closePath();
  45105. }
  45106. });
  45107. extendChartView({
  45108. type: 'sankey',
  45109. /**
  45110. * @private
  45111. * @type {module:echarts/chart/sankey/SankeySeries}
  45112. */
  45113. _model: null,
  45114. render: function (seriesModel, ecModel, api) {
  45115. var graph = seriesModel.getGraph();
  45116. var group = this.group;
  45117. var layoutInfo = seriesModel.layoutInfo;
  45118. var nodeData = seriesModel.getData();
  45119. var edgeData = seriesModel.getData('edge');
  45120. this._model = seriesModel;
  45121. group.removeAll();
  45122. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  45123. // generate a bezire Curve for each edge
  45124. graph.eachEdge(function (edge) {
  45125. var curve = new SankeyShape();
  45126. curve.dataIndex = edge.dataIndex;
  45127. curve.seriesIndex = seriesModel.seriesIndex;
  45128. curve.dataType = 'edge';
  45129. var lineStyleModel = edge.getModel('lineStyle');
  45130. var curvature = lineStyleModel.get('curveness');
  45131. var n1Layout = edge.node1.getLayout();
  45132. var n2Layout = edge.node2.getLayout();
  45133. var edgeLayout = edge.getLayout();
  45134. curve.shape.extent = Math.max(1, edgeLayout.dy);
  45135. var x1 = n1Layout.x + n1Layout.dx;
  45136. var y1 = n1Layout.y + edgeLayout.sy + edgeLayout.dy / 2;
  45137. var x2 = n2Layout.x;
  45138. var y2 = n2Layout.y + edgeLayout.ty + edgeLayout.dy / 2;
  45139. var cpx1 = x1 * (1 - curvature) + x2 * curvature;
  45140. var cpy1 = y1;
  45141. var cpx2 = x1 * curvature + x2 * (1 - curvature);
  45142. var cpy2 = y2;
  45143. curve.setShape({
  45144. x1: x1,
  45145. y1: y1,
  45146. x2: x2,
  45147. y2: y2,
  45148. cpx1: cpx1,
  45149. cpy1: cpy1,
  45150. cpx2: cpx2,
  45151. cpy2: cpy2
  45152. });
  45153. curve.setStyle(lineStyleModel.getItemStyle());
  45154. // Special color, use source node color or target node color
  45155. switch (curve.style.fill) {
  45156. case 'source':
  45157. curve.style.fill = edge.node1.getVisual('color');
  45158. break;
  45159. case 'target':
  45160. curve.style.fill = edge.node2.getVisual('color');
  45161. break;
  45162. }
  45163. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  45164. group.add(curve);
  45165. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  45166. });
  45167. // generate a rect for each node
  45168. graph.eachNode(function (node) {
  45169. var layout = node.getLayout();
  45170. var itemModel = node.getModel();
  45171. var labelModel = itemModel.getModel('label');
  45172. var labelHoverModel = itemModel.getModel('emphasis.label');
  45173. var rect = new Rect({
  45174. shape: {
  45175. x: layout.x,
  45176. y: layout.y,
  45177. width: node.getLayout().dx,
  45178. height: node.getLayout().dy
  45179. },
  45180. style: itemModel.getModel('itemStyle').getItemStyle()
  45181. });
  45182. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  45183. setLabelStyle(
  45184. rect.style, hoverStyle, labelModel, labelHoverModel,
  45185. {
  45186. labelFetcher: seriesModel,
  45187. labelDataIndex: node.dataIndex,
  45188. defaultText: node.id,
  45189. isRectText: true
  45190. }
  45191. );
  45192. rect.setStyle('fill', node.getVisual('color'));
  45193. setHoverStyle(rect, hoverStyle);
  45194. group.add(rect);
  45195. nodeData.setItemGraphicEl(node.dataIndex, rect);
  45196. rect.dataType = 'node';
  45197. });
  45198. if (!this._data && seriesModel.get('animation')) {
  45199. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  45200. group.removeClipPath();
  45201. }));
  45202. }
  45203. this._data = seriesModel.getData();
  45204. },
  45205. dispose: function () {}
  45206. });
  45207. // add animation to the view
  45208. function createGridClipShape$2(rect, seriesModel, cb) {
  45209. var rectEl = new Rect({
  45210. shape: {
  45211. x: rect.x - 10,
  45212. y: rect.y - 10,
  45213. width: 0,
  45214. height: rect.height + 20
  45215. }
  45216. });
  45217. initProps(rectEl, {
  45218. shape: {
  45219. width: rect.width + 20,
  45220. height: rect.height + 20
  45221. }
  45222. }, seriesModel, cb);
  45223. return rectEl;
  45224. }
  45225. /**
  45226. * nest helper used to group by the array.
  45227. * can specified the keys and sort the keys.
  45228. */
  45229. function nest() {
  45230. var keysFunction = [];
  45231. var sortKeysFunction = [];
  45232. /**
  45233. * map an Array into the mapObject.
  45234. * @param {Array} array
  45235. * @param {number} depth
  45236. */
  45237. function map$$1(array, depth) {
  45238. if (depth >= keysFunction.length) {
  45239. return array;
  45240. }
  45241. var i = -1;
  45242. var n = array.length;
  45243. var keyFunction = keysFunction[depth++];
  45244. var mapObject = {};
  45245. var valuesByKey = {};
  45246. while (++i < n) {
  45247. var keyValue = keyFunction(array[i]);
  45248. var values = valuesByKey[keyValue];
  45249. if (values) {
  45250. values.push(array[i]);
  45251. }
  45252. else {
  45253. valuesByKey[keyValue] = [array[i]];
  45254. }
  45255. }
  45256. each$1(valuesByKey, function (value, key) {
  45257. mapObject[key] = map$$1(value, depth);
  45258. });
  45259. return mapObject;
  45260. }
  45261. /**
  45262. * transform the Map Object to multidimensional Array
  45263. * @param {Object} map
  45264. * @param {number} depth
  45265. */
  45266. function entriesMap(mapObject, depth) {
  45267. if (depth >= keysFunction.length) {
  45268. return mapObject;
  45269. }
  45270. var array = [];
  45271. var sortKeyFunction = sortKeysFunction[depth++];
  45272. each$1(mapObject, function (value, key) {
  45273. array.push({
  45274. key: key, values: entriesMap(value, depth)
  45275. });
  45276. });
  45277. if (sortKeyFunction) {
  45278. return array.sort(function (a, b) {
  45279. return sortKeyFunction(a.key, b.key);
  45280. });
  45281. }
  45282. else {
  45283. return array;
  45284. }
  45285. }
  45286. return {
  45287. /**
  45288. * specified the key to groupby the arrays.
  45289. * users can specified one more keys.
  45290. * @param {Function} d
  45291. */
  45292. key: function (d) {
  45293. keysFunction.push(d);
  45294. return this;
  45295. },
  45296. /**
  45297. * specified the comparator to sort the keys
  45298. * @param {Function} order
  45299. */
  45300. sortKeys: function (order) {
  45301. sortKeysFunction[keysFunction.length - 1] = order;
  45302. return this;
  45303. },
  45304. /**
  45305. * the array to be grouped by.
  45306. * @param {Array} array
  45307. */
  45308. entries: function (array) {
  45309. return entriesMap(map$$1(array, 0), 0);
  45310. }
  45311. };
  45312. }
  45313. /**
  45314. * @file The layout algorithm of sankey view
  45315. * @author Deqing Li(annong035@gmail.com)
  45316. */
  45317. var sankeyLayout = function (ecModel, api, payload) {
  45318. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  45319. var nodeWidth = seriesModel.get('nodeWidth');
  45320. var nodeGap = seriesModel.get('nodeGap');
  45321. var layoutInfo = getViewRect$3(seriesModel, api);
  45322. seriesModel.layoutInfo = layoutInfo;
  45323. var width = layoutInfo.width;
  45324. var height = layoutInfo.height;
  45325. var graph = seriesModel.getGraph();
  45326. var nodes = graph.nodes;
  45327. var edges = graph.edges;
  45328. computeNodeValues(nodes);
  45329. var filteredNodes = filter(nodes, function (node) {
  45330. return node.getLayout().value === 0;
  45331. });
  45332. var iterations = filteredNodes.length !== 0
  45333. ? 0 : seriesModel.get('layoutIterations');
  45334. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations);
  45335. });
  45336. };
  45337. /**
  45338. * Get the layout position of the whole view
  45339. *
  45340. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  45341. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  45342. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  45343. */
  45344. function getViewRect$3(seriesModel, api) {
  45345. return getLayoutRect(
  45346. seriesModel.getBoxLayoutParams(), {
  45347. width: api.getWidth(),
  45348. height: api.getHeight()
  45349. }
  45350. );
  45351. }
  45352. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations) {
  45353. computeNodeBreadths(nodes, nodeWidth, width);
  45354. computeNodeDepths(nodes, edges, height, nodeGap, iterations);
  45355. computeEdgeDepths(nodes);
  45356. }
  45357. /**
  45358. * Compute the value of each node by summing the associated edge's value
  45359. *
  45360. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45361. */
  45362. function computeNodeValues(nodes) {
  45363. each$1(nodes, function (node) {
  45364. var value1 = sum(node.outEdges, getEdgeValue);
  45365. var value2 = sum(node.inEdges, getEdgeValue);
  45366. var value = Math.max(value1, value2);
  45367. node.setLayout({value: value}, true);
  45368. });
  45369. }
  45370. /**
  45371. * Compute the x-position for each node
  45372. *
  45373. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45374. * @param {number} nodeWidth the dx of the node
  45375. * @param {number} width the whole width of the area to draw the view
  45376. */
  45377. function computeNodeBreadths(nodes, nodeWidth, width) {
  45378. var remainNodes = nodes;
  45379. var nextNode = null;
  45380. var x = 0;
  45381. var kx = 0;
  45382. while (remainNodes.length) {
  45383. nextNode = [];
  45384. for (var i = 0, len = remainNodes.length; i < len; i++) {
  45385. var node = remainNodes[i];
  45386. node.setLayout({x: x}, true);
  45387. node.setLayout({dx: nodeWidth}, true);
  45388. for (var j = 0, lenj = node.outEdges.length; j < lenj; j++) {
  45389. nextNode.push(node.outEdges[j].node2);
  45390. }
  45391. }
  45392. remainNodes = nextNode;
  45393. ++x;
  45394. }
  45395. moveSinksRight(nodes, x);
  45396. kx = (width - nodeWidth) / (x - 1);
  45397. scaleNodeBreadths(nodes, kx);
  45398. }
  45399. /**
  45400. * All the node without outEgdes are assigned maximum x-position and
  45401. * be aligned in the last column.
  45402. *
  45403. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45404. * @param {number} x value (x-1) use to assign to node without outEdges
  45405. * as x-position
  45406. */
  45407. function moveSinksRight(nodes, x) {
  45408. each$1(nodes, function (node) {
  45409. if (!node.outEdges.length) {
  45410. node.setLayout({x: x - 1}, true);
  45411. }
  45412. });
  45413. }
  45414. /**
  45415. * Scale node x-position to the width
  45416. *
  45417. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45418. * @param {number} kx multiple used to scale nodes
  45419. */
  45420. function scaleNodeBreadths(nodes, kx) {
  45421. each$1(nodes, function (node) {
  45422. var nodeX = node.getLayout().x * kx;
  45423. node.setLayout({x: nodeX}, true);
  45424. });
  45425. }
  45426. /**
  45427. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  45428. *
  45429. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45430. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  45431. * @param {number} height the whole height of the area to draw the view
  45432. * @param {number} nodeGap the vertical distance between two nodes
  45433. * in the same column.
  45434. * @param {number} iterations the number of iterations for the algorithm
  45435. */
  45436. function computeNodeDepths(nodes, edges, height, nodeGap, iterations) {
  45437. var nodesByBreadth = nest()
  45438. .key(function (d) {
  45439. return d.getLayout().x;
  45440. })
  45441. .sortKeys(ascending)
  45442. .entries(nodes)
  45443. .map(function (d) {
  45444. return d.values;
  45445. });
  45446. initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap);
  45447. resolveCollisions(nodesByBreadth, nodeGap, height);
  45448. for (var alpha = 1; iterations > 0; iterations--) {
  45449. // 0.99 is a experience parameter, ensure that each iterations of
  45450. // changes as small as possible.
  45451. alpha *= 0.99;
  45452. relaxRightToLeft(nodesByBreadth, alpha);
  45453. resolveCollisions(nodesByBreadth, nodeGap, height);
  45454. relaxLeftToRight(nodesByBreadth, alpha);
  45455. resolveCollisions(nodesByBreadth, nodeGap, height);
  45456. }
  45457. }
  45458. /**
  45459. * Compute the original y-position for each node
  45460. *
  45461. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45462. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  45463. * group by the array of all sankey nodes based on the nodes x-position.
  45464. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  45465. * @param {number} height the whole height of the area to draw the view
  45466. * @param {number} nodeGap the vertical distance between two nodes
  45467. */
  45468. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap) {
  45469. var kyArray = [];
  45470. each$1(nodesByBreadth, function (nodes) {
  45471. var n = nodes.length;
  45472. var sum = 0;
  45473. each$1(nodes, function (node) {
  45474. sum += node.getLayout().value;
  45475. });
  45476. var ky = (height - (n - 1) * nodeGap) / sum;
  45477. kyArray.push(ky);
  45478. });
  45479. kyArray.sort(function (a, b) {
  45480. return a - b;
  45481. });
  45482. var ky0 = kyArray[0];
  45483. each$1(nodesByBreadth, function (nodes) {
  45484. each$1(nodes, function (node, i) {
  45485. node.setLayout({y: i}, true);
  45486. var nodeDy = node.getLayout().value * ky0;
  45487. node.setLayout({dy: nodeDy}, true);
  45488. });
  45489. });
  45490. each$1(edges, function (edge) {
  45491. var edgeDy = +edge.getValue() * ky0;
  45492. edge.setLayout({dy: edgeDy}, true);
  45493. });
  45494. }
  45495. /**
  45496. * Resolve the collision of initialized depth (y-position)
  45497. *
  45498. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  45499. * group by the array of all sankey nodes based on the nodes x-position.
  45500. * @param {number} nodeGap the vertical distance between two nodes
  45501. * @param {number} height the whole height of the area to draw the view
  45502. */
  45503. function resolveCollisions(nodesByBreadth, nodeGap, height) {
  45504. each$1(nodesByBreadth, function (nodes) {
  45505. var node;
  45506. var dy;
  45507. var y0 = 0;
  45508. var n = nodes.length;
  45509. var i;
  45510. nodes.sort(ascendingDepth);
  45511. for (i = 0; i < n; i++) {
  45512. node = nodes[i];
  45513. dy = y0 - node.getLayout().y;
  45514. if (dy > 0) {
  45515. var nodeY = node.getLayout().y + dy;
  45516. node.setLayout({y: nodeY}, true);
  45517. }
  45518. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  45519. }
  45520. // if the bottommost node goes outside the bounds, push it back up
  45521. dy = y0 - nodeGap - height;
  45522. if (dy > 0) {
  45523. var nodeY = node.getLayout().y - dy;
  45524. node.setLayout({y: nodeY}, true);
  45525. y0 = node.getLayout().y;
  45526. for (i = n - 2; i >= 0; --i) {
  45527. node = nodes[i];
  45528. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  45529. if (dy > 0) {
  45530. nodeY = node.getLayout().y - dy;
  45531. node.setLayout({y: nodeY}, true);
  45532. }
  45533. y0 = node.getLayout().y;
  45534. }
  45535. }
  45536. });
  45537. }
  45538. /**
  45539. * Change the y-position of the nodes, except most the right side nodes
  45540. *
  45541. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  45542. * group by the array of all sankey nodes based on the node x-position.
  45543. * @param {number} alpha parameter used to adjust the nodes y-position
  45544. */
  45545. function relaxRightToLeft(nodesByBreadth, alpha) {
  45546. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  45547. each$1(nodes, function (node) {
  45548. if (node.outEdges.length) {
  45549. var y = sum(node.outEdges, weightedTarget) / sum(node.outEdges, getEdgeValue);
  45550. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  45551. node.setLayout({y: nodeY}, true);
  45552. }
  45553. });
  45554. });
  45555. }
  45556. function weightedTarget(edge) {
  45557. return center$1(edge.node2) * edge.getValue();
  45558. }
  45559. /**
  45560. * Change the y-position of the nodes, except most the left side nodes
  45561. *
  45562. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  45563. * group by the array of all sankey nodes based on the node x-position.
  45564. * @param {number} alpha parameter used to adjust the nodes y-position
  45565. */
  45566. function relaxLeftToRight(nodesByBreadth, alpha) {
  45567. each$1(nodesByBreadth, function (nodes) {
  45568. each$1(nodes, function (node) {
  45569. if (node.inEdges.length) {
  45570. var y = sum(node.inEdges, weightedSource) / sum(node.inEdges, getEdgeValue);
  45571. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  45572. node.setLayout({y: nodeY}, true);
  45573. }
  45574. });
  45575. });
  45576. }
  45577. function weightedSource(edge) {
  45578. return center$1(edge.node1) * edge.getValue();
  45579. }
  45580. /**
  45581. * Compute the depth(y-position) of each edge
  45582. *
  45583. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  45584. */
  45585. function computeEdgeDepths(nodes) {
  45586. each$1(nodes, function (node) {
  45587. node.outEdges.sort(ascendingTargetDepth);
  45588. node.inEdges.sort(ascendingSourceDepth);
  45589. });
  45590. each$1(nodes, function (node) {
  45591. var sy = 0;
  45592. var ty = 0;
  45593. each$1(node.outEdges, function (edge) {
  45594. edge.setLayout({sy: sy}, true);
  45595. sy += edge.getLayout().dy;
  45596. });
  45597. each$1(node.inEdges, function (edge) {
  45598. edge.setLayout({ty: ty}, true);
  45599. ty += edge.getLayout().dy;
  45600. });
  45601. });
  45602. }
  45603. function ascendingTargetDepth(a, b) {
  45604. return a.node2.getLayout().y - b.node2.getLayout().y;
  45605. }
  45606. function ascendingSourceDepth(a, b) {
  45607. return a.node1.getLayout().y - b.node1.getLayout().y;
  45608. }
  45609. function sum(array, f) {
  45610. var sum = 0;
  45611. var len = array.length;
  45612. var i = -1;
  45613. while (++i < len) {
  45614. var value = +f.call(array, array[i], i);
  45615. if (!isNaN(value)) {
  45616. sum += value;
  45617. }
  45618. }
  45619. return sum;
  45620. }
  45621. function center$1(node) {
  45622. return node.getLayout().y + node.getLayout().dy / 2;
  45623. }
  45624. function ascendingDepth(a, b) {
  45625. return a.getLayout().y - b.getLayout().y;
  45626. }
  45627. function ascending(a, b) {
  45628. return a < b ? -1 : a > b ? 1 : a === b ? 0 : NaN;
  45629. }
  45630. function getEdgeValue(edge) {
  45631. return edge.getValue();
  45632. }
  45633. /**
  45634. * @file Visual encoding for sankey view
  45635. * @author Deqing Li(annong035@gmail.com)
  45636. */
  45637. var sankeyVisual = function (ecModel, payload) {
  45638. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  45639. var graph = seriesModel.getGraph();
  45640. var nodes = graph.nodes;
  45641. nodes.sort(function (a, b) {
  45642. return a.getLayout().value - b.getLayout().value;
  45643. });
  45644. var minValue = nodes[0].getLayout().value;
  45645. var maxValue = nodes[nodes.length - 1].getLayout().value;
  45646. each$1(nodes, function (node) {
  45647. var mapping = new VisualMapping({
  45648. type: 'color',
  45649. mappingMethod: 'linear',
  45650. dataExtent: [minValue, maxValue],
  45651. visual: seriesModel.get('color')
  45652. });
  45653. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  45654. node.setVisual('color', mapValueToColor);
  45655. // If set itemStyle.normal.color
  45656. var itemModel = node.getModel();
  45657. var customColor = itemModel.get('itemStyle.color');
  45658. if (customColor != null) {
  45659. node.setVisual('color', customColor);
  45660. }
  45661. });
  45662. });
  45663. };
  45664. registerLayout(sankeyLayout);
  45665. registerVisual(sankeyVisual);
  45666. /**
  45667. * @module echarts/chart/helper/Symbol
  45668. */
  45669. var WhiskerPath = Path.extend({
  45670. type: 'whiskerInBox',
  45671. shape: {},
  45672. buildPath: function (ctx, shape) {
  45673. for (var i in shape) {
  45674. if (shape.hasOwnProperty(i) && i.indexOf('ends') === 0) {
  45675. var pts = shape[i];
  45676. ctx.moveTo(pts[0][0], pts[0][1]);
  45677. ctx.lineTo(pts[1][0], pts[1][1]);
  45678. }
  45679. }
  45680. }
  45681. });
  45682. /**
  45683. * @constructor
  45684. * @alias {module:echarts/chart/helper/WhiskerBox}
  45685. * @param {module:echarts/data/List} data
  45686. * @param {number} idx
  45687. * @param {Function} styleUpdater
  45688. * @param {boolean} isInit
  45689. * @extends {module:zrender/graphic/Group}
  45690. */
  45691. function WhiskerBox(data, idx, styleUpdater, isInit) {
  45692. Group.call(this);
  45693. /**
  45694. * @type {number}
  45695. * @readOnly
  45696. */
  45697. this.bodyIndex;
  45698. /**
  45699. * @type {number}
  45700. * @readOnly
  45701. */
  45702. this.whiskerIndex;
  45703. /**
  45704. * @type {Function}
  45705. */
  45706. this.styleUpdater = styleUpdater;
  45707. this._createContent(data, idx, isInit);
  45708. this.updateData(data, idx, isInit);
  45709. /**
  45710. * Last series model.
  45711. * @type {module:echarts/model/Series}
  45712. */
  45713. this._seriesModel;
  45714. }
  45715. var whiskerBoxProto = WhiskerBox.prototype;
  45716. whiskerBoxProto._createContent = function (data, idx, isInit) {
  45717. var itemLayout = data.getItemLayout(idx);
  45718. var constDim = itemLayout.chartLayout === 'horizontal' ? 1 : 0;
  45719. var count = 0;
  45720. // Whisker element.
  45721. this.add(new Polygon({
  45722. shape: {
  45723. points: isInit
  45724. ? transInit(itemLayout.bodyEnds, constDim, itemLayout)
  45725. : itemLayout.bodyEnds
  45726. },
  45727. style: {strokeNoScale: true},
  45728. z2: 100
  45729. }));
  45730. this.bodyIndex = count++;
  45731. // Box element.
  45732. var whiskerEnds = map(itemLayout.whiskerEnds, function (ends) {
  45733. return isInit ? transInit(ends, constDim, itemLayout) : ends;
  45734. });
  45735. this.add(new WhiskerPath({
  45736. shape: makeWhiskerEndsShape(whiskerEnds),
  45737. style: {strokeNoScale: true},
  45738. z2: 100
  45739. }));
  45740. this.whiskerIndex = count++;
  45741. };
  45742. function transInit(points, dim, itemLayout) {
  45743. return map(points, function (point) {
  45744. point = point.slice();
  45745. point[dim] = itemLayout.initBaseline;
  45746. return point;
  45747. });
  45748. }
  45749. function makeWhiskerEndsShape(whiskerEnds) {
  45750. // zr animation only support 2-dim array.
  45751. var shape = {};
  45752. each$1(whiskerEnds, function (ends, i) {
  45753. shape['ends' + i] = ends;
  45754. });
  45755. return shape;
  45756. }
  45757. /**
  45758. * Update symbol properties
  45759. * @param {module:echarts/data/List} data
  45760. * @param {number} idx
  45761. */
  45762. whiskerBoxProto.updateData = function (data, idx, isInit) {
  45763. var seriesModel = this._seriesModel = data.hostModel;
  45764. var itemLayout = data.getItemLayout(idx);
  45765. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  45766. // this.childAt(this.bodyIndex).stopAnimation(true);
  45767. // this.childAt(this.whiskerIndex).stopAnimation(true);
  45768. updateMethod(
  45769. this.childAt(this.bodyIndex),
  45770. {shape: {points: itemLayout.bodyEnds}},
  45771. seriesModel, idx
  45772. );
  45773. updateMethod(
  45774. this.childAt(this.whiskerIndex),
  45775. {shape: makeWhiskerEndsShape(itemLayout.whiskerEnds)},
  45776. seriesModel, idx
  45777. );
  45778. this.styleUpdater.call(null, this, data, idx);
  45779. };
  45780. inherits(WhiskerBox, Group);
  45781. /**
  45782. * @constructor
  45783. * @alias module:echarts/chart/helper/WhiskerBoxDraw
  45784. */
  45785. function WhiskerBoxDraw(styleUpdater) {
  45786. this.group = new Group();
  45787. this.styleUpdater = styleUpdater;
  45788. }
  45789. var whiskerBoxDrawProto = WhiskerBoxDraw.prototype;
  45790. /**
  45791. * Update symbols draw by new data
  45792. * @param {module:echarts/data/List} data
  45793. */
  45794. whiskerBoxDrawProto.updateData = function (data) {
  45795. var group = this.group;
  45796. var oldData = this._data;
  45797. var styleUpdater = this.styleUpdater;
  45798. // There is no old data only when first rendering or switching from
  45799. // stream mode to normal mode, where previous elements should be removed.
  45800. if (!this._data) {
  45801. group.removeAll();
  45802. }
  45803. data.diff(oldData)
  45804. .add(function (newIdx) {
  45805. if (data.hasValue(newIdx)) {
  45806. var symbolEl = new WhiskerBox(data, newIdx, styleUpdater, true);
  45807. data.setItemGraphicEl(newIdx, symbolEl);
  45808. group.add(symbolEl);
  45809. }
  45810. })
  45811. .update(function (newIdx, oldIdx) {
  45812. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  45813. // Empty data
  45814. if (!data.hasValue(newIdx)) {
  45815. group.remove(symbolEl);
  45816. return;
  45817. }
  45818. if (!symbolEl) {
  45819. symbolEl = new WhiskerBox(data, newIdx, styleUpdater);
  45820. }
  45821. else {
  45822. symbolEl.updateData(data, newIdx);
  45823. }
  45824. // Add back
  45825. group.add(symbolEl);
  45826. data.setItemGraphicEl(newIdx, symbolEl);
  45827. })
  45828. .remove(function (oldIdx) {
  45829. var el = oldData.getItemGraphicEl(oldIdx);
  45830. el && group.remove(el);
  45831. })
  45832. .execute();
  45833. this._data = data;
  45834. };
  45835. whiskerBoxDrawProto.incrementalPrepareUpdate = function (seriesModel, ecModel, api) {
  45836. this.group.removeAll();
  45837. this._data = null;
  45838. };
  45839. whiskerBoxDrawProto.incrementalUpdate = function (params, seriesModel, ecModel, api) {
  45840. var data = seriesModel.getData();
  45841. for (var idx = params.start; idx < params.end; idx++) {
  45842. var symbolEl = new WhiskerBox(data, idx, this.styleUpdater, true);
  45843. symbolEl.incremental = true;
  45844. this.group.add(symbolEl);
  45845. }
  45846. };
  45847. /**
  45848. * Remove symbols.
  45849. * @param {module:echarts/data/List} data
  45850. */
  45851. whiskerBoxDrawProto.remove = function () {
  45852. var group = this.group;
  45853. var data = this._data;
  45854. this._data = null;
  45855. data && data.eachItemGraphicEl(function (el) {
  45856. el && group.remove(el);
  45857. });
  45858. };
  45859. var seriesModelMixin = {
  45860. /**
  45861. * @private
  45862. * @type {string}
  45863. */
  45864. _baseAxisDim: null,
  45865. /**
  45866. * @override
  45867. */
  45868. getInitialData: function (option, ecModel) {
  45869. // When both types of xAxis and yAxis are 'value', layout is
  45870. // needed to be specified by user. Otherwise, layout can be
  45871. // judged by which axis is category.
  45872. var ordinalMeta;
  45873. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  45874. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  45875. var xAxisType = xAxisModel.get('type');
  45876. var yAxisType = yAxisModel.get('type');
  45877. var addOrdinal;
  45878. // FIXME
  45879. // 考虑时间轴
  45880. if (xAxisType === 'category') {
  45881. option.layout = 'horizontal';
  45882. ordinalMeta = xAxisModel.getOrdinalMeta();
  45883. addOrdinal = true;
  45884. }
  45885. else if (yAxisType === 'category') {
  45886. option.layout = 'vertical';
  45887. ordinalMeta = yAxisModel.getOrdinalMeta();
  45888. addOrdinal = true;
  45889. }
  45890. else {
  45891. option.layout = option.layout || 'horizontal';
  45892. }
  45893. var coordDims = ['x', 'y'];
  45894. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  45895. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  45896. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  45897. var axisModels = [xAxisModel, yAxisModel];
  45898. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  45899. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  45900. var data = option.data;
  45901. // ??? FIXME make a stage to perform data transfrom.
  45902. // MUST create a new data, consider setOption({}) again.
  45903. if (data && addOrdinal) {
  45904. var newOptionData = [];
  45905. each$1(data, function (item, index) {
  45906. var newItem;
  45907. if (item.value && isArray(item.value)) {
  45908. newItem = item.value.slice();
  45909. item.value.unshift(index);
  45910. }
  45911. else if (isArray(item)) {
  45912. newItem = item.slice();
  45913. item.unshift(index);
  45914. }
  45915. else {
  45916. newItem = item;
  45917. }
  45918. newOptionData.push(newItem);
  45919. });
  45920. option.data = newOptionData;
  45921. }
  45922. var defaultValueDimensions = this.defaultValueDimensions;
  45923. return createListSimply(
  45924. this,
  45925. {
  45926. coordDimensions: [{
  45927. name: baseAxisDim,
  45928. type: getDimensionTypeByAxis(baseAxisType),
  45929. ordinalMeta: ordinalMeta,
  45930. otherDims: {
  45931. tooltip: false,
  45932. itemName: 0
  45933. },
  45934. dimsDef: ['base']
  45935. }, {
  45936. name: otherAxisDim,
  45937. type: getDimensionTypeByAxis(otherAxisType),
  45938. dimsDef: defaultValueDimensions.slice()
  45939. }],
  45940. dimensionsCount: defaultValueDimensions.length + 1
  45941. }
  45942. );
  45943. },
  45944. /**
  45945. * If horizontal, base axis is x, otherwise y.
  45946. * @override
  45947. */
  45948. getBaseAxis: function () {
  45949. var dim = this._baseAxisDim;
  45950. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  45951. }
  45952. };
  45953. var viewMixin = {
  45954. init: function () {
  45955. /**
  45956. * Old data.
  45957. * @private
  45958. * @type {module:echarts/chart/helper/WhiskerBoxDraw}
  45959. */
  45960. var whiskerBoxDraw = this._whiskerBoxDraw = new WhiskerBoxDraw(
  45961. this.getStyleUpdater()
  45962. );
  45963. this.group.add(whiskerBoxDraw.group);
  45964. },
  45965. render: function (seriesModel, ecModel, api) {
  45966. this._whiskerBoxDraw.updateData(seriesModel.getData());
  45967. },
  45968. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  45969. this._whiskerBoxDraw.incrementalPrepareUpdate(seriesModel, ecModel, api);
  45970. },
  45971. incrementalRender: function (params, seriesModel, ecModel, api) {
  45972. this._whiskerBoxDraw.incrementalUpdate(params, seriesModel, ecModel, api);
  45973. },
  45974. remove: function (ecModel) {
  45975. this._whiskerBoxDraw.remove();
  45976. }
  45977. };
  45978. var BoxplotSeries = SeriesModel.extend({
  45979. type: 'series.boxplot',
  45980. dependencies: ['xAxis', 'yAxis', 'grid'],
  45981. // TODO
  45982. // box width represents group size, so dimension should have 'size'.
  45983. /**
  45984. * @see <https://en.wikipedia.org/wiki/Box_plot>
  45985. * The meanings of 'min' and 'max' depend on user,
  45986. * and echarts do not need to know it.
  45987. * @readOnly
  45988. */
  45989. defaultValueDimensions: ['min', 'Q1', 'median', 'Q3', 'max'],
  45990. /**
  45991. * @type {Array.<string>}
  45992. * @readOnly
  45993. */
  45994. dimensions: null,
  45995. /**
  45996. * @override
  45997. */
  45998. defaultOption: {
  45999. zlevel: 0, // 一级层叠
  46000. z: 2, // 二级层叠
  46001. coordinateSystem: 'cartesian2d',
  46002. legendHoverLink: true,
  46003. hoverAnimation: true,
  46004. // xAxisIndex: 0,
  46005. // yAxisIndex: 0,
  46006. layout: null, // 'horizontal' or 'vertical'
  46007. boxWidth: [7, 50], // [min, max] can be percent of band width.
  46008. itemStyle: {
  46009. color: '#fff',
  46010. borderWidth: 1
  46011. },
  46012. emphasis: {
  46013. itemStyle: {
  46014. borderWidth: 2,
  46015. shadowBlur: 5,
  46016. shadowOffsetX: 2,
  46017. shadowOffsetY: 2,
  46018. shadowColor: 'rgba(0,0,0,0.4)'
  46019. }
  46020. },
  46021. animationEasing: 'elasticOut',
  46022. animationDuration: 800
  46023. }
  46024. });
  46025. mixin(BoxplotSeries, seriesModelMixin, true);
  46026. var BoxplotView = Chart.extend({
  46027. type: 'boxplot',
  46028. getStyleUpdater: function () {
  46029. return updateStyle$1;
  46030. },
  46031. dispose: noop
  46032. });
  46033. mixin(BoxplotView, viewMixin, true);
  46034. // Update common properties
  46035. var normalStyleAccessPath$1 = ['itemStyle'];
  46036. var emphasisStyleAccessPath$1 = ['emphasis', 'itemStyle'];
  46037. function updateStyle$1(itemGroup, data, idx) {
  46038. var itemModel = data.getItemModel(idx);
  46039. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$1);
  46040. var borderColor = data.getItemVisual(idx, 'color');
  46041. // Exclude borderColor.
  46042. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  46043. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  46044. whiskerEl.style.set(itemStyle);
  46045. whiskerEl.style.stroke = borderColor;
  46046. whiskerEl.dirty();
  46047. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  46048. bodyEl.style.set(itemStyle);
  46049. bodyEl.style.stroke = borderColor;
  46050. bodyEl.dirty();
  46051. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$1).getItemStyle();
  46052. setHoverStyle(itemGroup, hoverStyle);
  46053. }
  46054. var borderColorQuery = ['itemStyle', 'borderColor'];
  46055. var boxplotVisual = function (ecModel, api) {
  46056. var globalColors = ecModel.get('color');
  46057. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  46058. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  46059. var data = seriesModel.getData();
  46060. data.setVisual({
  46061. legendSymbol: 'roundRect',
  46062. // Use name 'color' but not 'borderColor' for legend usage and
  46063. // visual coding from other component like dataRange.
  46064. color: seriesModel.get(borderColorQuery) || defaulColor
  46065. });
  46066. // Only visible series has each data be visual encoded
  46067. if (!ecModel.isSeriesFiltered(seriesModel)) {
  46068. data.each(function (idx) {
  46069. var itemModel = data.getItemModel(idx);
  46070. data.setItemVisual(
  46071. idx,
  46072. {color: itemModel.get(borderColorQuery, true)}
  46073. );
  46074. });
  46075. }
  46076. });
  46077. };
  46078. var each$14 = each$1;
  46079. var boxplotLayout = function (ecModel) {
  46080. var groupResult = groupSeriesByAxis(ecModel);
  46081. each$14(groupResult, function (groupItem) {
  46082. var seriesModels = groupItem.seriesModels;
  46083. if (!seriesModels.length) {
  46084. return;
  46085. }
  46086. calculateBase(groupItem);
  46087. each$14(seriesModels, function (seriesModel, idx) {
  46088. layoutSingleSeries(
  46089. seriesModel,
  46090. groupItem.boxOffsetList[idx],
  46091. groupItem.boxWidthList[idx]
  46092. );
  46093. });
  46094. });
  46095. };
  46096. /**
  46097. * Group series by axis.
  46098. */
  46099. function groupSeriesByAxis(ecModel) {
  46100. var result = [];
  46101. var axisList = [];
  46102. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  46103. var baseAxis = seriesModel.getBaseAxis();
  46104. var idx = indexOf(axisList, baseAxis);
  46105. if (idx < 0) {
  46106. idx = axisList.length;
  46107. axisList[idx] = baseAxis;
  46108. result[idx] = {axis: baseAxis, seriesModels: []};
  46109. }
  46110. result[idx].seriesModels.push(seriesModel);
  46111. });
  46112. return result;
  46113. }
  46114. /**
  46115. * Calculate offset and box width for each series.
  46116. */
  46117. function calculateBase(groupItem) {
  46118. var extent;
  46119. var baseAxis = groupItem.axis;
  46120. var seriesModels = groupItem.seriesModels;
  46121. var seriesCount = seriesModels.length;
  46122. var boxWidthList = groupItem.boxWidthList = [];
  46123. var boxOffsetList = groupItem.boxOffsetList = [];
  46124. var boundList = [];
  46125. var bandWidth;
  46126. if (baseAxis.type === 'category') {
  46127. bandWidth = baseAxis.getBandWidth();
  46128. }
  46129. else {
  46130. var maxDataCount = 0;
  46131. each$14(seriesModels, function (seriesModel) {
  46132. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  46133. });
  46134. extent = baseAxis.getExtent(),
  46135. Math.abs(extent[1] - extent[0]) / maxDataCount;
  46136. }
  46137. each$14(seriesModels, function (seriesModel) {
  46138. var boxWidthBound = seriesModel.get('boxWidth');
  46139. if (!isArray(boxWidthBound)) {
  46140. boxWidthBound = [boxWidthBound, boxWidthBound];
  46141. }
  46142. boundList.push([
  46143. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  46144. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  46145. ]);
  46146. });
  46147. var availableWidth = bandWidth * 0.8 - 2;
  46148. var boxGap = availableWidth / seriesCount * 0.3;
  46149. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  46150. var base = boxWidth / 2 - availableWidth / 2;
  46151. each$14(seriesModels, function (seriesModel, idx) {
  46152. boxOffsetList.push(base);
  46153. base += boxGap + boxWidth;
  46154. boxWidthList.push(
  46155. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  46156. );
  46157. });
  46158. }
  46159. /**
  46160. * Calculate points location for each series.
  46161. */
  46162. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  46163. var coordSys = seriesModel.coordinateSystem;
  46164. var data = seriesModel.getData();
  46165. var halfWidth = boxWidth / 2;
  46166. var chartLayout = seriesModel.get('layout');
  46167. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  46168. var constDim = 1 - variableDim;
  46169. var coordDims = ['x', 'y'];
  46170. var vDims = [];
  46171. var cDim;
  46172. each$1(data.dimensions, function (dimName) {
  46173. var dimInfo = data.getDimensionInfo(dimName);
  46174. var coordDim = dimInfo.coordDim;
  46175. if (coordDim === coordDims[constDim]) {
  46176. vDims.push(dimName);
  46177. }
  46178. else if (coordDim === coordDims[variableDim]) {
  46179. cDim = dimName;
  46180. }
  46181. });
  46182. if (cDim == null || vDims.length < 5) {
  46183. return;
  46184. }
  46185. data.each([cDim].concat(vDims), function () {
  46186. var args = arguments;
  46187. var axisDimVal = args[0];
  46188. var idx = args[vDims.length + 1];
  46189. var median = getPoint(args[3]);
  46190. var end1 = getPoint(args[1]);
  46191. var end5 = getPoint(args[5]);
  46192. var whiskerEnds = [
  46193. [end1, getPoint(args[2])],
  46194. [end5, getPoint(args[4])]
  46195. ];
  46196. layEndLine(end1);
  46197. layEndLine(end5);
  46198. layEndLine(median);
  46199. var bodyEnds = [];
  46200. addBodyEnd(whiskerEnds[0][1], 0);
  46201. addBodyEnd(whiskerEnds[1][1], 1);
  46202. data.setItemLayout(idx, {
  46203. chartLayout: chartLayout,
  46204. initBaseline: median[constDim],
  46205. median: median,
  46206. bodyEnds: bodyEnds,
  46207. whiskerEnds: whiskerEnds
  46208. });
  46209. function getPoint(val) {
  46210. var p = [];
  46211. p[variableDim] = axisDimVal;
  46212. p[constDim] = val;
  46213. var point;
  46214. if (isNaN(axisDimVal) || isNaN(val)) {
  46215. point = [NaN, NaN];
  46216. }
  46217. else {
  46218. point = coordSys.dataToPoint(p);
  46219. point[variableDim] += offset;
  46220. }
  46221. return point;
  46222. }
  46223. function addBodyEnd(point, start) {
  46224. var point1 = point.slice();
  46225. var point2 = point.slice();
  46226. point1[variableDim] += halfWidth;
  46227. point2[variableDim] -= halfWidth;
  46228. start
  46229. ? bodyEnds.push(point1, point2)
  46230. : bodyEnds.push(point2, point1);
  46231. }
  46232. function layEndLine(endCenter) {
  46233. var line = [endCenter.slice(), endCenter.slice()];
  46234. line[0][variableDim] -= halfWidth;
  46235. line[1][variableDim] += halfWidth;
  46236. whiskerEnds.push(line);
  46237. }
  46238. });
  46239. }
  46240. registerVisual(boxplotVisual);
  46241. registerLayout(boxplotLayout);
  46242. var CandlestickSeries = SeriesModel.extend({
  46243. type: 'series.candlestick',
  46244. dependencies: ['xAxis', 'yAxis', 'grid'],
  46245. /**
  46246. * @readOnly
  46247. */
  46248. defaultValueDimensions: ['open', 'close', 'lowest', 'highest'],
  46249. /**
  46250. * @type {Array.<string>}
  46251. * @readOnly
  46252. */
  46253. dimensions: null,
  46254. /**
  46255. * @override
  46256. */
  46257. defaultOption: {
  46258. zlevel: 0, // 一级层叠
  46259. z: 2, // 二级层叠
  46260. coordinateSystem: 'cartesian2d',
  46261. legendHoverLink: true,
  46262. hoverAnimation: true,
  46263. // xAxisIndex: 0,
  46264. // yAxisIndex: 0,
  46265. layout: null, // 'horizontal' or 'vertical'
  46266. itemStyle: {
  46267. color: '#c23531', // 阳线 positive
  46268. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  46269. borderWidth: 1,
  46270. // FIXME
  46271. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  46272. borderColor: '#c23531',
  46273. borderColor0: '#314656'
  46274. },
  46275. emphasis: {
  46276. itemStyle: {
  46277. borderWidth: 2
  46278. }
  46279. },
  46280. barMaxWidth: null,
  46281. barMinWidth: null,
  46282. barWidth: null,
  46283. animationUpdate: false,
  46284. animationEasing: 'linear',
  46285. animationDuration: 300
  46286. },
  46287. /**
  46288. * Get dimension for shadow in dataZoom
  46289. * @return {string} dimension name
  46290. */
  46291. getShadowDim: function () {
  46292. return 'open';
  46293. },
  46294. brushSelector: function (dataIndex, data, selectors) {
  46295. var itemLayout = data.getItemLayout(dataIndex);
  46296. return selectors.rect(itemLayout.brushRect);
  46297. }
  46298. });
  46299. mixin(CandlestickSeries, seriesModelMixin, true);
  46300. var CandlestickView = Chart.extend({
  46301. type: 'candlestick',
  46302. getStyleUpdater: function () {
  46303. return updateStyle$2;
  46304. },
  46305. dispose: noop
  46306. });
  46307. mixin(CandlestickView, viewMixin, true);
  46308. // Update common properties
  46309. var normalStyleAccessPath$2 = ['itemStyle'];
  46310. var emphasisStyleAccessPath$2 = ['emphasis', 'itemStyle'];
  46311. function updateStyle$2(itemGroup, data, idx) {
  46312. var itemModel = data.getItemModel(idx);
  46313. var normalItemStyleModel = itemModel.getModel(normalStyleAccessPath$2);
  46314. var color = data.getItemVisual(idx, 'color');
  46315. var borderColor = data.getItemVisual(idx, 'borderColor') || color;
  46316. // Color must be excluded.
  46317. // Because symbol provide setColor individually to set fill and stroke
  46318. var itemStyle = normalItemStyleModel.getItemStyle(
  46319. ['color', 'color0', 'borderColor', 'borderColor0']
  46320. );
  46321. var whiskerEl = itemGroup.childAt(itemGroup.whiskerIndex);
  46322. whiskerEl.useStyle(itemStyle);
  46323. whiskerEl.style.stroke = borderColor;
  46324. var bodyEl = itemGroup.childAt(itemGroup.bodyIndex);
  46325. bodyEl.useStyle(itemStyle);
  46326. bodyEl.style.fill = color;
  46327. bodyEl.style.stroke = borderColor;
  46328. var hoverStyle = itemModel.getModel(emphasisStyleAccessPath$2).getItemStyle();
  46329. setHoverStyle(itemGroup, hoverStyle);
  46330. }
  46331. var preprocessor = function (option) {
  46332. if (!option || !isArray(option.series)) {
  46333. return;
  46334. }
  46335. // Translate 'k' to 'candlestick'.
  46336. each$1(option.series, function (seriesItem) {
  46337. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  46338. seriesItem.type = 'candlestick';
  46339. }
  46340. });
  46341. };
  46342. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  46343. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  46344. var positiveColorQuery = ['itemStyle', 'color'];
  46345. var negativeColorQuery = ['itemStyle', 'color0'];
  46346. var candlestickVisual = function (ecModel, api) {
  46347. ecModel.eachRawSeriesByType('candlestick', function (seriesModel) {
  46348. var data = seriesModel.getData();
  46349. data.setVisual({
  46350. legendSymbol: 'roundRect'
  46351. });
  46352. // Only visible series has each data be visual encoded
  46353. if (!ecModel.isSeriesFiltered(seriesModel)) {
  46354. data.each(function (idx) {
  46355. var itemModel = data.getItemModel(idx);
  46356. var sign = data.getItemLayout(idx).sign;
  46357. data.setItemVisual(
  46358. idx,
  46359. {
  46360. color: itemModel.get(
  46361. sign > 0 ? positiveColorQuery : negativeColorQuery
  46362. ),
  46363. borderColor: itemModel.get(
  46364. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  46365. )
  46366. }
  46367. );
  46368. });
  46369. }
  46370. });
  46371. };
  46372. var retrieve2$1 = retrieve2;
  46373. var candlestickLayout = function (ecModel) {
  46374. ecModel.eachSeriesByType('candlestick', function (seriesModel) {
  46375. var coordSys = seriesModel.coordinateSystem;
  46376. var data = seriesModel.getData();
  46377. var candleWidth = calculateCandleWidth(seriesModel, data);
  46378. var chartLayout = seriesModel.get('layout');
  46379. var variableDim = chartLayout === 'horizontal' ? 0 : 1;
  46380. var constDim = 1 - variableDim;
  46381. var coordDims = ['x', 'y'];
  46382. var vDims = [];
  46383. var cDim;
  46384. each$1(data.dimensions, function (dimName) {
  46385. var dimInfo = data.getDimensionInfo(dimName);
  46386. var coordDim = dimInfo.coordDim;
  46387. if (coordDim === coordDims[constDim]) {
  46388. vDims.push(dimName);
  46389. }
  46390. else if (coordDim === coordDims[variableDim]) {
  46391. cDim = dimName;
  46392. }
  46393. });
  46394. if (cDim == null || vDims.length < 4) {
  46395. return;
  46396. }
  46397. var dataIndex = 0;
  46398. data.each([cDim].concat(vDims), function () {
  46399. var args = arguments;
  46400. var axisDimVal = args[0];
  46401. var idx = args[vDims.length + 1];
  46402. var openVal = args[1];
  46403. var closeVal = args[2];
  46404. var lowestVal = args[3];
  46405. var highestVal = args[4];
  46406. var ocLow = Math.min(openVal, closeVal);
  46407. var ocHigh = Math.max(openVal, closeVal);
  46408. var ocLowPoint = getPoint(ocLow);
  46409. var ocHighPoint = getPoint(ocHigh);
  46410. var lowestPoint = getPoint(lowestVal);
  46411. var highestPoint = getPoint(highestVal);
  46412. var whiskerEnds = [
  46413. [
  46414. subPixelOptimizePoint(highestPoint),
  46415. subPixelOptimizePoint(ocHighPoint)
  46416. ],
  46417. [
  46418. subPixelOptimizePoint(lowestPoint),
  46419. subPixelOptimizePoint(ocLowPoint)
  46420. ]
  46421. ];
  46422. var bodyEnds = [];
  46423. addBodyEnd(ocHighPoint, 0);
  46424. addBodyEnd(ocLowPoint, 1);
  46425. var sign;
  46426. if (openVal > closeVal) {
  46427. sign = -1;
  46428. }
  46429. else if (openVal < closeVal) {
  46430. sign = 1;
  46431. }
  46432. else {
  46433. // If close === open, compare with close of last record
  46434. if (dataIndex > 0) {
  46435. sign = data.getItemModel(dataIndex - 1).get()[2]
  46436. <= closeVal
  46437. ? 1
  46438. : -1;
  46439. }
  46440. else {
  46441. // No record of previous, set to be positive
  46442. sign = 1;
  46443. }
  46444. }
  46445. data.setItemLayout(idx, {
  46446. chartLayout: chartLayout,
  46447. sign: sign,
  46448. initBaseline: openVal > closeVal
  46449. ? ocHighPoint[constDim] : ocLowPoint[constDim], // open point.
  46450. bodyEnds: bodyEnds,
  46451. whiskerEnds: whiskerEnds,
  46452. brushRect: makeBrushRect()
  46453. });
  46454. ++dataIndex;
  46455. function getPoint(val) {
  46456. var p = [];
  46457. p[variableDim] = axisDimVal;
  46458. p[constDim] = val;
  46459. return (isNaN(axisDimVal) || isNaN(val))
  46460. ? [NaN, NaN]
  46461. : coordSys.dataToPoint(p);
  46462. }
  46463. function addBodyEnd(point, start) {
  46464. var point1 = point.slice();
  46465. var point2 = point.slice();
  46466. point1[variableDim] = subPixelOptimize(
  46467. point1[variableDim] + candleWidth / 2, 1, false
  46468. );
  46469. point2[variableDim] = subPixelOptimize(
  46470. point2[variableDim] - candleWidth / 2, 1, true
  46471. );
  46472. start
  46473. ? bodyEnds.push(point1, point2)
  46474. : bodyEnds.push(point2, point1);
  46475. }
  46476. function makeBrushRect() {
  46477. var pmin = getPoint(Math.min(openVal, closeVal, lowestVal, highestVal));
  46478. var pmax = getPoint(Math.max(openVal, closeVal, lowestVal, highestVal));
  46479. pmin[variableDim] -= candleWidth / 2;
  46480. pmax[variableDim] -= candleWidth / 2;
  46481. return {
  46482. x: pmin[0],
  46483. y: pmin[1],
  46484. width: constDim ? candleWidth : pmax[0] - pmin[0],
  46485. height: constDim ? pmax[1] - pmin[1] : candleWidth
  46486. };
  46487. }
  46488. function subPixelOptimizePoint(point) {
  46489. point[variableDim] = subPixelOptimize(point[variableDim], 1);
  46490. return point;
  46491. }
  46492. });
  46493. });
  46494. };
  46495. function calculateCandleWidth(seriesModel, data) {
  46496. var baseAxis = seriesModel.getBaseAxis();
  46497. var extent;
  46498. var bandWidth = baseAxis.type === 'category'
  46499. ? baseAxis.getBandWidth()
  46500. : (
  46501. extent = baseAxis.getExtent(),
  46502. Math.abs(extent[1] - extent[0]) / data.count()
  46503. );
  46504. var barMaxWidth = parsePercent$1(
  46505. retrieve2$1(seriesModel.get('barMaxWidth'), bandWidth),
  46506. bandWidth
  46507. );
  46508. var barMinWidth = parsePercent$1(
  46509. retrieve2$1(seriesModel.get('barMinWidth'), 1),
  46510. bandWidth
  46511. );
  46512. var barWidth = seriesModel.get('barWidth');
  46513. return barWidth != null
  46514. ? parsePercent$1(barWidth, bandWidth)
  46515. // Put max outer to ensure bar visible in spite of overlap.
  46516. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  46517. }
  46518. registerPreprocessor(preprocessor);
  46519. registerVisual(candlestickVisual);
  46520. registerLayout(candlestickLayout);
  46521. SeriesModel.extend({
  46522. type: 'series.effectScatter',
  46523. dependencies: ['grid', 'polar'],
  46524. getInitialData: function (option, ecModel) {
  46525. return createListFromArray(this.getSource(), this);
  46526. },
  46527. brushSelector: 'point',
  46528. defaultOption: {
  46529. coordinateSystem: 'cartesian2d',
  46530. zlevel: 0,
  46531. z: 2,
  46532. legendHoverLink: true,
  46533. effectType: 'ripple',
  46534. progressive: 0,
  46535. // When to show the effect, option: 'render'|'emphasis'
  46536. showEffectOn: 'render',
  46537. // Ripple effect config
  46538. rippleEffect: {
  46539. period: 4,
  46540. // Scale of ripple
  46541. scale: 2.5,
  46542. // Brush type can be fill or stroke
  46543. brushType: 'fill'
  46544. },
  46545. // Cartesian coordinate system
  46546. // xAxisIndex: 0,
  46547. // yAxisIndex: 0,
  46548. // Polar coordinate system
  46549. // polarIndex: 0,
  46550. // Geo coordinate system
  46551. // geoIndex: 0,
  46552. // symbol: null, // 图形类型
  46553. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  46554. // symbolRotate: null, // 图形旋转控制
  46555. // large: false,
  46556. // Available when large is true
  46557. // largeThreshold: 2000,
  46558. // itemStyle: {
  46559. // opacity: 1
  46560. // }
  46561. }
  46562. });
  46563. /**
  46564. * Symbol with ripple effect
  46565. * @module echarts/chart/helper/EffectSymbol
  46566. */
  46567. var EFFECT_RIPPLE_NUMBER = 3;
  46568. function normalizeSymbolSize$1(symbolSize) {
  46569. if (!isArray(symbolSize)) {
  46570. symbolSize = [+symbolSize, +symbolSize];
  46571. }
  46572. return symbolSize;
  46573. }
  46574. function updateRipplePath(rippleGroup, effectCfg) {
  46575. rippleGroup.eachChild(function (ripplePath) {
  46576. ripplePath.attr({
  46577. z: effectCfg.z,
  46578. zlevel: effectCfg.zlevel,
  46579. style: {
  46580. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  46581. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  46582. }
  46583. });
  46584. });
  46585. }
  46586. /**
  46587. * @constructor
  46588. * @param {module:echarts/data/List} data
  46589. * @param {number} idx
  46590. * @extends {module:zrender/graphic/Group}
  46591. */
  46592. function EffectSymbol(data, idx) {
  46593. Group.call(this);
  46594. var symbol = new SymbolClz$1(data, idx);
  46595. var rippleGroup = new Group();
  46596. this.add(symbol);
  46597. this.add(rippleGroup);
  46598. rippleGroup.beforeUpdate = function () {
  46599. this.attr(symbol.getScale());
  46600. };
  46601. this.updateData(data, idx);
  46602. }
  46603. var effectSymbolProto = EffectSymbol.prototype;
  46604. effectSymbolProto.stopEffectAnimation = function () {
  46605. this.childAt(1).removeAll();
  46606. };
  46607. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  46608. var symbolType = effectCfg.symbolType;
  46609. var color = effectCfg.color;
  46610. var rippleGroup = this.childAt(1);
  46611. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  46612. // var ripplePath = createSymbol(
  46613. // symbolType, -0.5, -0.5, 1, 1, color
  46614. // );
  46615. // If width/height are set too small (e.g., set to 1) on ios10
  46616. // and macOS Sierra, a circle stroke become a rect, no matter what
  46617. // the scale is set. So we set width/height as 2. See #4136.
  46618. var ripplePath = createSymbol(
  46619. symbolType, -1, -1, 2, 2, color
  46620. );
  46621. ripplePath.attr({
  46622. style: {
  46623. strokeNoScale: true
  46624. },
  46625. z2: 99,
  46626. silent: true,
  46627. scale: [0.5, 0.5]
  46628. });
  46629. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  46630. // TODO Configurable effectCfg.period
  46631. ripplePath.animate('', true)
  46632. .when(effectCfg.period, {
  46633. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  46634. })
  46635. .delay(delay)
  46636. .start();
  46637. ripplePath.animateStyle(true)
  46638. .when(effectCfg.period, {
  46639. opacity: 0
  46640. })
  46641. .delay(delay)
  46642. .start();
  46643. rippleGroup.add(ripplePath);
  46644. }
  46645. updateRipplePath(rippleGroup, effectCfg);
  46646. };
  46647. /**
  46648. * Update effect symbol
  46649. */
  46650. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  46651. var oldEffectCfg = this._effectCfg;
  46652. var rippleGroup = this.childAt(1);
  46653. // Must reinitialize effect if following configuration changed
  46654. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  46655. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  46656. var propName = DIFFICULT_PROPS[i];
  46657. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  46658. this.stopEffectAnimation();
  46659. this.startEffectAnimation(effectCfg);
  46660. return;
  46661. }
  46662. }
  46663. updateRipplePath(rippleGroup, effectCfg);
  46664. };
  46665. /**
  46666. * Highlight symbol
  46667. */
  46668. effectSymbolProto.highlight = function () {
  46669. this.trigger('emphasis');
  46670. };
  46671. /**
  46672. * Downplay symbol
  46673. */
  46674. effectSymbolProto.downplay = function () {
  46675. this.trigger('normal');
  46676. };
  46677. /**
  46678. * Update symbol properties
  46679. * @param {module:echarts/data/List} data
  46680. * @param {number} idx
  46681. */
  46682. effectSymbolProto.updateData = function (data, idx) {
  46683. var seriesModel = data.hostModel;
  46684. this.childAt(0).updateData(data, idx);
  46685. var rippleGroup = this.childAt(1);
  46686. var itemModel = data.getItemModel(idx);
  46687. var symbolType = data.getItemVisual(idx, 'symbol');
  46688. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  46689. var color = data.getItemVisual(idx, 'color');
  46690. rippleGroup.attr('scale', symbolSize);
  46691. rippleGroup.traverse(function (ripplePath) {
  46692. ripplePath.attr({
  46693. fill: color
  46694. });
  46695. });
  46696. var symbolOffset = itemModel.getShallow('symbolOffset');
  46697. if (symbolOffset) {
  46698. var pos = rippleGroup.position;
  46699. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  46700. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  46701. }
  46702. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  46703. var effectCfg = {};
  46704. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  46705. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  46706. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  46707. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  46708. effectCfg.effectOffset = idx / data.count();
  46709. effectCfg.z = itemModel.getShallow('z') || 0;
  46710. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  46711. effectCfg.symbolType = symbolType;
  46712. effectCfg.color = color;
  46713. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  46714. if (effectCfg.showEffectOn === 'render') {
  46715. this._effectCfg
  46716. ? this.updateEffectAnimation(effectCfg)
  46717. : this.startEffectAnimation(effectCfg);
  46718. this._effectCfg = effectCfg;
  46719. }
  46720. else {
  46721. // Not keep old effect config
  46722. this._effectCfg = null;
  46723. this.stopEffectAnimation();
  46724. var symbol = this.childAt(0);
  46725. var onEmphasis = function () {
  46726. symbol.highlight();
  46727. if (effectCfg.showEffectOn !== 'render') {
  46728. this.startEffectAnimation(effectCfg);
  46729. }
  46730. };
  46731. var onNormal = function () {
  46732. symbol.downplay();
  46733. if (effectCfg.showEffectOn !== 'render') {
  46734. this.stopEffectAnimation();
  46735. }
  46736. };
  46737. this.on('mouseover', onEmphasis, this)
  46738. .on('mouseout', onNormal, this)
  46739. .on('emphasis', onEmphasis, this)
  46740. .on('normal', onNormal, this);
  46741. }
  46742. this._effectCfg = effectCfg;
  46743. };
  46744. effectSymbolProto.fadeOut = function (cb) {
  46745. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  46746. cb && cb();
  46747. };
  46748. inherits(EffectSymbol, Group);
  46749. extendChartView({
  46750. type: 'effectScatter',
  46751. init: function () {
  46752. this._symbolDraw = new SymbolDraw(EffectSymbol);
  46753. },
  46754. render: function (seriesModel, ecModel, api) {
  46755. var data = seriesModel.getData();
  46756. var effectSymbolDraw = this._symbolDraw;
  46757. effectSymbolDraw.updateData(data);
  46758. this.group.add(effectSymbolDraw.group);
  46759. },
  46760. updateTransform: function (seriesModel, ecModel, api) {
  46761. var data = seriesModel.getData();
  46762. this.group.dirty();
  46763. var res = pointsLayout().reset(seriesModel);
  46764. if (res.progress) {
  46765. res.progress({ start: 0, end: data.count() }, data);
  46766. }
  46767. this._symbolDraw.updateLayout(data);
  46768. },
  46769. _updateGroupTransform: function (seriesModel) {
  46770. var coordSys = seriesModel.coordinateSystem;
  46771. if (coordSys && coordSys.getRoamTransform) {
  46772. this.group.transform = clone$2(coordSys.getRoamTransform());
  46773. this.group.decomposeTransform();
  46774. }
  46775. },
  46776. remove: function (ecModel, api) {
  46777. this._symbolDraw && this._symbolDraw.remove(api);
  46778. },
  46779. dispose: function () {}
  46780. });
  46781. registerVisual(visualSymbol('effectScatter', 'circle'));
  46782. registerLayout(pointsLayout('effectScatter'));
  46783. var globalObj$1 = typeof window === 'undefined' ? global : window;
  46784. var Uint32Arr = globalObj$1.Uint32Array || Array;
  46785. var Float64Arr = globalObj$1.Float64Array || Array;
  46786. function compatEc2(seriesOpt) {
  46787. var data = seriesOpt.data;
  46788. if (data && data[0] && data[0][0] && data[0][0].coord) {
  46789. if (__DEV__) {
  46790. console.warn('Lines data configuration has been changed to'
  46791. + ' { coords:[[1,2],[2,3]] }');
  46792. }
  46793. seriesOpt.data = map(data, function (itemOpt) {
  46794. var coords = [
  46795. itemOpt[0].coord, itemOpt[1].coord
  46796. ];
  46797. var target = {
  46798. coords: coords
  46799. };
  46800. if (itemOpt[0].name) {
  46801. target.fromName = itemOpt[0].name;
  46802. }
  46803. if (itemOpt[1].name) {
  46804. target.toName = itemOpt[1].name;
  46805. }
  46806. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  46807. });
  46808. }
  46809. }
  46810. var LinesSeries = SeriesModel.extend({
  46811. type: 'series.lines',
  46812. dependencies: ['grid', 'polar'],
  46813. visualColorAccessPath: 'lineStyle.color',
  46814. init: function (option) {
  46815. // Not using preprocessor because mergeOption may not have series.type
  46816. compatEc2(option);
  46817. var result = this._processFlatCoordsArray(option.data);
  46818. this._flatCoords = result.flatCoords;
  46819. this._flatCoordsOffset = result.flatCoordsOffset;
  46820. if (result.flatCoords) {
  46821. option.data = new Float32Array(result.count);
  46822. }
  46823. LinesSeries.superApply(this, 'init', arguments);
  46824. },
  46825. mergeOption: function (option) {
  46826. compatEc2(option);
  46827. if (option.data) {
  46828. // Only update when have option data to merge.
  46829. var result = this._processFlatCoordsArray(option.data);
  46830. this._flatCoords = result.flatCoords;
  46831. this._flatCoordsOffset = result.flatCoordsOffset;
  46832. if (result.flatCoords) {
  46833. option.data = new Float32Array(result.count);
  46834. }
  46835. }
  46836. LinesSeries.superApply(this, 'mergeOption', arguments);
  46837. },
  46838. appendData: function (params) {
  46839. var result = this._processFlatCoordsArray(params.data);
  46840. if (result.flatCoords) {
  46841. if (!this._flatCoords) {
  46842. this._flatCoords = result.flatCoords;
  46843. this._flatCoordsOffset = result.flatCoordsOffset;
  46844. }
  46845. else {
  46846. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  46847. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  46848. }
  46849. params.data = new Float32Array(result.count);
  46850. }
  46851. this.getRawData().appendData(params.data);
  46852. },
  46853. _getCoordsFromItemModel: function (idx) {
  46854. var itemModel = this.getData().getItemModel(idx);
  46855. var coords = (itemModel.option instanceof Array)
  46856. ? itemModel.option : itemModel.getShallow('coords');
  46857. if (__DEV__) {
  46858. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  46859. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  46860. }
  46861. }
  46862. return coords;
  46863. },
  46864. getLineCoordsCount: function (idx) {
  46865. if (this._flatCoordsOffset) {
  46866. return this._flatCoordsOffset[idx * 2 + 1];
  46867. }
  46868. else {
  46869. return this._getCoordsFromItemModel(idx).length;
  46870. }
  46871. },
  46872. getLineCoords: function (idx, out) {
  46873. if (this._flatCoordsOffset) {
  46874. var offset = this._flatCoordsOffset[idx * 2];
  46875. var len = this._flatCoordsOffset[idx * 2 + 1];
  46876. for (var i = 0; i < len; i++) {
  46877. out[i] = out[i] || [];
  46878. out[i][0] = this._flatCoords[offset + i * 2];
  46879. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  46880. }
  46881. return len;
  46882. }
  46883. else {
  46884. var coords = this._getCoordsFromItemModel(idx);
  46885. for (var i = 0; i < coords.length; i++) {
  46886. out[i] = out[i] || [];
  46887. out[i][0] = coords[i][0];
  46888. out[i][1] = coords[i][1];
  46889. }
  46890. return coords.length;
  46891. }
  46892. },
  46893. _processFlatCoordsArray: function (data) {
  46894. var startOffset = 0;
  46895. if (this._flatCoords) {
  46896. startOffset = this._flatCoords.length;
  46897. }
  46898. // Stored as a typed array. In format
  46899. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  46900. if (typeof data[0] === 'number') {
  46901. var len = data.length;
  46902. // Store offset and len of each segment
  46903. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  46904. var coordsStorage = new Float64Arr(len);
  46905. var coordsCursor = 0;
  46906. var offsetCursor = 0;
  46907. var dataCount = 0;
  46908. for (var i = 0; i < len;) {
  46909. dataCount++;
  46910. var count = data[i++];
  46911. // Offset
  46912. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  46913. // Len
  46914. coordsOffsetAndLenStorage[offsetCursor++] = count;
  46915. for (var k = 0; k < count; k++) {
  46916. var x = data[i++];
  46917. var y = data[i++];
  46918. coordsStorage[coordsCursor++] = x;
  46919. coordsStorage[coordsCursor++] = y;
  46920. if (i > len) {
  46921. if (__DEV__) {
  46922. throw new Error('Invalid data format.');
  46923. }
  46924. }
  46925. }
  46926. }
  46927. return {
  46928. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  46929. flatCoords: coordsStorage,
  46930. count: dataCount
  46931. };
  46932. }
  46933. return {
  46934. flatCoordsOffset: null,
  46935. flatCoords: null,
  46936. count: data.length
  46937. };
  46938. },
  46939. getInitialData: function (option, ecModel) {
  46940. if (__DEV__) {
  46941. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  46942. if (!CoordSys) {
  46943. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  46944. }
  46945. }
  46946. var lineData = new List(['value'], this);
  46947. lineData.hasItemOption = false;
  46948. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  46949. // dataItem is simply coords
  46950. if (dataItem instanceof Array) {
  46951. return NaN;
  46952. }
  46953. else {
  46954. lineData.hasItemOption = true;
  46955. var value = dataItem.value;
  46956. if (value != null) {
  46957. return value instanceof Array ? value[dimIndex] : value;
  46958. }
  46959. }
  46960. });
  46961. return lineData;
  46962. },
  46963. formatTooltip: function (dataIndex) {
  46964. var data = this.getData();
  46965. var itemModel = data.getItemModel(dataIndex);
  46966. var name = itemModel.get('name');
  46967. if (name) {
  46968. return name;
  46969. }
  46970. var fromName = itemModel.get('fromName');
  46971. var toName = itemModel.get('toName');
  46972. var html = [];
  46973. fromName != null && html.push(fromName);
  46974. toName != null && html.push(toName);
  46975. return encodeHTML(html.join(' > '));
  46976. },
  46977. preventIncremental: function () {
  46978. return !!this.get('effect.show');
  46979. },
  46980. getProgressive: function () {
  46981. var progressive = this.option.progressive;
  46982. if (progressive == null) {
  46983. return this.option.large ? 1e4 : this.get('progressive');
  46984. }
  46985. return progressive;
  46986. },
  46987. getProgressiveThreshold: function () {
  46988. var progressiveThreshold = this.option.progressiveThreshold;
  46989. if (progressiveThreshold == null) {
  46990. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  46991. }
  46992. return progressiveThreshold;
  46993. },
  46994. defaultOption: {
  46995. coordinateSystem: 'geo',
  46996. zlevel: 0,
  46997. z: 2,
  46998. legendHoverLink: true,
  46999. hoverAnimation: true,
  47000. // Cartesian coordinate system
  47001. xAxisIndex: 0,
  47002. yAxisIndex: 0,
  47003. symbol: ['none', 'none'],
  47004. symbolSize: [10, 10],
  47005. // Geo coordinate system
  47006. geoIndex: 0,
  47007. effect: {
  47008. show: false,
  47009. period: 4,
  47010. // Animation delay. support callback
  47011. // delay: 0,
  47012. // If move with constant speed px/sec
  47013. // period will be ignored if this property is > 0,
  47014. constantSpeed: 0,
  47015. symbol: 'circle',
  47016. symbolSize: 3,
  47017. loop: true,
  47018. // Length of trail, 0 - 1
  47019. trailLength: 0.2
  47020. // Same with lineStyle.color
  47021. // color
  47022. },
  47023. large: false,
  47024. // Available when large is true
  47025. largeThreshold: 2000,
  47026. // If lines are polyline
  47027. // polyline not support curveness, label, animation
  47028. polyline: false,
  47029. label: {
  47030. show: false,
  47031. position: 'end'
  47032. // distance: 5,
  47033. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  47034. },
  47035. lineStyle: {
  47036. opacity: 0.5
  47037. }
  47038. }
  47039. });
  47040. /**
  47041. * Provide effect for line
  47042. * @module echarts/chart/helper/EffectLine
  47043. */
  47044. /**
  47045. * @constructor
  47046. * @extends {module:zrender/graphic/Group}
  47047. * @alias {module:echarts/chart/helper/Line}
  47048. */
  47049. function EffectLine(lineData, idx, seriesScope) {
  47050. Group.call(this);
  47051. this.add(this.createLine(lineData, idx, seriesScope));
  47052. this._updateEffectSymbol(lineData, idx);
  47053. }
  47054. var effectLineProto = EffectLine.prototype;
  47055. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  47056. return new Line$1(lineData, idx, seriesScope);
  47057. };
  47058. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  47059. var itemModel = lineData.getItemModel(idx);
  47060. var effectModel = itemModel.getModel('effect');
  47061. var size = effectModel.get('symbolSize');
  47062. var symbolType = effectModel.get('symbol');
  47063. if (!isArray(size)) {
  47064. size = [size, size];
  47065. }
  47066. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  47067. var symbol = this.childAt(1);
  47068. if (this._symbolType !== symbolType) {
  47069. // Remove previous
  47070. this.remove(symbol);
  47071. symbol = createSymbol(
  47072. symbolType, -0.5, -0.5, 1, 1, color
  47073. );
  47074. symbol.z2 = 100;
  47075. symbol.culling = true;
  47076. this.add(symbol);
  47077. }
  47078. // Symbol may be removed if loop is false
  47079. if (!symbol) {
  47080. return;
  47081. }
  47082. // Shadow color is same with color in default
  47083. symbol.setStyle('shadowColor', color);
  47084. symbol.setStyle(effectModel.getItemStyle(['color']));
  47085. symbol.attr('scale', size);
  47086. symbol.setColor(color);
  47087. symbol.attr('scale', size);
  47088. this._symbolType = symbolType;
  47089. this._updateEffectAnimation(lineData, effectModel, idx);
  47090. };
  47091. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  47092. var symbol = this.childAt(1);
  47093. if (!symbol) {
  47094. return;
  47095. }
  47096. var self = this;
  47097. var points = lineData.getItemLayout(idx);
  47098. var period = effectModel.get('period') * 1000;
  47099. var loop = effectModel.get('loop');
  47100. var constantSpeed = effectModel.get('constantSpeed');
  47101. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  47102. return idx / lineData.count() * period / 3;
  47103. });
  47104. var isDelayFunc = typeof delayExpr === 'function';
  47105. // Ignore when updating
  47106. symbol.ignore = true;
  47107. this.updateAnimationPoints(symbol, points);
  47108. if (constantSpeed > 0) {
  47109. period = this.getLineLength(symbol) / constantSpeed * 1000;
  47110. }
  47111. if (period !== this._period || loop !== this._loop) {
  47112. symbol.stopAnimation();
  47113. var delay = delayExpr;
  47114. if (isDelayFunc) {
  47115. delay = delayExpr(idx);
  47116. }
  47117. if (symbol.__t > 0) {
  47118. delay = -period * symbol.__t;
  47119. }
  47120. symbol.__t = 0;
  47121. var animator = symbol.animate('', loop)
  47122. .when(period, {
  47123. __t: 1
  47124. })
  47125. .delay(delay)
  47126. .during(function () {
  47127. self.updateSymbolPosition(symbol);
  47128. });
  47129. if (!loop) {
  47130. animator.done(function () {
  47131. self.remove(symbol);
  47132. });
  47133. }
  47134. animator.start();
  47135. }
  47136. this._period = period;
  47137. this._loop = loop;
  47138. };
  47139. effectLineProto.getLineLength = function (symbol) {
  47140. // Not so accurate
  47141. return (dist(symbol.__p1, symbol.__cp1)
  47142. + dist(symbol.__cp1, symbol.__p2));
  47143. };
  47144. effectLineProto.updateAnimationPoints = function (symbol, points) {
  47145. symbol.__p1 = points[0];
  47146. symbol.__p2 = points[1];
  47147. symbol.__cp1 = points[2] || [
  47148. (points[0][0] + points[1][0]) / 2,
  47149. (points[0][1] + points[1][1]) / 2
  47150. ];
  47151. };
  47152. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  47153. this.childAt(0).updateData(lineData, idx, seriesScope);
  47154. this._updateEffectSymbol(lineData, idx);
  47155. };
  47156. effectLineProto.updateSymbolPosition = function (symbol) {
  47157. var p1 = symbol.__p1;
  47158. var p2 = symbol.__p2;
  47159. var cp1 = symbol.__cp1;
  47160. var t = symbol.__t;
  47161. var pos = symbol.position;
  47162. var quadraticAt$$1 = quadraticAt;
  47163. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  47164. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  47165. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  47166. // Tangent
  47167. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  47168. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  47169. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  47170. symbol.ignore = false;
  47171. };
  47172. effectLineProto.updateLayout = function (lineData, idx) {
  47173. this.childAt(0).updateLayout(lineData, idx);
  47174. var effectModel = lineData.getItemModel(idx).getModel('effect');
  47175. this._updateEffectAnimation(lineData, effectModel, idx);
  47176. };
  47177. inherits(EffectLine, Group);
  47178. /**
  47179. * @module echarts/chart/helper/Line
  47180. */
  47181. /**
  47182. * @constructor
  47183. * @extends {module:zrender/graphic/Group}
  47184. * @alias {module:echarts/chart/helper/Polyline}
  47185. */
  47186. function Polyline$2(lineData, idx, seriesScope) {
  47187. Group.call(this);
  47188. this._createPolyline(lineData, idx, seriesScope);
  47189. }
  47190. var polylineProto = Polyline$2.prototype;
  47191. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  47192. // var seriesModel = lineData.hostModel;
  47193. var points = lineData.getItemLayout(idx);
  47194. var line = new Polyline({
  47195. shape: {
  47196. points: points
  47197. }
  47198. });
  47199. this.add(line);
  47200. this._updateCommonStl(lineData, idx, seriesScope);
  47201. };
  47202. polylineProto.updateData = function (lineData, idx, seriesScope) {
  47203. var seriesModel = lineData.hostModel;
  47204. var line = this.childAt(0);
  47205. var target = {
  47206. shape: {
  47207. points: lineData.getItemLayout(idx)
  47208. }
  47209. };
  47210. updateProps(line, target, seriesModel, idx);
  47211. this._updateCommonStl(lineData, idx, seriesScope);
  47212. };
  47213. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  47214. var line = this.childAt(0);
  47215. var itemModel = lineData.getItemModel(idx);
  47216. var visualColor = lineData.getItemVisual(idx, 'color');
  47217. var lineStyle = seriesScope && seriesScope.lineStyle;
  47218. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  47219. if (!seriesScope || lineData.hasItemOption) {
  47220. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  47221. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  47222. }
  47223. line.useStyle(defaults(
  47224. {
  47225. strokeNoScale: true,
  47226. fill: 'none',
  47227. stroke: visualColor
  47228. },
  47229. lineStyle
  47230. ));
  47231. line.hoverStyle = hoverLineStyle;
  47232. setHoverStyle(this);
  47233. };
  47234. polylineProto.updateLayout = function (lineData, idx) {
  47235. var polyline = this.childAt(0);
  47236. polyline.setShape('points', lineData.getItemLayout(idx));
  47237. };
  47238. inherits(Polyline$2, Group);
  47239. /**
  47240. * Provide effect for line
  47241. * @module echarts/chart/helper/EffectLine
  47242. */
  47243. /**
  47244. * @constructor
  47245. * @extends {module:echarts/chart/helper/EffectLine}
  47246. * @alias {module:echarts/chart/helper/Polyline}
  47247. */
  47248. function EffectPolyline(lineData, idx, seriesScope) {
  47249. EffectLine.call(this, lineData, idx, seriesScope);
  47250. this._lastFrame = 0;
  47251. this._lastFramePercent = 0;
  47252. }
  47253. var effectPolylineProto = EffectPolyline.prototype;
  47254. // Overwrite
  47255. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  47256. return new Polyline$2(lineData, idx, seriesScope);
  47257. };
  47258. // Overwrite
  47259. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  47260. this._points = points;
  47261. var accLenArr = [0];
  47262. var len$$1 = 0;
  47263. for (var i = 1; i < points.length; i++) {
  47264. var p1 = points[i - 1];
  47265. var p2 = points[i];
  47266. len$$1 += dist(p1, p2);
  47267. accLenArr.push(len$$1);
  47268. }
  47269. if (len$$1 === 0) {
  47270. return;
  47271. }
  47272. for (var i = 0; i < accLenArr.length; i++) {
  47273. accLenArr[i] /= len$$1;
  47274. }
  47275. this._offsets = accLenArr;
  47276. this._length = len$$1;
  47277. };
  47278. // Overwrite
  47279. effectPolylineProto.getLineLength = function (symbol) {
  47280. return this._length;
  47281. };
  47282. // Overwrite
  47283. effectPolylineProto.updateSymbolPosition = function (symbol) {
  47284. var t = symbol.__t;
  47285. var points = this._points;
  47286. var offsets = this._offsets;
  47287. var len$$1 = points.length;
  47288. if (!offsets) {
  47289. // Has length 0
  47290. return;
  47291. }
  47292. var lastFrame = this._lastFrame;
  47293. var frame;
  47294. if (t < this._lastFramePercent) {
  47295. // Start from the next frame
  47296. // PENDING start from lastFrame ?
  47297. var start = Math.min(lastFrame + 1, len$$1 - 1);
  47298. for (frame = start; frame >= 0; frame--) {
  47299. if (offsets[frame] <= t) {
  47300. break;
  47301. }
  47302. }
  47303. // PENDING really need to do this ?
  47304. frame = Math.min(frame, len$$1 - 2);
  47305. }
  47306. else {
  47307. for (var frame = lastFrame; frame < len$$1; frame++) {
  47308. if (offsets[frame] > t) {
  47309. break;
  47310. }
  47311. }
  47312. frame = Math.min(frame - 1, len$$1 - 2);
  47313. }
  47314. lerp(
  47315. symbol.position, points[frame], points[frame + 1],
  47316. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  47317. );
  47318. var tx = points[frame + 1][0] - points[frame][0];
  47319. var ty = points[frame + 1][1] - points[frame][1];
  47320. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  47321. this._lastFrame = frame;
  47322. this._lastFramePercent = t;
  47323. symbol.ignore = false;
  47324. };
  47325. inherits(EffectPolyline, EffectLine);
  47326. // TODO Batch by color
  47327. var LargeLineShape = extendShape({
  47328. shape: {
  47329. polyline: false,
  47330. curveness: 0,
  47331. segs: []
  47332. },
  47333. buildPath: function (path, shape) {
  47334. var segs = shape.segs;
  47335. var curveness = shape.curveness;
  47336. if (shape.polyline) {
  47337. for (var i = 0; i < segs.length;) {
  47338. var count = segs[i++];
  47339. if (count > 0) {
  47340. path.moveTo(segs[i++], segs[i++]);
  47341. for (var k = 1; k < count; k++) {
  47342. path.lineTo(segs[i++], segs[i++]);
  47343. }
  47344. }
  47345. }
  47346. }
  47347. else {
  47348. for (var i = 0; i < segs.length;) {
  47349. var x0 = segs[i++];
  47350. var y0 = segs[i++];
  47351. var x1 = segs[i++];
  47352. var y1 = segs[i++];
  47353. path.moveTo(x0, y0);
  47354. if (curveness > 0) {
  47355. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  47356. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  47357. path.quadraticCurveTo(x2, y2, x1, y1);
  47358. }
  47359. else {
  47360. path.lineTo(x1, y1);
  47361. }
  47362. }
  47363. }
  47364. },
  47365. findDataIndex: function (x, y) {
  47366. var shape = this.shape;
  47367. var segs = shape.segs;
  47368. var curveness = shape.curveness;
  47369. if (shape.polyline) {
  47370. var dataIndex = 0;
  47371. for (var i = 0; i < segs.length;) {
  47372. var count = segs[i++];
  47373. if (count > 0) {
  47374. var x0 = segs[i++];
  47375. var y0 = segs[i++];
  47376. for (var k = 1; k < count; k++) {
  47377. var x1 = segs[i++];
  47378. var y1 = segs[i++];
  47379. if (containStroke$1(x0, y0, x1, y1)) {
  47380. return dataIndex;
  47381. }
  47382. }
  47383. }
  47384. dataIndex++;
  47385. }
  47386. }
  47387. else {
  47388. var dataIndex = 0;
  47389. for (var i = 0; i < segs.length;) {
  47390. var x0 = segs[i++];
  47391. var y0 = segs[i++];
  47392. var x1 = segs[i++];
  47393. var y1 = segs[i++];
  47394. if (curveness > 0) {
  47395. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  47396. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  47397. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  47398. return dataIndex;
  47399. }
  47400. }
  47401. else {
  47402. if (containStroke$1(x0, y0, x1, y1)) {
  47403. return dataIndex;
  47404. }
  47405. }
  47406. dataIndex++;
  47407. }
  47408. }
  47409. return -1;
  47410. }
  47411. });
  47412. function LargeLineDraw() {
  47413. this.group = new Group();
  47414. }
  47415. var largeLineProto = LargeLineDraw.prototype;
  47416. largeLineProto.isPersistent = function () {
  47417. return !this._incremental;
  47418. };
  47419. /**
  47420. * Update symbols draw by new data
  47421. * @param {module:echarts/data/List} data
  47422. */
  47423. largeLineProto.updateData = function (data) {
  47424. this.group.removeAll();
  47425. var lineEl = new LargeLineShape({
  47426. rectHover: true,
  47427. cursor: 'default'
  47428. });
  47429. lineEl.setShape({
  47430. segs: data.getLayout('linesPoints')
  47431. });
  47432. this._setCommon(lineEl, data);
  47433. // Add back
  47434. this.group.add(lineEl);
  47435. this._incremental = null;
  47436. };
  47437. /**
  47438. * @override
  47439. */
  47440. largeLineProto.incrementalPrepareUpdate = function (data) {
  47441. this.group.removeAll();
  47442. this._clearIncremental();
  47443. if (data.count() > 5e5) {
  47444. if (!this._incremental) {
  47445. this._incremental = new IncrementalDisplayble({
  47446. silent: true
  47447. });
  47448. }
  47449. this.group.add(this._incremental);
  47450. }
  47451. else {
  47452. this._incremental = null;
  47453. }
  47454. };
  47455. /**
  47456. * @override
  47457. */
  47458. largeLineProto.incrementalUpdate = function (taskParams, data) {
  47459. var lineEl = new LargeLineShape();
  47460. lineEl.setShape({
  47461. segs: data.getLayout('linesPoints')
  47462. });
  47463. this._setCommon(lineEl, data, !!this._incremental);
  47464. if (!this._incremental) {
  47465. lineEl.rectHover = true;
  47466. lineEl.cursor = 'default';
  47467. lineEl.__startIndex = taskParams.start;
  47468. this.group.add(lineEl);
  47469. }
  47470. else {
  47471. this._incremental.addDisplayable(lineEl, true);
  47472. }
  47473. };
  47474. /**
  47475. * @override
  47476. */
  47477. largeLineProto.remove = function () {
  47478. this._clearIncremental();
  47479. this._incremental = null;
  47480. this.group.removeAll();
  47481. };
  47482. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  47483. var hostModel = data.hostModel;
  47484. lineEl.setShape({
  47485. polyline: hostModel.get('polyline'),
  47486. curveness: hostModel.get('lineStyle.curveness')
  47487. });
  47488. lineEl.useStyle(
  47489. hostModel.getModel('lineStyle').getLineStyle()
  47490. );
  47491. lineEl.style.strokeNoScale = true;
  47492. var visualColor = data.getVisual('color');
  47493. if (visualColor) {
  47494. lineEl.setStyle('stroke', visualColor);
  47495. }
  47496. lineEl.setStyle('fill');
  47497. if (!isIncremental) {
  47498. // Enable tooltip
  47499. // PENDING May have performance issue when path is extremely large
  47500. lineEl.seriesIndex = hostModel.seriesIndex;
  47501. lineEl.on('mousemove', function (e) {
  47502. lineEl.dataIndex = null;
  47503. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  47504. if (dataIndex > 0) {
  47505. // Provide dataIndex for tooltip
  47506. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  47507. }
  47508. });
  47509. }
  47510. };
  47511. largeLineProto._clearIncremental = function () {
  47512. var incremental = this._incremental;
  47513. if (incremental) {
  47514. incremental.clearDisplaybles();
  47515. }
  47516. };
  47517. var linesLayout = {
  47518. seriesType: 'lines',
  47519. plan: createRenderPlanner(),
  47520. reset: function (seriesModel) {
  47521. var coordSys = seriesModel.coordinateSystem;
  47522. var isPolyline = seriesModel.get('polyline');
  47523. var isLarge = seriesModel.pipelineContext.large;
  47524. function progress(params, lineData) {
  47525. var lineCoords = [];
  47526. if (isLarge) {
  47527. var points;
  47528. var segCount = params.end - params.start;
  47529. if (isPolyline) {
  47530. var totalCoordsCount = 0;
  47531. for (var i = params.start; i < params.end; i++) {
  47532. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  47533. }
  47534. points = new Float32Array(segCount + totalCoordsCount * 2);
  47535. }
  47536. else {
  47537. points = new Float32Array(segCount * 2);
  47538. }
  47539. var offset = 0;
  47540. var pt = [];
  47541. for (var i = params.start; i < params.end; i++) {
  47542. var len = seriesModel.getLineCoords(i, lineCoords);
  47543. if (isPolyline) {
  47544. points[offset++] = len;
  47545. }
  47546. for (var k = 0; k < len; k++) {
  47547. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  47548. points[offset++] = pt[0];
  47549. points[offset++] = pt[1];
  47550. }
  47551. }
  47552. lineData.setLayout('linesPoints', points);
  47553. }
  47554. else {
  47555. for (var i = params.start; i < params.end; i++) {
  47556. var itemModel = lineData.getItemModel(i);
  47557. var len = seriesModel.getLineCoords(i, lineCoords);
  47558. var pts = [];
  47559. if (isPolyline) {
  47560. for (var j = 0; j < len; j++) {
  47561. pts.push(coordSys.dataToPoint(lineCoords[j]));
  47562. }
  47563. }
  47564. else {
  47565. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  47566. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  47567. var curveness = itemModel.get('lineStyle.curveness');
  47568. if (+curveness) {
  47569. pts[2] = [
  47570. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  47571. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  47572. ];
  47573. }
  47574. }
  47575. lineData.setItemLayout(i, pts);
  47576. }
  47577. }
  47578. }
  47579. return { progress: progress };
  47580. }
  47581. };
  47582. extendChartView({
  47583. type: 'lines',
  47584. init: function () {},
  47585. render: function (seriesModel, ecModel, api) {
  47586. var data = seriesModel.getData();
  47587. var lineDraw = this._updateLineDraw(data, seriesModel);
  47588. var zlevel = seriesModel.get('zlevel');
  47589. var trailLength = seriesModel.get('effect.trailLength');
  47590. var zr = api.getZr();
  47591. // Avoid the drag cause ghost shadow
  47592. // FIXME Better way ?
  47593. // SVG doesn't support
  47594. var isSvg = zr.painter.getType() === 'svg';
  47595. if (!isSvg) {
  47596. zr.painter.getLayer(zlevel).clear(true);
  47597. }
  47598. // Config layer with motion blur
  47599. if (this._lastZlevel != null && !isSvg) {
  47600. zr.configLayer(this._lastZlevel, {
  47601. motionBlur: false
  47602. });
  47603. }
  47604. if (this._showEffect(seriesModel) && trailLength) {
  47605. if (__DEV__) {
  47606. var notInIndividual = false;
  47607. ecModel.eachSeries(function (otherSeriesModel) {
  47608. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  47609. notInIndividual = true;
  47610. }
  47611. });
  47612. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  47613. }
  47614. if (!isSvg) {
  47615. zr.configLayer(zlevel, {
  47616. motionBlur: true,
  47617. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  47618. });
  47619. }
  47620. }
  47621. lineDraw.updateData(data);
  47622. this._lastZlevel = zlevel;
  47623. this._finished = true;
  47624. },
  47625. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  47626. var data = seriesModel.getData();
  47627. var lineDraw = this._updateLineDraw(data, seriesModel);
  47628. lineDraw.incrementalPrepareUpdate(data);
  47629. this._clearLayer(api);
  47630. this._finished = false;
  47631. },
  47632. incrementalRender: function (taskParams, seriesModel, ecModel) {
  47633. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  47634. this._finished = taskParams.end === seriesModel.getData().count();
  47635. },
  47636. updateTransform: function (seriesModel, ecModel, api) {
  47637. var data = seriesModel.getData();
  47638. if (!this._finished || seriesModel.pipelineContext.large) {
  47639. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  47640. return {
  47641. update: true
  47642. };
  47643. }
  47644. else {
  47645. // TODO Use same logic with ScatterView.
  47646. // Manually update layout
  47647. var res = linesLayout.reset(seriesModel);
  47648. if (res.progress) {
  47649. res.progress({ start: 0, end: data.count() }, data);
  47650. }
  47651. this._lineDraw.updateLayout();
  47652. this._clearLayer(api);
  47653. }
  47654. },
  47655. _updateLineDraw: function (data, seriesModel) {
  47656. var lineDraw = this._lineDraw;
  47657. var hasEffect = this._showEffect(seriesModel);
  47658. var isPolyline = !!seriesModel.get('polyline');
  47659. var pipelineContext = seriesModel.pipelineContext;
  47660. var isLargeDraw = pipelineContext.large;
  47661. if (__DEV__) {
  47662. if (hasEffect && isLargeDraw) {
  47663. console.warn('Large lines not support effect');
  47664. }
  47665. }
  47666. if (!lineDraw
  47667. || hasEffect !== this._hasEffet
  47668. || isPolyline !== this._isPolyline
  47669. || isLargeDraw !== this._isLargeDraw
  47670. ) {
  47671. if (lineDraw) {
  47672. lineDraw.remove();
  47673. }
  47674. lineDraw = this._lineDraw = isLargeDraw
  47675. ? new LargeLineDraw()
  47676. : new LineDraw(
  47677. isPolyline
  47678. ? (hasEffect ? EffectPolyline : Polyline$2)
  47679. : (hasEffect ? EffectLine : Line$1)
  47680. );
  47681. this._hasEffet = hasEffect;
  47682. this._isPolyline = isPolyline;
  47683. this._isLargeDraw = isLargeDraw;
  47684. this.group.removeAll();
  47685. }
  47686. this.group.add(lineDraw.group);
  47687. return lineDraw;
  47688. },
  47689. _showEffect: function (seriesModel) {
  47690. return !!seriesModel.get('effect.show');
  47691. },
  47692. _clearLayer: function (api) {
  47693. // Not use motion when dragging or zooming
  47694. var zr = api.getZr();
  47695. var isSvg = zr.painter.getType() === 'svg';
  47696. if (!isSvg && this._lastZlevel != null) {
  47697. zr.painter.getLayer(this._lastZlevel).clear(true);
  47698. }
  47699. },
  47700. remove: function (ecModel, api) {
  47701. this._lineDraw && this._lineDraw.remove();
  47702. this._lineDraw = null;
  47703. // Clear motion when lineDraw is removed
  47704. this._clearLayer(api);
  47705. },
  47706. dispose: function () {}
  47707. });
  47708. function normalize$2(a) {
  47709. if (!(a instanceof Array)) {
  47710. a = [a, a];
  47711. }
  47712. return a;
  47713. }
  47714. var opacityQuery = 'lineStyle.opacity'.split('.');
  47715. var linesVisual = {
  47716. seriesType: 'lines',
  47717. reset: function (seriesModel, ecModel, api) {
  47718. var symbolType = normalize$2(seriesModel.get('symbol'));
  47719. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  47720. var data = seriesModel.getData();
  47721. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  47722. data.setVisual('toSymbol', symbolType && symbolType[1]);
  47723. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  47724. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  47725. data.setVisual('opacity', seriesModel.get(opacityQuery));
  47726. function dataEach(data, idx) {
  47727. var itemModel = data.getItemModel(idx);
  47728. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  47729. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  47730. var opacity = itemModel.get(opacityQuery);
  47731. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  47732. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  47733. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  47734. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  47735. data.setItemVisual(idx, 'opacity', opacity);
  47736. }
  47737. return {dataEach: data.hasItemOption ? dataEach : null};
  47738. }
  47739. };
  47740. registerLayout(linesLayout);
  47741. registerVisual(linesVisual);
  47742. SeriesModel.extend({
  47743. type: 'series.heatmap',
  47744. getInitialData: function (option, ecModel) {
  47745. return createListFromArray(this.getSource(), this, {
  47746. generateCoord: 'value'
  47747. });
  47748. },
  47749. preventIncremental: function () {
  47750. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  47751. if (coordSysCreator && coordSysCreator.dimensions) {
  47752. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  47753. }
  47754. },
  47755. defaultOption: {
  47756. // Cartesian2D or geo
  47757. coordinateSystem: 'cartesian2d',
  47758. zlevel: 0,
  47759. z: 2,
  47760. // Cartesian coordinate system
  47761. // xAxisIndex: 0,
  47762. // yAxisIndex: 0,
  47763. // Geo coordinate system
  47764. geoIndex: 0,
  47765. blurSize: 30,
  47766. pointSize: 20,
  47767. maxOpacity: 1,
  47768. minOpacity: 0
  47769. }
  47770. });
  47771. /**
  47772. * @file defines echarts Heatmap Chart
  47773. * @author Ovilia (me@zhangwenli.com)
  47774. * Inspired by https://github.com/mourner/simpleheat
  47775. *
  47776. * @module
  47777. */
  47778. var GRADIENT_LEVELS = 256;
  47779. /**
  47780. * Heatmap Chart
  47781. *
  47782. * @class
  47783. */
  47784. function Heatmap() {
  47785. var canvas = createCanvas();
  47786. this.canvas = canvas;
  47787. this.blurSize = 30;
  47788. this.pointSize = 20;
  47789. this.maxOpacity = 1;
  47790. this.minOpacity = 0;
  47791. this._gradientPixels = {};
  47792. }
  47793. Heatmap.prototype = {
  47794. /**
  47795. * Renders Heatmap and returns the rendered canvas
  47796. * @param {Array} data array of data, each has x, y, value
  47797. * @param {number} width canvas width
  47798. * @param {number} height canvas height
  47799. */
  47800. update: function(data, width, height, normalize, colorFunc, isInRange) {
  47801. var brush = this._getBrush();
  47802. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  47803. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  47804. var r = this.pointSize + this.blurSize;
  47805. var canvas = this.canvas;
  47806. var ctx = canvas.getContext('2d');
  47807. var len = data.length;
  47808. canvas.width = width;
  47809. canvas.height = height;
  47810. for (var i = 0; i < len; ++i) {
  47811. var p = data[i];
  47812. var x = p[0];
  47813. var y = p[1];
  47814. var value = p[2];
  47815. // calculate alpha using value
  47816. var alpha = normalize(value);
  47817. // draw with the circle brush with alpha
  47818. ctx.globalAlpha = alpha;
  47819. ctx.drawImage(brush, x - r, y - r);
  47820. }
  47821. if (!canvas.width || !canvas.height) {
  47822. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  47823. // 'CanvasRenderingContext2D': The source height is 0."
  47824. return canvas;
  47825. }
  47826. // colorize the canvas using alpha value and set with gradient
  47827. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  47828. var pixels = imageData.data;
  47829. var offset = 0;
  47830. var pixelLen = pixels.length;
  47831. var minOpacity = this.minOpacity;
  47832. var maxOpacity = this.maxOpacity;
  47833. var diffOpacity = maxOpacity - minOpacity;
  47834. while(offset < pixelLen) {
  47835. var alpha = pixels[offset + 3] / 256;
  47836. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  47837. // Simple optimize to ignore the empty data
  47838. if (alpha > 0) {
  47839. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  47840. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  47841. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  47842. pixels[offset++] = gradient[gradientOffset];
  47843. pixels[offset++] = gradient[gradientOffset + 1];
  47844. pixels[offset++] = gradient[gradientOffset + 2];
  47845. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  47846. }
  47847. else {
  47848. offset += 4;
  47849. }
  47850. }
  47851. ctx.putImageData(imageData, 0, 0);
  47852. return canvas;
  47853. },
  47854. /**
  47855. * get canvas of a black circle brush used for canvas to draw later
  47856. * @private
  47857. * @returns {Object} circle brush canvas
  47858. */
  47859. _getBrush: function() {
  47860. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  47861. // set brush size
  47862. var r = this.pointSize + this.blurSize;
  47863. var d = r * 2;
  47864. brushCanvas.width = d;
  47865. brushCanvas.height = d;
  47866. var ctx = brushCanvas.getContext('2d');
  47867. ctx.clearRect(0, 0, d, d);
  47868. // in order to render shadow without the distinct circle,
  47869. // draw the distinct circle in an invisible place,
  47870. // and use shadowOffset to draw shadow in the center of the canvas
  47871. ctx.shadowOffsetX = d;
  47872. ctx.shadowBlur = this.blurSize;
  47873. // draw the shadow in black, and use alpha and shadow blur to generate
  47874. // color in color map
  47875. ctx.shadowColor = '#000';
  47876. // draw circle in the left to the canvas
  47877. ctx.beginPath();
  47878. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  47879. ctx.closePath();
  47880. ctx.fill();
  47881. return brushCanvas;
  47882. },
  47883. /**
  47884. * get gradient color map
  47885. * @private
  47886. */
  47887. _getGradient: function (data, colorFunc, state) {
  47888. var gradientPixels = this._gradientPixels;
  47889. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  47890. var color = [0, 0, 0, 0];
  47891. var off = 0;
  47892. for (var i = 0; i < 256; i++) {
  47893. colorFunc[state](i / 255, true, color);
  47894. pixelsSingleState[off++] = color[0];
  47895. pixelsSingleState[off++] = color[1];
  47896. pixelsSingleState[off++] = color[2];
  47897. pixelsSingleState[off++] = color[3];
  47898. }
  47899. return pixelsSingleState;
  47900. }
  47901. };
  47902. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  47903. var dataSpan = dataExtent[1] - dataExtent[0];
  47904. pieceList = map(pieceList, function (piece) {
  47905. return {
  47906. interval: [
  47907. (piece.interval[0] - dataExtent[0]) / dataSpan,
  47908. (piece.interval[1] - dataExtent[0]) / dataSpan
  47909. ]
  47910. };
  47911. });
  47912. var len = pieceList.length;
  47913. var lastIndex = 0;
  47914. return function (val) {
  47915. // Try to find in the location of the last found
  47916. for (var i = lastIndex; i < len; i++) {
  47917. var interval = pieceList[i].interval;
  47918. if (interval[0] <= val && val <= interval[1]) {
  47919. lastIndex = i;
  47920. break;
  47921. }
  47922. }
  47923. if (i === len) { // Not found, back interation
  47924. for (var i = lastIndex - 1; i >= 0; i--) {
  47925. var interval = pieceList[i].interval;
  47926. if (interval[0] <= val && val <= interval[1]) {
  47927. lastIndex = i;
  47928. break;
  47929. }
  47930. }
  47931. }
  47932. return i >= 0 && i < len && selected[i];
  47933. };
  47934. }
  47935. function getIsInContinuousRange(dataExtent, range) {
  47936. var dataSpan = dataExtent[1] - dataExtent[0];
  47937. range = [
  47938. (range[0] - dataExtent[0]) / dataSpan,
  47939. (range[1] - dataExtent[0]) / dataSpan
  47940. ];
  47941. return function (val) {
  47942. return val >= range[0] && val <= range[1];
  47943. };
  47944. }
  47945. function isGeoCoordSys(coordSys) {
  47946. var dimensions = coordSys.dimensions;
  47947. // Not use coorSys.type === 'geo' because coordSys maybe extended
  47948. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  47949. }
  47950. extendChartView({
  47951. type: 'heatmap',
  47952. render: function (seriesModel, ecModel, api) {
  47953. var visualMapOfThisSeries;
  47954. ecModel.eachComponent('visualMap', function (visualMap) {
  47955. visualMap.eachTargetSeries(function (targetSeries) {
  47956. if (targetSeries === seriesModel) {
  47957. visualMapOfThisSeries = visualMap;
  47958. }
  47959. });
  47960. });
  47961. if (__DEV__) {
  47962. if (!visualMapOfThisSeries) {
  47963. throw new Error('Heatmap must use with visualMap');
  47964. }
  47965. }
  47966. this.group.removeAll();
  47967. this._incrementalDisplayable = null;
  47968. var coordSys = seriesModel.coordinateSystem;
  47969. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  47970. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  47971. }
  47972. else if (isGeoCoordSys(coordSys)) {
  47973. this._renderOnGeo(
  47974. coordSys, seriesModel, visualMapOfThisSeries, api
  47975. );
  47976. }
  47977. },
  47978. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  47979. this.group.removeAll();
  47980. },
  47981. incrementalRender: function (params, seriesModel, ecModel, api) {
  47982. var coordSys = seriesModel.coordinateSystem;
  47983. if (coordSys) {
  47984. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  47985. }
  47986. },
  47987. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  47988. var coordSys = seriesModel.coordinateSystem;
  47989. var width;
  47990. var height;
  47991. if (coordSys.type === 'cartesian2d') {
  47992. var xAxis = coordSys.getAxis('x');
  47993. var yAxis = coordSys.getAxis('y');
  47994. if (__DEV__) {
  47995. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  47996. throw new Error('Heatmap on cartesian must have two category axes');
  47997. }
  47998. if (!(xAxis.onBand && yAxis.onBand)) {
  47999. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  48000. }
  48001. }
  48002. width = xAxis.getBandWidth();
  48003. height = yAxis.getBandWidth();
  48004. }
  48005. var group = this.group;
  48006. var data = seriesModel.getData();
  48007. var itemStyleQuery = 'itemStyle';
  48008. var hoverItemStyleQuery = 'emphasis.itemStyle';
  48009. var labelQuery = 'label';
  48010. var hoverLabelQuery = 'emphasis.label';
  48011. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  48012. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  48013. var labelModel = seriesModel.getModel(labelQuery);
  48014. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  48015. var coordSysType = coordSys.type;
  48016. var dataDims = coordSysType === 'cartesian2d'
  48017. ? [
  48018. data.mapDimension('x'),
  48019. data.mapDimension('y'),
  48020. data.mapDimension('value')
  48021. ]
  48022. : [
  48023. data.mapDimension('time'),
  48024. data.mapDimension('value')
  48025. ];
  48026. for (var idx = start; idx < end; idx++) {
  48027. var rect;
  48028. if (coordSysType === 'cartesian2d') {
  48029. // Ignore empty data
  48030. if (isNaN(data.get(dataDims[2], idx))) {
  48031. continue;
  48032. }
  48033. var point = coordSys.dataToPoint([
  48034. data.get(dataDims[0], idx),
  48035. data.get(dataDims[1], idx)
  48036. ]);
  48037. rect = new Rect({
  48038. shape: {
  48039. x: point[0] - width / 2,
  48040. y: point[1] - height / 2,
  48041. width: width,
  48042. height: height
  48043. },
  48044. style: {
  48045. fill: data.getItemVisual(idx, 'color'),
  48046. opacity: data.getItemVisual(idx, 'opacity')
  48047. }
  48048. });
  48049. }
  48050. else {
  48051. // Ignore empty data
  48052. if (isNaN(data.get(dataDims[1], idx))) {
  48053. continue;
  48054. }
  48055. rect = new Rect({
  48056. z2: 1,
  48057. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  48058. style: {
  48059. fill: data.getItemVisual(idx, 'color'),
  48060. opacity: data.getItemVisual(idx, 'opacity')
  48061. }
  48062. });
  48063. }
  48064. var itemModel = data.getItemModel(idx);
  48065. // Optimization for large datset
  48066. if (data.hasItemOption) {
  48067. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  48068. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  48069. labelModel = itemModel.getModel(labelQuery);
  48070. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  48071. }
  48072. var rawValue = seriesModel.getRawValue(idx);
  48073. var defaultText = '-';
  48074. if (rawValue && rawValue[2] != null) {
  48075. defaultText = rawValue[2];
  48076. }
  48077. setLabelStyle(
  48078. style, hoverStl, labelModel, hoverLabelModel,
  48079. {
  48080. labelFetcher: seriesModel,
  48081. labelDataIndex: idx,
  48082. defaultText: defaultText,
  48083. isRectText: true
  48084. }
  48085. );
  48086. rect.setStyle(style);
  48087. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  48088. rect.incremental = incremental;
  48089. // PENDING
  48090. if (incremental) {
  48091. // Rect must use hover layer if it's incremental.
  48092. rect.useHoverLayer = true;
  48093. }
  48094. group.add(rect);
  48095. data.setItemGraphicEl(idx, rect);
  48096. }
  48097. },
  48098. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  48099. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  48100. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  48101. // if (!visualMapping) {
  48102. // throw new Error('Data range must have color visuals');
  48103. // }
  48104. var data = seriesModel.getData();
  48105. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  48106. hmLayer.blurSize = seriesModel.get('blurSize');
  48107. hmLayer.pointSize = seriesModel.get('pointSize');
  48108. hmLayer.minOpacity = seriesModel.get('minOpacity');
  48109. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  48110. var rect = geo.getViewRect().clone();
  48111. var roamTransform = geo.getRoamTransform();
  48112. rect.applyTransform(roamTransform);
  48113. // Clamp on viewport
  48114. var x = Math.max(rect.x, 0);
  48115. var y = Math.max(rect.y, 0);
  48116. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  48117. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  48118. var width = x2 - x;
  48119. var height = y2 - y;
  48120. var dims = [
  48121. data.mapDimension('lng'),
  48122. data.mapDimension('lat'),
  48123. data.mapDimension('value')
  48124. ];
  48125. var points = data.mapArray(dims, function (lng, lat, value) {
  48126. var pt = geo.dataToPoint([lng, lat]);
  48127. pt[0] -= x;
  48128. pt[1] -= y;
  48129. pt.push(value);
  48130. return pt;
  48131. });
  48132. var dataExtent = visualMapModel.getExtent();
  48133. var isInRange = visualMapModel.type === 'visualMap.continuous'
  48134. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  48135. : getIsInPiecewiseRange(
  48136. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  48137. );
  48138. hmLayer.update(
  48139. points, width, height,
  48140. inRangeVisuals.color.getNormalizer(),
  48141. {
  48142. inRange: inRangeVisuals.color.getColorMapper(),
  48143. outOfRange: outOfRangeVisuals.color.getColorMapper()
  48144. },
  48145. isInRange
  48146. );
  48147. var img = new ZImage({
  48148. style: {
  48149. width: width,
  48150. height: height,
  48151. x: x,
  48152. y: y,
  48153. image: hmLayer.canvas
  48154. },
  48155. silent: true
  48156. });
  48157. this.group.add(img);
  48158. },
  48159. dispose: function () {}
  48160. });
  48161. var PictorialBarSeries = BaseBarSeries.extend({
  48162. type: 'series.pictorialBar',
  48163. dependencies: ['grid'],
  48164. defaultOption: {
  48165. symbol: 'circle', // Customized bar shape
  48166. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  48167. symbolRotate: null,
  48168. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  48169. symbolOffset: null,
  48170. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  48171. // Auto margin by defualt.
  48172. symbolRepeat: false, // false/null/undefined, means no repeat.
  48173. // Can be true, means auto calculate repeat times and cut by data.
  48174. // Can be a number, specifies repeat times, and do not cut by data.
  48175. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  48176. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  48177. symbolClip: false,
  48178. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  48179. symbolPatternSize: 400, // 400 * 400 px
  48180. barGap: '-100%', // In most case, overlap is needed.
  48181. // z can be set in data item, which is z2 actually.
  48182. // Disable progressive
  48183. progressive: 0,
  48184. hoverAnimation: false // Open only when needed.
  48185. },
  48186. getInitialData: function (option) {
  48187. // Disable stack.
  48188. option.stack = null;
  48189. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  48190. }
  48191. });
  48192. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  48193. // index: +isHorizontal
  48194. var LAYOUT_ATTRS = [
  48195. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  48196. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  48197. ];
  48198. var pathForLineWidth = new Circle();
  48199. var BarView$1 = extendChartView({
  48200. type: 'pictorialBar',
  48201. render: function (seriesModel, ecModel, api) {
  48202. var group = this.group;
  48203. var data = seriesModel.getData();
  48204. var oldData = this._data;
  48205. var cartesian = seriesModel.coordinateSystem;
  48206. var baseAxis = cartesian.getBaseAxis();
  48207. var isHorizontal = !!baseAxis.isHorizontal();
  48208. var coordSysRect = cartesian.grid.getRect();
  48209. var opt = {
  48210. ecSize: {width: api.getWidth(), height: api.getHeight()},
  48211. seriesModel: seriesModel,
  48212. coordSys: cartesian,
  48213. coordSysExtent: [
  48214. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  48215. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  48216. ],
  48217. isHorizontal: isHorizontal,
  48218. valueDim: LAYOUT_ATTRS[+isHorizontal],
  48219. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  48220. };
  48221. data.diff(oldData)
  48222. .add(function (dataIndex) {
  48223. if (!data.hasValue(dataIndex)) {
  48224. return;
  48225. }
  48226. var itemModel = getItemModel(data, dataIndex);
  48227. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  48228. var bar = createBar(data, opt, symbolMeta);
  48229. data.setItemGraphicEl(dataIndex, bar);
  48230. group.add(bar);
  48231. updateCommon$1(bar, opt, symbolMeta);
  48232. })
  48233. .update(function (newIndex, oldIndex) {
  48234. var bar = oldData.getItemGraphicEl(oldIndex);
  48235. if (!data.hasValue(newIndex)) {
  48236. group.remove(bar);
  48237. return;
  48238. }
  48239. var itemModel = getItemModel(data, newIndex);
  48240. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  48241. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  48242. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  48243. group.remove(bar);
  48244. data.setItemGraphicEl(newIndex, null);
  48245. bar = null;
  48246. }
  48247. if (bar) {
  48248. updateBar(bar, opt, symbolMeta);
  48249. }
  48250. else {
  48251. bar = createBar(data, opt, symbolMeta, true);
  48252. }
  48253. data.setItemGraphicEl(newIndex, bar);
  48254. bar.__pictorialSymbolMeta = symbolMeta;
  48255. // Add back
  48256. group.add(bar);
  48257. updateCommon$1(bar, opt, symbolMeta);
  48258. })
  48259. .remove(function (dataIndex) {
  48260. var bar = oldData.getItemGraphicEl(dataIndex);
  48261. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  48262. })
  48263. .execute();
  48264. this._data = data;
  48265. return this.group;
  48266. },
  48267. dispose: noop,
  48268. remove: function (ecModel, api) {
  48269. var group = this.group;
  48270. var data = this._data;
  48271. if (ecModel.get('animation')) {
  48272. if (data) {
  48273. data.eachItemGraphicEl(function (bar) {
  48274. removeBar(data, bar.dataIndex, ecModel, bar);
  48275. });
  48276. }
  48277. }
  48278. else {
  48279. group.removeAll();
  48280. }
  48281. }
  48282. });
  48283. // Set or calculate default value about symbol, and calculate layout info.
  48284. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  48285. var layout = data.getItemLayout(dataIndex);
  48286. var symbolRepeat = itemModel.get('symbolRepeat');
  48287. var symbolClip = itemModel.get('symbolClip');
  48288. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  48289. var symbolRotate = itemModel.get('symbolRotate');
  48290. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  48291. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  48292. var isAnimationEnabled = itemModel.isAnimationEnabled();
  48293. var symbolMeta = {
  48294. dataIndex: dataIndex,
  48295. layout: layout,
  48296. itemModel: itemModel,
  48297. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  48298. color: data.getItemVisual(dataIndex, 'color'),
  48299. symbolClip: symbolClip,
  48300. symbolRepeat: symbolRepeat,
  48301. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  48302. symbolPatternSize: symbolPatternSize,
  48303. rotation: rotation,
  48304. animationModel: isAnimationEnabled ? itemModel : null,
  48305. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  48306. z2: itemModel.getShallow('z', true) || 0
  48307. };
  48308. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  48309. prepareSymbolSize(
  48310. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  48311. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  48312. );
  48313. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  48314. var symbolSize = symbolMeta.symbolSize;
  48315. var symbolOffset = itemModel.get('symbolOffset');
  48316. if (isArray(symbolOffset)) {
  48317. symbolOffset = [
  48318. parsePercent$1(symbolOffset[0], symbolSize[0]),
  48319. parsePercent$1(symbolOffset[1], symbolSize[1])
  48320. ];
  48321. }
  48322. prepareLayoutInfo(
  48323. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  48324. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  48325. opt, symbolMeta
  48326. );
  48327. return symbolMeta;
  48328. }
  48329. // bar length can be negative.
  48330. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  48331. var valueDim = opt.valueDim;
  48332. var symbolBoundingData = itemModel.get('symbolBoundingData');
  48333. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  48334. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  48335. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  48336. var boundingLength;
  48337. if (isArray(symbolBoundingData)) {
  48338. var symbolBoundingExtent = [
  48339. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  48340. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  48341. ];
  48342. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  48343. boundingLength = symbolBoundingExtent[pxSignIdx];
  48344. }
  48345. else if (symbolBoundingData != null) {
  48346. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  48347. }
  48348. else if (symbolRepeat) {
  48349. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  48350. }
  48351. else {
  48352. boundingLength = layout[valueDim.wh];
  48353. }
  48354. output.boundingLength = boundingLength;
  48355. if (symbolRepeat) {
  48356. output.repeatCutLength = layout[valueDim.wh];
  48357. }
  48358. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  48359. }
  48360. function convertToCoordOnAxis(axis, value) {
  48361. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  48362. }
  48363. // Support ['100%', '100%']
  48364. function prepareSymbolSize(
  48365. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  48366. pxSign, symbolPatternSize, opt, output
  48367. ) {
  48368. var valueDim = opt.valueDim;
  48369. var categoryDim = opt.categoryDim;
  48370. var categorySize = Math.abs(layout[categoryDim.wh]);
  48371. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  48372. if (isArray(symbolSize)) {
  48373. symbolSize = symbolSize.slice();
  48374. }
  48375. else {
  48376. if (symbolSize == null) {
  48377. symbolSize = '100%';
  48378. }
  48379. symbolSize = [symbolSize, symbolSize];
  48380. }
  48381. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  48382. // to complicated to calculate real percent value if considering scaled lineWidth.
  48383. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  48384. // which can be tolerated in pictorial chart.
  48385. symbolSize[categoryDim.index] = parsePercent$1(
  48386. symbolSize[categoryDim.index],
  48387. categorySize
  48388. );
  48389. symbolSize[valueDim.index] = parsePercent$1(
  48390. symbolSize[valueDim.index],
  48391. symbolRepeat ? categorySize : Math.abs(boundingLength)
  48392. );
  48393. output.symbolSize = symbolSize;
  48394. // If x or y is less than zero, show reversed shape.
  48395. var symbolScale = output.symbolScale = [
  48396. symbolSize[0] / symbolPatternSize,
  48397. symbolSize[1] / symbolPatternSize
  48398. ];
  48399. // Follow convention, 'right' and 'top' is the normal scale.
  48400. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  48401. }
  48402. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  48403. // In symbols are drawn with scale, so do not need to care about the case that width
  48404. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  48405. // be calculated.
  48406. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  48407. if (valueLineWidth) {
  48408. pathForLineWidth.attr({
  48409. scale: symbolScale.slice(),
  48410. rotation: rotation
  48411. });
  48412. pathForLineWidth.updateTransform();
  48413. valueLineWidth /= pathForLineWidth.getLineScale();
  48414. valueLineWidth *= symbolScale[opt.valueDim.index];
  48415. }
  48416. output.valueLineWidth = valueLineWidth;
  48417. }
  48418. function prepareLayoutInfo(
  48419. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  48420. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  48421. ) {
  48422. var categoryDim = opt.categoryDim;
  48423. var valueDim = opt.valueDim;
  48424. var pxSign = output.pxSign;
  48425. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  48426. var pathLen = unitLength;
  48427. // Note: rotation will not effect the layout of symbols, because user may
  48428. // want symbols to rotate on its center, which should not be translated
  48429. // when rotating.
  48430. if (symbolRepeat) {
  48431. var absBoundingLength = Math.abs(boundingLength);
  48432. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  48433. var hasEndGap = false;
  48434. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  48435. hasEndGap = true;
  48436. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  48437. }
  48438. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  48439. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  48440. // When symbol margin is less than 0, margin at both ends will be subtracted
  48441. // to ensure that all of the symbols will not be overflow the given area.
  48442. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  48443. // Both final repeatTimes and final symbolMargin area calculated based on
  48444. // boundingLength.
  48445. var repeatSpecified = isNumeric(symbolRepeat);
  48446. var repeatTimes = repeatSpecified
  48447. ? symbolRepeat
  48448. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  48449. // Adjust calculate margin, to ensure each symbol is displayed
  48450. // entirely in the given layout area.
  48451. var mDiff = absBoundingLength - repeatTimes * unitLength;
  48452. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  48453. uLenWithMargin = unitLength + symbolMargin * 2;
  48454. endFix = hasEndGap ? 0 : symbolMargin * 2;
  48455. // Update repeatTimes when not all symbol will be shown.
  48456. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  48457. repeatTimes = repeatCutLength
  48458. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  48459. : 0;
  48460. }
  48461. pathLen = repeatTimes * uLenWithMargin - endFix;
  48462. output.repeatTimes = repeatTimes;
  48463. output.symbolMargin = symbolMargin;
  48464. }
  48465. var sizeFix = pxSign * (pathLen / 2);
  48466. var pathPosition = output.pathPosition = [];
  48467. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  48468. pathPosition[valueDim.index] = symbolPosition === 'start'
  48469. ? sizeFix
  48470. : symbolPosition === 'end'
  48471. ? boundingLength - sizeFix
  48472. : boundingLength / 2; // 'center'
  48473. if (symbolOffset) {
  48474. pathPosition[0] += symbolOffset[0];
  48475. pathPosition[1] += symbolOffset[1];
  48476. }
  48477. var bundlePosition = output.bundlePosition = [];
  48478. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  48479. bundlePosition[valueDim.index] = layout[valueDim.xy];
  48480. var barRectShape = output.barRectShape = extend({}, layout);
  48481. barRectShape[valueDim.wh] = pxSign * Math.max(
  48482. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  48483. );
  48484. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  48485. var clipShape = output.clipShape = {};
  48486. // Consider that symbol may be overflow layout rect.
  48487. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  48488. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  48489. clipShape[valueDim.xy] = 0;
  48490. clipShape[valueDim.wh] = layout[valueDim.wh];
  48491. }
  48492. function createPath(symbolMeta) {
  48493. var symbolPatternSize = symbolMeta.symbolPatternSize;
  48494. var path = createSymbol(
  48495. // Consider texture img, make a big size.
  48496. symbolMeta.symbolType,
  48497. -symbolPatternSize / 2,
  48498. -symbolPatternSize / 2,
  48499. symbolPatternSize,
  48500. symbolPatternSize,
  48501. symbolMeta.color
  48502. );
  48503. path.attr({
  48504. culling: true
  48505. });
  48506. path.type !== 'image' && path.setStyle({
  48507. strokeNoScale: true
  48508. });
  48509. return path;
  48510. }
  48511. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  48512. var bundle = bar.__pictorialBundle;
  48513. var symbolSize = symbolMeta.symbolSize;
  48514. var valueLineWidth = symbolMeta.valueLineWidth;
  48515. var pathPosition = symbolMeta.pathPosition;
  48516. var valueDim = opt.valueDim;
  48517. var repeatTimes = symbolMeta.repeatTimes || 0;
  48518. var index = 0;
  48519. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  48520. eachPath(bar, function (path) {
  48521. path.__pictorialAnimationIndex = index;
  48522. path.__pictorialRepeatTimes = repeatTimes;
  48523. if (index < repeatTimes) {
  48524. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  48525. }
  48526. else {
  48527. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  48528. bundle.remove(path);
  48529. });
  48530. }
  48531. updateHoverAnimation(path, symbolMeta);
  48532. index++;
  48533. });
  48534. for (; index < repeatTimes; index++) {
  48535. var path = createPath(symbolMeta);
  48536. path.__pictorialAnimationIndex = index;
  48537. path.__pictorialRepeatTimes = repeatTimes;
  48538. bundle.add(path);
  48539. var target = makeTarget(index);
  48540. updateAttr(
  48541. path,
  48542. {
  48543. position: target.position,
  48544. scale: [0, 0]
  48545. },
  48546. {
  48547. scale: target.scale,
  48548. rotation: target.rotation
  48549. },
  48550. symbolMeta,
  48551. isUpdate
  48552. );
  48553. // FIXME
  48554. // If all emphasis/normal through action.
  48555. path
  48556. .on('mouseover', onMouseOver)
  48557. .on('mouseout', onMouseOut);
  48558. updateHoverAnimation(path, symbolMeta);
  48559. }
  48560. function makeTarget(index) {
  48561. var position = pathPosition.slice();
  48562. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  48563. // Otherwise: i = index;
  48564. var pxSign = symbolMeta.pxSign;
  48565. var i = index;
  48566. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  48567. i = repeatTimes - 1 - index;
  48568. }
  48569. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  48570. return {
  48571. position: position,
  48572. scale: symbolMeta.symbolScale.slice(),
  48573. rotation: symbolMeta.rotation
  48574. };
  48575. }
  48576. function onMouseOver() {
  48577. eachPath(bar, function (path) {
  48578. path.trigger('emphasis');
  48579. });
  48580. }
  48581. function onMouseOut() {
  48582. eachPath(bar, function (path) {
  48583. path.trigger('normal');
  48584. });
  48585. }
  48586. }
  48587. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  48588. var bundle = bar.__pictorialBundle;
  48589. var mainPath = bar.__pictorialMainPath;
  48590. if (!mainPath) {
  48591. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  48592. bundle.add(mainPath);
  48593. updateAttr(
  48594. mainPath,
  48595. {
  48596. position: symbolMeta.pathPosition.slice(),
  48597. scale: [0, 0],
  48598. rotation: symbolMeta.rotation
  48599. },
  48600. {
  48601. scale: symbolMeta.symbolScale.slice()
  48602. },
  48603. symbolMeta,
  48604. isUpdate
  48605. );
  48606. mainPath
  48607. .on('mouseover', onMouseOver)
  48608. .on('mouseout', onMouseOut);
  48609. }
  48610. else {
  48611. updateAttr(
  48612. mainPath,
  48613. null,
  48614. {
  48615. position: symbolMeta.pathPosition.slice(),
  48616. scale: symbolMeta.symbolScale.slice(),
  48617. rotation: symbolMeta.rotation
  48618. },
  48619. symbolMeta,
  48620. isUpdate
  48621. );
  48622. }
  48623. updateHoverAnimation(mainPath, symbolMeta);
  48624. function onMouseOver() {
  48625. this.trigger('emphasis');
  48626. }
  48627. function onMouseOut() {
  48628. this.trigger('normal');
  48629. }
  48630. }
  48631. // bar rect is used for label.
  48632. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  48633. var rectShape = extend({}, symbolMeta.barRectShape);
  48634. var barRect = bar.__pictorialBarRect;
  48635. if (!barRect) {
  48636. barRect = bar.__pictorialBarRect = new Rect({
  48637. z2: 2,
  48638. shape: rectShape,
  48639. silent: true,
  48640. style: {
  48641. stroke: 'transparent',
  48642. fill: 'transparent',
  48643. lineWidth: 0
  48644. }
  48645. });
  48646. bar.add(barRect);
  48647. }
  48648. else {
  48649. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  48650. }
  48651. }
  48652. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  48653. // If not clip, symbol will be remove and rebuilt.
  48654. if (symbolMeta.symbolClip) {
  48655. var clipPath = bar.__pictorialClipPath;
  48656. var clipShape = extend({}, symbolMeta.clipShape);
  48657. var valueDim = opt.valueDim;
  48658. var animationModel = symbolMeta.animationModel;
  48659. var dataIndex = symbolMeta.dataIndex;
  48660. if (clipPath) {
  48661. updateProps(
  48662. clipPath, {shape: clipShape}, animationModel, dataIndex
  48663. );
  48664. }
  48665. else {
  48666. clipShape[valueDim.wh] = 0;
  48667. clipPath = new Rect({shape: clipShape});
  48668. bar.__pictorialBundle.setClipPath(clipPath);
  48669. bar.__pictorialClipPath = clipPath;
  48670. var target = {};
  48671. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  48672. graphic[isUpdate ? 'updateProps' : 'initProps'](
  48673. clipPath, {shape: target}, animationModel, dataIndex
  48674. );
  48675. }
  48676. }
  48677. }
  48678. function getItemModel(data, dataIndex) {
  48679. var itemModel = data.getItemModel(dataIndex);
  48680. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  48681. itemModel.isAnimationEnabled = isAnimationEnabled;
  48682. return itemModel;
  48683. }
  48684. function getAnimationDelayParams(path) {
  48685. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  48686. return {
  48687. index: path.__pictorialAnimationIndex,
  48688. count: path.__pictorialRepeatTimes
  48689. };
  48690. }
  48691. function isAnimationEnabled() {
  48692. // `animation` prop can be set on itemModel in pictorial bar chart.
  48693. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  48694. }
  48695. function updateHoverAnimation(path, symbolMeta) {
  48696. path.off('emphasis').off('normal');
  48697. var scale = symbolMeta.symbolScale.slice();
  48698. symbolMeta.hoverAnimation && path
  48699. .on('emphasis', function() {
  48700. this.animateTo({
  48701. scale: [scale[0] * 1.1, scale[1] * 1.1]
  48702. }, 400, 'elasticOut');
  48703. })
  48704. .on('normal', function() {
  48705. this.animateTo({
  48706. scale: scale.slice()
  48707. }, 400, 'elasticOut');
  48708. });
  48709. }
  48710. function createBar(data, opt, symbolMeta, isUpdate) {
  48711. // bar is the main element for each data.
  48712. var bar = new Group();
  48713. // bundle is used for location and clip.
  48714. var bundle = new Group();
  48715. bar.add(bundle);
  48716. bar.__pictorialBundle = bundle;
  48717. bundle.attr('position', symbolMeta.bundlePosition.slice());
  48718. if (symbolMeta.symbolRepeat) {
  48719. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  48720. }
  48721. else {
  48722. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  48723. }
  48724. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  48725. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  48726. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  48727. bar.__pictorialSymbolMeta = symbolMeta;
  48728. return bar;
  48729. }
  48730. function updateBar(bar, opt, symbolMeta) {
  48731. var animationModel = symbolMeta.animationModel;
  48732. var dataIndex = symbolMeta.dataIndex;
  48733. var bundle = bar.__pictorialBundle;
  48734. updateProps(
  48735. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  48736. );
  48737. if (symbolMeta.symbolRepeat) {
  48738. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  48739. }
  48740. else {
  48741. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  48742. }
  48743. createOrUpdateBarRect(bar, symbolMeta, true);
  48744. createOrUpdateClip(bar, opt, symbolMeta, true);
  48745. }
  48746. function removeBar(data, dataIndex, animationModel, bar) {
  48747. // Not show text when animating
  48748. var labelRect = bar.__pictorialBarRect;
  48749. labelRect && (labelRect.style.text = null);
  48750. var pathes = [];
  48751. eachPath(bar, function (path) {
  48752. pathes.push(path);
  48753. });
  48754. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  48755. // I do not find proper remove animation for clip yet.
  48756. bar.__pictorialClipPath && (animationModel = null);
  48757. each$1(pathes, function (path) {
  48758. updateProps(
  48759. path, {scale: [0, 0]}, animationModel, dataIndex,
  48760. function () {
  48761. bar.parent && bar.parent.remove(bar);
  48762. }
  48763. );
  48764. });
  48765. data.setItemGraphicEl(dataIndex, null);
  48766. }
  48767. function getShapeStr(data, symbolMeta) {
  48768. return [
  48769. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  48770. !!symbolMeta.symbolRepeat,
  48771. !!symbolMeta.symbolClip
  48772. ].join(':');
  48773. }
  48774. function eachPath(bar, cb, context) {
  48775. // Do not use Group#eachChild, because it do not support remove.
  48776. each$1(bar.__pictorialBundle.children(), function (el) {
  48777. el !== bar.__pictorialBarRect && cb.call(context, el);
  48778. });
  48779. }
  48780. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  48781. immediateAttrs && el.attr(immediateAttrs);
  48782. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  48783. if (symbolMeta.symbolClip && !isUpdate) {
  48784. animationAttrs && el.attr(animationAttrs);
  48785. }
  48786. else {
  48787. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  48788. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  48789. );
  48790. }
  48791. }
  48792. function updateCommon$1(bar, opt, symbolMeta) {
  48793. var color = symbolMeta.color;
  48794. var dataIndex = symbolMeta.dataIndex;
  48795. var itemModel = symbolMeta.itemModel;
  48796. // Color must be excluded.
  48797. // Because symbol provide setColor individually to set fill and stroke
  48798. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  48799. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  48800. var cursorStyle = itemModel.getShallow('cursor');
  48801. eachPath(bar, function (path) {
  48802. // PENDING setColor should be before setStyle!!!
  48803. path.setColor(color);
  48804. path.setStyle(defaults(
  48805. {
  48806. fill: color,
  48807. opacity: symbolMeta.opacity
  48808. },
  48809. normalStyle
  48810. ));
  48811. setHoverStyle(path, hoverStyle);
  48812. cursorStyle && (path.cursor = cursorStyle);
  48813. path.z2 = symbolMeta.z2;
  48814. });
  48815. var barRectHoverStyle = {};
  48816. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  48817. var barRect = bar.__pictorialBarRect;
  48818. setLabel(
  48819. barRect.style, barRectHoverStyle, itemModel,
  48820. color, opt.seriesModel, dataIndex, barPositionOutside
  48821. );
  48822. setHoverStyle(barRect, barRectHoverStyle);
  48823. }
  48824. function toIntTimes(times) {
  48825. var roundedTimes = Math.round(times);
  48826. // Escapse accurate error
  48827. return Math.abs(times - roundedTimes) < 1e-4
  48828. ? roundedTimes
  48829. : Math.ceil(times);
  48830. }
  48831. // In case developer forget to include grid component
  48832. registerLayout(curry(
  48833. layout, 'pictorialBar'
  48834. ));
  48835. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  48836. /**
  48837. * @constructor module:echarts/coord/single/SingleAxis
  48838. * @extends {module:echarts/coord/Axis}
  48839. * @param {string} dim
  48840. * @param {*} scale
  48841. * @param {Array.<number>} coordExtent
  48842. * @param {string} axisType
  48843. * @param {string} position
  48844. */
  48845. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  48846. Axis.call(this, dim, scale, coordExtent);
  48847. /**
  48848. * Axis type
  48849. * - 'category'
  48850. * - 'value'
  48851. * - 'time'
  48852. * - 'log'
  48853. * @type {string}
  48854. */
  48855. this.type = axisType || 'value';
  48856. /**
  48857. * Axis position
  48858. * - 'top'
  48859. * - 'bottom'
  48860. * - 'left'
  48861. * - 'right'
  48862. * @type {string}
  48863. */
  48864. this.position = position || 'bottom';
  48865. /**
  48866. * Axis orient
  48867. * - 'horizontal'
  48868. * - 'vertical'
  48869. * @type {[type]}
  48870. */
  48871. this.orient = null;
  48872. /**
  48873. * @type {number}
  48874. */
  48875. this._labelInterval = null;
  48876. };
  48877. SingleAxis.prototype = {
  48878. constructor: SingleAxis,
  48879. /**
  48880. * Axis model
  48881. * @type {module:echarts/coord/single/AxisModel}
  48882. */
  48883. model: null,
  48884. /**
  48885. * Judge the orient of the axis.
  48886. * @return {boolean}
  48887. */
  48888. isHorizontal: function () {
  48889. var position = this.position;
  48890. return position === 'top' || position === 'bottom';
  48891. },
  48892. /**
  48893. * @override
  48894. */
  48895. pointToData: function (point, clamp) {
  48896. return this.coordinateSystem.pointToData(point, clamp)[0];
  48897. },
  48898. /**
  48899. * Convert the local coord(processed by dataToCoord())
  48900. * to global coord(concrete pixel coord).
  48901. * designated by module:echarts/coord/single/Single.
  48902. * @type {Function}
  48903. */
  48904. toGlobalCoord: null,
  48905. /**
  48906. * Convert the global coord to local coord.
  48907. * designated by module:echarts/coord/single/Single.
  48908. * @type {Function}
  48909. */
  48910. toLocalCoord: null
  48911. };
  48912. inherits(SingleAxis, Axis);
  48913. /**
  48914. * Single coordinates system.
  48915. */
  48916. /**
  48917. * Create a single coordinates system.
  48918. *
  48919. * @param {module:echarts/coord/single/AxisModel} axisModel
  48920. * @param {module:echarts/model/Global} ecModel
  48921. * @param {module:echarts/ExtensionAPI} api
  48922. */
  48923. function Single(axisModel, ecModel, api) {
  48924. /**
  48925. * @type {string}
  48926. * @readOnly
  48927. */
  48928. this.dimension = 'single';
  48929. /**
  48930. * Add it just for draw tooltip.
  48931. *
  48932. * @type {Array.<string>}
  48933. * @readOnly
  48934. */
  48935. this.dimensions = ['single'];
  48936. /**
  48937. * @private
  48938. * @type {module:echarts/coord/single/SingleAxis}.
  48939. */
  48940. this._axis = null;
  48941. /**
  48942. * @private
  48943. * @type {module:zrender/core/BoundingRect}
  48944. */
  48945. this._rect;
  48946. this._init(axisModel, ecModel, api);
  48947. /**
  48948. * @type {module:echarts/coord/single/AxisModel}
  48949. */
  48950. this.model = axisModel;
  48951. }
  48952. Single.prototype = {
  48953. type: 'singleAxis',
  48954. axisPointerEnabled: true,
  48955. constructor: Single,
  48956. /**
  48957. * Initialize single coordinate system.
  48958. *
  48959. * @param {module:echarts/coord/single/AxisModel} axisModel
  48960. * @param {module:echarts/model/Global} ecModel
  48961. * @param {module:echarts/ExtensionAPI} api
  48962. * @private
  48963. */
  48964. _init: function (axisModel, ecModel, api) {
  48965. var dim = this.dimension;
  48966. var axis = new SingleAxis(
  48967. dim,
  48968. createScaleByModel(axisModel),
  48969. [0, 0],
  48970. axisModel.get('type'),
  48971. axisModel.get('position')
  48972. );
  48973. var isCategory = axis.type === 'category';
  48974. axis.onBand = isCategory && axisModel.get('boundaryGap');
  48975. axis.inverse = axisModel.get('inverse');
  48976. axis.orient = axisModel.get('orient');
  48977. axisModel.axis = axis;
  48978. axis.model = axisModel;
  48979. axis.coordinateSystem = this;
  48980. this._axis = axis;
  48981. },
  48982. /**
  48983. * Update axis scale after data processed
  48984. * @param {module:echarts/model/Global} ecModel
  48985. * @param {module:echarts/ExtensionAPI} api
  48986. */
  48987. update: function (ecModel, api) {
  48988. ecModel.eachSeries(function (seriesModel) {
  48989. if (seriesModel.coordinateSystem === this) {
  48990. var data = seriesModel.getData();
  48991. each$1(data.mapDimension(this.dimension, true), function (dim) {
  48992. this._axis.scale.unionExtentFromData(data, dim);
  48993. }, this);
  48994. niceScaleExtent(this._axis.scale, this._axis.model);
  48995. }
  48996. }, this);
  48997. },
  48998. /**
  48999. * Resize the single coordinate system.
  49000. *
  49001. * @param {module:echarts/coord/single/AxisModel} axisModel
  49002. * @param {module:echarts/ExtensionAPI} api
  49003. */
  49004. resize: function (axisModel, api) {
  49005. this._rect = getLayoutRect(
  49006. {
  49007. left: axisModel.get('left'),
  49008. top: axisModel.get('top'),
  49009. right: axisModel.get('right'),
  49010. bottom: axisModel.get('bottom'),
  49011. width: axisModel.get('width'),
  49012. height: axisModel.get('height')
  49013. },
  49014. {
  49015. width: api.getWidth(),
  49016. height: api.getHeight()
  49017. }
  49018. );
  49019. this._adjustAxis();
  49020. },
  49021. /**
  49022. * @return {module:zrender/core/BoundingRect}
  49023. */
  49024. getRect: function () {
  49025. return this._rect;
  49026. },
  49027. /**
  49028. * @private
  49029. */
  49030. _adjustAxis: function () {
  49031. var rect = this._rect;
  49032. var axis = this._axis;
  49033. var isHorizontal = axis.isHorizontal();
  49034. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  49035. var idx = axis.reverse ? 1 : 0;
  49036. axis.setExtent(extent[idx], extent[1 - idx]);
  49037. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  49038. },
  49039. /**
  49040. * @param {module:echarts/coord/single/SingleAxis} axis
  49041. * @param {number} coordBase
  49042. */
  49043. _updateAxisTransform: function (axis, coordBase) {
  49044. var axisExtent = axis.getExtent();
  49045. var extentSum = axisExtent[0] + axisExtent[1];
  49046. var isHorizontal = axis.isHorizontal();
  49047. axis.toGlobalCoord = isHorizontal
  49048. ? function (coord) {
  49049. return coord + coordBase;
  49050. }
  49051. : function (coord) {
  49052. return extentSum - coord + coordBase;
  49053. };
  49054. axis.toLocalCoord = isHorizontal
  49055. ? function (coord) {
  49056. return coord - coordBase;
  49057. }
  49058. : function (coord) {
  49059. return extentSum - coord + coordBase;
  49060. };
  49061. },
  49062. /**
  49063. * Get axis.
  49064. *
  49065. * @return {module:echarts/coord/single/SingleAxis}
  49066. */
  49067. getAxis: function () {
  49068. return this._axis;
  49069. },
  49070. /**
  49071. * Get axis, add it just for draw tooltip.
  49072. *
  49073. * @return {[type]} [description]
  49074. */
  49075. getBaseAxis: function () {
  49076. return this._axis;
  49077. },
  49078. /**
  49079. * @return {Array.<module:echarts/coord/Axis>}
  49080. */
  49081. getAxes: function () {
  49082. return [this._axis];
  49083. },
  49084. /**
  49085. * @return {Object} {baseAxes: [], otherAxes: []}
  49086. */
  49087. getTooltipAxes: function () {
  49088. return {baseAxes: [this.getAxis()]};
  49089. },
  49090. /**
  49091. * If contain point.
  49092. *
  49093. * @param {Array.<number>} point
  49094. * @return {boolean}
  49095. */
  49096. containPoint: function (point) {
  49097. var rect = this.getRect();
  49098. var axis = this.getAxis();
  49099. var orient = axis.orient;
  49100. if (orient === 'horizontal') {
  49101. return axis.contain(axis.toLocalCoord(point[0]))
  49102. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  49103. }
  49104. else {
  49105. return axis.contain(axis.toLocalCoord(point[1]))
  49106. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  49107. }
  49108. },
  49109. /**
  49110. * @param {Array.<number>} point
  49111. * @return {Array.<number>}
  49112. */
  49113. pointToData: function (point) {
  49114. var axis = this.getAxis();
  49115. return [axis.coordToData(axis.toLocalCoord(
  49116. point[axis.orient === 'horizontal' ? 0 : 1]
  49117. ))];
  49118. },
  49119. /**
  49120. * Convert the series data to concrete point.
  49121. *
  49122. * @param {number|Array.<number>} val
  49123. * @return {Array.<number>}
  49124. */
  49125. dataToPoint: function (val) {
  49126. var axis = this.getAxis();
  49127. var rect = this.getRect();
  49128. var pt = [];
  49129. var idx = axis.orient === 'horizontal' ? 0 : 1;
  49130. if (val instanceof Array) {
  49131. val = val[0];
  49132. }
  49133. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  49134. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  49135. return pt;
  49136. }
  49137. };
  49138. /**
  49139. * Single coordinate system creator.
  49140. */
  49141. /**
  49142. * Create single coordinate system and inject it into seriesModel.
  49143. *
  49144. * @param {module:echarts/model/Global} ecModel
  49145. * @param {module:echarts/ExtensionAPI} api
  49146. * @return {Array.<module:echarts/coord/single/Single>}
  49147. */
  49148. function create$3(ecModel, api) {
  49149. var singles = [];
  49150. ecModel.eachComponent('singleAxis', function(axisModel, idx) {
  49151. var single = new Single(axisModel, ecModel, api);
  49152. single.name = 'single_' + idx;
  49153. single.resize(axisModel, api);
  49154. axisModel.coordinateSystem = single;
  49155. singles.push(single);
  49156. });
  49157. ecModel.eachSeries(function (seriesModel) {
  49158. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  49159. var singleAxisModel = ecModel.queryComponents({
  49160. mainType: 'singleAxis',
  49161. index: seriesModel.get('singleAxisIndex'),
  49162. id: seriesModel.get('singleAxisId')
  49163. })[0];
  49164. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  49165. }
  49166. });
  49167. return singles;
  49168. }
  49169. CoordinateSystemManager.register('single', {
  49170. create: create$3,
  49171. dimensions: Single.prototype.dimensions
  49172. });
  49173. /**
  49174. * @param {Object} opt {labelInside}
  49175. * @return {Object} {
  49176. * position, rotation, labelDirection, labelOffset,
  49177. * tickDirection, labelRotate, labelInterval, z2
  49178. * }
  49179. */
  49180. function layout$2 (axisModel, opt) {
  49181. opt = opt || {};
  49182. var single = axisModel.coordinateSystem;
  49183. var axis = axisModel.axis;
  49184. var layout = {};
  49185. var axisPosition = axis.position;
  49186. var orient = axis.orient;
  49187. var rect = single.getRect();
  49188. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  49189. var positionMap = {
  49190. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  49191. vertical: {left: rectBound[0], right: rectBound[1]}
  49192. };
  49193. layout.position = [
  49194. orient === 'vertical'
  49195. ? positionMap.vertical[axisPosition]
  49196. : rectBound[0],
  49197. orient === 'horizontal'
  49198. ? positionMap.horizontal[axisPosition]
  49199. : rectBound[3]
  49200. ];
  49201. var r = {horizontal: 0, vertical: 1};
  49202. layout.rotation = Math.PI / 2 * r[orient];
  49203. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  49204. layout.labelDirection = layout.tickDirection
  49205. = layout.nameDirection
  49206. = directionMap[axisPosition];
  49207. if (axisModel.get('axisTick.inside')) {
  49208. layout.tickDirection = -layout.tickDirection;
  49209. }
  49210. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  49211. layout.labelDirection = -layout.labelDirection;
  49212. }
  49213. var labelRotation = opt.rotate;
  49214. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  49215. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  49216. layout.labelInterval = axis.getLabelInterval();
  49217. layout.z2 = 1;
  49218. return layout;
  49219. }
  49220. var getInterval$2 = AxisBuilder.getInterval;
  49221. var ifIgnoreOnTick$2 = AxisBuilder.ifIgnoreOnTick;
  49222. var axisBuilderAttrs$2 = [
  49223. 'axisLine', 'axisTickLabel', 'axisName'
  49224. ];
  49225. var selfBuilderAttr = 'splitLine';
  49226. var SingleAxisView = AxisView.extend({
  49227. type: 'singleAxis',
  49228. axisPointerClass: 'SingleAxisPointer',
  49229. render: function (axisModel, ecModel, api, payload) {
  49230. var group = this.group;
  49231. group.removeAll();
  49232. var layout = layout$2(axisModel);
  49233. var axisBuilder = new AxisBuilder(axisModel, layout);
  49234. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  49235. group.add(axisBuilder.getGroup());
  49236. if (axisModel.get(selfBuilderAttr + '.show')) {
  49237. this['_' + selfBuilderAttr](axisModel, layout.labelInterval);
  49238. }
  49239. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  49240. },
  49241. _splitLine: function(axisModel, labelInterval) {
  49242. var axis = axisModel.axis;
  49243. if (axis.scale.isBlank()) {
  49244. return;
  49245. }
  49246. var splitLineModel = axisModel.getModel('splitLine');
  49247. var lineStyleModel = splitLineModel.getModel('lineStyle');
  49248. var lineWidth = lineStyleModel.get('width');
  49249. var lineColors = lineStyleModel.get('color');
  49250. var lineInterval = getInterval$2(splitLineModel, labelInterval);
  49251. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  49252. var gridRect = axisModel.coordinateSystem.getRect();
  49253. var isHorizontal = axis.isHorizontal();
  49254. var splitLines = [];
  49255. var lineCount = 0;
  49256. var ticksCoords = axis.getTicksCoords();
  49257. var p1 = [];
  49258. var p2 = [];
  49259. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  49260. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  49261. for (var i = 0; i < ticksCoords.length; ++i) {
  49262. if (ifIgnoreOnTick$2(
  49263. axis, i, lineInterval, ticksCoords.length,
  49264. showMinLabel, showMaxLabel
  49265. )) {
  49266. continue;
  49267. }
  49268. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  49269. if (isHorizontal) {
  49270. p1[0] = tickCoord;
  49271. p1[1] = gridRect.y;
  49272. p2[0] = tickCoord;
  49273. p2[1] = gridRect.y + gridRect.height;
  49274. }
  49275. else {
  49276. p1[0] = gridRect.x;
  49277. p1[1] = tickCoord;
  49278. p2[0] = gridRect.x + gridRect.width;
  49279. p2[1] = tickCoord;
  49280. }
  49281. var colorIndex = (lineCount++) % lineColors.length;
  49282. splitLines[colorIndex] = splitLines[colorIndex] || [];
  49283. splitLines[colorIndex].push(new Line(
  49284. subPixelOptimizeLine({
  49285. shape: {
  49286. x1: p1[0],
  49287. y1: p1[1],
  49288. x2: p2[0],
  49289. y2: p2[1]
  49290. },
  49291. style: {
  49292. lineWidth: lineWidth
  49293. },
  49294. silent: true
  49295. })));
  49296. }
  49297. for (var i = 0; i < splitLines.length; ++i) {
  49298. this.group.add(mergePath(splitLines[i], {
  49299. style: {
  49300. stroke: lineColors[i % lineColors.length],
  49301. lineDash: lineStyleModel.getLineDash(lineWidth),
  49302. lineWidth: lineWidth
  49303. },
  49304. silent: true
  49305. }));
  49306. }
  49307. }
  49308. });
  49309. var AxisModel$4 = ComponentModel.extend({
  49310. type: 'singleAxis',
  49311. layoutMode: 'box',
  49312. /**
  49313. * @type {module:echarts/coord/single/SingleAxis}
  49314. */
  49315. axis: null,
  49316. /**
  49317. * @type {module:echarts/coord/single/Single}
  49318. */
  49319. coordinateSystem: null,
  49320. /**
  49321. * @override
  49322. */
  49323. getCoordSysModel: function () {
  49324. return this;
  49325. }
  49326. });
  49327. var defaultOption$2 = {
  49328. left: '5%',
  49329. top: '5%',
  49330. right: '5%',
  49331. bottom: '5%',
  49332. type: 'value',
  49333. position: 'bottom',
  49334. orient: 'horizontal',
  49335. axisLine: {
  49336. show: true,
  49337. lineStyle: {
  49338. width: 2,
  49339. type: 'solid'
  49340. }
  49341. },
  49342. // Single coordinate system and single axis is the,
  49343. // which is used as the parent tooltip model.
  49344. // same model, so we set default tooltip show as true.
  49345. tooltip: {
  49346. show: true
  49347. },
  49348. axisTick: {
  49349. show: true,
  49350. length: 6,
  49351. lineStyle: {
  49352. width: 2
  49353. }
  49354. },
  49355. axisLabel: {
  49356. show: true,
  49357. interval: 'auto'
  49358. },
  49359. splitLine: {
  49360. show: true,
  49361. lineStyle: {
  49362. type: 'dashed',
  49363. opacity: 0.2
  49364. }
  49365. }
  49366. };
  49367. function getAxisType$2(axisName, option) {
  49368. return option.type || (option.data ? 'category' : 'value');
  49369. }
  49370. merge(AxisModel$4.prototype, axisModelCommonMixin);
  49371. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  49372. /**
  49373. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  49374. * @param {module:echarts/model/Global} ecModel
  49375. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  49376. */
  49377. var findPointFromSeries = function (finder, ecModel) {
  49378. var point = [];
  49379. var seriesIndex = finder.seriesIndex;
  49380. var seriesModel;
  49381. if (seriesIndex == null || !(
  49382. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  49383. )) {
  49384. return {point: []};
  49385. }
  49386. var data = seriesModel.getData();
  49387. var dataIndex = queryDataIndex(data, finder);
  49388. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  49389. return {point: []};
  49390. }
  49391. var el = data.getItemGraphicEl(dataIndex);
  49392. var coordSys = seriesModel.coordinateSystem;
  49393. if (seriesModel.getTooltipPosition) {
  49394. point = seriesModel.getTooltipPosition(dataIndex) || [];
  49395. }
  49396. else if (coordSys && coordSys.dataToPoint) {
  49397. point = coordSys.dataToPoint(
  49398. data.getValues(
  49399. map(coordSys.dimensions, function (dim) {
  49400. return data.mapDimension(dim);
  49401. }), dataIndex, true
  49402. )
  49403. ) || [];
  49404. }
  49405. else if (el) {
  49406. // Use graphic bounding rect
  49407. var rect = el.getBoundingRect().clone();
  49408. rect.applyTransform(el.transform);
  49409. point = [
  49410. rect.x + rect.width / 2,
  49411. rect.y + rect.height / 2
  49412. ];
  49413. }
  49414. return {point: point, el: el};
  49415. };
  49416. var each$15 = each$1;
  49417. var curry$3 = curry;
  49418. var inner$6 = makeInner();
  49419. /**
  49420. * Basic logic: check all axis, if they do not demand show/highlight,
  49421. * then hide/downplay them.
  49422. *
  49423. * @param {Object} coordSysAxesInfo
  49424. * @param {Object} payload
  49425. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  49426. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  49427. * trigger axisPointer and tooltip.
  49428. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  49429. * trigger axisPointer and tooltip.
  49430. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  49431. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  49432. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  49433. * [{
  49434. * axisDim: 'x'|'y'|'angle'|...,
  49435. * axisIndex: ...,
  49436. * value: ...
  49437. * }, ...]
  49438. * @param {Function} [payload.dispatchAction]
  49439. * @param {Object} [payload.tooltipOption]
  49440. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  49441. * which can be specified in dispatchAction
  49442. * @param {module:echarts/model/Global} ecModel
  49443. * @param {module:echarts/ExtensionAPI} api
  49444. * @return {Object} content of event obj for echarts.connect.
  49445. */
  49446. var axisTrigger = function (payload, ecModel, api) {
  49447. var currTrigger = payload.currTrigger;
  49448. var point = [payload.x, payload.y];
  49449. var finder = payload;
  49450. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  49451. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  49452. // Pending
  49453. // See #6121. But we are not able to reproduce it yet.
  49454. if (!coordSysAxesInfo) {
  49455. return;
  49456. }
  49457. if (illegalPoint(point)) {
  49458. // Used in the default behavior of `connection`: use the sample seriesIndex
  49459. // and dataIndex. And also used in the tooltipView trigger.
  49460. point = findPointFromSeries({
  49461. seriesIndex: finder.seriesIndex,
  49462. // Do not use dataIndexInside from other ec instance.
  49463. // FIXME: auto detect it?
  49464. dataIndex: finder.dataIndex
  49465. }, ecModel).point;
  49466. }
  49467. var isIllegalPoint = illegalPoint(point);
  49468. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  49469. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  49470. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  49471. // and dataIndex.
  49472. var inputAxesInfo = finder.axesInfo;
  49473. var axesInfo = coordSysAxesInfo.axesInfo;
  49474. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  49475. var outputFinder = {};
  49476. var showValueMap = {};
  49477. var dataByCoordSys = {list: [], map: {}};
  49478. var updaters = {
  49479. showPointer: curry$3(showPointer, showValueMap),
  49480. showTooltip: curry$3(showTooltip, dataByCoordSys)
  49481. };
  49482. // Process for triggered axes.
  49483. each$15(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  49484. // If a point given, it must be contained by the coordinate system.
  49485. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  49486. each$15(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  49487. var axis = axisInfo.axis;
  49488. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  49489. // If no inputAxesInfo, no axis is restricted.
  49490. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  49491. var val = inputAxisInfo && inputAxisInfo.value;
  49492. if (val == null && !isIllegalPoint) {
  49493. val = axis.pointToData(point);
  49494. }
  49495. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  49496. }
  49497. });
  49498. });
  49499. // Process for linked axes.
  49500. var linkTriggers = {};
  49501. each$15(axesInfo, function (tarAxisInfo, tarKey) {
  49502. var linkGroup = tarAxisInfo.linkGroup;
  49503. // If axis has been triggered in the previous stage, it should not be triggered by link.
  49504. if (linkGroup && !showValueMap[tarKey]) {
  49505. each$15(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  49506. var srcValItem = showValueMap[srcKey];
  49507. // If srcValItem exist, source axis is triggered, so link to target axis.
  49508. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  49509. var val = srcValItem.value;
  49510. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  49511. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  49512. )));
  49513. linkTriggers[tarAxisInfo.key] = val;
  49514. }
  49515. });
  49516. }
  49517. });
  49518. each$15(linkTriggers, function (val, tarKey) {
  49519. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  49520. });
  49521. updateModelActually(showValueMap, axesInfo, outputFinder);
  49522. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  49523. dispatchHighDownActually(axesInfo, dispatchAction, api);
  49524. return outputFinder;
  49525. };
  49526. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  49527. var axis = axisInfo.axis;
  49528. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  49529. return;
  49530. }
  49531. if (!axisInfo.involveSeries) {
  49532. updaters.showPointer(axisInfo, newValue);
  49533. return;
  49534. }
  49535. // Heavy calculation. So put it after axis.containData checking.
  49536. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  49537. var payloadBatch = payloadInfo.payloadBatch;
  49538. var snapToValue = payloadInfo.snapToValue;
  49539. // Fill content of event obj for echarts.connect.
  49540. // By defualt use the first involved series data as a sample to connect.
  49541. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  49542. extend(outputFinder, payloadBatch[0]);
  49543. }
  49544. // If no linkSource input, this process is for collecting link
  49545. // target, where snap should not be accepted.
  49546. if (!dontSnap && axisInfo.snap) {
  49547. if (axis.containData(snapToValue) && snapToValue != null) {
  49548. newValue = snapToValue;
  49549. }
  49550. }
  49551. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  49552. // Tooltip should always be snapToValue, otherwise there will be
  49553. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  49554. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  49555. }
  49556. function buildPayloadsBySeries(value, axisInfo) {
  49557. var axis = axisInfo.axis;
  49558. var dim = axis.dim;
  49559. var snapToValue = value;
  49560. var payloadBatch = [];
  49561. var minDist = Number.MAX_VALUE;
  49562. var minDiff = -1;
  49563. each$15(axisInfo.seriesModels, function (series, idx) {
  49564. var dataDim = series.getData().mapDimension(dim, true);
  49565. var seriesNestestValue;
  49566. var dataIndices;
  49567. if (series.getAxisTooltipData) {
  49568. var result = series.getAxisTooltipData(dataDim, value, axis);
  49569. dataIndices = result.dataIndices;
  49570. seriesNestestValue = result.nestestValue;
  49571. }
  49572. else {
  49573. dataIndices = series.getData().indicesOfNearest(
  49574. dataDim[0],
  49575. value,
  49576. // Add a threshold to avoid find the wrong dataIndex
  49577. // when data length is not same.
  49578. // false,
  49579. axis.type === 'category' ? 0.5 : null
  49580. );
  49581. if (!dataIndices.length) {
  49582. return;
  49583. }
  49584. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  49585. }
  49586. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  49587. return;
  49588. }
  49589. var diff = value - seriesNestestValue;
  49590. var dist = Math.abs(diff);
  49591. // Consider category case
  49592. if (dist <= minDist) {
  49593. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  49594. minDist = dist;
  49595. minDiff = diff;
  49596. snapToValue = seriesNestestValue;
  49597. payloadBatch.length = 0;
  49598. }
  49599. each$15(dataIndices, function (dataIndex) {
  49600. payloadBatch.push({
  49601. seriesIndex: series.seriesIndex,
  49602. dataIndexInside: dataIndex,
  49603. dataIndex: series.getData().getRawIndex(dataIndex)
  49604. });
  49605. });
  49606. }
  49607. });
  49608. return {
  49609. payloadBatch: payloadBatch,
  49610. snapToValue: snapToValue
  49611. };
  49612. }
  49613. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  49614. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  49615. }
  49616. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  49617. var payloadBatch = payloadInfo.payloadBatch;
  49618. var axis = axisInfo.axis;
  49619. var axisModel = axis.model;
  49620. var axisPointerModel = axisInfo.axisPointerModel;
  49621. // If no data, do not create anything in dataByCoordSys,
  49622. // whose length will be used to judge whether dispatch action.
  49623. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  49624. return;
  49625. }
  49626. var coordSysModel = axisInfo.coordSys.model;
  49627. var coordSysKey = makeKey(coordSysModel);
  49628. var coordSysItem = dataByCoordSys.map[coordSysKey];
  49629. if (!coordSysItem) {
  49630. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  49631. coordSysId: coordSysModel.id,
  49632. coordSysIndex: coordSysModel.componentIndex,
  49633. coordSysType: coordSysModel.type,
  49634. coordSysMainType: coordSysModel.mainType,
  49635. dataByAxis: []
  49636. };
  49637. dataByCoordSys.list.push(coordSysItem);
  49638. }
  49639. coordSysItem.dataByAxis.push({
  49640. axisDim: axis.dim,
  49641. axisIndex: axisModel.componentIndex,
  49642. axisType: axisModel.type,
  49643. axisId: axisModel.id,
  49644. value: value,
  49645. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  49646. // depends that all models have been updated. So it should not be performed
  49647. // here. Considering axisPointerModel used here is volatile, which is hard
  49648. // to be retrieve in TooltipView, we prepare parameters here.
  49649. valueLabelOpt: {
  49650. precision: axisPointerModel.get('label.precision'),
  49651. formatter: axisPointerModel.get('label.formatter')
  49652. },
  49653. seriesDataIndices: payloadBatch.slice()
  49654. });
  49655. }
  49656. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  49657. var outputAxesInfo = outputFinder.axesInfo = [];
  49658. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  49659. each$15(axesInfo, function (axisInfo, key) {
  49660. var option = axisInfo.axisPointerModel.option;
  49661. var valItem = showValueMap[key];
  49662. if (valItem) {
  49663. !axisInfo.useHandle && (option.status = 'show');
  49664. option.value = valItem.value;
  49665. // For label formatter param and highlight.
  49666. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  49667. }
  49668. // When always show (e.g., handle used), remain
  49669. // original value and status.
  49670. else {
  49671. // If hide, value still need to be set, consider
  49672. // click legend to toggle axis blank.
  49673. !axisInfo.useHandle && (option.status = 'hide');
  49674. }
  49675. // If status is 'hide', should be no info in payload.
  49676. option.status === 'show' && outputAxesInfo.push({
  49677. axisDim: axisInfo.axis.dim,
  49678. axisIndex: axisInfo.axis.model.componentIndex,
  49679. value: option.value
  49680. });
  49681. });
  49682. }
  49683. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  49684. // Basic logic: If no showTip required, hideTip will be dispatched.
  49685. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  49686. dispatchAction({type: 'hideTip'});
  49687. return;
  49688. }
  49689. // In most case only one axis (or event one series is used). It is
  49690. // convinient to fetch payload.seriesIndex and payload.dataIndex
  49691. // dirtectly. So put the first seriesIndex and dataIndex of the first
  49692. // axis on the payload.
  49693. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  49694. dispatchAction({
  49695. type: 'showTip',
  49696. escapeConnect: true,
  49697. x: point[0],
  49698. y: point[1],
  49699. tooltipOption: payload.tooltipOption,
  49700. position: payload.position,
  49701. dataIndexInside: sampleItem.dataIndexInside,
  49702. dataIndex: sampleItem.dataIndex,
  49703. seriesIndex: sampleItem.seriesIndex,
  49704. dataByCoordSys: dataByCoordSys.list
  49705. });
  49706. }
  49707. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  49708. // FIXME
  49709. // highlight status modification shoule be a stage of main process?
  49710. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  49711. var zr = api.getZr();
  49712. var highDownKey = 'axisPointerLastHighlights';
  49713. var lastHighlights = inner$6(zr)[highDownKey] || {};
  49714. var newHighlights = inner$6(zr)[highDownKey] = {};
  49715. // Update highlight/downplay status according to axisPointer model.
  49716. // Build hash map and remove duplicate incidentally.
  49717. each$15(axesInfo, function (axisInfo, key) {
  49718. var option = axisInfo.axisPointerModel.option;
  49719. option.status === 'show' && each$15(option.seriesDataIndices, function (batchItem) {
  49720. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  49721. newHighlights[key] = batchItem;
  49722. });
  49723. });
  49724. // Diff.
  49725. var toHighlight = [];
  49726. var toDownplay = [];
  49727. each$1(lastHighlights, function (batchItem, key) {
  49728. !newHighlights[key] && toDownplay.push(batchItem);
  49729. });
  49730. each$1(newHighlights, function (batchItem, key) {
  49731. !lastHighlights[key] && toHighlight.push(batchItem);
  49732. });
  49733. toDownplay.length && api.dispatchAction({
  49734. type: 'downplay', escapeConnect: true, batch: toDownplay
  49735. });
  49736. toHighlight.length && api.dispatchAction({
  49737. type: 'highlight', escapeConnect: true, batch: toHighlight
  49738. });
  49739. }
  49740. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  49741. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  49742. var inputAxisInfo = inputAxesInfo[i];
  49743. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  49744. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  49745. ) {
  49746. return inputAxisInfo;
  49747. }
  49748. }
  49749. }
  49750. function makeMapperParam(axisInfo) {
  49751. var axisModel = axisInfo.axis.model;
  49752. var item = {};
  49753. var dim = item.axisDim = axisInfo.axis.dim;
  49754. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  49755. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  49756. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  49757. return item;
  49758. }
  49759. function illegalPoint(point) {
  49760. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  49761. }
  49762. var AxisPointerModel = extendComponentModel({
  49763. type: 'axisPointer',
  49764. coordSysAxesInfo: null,
  49765. defaultOption: {
  49766. // 'auto' means that show when triggered by tooltip or handle.
  49767. show: 'auto',
  49768. // 'click' | 'mousemove' | 'none'
  49769. triggerOn: null, // set default in AxisPonterView.js
  49770. zlevel: 0,
  49771. z: 50,
  49772. type: 'line',
  49773. // axispointer triggered by tootip determine snap automatically,
  49774. // see `modelHelper`.
  49775. snap: false,
  49776. triggerTooltip: true,
  49777. value: null,
  49778. status: null, // Init value depends on whether handle is used.
  49779. // [group0, group1, ...]
  49780. // Each group can be: {
  49781. // mapper: function () {},
  49782. // singleTooltip: 'multiple', // 'multiple' or 'single'
  49783. // xAxisId: ...,
  49784. // yAxisName: ...,
  49785. // angleAxisIndex: ...
  49786. // }
  49787. // mapper: can be ignored.
  49788. // input: {axisInfo, value}
  49789. // output: {axisInfo, value}
  49790. link: [],
  49791. // Do not set 'auto' here, otherwise global animation: false
  49792. // will not effect at this axispointer.
  49793. animation: null,
  49794. animationDurationUpdate: 200,
  49795. lineStyle: {
  49796. color: '#aaa',
  49797. width: 1,
  49798. type: 'solid'
  49799. },
  49800. shadowStyle: {
  49801. color: 'rgba(150,150,150,0.3)'
  49802. },
  49803. label: {
  49804. show: true,
  49805. formatter: null, // string | Function
  49806. precision: 'auto', // Or a number like 0, 1, 2 ...
  49807. margin: 3,
  49808. color: '#fff',
  49809. padding: [5, 7, 5, 7],
  49810. backgroundColor: 'auto', // default: axis line color
  49811. borderColor: null,
  49812. borderWidth: 0,
  49813. shadowBlur: 3,
  49814. shadowColor: '#aaa'
  49815. // Considering applicability, common style should
  49816. // better not have shadowOffset.
  49817. // shadowOffsetX: 0,
  49818. // shadowOffsetY: 2
  49819. },
  49820. handle: {
  49821. show: false,
  49822. 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
  49823. size: 45,
  49824. // handle margin is from symbol center to axis, which is stable when circular move.
  49825. margin: 50,
  49826. // color: '#1b8bbd'
  49827. // color: '#2f4554'
  49828. color: '#333',
  49829. shadowBlur: 3,
  49830. shadowColor: '#aaa',
  49831. shadowOffsetX: 0,
  49832. shadowOffsetY: 2,
  49833. // For mobile performance
  49834. throttle: 40
  49835. }
  49836. }
  49837. });
  49838. var inner$7 = makeInner();
  49839. var each$16 = each$1;
  49840. /**
  49841. * @param {string} key
  49842. * @param {module:echarts/ExtensionAPI} api
  49843. * @param {Function} handler
  49844. * param: {string} currTrigger
  49845. * param: {Array.<number>} point
  49846. */
  49847. function register(key, api, handler) {
  49848. if (env$1.node) {
  49849. return;
  49850. }
  49851. var zr = api.getZr();
  49852. inner$7(zr).records || (inner$7(zr).records = {});
  49853. initGlobalListeners(zr, api);
  49854. var record = inner$7(zr).records[key] || (inner$7(zr).records[key] = {});
  49855. record.handler = handler;
  49856. }
  49857. function initGlobalListeners(zr, api) {
  49858. if (inner$7(zr).initialized) {
  49859. return;
  49860. }
  49861. inner$7(zr).initialized = true;
  49862. useHandler('click', curry(doEnter, 'click'));
  49863. useHandler('mousemove', curry(doEnter, 'mousemove'));
  49864. // useHandler('mouseout', onLeave);
  49865. useHandler('globalout', onLeave);
  49866. function useHandler(eventType, cb) {
  49867. zr.on(eventType, function (e) {
  49868. var dis = makeDispatchAction(api);
  49869. each$16(inner$7(zr).records, function (record) {
  49870. record && cb(record, e, dis.dispatchAction);
  49871. });
  49872. dispatchTooltipFinally(dis.pendings, api);
  49873. });
  49874. }
  49875. }
  49876. function dispatchTooltipFinally(pendings, api) {
  49877. var showLen = pendings.showTip.length;
  49878. var hideLen = pendings.hideTip.length;
  49879. var actuallyPayload;
  49880. if (showLen) {
  49881. actuallyPayload = pendings.showTip[showLen - 1];
  49882. }
  49883. else if (hideLen) {
  49884. actuallyPayload = pendings.hideTip[hideLen - 1];
  49885. }
  49886. if (actuallyPayload) {
  49887. actuallyPayload.dispatchAction = null;
  49888. api.dispatchAction(actuallyPayload);
  49889. }
  49890. }
  49891. function onLeave(record, e, dispatchAction) {
  49892. record.handler('leave', null, dispatchAction);
  49893. }
  49894. function doEnter(currTrigger, record, e, dispatchAction) {
  49895. record.handler(currTrigger, e, dispatchAction);
  49896. }
  49897. function makeDispatchAction(api) {
  49898. var pendings = {
  49899. showTip: [],
  49900. hideTip: []
  49901. };
  49902. // FIXME
  49903. // better approach?
  49904. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  49905. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  49906. // So we have to add "final stage" to merge those dispatched actions.
  49907. var dispatchAction = function (payload) {
  49908. var pendingList = pendings[payload.type];
  49909. if (pendingList) {
  49910. pendingList.push(payload);
  49911. }
  49912. else {
  49913. payload.dispatchAction = dispatchAction;
  49914. api.dispatchAction(payload);
  49915. }
  49916. };
  49917. return {
  49918. dispatchAction: dispatchAction,
  49919. pendings: pendings
  49920. };
  49921. }
  49922. /**
  49923. * @param {string} key
  49924. * @param {module:echarts/ExtensionAPI} api
  49925. */
  49926. function unregister(key, api) {
  49927. if (env$1.node) {
  49928. return;
  49929. }
  49930. var zr = api.getZr();
  49931. var record = (inner$7(zr).records || {})[key];
  49932. if (record) {
  49933. inner$7(zr).records[key] = null;
  49934. }
  49935. }
  49936. var AxisPointerView = extendComponentView({
  49937. type: 'axisPointer',
  49938. render: function (globalAxisPointerModel, ecModel, api) {
  49939. var globalTooltipModel = ecModel.getComponent('tooltip');
  49940. var triggerOn = globalAxisPointerModel.get('triggerOn')
  49941. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  49942. // Register global listener in AxisPointerView to enable
  49943. // AxisPointerView to be independent to Tooltip.
  49944. register(
  49945. 'axisPointer',
  49946. api,
  49947. function (currTrigger, e, dispatchAction) {
  49948. // If 'none', it is not controlled by mouse totally.
  49949. if (triggerOn !== 'none'
  49950. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  49951. ) {
  49952. dispatchAction({
  49953. type: 'updateAxisPointer',
  49954. currTrigger: currTrigger,
  49955. x: e && e.offsetX,
  49956. y: e && e.offsetY
  49957. });
  49958. }
  49959. }
  49960. );
  49961. },
  49962. /**
  49963. * @override
  49964. */
  49965. remove: function (ecModel, api) {
  49966. unregister(api.getZr(), 'axisPointer');
  49967. AxisPointerView.superApply(this._model, 'remove', arguments);
  49968. },
  49969. /**
  49970. * @override
  49971. */
  49972. dispose: function (ecModel, api) {
  49973. unregister('axisPointer', api);
  49974. AxisPointerView.superApply(this._model, 'dispose', arguments);
  49975. }
  49976. });
  49977. var inner$8 = makeInner();
  49978. var clone$4 = clone;
  49979. var bind$2 = bind;
  49980. /**
  49981. * Base axis pointer class in 2D.
  49982. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  49983. */
  49984. function BaseAxisPointer () {
  49985. }
  49986. BaseAxisPointer.prototype = {
  49987. /**
  49988. * @private
  49989. */
  49990. _group: null,
  49991. /**
  49992. * @private
  49993. */
  49994. _lastGraphicKey: null,
  49995. /**
  49996. * @private
  49997. */
  49998. _handle: null,
  49999. /**
  50000. * @private
  50001. */
  50002. _dragging: false,
  50003. /**
  50004. * @private
  50005. */
  50006. _lastValue: null,
  50007. /**
  50008. * @private
  50009. */
  50010. _lastStatus: null,
  50011. /**
  50012. * @private
  50013. */
  50014. _payloadInfo: null,
  50015. /**
  50016. * In px, arbitrary value. Do not set too small,
  50017. * no animation is ok for most cases.
  50018. * @protected
  50019. */
  50020. animationThreshold: 15,
  50021. /**
  50022. * @implement
  50023. */
  50024. render: function (axisModel, axisPointerModel, api, forceRender) {
  50025. var value = axisPointerModel.get('value');
  50026. var status = axisPointerModel.get('status');
  50027. // Bind them to `this`, not in closure, otherwise they will not
  50028. // be replaced when user calling setOption in not merge mode.
  50029. this._axisModel = axisModel;
  50030. this._axisPointerModel = axisPointerModel;
  50031. this._api = api;
  50032. // Optimize: `render` will be called repeatly during mouse move.
  50033. // So it is power consuming if performing `render` each time,
  50034. // especially on mobile device.
  50035. if (!forceRender
  50036. && this._lastValue === value
  50037. && this._lastStatus === status
  50038. ) {
  50039. return;
  50040. }
  50041. this._lastValue = value;
  50042. this._lastStatus = status;
  50043. var group = this._group;
  50044. var handle = this._handle;
  50045. if (!status || status === 'hide') {
  50046. // Do not clear here, for animation better.
  50047. group && group.hide();
  50048. handle && handle.hide();
  50049. return;
  50050. }
  50051. group && group.show();
  50052. handle && handle.show();
  50053. // Otherwise status is 'show'
  50054. var elOption = {};
  50055. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  50056. // Enable change axis pointer type.
  50057. var graphicKey = elOption.graphicKey;
  50058. if (graphicKey !== this._lastGraphicKey) {
  50059. this.clear(api);
  50060. }
  50061. this._lastGraphicKey = graphicKey;
  50062. var moveAnimation = this._moveAnimation =
  50063. this.determineAnimation(axisModel, axisPointerModel);
  50064. if (!group) {
  50065. group = this._group = new Group();
  50066. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  50067. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  50068. api.getZr().add(group);
  50069. }
  50070. else {
  50071. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  50072. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  50073. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  50074. }
  50075. updateMandatoryProps(group, axisPointerModel, true);
  50076. this._renderHandle(value);
  50077. },
  50078. /**
  50079. * @implement
  50080. */
  50081. remove: function (api) {
  50082. this.clear(api);
  50083. },
  50084. /**
  50085. * @implement
  50086. */
  50087. dispose: function (api) {
  50088. this.clear(api);
  50089. },
  50090. /**
  50091. * @protected
  50092. */
  50093. determineAnimation: function (axisModel, axisPointerModel) {
  50094. var animation = axisPointerModel.get('animation');
  50095. var axis = axisModel.axis;
  50096. var isCategoryAxis = axis.type === 'category';
  50097. var useSnap = axisPointerModel.get('snap');
  50098. // Value axis without snap always do not snap.
  50099. if (!useSnap && !isCategoryAxis) {
  50100. return false;
  50101. }
  50102. if (animation === 'auto' || animation == null) {
  50103. var animationThreshold = this.animationThreshold;
  50104. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  50105. return true;
  50106. }
  50107. // It is important to auto animation when snap used. Consider if there is
  50108. // a dataZoom, animation will be disabled when too many points exist, while
  50109. // it will be enabled for better visual effect when little points exist.
  50110. if (useSnap) {
  50111. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  50112. var axisExtent = axis.getExtent();
  50113. // Approximate band width
  50114. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  50115. }
  50116. return false;
  50117. }
  50118. return animation === true;
  50119. },
  50120. /**
  50121. * add {pointer, label, graphicKey} to elOption
  50122. * @protected
  50123. */
  50124. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  50125. // Shoule be implemenented by sub-class.
  50126. },
  50127. /**
  50128. * @protected
  50129. */
  50130. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  50131. var pointerOption = elOption.pointer;
  50132. if (pointerOption) {
  50133. var pointerEl = inner$8(group).pointerEl = new graphic[pointerOption.type](
  50134. clone$4(elOption.pointer)
  50135. );
  50136. group.add(pointerEl);
  50137. }
  50138. },
  50139. /**
  50140. * @protected
  50141. */
  50142. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  50143. if (elOption.label) {
  50144. var labelEl = inner$8(group).labelEl = new Rect(
  50145. clone$4(elOption.label)
  50146. );
  50147. group.add(labelEl);
  50148. updateLabelShowHide(labelEl, axisPointerModel);
  50149. }
  50150. },
  50151. /**
  50152. * @protected
  50153. */
  50154. updatePointerEl: function (group, elOption, updateProps$$1) {
  50155. var pointerEl = inner$8(group).pointerEl;
  50156. if (pointerEl) {
  50157. pointerEl.setStyle(elOption.pointer.style);
  50158. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  50159. }
  50160. },
  50161. /**
  50162. * @protected
  50163. */
  50164. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  50165. var labelEl = inner$8(group).labelEl;
  50166. if (labelEl) {
  50167. labelEl.setStyle(elOption.label.style);
  50168. updateProps$$1(labelEl, {
  50169. // Consider text length change in vertical axis, animation should
  50170. // be used on shape, otherwise the effect will be weird.
  50171. shape: elOption.label.shape,
  50172. position: elOption.label.position
  50173. });
  50174. updateLabelShowHide(labelEl, axisPointerModel);
  50175. }
  50176. },
  50177. /**
  50178. * @private
  50179. */
  50180. _renderHandle: function (value) {
  50181. if (this._dragging || !this.updateHandleTransform) {
  50182. return;
  50183. }
  50184. var axisPointerModel = this._axisPointerModel;
  50185. var zr = this._api.getZr();
  50186. var handle = this._handle;
  50187. var handleModel = axisPointerModel.getModel('handle');
  50188. var status = axisPointerModel.get('status');
  50189. if (!handleModel.get('show') || !status || status === 'hide') {
  50190. handle && zr.remove(handle);
  50191. this._handle = null;
  50192. return;
  50193. }
  50194. var isInit;
  50195. if (!this._handle) {
  50196. isInit = true;
  50197. handle = this._handle = createIcon(
  50198. handleModel.get('icon'),
  50199. {
  50200. cursor: 'move',
  50201. draggable: true,
  50202. onmousemove: function (e) {
  50203. // Fot mobile devicem, prevent screen slider on the button.
  50204. stop(e.event);
  50205. },
  50206. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  50207. drift: bind$2(this._onHandleDragMove, this),
  50208. ondragend: bind$2(this._onHandleDragEnd, this)
  50209. }
  50210. );
  50211. zr.add(handle);
  50212. }
  50213. updateMandatoryProps(handle, axisPointerModel, false);
  50214. // update style
  50215. var includeStyles = [
  50216. 'color', 'borderColor', 'borderWidth', 'opacity',
  50217. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  50218. ];
  50219. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  50220. // update position
  50221. var handleSize = handleModel.get('size');
  50222. if (!isArray(handleSize)) {
  50223. handleSize = [handleSize, handleSize];
  50224. }
  50225. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  50226. createOrUpdate(
  50227. this,
  50228. '_doDispatchAxisPointer',
  50229. handleModel.get('throttle') || 0,
  50230. 'fixRate'
  50231. );
  50232. this._moveHandleToValue(value, isInit);
  50233. },
  50234. /**
  50235. * @private
  50236. */
  50237. _moveHandleToValue: function (value, isInit) {
  50238. updateProps$1(
  50239. this._axisPointerModel,
  50240. !isInit && this._moveAnimation,
  50241. this._handle,
  50242. getHandleTransProps(this.getHandleTransform(
  50243. value, this._axisModel, this._axisPointerModel
  50244. ))
  50245. );
  50246. },
  50247. /**
  50248. * @private
  50249. */
  50250. _onHandleDragMove: function (dx, dy) {
  50251. var handle = this._handle;
  50252. if (!handle) {
  50253. return;
  50254. }
  50255. this._dragging = true;
  50256. // Persistent for throttle.
  50257. var trans = this.updateHandleTransform(
  50258. getHandleTransProps(handle),
  50259. [dx, dy],
  50260. this._axisModel,
  50261. this._axisPointerModel
  50262. );
  50263. this._payloadInfo = trans;
  50264. handle.stopAnimation();
  50265. handle.attr(getHandleTransProps(trans));
  50266. inner$8(handle).lastProp = null;
  50267. this._doDispatchAxisPointer();
  50268. },
  50269. /**
  50270. * Throttled method.
  50271. * @private
  50272. */
  50273. _doDispatchAxisPointer: function () {
  50274. var handle = this._handle;
  50275. if (!handle) {
  50276. return;
  50277. }
  50278. var payloadInfo = this._payloadInfo;
  50279. var axisModel = this._axisModel;
  50280. this._api.dispatchAction({
  50281. type: 'updateAxisPointer',
  50282. x: payloadInfo.cursorPoint[0],
  50283. y: payloadInfo.cursorPoint[1],
  50284. tooltipOption: payloadInfo.tooltipOption,
  50285. axesInfo: [{
  50286. axisDim: axisModel.axis.dim,
  50287. axisIndex: axisModel.componentIndex
  50288. }]
  50289. });
  50290. },
  50291. /**
  50292. * @private
  50293. */
  50294. _onHandleDragEnd: function (moveAnimation) {
  50295. this._dragging = false;
  50296. var handle = this._handle;
  50297. if (!handle) {
  50298. return;
  50299. }
  50300. var value = this._axisPointerModel.get('value');
  50301. // Consider snap or categroy axis, handle may be not consistent with
  50302. // axisPointer. So move handle to align the exact value position when
  50303. // drag ended.
  50304. this._moveHandleToValue(value);
  50305. // For the effect: tooltip will be shown when finger holding on handle
  50306. // button, and will be hidden after finger left handle button.
  50307. this._api.dispatchAction({
  50308. type: 'hideTip'
  50309. });
  50310. },
  50311. /**
  50312. * Should be implemenented by sub-class if support `handle`.
  50313. * @protected
  50314. * @param {number} value
  50315. * @param {module:echarts/model/Model} axisModel
  50316. * @param {module:echarts/model/Model} axisPointerModel
  50317. * @return {Object} {position: [x, y], rotation: 0}
  50318. */
  50319. getHandleTransform: null,
  50320. /**
  50321. * * Should be implemenented by sub-class if support `handle`.
  50322. * @protected
  50323. * @param {Object} transform {position, rotation}
  50324. * @param {Array.<number>} delta [dx, dy]
  50325. * @param {module:echarts/model/Model} axisModel
  50326. * @param {module:echarts/model/Model} axisPointerModel
  50327. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  50328. */
  50329. updateHandleTransform: null,
  50330. /**
  50331. * @private
  50332. */
  50333. clear: function (api) {
  50334. this._lastValue = null;
  50335. this._lastStatus = null;
  50336. var zr = api.getZr();
  50337. var group = this._group;
  50338. var handle = this._handle;
  50339. if (zr && group) {
  50340. this._lastGraphicKey = null;
  50341. group && zr.remove(group);
  50342. handle && zr.remove(handle);
  50343. this._group = null;
  50344. this._handle = null;
  50345. this._payloadInfo = null;
  50346. }
  50347. },
  50348. /**
  50349. * @protected
  50350. */
  50351. doClear: function () {
  50352. // Implemented by sub-class if necessary.
  50353. },
  50354. /**
  50355. * @protected
  50356. * @param {Array.<number>} xy
  50357. * @param {Array.<number>} wh
  50358. * @param {number} [xDimIndex=0] or 1
  50359. */
  50360. buildLabel: function (xy, wh, xDimIndex) {
  50361. xDimIndex = xDimIndex || 0;
  50362. return {
  50363. x: xy[xDimIndex],
  50364. y: xy[1 - xDimIndex],
  50365. width: wh[xDimIndex],
  50366. height: wh[1 - xDimIndex]
  50367. };
  50368. }
  50369. };
  50370. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  50371. function updateProps$1(animationModel, moveAnimation, el, props) {
  50372. // Animation optimize.
  50373. if (!propsEqual(inner$8(el).lastProp, props)) {
  50374. inner$8(el).lastProp = props;
  50375. moveAnimation
  50376. ? updateProps(el, props, animationModel)
  50377. : (el.stopAnimation(), el.attr(props));
  50378. }
  50379. }
  50380. function propsEqual(lastProps, newProps) {
  50381. if (isObject$1(lastProps) && isObject$1(newProps)) {
  50382. var equals = true;
  50383. each$1(newProps, function (item, key) {
  50384. equals = equals && propsEqual(lastProps[key], item);
  50385. });
  50386. return !!equals;
  50387. }
  50388. else {
  50389. return lastProps === newProps;
  50390. }
  50391. }
  50392. function updateLabelShowHide(labelEl, axisPointerModel) {
  50393. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  50394. }
  50395. function getHandleTransProps(trans) {
  50396. return {
  50397. position: trans.position.slice(),
  50398. rotation: trans.rotation || 0
  50399. };
  50400. }
  50401. function updateMandatoryProps(group, axisPointerModel, silent) {
  50402. var z = axisPointerModel.get('z');
  50403. var zlevel = axisPointerModel.get('zlevel');
  50404. group && group.traverse(function (el) {
  50405. if (el.type !== 'group') {
  50406. z != null && (el.z = z);
  50407. zlevel != null && (el.zlevel = zlevel);
  50408. el.silent = silent;
  50409. }
  50410. });
  50411. }
  50412. enableClassExtend(BaseAxisPointer);
  50413. /**
  50414. * @param {module:echarts/model/Model} axisPointerModel
  50415. */
  50416. function buildElStyle(axisPointerModel) {
  50417. var axisPointerType = axisPointerModel.get('type');
  50418. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  50419. var style;
  50420. if (axisPointerType === 'line') {
  50421. style = styleModel.getLineStyle();
  50422. style.fill = null;
  50423. }
  50424. else if (axisPointerType === 'shadow') {
  50425. style = styleModel.getAreaStyle();
  50426. style.stroke = null;
  50427. }
  50428. return style;
  50429. }
  50430. /**
  50431. * @param {Function} labelPos {align, verticalAlign, position}
  50432. */
  50433. function buildLabelElOption(
  50434. elOption, axisModel, axisPointerModel, api, labelPos
  50435. ) {
  50436. var value = axisPointerModel.get('value');
  50437. var text = getValueLabel(
  50438. value, axisModel.axis, axisModel.ecModel,
  50439. axisPointerModel.get('seriesDataIndices'),
  50440. {
  50441. precision: axisPointerModel.get('label.precision'),
  50442. formatter: axisPointerModel.get('label.formatter')
  50443. }
  50444. );
  50445. var labelModel = axisPointerModel.getModel('label');
  50446. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  50447. var font = labelModel.getFont();
  50448. var textRect = getBoundingRect(text, font);
  50449. var position = labelPos.position;
  50450. var width = textRect.width + paddings[1] + paddings[3];
  50451. var height = textRect.height + paddings[0] + paddings[2];
  50452. // Adjust by align.
  50453. var align = labelPos.align;
  50454. align === 'right' && (position[0] -= width);
  50455. align === 'center' && (position[0] -= width / 2);
  50456. var verticalAlign = labelPos.verticalAlign;
  50457. verticalAlign === 'bottom' && (position[1] -= height);
  50458. verticalAlign === 'middle' && (position[1] -= height / 2);
  50459. // Not overflow ec container
  50460. confineInContainer(position, width, height, api);
  50461. var bgColor = labelModel.get('backgroundColor');
  50462. if (!bgColor || bgColor === 'auto') {
  50463. bgColor = axisModel.get('axisLine.lineStyle.color');
  50464. }
  50465. elOption.label = {
  50466. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  50467. position: position.slice(),
  50468. // TODO: rich
  50469. style: {
  50470. text: text,
  50471. textFont: font,
  50472. textFill: labelModel.getTextColor(),
  50473. textPosition: 'inside',
  50474. fill: bgColor,
  50475. stroke: labelModel.get('borderColor') || 'transparent',
  50476. lineWidth: labelModel.get('borderWidth') || 0,
  50477. shadowBlur: labelModel.get('shadowBlur'),
  50478. shadowColor: labelModel.get('shadowColor'),
  50479. shadowOffsetX: labelModel.get('shadowOffsetX'),
  50480. shadowOffsetY: labelModel.get('shadowOffsetY')
  50481. },
  50482. // Lable should be over axisPointer.
  50483. z2: 10
  50484. };
  50485. }
  50486. // Do not overflow ec container
  50487. function confineInContainer(position, width, height, api) {
  50488. var viewWidth = api.getWidth();
  50489. var viewHeight = api.getHeight();
  50490. position[0] = Math.min(position[0] + width, viewWidth) - width;
  50491. position[1] = Math.min(position[1] + height, viewHeight) - height;
  50492. position[0] = Math.max(position[0], 0);
  50493. position[1] = Math.max(position[1], 0);
  50494. }
  50495. /**
  50496. * @param {number} value
  50497. * @param {module:echarts/coord/Axis} axis
  50498. * @param {module:echarts/model/Global} ecModel
  50499. * @param {Object} opt
  50500. * @param {Array.<Object>} seriesDataIndices
  50501. * @param {number|string} opt.precision 'auto' or a number
  50502. * @param {string|Function} opt.formatter label formatter
  50503. */
  50504. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  50505. var text = axis.scale.getLabel(
  50506. // If `precision` is set, width can be fixed (like '12.00500'), which
  50507. // helps to debounce when when moving label.
  50508. value, {precision: opt.precision}
  50509. );
  50510. var formatter = opt.formatter;
  50511. if (formatter) {
  50512. var params = {
  50513. value: getAxisRawValue(axis, value),
  50514. seriesData: []
  50515. };
  50516. each$1(seriesDataIndices, function (idxItem) {
  50517. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  50518. var dataIndex = idxItem.dataIndexInside;
  50519. var dataParams = series && series.getDataParams(dataIndex);
  50520. dataParams && params.seriesData.push(dataParams);
  50521. });
  50522. if (isString(formatter)) {
  50523. text = formatter.replace('{value}', text);
  50524. }
  50525. else if (isFunction$1(formatter)) {
  50526. text = formatter(params);
  50527. }
  50528. }
  50529. return text;
  50530. }
  50531. /**
  50532. * @param {module:echarts/coord/Axis} axis
  50533. * @param {number} value
  50534. * @param {Object} layoutInfo {
  50535. * rotation, position, labelOffset, labelDirection, labelMargin
  50536. * }
  50537. */
  50538. function getTransformedPosition (axis, value, layoutInfo) {
  50539. var transform = create$1();
  50540. rotate(transform, transform, layoutInfo.rotation);
  50541. translate(transform, transform, layoutInfo.position);
  50542. return applyTransform$1([
  50543. axis.dataToCoord(value),
  50544. (layoutInfo.labelOffset || 0)
  50545. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  50546. ], transform);
  50547. }
  50548. function buildCartesianSingleLabelElOption(
  50549. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  50550. ) {
  50551. var textLayout = AxisBuilder.innerTextLayout(
  50552. layoutInfo.rotation, 0, layoutInfo.labelDirection
  50553. );
  50554. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  50555. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  50556. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  50557. align: textLayout.textAlign,
  50558. verticalAlign: textLayout.textVerticalAlign
  50559. });
  50560. }
  50561. /**
  50562. * @param {Array.<number>} p1
  50563. * @param {Array.<number>} p2
  50564. * @param {number} [xDimIndex=0] or 1
  50565. */
  50566. function makeLineShape(p1, p2, xDimIndex) {
  50567. xDimIndex = xDimIndex || 0;
  50568. return {
  50569. x1: p1[xDimIndex],
  50570. y1: p1[1 - xDimIndex],
  50571. x2: p2[xDimIndex],
  50572. y2: p2[1 - xDimIndex]
  50573. };
  50574. }
  50575. /**
  50576. * @param {Array.<number>} xy
  50577. * @param {Array.<number>} wh
  50578. * @param {number} [xDimIndex=0] or 1
  50579. */
  50580. function makeRectShape(xy, wh, xDimIndex) {
  50581. xDimIndex = xDimIndex || 0;
  50582. return {
  50583. x: xy[xDimIndex],
  50584. y: xy[1 - xDimIndex],
  50585. width: wh[xDimIndex],
  50586. height: wh[1 - xDimIndex]
  50587. };
  50588. }
  50589. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  50590. return {
  50591. cx: cx,
  50592. cy: cy,
  50593. r0: r0,
  50594. r: r,
  50595. startAngle: startAngle,
  50596. endAngle: endAngle,
  50597. clockwise: true
  50598. };
  50599. }
  50600. var CartesianAxisPointer = BaseAxisPointer.extend({
  50601. /**
  50602. * @override
  50603. */
  50604. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  50605. var axis = axisModel.axis;
  50606. var grid = axis.grid;
  50607. var axisPointerType = axisPointerModel.get('type');
  50608. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  50609. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  50610. if (axisPointerType && axisPointerType !== 'none') {
  50611. var elStyle = buildElStyle(axisPointerModel);
  50612. var pointerOption = pointerShapeBuilder[axisPointerType](
  50613. axis, pixelValue, otherExtent, elStyle
  50614. );
  50615. pointerOption.style = elStyle;
  50616. elOption.graphicKey = pointerOption.type;
  50617. elOption.pointer = pointerOption;
  50618. }
  50619. var layoutInfo = layout$1(grid.model, axisModel);
  50620. buildCartesianSingleLabelElOption(
  50621. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  50622. );
  50623. },
  50624. /**
  50625. * @override
  50626. */
  50627. getHandleTransform: function (value, axisModel, axisPointerModel) {
  50628. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  50629. labelInside: false
  50630. });
  50631. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  50632. return {
  50633. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  50634. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  50635. };
  50636. },
  50637. /**
  50638. * @override
  50639. */
  50640. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  50641. var axis = axisModel.axis;
  50642. var grid = axis.grid;
  50643. var axisExtent = axis.getGlobalExtent(true);
  50644. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  50645. var dimIndex = axis.dim === 'x' ? 0 : 1;
  50646. var currPosition = transform.position;
  50647. currPosition[dimIndex] += delta[dimIndex];
  50648. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  50649. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  50650. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  50651. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  50652. cursorPoint[dimIndex] = currPosition[dimIndex];
  50653. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  50654. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  50655. return {
  50656. position: currPosition,
  50657. rotation: transform.rotation,
  50658. cursorPoint: cursorPoint,
  50659. tooltipOption: tooltipOptions[dimIndex]
  50660. };
  50661. }
  50662. });
  50663. function getCartesian(grid, axis) {
  50664. var opt = {};
  50665. opt[axis.dim + 'AxisIndex'] = axis.index;
  50666. return grid.getCartesian(opt);
  50667. }
  50668. var pointerShapeBuilder = {
  50669. line: function (axis, pixelValue, otherExtent, elStyle) {
  50670. var targetShape = makeLineShape(
  50671. [pixelValue, otherExtent[0]],
  50672. [pixelValue, otherExtent[1]],
  50673. getAxisDimIndex(axis)
  50674. );
  50675. subPixelOptimizeLine({
  50676. shape: targetShape,
  50677. style: elStyle
  50678. });
  50679. return {
  50680. type: 'Line',
  50681. shape: targetShape
  50682. };
  50683. },
  50684. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  50685. var bandWidth = axis.getBandWidth();
  50686. var span = otherExtent[1] - otherExtent[0];
  50687. return {
  50688. type: 'Rect',
  50689. shape: makeRectShape(
  50690. [pixelValue - bandWidth / 2, otherExtent[0]],
  50691. [bandWidth, span],
  50692. getAxisDimIndex(axis)
  50693. )
  50694. };
  50695. }
  50696. };
  50697. function getAxisDimIndex(axis) {
  50698. return axis.dim === 'x' ? 0 : 1;
  50699. }
  50700. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  50701. // CartesianAxisPointer is not supposed to be required here. But consider
  50702. // echarts.simple.js and online build tooltip, which only require gridSimple,
  50703. // CartesianAxisPointer should be able to required somewhere.
  50704. registerPreprocessor(function (option) {
  50705. // Always has a global axisPointerModel for default setting.
  50706. if (option) {
  50707. (!option.axisPointer || option.axisPointer.length === 0)
  50708. && (option.axisPointer = {});
  50709. var link = option.axisPointer.link;
  50710. // Normalize to array to avoid object mergin. But if link
  50711. // is not set, remain null/undefined, otherwise it will
  50712. // override existent link setting.
  50713. if (link && !isArray(link)) {
  50714. option.axisPointer.link = [link];
  50715. }
  50716. }
  50717. });
  50718. // This process should proformed after coordinate systems created
  50719. // and series data processed. So put it on statistic processing stage.
  50720. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  50721. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  50722. // allAxesInfo should be updated when setOption performed.
  50723. ecModel.getComponent('axisPointer').coordSysAxesInfo
  50724. = collect(ecModel, api);
  50725. });
  50726. // Broadcast to all views.
  50727. registerAction({
  50728. type: 'updateAxisPointer',
  50729. event: 'updateAxisPointer',
  50730. update: ':updateAxisPointer'
  50731. }, axisTrigger);
  50732. var XY = ['x', 'y'];
  50733. var WH = ['width', 'height'];
  50734. var SingleAxisPointer = BaseAxisPointer.extend({
  50735. /**
  50736. * @override
  50737. */
  50738. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  50739. var axis = axisModel.axis;
  50740. var coordSys = axis.coordinateSystem;
  50741. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  50742. var pixelValue = coordSys.dataToPoint(value)[0];
  50743. var axisPointerType = axisPointerModel.get('type');
  50744. if (axisPointerType && axisPointerType !== 'none') {
  50745. var elStyle = buildElStyle(axisPointerModel);
  50746. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  50747. axis, pixelValue, otherExtent, elStyle
  50748. );
  50749. pointerOption.style = elStyle;
  50750. elOption.graphicKey = pointerOption.type;
  50751. elOption.pointer = pointerOption;
  50752. }
  50753. var layoutInfo = layout$2(axisModel);
  50754. buildCartesianSingleLabelElOption(
  50755. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  50756. );
  50757. },
  50758. /**
  50759. * @override
  50760. */
  50761. getHandleTransform: function (value, axisModel, axisPointerModel) {
  50762. var layoutInfo = layout$2(axisModel, {labelInside: false});
  50763. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  50764. return {
  50765. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  50766. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  50767. };
  50768. },
  50769. /**
  50770. * @override
  50771. */
  50772. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  50773. var axis = axisModel.axis;
  50774. var coordSys = axis.coordinateSystem;
  50775. var dimIndex = getPointDimIndex(axis);
  50776. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  50777. var currPosition = transform.position;
  50778. currPosition[dimIndex] += delta[dimIndex];
  50779. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  50780. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  50781. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  50782. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  50783. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  50784. cursorPoint[dimIndex] = currPosition[dimIndex];
  50785. return {
  50786. position: currPosition,
  50787. rotation: transform.rotation,
  50788. cursorPoint: cursorPoint,
  50789. tooltipOption: {
  50790. verticalAlign: 'middle'
  50791. }
  50792. };
  50793. }
  50794. });
  50795. var pointerShapeBuilder$1 = {
  50796. line: function (axis, pixelValue, otherExtent, elStyle) {
  50797. var targetShape = makeLineShape(
  50798. [pixelValue, otherExtent[0]],
  50799. [pixelValue, otherExtent[1]],
  50800. getPointDimIndex(axis)
  50801. );
  50802. subPixelOptimizeLine({
  50803. shape: targetShape,
  50804. style: elStyle
  50805. });
  50806. return {
  50807. type: 'Line',
  50808. shape: targetShape
  50809. };
  50810. },
  50811. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  50812. var bandWidth = axis.getBandWidth();
  50813. var span = otherExtent[1] - otherExtent[0];
  50814. return {
  50815. type: 'Rect',
  50816. shape: makeRectShape(
  50817. [pixelValue - bandWidth / 2, otherExtent[0]],
  50818. [bandWidth, span],
  50819. getPointDimIndex(axis)
  50820. )
  50821. };
  50822. }
  50823. };
  50824. function getPointDimIndex(axis) {
  50825. return axis.isHorizontal() ? 0 : 1;
  50826. }
  50827. function getGlobalExtent(coordSys, dimIndex) {
  50828. var rect = coordSys.getRect();
  50829. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  50830. }
  50831. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  50832. extendComponentView({
  50833. type: 'single'
  50834. });
  50835. /**
  50836. * @file Define the themeRiver view's series model
  50837. * @author Deqing Li(annong035@gmail.com)
  50838. */
  50839. var DATA_NAME_INDEX = 2;
  50840. var ThemeRiverSeries = SeriesModel.extend({
  50841. type: 'series.themeRiver',
  50842. dependencies: ['singleAxis'],
  50843. /**
  50844. * @readOnly
  50845. * @type {module:zrender/core/util#HashMap}
  50846. */
  50847. nameMap: null,
  50848. /**
  50849. * @override
  50850. */
  50851. init: function (option) {
  50852. ThemeRiverSeries.superApply(this, 'init', arguments);
  50853. // Put this function here is for the sake of consistency of code style.
  50854. // Enable legend selection for each data item
  50855. // Use a function instead of direct access because data reference may changed
  50856. this.legendDataProvider = function () {
  50857. return this.getRawData();
  50858. };
  50859. },
  50860. /**
  50861. * If there is no value of a certain point in the time for some event,set it value to 0.
  50862. *
  50863. * @param {Array} data initial data in the option
  50864. * @return {Array}
  50865. */
  50866. fixData: function (data) {
  50867. var rawDataLength = data.length;
  50868. // grouped data by name
  50869. var dataByName = nest()
  50870. .key(function (dataItem) {
  50871. return dataItem[2];
  50872. })
  50873. .entries(data);
  50874. // data group in each layer
  50875. var layData = map(dataByName, function (d) {
  50876. return {
  50877. name: d.key,
  50878. dataList: d.values
  50879. };
  50880. });
  50881. var layerNum = layData.length;
  50882. var largestLayer = -1;
  50883. var index = -1;
  50884. for (var i = 0; i < layerNum; ++i) {
  50885. var len = layData[i].dataList.length;
  50886. if (len > largestLayer) {
  50887. largestLayer = len;
  50888. index = i;
  50889. }
  50890. }
  50891. for (var k = 0; k < layerNum; ++k) {
  50892. if (k === index) {
  50893. continue;
  50894. }
  50895. var name = layData[k].name;
  50896. for (var j = 0; j < largestLayer; ++j) {
  50897. var timeValue = layData[index].dataList[j][0];
  50898. var length = layData[k].dataList.length;
  50899. var keyIndex = -1;
  50900. for (var l = 0; l < length; ++l) {
  50901. var value = layData[k].dataList[l][0];
  50902. if (value === timeValue) {
  50903. keyIndex = l;
  50904. break;
  50905. }
  50906. }
  50907. if (keyIndex === -1) {
  50908. data[rawDataLength] = [];
  50909. data[rawDataLength][0] = timeValue;
  50910. data[rawDataLength][1] = 0;
  50911. data[rawDataLength][2] = name;
  50912. rawDataLength++;
  50913. }
  50914. }
  50915. }
  50916. return data;
  50917. },
  50918. /**
  50919. * @override
  50920. * @param {Object} option the initial option that user gived
  50921. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  50922. * @return {module:echarts/data/List}
  50923. */
  50924. getInitialData: function (option, ecModel) {
  50925. var singleAxisModel = ecModel.queryComponents({
  50926. mainType: 'singleAxis',
  50927. index: this.get('singleAxisIndex'),
  50928. id: this.get('singleAxisId')
  50929. })[0];
  50930. var axisType = singleAxisModel.get('type');
  50931. // filter the data item with the value of label is undefined
  50932. var filterData = filter(option.data, function (dataItem) {
  50933. return dataItem[2] !== undefined;
  50934. });
  50935. // ??? TODO design a stage to transfer data for themeRiver and lines?
  50936. var data = this.fixData(filterData || []);
  50937. var nameList = [];
  50938. var nameMap = this.nameMap = createHashMap();
  50939. var count = 0;
  50940. for (var i = 0; i < data.length; ++i) {
  50941. nameList.push(data[i][DATA_NAME_INDEX]);
  50942. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  50943. nameMap.set(data[i][DATA_NAME_INDEX], count);
  50944. count++;
  50945. }
  50946. }
  50947. var dimensionsInfo = createDimensions(data, {
  50948. coordDimensions: ['single'],
  50949. dimensionsDefine: [
  50950. {
  50951. name: 'time',
  50952. type: getDimensionTypeByAxis(axisType)
  50953. },
  50954. {
  50955. name: 'value',
  50956. type: 'float'
  50957. },
  50958. {
  50959. name: 'name',
  50960. type: 'ordinal'
  50961. }
  50962. ],
  50963. encodeDefine: {
  50964. single: 0,
  50965. value: 1,
  50966. itemName: 2
  50967. }
  50968. });
  50969. var list = new List(dimensionsInfo, this);
  50970. list.initData(data);
  50971. return list;
  50972. },
  50973. /**
  50974. * The raw data is divided into multiple layers and each layer
  50975. * has same name.
  50976. *
  50977. * @return {Array.<Array.<number>>}
  50978. */
  50979. getLayerSeries: function () {
  50980. var data = this.getData();
  50981. var lenCount = data.count();
  50982. var indexArr = [];
  50983. for (var i = 0; i < lenCount; ++i) {
  50984. indexArr[i] = i;
  50985. }
  50986. // data group by name
  50987. var dataByName = nest()
  50988. .key(function (index) {
  50989. return data.get('name', index);
  50990. })
  50991. .entries(indexArr);
  50992. var layerSeries = map(dataByName, function (d) {
  50993. return {
  50994. name: d.key,
  50995. indices: d.values
  50996. };
  50997. });
  50998. var timeDim = data.mapDimension('single');
  50999. for (var j = 0; j < layerSeries.length; ++j) {
  51000. layerSeries[j].indices.sort(comparer);
  51001. }
  51002. function comparer(index1, index2) {
  51003. return data.get(timeDim, index1) - data.get(timeDim, index2);
  51004. }
  51005. return layerSeries;
  51006. },
  51007. /**
  51008. * Get data indices for show tooltip content
  51009. *
  51010. * @param {Array.<string>|string} dim single coordinate dimension
  51011. * @param {number} value axis value
  51012. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  51013. * the themeRiver.
  51014. * @return {Object} {dataIndices, nestestValue}
  51015. */
  51016. getAxisTooltipData: function (dim, value, baseAxis) {
  51017. if (!isArray(dim)) {
  51018. dim = dim ? [dim] : [];
  51019. }
  51020. var data = this.getData();
  51021. var layerSeries = this.getLayerSeries();
  51022. var indices = [];
  51023. var layerNum = layerSeries.length;
  51024. var nestestValue;
  51025. for (var i = 0; i < layerNum; ++i) {
  51026. var minDist = Number.MAX_VALUE;
  51027. var nearestIdx = -1;
  51028. var pointNum = layerSeries[i].indices.length;
  51029. for (var j = 0; j < pointNum; ++j) {
  51030. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  51031. var dist = Math.abs(theValue - value);
  51032. if (dist <= minDist) {
  51033. nestestValue = theValue;
  51034. minDist = dist;
  51035. nearestIdx = layerSeries[i].indices[j];
  51036. }
  51037. }
  51038. indices.push(nearestIdx);
  51039. }
  51040. return {dataIndices: indices, nestestValue: nestestValue};
  51041. },
  51042. /**
  51043. * @override
  51044. * @param {number} dataIndex index of data
  51045. */
  51046. formatTooltip: function (dataIndex) {
  51047. var data = this.getData();
  51048. var htmlName = data.getName(dataIndex);
  51049. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  51050. if (isNaN(htmlValue) || htmlValue == null) {
  51051. htmlValue = '-';
  51052. }
  51053. return encodeHTML(htmlName + ' : ' + htmlValue);
  51054. },
  51055. defaultOption: {
  51056. zlevel: 0,
  51057. z: 2,
  51058. coordinateSystem: 'singleAxis',
  51059. // gap in axis's orthogonal orientation
  51060. boundaryGap: ['10%', '10%'],
  51061. // legendHoverLink: true,
  51062. singleAxisIndex: 0,
  51063. animationEasing: 'linear',
  51064. label: {
  51065. margin: 4,
  51066. textAlign: 'right',
  51067. show: true,
  51068. position: 'left',
  51069. color: '#000',
  51070. fontSize: 11
  51071. },
  51072. emphasis: {
  51073. label: {
  51074. show: true
  51075. }
  51076. }
  51077. }
  51078. });
  51079. /**
  51080. * @file The file used to draw themeRiver view
  51081. * @author Deqing Li(annong035@gmail.com)
  51082. */
  51083. extendChartView({
  51084. type: 'themeRiver',
  51085. init: function () {
  51086. this._layers = [];
  51087. },
  51088. render: function (seriesModel, ecModel, api) {
  51089. var data = seriesModel.getData();
  51090. var group = this.group;
  51091. var layerSeries = seriesModel.getLayerSeries();
  51092. var layoutInfo = data.getLayout('layoutInfo');
  51093. var rect = layoutInfo.rect;
  51094. var boundaryGap = layoutInfo.boundaryGap;
  51095. group.attr('position', [0, rect.y + boundaryGap[0]]);
  51096. function keyGetter(item) {
  51097. return item.name;
  51098. }
  51099. var dataDiffer = new DataDiffer(
  51100. this._layersSeries || [], layerSeries,
  51101. keyGetter, keyGetter
  51102. );
  51103. var newLayersGroups = {};
  51104. dataDiffer
  51105. .add(bind(process, this, 'add'))
  51106. .update(bind(process, this, 'update'))
  51107. .remove(bind(process, this, 'remove'))
  51108. .execute();
  51109. function process(status, idx, oldIdx) {
  51110. var oldLayersGroups = this._layers;
  51111. if (status === 'remove') {
  51112. group.remove(oldLayersGroups[idx]);
  51113. return;
  51114. }
  51115. var points0 = [];
  51116. var points1 = [];
  51117. var color;
  51118. var indices = layerSeries[idx].indices;
  51119. for (var j = 0; j < indices.length; j++) {
  51120. var layout = data.getItemLayout(indices[j]);
  51121. var x = layout.x;
  51122. var y0 = layout.y0;
  51123. var y = layout.y;
  51124. points0.push([x, y0]);
  51125. points1.push([x, y0 + y]);
  51126. color = data.getItemVisual(indices[j], 'color');
  51127. }
  51128. var polygon;
  51129. var text;
  51130. var textLayout = data.getItemLayout(indices[0]);
  51131. var itemModel = data.getItemModel(indices[j - 1]);
  51132. var labelModel = itemModel.getModel('label');
  51133. var margin = labelModel.get('margin');
  51134. if (status === 'add') {
  51135. var layerGroup = newLayersGroups[idx] = new Group();
  51136. polygon = new Polygon$1({
  51137. shape: {
  51138. points: points0,
  51139. stackedOnPoints: points1,
  51140. smooth: 0.4,
  51141. stackedOnSmooth: 0.4,
  51142. smoothConstraint: false
  51143. },
  51144. z2: 0
  51145. });
  51146. text = new Text({
  51147. style: {
  51148. x: textLayout.x - margin,
  51149. y: textLayout.y0 + textLayout.y / 2
  51150. }
  51151. });
  51152. layerGroup.add(polygon);
  51153. layerGroup.add(text);
  51154. group.add(layerGroup);
  51155. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  51156. polygon.removeClipPath();
  51157. }));
  51158. }
  51159. else {
  51160. var layerGroup = oldLayersGroups[oldIdx];
  51161. polygon = layerGroup.childAt(0);
  51162. text = layerGroup.childAt(1);
  51163. group.add(layerGroup);
  51164. newLayersGroups[idx] = layerGroup;
  51165. updateProps(polygon, {
  51166. shape: {
  51167. points: points0,
  51168. stackedOnPoints: points1
  51169. }
  51170. }, seriesModel);
  51171. updateProps(text, {
  51172. style: {
  51173. x: textLayout.x - margin,
  51174. y: textLayout.y0 + textLayout.y / 2
  51175. }
  51176. }, seriesModel);
  51177. }
  51178. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  51179. var itemStyleModel = itemModel.getModel('itemStyle');
  51180. setTextStyle(text.style, labelModel, {
  51181. text: labelModel.get('show')
  51182. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  51183. || data.getName(indices[j - 1])
  51184. : null,
  51185. textVerticalAlign: 'middle'
  51186. });
  51187. polygon.setStyle(extend({
  51188. fill: color
  51189. }, itemStyleModel.getItemStyle(['color'])));
  51190. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  51191. }
  51192. this._layersSeries = layerSeries;
  51193. this._layers = newLayersGroups;
  51194. },
  51195. dispose: function () {}
  51196. });
  51197. // add animation to the view
  51198. function createGridClipShape$3(rect, seriesModel, cb) {
  51199. var rectEl = new Rect({
  51200. shape: {
  51201. x: rect.x - 10,
  51202. y: rect.y - 10,
  51203. width: 0,
  51204. height: rect.height + 20
  51205. }
  51206. });
  51207. initProps(rectEl, {
  51208. shape: {
  51209. width: rect.width + 20,
  51210. height: rect.height + 20
  51211. }
  51212. }, seriesModel, cb);
  51213. return rectEl;
  51214. }
  51215. /**
  51216. * @file Using layout algorithm transform the raw data to layout information.
  51217. * @author Deqing Li(annong035@gmail.com)
  51218. */
  51219. var themeRiverLayout = function (ecModel, api) {
  51220. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  51221. var data = seriesModel.getData();
  51222. var single = seriesModel.coordinateSystem;
  51223. var layoutInfo = {};
  51224. // use the axis boundingRect for view
  51225. var rect = single.getRect();
  51226. layoutInfo.rect = rect;
  51227. var boundaryGap = seriesModel.get('boundaryGap');
  51228. var axis = single.getAxis();
  51229. layoutInfo.boundaryGap = boundaryGap;
  51230. if (axis.orient === 'horizontal') {
  51231. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  51232. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  51233. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  51234. themeRiverLayout$1(data, seriesModel, height);
  51235. }
  51236. else {
  51237. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  51238. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  51239. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  51240. themeRiverLayout$1(data, seriesModel, width);
  51241. }
  51242. data.setLayout('layoutInfo', layoutInfo);
  51243. });
  51244. };
  51245. /**
  51246. * The layout information about themeriver
  51247. *
  51248. * @param {module:echarts/data/List} data data in the series
  51249. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  51250. * @param {number} height value used to compute every series height
  51251. */
  51252. function themeRiverLayout$1(data, seriesModel, height) {
  51253. if (!data.count()) {
  51254. return;
  51255. }
  51256. var coordSys = seriesModel.coordinateSystem;
  51257. // the data in each layer are organized into a series.
  51258. var layerSeries = seriesModel.getLayerSeries();
  51259. // the points in each layer.
  51260. var timeDim = data.mapDimension('single');
  51261. var valueDim = data.mapDimension('value');
  51262. var layerPoints = map(layerSeries, function (singleLayer) {
  51263. return map(singleLayer.indices, function (idx) {
  51264. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  51265. pt[1] = data.get(valueDim, idx);
  51266. return pt;
  51267. });
  51268. });
  51269. var base = computeBaseline(layerPoints);
  51270. var baseLine = base.y0;
  51271. var ky = height / base.max;
  51272. // set layout information for each item.
  51273. var n = layerSeries.length;
  51274. var m = layerSeries[0].indices.length;
  51275. var baseY0;
  51276. for (var j = 0; j < m; ++j) {
  51277. baseY0 = baseLine[j] * ky;
  51278. data.setItemLayout(layerSeries[0].indices[j], {
  51279. layerIndex: 0,
  51280. x: layerPoints[0][j][0],
  51281. y0: baseY0,
  51282. y: layerPoints[0][j][1] * ky
  51283. });
  51284. for (var i = 1; i < n; ++i) {
  51285. baseY0 += layerPoints[i - 1][j][1] * ky;
  51286. data.setItemLayout(layerSeries[i].indices[j], {
  51287. layerIndex: i,
  51288. x: layerPoints[i][j][0],
  51289. y0: baseY0,
  51290. y: layerPoints[i][j][1] * ky
  51291. });
  51292. }
  51293. }
  51294. }
  51295. /**
  51296. * Compute the baseLine of the rawdata
  51297. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  51298. *
  51299. * @param {Array.<Array>} data the points in each layer
  51300. * @return {Object}
  51301. */
  51302. function computeBaseline(data) {
  51303. var layerNum = data.length;
  51304. var pointNum = data[0].length;
  51305. var sums = [];
  51306. var y0 = [];
  51307. var max = 0;
  51308. var temp;
  51309. var base = {};
  51310. for (var i = 0; i < pointNum; ++i) {
  51311. for (var j = 0, temp = 0; j < layerNum; ++j) {
  51312. temp += data[j][i][1];
  51313. }
  51314. if (temp > max) {
  51315. max = temp;
  51316. }
  51317. sums.push(temp);
  51318. }
  51319. for (var k = 0; k < pointNum; ++k) {
  51320. y0[k] = (max - sums[k]) / 2;
  51321. }
  51322. max = 0;
  51323. for (var l = 0; l < pointNum; ++l) {
  51324. var sum = sums[l] + y0[l];
  51325. if (sum > max) {
  51326. max = sum;
  51327. }
  51328. }
  51329. base.y0 = y0;
  51330. base.max = max;
  51331. return base;
  51332. }
  51333. /**
  51334. * @file Visual encoding for themeRiver view
  51335. * @author Deqing Li(annong035@gmail.com)
  51336. */
  51337. var themeRiverVisual = function (ecModel) {
  51338. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  51339. var data = seriesModel.getData();
  51340. var rawData = seriesModel.getRawData();
  51341. var colorList = seriesModel.get('color');
  51342. var idxMap = createHashMap();
  51343. data.each(function (idx) {
  51344. idxMap.set(data.getRawIndex(idx), idx);
  51345. });
  51346. rawData.each(function (rawIndex) {
  51347. var name = rawData.getName(rawIndex);
  51348. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  51349. rawData.setItemVisual(rawIndex, 'color', color);
  51350. var idx = idxMap.get(rawIndex);
  51351. if (idx != null) {
  51352. data.setItemVisual(idx, 'color', color);
  51353. }
  51354. });
  51355. });
  51356. };
  51357. registerLayout(themeRiverLayout);
  51358. registerVisual(themeRiverVisual);
  51359. registerProcessor(dataFilter('themeRiver'));
  51360. SeriesModel.extend({
  51361. type: 'series.sunburst',
  51362. /**
  51363. * @type {module:echarts/data/Tree~Node}
  51364. */
  51365. _viewRoot: null,
  51366. getInitialData: function (option, ecModel) {
  51367. // Create a virtual root.
  51368. var root = { name: option.name, children: option.data };
  51369. completeTreeValue$1(root);
  51370. var levels = option.levels || [];
  51371. // levels = option.levels = setDefault(levels, ecModel);
  51372. var treeOption = {};
  51373. treeOption.levels = levels;
  51374. // Make sure always a new tree is created when setOption,
  51375. // in TreemapView, we check whether oldTree === newTree
  51376. // to choose mappings approach among old shapes and new shapes.
  51377. return Tree.createTree(root, this, treeOption).data;
  51378. },
  51379. optionUpdated: function () {
  51380. this.resetViewRoot();
  51381. },
  51382. /*
  51383. * @override
  51384. */
  51385. getDataParams: function (dataIndex) {
  51386. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  51387. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  51388. params.treePathInfo = wrapTreePathInfo(node, this);
  51389. return params;
  51390. },
  51391. defaultOption: {
  51392. zlevel: 0,
  51393. z: 2,
  51394. // 默认全局居中
  51395. center: ['50%', '50%'],
  51396. radius: [0, '75%'],
  51397. // 默认顺时针
  51398. clockwise: true,
  51399. startAngle: 90,
  51400. // 最小角度改为0
  51401. minAngle: 0,
  51402. percentPrecision: 2,
  51403. // If still show when all data zero.
  51404. stillShowZeroSum: true,
  51405. // Policy of highlighting pieces when hover on one
  51406. // Valid values: 'none' (for not downplay others), 'descendant',
  51407. // 'ancestor', 'self'
  51408. highlightPolicy: 'descendant',
  51409. // 'rootToNode', 'link', or false
  51410. nodeClick: 'rootToNode',
  51411. renderLabelForZeroData: false,
  51412. label: {
  51413. // could be: 'radial', 'tangential', or 'none'
  51414. rotate: 'radial',
  51415. show: true,
  51416. opacity: 1,
  51417. // 'left' is for inner side of inside, and 'right' is for outter
  51418. // side for inside
  51419. align: 'center',
  51420. position: 'inside',
  51421. distance: 5,
  51422. silent: true,
  51423. emphasis: {}
  51424. },
  51425. itemStyle: {
  51426. borderWidth: 1,
  51427. borderColor: 'white',
  51428. opacity: 1,
  51429. emphasis: {},
  51430. highlight: {
  51431. opacity: 1
  51432. },
  51433. downplay: {
  51434. opacity: 0.9
  51435. }
  51436. },
  51437. // Animation type canbe expansion, scale
  51438. animationType: 'expansion',
  51439. animationDuration: 1000,
  51440. animationDurationUpdate: 500,
  51441. animationEasing: 'cubicOut',
  51442. data: [],
  51443. levels: [],
  51444. /**
  51445. * Sort order.
  51446. *
  51447. * Valid values: 'desc', 'asc', null, or callback function.
  51448. * 'desc' and 'asc' for descend and ascendant order;
  51449. * null for not sorting;
  51450. * example of callback function:
  51451. * function(nodeA, nodeB) {
  51452. * return nodeA.getValue() - nodeB.getValue();
  51453. * }
  51454. */
  51455. sort: 'desc'
  51456. },
  51457. getViewRoot: function () {
  51458. return this._viewRoot;
  51459. },
  51460. /**
  51461. * @param {module:echarts/data/Tree~Node} [viewRoot]
  51462. */
  51463. resetViewRoot: function (viewRoot) {
  51464. viewRoot
  51465. ? (this._viewRoot = viewRoot)
  51466. : (viewRoot = this._viewRoot);
  51467. var root = this.getRawData().tree.root;
  51468. if (!viewRoot
  51469. || (viewRoot !== root && !root.contains(viewRoot))
  51470. ) {
  51471. this._viewRoot = root;
  51472. }
  51473. }
  51474. });
  51475. /**
  51476. * @param {Object} dataNode
  51477. */
  51478. function completeTreeValue$1(dataNode) {
  51479. // Postorder travel tree.
  51480. // If value of none-leaf node is not set,
  51481. // calculate it by suming up the value of all children.
  51482. var sum = 0;
  51483. each$1(dataNode.children, function (child) {
  51484. completeTreeValue$1(child);
  51485. var childValue = child.value;
  51486. isArray(childValue) && (childValue = childValue[0]);
  51487. sum += childValue;
  51488. });
  51489. var thisValue = dataNode.value;
  51490. if (isArray(thisValue)) {
  51491. thisValue = thisValue[0];
  51492. }
  51493. if (thisValue == null || isNaN(thisValue)) {
  51494. thisValue = sum;
  51495. }
  51496. // Value should not less than 0.
  51497. if (thisValue < 0) {
  51498. thisValue = 0;
  51499. }
  51500. isArray(dataNode.value)
  51501. ? (dataNode.value[0] = thisValue)
  51502. : (dataNode.value = thisValue);
  51503. }
  51504. var NodeHighlightPolicy = {
  51505. NONE: 'none', // not downplay others
  51506. DESCENDANT: 'descendant',
  51507. ANCESTOR: 'ancestor',
  51508. SELF: 'self'
  51509. };
  51510. var DEFAULT_SECTOR_Z = 2;
  51511. var DEFAULT_TEXT_Z = 4;
  51512. /**
  51513. * Sunburstce of Sunburst including Sector, Label, LabelLine
  51514. * @constructor
  51515. * @extends {module:zrender/graphic/Group}
  51516. */
  51517. function SunburstPiece(node, seriesModel, ecModel) {
  51518. Group.call(this);
  51519. var sector = new Sector({
  51520. z2: DEFAULT_SECTOR_Z
  51521. });
  51522. var text = new Text({
  51523. z2: DEFAULT_TEXT_Z,
  51524. silent: node.getModel('label').get('silent')
  51525. });
  51526. this.add(sector);
  51527. this.add(text);
  51528. this.updateData(true, node, 'normal', seriesModel, ecModel);
  51529. // Hover to change label and labelLine
  51530. function onEmphasis() {
  51531. text.ignore = text.hoverIgnore;
  51532. }
  51533. function onNormal() {
  51534. text.ignore = text.normalIgnore;
  51535. }
  51536. this.on('emphasis', onEmphasis)
  51537. .on('normal', onNormal)
  51538. .on('mouseover', onEmphasis)
  51539. .on('mouseout', onNormal);
  51540. }
  51541. var SunburstPieceProto = SunburstPiece.prototype;
  51542. SunburstPieceProto.updateData = function (
  51543. firstCreate,
  51544. node,
  51545. state,
  51546. seriesModel,
  51547. ecModel
  51548. ) {
  51549. this.node = node;
  51550. node.piece = this;
  51551. seriesModel = seriesModel || this._seriesModel;
  51552. ecModel = ecModel || this._ecModel;
  51553. var sector = this.childAt(0);
  51554. sector.dataIndex = node.dataIndex;
  51555. var itemModel = node.getModel();
  51556. var layout = node.getLayout();
  51557. var sectorShape = extend({}, layout);
  51558. sectorShape.label = null;
  51559. var visualColor = getNodeColor(node, seriesModel, ecModel);
  51560. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  51561. var style;
  51562. if (state === 'normal') {
  51563. style = normalStyle;
  51564. }
  51565. else {
  51566. var stateStyle = itemModel.getModel(state + '.itemStyle')
  51567. .getItemStyle();
  51568. style = merge(stateStyle, normalStyle);
  51569. }
  51570. style = defaults(
  51571. {
  51572. lineJoin: 'bevel',
  51573. fill: style.fill || visualColor
  51574. },
  51575. style
  51576. );
  51577. if (firstCreate) {
  51578. sector.setShape(sectorShape);
  51579. sector.shape.r = layout.r0;
  51580. updateProps(
  51581. sector,
  51582. {
  51583. shape: {
  51584. r: layout.r
  51585. }
  51586. },
  51587. seriesModel,
  51588. node.dataIndex
  51589. );
  51590. sector.useStyle(style);
  51591. }
  51592. else if (typeof style.fill === 'object' && style.fill.type
  51593. || typeof sector.style.fill === 'object' && sector.style.fill.type
  51594. ) {
  51595. // Disable animation for gradient since no interpolation method
  51596. // is supported for gradient
  51597. updateProps(sector, {
  51598. shape: sectorShape
  51599. }, seriesModel);
  51600. sector.useStyle(style);
  51601. }
  51602. else {
  51603. updateProps(sector, {
  51604. shape: sectorShape,
  51605. style: style
  51606. }, seriesModel);
  51607. }
  51608. this._updateLabel(seriesModel, visualColor, state);
  51609. var cursorStyle = itemModel.getShallow('cursor');
  51610. cursorStyle && sector.attr('cursor', cursorStyle);
  51611. if (firstCreate) {
  51612. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  51613. this._initEvents(sector, node, seriesModel, highlightPolicy);
  51614. }
  51615. this._seriesModel = seriesModel || this._seriesModel;
  51616. this._ecModel = ecModel || this._ecModel;
  51617. };
  51618. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  51619. var that = this;
  51620. this.node.hostTree.root.eachNode(function (n) {
  51621. if (n.piece) {
  51622. if (that.node === n) {
  51623. n.piece.updateData(false, n, 'emphasis');
  51624. }
  51625. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  51626. n.piece.childAt(0).trigger('highlight');
  51627. }
  51628. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  51629. n.piece.childAt(0).trigger('downplay');
  51630. }
  51631. }
  51632. });
  51633. };
  51634. SunburstPieceProto.onNormal = function () {
  51635. this.node.hostTree.root.eachNode(function (n) {
  51636. if (n.piece) {
  51637. n.piece.updateData(false, n, 'normal');
  51638. }
  51639. });
  51640. };
  51641. SunburstPieceProto.onHighlight = function () {
  51642. this.updateData(false, this.node, 'highlight');
  51643. };
  51644. SunburstPieceProto.onDownplay = function () {
  51645. this.updateData(false, this.node, 'downplay');
  51646. };
  51647. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  51648. var itemModel = this.node.getModel();
  51649. var normalModel = itemModel.getModel('label');
  51650. var labelModel = state === 'normal' || state === 'emphasis'
  51651. ? normalModel
  51652. : itemModel.getModel(state + '.label');
  51653. var labelHoverModel = itemModel.getModel('emphasis.label');
  51654. var text = retrieve(
  51655. seriesModel.getFormattedLabel(
  51656. this.node.dataIndex, 'normal', null, null, 'label'
  51657. ),
  51658. this.node.name
  51659. );
  51660. if (getLabelAttr('show') === false) {
  51661. text = '';
  51662. }
  51663. var layout = this.node.getLayout();
  51664. var labelMinAngle = labelModel.get('minAngle');
  51665. if (labelMinAngle == null) {
  51666. labelMinAngle = normalModel.get('minAngle');
  51667. }
  51668. labelMinAngle = labelMinAngle / 180 * Math.PI;
  51669. var angle = layout.endAngle - layout.startAngle;
  51670. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  51671. // Not displaying text when angle is too small
  51672. text = '';
  51673. }
  51674. var label = this.childAt(1);
  51675. setLabelStyle(
  51676. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  51677. {
  51678. defaultText: labelModel.getShallow('show') ? text : null,
  51679. autoColor: visualColor,
  51680. useInsideStyle: true
  51681. }
  51682. );
  51683. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  51684. var dx = Math.cos(midAngle);
  51685. var dy = Math.sin(midAngle);
  51686. var r;
  51687. var labelPosition = getLabelAttr('position');
  51688. var labelPadding = getLabelAttr('distance') || 0;
  51689. var textAlign = getLabelAttr('align');
  51690. if (labelPosition === 'outside') {
  51691. r = layout.r + labelPadding;
  51692. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  51693. }
  51694. else {
  51695. if (!textAlign || textAlign === 'center') {
  51696. r = (layout.r + layout.r0) / 2;
  51697. textAlign = 'center';
  51698. }
  51699. else if (textAlign === 'left') {
  51700. r = layout.r0 + labelPadding;
  51701. if (midAngle > Math.PI / 2) {
  51702. textAlign = 'right';
  51703. }
  51704. }
  51705. else if (textAlign === 'right') {
  51706. r = layout.r - labelPadding;
  51707. if (midAngle > Math.PI / 2) {
  51708. textAlign = 'left';
  51709. }
  51710. }
  51711. }
  51712. label.attr('style', {
  51713. text: text,
  51714. textAlign: textAlign,
  51715. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  51716. opacity: getLabelAttr('opacity')
  51717. });
  51718. var textX = r * dx + layout.cx;
  51719. var textY = r * dy + layout.cy;
  51720. label.attr('position', [textX, textY]);
  51721. var rotateType = getLabelAttr('rotate');
  51722. var rotate = 0;
  51723. if (rotateType === 'radial') {
  51724. rotate = -midAngle;
  51725. if (rotate < -Math.PI / 2) {
  51726. rotate += Math.PI;
  51727. }
  51728. }
  51729. else if (rotateType === 'tangential') {
  51730. rotate = Math.PI / 2 - midAngle;
  51731. if (rotate > Math.PI / 2) {
  51732. rotate -= Math.PI;
  51733. }
  51734. else if (rotate < -Math.PI / 2) {
  51735. rotate += Math.PI;
  51736. }
  51737. } else if (typeof rotateType === 'number') {
  51738. rotate = rotateType * Math.PI / 180;
  51739. }
  51740. label.attr('rotation', rotate);
  51741. function getLabelAttr(name) {
  51742. var stateAttr = labelModel.get(name);
  51743. if (stateAttr == null) {
  51744. return normalModel.get(name);
  51745. }
  51746. else {
  51747. return stateAttr;
  51748. }
  51749. }
  51750. };
  51751. SunburstPieceProto._initEvents = function (
  51752. sector,
  51753. node,
  51754. seriesModel,
  51755. highlightPolicy
  51756. ) {
  51757. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  51758. var that = this;
  51759. var onEmphasis = function () {
  51760. that.onEmphasis(highlightPolicy);
  51761. };
  51762. var onNormal = function () {
  51763. that.onNormal();
  51764. };
  51765. var onDownplay = function () {
  51766. that.onDownplay();
  51767. };
  51768. var onHighlight = function () {
  51769. that.onHighlight();
  51770. };
  51771. if (seriesModel.isAnimationEnabled()) {
  51772. sector
  51773. .on('mouseover', onEmphasis)
  51774. .on('mouseout', onNormal)
  51775. .on('emphasis', onEmphasis)
  51776. .on('normal', onNormal)
  51777. .on('downplay', onDownplay)
  51778. .on('highlight', onHighlight);
  51779. }
  51780. };
  51781. inherits(SunburstPiece, Group);
  51782. /**
  51783. * Get node color
  51784. *
  51785. * @param {TreeNode} node the node to get color
  51786. * @param {module:echarts/model/Series} seriesModel series
  51787. * @param {module:echarts/model/Global} ecModel echarts defaults
  51788. */
  51789. function getNodeColor(node, seriesModel, ecModel) {
  51790. // Color from visualMap
  51791. var visualColor = node.getVisual('color');
  51792. var visualMetaList = node.getVisual('visualMeta');
  51793. if (!visualMetaList || visualMetaList.length === 0) {
  51794. // Use first-generation color if has no visualMap
  51795. visualColor = null;
  51796. }
  51797. // Self color or level color
  51798. var color = node.getModel('itemStyle').get('color');
  51799. if (color) {
  51800. return color;
  51801. }
  51802. else if (visualColor) {
  51803. // Color mapping
  51804. return visualColor;
  51805. }
  51806. else if (node.depth === 0) {
  51807. // Virtual root node
  51808. return ecModel.option.color[0];
  51809. }
  51810. else {
  51811. // First-generation color
  51812. var length = ecModel.option.color.length;
  51813. color = ecModel.option.color[getRootId(node) % length];
  51814. }
  51815. return color;
  51816. }
  51817. /**
  51818. * Get index of root in sorted order
  51819. *
  51820. * @param {TreeNode} node current node
  51821. * @return {number} index in root
  51822. */
  51823. function getRootId(node) {
  51824. var ancestor = node;
  51825. while (ancestor.depth > 1) {
  51826. ancestor = ancestor.parentNode;
  51827. }
  51828. var virtualRoot = node.getAncestors()[0];
  51829. return indexOf(virtualRoot.children, ancestor);
  51830. }
  51831. function isNodeHighlighted(node, activeNode, policy) {
  51832. if (policy === NodeHighlightPolicy.NONE) {
  51833. return false;
  51834. }
  51835. else if (policy === NodeHighlightPolicy.SELF) {
  51836. return node === activeNode;
  51837. }
  51838. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  51839. return node === activeNode || node.isAncestorOf(activeNode);
  51840. }
  51841. else {
  51842. return node === activeNode || node.isDescendantOf(activeNode);
  51843. }
  51844. }
  51845. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  51846. var SunburstView = Chart.extend({
  51847. type: 'sunburst',
  51848. init: function () {
  51849. },
  51850. render: function (seriesModel, ecModel, api, payload) {
  51851. var that = this;
  51852. this.seriesModel = seriesModel;
  51853. this.api = api;
  51854. this.ecModel = ecModel;
  51855. var data = seriesModel.getData();
  51856. var virtualRoot = data.tree.root;
  51857. var newRoot = seriesModel.getViewRoot();
  51858. var group = this.group;
  51859. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  51860. var newChildren = [];
  51861. newRoot.eachNode(function (node) {
  51862. newChildren.push(node);
  51863. });
  51864. var oldChildren = this._oldChildren || [];
  51865. dualTravel(newChildren, oldChildren);
  51866. renderRollUp(virtualRoot, newRoot);
  51867. if (payload && payload.highlight && payload.highlight.piece) {
  51868. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  51869. payload.highlight.piece.onEmphasis(highlightPolicy);
  51870. }
  51871. else if (payload && payload.unhighlight) {
  51872. var piece = virtualRoot.piece;
  51873. if (!piece && virtualRoot.children.length) {
  51874. piece = virtualRoot.children[0].piece;
  51875. }
  51876. if (piece) {
  51877. piece.onNormal();
  51878. }
  51879. }
  51880. this._initEvents();
  51881. this._oldChildren = newChildren;
  51882. function dualTravel(newChildren, oldChildren) {
  51883. if (newChildren.length === 0 && oldChildren.length === 0) {
  51884. return;
  51885. }
  51886. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  51887. .add(processNode)
  51888. .update(processNode)
  51889. .remove(curry(processNode, null))
  51890. .execute();
  51891. function getKey(node) {
  51892. return node.getId();
  51893. }
  51894. function processNode(newId, oldId) {
  51895. var newNode = newId == null ? null : newChildren[newId];
  51896. var oldNode = oldId == null ? null : oldChildren[oldId];
  51897. doRenderNode(newNode, oldNode);
  51898. }
  51899. }
  51900. function doRenderNode(newNode, oldNode) {
  51901. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  51902. // Not render data with value 0
  51903. newNode = null;
  51904. }
  51905. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  51906. if (oldNode && oldNode.piece) {
  51907. if (newNode) {
  51908. // Update
  51909. oldNode.piece.updateData(
  51910. false, newNode, 'normal', seriesModel, ecModel);
  51911. // For tooltip
  51912. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  51913. }
  51914. else {
  51915. // Remove
  51916. removeNode(oldNode);
  51917. }
  51918. }
  51919. else if (newNode) {
  51920. // Add
  51921. var piece = new SunburstPiece(
  51922. newNode,
  51923. seriesModel,
  51924. ecModel
  51925. );
  51926. group.add(piece);
  51927. // For tooltip
  51928. data.setItemGraphicEl(newNode.dataIndex, piece);
  51929. }
  51930. }
  51931. }
  51932. function removeNode(node) {
  51933. if (!node) {
  51934. return;
  51935. }
  51936. if (node.piece) {
  51937. group.remove(node.piece);
  51938. node.piece = null;
  51939. }
  51940. }
  51941. function renderRollUp(virtualRoot, viewRoot) {
  51942. if (viewRoot.depth > 0) {
  51943. // Render
  51944. if (virtualRoot.piece) {
  51945. // Update
  51946. virtualRoot.piece.updateData(
  51947. false, virtualRoot, 'normal', seriesModel, ecModel);
  51948. }
  51949. else {
  51950. // Add
  51951. virtualRoot.piece = new SunburstPiece(
  51952. virtualRoot,
  51953. seriesModel,
  51954. ecModel
  51955. );
  51956. group.add(virtualRoot.piece);
  51957. }
  51958. if (viewRoot.piece._onclickEvent) {
  51959. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  51960. }
  51961. var event = function (e) {
  51962. that._rootToNode(viewRoot.parentNode);
  51963. };
  51964. viewRoot.piece._onclickEvent = event;
  51965. virtualRoot.piece.on('click', event);
  51966. }
  51967. else if (virtualRoot.piece) {
  51968. // Remove
  51969. group.remove(virtualRoot.piece);
  51970. virtualRoot.piece = null;
  51971. }
  51972. }
  51973. },
  51974. dispose: function () {
  51975. },
  51976. /**
  51977. * @private
  51978. */
  51979. _initEvents: function () {
  51980. var that = this;
  51981. var event = function (e) {
  51982. var targetFound = false;
  51983. var viewRoot = that.seriesModel.getViewRoot();
  51984. viewRoot.eachNode(function (node) {
  51985. if (!targetFound
  51986. && node.piece && node.piece.childAt(0) === e.target
  51987. ) {
  51988. var nodeClick = node.getModel().get('nodeClick');
  51989. if (nodeClick === 'rootToNode') {
  51990. that._rootToNode(node);
  51991. }
  51992. else if (nodeClick === 'link') {
  51993. var itemModel = node.getModel();
  51994. var link = itemModel.get('link');
  51995. if (link) {
  51996. var linkTarget = itemModel.get('target', true)
  51997. || '_blank';
  51998. window.open(link, linkTarget);
  51999. }
  52000. }
  52001. targetFound = true;
  52002. }
  52003. });
  52004. };
  52005. if (this.group._onclickEvent) {
  52006. this.group.off('click', this.group._onclickEvent);
  52007. }
  52008. this.group.on('click', event);
  52009. this.group._onclickEvent = event;
  52010. },
  52011. /**
  52012. * @private
  52013. */
  52014. _rootToNode: function (node) {
  52015. if (node !== this.seriesModel.getViewRoot()) {
  52016. this.api.dispatchAction({
  52017. type: ROOT_TO_NODE_ACTION,
  52018. from: this.uid,
  52019. seriesId: this.seriesModel.id,
  52020. targetNode: node
  52021. });
  52022. }
  52023. },
  52024. /**
  52025. * @implement
  52026. */
  52027. containPoint: function (point, seriesModel) {
  52028. var treeRoot = seriesModel.getData();
  52029. var itemLayout = treeRoot.getItemLayout(0);
  52030. if (itemLayout) {
  52031. var dx = point[0] - itemLayout.cx;
  52032. var dy = point[1] - itemLayout.cy;
  52033. var radius = Math.sqrt(dx * dx + dy * dy);
  52034. return radius <= itemLayout.r && radius >= itemLayout.r0;
  52035. }
  52036. }
  52037. });
  52038. /**
  52039. * @file Sunburst action
  52040. */
  52041. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  52042. registerAction(
  52043. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  52044. function (payload, ecModel) {
  52045. ecModel.eachComponent(
  52046. {mainType: 'series', subType: 'sunburst', query: payload},
  52047. handleRootToNode
  52048. );
  52049. function handleRootToNode(model, index) {
  52050. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  52051. if (targetInfo) {
  52052. var originViewRoot = model.getViewRoot();
  52053. if (originViewRoot) {
  52054. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  52055. ? 'rollUp' : 'drillDown';
  52056. }
  52057. model.resetViewRoot(targetInfo.node);
  52058. }
  52059. }
  52060. }
  52061. );
  52062. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  52063. registerAction(
  52064. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  52065. function (payload, ecModel) {
  52066. ecModel.eachComponent(
  52067. {mainType: 'series', subType: 'sunburst', query: payload},
  52068. handleHighlight
  52069. );
  52070. function handleHighlight(model, index) {
  52071. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  52072. if (targetInfo) {
  52073. payload.highlight = targetInfo.node;
  52074. }
  52075. }
  52076. }
  52077. );
  52078. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  52079. registerAction(
  52080. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  52081. function (payload, ecModel) {
  52082. ecModel.eachComponent(
  52083. {mainType: 'series', subType: 'sunburst', query: payload},
  52084. handleUnhighlight
  52085. );
  52086. function handleUnhighlight(model, index) {
  52087. payload.unhighlight = true;
  52088. }
  52089. }
  52090. );
  52091. var RADIAN$1 = Math.PI / 180;
  52092. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  52093. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  52094. var center = seriesModel.get('center');
  52095. var radius = seriesModel.get('radius');
  52096. if (!isArray(radius)) {
  52097. radius = [0, radius];
  52098. }
  52099. if (!isArray(center)) {
  52100. center = [center, center];
  52101. }
  52102. var width = api.getWidth();
  52103. var height = api.getHeight();
  52104. var size = Math.min(width, height);
  52105. var cx = parsePercent$1(center[0], width);
  52106. var cy = parsePercent$1(center[1], height);
  52107. var r0 = parsePercent$1(radius[0], size / 2);
  52108. var r = parsePercent$1(radius[1], size / 2);
  52109. var startAngle = -seriesModel.get('startAngle') * RADIAN$1;
  52110. var minAngle = seriesModel.get('minAngle') * RADIAN$1;
  52111. var virtualRoot = seriesModel.getData().tree.root;
  52112. var treeRoot = seriesModel.getViewRoot();
  52113. var rootDepth = treeRoot.depth;
  52114. var sort = seriesModel.get('sort');
  52115. if (sort != null) {
  52116. initChildren$1(treeRoot, sort);
  52117. }
  52118. var validDataCount = 0;
  52119. each$1(treeRoot.children, function (child) {
  52120. !isNaN(child.getValue()) && validDataCount++;
  52121. });
  52122. var sum = treeRoot.getValue();
  52123. // Sum may be 0
  52124. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  52125. var renderRollupNode = treeRoot.depth > 0;
  52126. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  52127. var rPerLevel = (r - r0) / (levels || 1);
  52128. var clockwise = seriesModel.get('clockwise');
  52129. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  52130. // In the case some sector angle is smaller than minAngle
  52131. var dir = clockwise ? 1 : -1;
  52132. /**
  52133. * Render a tree
  52134. * @return increased angle
  52135. */
  52136. var renderNode = function (node, startAngle) {
  52137. if (!node) {
  52138. return;
  52139. }
  52140. var endAngle = startAngle;
  52141. // Render self
  52142. if (node !== virtualRoot) {
  52143. // Tree node is virtual, so it doesn't need to be drawn
  52144. var value = node.getValue();
  52145. var angle = (sum === 0 && stillShowZeroSum)
  52146. ? unitRadian : (value * unitRadian);
  52147. if (angle < minAngle) {
  52148. angle = minAngle;
  52149. }
  52150. else {
  52151. }
  52152. endAngle = startAngle + dir * angle;
  52153. var depth = node.depth - rootDepth
  52154. - (renderRollupNode ? -1 : 1);
  52155. var rStart = r0 + rPerLevel * depth;
  52156. var rEnd = r0 + rPerLevel * (depth + 1);
  52157. var itemModel = node.getModel();
  52158. if (itemModel.get('r0') != null) {
  52159. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  52160. }
  52161. if (itemModel.get('r') != null) {
  52162. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  52163. }
  52164. node.setLayout({
  52165. angle: angle,
  52166. startAngle: startAngle,
  52167. endAngle: endAngle,
  52168. clockwise: clockwise,
  52169. cx: cx,
  52170. cy: cy,
  52171. r0: rStart,
  52172. r: rEnd
  52173. });
  52174. }
  52175. // Render children
  52176. if (node.children && node.children.length) {
  52177. // currentAngle = startAngle;
  52178. var siblingAngle = 0;
  52179. each$1(node.children, function (node) {
  52180. siblingAngle += renderNode(node, startAngle + siblingAngle);
  52181. });
  52182. }
  52183. return endAngle - startAngle;
  52184. };
  52185. // Virtual root node for roll up
  52186. if (renderRollupNode) {
  52187. var rStart = r0;
  52188. var rEnd = r0 + rPerLevel;
  52189. var angle = Math.PI * 2;
  52190. virtualRoot.setLayout({
  52191. angle: angle,
  52192. startAngle: startAngle,
  52193. endAngle: startAngle + angle,
  52194. clockwise: clockwise,
  52195. cx: cx,
  52196. cy: cy,
  52197. r0: rStart,
  52198. r: rEnd
  52199. });
  52200. }
  52201. renderNode(treeRoot, startAngle);
  52202. });
  52203. };
  52204. /**
  52205. * Init node children by order and update visual
  52206. *
  52207. * @param {TreeNode} node root node
  52208. * @param {boolean} isAsc if is in ascendant order
  52209. */
  52210. function initChildren$1(node, isAsc) {
  52211. var children = node.children || [];
  52212. node.children = sort$2(children, isAsc);
  52213. // Init children recursively
  52214. if (children.length) {
  52215. each$1(node.children, function (child) {
  52216. initChildren$1(child, isAsc);
  52217. });
  52218. }
  52219. }
  52220. /**
  52221. * Sort children nodes
  52222. *
  52223. * @param {TreeNode[]} children children of node to be sorted
  52224. * @param {string | function | null} sort sort method
  52225. * See SunburstSeries.js for details.
  52226. */
  52227. function sort$2(children, sortOrder) {
  52228. if (typeof sortOrder === 'function') {
  52229. return children.sort(sortOrder);
  52230. }
  52231. else {
  52232. var isAsc = sortOrder === 'asc';
  52233. return children.sort(function (a, b) {
  52234. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  52235. return diff === 0
  52236. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  52237. : diff;
  52238. });
  52239. }
  52240. }
  52241. registerVisual(curry(dataColor, 'sunburst'));
  52242. registerLayout(curry(sunburstLayout, 'sunburst'));
  52243. registerProcessor(curry(dataFilter, 'sunburst'));
  52244. function dataToCoordSize(dataSize, dataItem) {
  52245. // dataItem is necessary in log axis.
  52246. dataItem = dataItem || [0, 0];
  52247. return map(['x', 'y'], function (dim, dimIdx) {
  52248. var axis = this.getAxis(dim);
  52249. var val = dataItem[dimIdx];
  52250. var halfSize = dataSize[dimIdx] / 2;
  52251. return axis.type === 'category'
  52252. ? axis.getBandWidth()
  52253. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  52254. }, this);
  52255. }
  52256. var prepareCartesian2d = function (coordSys) {
  52257. var rect = coordSys.grid.getRect();
  52258. return {
  52259. coordSys: {
  52260. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  52261. type: 'cartesian2d',
  52262. x: rect.x,
  52263. y: rect.y,
  52264. width: rect.width,
  52265. height: rect.height
  52266. },
  52267. api: {
  52268. coord: function (data) {
  52269. // do not provide "out" param
  52270. return coordSys.dataToPoint(data);
  52271. },
  52272. size: bind(dataToCoordSize, coordSys)
  52273. }
  52274. };
  52275. };
  52276. function dataToCoordSize$1(dataSize, dataItem) {
  52277. dataItem = dataItem || [0, 0];
  52278. return map([0, 1], function (dimIdx) {
  52279. var val = dataItem[dimIdx];
  52280. var halfSize = dataSize[dimIdx] / 2;
  52281. var p1 = [];
  52282. var p2 = [];
  52283. p1[dimIdx] = val - halfSize;
  52284. p2[dimIdx] = val + halfSize;
  52285. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  52286. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  52287. }, this);
  52288. }
  52289. var prepareGeo = function (coordSys) {
  52290. var rect = coordSys.getBoundingRect();
  52291. return {
  52292. coordSys: {
  52293. type: 'geo',
  52294. x: rect.x,
  52295. y: rect.y,
  52296. width: rect.width,
  52297. height: rect.height
  52298. },
  52299. api: {
  52300. coord: function (data) {
  52301. // do not provide "out" and noRoam param,
  52302. // Compatible with this usage:
  52303. // echarts.util.map(item.points, api.coord)
  52304. return coordSys.dataToPoint(data);
  52305. },
  52306. size: bind(dataToCoordSize$1, coordSys)
  52307. }
  52308. };
  52309. };
  52310. function dataToCoordSize$2(dataSize, dataItem) {
  52311. // dataItem is necessary in log axis.
  52312. var axis = this.getAxis();
  52313. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  52314. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  52315. return axis.type === 'category'
  52316. ? axis.getBandWidth()
  52317. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  52318. }
  52319. var prepareSingleAxis = function (coordSys) {
  52320. var rect = coordSys.getRect();
  52321. return {
  52322. coordSys: {
  52323. type: 'singleAxis',
  52324. x: rect.x,
  52325. y: rect.y,
  52326. width: rect.width,
  52327. height: rect.height
  52328. },
  52329. api: {
  52330. coord: function (val) {
  52331. // do not provide "out" param
  52332. return coordSys.dataToPoint(val);
  52333. },
  52334. size: bind(dataToCoordSize$2, coordSys)
  52335. }
  52336. };
  52337. };
  52338. function dataToCoordSize$3(dataSize, dataItem) {
  52339. // dataItem is necessary in log axis.
  52340. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  52341. var axis = this['get' + dim + 'Axis']();
  52342. var val = dataItem[dimIdx];
  52343. var halfSize = dataSize[dimIdx] / 2;
  52344. var method = 'dataTo' + dim;
  52345. var result = axis.type === 'category'
  52346. ? axis.getBandWidth()
  52347. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  52348. if (dim === 'Angle') {
  52349. result = result * Math.PI / 180;
  52350. }
  52351. return result;
  52352. }, this);
  52353. }
  52354. var preparePolar = function (coordSys) {
  52355. var radiusAxis = coordSys.getRadiusAxis();
  52356. var angleAxis = coordSys.getAngleAxis();
  52357. var radius = radiusAxis.getExtent();
  52358. radius[0] > radius[1] && radius.reverse();
  52359. return {
  52360. coordSys: {
  52361. type: 'polar',
  52362. cx: coordSys.cx,
  52363. cy: coordSys.cy,
  52364. r: radius[1],
  52365. r0: radius[0]
  52366. },
  52367. api: {
  52368. coord: bind(function (data) {
  52369. var radius = radiusAxis.dataToRadius(data[0]);
  52370. var angle = angleAxis.dataToAngle(data[1]);
  52371. var coord = coordSys.coordToPoint([radius, angle]);
  52372. coord.push(radius, angle * Math.PI / 180);
  52373. return coord;
  52374. }),
  52375. size: bind(dataToCoordSize$3, coordSys)
  52376. }
  52377. };
  52378. };
  52379. var prepareCalendar = function (coordSys) {
  52380. var rect = coordSys.getRect();
  52381. var rangeInfo = coordSys.getRangeInfo();
  52382. return {
  52383. coordSys: {
  52384. type: 'calendar',
  52385. x: rect.x,
  52386. y: rect.y,
  52387. width: rect.width,
  52388. height: rect.height,
  52389. cellWidth: coordSys.getCellWidth(),
  52390. cellHeight: coordSys.getCellHeight(),
  52391. rangeInfo: {
  52392. start: rangeInfo.start,
  52393. end: rangeInfo.end,
  52394. weeks: rangeInfo.weeks,
  52395. dayCount: rangeInfo.allDay
  52396. }
  52397. },
  52398. api: {
  52399. coord: function (data, clamp) {
  52400. return coordSys.dataToPoint(data, clamp);
  52401. }
  52402. }
  52403. };
  52404. };
  52405. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  52406. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  52407. var LABEL_NORMAL = ['label'];
  52408. var LABEL_EMPHASIS = ['emphasis', 'label'];
  52409. // Use prefix to avoid index to be the same as el.name,
  52410. // which will cause weird udpate animation.
  52411. var GROUP_DIFF_PREFIX = 'e\0\0';
  52412. /**
  52413. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  52414. * of each coordinate systems are not required by each coordinate systems directly, but
  52415. * required by the module `custom`.
  52416. *
  52417. * prepareInfoForCustomSeries {Function}: optional
  52418. * @return {Object} {coordSys: {...}, api: {
  52419. * coord: function (data, clamp) {}, // return point in global.
  52420. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  52421. * }}
  52422. */
  52423. var prepareCustoms = {
  52424. cartesian2d: prepareCartesian2d,
  52425. geo: prepareGeo,
  52426. singleAxis: prepareSingleAxis,
  52427. polar: preparePolar,
  52428. calendar: prepareCalendar
  52429. };
  52430. // ------
  52431. // Model
  52432. // ------
  52433. extendSeriesModel({
  52434. type: 'series.custom',
  52435. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  52436. defaultOption: {
  52437. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  52438. zlevel: 0,
  52439. z: 2,
  52440. legendHoverLink: true
  52441. // Cartesian coordinate system
  52442. // xAxisIndex: 0,
  52443. // yAxisIndex: 0,
  52444. // Polar coordinate system
  52445. // polarIndex: 0,
  52446. // Geo coordinate system
  52447. // geoIndex: 0,
  52448. // label: {}
  52449. // itemStyle: {}
  52450. },
  52451. getInitialData: function (option, ecModel) {
  52452. return createListFromArray(this.getSource(), this);
  52453. }
  52454. });
  52455. // -----
  52456. // View
  52457. // -----
  52458. extendChartView({
  52459. type: 'custom',
  52460. /**
  52461. * @private
  52462. * @type {module:echarts/data/List}
  52463. */
  52464. _data: null,
  52465. /**
  52466. * @override
  52467. */
  52468. render: function (customSeries, ecModel, api) {
  52469. var oldData = this._data;
  52470. var data = customSeries.getData();
  52471. var group = this.group;
  52472. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  52473. this.group.removeAll();
  52474. data.diff(oldData)
  52475. .add(function (newIdx) {
  52476. createOrUpdate$1(
  52477. null, newIdx, renderItem(newIdx), customSeries, group, data
  52478. );
  52479. })
  52480. .update(function (newIdx, oldIdx) {
  52481. var el = oldData.getItemGraphicEl(oldIdx);
  52482. createOrUpdate$1(
  52483. el, newIdx, renderItem(newIdx), customSeries, group, data
  52484. );
  52485. })
  52486. .remove(function (oldIdx) {
  52487. var el = oldData.getItemGraphicEl(oldIdx);
  52488. el && group.remove(el);
  52489. })
  52490. .execute();
  52491. this._data = data;
  52492. },
  52493. incrementalPrepareRender: function (customSeries, ecModel, api) {
  52494. this.group.removeAll();
  52495. this._data = null;
  52496. },
  52497. incrementalRender: function (params, customSeries, ecModel, api) {
  52498. var data = customSeries.getData();
  52499. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  52500. function setIncrementalAndHoverLayer(el) {
  52501. if (!el.isGroup) {
  52502. el.incremental = true;
  52503. el.useHoverLayer = true;
  52504. }
  52505. }
  52506. for (var idx = params.start; idx < params.end; idx++) {
  52507. var el = createOrUpdate$1(null, idx, renderItem(idx), customSeries, this.group, data);
  52508. el.traverse(setIncrementalAndHoverLayer);
  52509. }
  52510. },
  52511. /**
  52512. * @override
  52513. */
  52514. dispose: noop
  52515. });
  52516. function createEl(elOption) {
  52517. var graphicType = elOption.type;
  52518. var el;
  52519. if (graphicType === 'path') {
  52520. var shape = elOption.shape;
  52521. el = makePath(
  52522. shape.pathData,
  52523. null,
  52524. {
  52525. x: shape.x || 0,
  52526. y: shape.y || 0,
  52527. width: shape.width || 0,
  52528. height: shape.height || 0
  52529. },
  52530. 'center'
  52531. );
  52532. el.__customPathData = elOption.pathData;
  52533. }
  52534. else if (graphicType === 'image') {
  52535. el = new ZImage({
  52536. });
  52537. el.__customImagePath = elOption.style.image;
  52538. }
  52539. else if (graphicType === 'text') {
  52540. el = new Text({
  52541. });
  52542. el.__customText = elOption.style.text;
  52543. }
  52544. else {
  52545. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  52546. if (__DEV__) {
  52547. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  52548. }
  52549. el = new Clz();
  52550. }
  52551. el.__customGraphicType = graphicType;
  52552. el.name = elOption.name;
  52553. return el;
  52554. }
  52555. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
  52556. var targetProps = {};
  52557. var elOptionStyle = elOption.style || {};
  52558. elOption.shape && (targetProps.shape = clone(elOption.shape));
  52559. elOption.position && (targetProps.position = elOption.position.slice());
  52560. elOption.scale && (targetProps.scale = elOption.scale.slice());
  52561. elOption.origin && (targetProps.origin = elOption.origin.slice());
  52562. elOption.rotation && (targetProps.rotation = elOption.rotation);
  52563. if (el.type === 'image' && elOption.style) {
  52564. var targetStyle = targetProps.style = {};
  52565. each$1(['x', 'y', 'width', 'height'], function (prop) {
  52566. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  52567. });
  52568. }
  52569. if (el.type === 'text' && elOption.style) {
  52570. var targetStyle = targetProps.style = {};
  52571. each$1(['x', 'y'], function (prop) {
  52572. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  52573. });
  52574. // Compatible with previous: both support
  52575. // textFill and fill, textStroke and stroke in 'text' element.
  52576. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  52577. elOptionStyle.textFill = elOptionStyle.fill
  52578. );
  52579. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  52580. elOptionStyle.textStroke = elOptionStyle.stroke
  52581. );
  52582. }
  52583. if (el.type !== 'group') {
  52584. el.useStyle(elOptionStyle);
  52585. // Init animation.
  52586. if (isInit) {
  52587. el.style.opacity = 0;
  52588. var targetOpacity = elOptionStyle.opacity;
  52589. targetOpacity == null && (targetOpacity = 1);
  52590. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  52591. }
  52592. }
  52593. if (isInit) {
  52594. el.attr(targetProps);
  52595. }
  52596. else {
  52597. updateProps(el, targetProps, animatableModel, dataIndex);
  52598. }
  52599. // z2 must not be null/undefined, otherwise sort error may occur.
  52600. el.attr({z2: elOption.z2 || 0, silent: elOption.silent});
  52601. elOption.styleEmphasis !== false && setHoverStyle(el, elOption.styleEmphasis);
  52602. }
  52603. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  52604. if (elOptionStyle[prop] != null && !isInit) {
  52605. targetStyle[prop] = elOptionStyle[prop];
  52606. elOptionStyle[prop] = oldElStyle[prop];
  52607. }
  52608. }
  52609. function makeRenderItem(customSeries, data, ecModel, api) {
  52610. var renderItem = customSeries.get('renderItem');
  52611. var coordSys = customSeries.coordinateSystem;
  52612. var prepareResult = {};
  52613. if (coordSys) {
  52614. if (__DEV__) {
  52615. assert$1(renderItem, 'series.render is required.');
  52616. assert$1(
  52617. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  52618. 'This coordSys does not support custom series.'
  52619. );
  52620. }
  52621. prepareResult = coordSys.prepareCustoms
  52622. ? coordSys.prepareCustoms()
  52623. : prepareCustoms[coordSys.type](coordSys);
  52624. }
  52625. var userAPI = defaults({
  52626. getWidth: api.getWidth,
  52627. getHeight: api.getHeight,
  52628. getZr: api.getZr,
  52629. getDevicePixelRatio: api.getDevicePixelRatio,
  52630. value: value,
  52631. style: style,
  52632. styleEmphasis: styleEmphasis,
  52633. visual: visual,
  52634. barLayout: barLayout,
  52635. currentSeriesIndices: currentSeriesIndices,
  52636. font: font
  52637. }, prepareResult.api || {});
  52638. var userParams = {
  52639. context: {},
  52640. seriesId: customSeries.id,
  52641. seriesName: customSeries.name,
  52642. seriesIndex: customSeries.seriesIndex,
  52643. coordSys: prepareResult.coordSys,
  52644. dataInsideLength: data.count(),
  52645. encode: wrapEncodeDef(customSeries.getData())
  52646. };
  52647. // Do not support call `api` asynchronously without dataIndexInside input.
  52648. var currDataIndexInside;
  52649. var currDirty = true;
  52650. var currItemModel;
  52651. var currLabelNormalModel;
  52652. var currLabelEmphasisModel;
  52653. var currVisualColor;
  52654. return function (dataIndexInside) {
  52655. currDataIndexInside = dataIndexInside;
  52656. currDirty = true;
  52657. return renderItem && renderItem(
  52658. defaults({
  52659. dataIndexInside: dataIndexInside,
  52660. dataIndex: data.getRawIndex(dataIndexInside)
  52661. }, userParams),
  52662. userAPI
  52663. ) || {};
  52664. };
  52665. // Do not update cache until api called.
  52666. function updateCache(dataIndexInside) {
  52667. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52668. if (currDirty) {
  52669. currItemModel = data.getItemModel(dataIndexInside);
  52670. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  52671. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  52672. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  52673. currDirty = false;
  52674. }
  52675. }
  52676. /**
  52677. * @public
  52678. * @param {number|string} dim
  52679. * @param {number} [dataIndexInside=currDataIndexInside]
  52680. * @return {number|string} value
  52681. */
  52682. function value(dim, dataIndexInside) {
  52683. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52684. return data.get(data.getDimension(dim || 0), dataIndexInside);
  52685. }
  52686. /**
  52687. * By default, `visual` is applied to style (to support visualMap).
  52688. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  52689. * it can be implemented as:
  52690. * `api.style({stroke: api.visual('color'), fill: null})`;
  52691. * @public
  52692. * @param {Object} [extra]
  52693. * @param {number} [dataIndexInside=currDataIndexInside]
  52694. */
  52695. function style(extra, dataIndexInside) {
  52696. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52697. updateCache(dataIndexInside);
  52698. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  52699. currVisualColor != null && (itemStyle.fill = currVisualColor);
  52700. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  52701. opacity != null && (itemStyle.opacity = opacity);
  52702. setTextStyle(itemStyle, currLabelNormalModel, null, {
  52703. autoColor: currVisualColor,
  52704. isRectText: true
  52705. });
  52706. itemStyle.text = currLabelNormalModel.getShallow('show')
  52707. ? retrieve2(
  52708. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  52709. getDefaultLabel(data, dataIndexInside)
  52710. )
  52711. : null;
  52712. extra && extend(itemStyle, extra);
  52713. return itemStyle;
  52714. }
  52715. /**
  52716. * @public
  52717. * @param {Object} [extra]
  52718. * @param {number} [dataIndexInside=currDataIndexInside]
  52719. */
  52720. function styleEmphasis(extra, dataIndexInside) {
  52721. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52722. updateCache(dataIndexInside);
  52723. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  52724. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  52725. isRectText: true
  52726. }, true);
  52727. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  52728. ? retrieve3(
  52729. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  52730. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  52731. getDefaultLabel(data, dataIndexInside)
  52732. )
  52733. : null;
  52734. extra && extend(itemStyle, extra);
  52735. return itemStyle;
  52736. }
  52737. /**
  52738. * @public
  52739. * @param {string} visualType
  52740. * @param {number} [dataIndexInside=currDataIndexInside]
  52741. */
  52742. function visual(visualType, dataIndexInside) {
  52743. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  52744. return data.getItemVisual(dataIndexInside, visualType);
  52745. }
  52746. /**
  52747. * @public
  52748. * @param {number} opt.count Positive interger.
  52749. * @param {number} [opt.barWidth]
  52750. * @param {number} [opt.barMaxWidth]
  52751. * @param {number} [opt.barGap]
  52752. * @param {number} [opt.barCategoryGap]
  52753. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  52754. */
  52755. function barLayout(opt) {
  52756. if (coordSys.getBaseAxis) {
  52757. var baseAxis = coordSys.getBaseAxis();
  52758. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  52759. }
  52760. }
  52761. /**
  52762. * @public
  52763. * @return {Array.<number>}
  52764. */
  52765. function currentSeriesIndices() {
  52766. return ecModel.getCurrentSeriesIndices();
  52767. }
  52768. /**
  52769. * @public
  52770. * @param {Object} opt
  52771. * @param {string} [opt.fontStyle]
  52772. * @param {number} [opt.fontWeight]
  52773. * @param {number} [opt.fontSize]
  52774. * @param {string} [opt.fontFamily]
  52775. * @return {string} font string
  52776. */
  52777. function font(opt) {
  52778. return getFont(opt, ecModel);
  52779. }
  52780. }
  52781. function wrapEncodeDef(data) {
  52782. var encodeDef = {};
  52783. each$1(data.dimensions, function (dimName, dataDimIndex) {
  52784. var dimInfo = data.getDimensionInfo(dimName);
  52785. if (!dimInfo.isExtraCoord) {
  52786. var coordDim = dimInfo.coordDim;
  52787. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  52788. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  52789. }
  52790. });
  52791. return encodeDef;
  52792. }
  52793. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  52794. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
  52795. el && data.setItemGraphicEl(dataIndex, el);
  52796. return el;
  52797. }
  52798. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
  52799. var elOptionType = elOption.type;
  52800. if (el
  52801. && elOptionType !== el.__customGraphicType
  52802. && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
  52803. && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
  52804. && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
  52805. ) {
  52806. group.remove(el);
  52807. el = null;
  52808. }
  52809. // `elOption.type` is undefined when `renderItem` returns nothing.
  52810. if (elOptionType == null) {
  52811. return;
  52812. }
  52813. var isInit = !el;
  52814. !el && (el = createEl(elOption));
  52815. updateEl(el, dataIndex, elOption, animatableModel, data, isInit);
  52816. if (elOptionType === 'group') {
  52817. var oldChildren = el.children() || [];
  52818. var newChildren = elOption.children || [];
  52819. if (elOption.diffChildrenByName) {
  52820. // lower performance.
  52821. diffGroupChildren({
  52822. oldChildren: oldChildren,
  52823. newChildren: newChildren,
  52824. dataIndex: dataIndex,
  52825. animatableModel: animatableModel,
  52826. group: el,
  52827. data: data
  52828. });
  52829. }
  52830. else {
  52831. // better performance.
  52832. var index = 0;
  52833. for (; index < newChildren.length; index++) {
  52834. doCreateOrUpdate(
  52835. el.childAt(index),
  52836. dataIndex,
  52837. newChildren[index],
  52838. animatableModel,
  52839. el,
  52840. data
  52841. );
  52842. }
  52843. for (; index < oldChildren.length; index++) {
  52844. oldChildren[index] && el.remove(oldChildren[index]);
  52845. }
  52846. }
  52847. }
  52848. group.add(el);
  52849. return el;
  52850. }
  52851. function diffGroupChildren(context) {
  52852. (new DataDiffer(
  52853. context.oldChildren,
  52854. context.newChildren,
  52855. getKey,
  52856. getKey,
  52857. context
  52858. ))
  52859. .add(processAddUpdate)
  52860. .update(processAddUpdate)
  52861. .remove(processRemove)
  52862. .execute();
  52863. }
  52864. function getKey(item, idx) {
  52865. var name = item && item.name;
  52866. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  52867. }
  52868. function processAddUpdate(newIndex, oldIndex) {
  52869. var context = this.context;
  52870. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  52871. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  52872. doCreateOrUpdate(
  52873. child,
  52874. context.dataIndex,
  52875. childOption,
  52876. context.animatableModel,
  52877. context.group,
  52878. context.data
  52879. );
  52880. }
  52881. function processRemove(oldIndex) {
  52882. var context = this.context;
  52883. var child = context.oldChildren[oldIndex];
  52884. child && context.group.remove(child);
  52885. }
  52886. // -------------
  52887. // Preprocessor
  52888. // -------------
  52889. registerPreprocessor(function (option) {
  52890. var graphicOption = option.graphic;
  52891. // Convert
  52892. // {graphic: [{left: 10, type: 'circle'}, ...]}
  52893. // or
  52894. // {graphic: {left: 10, type: 'circle'}}
  52895. // to
  52896. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  52897. if (isArray(graphicOption)) {
  52898. if (!graphicOption[0] || !graphicOption[0].elements) {
  52899. option.graphic = [{elements: graphicOption}];
  52900. }
  52901. else {
  52902. // Only one graphic instance can be instantiated. (We dont
  52903. // want that too many views are created in echarts._viewMap)
  52904. option.graphic = [option.graphic[0]];
  52905. }
  52906. }
  52907. else if (graphicOption && !graphicOption.elements) {
  52908. option.graphic = [{elements: [graphicOption]}];
  52909. }
  52910. });
  52911. // ------
  52912. // Model
  52913. // ------
  52914. var GraphicModel = extendComponentModel({
  52915. type: 'graphic',
  52916. defaultOption: {
  52917. // Extra properties for each elements:
  52918. //
  52919. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  52920. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  52921. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  52922. // This mechanism is useful when you want to position a group/element
  52923. // against the right side or the center of this container.
  52924. //
  52925. // width/height: (can only be pixel value, default 0)
  52926. // Only be used to specify contianer(group) size, if needed. And
  52927. // can not be percentage value (like '33%'). See the reason in the
  52928. // layout algorithm below.
  52929. //
  52930. // bounding: (enum: 'all' (default) | 'raw')
  52931. // Specify how to calculate boundingRect when locating.
  52932. // 'all': Get uioned and transformed boundingRect
  52933. // from both itself and its descendants.
  52934. // This mode simplies confining a group of elements in the bounding
  52935. // of their ancester container (e.g., using 'right: 0').
  52936. // 'raw': Only use the boundingRect of itself and before transformed.
  52937. // This mode is similar to css behavior, which is useful when you
  52938. // want an element to be able to overflow its container. (Consider
  52939. // a rotated circle needs to be located in a corner.)
  52940. // Note: elements is always behind its ancestors in this elements array.
  52941. elements: [],
  52942. parentId: null
  52943. },
  52944. /**
  52945. * Save el options for the sake of the performance (only update modified graphics).
  52946. * The order is the same as those in option. (ancesters -> descendants)
  52947. *
  52948. * @private
  52949. * @type {Array.<Object>}
  52950. */
  52951. _elOptionsToUpdate: null,
  52952. /**
  52953. * @override
  52954. */
  52955. mergeOption: function (option) {
  52956. // Prevent default merge to elements
  52957. var elements = this.option.elements;
  52958. this.option.elements = null;
  52959. GraphicModel.superApply(this, 'mergeOption', arguments);
  52960. this.option.elements = elements;
  52961. },
  52962. /**
  52963. * @override
  52964. */
  52965. optionUpdated: function (newOption, isInit) {
  52966. var thisOption = this.option;
  52967. var newList = (isInit ? thisOption : newOption).elements;
  52968. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  52969. var flattenedList = [];
  52970. this._flatten(newList, flattenedList);
  52971. var mappingResult = mappingToExists(existList, flattenedList);
  52972. makeIdAndName(mappingResult);
  52973. // Clear elOptionsToUpdate
  52974. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  52975. each$1(mappingResult, function (resultItem, index) {
  52976. var newElOption = resultItem.option;
  52977. if (__DEV__) {
  52978. assert$1(
  52979. isObject$1(newElOption) || resultItem.exist,
  52980. 'Empty graphic option definition'
  52981. );
  52982. }
  52983. if (!newElOption) {
  52984. return;
  52985. }
  52986. elOptionsToUpdate.push(newElOption);
  52987. setKeyInfoToNewElOption(resultItem, newElOption);
  52988. mergeNewElOptionToExist(existList, index, newElOption);
  52989. setLayoutInfoToExist(existList[index], newElOption);
  52990. }, this);
  52991. // Clean
  52992. for (var i = existList.length - 1; i >= 0; i--) {
  52993. if (existList[i] == null) {
  52994. existList.splice(i, 1);
  52995. }
  52996. else {
  52997. // $action should be volatile, otherwise option gotten from
  52998. // `getOption` will contain unexpected $action.
  52999. delete existList[i].$action;
  53000. }
  53001. }
  53002. },
  53003. /**
  53004. * Convert
  53005. * [{
  53006. * type: 'group',
  53007. * id: 'xx',
  53008. * children: [{type: 'circle'}, {type: 'polygon'}]
  53009. * }]
  53010. * to
  53011. * [
  53012. * {type: 'group', id: 'xx'},
  53013. * {type: 'circle', parentId: 'xx'},
  53014. * {type: 'polygon', parentId: 'xx'}
  53015. * ]
  53016. *
  53017. * @private
  53018. * @param {Array.<Object>} optionList option list
  53019. * @param {Array.<Object>} result result of flatten
  53020. * @param {Object} parentOption parent option
  53021. */
  53022. _flatten: function (optionList, result, parentOption) {
  53023. each$1(optionList, function (option) {
  53024. if (!option) {
  53025. return;
  53026. }
  53027. if (parentOption) {
  53028. option.parentOption = parentOption;
  53029. }
  53030. result.push(option);
  53031. var children = option.children;
  53032. if (option.type === 'group' && children) {
  53033. this._flatten(children, result, option);
  53034. }
  53035. // Deleting for JSON output, and for not affecting group creation.
  53036. delete option.children;
  53037. }, this);
  53038. },
  53039. // FIXME
  53040. // Pass to view using payload? setOption has a payload?
  53041. useElOptionsToUpdate: function () {
  53042. var els = this._elOptionsToUpdate;
  53043. // Clear to avoid render duplicately when zooming.
  53044. this._elOptionsToUpdate = null;
  53045. return els;
  53046. }
  53047. });
  53048. // -----
  53049. // View
  53050. // -----
  53051. extendComponentView({
  53052. type: 'graphic',
  53053. /**
  53054. * @override
  53055. */
  53056. init: function (ecModel, api) {
  53057. /**
  53058. * @private
  53059. * @type {module:zrender/core/util.HashMap}
  53060. */
  53061. this._elMap = createHashMap();
  53062. /**
  53063. * @private
  53064. * @type {module:echarts/graphic/GraphicModel}
  53065. */
  53066. this._lastGraphicModel;
  53067. },
  53068. /**
  53069. * @override
  53070. */
  53071. render: function (graphicModel, ecModel, api) {
  53072. // Having leveraged between use cases and algorithm complexity, a very
  53073. // simple layout mechanism is used:
  53074. // The size(width/height) can be determined by itself or its parent (not
  53075. // implemented yet), but can not by its children. (Top-down travel)
  53076. // The location(x/y) can be determined by the bounding rect of itself
  53077. // (can including its descendants or not) and the size of its parent.
  53078. // (Bottom-up travel)
  53079. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  53080. // view will be reused.
  53081. if (graphicModel !== this._lastGraphicModel) {
  53082. this._clear();
  53083. }
  53084. this._lastGraphicModel = graphicModel;
  53085. this._updateElements(graphicModel, api);
  53086. this._relocate(graphicModel, api);
  53087. },
  53088. /**
  53089. * Update graphic elements.
  53090. *
  53091. * @private
  53092. * @param {Object} graphicModel graphic model
  53093. * @param {module:echarts/ExtensionAPI} api extension API
  53094. */
  53095. _updateElements: function (graphicModel, api) {
  53096. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  53097. if (!elOptionsToUpdate) {
  53098. return;
  53099. }
  53100. var elMap = this._elMap;
  53101. var rootGroup = this.group;
  53102. // Top-down tranverse to assign graphic settings to each elements.
  53103. each$1(elOptionsToUpdate, function (elOption) {
  53104. var $action = elOption.$action;
  53105. var id = elOption.id;
  53106. var existEl = elMap.get(id);
  53107. var parentId = elOption.parentId;
  53108. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  53109. if (elOption.type === 'text') {
  53110. var elOptionStyle = elOption.style;
  53111. // In top/bottom mode, textVerticalAlign should not be used, which cause
  53112. // inaccurately locating.
  53113. if (elOption.hv && elOption.hv[1]) {
  53114. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  53115. }
  53116. // Compatible with previous setting: both support fill and textFill,
  53117. // stroke and textStroke.
  53118. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  53119. elOptionStyle.textFill = elOptionStyle.fill
  53120. );
  53121. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  53122. elOptionStyle.textStroke = elOptionStyle.stroke
  53123. );
  53124. }
  53125. // Remove unnecessary props to avoid potential problems.
  53126. var elOptionCleaned = getCleanedElOption(elOption);
  53127. // For simple, do not support parent change, otherwise reorder is needed.
  53128. if (__DEV__) {
  53129. existEl && assert$1(
  53130. targetElParent === existEl.parent,
  53131. 'Changing parent is not supported.'
  53132. );
  53133. }
  53134. if (!$action || $action === 'merge') {
  53135. existEl
  53136. ? existEl.attr(elOptionCleaned)
  53137. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  53138. }
  53139. else if ($action === 'replace') {
  53140. removeEl(existEl, elMap);
  53141. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  53142. }
  53143. else if ($action === 'remove') {
  53144. removeEl(existEl, elMap);
  53145. }
  53146. var el = elMap.get(id);
  53147. if (el) {
  53148. el.__ecGraphicWidth = elOption.width;
  53149. el.__ecGraphicHeight = elOption.height;
  53150. }
  53151. });
  53152. },
  53153. /**
  53154. * Locate graphic elements.
  53155. *
  53156. * @private
  53157. * @param {Object} graphicModel graphic model
  53158. * @param {module:echarts/ExtensionAPI} api extension API
  53159. */
  53160. _relocate: function (graphicModel, api) {
  53161. var elOptions = graphicModel.option.elements;
  53162. var rootGroup = this.group;
  53163. var elMap = this._elMap;
  53164. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  53165. for (var i = elOptions.length - 1; i >= 0; i--) {
  53166. var elOption = elOptions[i];
  53167. var el = elMap.get(elOption.id);
  53168. if (!el) {
  53169. continue;
  53170. }
  53171. var parentEl = el.parent;
  53172. var containerInfo = parentEl === rootGroup
  53173. ? {
  53174. width: api.getWidth(),
  53175. height: api.getHeight()
  53176. }
  53177. : { // Like 'position:absolut' in css, default 0.
  53178. width: parentEl.__ecGraphicWidth || 0,
  53179. height: parentEl.__ecGraphicHeight || 0
  53180. };
  53181. positionElement(
  53182. el, elOption, containerInfo, null,
  53183. {hv: elOption.hv, boundingMode: elOption.bounding}
  53184. );
  53185. }
  53186. },
  53187. /**
  53188. * Clear all elements.
  53189. *
  53190. * @private
  53191. */
  53192. _clear: function () {
  53193. var elMap = this._elMap;
  53194. elMap.each(function (el) {
  53195. removeEl(el, elMap);
  53196. });
  53197. this._elMap = createHashMap();
  53198. },
  53199. /**
  53200. * @override
  53201. */
  53202. dispose: function () {
  53203. this._clear();
  53204. }
  53205. });
  53206. function createEl$1(id, targetElParent, elOption, elMap) {
  53207. var graphicType = elOption.type;
  53208. if (__DEV__) {
  53209. assert$1(graphicType, 'graphic type MUST be set');
  53210. }
  53211. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  53212. if (__DEV__) {
  53213. assert$1(Clz, 'graphic type can not be found');
  53214. }
  53215. var el = new Clz(elOption);
  53216. targetElParent.add(el);
  53217. elMap.set(id, el);
  53218. el.__ecGraphicId = id;
  53219. }
  53220. function removeEl(existEl, elMap) {
  53221. var existElParent = existEl && existEl.parent;
  53222. if (existElParent) {
  53223. existEl.type === 'group' && existEl.traverse(function (el) {
  53224. removeEl(el, elMap);
  53225. });
  53226. elMap.removeKey(existEl.__ecGraphicId);
  53227. existElParent.remove(existEl);
  53228. }
  53229. }
  53230. // Remove unnecessary props to avoid potential problems.
  53231. function getCleanedElOption(elOption) {
  53232. elOption = extend({}, elOption);
  53233. each$1(
  53234. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  53235. function (name) {
  53236. delete elOption[name];
  53237. }
  53238. );
  53239. return elOption;
  53240. }
  53241. function isSetLoc(obj, props) {
  53242. var isSet;
  53243. each$1(props, function (prop) {
  53244. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  53245. });
  53246. return isSet;
  53247. }
  53248. function setKeyInfoToNewElOption(resultItem, newElOption) {
  53249. var existElOption = resultItem.exist;
  53250. // Set id and type after id assigned.
  53251. newElOption.id = resultItem.keyInfo.id;
  53252. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  53253. // Set parent id if not specified
  53254. if (newElOption.parentId == null) {
  53255. var newElParentOption = newElOption.parentOption;
  53256. if (newElParentOption) {
  53257. newElOption.parentId = newElParentOption.id;
  53258. }
  53259. else if (existElOption) {
  53260. newElOption.parentId = existElOption.parentId;
  53261. }
  53262. }
  53263. // Clear
  53264. newElOption.parentOption = null;
  53265. }
  53266. function mergeNewElOptionToExist(existList, index, newElOption) {
  53267. // Update existing options, for `getOption` feature.
  53268. var newElOptCopy = extend({}, newElOption);
  53269. var existElOption = existList[index];
  53270. var $action = newElOption.$action || 'merge';
  53271. if ($action === 'merge') {
  53272. if (existElOption) {
  53273. if (__DEV__) {
  53274. var newType = newElOption.type;
  53275. assert$1(
  53276. !newType || existElOption.type === newType,
  53277. 'Please set $action: "replace" to change `type`'
  53278. );
  53279. }
  53280. // We can ensure that newElOptCopy and existElOption are not
  53281. // the same object, so `merge` will not change newElOptCopy.
  53282. merge(existElOption, newElOptCopy, true);
  53283. // Rigid body, use ignoreSize.
  53284. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  53285. // Will be used in render.
  53286. copyLayoutParams(newElOption, existElOption);
  53287. }
  53288. else {
  53289. existList[index] = newElOptCopy;
  53290. }
  53291. }
  53292. else if ($action === 'replace') {
  53293. existList[index] = newElOptCopy;
  53294. }
  53295. else if ($action === 'remove') {
  53296. // null will be cleaned later.
  53297. existElOption && (existList[index] = null);
  53298. }
  53299. }
  53300. function setLayoutInfoToExist(existItem, newElOption) {
  53301. if (!existItem) {
  53302. return;
  53303. }
  53304. existItem.hv = newElOption.hv = [
  53305. // Rigid body, dont care `width`.
  53306. isSetLoc(newElOption, ['left', 'right']),
  53307. // Rigid body, dont care `height`.
  53308. isSetLoc(newElOption, ['top', 'bottom'])
  53309. ];
  53310. // Give default group size. Otherwise layout error may occur.
  53311. if (existItem.type === 'group') {
  53312. existItem.width == null && (existItem.width = newElOption.width = 0);
  53313. existItem.height == null && (existItem.height = newElOption.height = 0);
  53314. }
  53315. }
  53316. var LegendModel = extendComponentModel({
  53317. type: 'legend.plain',
  53318. dependencies: ['series'],
  53319. layoutMode: {
  53320. type: 'box',
  53321. // legend.width/height are maxWidth/maxHeight actually,
  53322. // whereas realy width/height is calculated by its content.
  53323. // (Setting {left: 10, right: 10} does not make sense).
  53324. // So consider the case:
  53325. // `setOption({legend: {left: 10});`
  53326. // then `setOption({legend: {right: 10});`
  53327. // The previous `left` should be cleared by setting `ignoreSize`.
  53328. ignoreSize: true
  53329. },
  53330. init: function (option, parentModel, ecModel) {
  53331. this.mergeDefaultAndTheme(option, ecModel);
  53332. option.selected = option.selected || {};
  53333. },
  53334. mergeOption: function (option) {
  53335. LegendModel.superCall(this, 'mergeOption', option);
  53336. },
  53337. optionUpdated: function () {
  53338. this._updateData(this.ecModel);
  53339. var legendData = this._data;
  53340. // If selectedMode is single, try to select one
  53341. if (legendData[0] && this.get('selectedMode') === 'single') {
  53342. var hasSelected = false;
  53343. // If has any selected in option.selected
  53344. for (var i = 0; i < legendData.length; i++) {
  53345. var name = legendData[i].get('name');
  53346. if (this.isSelected(name)) {
  53347. // Force to unselect others
  53348. this.select(name);
  53349. hasSelected = true;
  53350. break;
  53351. }
  53352. }
  53353. // Try select the first if selectedMode is single
  53354. !hasSelected && this.select(legendData[0].get('name'));
  53355. }
  53356. },
  53357. _updateData: function (ecModel) {
  53358. var potentialData = [];
  53359. var availableNames = [];
  53360. ecModel.eachRawSeries(function (seriesModel) {
  53361. var seriesName = seriesModel.name;
  53362. availableNames.push(seriesName);
  53363. var isPotential;
  53364. if (seriesModel.legendDataProvider) {
  53365. var data = seriesModel.legendDataProvider();
  53366. var names = data.mapArray(data.getName);
  53367. if (!ecModel.isSeriesFiltered(seriesModel)) {
  53368. availableNames = availableNames.concat(names);
  53369. }
  53370. if (names.length) {
  53371. potentialData = potentialData.concat(names);
  53372. }
  53373. else {
  53374. isPotential = true;
  53375. }
  53376. }
  53377. else {
  53378. isPotential = true;
  53379. }
  53380. if (isPotential && isNameSpecified(seriesModel)) {
  53381. potentialData.push(seriesModel.name);
  53382. }
  53383. });
  53384. /**
  53385. * @type {Array.<string>}
  53386. * @private
  53387. */
  53388. this._availableNames = availableNames;
  53389. // If legend.data not specified in option, use availableNames as data,
  53390. // which is convinient for user preparing option.
  53391. var rawData = this.get('data') || potentialData;
  53392. var legendData = map(rawData, function (dataItem) {
  53393. // Can be string or number
  53394. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  53395. dataItem = {
  53396. name: dataItem
  53397. };
  53398. }
  53399. return new Model(dataItem, this, this.ecModel);
  53400. }, this);
  53401. /**
  53402. * @type {Array.<module:echarts/model/Model>}
  53403. * @private
  53404. */
  53405. this._data = legendData;
  53406. },
  53407. /**
  53408. * @return {Array.<module:echarts/model/Model>}
  53409. */
  53410. getData: function () {
  53411. return this._data;
  53412. },
  53413. /**
  53414. * @param {string} name
  53415. */
  53416. select: function (name) {
  53417. var selected = this.option.selected;
  53418. var selectedMode = this.get('selectedMode');
  53419. if (selectedMode === 'single') {
  53420. var data = this._data;
  53421. each$1(data, function (dataItem) {
  53422. selected[dataItem.get('name')] = false;
  53423. });
  53424. }
  53425. selected[name] = true;
  53426. },
  53427. /**
  53428. * @param {string} name
  53429. */
  53430. unSelect: function (name) {
  53431. if (this.get('selectedMode') !== 'single') {
  53432. this.option.selected[name] = false;
  53433. }
  53434. },
  53435. /**
  53436. * @param {string} name
  53437. */
  53438. toggleSelected: function (name) {
  53439. var selected = this.option.selected;
  53440. // Default is true
  53441. if (!selected.hasOwnProperty(name)) {
  53442. selected[name] = true;
  53443. }
  53444. this[selected[name] ? 'unSelect' : 'select'](name);
  53445. },
  53446. /**
  53447. * @param {string} name
  53448. */
  53449. isSelected: function (name) {
  53450. var selected = this.option.selected;
  53451. return !(selected.hasOwnProperty(name) && !selected[name])
  53452. && indexOf(this._availableNames, name) >= 0;
  53453. },
  53454. defaultOption: {
  53455. // 一级层叠
  53456. zlevel: 0,
  53457. // 二级层叠
  53458. z: 4,
  53459. show: true,
  53460. // 布局方式,默认为水平布局,可选为:
  53461. // 'horizontal' | 'vertical'
  53462. orient: 'horizontal',
  53463. left: 'center',
  53464. // right: 'center',
  53465. top: 0,
  53466. // bottom: null,
  53467. // 水平对齐
  53468. // 'auto' | 'left' | 'right'
  53469. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  53470. align: 'auto',
  53471. backgroundColor: 'rgba(0,0,0,0)',
  53472. // 图例边框颜色
  53473. borderColor: '#ccc',
  53474. borderRadius: 0,
  53475. // 图例边框线宽,单位px,默认为0(无边框)
  53476. borderWidth: 0,
  53477. // 图例内边距,单位px,默认各方向内边距为5,
  53478. // 接受数组分别设定上右下左边距,同css
  53479. padding: 5,
  53480. // 各个item之间的间隔,单位px,默认为10,
  53481. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  53482. itemGap: 10,
  53483. // 图例图形宽度
  53484. itemWidth: 25,
  53485. // 图例图形高度
  53486. itemHeight: 14,
  53487. // 图例关闭时候的颜色
  53488. inactiveColor: '#ccc',
  53489. textStyle: {
  53490. // 图例文字颜色
  53491. color: '#333'
  53492. },
  53493. // formatter: '',
  53494. // 选择模式,默认开启图例开关
  53495. selectedMode: true,
  53496. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  53497. // selected: null,
  53498. // 图例内容(详见legend.data,数组中每一项代表一个item
  53499. // data: [],
  53500. // Tooltip 相关配置
  53501. tooltip: {
  53502. show: false
  53503. }
  53504. }
  53505. });
  53506. function legendSelectActionHandler(methodName, payload, ecModel) {
  53507. var selectedMap = {};
  53508. var isToggleSelect = methodName === 'toggleSelected';
  53509. var isSelected;
  53510. // Update all legend components
  53511. ecModel.eachComponent('legend', function (legendModel) {
  53512. if (isToggleSelect && isSelected != null) {
  53513. // Force other legend has same selected status
  53514. // Or the first is toggled to true and other are toggled to false
  53515. // In the case one legend has some item unSelected in option. And if other legend
  53516. // doesn't has the item, they will assume it is selected.
  53517. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  53518. }
  53519. else {
  53520. legendModel[methodName](payload.name);
  53521. isSelected = legendModel.isSelected(payload.name);
  53522. }
  53523. var legendData = legendModel.getData();
  53524. each$1(legendData, function (model) {
  53525. var name = model.get('name');
  53526. // Wrap element
  53527. if (name === '\n' || name === '') {
  53528. return;
  53529. }
  53530. var isItemSelected = legendModel.isSelected(name);
  53531. if (selectedMap.hasOwnProperty(name)) {
  53532. // Unselected if any legend is unselected
  53533. selectedMap[name] = selectedMap[name] && isItemSelected;
  53534. }
  53535. else {
  53536. selectedMap[name] = isItemSelected;
  53537. }
  53538. });
  53539. });
  53540. // Return the event explicitly
  53541. return {
  53542. name: payload.name,
  53543. selected: selectedMap
  53544. };
  53545. }
  53546. /**
  53547. * @event legendToggleSelect
  53548. * @type {Object}
  53549. * @property {string} type 'legendToggleSelect'
  53550. * @property {string} [from]
  53551. * @property {string} name Series name or data item name
  53552. */
  53553. registerAction(
  53554. 'legendToggleSelect', 'legendselectchanged',
  53555. curry(legendSelectActionHandler, 'toggleSelected')
  53556. );
  53557. /**
  53558. * @event legendSelect
  53559. * @type {Object}
  53560. * @property {string} type 'legendSelect'
  53561. * @property {string} name Series name or data item name
  53562. */
  53563. registerAction(
  53564. 'legendSelect', 'legendselected',
  53565. curry(legendSelectActionHandler, 'select')
  53566. );
  53567. /**
  53568. * @event legendUnSelect
  53569. * @type {Object}
  53570. * @property {string} type 'legendUnSelect'
  53571. * @property {string} name Series name or data item name
  53572. */
  53573. registerAction(
  53574. 'legendUnSelect', 'legendunselected',
  53575. curry(legendSelectActionHandler, 'unSelect')
  53576. );
  53577. /**
  53578. * Layout list like component.
  53579. * It will box layout each items in group of component and then position the whole group in the viewport
  53580. * @param {module:zrender/group/Group} group
  53581. * @param {module:echarts/model/Component} componentModel
  53582. * @param {module:echarts/ExtensionAPI}
  53583. */
  53584. function layout$3(group, componentModel, api) {
  53585. var boxLayoutParams = componentModel.getBoxLayoutParams();
  53586. var padding = componentModel.get('padding');
  53587. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  53588. var rect = getLayoutRect(
  53589. boxLayoutParams,
  53590. viewportSize,
  53591. padding
  53592. );
  53593. box(
  53594. componentModel.get('orient'),
  53595. group,
  53596. componentModel.get('itemGap'),
  53597. rect.width,
  53598. rect.height
  53599. );
  53600. positionElement(
  53601. group,
  53602. boxLayoutParams,
  53603. viewportSize,
  53604. padding
  53605. );
  53606. }
  53607. function makeBackground(rect, componentModel) {
  53608. var padding = normalizeCssArray$1(
  53609. componentModel.get('padding')
  53610. );
  53611. var style = componentModel.getItemStyle(['color', 'opacity']);
  53612. style.fill = componentModel.get('backgroundColor');
  53613. var rect = new Rect({
  53614. shape: {
  53615. x: rect.x - padding[3],
  53616. y: rect.y - padding[0],
  53617. width: rect.width + padding[1] + padding[3],
  53618. height: rect.height + padding[0] + padding[2],
  53619. r: componentModel.get('borderRadius')
  53620. },
  53621. style: style,
  53622. silent: true,
  53623. z2: -1
  53624. });
  53625. // FIXME
  53626. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  53627. // and background rect when setting like `left: 0`, `top: 0`.
  53628. // graphic.subPixelOptimizeRect(rect);
  53629. return rect;
  53630. }
  53631. var curry$4 = curry;
  53632. var each$17 = each$1;
  53633. var Group$3 = Group;
  53634. var LegendView = extendComponentView({
  53635. type: 'legend.plain',
  53636. newlineDisabled: false,
  53637. /**
  53638. * @override
  53639. */
  53640. init: function () {
  53641. /**
  53642. * @private
  53643. * @type {module:zrender/container/Group}
  53644. */
  53645. this.group.add(this._contentGroup = new Group$3());
  53646. /**
  53647. * @private
  53648. * @type {module:zrender/Element}
  53649. */
  53650. this._backgroundEl;
  53651. },
  53652. /**
  53653. * @protected
  53654. */
  53655. getContentGroup: function () {
  53656. return this._contentGroup;
  53657. },
  53658. /**
  53659. * @override
  53660. */
  53661. render: function (legendModel, ecModel, api) {
  53662. this.resetInner();
  53663. if (!legendModel.get('show', true)) {
  53664. return;
  53665. }
  53666. var itemAlign = legendModel.get('align');
  53667. if (!itemAlign || itemAlign === 'auto') {
  53668. itemAlign = (
  53669. legendModel.get('left') === 'right'
  53670. && legendModel.get('orient') === 'vertical'
  53671. ) ? 'right' : 'left';
  53672. }
  53673. this.renderInner(itemAlign, legendModel, ecModel, api);
  53674. // Perform layout.
  53675. var positionInfo = legendModel.getBoxLayoutParams();
  53676. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  53677. var padding = legendModel.get('padding');
  53678. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  53679. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  53680. // Place mainGroup, based on the calculated `mainRect`.
  53681. var layoutRect = getLayoutRect(
  53682. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  53683. viewportSize,
  53684. padding
  53685. );
  53686. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  53687. // Render background after group is layout.
  53688. this.group.add(
  53689. this._backgroundEl = makeBackground(mainRect, legendModel)
  53690. );
  53691. },
  53692. /**
  53693. * @protected
  53694. */
  53695. resetInner: function () {
  53696. this.getContentGroup().removeAll();
  53697. this._backgroundEl && this.group.remove(this._backgroundEl);
  53698. },
  53699. /**
  53700. * @protected
  53701. */
  53702. renderInner: function (itemAlign, legendModel, ecModel, api) {
  53703. var contentGroup = this.getContentGroup();
  53704. var legendDrawnMap = createHashMap();
  53705. var selectMode = legendModel.get('selectedMode');
  53706. each$17(legendModel.getData(), function (itemModel, dataIndex) {
  53707. var name = itemModel.get('name');
  53708. // Use empty string or \n as a newline string
  53709. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  53710. contentGroup.add(new Group$3({
  53711. newline: true
  53712. }));
  53713. return;
  53714. }
  53715. var seriesModel = ecModel.getSeriesByName(name)[0];
  53716. if (legendDrawnMap.get(name)) {
  53717. // Have been drawed
  53718. return;
  53719. }
  53720. // Series legend
  53721. if (seriesModel) {
  53722. var data = seriesModel.getData();
  53723. var color = data.getVisual('color');
  53724. // If color is a callback function
  53725. if (typeof color === 'function') {
  53726. // Use the first data
  53727. color = color(seriesModel.getDataParams(0));
  53728. }
  53729. // Using rect symbol defaultly
  53730. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  53731. var symbolType = data.getVisual('symbol');
  53732. var itemGroup = this._createItem(
  53733. name, dataIndex, itemModel, legendModel,
  53734. legendSymbolType, symbolType,
  53735. itemAlign, color,
  53736. selectMode
  53737. );
  53738. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  53739. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, null, api))
  53740. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, null, api));
  53741. legendDrawnMap.set(name, true);
  53742. }
  53743. else {
  53744. // Data legend of pie, funnel
  53745. ecModel.eachRawSeries(function (seriesModel) {
  53746. // In case multiple series has same data name
  53747. if (legendDrawnMap.get(name)) {
  53748. return;
  53749. }
  53750. if (seriesModel.legendDataProvider) {
  53751. var data = seriesModel.legendDataProvider();
  53752. var idx = data.indexOfName(name);
  53753. if (idx < 0) {
  53754. return;
  53755. }
  53756. var color = data.getItemVisual(idx, 'color');
  53757. var legendSymbolType = 'roundRect';
  53758. var itemGroup = this._createItem(
  53759. name, dataIndex, itemModel, legendModel,
  53760. legendSymbolType, null,
  53761. itemAlign, color,
  53762. selectMode
  53763. );
  53764. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  53765. // FIXME Should not specify the series name
  53766. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, name, api))
  53767. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, name, api));
  53768. legendDrawnMap.set(name, true);
  53769. }
  53770. }, this);
  53771. }
  53772. if (__DEV__) {
  53773. if (!legendDrawnMap.get(name)) {
  53774. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  53775. }
  53776. }
  53777. }, this);
  53778. },
  53779. _createItem: function (
  53780. name, dataIndex, itemModel, legendModel,
  53781. legendSymbolType, symbolType,
  53782. itemAlign, color, selectMode
  53783. ) {
  53784. var itemWidth = legendModel.get('itemWidth');
  53785. var itemHeight = legendModel.get('itemHeight');
  53786. var inactiveColor = legendModel.get('inactiveColor');
  53787. var isSelected = legendModel.isSelected(name);
  53788. var itemGroup = new Group$3();
  53789. var textStyleModel = itemModel.getModel('textStyle');
  53790. var itemIcon = itemModel.get('icon');
  53791. var tooltipModel = itemModel.getModel('tooltip');
  53792. var legendGlobalTooltipModel = tooltipModel.parentModel;
  53793. // Use user given icon first
  53794. legendSymbolType = itemIcon || legendSymbolType;
  53795. itemGroup.add(createSymbol(
  53796. legendSymbolType,
  53797. 0,
  53798. 0,
  53799. itemWidth,
  53800. itemHeight,
  53801. isSelected ? color : inactiveColor,
  53802. true
  53803. ));
  53804. // Compose symbols
  53805. // PENDING
  53806. if (!itemIcon && symbolType
  53807. // At least show one symbol, can't be all none
  53808. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  53809. ) {
  53810. var size = itemHeight * 0.8;
  53811. if (symbolType === 'none') {
  53812. symbolType = 'circle';
  53813. }
  53814. // Put symbol in the center
  53815. itemGroup.add(createSymbol(
  53816. symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
  53817. isSelected ? color : inactiveColor
  53818. ));
  53819. }
  53820. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  53821. var textAlign = itemAlign;
  53822. var formatter = legendModel.get('formatter');
  53823. var content = name;
  53824. if (typeof formatter === 'string' && formatter) {
  53825. content = formatter.replace('{name}', name != null ? name : '');
  53826. }
  53827. else if (typeof formatter === 'function') {
  53828. content = formatter(name);
  53829. }
  53830. itemGroup.add(new Text({
  53831. style: setTextStyle({}, textStyleModel, {
  53832. text: content,
  53833. x: textX,
  53834. y: itemHeight / 2,
  53835. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  53836. textAlign: textAlign,
  53837. textVerticalAlign: 'middle'
  53838. })
  53839. }));
  53840. // Add a invisible rect to increase the area of mouse hover
  53841. var hitRect = new Rect({
  53842. shape: itemGroup.getBoundingRect(),
  53843. invisible: true,
  53844. tooltip: tooltipModel.get('show') ? extend({
  53845. content: name,
  53846. // Defaul formatter
  53847. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  53848. return name;
  53849. },
  53850. formatterParams: {
  53851. componentType: 'legend',
  53852. legendIndex: legendModel.componentIndex,
  53853. name: name,
  53854. $vars: ['name']
  53855. }
  53856. }, tooltipModel.option) : null
  53857. });
  53858. itemGroup.add(hitRect);
  53859. itemGroup.eachChild(function (child) {
  53860. child.silent = true;
  53861. });
  53862. hitRect.silent = !selectMode;
  53863. this.getContentGroup().add(itemGroup);
  53864. setHoverStyle(itemGroup);
  53865. itemGroup.__legendDataIndex = dataIndex;
  53866. return itemGroup;
  53867. },
  53868. /**
  53869. * @protected
  53870. */
  53871. layoutInner: function (legendModel, itemAlign, maxSize) {
  53872. var contentGroup = this.getContentGroup();
  53873. // Place items in contentGroup.
  53874. box(
  53875. legendModel.get('orient'),
  53876. contentGroup,
  53877. legendModel.get('itemGap'),
  53878. maxSize.width,
  53879. maxSize.height
  53880. );
  53881. var contentRect = contentGroup.getBoundingRect();
  53882. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  53883. return this.group.getBoundingRect();
  53884. }
  53885. });
  53886. function dispatchSelectAction(name, api) {
  53887. api.dispatchAction({
  53888. type: 'legendToggleSelect',
  53889. name: name
  53890. });
  53891. }
  53892. function dispatchHighlightAction(seriesModel, dataName, api) {
  53893. // If element hover will move to a hoverLayer.
  53894. var el = api.getZr().storage.getDisplayList()[0];
  53895. if (!(el && el.useHoverLayer)) {
  53896. seriesModel.get('legendHoverLink') && api.dispatchAction({
  53897. type: 'highlight',
  53898. seriesName: seriesModel.name,
  53899. name: dataName
  53900. });
  53901. }
  53902. }
  53903. function dispatchDownplayAction(seriesModel, dataName, api) {
  53904. // If element hover will move to a hoverLayer.
  53905. var el = api.getZr().storage.getDisplayList()[0];
  53906. if (!(el && el.useHoverLayer)) {
  53907. seriesModel.get('legendHoverLink') && api.dispatchAction({
  53908. type: 'downplay',
  53909. seriesName: seriesModel.name,
  53910. name: dataName
  53911. });
  53912. }
  53913. }
  53914. var legendFilter = function (ecModel) {
  53915. var legendModels = ecModel.findComponents({
  53916. mainType: 'legend'
  53917. });
  53918. if (legendModels && legendModels.length) {
  53919. ecModel.filterSeries(function (series) {
  53920. // If in any legend component the status is not selected.
  53921. // Because in legend series is assumed selected when it is not in the legend data.
  53922. for (var i = 0; i < legendModels.length; i++) {
  53923. if (!legendModels[i].isSelected(series.name)) {
  53924. return false;
  53925. }
  53926. }
  53927. return true;
  53928. });
  53929. }
  53930. };
  53931. // Do not contain scrollable legend, for sake of file size.
  53932. // Series Filter
  53933. registerProcessor(legendFilter);
  53934. ComponentModel.registerSubTypeDefaulter('legend', function () {
  53935. // Default 'plain' when no type specified.
  53936. return 'plain';
  53937. });
  53938. var ScrollableLegendModel = LegendModel.extend({
  53939. type: 'legend.scroll',
  53940. /**
  53941. * @param {number} scrollDataIndex
  53942. */
  53943. setScrollDataIndex: function (scrollDataIndex) {
  53944. this.option.scrollDataIndex = scrollDataIndex;
  53945. },
  53946. defaultOption: {
  53947. scrollDataIndex: 0,
  53948. pageButtonItemGap: 5,
  53949. pageButtonGap: null,
  53950. pageButtonPosition: 'end', // 'start' or 'end'
  53951. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  53952. pageIcons: {
  53953. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  53954. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  53955. },
  53956. pageIconColor: '#2f4554',
  53957. pageIconInactiveColor: '#aaa',
  53958. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  53959. pageTextStyle: {
  53960. color: '#333'
  53961. },
  53962. animationDurationUpdate: 800
  53963. },
  53964. /**
  53965. * @override
  53966. */
  53967. init: function (option, parentModel, ecModel, extraOpt) {
  53968. var inputPositionParams = getLayoutParams(option);
  53969. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  53970. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  53971. },
  53972. /**
  53973. * @override
  53974. */
  53975. mergeOption: function (option, extraOpt) {
  53976. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  53977. mergeAndNormalizeLayoutParams(this, this.option, option);
  53978. },
  53979. getOrient: function () {
  53980. return this.get('orient') === 'vertical'
  53981. ? {index: 1, name: 'vertical'}
  53982. : {index: 0, name: 'horizontal'};
  53983. }
  53984. });
  53985. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  53986. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  53987. var orient = legendModel.getOrient();
  53988. var ignoreSize = [1, 1];
  53989. ignoreSize[orient.index] = 0;
  53990. mergeLayoutParam(target, raw, {
  53991. type: 'box', ignoreSize: ignoreSize
  53992. });
  53993. }
  53994. /**
  53995. * Separate legend and scrollable legend to reduce package size.
  53996. */
  53997. var Group$4 = Group;
  53998. var WH$1 = ['width', 'height'];
  53999. var XY$1 = ['x', 'y'];
  54000. var ScrollableLegendView = LegendView.extend({
  54001. type: 'legend.scroll',
  54002. newlineDisabled: true,
  54003. init: function () {
  54004. ScrollableLegendView.superCall(this, 'init');
  54005. /**
  54006. * @private
  54007. * @type {number} For `scroll`.
  54008. */
  54009. this._currentIndex = 0;
  54010. /**
  54011. * @private
  54012. * @type {module:zrender/container/Group}
  54013. */
  54014. this.group.add(this._containerGroup = new Group$4());
  54015. this._containerGroup.add(this.getContentGroup());
  54016. /**
  54017. * @private
  54018. * @type {module:zrender/container/Group}
  54019. */
  54020. this.group.add(this._controllerGroup = new Group$4());
  54021. /**
  54022. *
  54023. * @private
  54024. */
  54025. this._showController;
  54026. },
  54027. /**
  54028. * @override
  54029. */
  54030. resetInner: function () {
  54031. ScrollableLegendView.superCall(this, 'resetInner');
  54032. this._controllerGroup.removeAll();
  54033. this._containerGroup.removeClipPath();
  54034. this._containerGroup.__rectSize = null;
  54035. },
  54036. /**
  54037. * @override
  54038. */
  54039. renderInner: function (itemAlign, legendModel, ecModel, api) {
  54040. var me = this;
  54041. // Render content items.
  54042. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  54043. var controllerGroup = this._controllerGroup;
  54044. var pageIconSize = legendModel.get('pageIconSize', true);
  54045. if (!isArray(pageIconSize)) {
  54046. pageIconSize = [pageIconSize, pageIconSize];
  54047. }
  54048. createPageButton('pagePrev', 0);
  54049. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  54050. controllerGroup.add(new Text({
  54051. name: 'pageText',
  54052. style: {
  54053. textFill: pageTextStyleModel.getTextColor(),
  54054. font: pageTextStyleModel.getFont(),
  54055. textVerticalAlign: 'middle',
  54056. textAlign: 'center'
  54057. },
  54058. silent: true
  54059. }));
  54060. createPageButton('pageNext', 1);
  54061. function createPageButton(name, iconIdx) {
  54062. var pageDataIndexName = name + 'DataIndex';
  54063. var icon = createIcon(
  54064. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  54065. {
  54066. // Buttons will be created in each render, so we do not need
  54067. // to worry about avoiding using legendModel kept in scope.
  54068. onclick: bind(
  54069. me._pageGo, me, pageDataIndexName, legendModel, api
  54070. )
  54071. },
  54072. {
  54073. x: -pageIconSize[0] / 2,
  54074. y: -pageIconSize[1] / 2,
  54075. width: pageIconSize[0],
  54076. height: pageIconSize[1]
  54077. }
  54078. );
  54079. icon.name = name;
  54080. controllerGroup.add(icon);
  54081. }
  54082. },
  54083. /**
  54084. * @override
  54085. */
  54086. layoutInner: function (legendModel, itemAlign, maxSize) {
  54087. var contentGroup = this.getContentGroup();
  54088. var containerGroup = this._containerGroup;
  54089. var controllerGroup = this._controllerGroup;
  54090. var orientIdx = legendModel.getOrient().index;
  54091. var wh = WH$1[orientIdx];
  54092. var hw = WH$1[1 - orientIdx];
  54093. var yx = XY$1[1 - orientIdx];
  54094. // Place items in contentGroup.
  54095. box(
  54096. legendModel.get('orient'),
  54097. contentGroup,
  54098. legendModel.get('itemGap'),
  54099. !orientIdx ? null : maxSize.width,
  54100. orientIdx ? null : maxSize.height
  54101. );
  54102. box(
  54103. // Buttons in controller are layout always horizontally.
  54104. 'horizontal',
  54105. controllerGroup,
  54106. legendModel.get('pageButtonItemGap', true)
  54107. );
  54108. var contentRect = contentGroup.getBoundingRect();
  54109. var controllerRect = controllerGroup.getBoundingRect();
  54110. var showController = this._showController = contentRect[wh] > maxSize[wh];
  54111. var contentPos = [-contentRect.x, -contentRect.y];
  54112. // Remain contentPos when scroll animation perfroming.
  54113. contentPos[orientIdx] = contentGroup.position[orientIdx];
  54114. // Layout container group based on 0.
  54115. var containerPos = [0, 0];
  54116. var controllerPos = [-controllerRect.x, -controllerRect.y];
  54117. var pageButtonGap = retrieve2(
  54118. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  54119. );
  54120. // Place containerGroup and controllerGroup and contentGroup.
  54121. if (showController) {
  54122. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  54123. // controller is on the right / bottom.
  54124. if (pageButtonPosition === 'end') {
  54125. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  54126. }
  54127. // controller is on the left / top.
  54128. else {
  54129. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  54130. }
  54131. }
  54132. // Always align controller to content as 'middle'.
  54133. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  54134. contentGroup.attr('position', contentPos);
  54135. containerGroup.attr('position', containerPos);
  54136. controllerGroup.attr('position', controllerPos);
  54137. // Calculate `mainRect` and set `clipPath`.
  54138. // mainRect should not be calculated by `this.group.getBoundingRect()`
  54139. // for sake of the overflow.
  54140. var mainRect = this.group.getBoundingRect();
  54141. var mainRect = {x: 0, y: 0};
  54142. // Consider content may be overflow (should be clipped).
  54143. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  54144. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  54145. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  54146. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  54147. containerGroup.__rectSize = maxSize[wh];
  54148. if (showController) {
  54149. var clipShape = {x: 0, y: 0};
  54150. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  54151. clipShape[hw] = mainRect[hw];
  54152. containerGroup.setClipPath(new Rect({shape: clipShape}));
  54153. // Consider content may be larger than container, container rect
  54154. // can not be obtained from `containerGroup.getBoundingRect()`.
  54155. containerGroup.__rectSize = clipShape[wh];
  54156. }
  54157. else {
  54158. // Do not remove or ignore controller. Keep them set as place holders.
  54159. controllerGroup.eachChild(function (child) {
  54160. child.attr({invisible: true, silent: true});
  54161. });
  54162. }
  54163. // Content translate animation.
  54164. var pageInfo = this._getPageInfo(legendModel);
  54165. pageInfo.pageIndex != null && updateProps(
  54166. contentGroup,
  54167. {position: pageInfo.contentPosition},
  54168. // When switch from "show controller" to "not show controller", view should be
  54169. // updated immediately without animation, otherwise causes weird efffect.
  54170. showController ? legendModel : false
  54171. );
  54172. this._updatePageInfoView(legendModel, pageInfo);
  54173. return mainRect;
  54174. },
  54175. _pageGo: function (to, legendModel, api) {
  54176. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  54177. scrollDataIndex != null && api.dispatchAction({
  54178. type: 'legendScroll',
  54179. scrollDataIndex: scrollDataIndex,
  54180. legendId: legendModel.id
  54181. });
  54182. },
  54183. _updatePageInfoView: function (legendModel, pageInfo) {
  54184. var controllerGroup = this._controllerGroup;
  54185. each$1(['pagePrev', 'pageNext'], function (name) {
  54186. var canJump = pageInfo[name + 'DataIndex'] != null;
  54187. var icon = controllerGroup.childOfName(name);
  54188. if (icon) {
  54189. icon.setStyle(
  54190. 'fill',
  54191. canJump
  54192. ? legendModel.get('pageIconColor', true)
  54193. : legendModel.get('pageIconInactiveColor', true)
  54194. );
  54195. icon.cursor = canJump ? 'pointer' : 'default';
  54196. }
  54197. });
  54198. var pageText = controllerGroup.childOfName('pageText');
  54199. var pageFormatter = legendModel.get('pageFormatter');
  54200. var pageIndex = pageInfo.pageIndex;
  54201. var current = pageIndex != null ? pageIndex + 1 : 0;
  54202. var total = pageInfo.pageCount;
  54203. pageText && pageFormatter && pageText.setStyle(
  54204. 'text',
  54205. isString(pageFormatter)
  54206. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  54207. : pageFormatter({current: current, total: total})
  54208. );
  54209. },
  54210. /**
  54211. * @param {module:echarts/model/Model} legendModel
  54212. * @return {Object} {
  54213. * contentPosition: Array.<number>, null when data item not found.
  54214. * pageIndex: number, null when data item not found.
  54215. * pageCount: number, always be a number, can be 0.
  54216. * pagePrevDataIndex: number, null when no next page.
  54217. * pageNextDataIndex: number, null when no previous page.
  54218. * }
  54219. */
  54220. _getPageInfo: function (legendModel) {
  54221. // Align left or top by the current dataIndex.
  54222. var currDataIndex = legendModel.get('scrollDataIndex', true);
  54223. var contentGroup = this.getContentGroup();
  54224. var contentRect = contentGroup.getBoundingRect();
  54225. var containerRectSize = this._containerGroup.__rectSize;
  54226. var orientIdx = legendModel.getOrient().index;
  54227. var wh = WH$1[orientIdx];
  54228. var hw = WH$1[1 - orientIdx];
  54229. var xy = XY$1[orientIdx];
  54230. var contentPos = contentGroup.position.slice();
  54231. var pageIndex;
  54232. var pagePrevDataIndex;
  54233. var pageNextDataIndex;
  54234. var targetItemGroup;
  54235. if (this._showController) {
  54236. contentGroup.eachChild(function (child) {
  54237. if (child.__legendDataIndex === currDataIndex) {
  54238. targetItemGroup = child;
  54239. }
  54240. });
  54241. }
  54242. else {
  54243. targetItemGroup = contentGroup.childAt(0);
  54244. }
  54245. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  54246. if (targetItemGroup) {
  54247. var itemRect = targetItemGroup.getBoundingRect();
  54248. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  54249. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  54250. pageIndex = Math.floor(
  54251. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  54252. );
  54253. pageIndex = (contentRect[wh] && pageCount)
  54254. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  54255. : -1;
  54256. var winRect = {x: 0, y: 0};
  54257. winRect[wh] = containerRectSize;
  54258. winRect[hw] = contentRect[hw];
  54259. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  54260. var startIdx;
  54261. var children = contentGroup.children();
  54262. contentGroup.eachChild(function (child, index) {
  54263. var itemRect = getItemRect(child);
  54264. if (itemRect.intersect(winRect)) {
  54265. startIdx == null && (startIdx = index);
  54266. // It is user-friendly that the last item shown in the
  54267. // current window is shown at the begining of next window.
  54268. pageNextDataIndex = child.__legendDataIndex;
  54269. }
  54270. // If the last item is shown entirely, no next page.
  54271. if (index === children.length - 1
  54272. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  54273. ) {
  54274. pageNextDataIndex = null;
  54275. }
  54276. });
  54277. // Always align based on the left/top most item, so the left/top most
  54278. // item in the previous window is needed to be found here.
  54279. if (startIdx != null) {
  54280. var startItem = children[startIdx];
  54281. var startRect = getItemRect(startItem);
  54282. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  54283. // If the first item is shown entirely, no previous page.
  54284. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  54285. pagePrevDataIndex = null;
  54286. }
  54287. else {
  54288. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  54289. startIdx--;
  54290. }
  54291. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  54292. }
  54293. }
  54294. }
  54295. return {
  54296. contentPosition: contentPos,
  54297. pageIndex: pageIndex,
  54298. pageCount: pageCount,
  54299. pagePrevDataIndex: pagePrevDataIndex,
  54300. pageNextDataIndex: pageNextDataIndex
  54301. };
  54302. function getItemRect(el) {
  54303. var itemRect = el.getBoundingRect().clone();
  54304. itemRect[xy] += el.position[orientIdx];
  54305. return itemRect;
  54306. }
  54307. }
  54308. });
  54309. /**
  54310. * @event legendScroll
  54311. * @type {Object}
  54312. * @property {string} type 'legendScroll'
  54313. * @property {string} scrollDataIndex
  54314. */
  54315. registerAction(
  54316. 'legendScroll', 'legendscroll',
  54317. function (payload, ecModel) {
  54318. var scrollDataIndex = payload.scrollDataIndex;
  54319. scrollDataIndex != null && ecModel.eachComponent(
  54320. {mainType: 'legend', subType: 'scroll', query: payload},
  54321. function (legendModel) {
  54322. legendModel.setScrollDataIndex(scrollDataIndex);
  54323. }
  54324. );
  54325. }
  54326. );
  54327. /**
  54328. * Legend component entry file8
  54329. */
  54330. extendComponentModel({
  54331. type: 'tooltip',
  54332. dependencies: ['axisPointer'],
  54333. defaultOption: {
  54334. zlevel: 0,
  54335. z: 8,
  54336. show: true,
  54337. // tooltip主体内容
  54338. showContent: true,
  54339. // 'trigger' only works on coordinate system.
  54340. // 'item' | 'axis' | 'none'
  54341. trigger: 'item',
  54342. // 'click' | 'mousemove' | 'none'
  54343. triggerOn: 'mousemove|click',
  54344. alwaysShowContent: false,
  54345. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  54346. // 位置 {Array} | {Function}
  54347. // position: null
  54348. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  54349. // align: null,
  54350. // verticalAlign: null,
  54351. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  54352. confine: false,
  54353. // 内容格式器:{string}(Template) ¦ {Function}
  54354. // formatter: null
  54355. showDelay: 0,
  54356. // 隐藏延迟,单位ms
  54357. hideDelay: 100,
  54358. // 动画变换时间,单位s
  54359. transitionDuration: 0.4,
  54360. enterable: false,
  54361. // 提示背景颜色,默认为透明度为0.7的黑色
  54362. backgroundColor: 'rgba(50,50,50,0.7)',
  54363. // 提示边框颜色
  54364. borderColor: '#333',
  54365. // 提示边框圆角,单位px,默认为4
  54366. borderRadius: 4,
  54367. // 提示边框线宽,单位px,默认为0(无边框)
  54368. borderWidth: 0,
  54369. // 提示内边距,单位px,默认各方向内边距为5,
  54370. // 接受数组分别设定上右下左边距,同css
  54371. padding: 5,
  54372. // Extra css text
  54373. extraCssText: '',
  54374. // 坐标轴指示器,坐标轴触发有效
  54375. axisPointer: {
  54376. // 默认为直线
  54377. // 可选为:'line' | 'shadow' | 'cross'
  54378. type: 'line',
  54379. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  54380. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  54381. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  54382. // 极坐标系会默认选择 angle 轴
  54383. axis: 'auto',
  54384. animation: 'auto',
  54385. animationDurationUpdate: 200,
  54386. animationEasingUpdate: 'exponentialOut',
  54387. crossStyle: {
  54388. color: '#999',
  54389. width: 1,
  54390. type: 'dashed',
  54391. // TODO formatter
  54392. textStyle: {}
  54393. }
  54394. // lineStyle and shadowStyle should not be specified here,
  54395. // otherwise it will always override those styles on option.axisPointer.
  54396. },
  54397. textStyle: {
  54398. color: '#fff',
  54399. fontSize: 14
  54400. }
  54401. }
  54402. });
  54403. var each$19 = each$1;
  54404. var toCamelCase$1 = toCamelCase;
  54405. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  54406. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  54407. /**
  54408. * @param {number} duration
  54409. * @return {string}
  54410. * @inner
  54411. */
  54412. function assembleTransition(duration) {
  54413. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  54414. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  54415. + 'top ' + duration + 's ' + transitionCurve;
  54416. return map(vendors, function (vendorPrefix) {
  54417. return vendorPrefix + 'transition:' + transitionText;
  54418. }).join(';');
  54419. }
  54420. /**
  54421. * @param {Object} textStyle
  54422. * @return {string}
  54423. * @inner
  54424. */
  54425. function assembleFont(textStyleModel) {
  54426. var cssText = [];
  54427. var fontSize = textStyleModel.get('fontSize');
  54428. var color = textStyleModel.getTextColor();
  54429. color && cssText.push('color:' + color);
  54430. cssText.push('font:' + textStyleModel.getFont());
  54431. fontSize &&
  54432. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  54433. each$19(['decoration', 'align'], function (name) {
  54434. var val = textStyleModel.get(name);
  54435. val && cssText.push('text-' + name + ':' + val);
  54436. });
  54437. return cssText.join(';');
  54438. }
  54439. /**
  54440. * @param {Object} tooltipModel
  54441. * @return {string}
  54442. * @inner
  54443. */
  54444. function assembleCssText(tooltipModel) {
  54445. var cssText = [];
  54446. var transitionDuration = tooltipModel.get('transitionDuration');
  54447. var backgroundColor = tooltipModel.get('backgroundColor');
  54448. var textStyleModel = tooltipModel.getModel('textStyle');
  54449. var padding = tooltipModel.get('padding');
  54450. // Animation transition. Do not animate when transitionDuration is 0.
  54451. transitionDuration &&
  54452. cssText.push(assembleTransition(transitionDuration));
  54453. if (backgroundColor) {
  54454. if (env$1.canvasSupported) {
  54455. cssText.push('background-Color:' + backgroundColor);
  54456. }
  54457. else {
  54458. // for ie
  54459. cssText.push(
  54460. 'background-Color:#' + toHex(backgroundColor)
  54461. );
  54462. cssText.push('filter:alpha(opacity=70)');
  54463. }
  54464. }
  54465. // Border style
  54466. each$19(['width', 'color', 'radius'], function (name) {
  54467. var borderName = 'border-' + name;
  54468. var camelCase = toCamelCase$1(borderName);
  54469. var val = tooltipModel.get(camelCase);
  54470. val != null &&
  54471. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  54472. });
  54473. // Text style
  54474. cssText.push(assembleFont(textStyleModel));
  54475. // Padding
  54476. if (padding != null) {
  54477. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  54478. }
  54479. return cssText.join(';') + ';';
  54480. }
  54481. /**
  54482. * @alias module:echarts/component/tooltip/TooltipContent
  54483. * @constructor
  54484. */
  54485. function TooltipContent(container, api) {
  54486. if (env$1.wxa) {
  54487. return null;
  54488. }
  54489. var el = document.createElement('div');
  54490. var zr = this._zr = api.getZr();
  54491. this.el = el;
  54492. this._x = api.getWidth() / 2;
  54493. this._y = api.getHeight() / 2;
  54494. container.appendChild(el);
  54495. this._container = container;
  54496. this._show = false;
  54497. /**
  54498. * @private
  54499. */
  54500. this._hideTimeout;
  54501. var self = this;
  54502. el.onmouseenter = function () {
  54503. // clear the timeout in hideLater and keep showing tooltip
  54504. if (self._enterable) {
  54505. clearTimeout(self._hideTimeout);
  54506. self._show = true;
  54507. }
  54508. self._inContent = true;
  54509. };
  54510. el.onmousemove = function (e) {
  54511. e = e || window.event;
  54512. if (!self._enterable) {
  54513. // Try trigger zrender event to avoid mouse
  54514. // in and out shape too frequently
  54515. var handler = zr.handler;
  54516. normalizeEvent(container, e, true);
  54517. handler.dispatch('mousemove', e);
  54518. }
  54519. };
  54520. el.onmouseleave = function () {
  54521. if (self._enterable) {
  54522. if (self._show) {
  54523. self.hideLater(self._hideDelay);
  54524. }
  54525. }
  54526. self._inContent = false;
  54527. };
  54528. }
  54529. TooltipContent.prototype = {
  54530. constructor: TooltipContent,
  54531. /**
  54532. * @private
  54533. * @type {boolean}
  54534. */
  54535. _enterable: true,
  54536. /**
  54537. * Update when tooltip is rendered
  54538. */
  54539. update: function () {
  54540. // FIXME
  54541. // Move this logic to ec main?
  54542. var container = this._container;
  54543. var stl = container.currentStyle
  54544. || document.defaultView.getComputedStyle(container);
  54545. var domStyle = container.style;
  54546. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  54547. domStyle.position = 'relative';
  54548. }
  54549. // Hide the tooltip
  54550. // PENDING
  54551. // this.hide();
  54552. },
  54553. show: function (tooltipModel) {
  54554. clearTimeout(this._hideTimeout);
  54555. var el = this.el;
  54556. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  54557. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  54558. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  54559. + (tooltipModel.get('extraCssText') || '');
  54560. el.style.display = el.innerHTML ? 'block' : 'none';
  54561. this._show = true;
  54562. },
  54563. setContent: function (content) {
  54564. this.el.innerHTML = content == null ? '' : content;
  54565. },
  54566. setEnterable: function (enterable) {
  54567. this._enterable = enterable;
  54568. },
  54569. getSize: function () {
  54570. var el = this.el;
  54571. return [el.clientWidth, el.clientHeight];
  54572. },
  54573. moveTo: function (x, y) {
  54574. // xy should be based on canvas root. But tooltipContent is
  54575. // the sibling of canvas root. So padding of ec container
  54576. // should be considered here.
  54577. var zr = this._zr;
  54578. var viewportRootOffset;
  54579. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  54580. x += viewportRootOffset.offsetLeft;
  54581. y += viewportRootOffset.offsetTop;
  54582. }
  54583. var style = this.el.style;
  54584. style.left = x + 'px';
  54585. style.top = y + 'px';
  54586. this._x = x;
  54587. this._y = y;
  54588. },
  54589. hide: function () {
  54590. this.el.style.display = 'none';
  54591. this._show = false;
  54592. },
  54593. hideLater: function (time) {
  54594. if (this._show && !(this._inContent && this._enterable)) {
  54595. if (time) {
  54596. this._hideDelay = time;
  54597. // Set show false to avoid invoke hideLater mutiple times
  54598. this._show = false;
  54599. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  54600. }
  54601. else {
  54602. this.hide();
  54603. }
  54604. }
  54605. },
  54606. isShow: function () {
  54607. return this._show;
  54608. }
  54609. };
  54610. var bind$3 = bind;
  54611. var each$18 = each$1;
  54612. var parsePercent$2 = parsePercent$1;
  54613. var proxyRect = new Rect({
  54614. shape: {x: -1, y: -1, width: 2, height: 2}
  54615. });
  54616. extendComponentView({
  54617. type: 'tooltip',
  54618. init: function (ecModel, api) {
  54619. if (env$1.node) {
  54620. return;
  54621. }
  54622. var tooltipContent = new TooltipContent(api.getDom(), api);
  54623. this._tooltipContent = tooltipContent;
  54624. },
  54625. render: function (tooltipModel, ecModel, api) {
  54626. if (env$1.node || env$1.wxa) {
  54627. return;
  54628. }
  54629. // Reset
  54630. this.group.removeAll();
  54631. /**
  54632. * @private
  54633. * @type {module:echarts/component/tooltip/TooltipModel}
  54634. */
  54635. this._tooltipModel = tooltipModel;
  54636. /**
  54637. * @private
  54638. * @type {module:echarts/model/Global}
  54639. */
  54640. this._ecModel = ecModel;
  54641. /**
  54642. * @private
  54643. * @type {module:echarts/ExtensionAPI}
  54644. */
  54645. this._api = api;
  54646. /**
  54647. * Should be cleaned when render.
  54648. * @private
  54649. * @type {Array.<Array.<Object>>}
  54650. */
  54651. this._lastDataByCoordSys = null;
  54652. /**
  54653. * @private
  54654. * @type {boolean}
  54655. */
  54656. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  54657. var tooltipContent = this._tooltipContent;
  54658. tooltipContent.update();
  54659. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  54660. this._initGlobalListener();
  54661. this._keepShow();
  54662. },
  54663. _initGlobalListener: function () {
  54664. var tooltipModel = this._tooltipModel;
  54665. var triggerOn = tooltipModel.get('triggerOn');
  54666. register(
  54667. 'itemTooltip',
  54668. this._api,
  54669. bind$3(function (currTrigger, e, dispatchAction) {
  54670. // If 'none', it is not controlled by mouse totally.
  54671. if (triggerOn !== 'none') {
  54672. if (triggerOn.indexOf(currTrigger) >= 0) {
  54673. this._tryShow(e, dispatchAction);
  54674. }
  54675. else if (currTrigger === 'leave') {
  54676. this._hide(dispatchAction);
  54677. }
  54678. }
  54679. }, this)
  54680. );
  54681. },
  54682. _keepShow: function () {
  54683. var tooltipModel = this._tooltipModel;
  54684. var ecModel = this._ecModel;
  54685. var api = this._api;
  54686. // Try to keep the tooltip show when refreshing
  54687. if (this._lastX != null
  54688. && this._lastY != null
  54689. // When user is willing to control tooltip totally using API,
  54690. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  54691. // which is not expected.
  54692. && tooltipModel.get('triggerOn') !== 'none'
  54693. ) {
  54694. var self = this;
  54695. clearTimeout(this._refreshUpdateTimeout);
  54696. this._refreshUpdateTimeout = setTimeout(function () {
  54697. // Show tip next tick after other charts are rendered
  54698. // In case highlight action has wrong result
  54699. // FIXME
  54700. self.manuallyShowTip(tooltipModel, ecModel, api, {
  54701. x: self._lastX,
  54702. y: self._lastY
  54703. });
  54704. });
  54705. }
  54706. },
  54707. /**
  54708. * Show tip manually by
  54709. * dispatchAction({
  54710. * type: 'showTip',
  54711. * x: 10,
  54712. * y: 10
  54713. * });
  54714. * Or
  54715. * dispatchAction({
  54716. * type: 'showTip',
  54717. * seriesIndex: 0,
  54718. * dataIndex or dataIndexInside or name
  54719. * });
  54720. *
  54721. * TODO Batch
  54722. */
  54723. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  54724. if (payload.from === this.uid || env$1.node) {
  54725. return;
  54726. }
  54727. var dispatchAction = makeDispatchAction$1(payload, api);
  54728. // Reset ticket
  54729. this._ticket = '';
  54730. // When triggered from axisPointer.
  54731. var dataByCoordSys = payload.dataByCoordSys;
  54732. if (payload.tooltip && payload.x != null && payload.y != null) {
  54733. var el = proxyRect;
  54734. el.position = [payload.x, payload.y];
  54735. el.update();
  54736. el.tooltip = payload.tooltip;
  54737. // Manually show tooltip while view is not using zrender elements.
  54738. this._tryShow({
  54739. offsetX: payload.x,
  54740. offsetY: payload.y,
  54741. target: el
  54742. }, dispatchAction);
  54743. }
  54744. else if (dataByCoordSys) {
  54745. this._tryShow({
  54746. offsetX: payload.x,
  54747. offsetY: payload.y,
  54748. position: payload.position,
  54749. event: {},
  54750. dataByCoordSys: payload.dataByCoordSys,
  54751. tooltipOption: payload.tooltipOption
  54752. }, dispatchAction);
  54753. }
  54754. else if (payload.seriesIndex != null) {
  54755. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  54756. return;
  54757. }
  54758. var pointInfo = findPointFromSeries(payload, ecModel);
  54759. var cx = pointInfo.point[0];
  54760. var cy = pointInfo.point[1];
  54761. if (cx != null && cy != null) {
  54762. this._tryShow({
  54763. offsetX: cx,
  54764. offsetY: cy,
  54765. position: payload.position,
  54766. target: pointInfo.el,
  54767. event: {}
  54768. }, dispatchAction);
  54769. }
  54770. }
  54771. else if (payload.x != null && payload.y != null) {
  54772. // FIXME
  54773. // should wrap dispatchAction like `axisPointer/globalListener` ?
  54774. api.dispatchAction({
  54775. type: 'updateAxisPointer',
  54776. x: payload.x,
  54777. y: payload.y
  54778. });
  54779. this._tryShow({
  54780. offsetX: payload.x,
  54781. offsetY: payload.y,
  54782. position: payload.position,
  54783. target: api.getZr().findHover(payload.x, payload.y).target,
  54784. event: {}
  54785. }, dispatchAction);
  54786. }
  54787. },
  54788. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  54789. var tooltipContent = this._tooltipContent;
  54790. if (!this._alwaysShowContent && this._tooltipModel) {
  54791. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  54792. }
  54793. this._lastX = this._lastY = null;
  54794. if (payload.from !== this.uid) {
  54795. this._hide(makeDispatchAction$1(payload, api));
  54796. }
  54797. },
  54798. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  54799. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  54800. // and tooltip.
  54801. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  54802. var seriesIndex = payload.seriesIndex;
  54803. var dataIndex = payload.dataIndex;
  54804. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  54805. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  54806. return;
  54807. }
  54808. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  54809. if (!seriesModel) {
  54810. return;
  54811. }
  54812. var data = seriesModel.getData();
  54813. var tooltipModel = buildTooltipModel([
  54814. data.getItemModel(dataIndex),
  54815. seriesModel,
  54816. (seriesModel.coordinateSystem || {}).model,
  54817. tooltipModel
  54818. ]);
  54819. if (tooltipModel.get('trigger') !== 'axis') {
  54820. return;
  54821. }
  54822. api.dispatchAction({
  54823. type: 'updateAxisPointer',
  54824. seriesIndex: seriesIndex,
  54825. dataIndex: dataIndex,
  54826. position: payload.position
  54827. });
  54828. return true;
  54829. },
  54830. _tryShow: function (e, dispatchAction) {
  54831. var el = e.target;
  54832. var tooltipModel = this._tooltipModel;
  54833. if (!tooltipModel) {
  54834. return;
  54835. }
  54836. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  54837. this._lastX = e.offsetX;
  54838. this._lastY = e.offsetY;
  54839. var dataByCoordSys = e.dataByCoordSys;
  54840. if (dataByCoordSys && dataByCoordSys.length) {
  54841. this._showAxisTooltip(dataByCoordSys, e);
  54842. }
  54843. // Always show item tooltip if mouse is on the element with dataIndex
  54844. else if (el && el.dataIndex != null) {
  54845. this._lastDataByCoordSys = null;
  54846. this._showSeriesItemTooltip(e, el, dispatchAction);
  54847. }
  54848. // Tooltip provided directly. Like legend.
  54849. else if (el && el.tooltip) {
  54850. this._lastDataByCoordSys = null;
  54851. this._showComponentItemTooltip(e, el, dispatchAction);
  54852. }
  54853. else {
  54854. this._lastDataByCoordSys = null;
  54855. this._hide(dispatchAction);
  54856. }
  54857. },
  54858. _showOrMove: function (tooltipModel, cb) {
  54859. // showDelay is used in this case: tooltip.enterable is set
  54860. // as true. User intent to move mouse into tooltip and click
  54861. // something. `showDelay` makes it easyer to enter the content
  54862. // but tooltip do not move immediately.
  54863. var delay = tooltipModel.get('showDelay');
  54864. cb = bind(cb, this);
  54865. clearTimeout(this._showTimout);
  54866. delay > 0
  54867. ? (this._showTimout = setTimeout(cb, delay))
  54868. : cb();
  54869. },
  54870. _showAxisTooltip: function (dataByCoordSys, e) {
  54871. var ecModel = this._ecModel;
  54872. var globalTooltipModel = this._tooltipModel;
  54873. var point = [e.offsetX, e.offsetY];
  54874. var singleDefaultHTML = [];
  54875. var singleParamsList = [];
  54876. var singleTooltipModel = buildTooltipModel([
  54877. e.tooltipOption,
  54878. globalTooltipModel
  54879. ]);
  54880. each$18(dataByCoordSys, function (itemCoordSys) {
  54881. // var coordParamList = [];
  54882. // var coordDefaultHTML = [];
  54883. // var coordTooltipModel = buildTooltipModel([
  54884. // e.tooltipOption,
  54885. // itemCoordSys.tooltipOption,
  54886. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  54887. // globalTooltipModel
  54888. // ]);
  54889. // var displayMode = coordTooltipModel.get('displayMode');
  54890. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  54891. each$18(itemCoordSys.dataByAxis, function (item) {
  54892. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  54893. var axisValue = item.value;
  54894. var seriesDefaultHTML = [];
  54895. if (!axisModel || axisValue == null) {
  54896. return;
  54897. }
  54898. var valueLabel = getValueLabel(
  54899. axisValue, axisModel.axis, ecModel,
  54900. item.seriesDataIndices,
  54901. item.valueLabelOpt
  54902. );
  54903. each$1(item.seriesDataIndices, function (idxItem) {
  54904. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  54905. var dataIndex = idxItem.dataIndexInside;
  54906. var dataParams = series && series.getDataParams(dataIndex);
  54907. dataParams.axisDim = item.axisDim;
  54908. dataParams.axisIndex = item.axisIndex;
  54909. dataParams.axisType = item.axisType;
  54910. dataParams.axisId = item.axisId;
  54911. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  54912. dataParams.axisValueLabel = valueLabel;
  54913. if (dataParams) {
  54914. singleParamsList.push(dataParams);
  54915. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  54916. }
  54917. });
  54918. // Default tooltip content
  54919. // FIXME
  54920. // (1) shold be the first data which has name?
  54921. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  54922. var firstLine = valueLabel;
  54923. singleDefaultHTML.push(
  54924. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  54925. + seriesDefaultHTML.join('<br />')
  54926. );
  54927. });
  54928. }, this);
  54929. // In most case, the second axis is shown upper than the first one.
  54930. singleDefaultHTML.reverse();
  54931. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  54932. var positionExpr = e.position;
  54933. this._showOrMove(singleTooltipModel, function () {
  54934. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  54935. this._updatePosition(
  54936. singleTooltipModel,
  54937. positionExpr,
  54938. point[0], point[1],
  54939. this._tooltipContent,
  54940. singleParamsList
  54941. );
  54942. }
  54943. else {
  54944. this._showTooltipContent(
  54945. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  54946. point[0], point[1], positionExpr
  54947. );
  54948. }
  54949. });
  54950. // Do not trigger events here, because this branch only be entered
  54951. // from dispatchAction.
  54952. },
  54953. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  54954. var ecModel = this._ecModel;
  54955. // Use dataModel in element if possible
  54956. // Used when mouseover on a element like markPoint or edge
  54957. // In which case, the data is not main data in series.
  54958. var seriesIndex = el.seriesIndex;
  54959. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  54960. // For example, graph link.
  54961. var dataModel = el.dataModel || seriesModel;
  54962. var dataIndex = el.dataIndex;
  54963. var dataType = el.dataType;
  54964. var data = dataModel.getData();
  54965. var tooltipModel = buildTooltipModel([
  54966. data.getItemModel(dataIndex),
  54967. dataModel,
  54968. seriesModel && (seriesModel.coordinateSystem || {}).model,
  54969. this._tooltipModel
  54970. ]);
  54971. var tooltipTrigger = tooltipModel.get('trigger');
  54972. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  54973. return;
  54974. }
  54975. var params = dataModel.getDataParams(dataIndex, dataType);
  54976. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  54977. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  54978. this._showOrMove(tooltipModel, function () {
  54979. this._showTooltipContent(
  54980. tooltipModel, defaultHtml, params, asyncTicket,
  54981. e.offsetX, e.offsetY, e.position, e.target
  54982. );
  54983. });
  54984. // FIXME
  54985. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  54986. dispatchAction({
  54987. type: 'showTip',
  54988. dataIndexInside: dataIndex,
  54989. dataIndex: data.getRawIndex(dataIndex),
  54990. seriesIndex: seriesIndex,
  54991. from: this.uid
  54992. });
  54993. },
  54994. _showComponentItemTooltip: function (e, el, dispatchAction) {
  54995. var tooltipOpt = el.tooltip;
  54996. if (typeof tooltipOpt === 'string') {
  54997. var content = tooltipOpt;
  54998. tooltipOpt = {
  54999. content: content,
  55000. // Fixed formatter
  55001. formatter: content
  55002. };
  55003. }
  55004. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  55005. var defaultHtml = subTooltipModel.get('content');
  55006. var asyncTicket = Math.random();
  55007. // Do not check whether `trigger` is 'none' here, because `trigger`
  55008. // only works on cooridinate system. In fact, we have not found case
  55009. // that requires setting `trigger` nothing on component yet.
  55010. this._showOrMove(subTooltipModel, function () {
  55011. this._showTooltipContent(
  55012. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  55013. asyncTicket, e.offsetX, e.offsetY, e.position, el
  55014. );
  55015. });
  55016. // If not dispatch showTip, tip may be hide triggered by axis.
  55017. dispatchAction({
  55018. type: 'showTip',
  55019. from: this.uid
  55020. });
  55021. },
  55022. _showTooltipContent: function (
  55023. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  55024. ) {
  55025. // Reset ticket
  55026. this._ticket = '';
  55027. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  55028. return;
  55029. }
  55030. var tooltipContent = this._tooltipContent;
  55031. var formatter = tooltipModel.get('formatter');
  55032. positionExpr = positionExpr || tooltipModel.get('position');
  55033. var html = defaultHtml;
  55034. if (formatter && typeof formatter === 'string') {
  55035. html = formatTpl(formatter, params, true);
  55036. }
  55037. else if (typeof formatter === 'function') {
  55038. var callback = bind$3(function (cbTicket, html) {
  55039. if (cbTicket === this._ticket) {
  55040. tooltipContent.setContent(html);
  55041. this._updatePosition(
  55042. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  55043. );
  55044. }
  55045. }, this);
  55046. this._ticket = asyncTicket;
  55047. html = formatter(params, asyncTicket, callback);
  55048. }
  55049. tooltipContent.setContent(html);
  55050. tooltipContent.show(tooltipModel);
  55051. this._updatePosition(
  55052. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  55053. );
  55054. },
  55055. /**
  55056. * @param {string|Function|Array.<number>|Object} positionExpr
  55057. * @param {number} x Mouse x
  55058. * @param {number} y Mouse y
  55059. * @param {boolean} confine Whether confine tooltip content in view rect.
  55060. * @param {Object|<Array.<Object>} params
  55061. * @param {module:zrender/Element} el target element
  55062. * @param {module:echarts/ExtensionAPI} api
  55063. * @return {Array.<number>}
  55064. */
  55065. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  55066. var viewWidth = this._api.getWidth();
  55067. var viewHeight = this._api.getHeight();
  55068. positionExpr = positionExpr || tooltipModel.get('position');
  55069. var contentSize = content.getSize();
  55070. var align = tooltipModel.get('align');
  55071. var vAlign = tooltipModel.get('verticalAlign');
  55072. var rect = el && el.getBoundingRect().clone();
  55073. el && rect.applyTransform(el.transform);
  55074. if (typeof positionExpr === 'function') {
  55075. // Callback of position can be an array or a string specify the position
  55076. positionExpr = positionExpr([x, y], params, content.el, rect, {
  55077. viewSize: [viewWidth, viewHeight],
  55078. contentSize: contentSize.slice()
  55079. });
  55080. }
  55081. if (isArray(positionExpr)) {
  55082. x = parsePercent$2(positionExpr[0], viewWidth);
  55083. y = parsePercent$2(positionExpr[1], viewHeight);
  55084. }
  55085. else if (isObject$1(positionExpr)) {
  55086. positionExpr.width = contentSize[0];
  55087. positionExpr.height = contentSize[1];
  55088. var layoutRect = getLayoutRect(
  55089. positionExpr, {width: viewWidth, height: viewHeight}
  55090. );
  55091. x = layoutRect.x;
  55092. y = layoutRect.y;
  55093. align = null;
  55094. // When positionExpr is left/top/right/bottom,
  55095. // align and verticalAlign will not work.
  55096. vAlign = null;
  55097. }
  55098. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  55099. else if (typeof positionExpr === 'string' && el) {
  55100. var pos = calcTooltipPosition(
  55101. positionExpr, rect, contentSize
  55102. );
  55103. x = pos[0];
  55104. y = pos[1];
  55105. }
  55106. else {
  55107. var pos = refixTooltipPosition(
  55108. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  55109. );
  55110. x = pos[0];
  55111. y = pos[1];
  55112. }
  55113. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  55114. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  55115. if (tooltipModel.get('confine')) {
  55116. var pos = confineTooltipPosition(
  55117. x, y, content.el, viewWidth, viewHeight
  55118. );
  55119. x = pos[0];
  55120. y = pos[1];
  55121. }
  55122. content.moveTo(x, y);
  55123. },
  55124. // FIXME
  55125. // Should we remove this but leave this to user?
  55126. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  55127. var lastCoordSys = this._lastDataByCoordSys;
  55128. var contentNotChanged = !!lastCoordSys
  55129. && lastCoordSys.length === dataByCoordSys.length;
  55130. contentNotChanged && each$18(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  55131. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  55132. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  55133. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  55134. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  55135. contentNotChanged && each$18(lastDataByAxis, function (lastItem, indexAxis) {
  55136. var thisItem = thisDataByAxis[indexAxis] || {};
  55137. var lastIndices = lastItem.seriesDataIndices || [];
  55138. var newIndices = thisItem.seriesDataIndices || [];
  55139. contentNotChanged &=
  55140. lastItem.value === thisItem.value
  55141. && lastItem.axisType === thisItem.axisType
  55142. && lastItem.axisId === thisItem.axisId
  55143. && lastIndices.length === newIndices.length;
  55144. contentNotChanged && each$18(lastIndices, function (lastIdxItem, j) {
  55145. var newIdxItem = newIndices[j];
  55146. contentNotChanged &=
  55147. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  55148. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  55149. });
  55150. });
  55151. });
  55152. this._lastDataByCoordSys = dataByCoordSys;
  55153. return !!contentNotChanged;
  55154. },
  55155. _hide: function (dispatchAction) {
  55156. // Do not directly hideLater here, because this behavior may be prevented
  55157. // in dispatchAction when showTip is dispatched.
  55158. // FIXME
  55159. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  55160. this._lastDataByCoordSys = null;
  55161. dispatchAction({
  55162. type: 'hideTip',
  55163. from: this.uid
  55164. });
  55165. },
  55166. dispose: function (ecModel, api) {
  55167. if (env$1.node) {
  55168. return;
  55169. }
  55170. this._tooltipContent.hide();
  55171. unregister('itemTooltip', api);
  55172. }
  55173. });
  55174. /**
  55175. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  55176. * From top to bottom. (the last one should be globalTooltipModel);
  55177. */
  55178. function buildTooltipModel(modelCascade) {
  55179. var resultModel = modelCascade.pop();
  55180. while (modelCascade.length) {
  55181. var tooltipOpt = modelCascade.pop();
  55182. if (tooltipOpt) {
  55183. if (Model.isInstance(tooltipOpt)) {
  55184. tooltipOpt = tooltipOpt.get('tooltip', true);
  55185. }
  55186. // In each data item tooltip can be simply write:
  55187. // {
  55188. // value: 10,
  55189. // tooltip: 'Something you need to know'
  55190. // }
  55191. if (typeof tooltipOpt === 'string') {
  55192. tooltipOpt = {formatter: tooltipOpt};
  55193. }
  55194. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  55195. }
  55196. }
  55197. return resultModel;
  55198. }
  55199. function makeDispatchAction$1(payload, api) {
  55200. return payload.dispatchAction || bind(api.dispatchAction, api);
  55201. }
  55202. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  55203. var size = getOuterSize(el);
  55204. var width = size.width;
  55205. var height = size.height;
  55206. if (gapH != null) {
  55207. if (x + width + gapH > viewWidth) {
  55208. x -= width + gapH;
  55209. }
  55210. else {
  55211. x += gapH;
  55212. }
  55213. }
  55214. if (gapV != null) {
  55215. if (y + height + gapV > viewHeight) {
  55216. y -= height + gapV;
  55217. }
  55218. else {
  55219. y += gapV;
  55220. }
  55221. }
  55222. return [x, y];
  55223. }
  55224. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  55225. var size = getOuterSize(el);
  55226. var width = size.width;
  55227. var height = size.height;
  55228. x = Math.min(x + width, viewWidth) - width;
  55229. y = Math.min(y + height, viewHeight) - height;
  55230. x = Math.max(x, 0);
  55231. y = Math.max(y, 0);
  55232. return [x, y];
  55233. }
  55234. function getOuterSize(el) {
  55235. var width = el.clientWidth;
  55236. var height = el.clientHeight;
  55237. // Consider browser compatibility.
  55238. // IE8 does not support getComputedStyle.
  55239. if (document.defaultView && document.defaultView.getComputedStyle) {
  55240. var stl = document.defaultView.getComputedStyle(el);
  55241. if (stl) {
  55242. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  55243. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  55244. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  55245. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  55246. }
  55247. }
  55248. return {width: width, height: height};
  55249. }
  55250. function calcTooltipPosition(position, rect, contentSize) {
  55251. var domWidth = contentSize[0];
  55252. var domHeight = contentSize[1];
  55253. var gap = 5;
  55254. var x = 0;
  55255. var y = 0;
  55256. var rectWidth = rect.width;
  55257. var rectHeight = rect.height;
  55258. switch (position) {
  55259. case 'inside':
  55260. x = rect.x + rectWidth / 2 - domWidth / 2;
  55261. y = rect.y + rectHeight / 2 - domHeight / 2;
  55262. break;
  55263. case 'top':
  55264. x = rect.x + rectWidth / 2 - domWidth / 2;
  55265. y = rect.y - domHeight - gap;
  55266. break;
  55267. case 'bottom':
  55268. x = rect.x + rectWidth / 2 - domWidth / 2;
  55269. y = rect.y + rectHeight + gap;
  55270. break;
  55271. case 'left':
  55272. x = rect.x - domWidth - gap;
  55273. y = rect.y + rectHeight / 2 - domHeight / 2;
  55274. break;
  55275. case 'right':
  55276. x = rect.x + rectWidth + gap;
  55277. y = rect.y + rectHeight / 2 - domHeight / 2;
  55278. }
  55279. return [x, y];
  55280. }
  55281. function isCenterAlign(align) {
  55282. return align === 'center' || align === 'middle';
  55283. }
  55284. // FIXME Better way to pack data in graphic element
  55285. /**
  55286. * @action
  55287. * @property {string} type
  55288. * @property {number} seriesIndex
  55289. * @property {number} dataIndex
  55290. * @property {number} [x]
  55291. * @property {number} [y]
  55292. */
  55293. registerAction(
  55294. {
  55295. type: 'showTip',
  55296. event: 'showTip',
  55297. update: 'tooltip:manuallyShowTip'
  55298. },
  55299. // noop
  55300. function () {}
  55301. );
  55302. registerAction(
  55303. {
  55304. type: 'hideTip',
  55305. event: 'hideTip',
  55306. update: 'tooltip:manuallyHideTip'
  55307. },
  55308. // noop
  55309. function () {}
  55310. );
  55311. function getSeriesStackId$1(seriesModel) {
  55312. return seriesModel.get('stack')
  55313. || '__ec_stack_' + seriesModel.seriesIndex;
  55314. }
  55315. function getAxisKey$1(axis) {
  55316. return axis.dim;
  55317. }
  55318. /**
  55319. * @param {string} seriesType
  55320. * @param {module:echarts/model/Global} ecModel
  55321. * @param {module:echarts/ExtensionAPI} api
  55322. */
  55323. function barLayoutPolar(seriesType, ecModel, api) {
  55324. var width = api.getWidth();
  55325. var height = api.getHeight();
  55326. var lastStackCoords = {};
  55327. var barWidthAndOffset = calRadialBar(
  55328. filter(
  55329. ecModel.getSeriesByType(seriesType),
  55330. function (seriesModel) {
  55331. return !ecModel.isSeriesFiltered(seriesModel)
  55332. && seriesModel.coordinateSystem
  55333. && seriesModel.coordinateSystem.type === 'polar';
  55334. }
  55335. )
  55336. );
  55337. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  55338. // Check series coordinate, do layout for polar only
  55339. if (seriesModel.coordinateSystem.type !== 'polar') {
  55340. return;
  55341. }
  55342. var data = seriesModel.getData();
  55343. var polar = seriesModel.coordinateSystem;
  55344. var baseAxis = polar.getBaseAxis();
  55345. var stackId = getSeriesStackId$1(seriesModel);
  55346. var columnLayoutInfo
  55347. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  55348. var columnOffset = columnLayoutInfo.offset;
  55349. var columnWidth = columnLayoutInfo.width;
  55350. var valueAxis = polar.getOtherAxis(baseAxis);
  55351. var center = seriesModel.get('center') || ['50%', '50%'];
  55352. var cx = parsePercent$1(center[0], width);
  55353. var cy = parsePercent$1(center[1], height);
  55354. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  55355. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  55356. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  55357. var valueDim = data.mapDimension(valueAxis.dim);
  55358. var baseDim = data.mapDimension(baseAxis.dim);
  55359. var stacked = isDimensionStacked(data, valueDim, baseDim);
  55360. var valueAxisStart = valueAxis.getExtent()[0];
  55361. for (var idx = 0, len = data.count(); idx < len; idx++) {
  55362. var value = data.get(valueDim, idx);
  55363. var baseValue = data.get(baseDim, idx);
  55364. if (isNaN(value)) {
  55365. continue;
  55366. }
  55367. var sign = value >= 0 ? 'p' : 'n';
  55368. var baseCoord = valueAxisStart;
  55369. // Because of the barMinHeight, we can not use the value in
  55370. // stackResultDimension directly.
  55371. // Only ordinal axis can be stacked.
  55372. if (stacked) {
  55373. if (!lastStackCoords[stackId][baseValue]) {
  55374. lastStackCoords[stackId][baseValue] = {
  55375. p: valueAxisStart, // Positive stack
  55376. n: valueAxisStart // Negative stack
  55377. };
  55378. }
  55379. // Should also consider #4243
  55380. baseCoord = lastStackCoords[stackId][baseValue][sign];
  55381. }
  55382. var r0;
  55383. var r;
  55384. var startAngle;
  55385. var endAngle;
  55386. // radial sector
  55387. if (valueAxis.dim === 'radius') {
  55388. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  55389. var angle = baseAxis.dataToAngle(baseValue);
  55390. if (Math.abs(radiusSpan) < barMinHeight) {
  55391. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  55392. }
  55393. r0 = baseCoord;
  55394. r = baseCoord + radiusSpan;
  55395. startAngle = angle - columnOffset;
  55396. endAngle = startAngle - columnWidth;
  55397. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  55398. }
  55399. // tangential sector
  55400. else {
  55401. // angleAxis must be clamped.
  55402. var angleSpan = valueAxis.dataToAngle(value, true) - valueAxisStart;
  55403. var radius = baseAxis.dataToRadius(baseValue);
  55404. if (Math.abs(angleSpan) < barMinAngle) {
  55405. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  55406. }
  55407. r0 = radius + columnOffset;
  55408. r = r0 + columnWidth;
  55409. startAngle = baseCoord;
  55410. endAngle = baseCoord + angleSpan;
  55411. // if the previous stack is at the end of the ring,
  55412. // add a round to differentiate it from origin
  55413. // var extent = angleAxis.getExtent();
  55414. // var stackCoord = angle;
  55415. // if (stackCoord === extent[0] && value > 0) {
  55416. // stackCoord = extent[1];
  55417. // }
  55418. // else if (stackCoord === extent[1] && value < 0) {
  55419. // stackCoord = extent[0];
  55420. // }
  55421. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  55422. }
  55423. data.setItemLayout(idx, {
  55424. cx: cx,
  55425. cy: cy,
  55426. r0: r0,
  55427. r: r,
  55428. // Consider that positive angle is anti-clockwise,
  55429. // while positive radian of sector is clockwise
  55430. startAngle: -startAngle * Math.PI / 180,
  55431. endAngle: -endAngle * Math.PI / 180
  55432. });
  55433. }
  55434. }, this);
  55435. }
  55436. /**
  55437. * Calculate bar width and offset for radial bar charts
  55438. */
  55439. function calRadialBar(barSeries, api) {
  55440. // Columns info on each category axis. Key is polar name
  55441. var columnsMap = {};
  55442. each$1(barSeries, function (seriesModel, idx) {
  55443. var data = seriesModel.getData();
  55444. var polar = seriesModel.coordinateSystem;
  55445. var baseAxis = polar.getBaseAxis();
  55446. var axisExtent = baseAxis.getExtent();
  55447. var bandWidth = baseAxis.type === 'category'
  55448. ? baseAxis.getBandWidth()
  55449. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  55450. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  55451. bandWidth: bandWidth,
  55452. remainedWidth: bandWidth,
  55453. autoWidthCount: 0,
  55454. categoryGap: '20%',
  55455. gap: '30%',
  55456. stacks: {}
  55457. };
  55458. var stacks = columnsOnAxis.stacks;
  55459. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  55460. var stackId = getSeriesStackId$1(seriesModel);
  55461. if (!stacks[stackId]) {
  55462. columnsOnAxis.autoWidthCount++;
  55463. }
  55464. stacks[stackId] = stacks[stackId] || {
  55465. width: 0,
  55466. maxWidth: 0
  55467. };
  55468. var barWidth = parsePercent$1(
  55469. seriesModel.get('barWidth'),
  55470. bandWidth
  55471. );
  55472. var barMaxWidth = parsePercent$1(
  55473. seriesModel.get('barMaxWidth'),
  55474. bandWidth
  55475. );
  55476. var barGap = seriesModel.get('barGap');
  55477. var barCategoryGap = seriesModel.get('barCategoryGap');
  55478. if (barWidth && !stacks[stackId].width) {
  55479. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  55480. stacks[stackId].width = barWidth;
  55481. columnsOnAxis.remainedWidth -= barWidth;
  55482. }
  55483. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  55484. (barGap != null) && (columnsOnAxis.gap = barGap);
  55485. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  55486. });
  55487. var result = {};
  55488. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  55489. result[coordSysName] = {};
  55490. var stacks = columnsOnAxis.stacks;
  55491. var bandWidth = columnsOnAxis.bandWidth;
  55492. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  55493. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  55494. var remainedWidth = columnsOnAxis.remainedWidth;
  55495. var autoWidthCount = columnsOnAxis.autoWidthCount;
  55496. var autoWidth = (remainedWidth - categoryGap)
  55497. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  55498. autoWidth = Math.max(autoWidth, 0);
  55499. // Find if any auto calculated bar exceeded maxBarWidth
  55500. each$1(stacks, function (column, stack) {
  55501. var maxWidth = column.maxWidth;
  55502. if (maxWidth && maxWidth < autoWidth) {
  55503. maxWidth = Math.min(maxWidth, remainedWidth);
  55504. if (column.width) {
  55505. maxWidth = Math.min(maxWidth, column.width);
  55506. }
  55507. remainedWidth -= maxWidth;
  55508. column.width = maxWidth;
  55509. autoWidthCount--;
  55510. }
  55511. });
  55512. // Recalculate width again
  55513. autoWidth = (remainedWidth - categoryGap)
  55514. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  55515. autoWidth = Math.max(autoWidth, 0);
  55516. var widthSum = 0;
  55517. var lastColumn;
  55518. each$1(stacks, function (column, idx) {
  55519. if (!column.width) {
  55520. column.width = autoWidth;
  55521. }
  55522. lastColumn = column;
  55523. widthSum += column.width * (1 + barGapPercent);
  55524. });
  55525. if (lastColumn) {
  55526. widthSum -= lastColumn.width * barGapPercent;
  55527. }
  55528. var offset = -widthSum / 2;
  55529. each$1(stacks, function (column, stackId) {
  55530. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  55531. offset: offset,
  55532. width: column.width
  55533. };
  55534. offset += column.width * (1 + barGapPercent);
  55535. });
  55536. });
  55537. return result;
  55538. }
  55539. function RadiusAxis(scale, radiusExtent) {
  55540. Axis.call(this, 'radius', scale, radiusExtent);
  55541. /**
  55542. * Axis type
  55543. * - 'category'
  55544. * - 'value'
  55545. * - 'time'
  55546. * - 'log'
  55547. * @type {string}
  55548. */
  55549. this.type = 'category';
  55550. }
  55551. RadiusAxis.prototype = {
  55552. constructor: RadiusAxis,
  55553. /**
  55554. * @override
  55555. */
  55556. pointToData: function (point, clamp) {
  55557. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  55558. },
  55559. dataToRadius: Axis.prototype.dataToCoord,
  55560. radiusToData: Axis.prototype.coordToData
  55561. };
  55562. inherits(RadiusAxis, Axis);
  55563. function AngleAxis(scale, angleExtent) {
  55564. angleExtent = angleExtent || [0, 360];
  55565. Axis.call(this, 'angle', scale, angleExtent);
  55566. /**
  55567. * Axis type
  55568. * - 'category'
  55569. * - 'value'
  55570. * - 'time'
  55571. * - 'log'
  55572. * @type {string}
  55573. */
  55574. this.type = 'category';
  55575. }
  55576. AngleAxis.prototype = {
  55577. constructor: AngleAxis,
  55578. /**
  55579. * @override
  55580. */
  55581. pointToData: function (point, clamp) {
  55582. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  55583. },
  55584. dataToAngle: Axis.prototype.dataToCoord,
  55585. angleToData: Axis.prototype.coordToData
  55586. };
  55587. inherits(AngleAxis, Axis);
  55588. /**
  55589. * @module echarts/coord/polar/Polar
  55590. */
  55591. /**
  55592. * @alias {module:echarts/coord/polar/Polar}
  55593. * @constructor
  55594. * @param {string} name
  55595. */
  55596. var Polar = function (name) {
  55597. /**
  55598. * @type {string}
  55599. */
  55600. this.name = name || '';
  55601. /**
  55602. * x of polar center
  55603. * @type {number}
  55604. */
  55605. this.cx = 0;
  55606. /**
  55607. * y of polar center
  55608. * @type {number}
  55609. */
  55610. this.cy = 0;
  55611. /**
  55612. * @type {module:echarts/coord/polar/RadiusAxis}
  55613. * @private
  55614. */
  55615. this._radiusAxis = new RadiusAxis();
  55616. /**
  55617. * @type {module:echarts/coord/polar/AngleAxis}
  55618. * @private
  55619. */
  55620. this._angleAxis = new AngleAxis();
  55621. this._radiusAxis.polar = this._angleAxis.polar = this;
  55622. };
  55623. Polar.prototype = {
  55624. type: 'polar',
  55625. axisPointerEnabled: true,
  55626. constructor: Polar,
  55627. /**
  55628. * @param {Array.<string>}
  55629. * @readOnly
  55630. */
  55631. dimensions: ['radius', 'angle'],
  55632. /**
  55633. * @type {module:echarts/coord/PolarModel}
  55634. */
  55635. model: null,
  55636. /**
  55637. * If contain coord
  55638. * @param {Array.<number>} point
  55639. * @return {boolean}
  55640. */
  55641. containPoint: function (point) {
  55642. var coord = this.pointToCoord(point);
  55643. return this._radiusAxis.contain(coord[0])
  55644. && this._angleAxis.contain(coord[1]);
  55645. },
  55646. /**
  55647. * If contain data
  55648. * @param {Array.<number>} data
  55649. * @return {boolean}
  55650. */
  55651. containData: function (data) {
  55652. return this._radiusAxis.containData(data[0])
  55653. && this._angleAxis.containData(data[1]);
  55654. },
  55655. /**
  55656. * @param {string} dim
  55657. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55658. */
  55659. getAxis: function (dim) {
  55660. return this['_' + dim + 'Axis'];
  55661. },
  55662. /**
  55663. * @return {Array.<module:echarts/coord/Axis>}
  55664. */
  55665. getAxes: function () {
  55666. return [this._radiusAxis, this._angleAxis];
  55667. },
  55668. /**
  55669. * Get axes by type of scale
  55670. * @param {string} scaleType
  55671. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55672. */
  55673. getAxesByScale: function (scaleType) {
  55674. var axes = [];
  55675. var angleAxis = this._angleAxis;
  55676. var radiusAxis = this._radiusAxis;
  55677. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  55678. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  55679. return axes;
  55680. },
  55681. /**
  55682. * @return {module:echarts/coord/polar/AngleAxis}
  55683. */
  55684. getAngleAxis: function () {
  55685. return this._angleAxis;
  55686. },
  55687. /**
  55688. * @return {module:echarts/coord/polar/RadiusAxis}
  55689. */
  55690. getRadiusAxis: function () {
  55691. return this._radiusAxis;
  55692. },
  55693. /**
  55694. * @param {module:echarts/coord/polar/Axis}
  55695. * @return {module:echarts/coord/polar/Axis}
  55696. */
  55697. getOtherAxis: function (axis) {
  55698. var angleAxis = this._angleAxis;
  55699. return axis === angleAxis ? this._radiusAxis : angleAxis;
  55700. },
  55701. /**
  55702. * Base axis will be used on stacking.
  55703. *
  55704. * @return {module:echarts/coord/polar/Axis}
  55705. */
  55706. getBaseAxis: function () {
  55707. return this.getAxesByScale('ordinal')[0]
  55708. || this.getAxesByScale('time')[0]
  55709. || this.getAngleAxis();
  55710. },
  55711. /**
  55712. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  55713. * @return {Object} {baseAxes: [], otherAxes: []}
  55714. */
  55715. getTooltipAxes: function (dim) {
  55716. var baseAxis = (dim != null && dim !== 'auto')
  55717. ? this.getAxis(dim) : this.getBaseAxis();
  55718. return {
  55719. baseAxes: [baseAxis],
  55720. otherAxes: [this.getOtherAxis(baseAxis)]
  55721. };
  55722. },
  55723. /**
  55724. * Convert a single data item to (x, y) point.
  55725. * Parameter data is an array which the first element is radius and the second is angle
  55726. * @param {Array.<number>} data
  55727. * @param {boolean} [clamp=false]
  55728. * @return {Array.<number>}
  55729. */
  55730. dataToPoint: function (data, clamp) {
  55731. return this.coordToPoint([
  55732. this._radiusAxis.dataToRadius(data[0], clamp),
  55733. this._angleAxis.dataToAngle(data[1], clamp)
  55734. ]);
  55735. },
  55736. /**
  55737. * Convert a (x, y) point to data
  55738. * @param {Array.<number>} point
  55739. * @param {boolean} [clamp=false]
  55740. * @return {Array.<number>}
  55741. */
  55742. pointToData: function (point, clamp) {
  55743. var coord = this.pointToCoord(point);
  55744. return [
  55745. this._radiusAxis.radiusToData(coord[0], clamp),
  55746. this._angleAxis.angleToData(coord[1], clamp)
  55747. ];
  55748. },
  55749. /**
  55750. * Convert a (x, y) point to (radius, angle) coord
  55751. * @param {Array.<number>} point
  55752. * @return {Array.<number>}
  55753. */
  55754. pointToCoord: function (point) {
  55755. var dx = point[0] - this.cx;
  55756. var dy = point[1] - this.cy;
  55757. var angleAxis = this.getAngleAxis();
  55758. var extent = angleAxis.getExtent();
  55759. var minAngle = Math.min(extent[0], extent[1]);
  55760. var maxAngle = Math.max(extent[0], extent[1]);
  55761. // Fix fixed extent in polarCreator
  55762. // FIXME
  55763. angleAxis.inverse
  55764. ? (minAngle = maxAngle - 360)
  55765. : (maxAngle = minAngle + 360);
  55766. var radius = Math.sqrt(dx * dx + dy * dy);
  55767. dx /= radius;
  55768. dy /= radius;
  55769. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  55770. // move to angleExtent
  55771. var dir = radian < minAngle ? 1 : -1;
  55772. while (radian < minAngle || radian > maxAngle) {
  55773. radian += dir * 360;
  55774. }
  55775. return [radius, radian];
  55776. },
  55777. /**
  55778. * Convert a (radius, angle) coord to (x, y) point
  55779. * @param {Array.<number>} coord
  55780. * @return {Array.<number>}
  55781. */
  55782. coordToPoint: function (coord) {
  55783. var radius = coord[0];
  55784. var radian = coord[1] / 180 * Math.PI;
  55785. var x = Math.cos(radian) * radius + this.cx;
  55786. // Inverse the y
  55787. var y = -Math.sin(radian) * radius + this.cy;
  55788. return [x, y];
  55789. }
  55790. };
  55791. var PolarAxisModel = ComponentModel.extend({
  55792. type: 'polarAxis',
  55793. /**
  55794. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55795. */
  55796. axis: null,
  55797. /**
  55798. * @override
  55799. */
  55800. getCoordSysModel: function () {
  55801. return this.ecModel.queryComponents({
  55802. mainType: 'polar',
  55803. index: this.option.polarIndex,
  55804. id: this.option.polarId
  55805. })[0];
  55806. }
  55807. });
  55808. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  55809. var polarAxisDefaultExtendedOption = {
  55810. angle: {
  55811. // polarIndex: 0,
  55812. // polarId: '',
  55813. startAngle: 90,
  55814. clockwise: true,
  55815. splitNumber: 12,
  55816. axisLabel: {
  55817. rotate: false
  55818. }
  55819. },
  55820. radius: {
  55821. // polarIndex: 0,
  55822. // polarId: '',
  55823. splitNumber: 5
  55824. }
  55825. };
  55826. function getAxisType$3(axisDim, option) {
  55827. // Default axis with data is category axis
  55828. return option.type || (option.data ? 'category' : 'value');
  55829. }
  55830. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  55831. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  55832. extendComponentModel({
  55833. type: 'polar',
  55834. dependencies: ['polarAxis', 'angleAxis'],
  55835. /**
  55836. * @type {module:echarts/coord/polar/Polar}
  55837. */
  55838. coordinateSystem: null,
  55839. /**
  55840. * @param {string} axisType
  55841. * @return {module:echarts/coord/polar/AxisModel}
  55842. */
  55843. findAxisModel: function (axisType) {
  55844. var foundAxisModel;
  55845. var ecModel = this.ecModel;
  55846. ecModel.eachComponent(axisType, function (axisModel) {
  55847. if (axisModel.getCoordSysModel() === this) {
  55848. foundAxisModel = axisModel;
  55849. }
  55850. }, this);
  55851. return foundAxisModel;
  55852. },
  55853. defaultOption: {
  55854. zlevel: 0,
  55855. z: 0,
  55856. center: ['50%', '50%'],
  55857. radius: '80%'
  55858. }
  55859. });
  55860. // TODO Axis scale
  55861. // 依赖 PolarModel 做预处理
  55862. /**
  55863. * Resize method bound to the polar
  55864. * @param {module:echarts/coord/polar/PolarModel} polarModel
  55865. * @param {module:echarts/ExtensionAPI} api
  55866. */
  55867. function resizePolar(polar, polarModel, api) {
  55868. var center = polarModel.get('center');
  55869. var width = api.getWidth();
  55870. var height = api.getHeight();
  55871. polar.cx = parsePercent$1(center[0], width);
  55872. polar.cy = parsePercent$1(center[1], height);
  55873. var radiusAxis = polar.getRadiusAxis();
  55874. var size = Math.min(width, height) / 2;
  55875. var radius = parsePercent$1(polarModel.get('radius'), size);
  55876. radiusAxis.inverse
  55877. ? radiusAxis.setExtent(radius, 0)
  55878. : radiusAxis.setExtent(0, radius);
  55879. }
  55880. /**
  55881. * Update polar
  55882. */
  55883. function updatePolarScale(ecModel, api) {
  55884. var polar = this;
  55885. var angleAxis = polar.getAngleAxis();
  55886. var radiusAxis = polar.getRadiusAxis();
  55887. // Reset scale
  55888. angleAxis.scale.setExtent(Infinity, -Infinity);
  55889. radiusAxis.scale.setExtent(Infinity, -Infinity);
  55890. ecModel.eachSeries(function (seriesModel) {
  55891. if (seriesModel.coordinateSystem === polar) {
  55892. var data = seriesModel.getData();
  55893. each$1(data.mapDimension('radius', true), function (dim) {
  55894. radiusAxis.scale.unionExtentFromData(data, dim);
  55895. });
  55896. each$1(data.mapDimension('angle', true), function (dim) {
  55897. angleAxis.scale.unionExtentFromData(data, dim);
  55898. });
  55899. }
  55900. });
  55901. niceScaleExtent(angleAxis.scale, angleAxis.model);
  55902. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  55903. // Fix extent of category angle axis
  55904. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  55905. var extent = angleAxis.getExtent();
  55906. var diff = 360 / angleAxis.scale.count();
  55907. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  55908. angleAxis.setExtent(extent[0], extent[1]);
  55909. }
  55910. }
  55911. /**
  55912. * Set common axis properties
  55913. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  55914. * @param {module:echarts/coord/polar/AxisModel}
  55915. * @inner
  55916. */
  55917. function setAxis(axis, axisModel) {
  55918. axis.type = axisModel.get('type');
  55919. axis.scale = createScaleByModel(axisModel);
  55920. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  55921. axis.inverse = axisModel.get('inverse');
  55922. if (axisModel.mainType === 'angleAxis') {
  55923. axis.inverse ^= axisModel.get('clockwise');
  55924. var startAngle = axisModel.get('startAngle');
  55925. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  55926. }
  55927. // Inject axis instance
  55928. axisModel.axis = axis;
  55929. axis.model = axisModel;
  55930. }
  55931. var polarCreator = {
  55932. dimensions: Polar.prototype.dimensions,
  55933. create: function (ecModel, api) {
  55934. var polarList = [];
  55935. ecModel.eachComponent('polar', function (polarModel, idx) {
  55936. var polar = new Polar(idx);
  55937. // Inject resize and update method
  55938. polar.update = updatePolarScale;
  55939. var radiusAxis = polar.getRadiusAxis();
  55940. var angleAxis = polar.getAngleAxis();
  55941. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  55942. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  55943. setAxis(radiusAxis, radiusAxisModel);
  55944. setAxis(angleAxis, angleAxisModel);
  55945. resizePolar(polar, polarModel, api);
  55946. polarList.push(polar);
  55947. polarModel.coordinateSystem = polar;
  55948. polar.model = polarModel;
  55949. });
  55950. // Inject coordinateSystem to series
  55951. ecModel.eachSeries(function (seriesModel) {
  55952. if (seriesModel.get('coordinateSystem') === 'polar') {
  55953. var polarModel = ecModel.queryComponents({
  55954. mainType: 'polar',
  55955. index: seriesModel.get('polarIndex'),
  55956. id: seriesModel.get('polarId')
  55957. })[0];
  55958. if (__DEV__) {
  55959. if (!polarModel) {
  55960. throw new Error(
  55961. 'Polar "' + retrieve(
  55962. seriesModel.get('polarIndex'),
  55963. seriesModel.get('polarId'),
  55964. 0
  55965. ) + '" not found'
  55966. );
  55967. }
  55968. }
  55969. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  55970. }
  55971. });
  55972. return polarList;
  55973. }
  55974. };
  55975. CoordinateSystemManager.register('polar', polarCreator);
  55976. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  55977. function getAxisLineShape(polar, rExtent, angle) {
  55978. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  55979. var start = polar.coordToPoint([rExtent[0], angle]);
  55980. var end = polar.coordToPoint([rExtent[1], angle]);
  55981. return {
  55982. x1: start[0],
  55983. y1: start[1],
  55984. x2: end[0],
  55985. y2: end[1]
  55986. };
  55987. }
  55988. function getRadiusIdx(polar) {
  55989. var radiusAxis = polar.getRadiusAxis();
  55990. return radiusAxis.inverse ? 0 : 1;
  55991. }
  55992. AxisView.extend({
  55993. type: 'angleAxis',
  55994. axisPointerClass: 'PolarAxisPointer',
  55995. render: function (angleAxisModel, ecModel) {
  55996. this.group.removeAll();
  55997. if (!angleAxisModel.get('show')) {
  55998. return;
  55999. }
  56000. var angleAxis = angleAxisModel.axis;
  56001. var polar = angleAxis.polar;
  56002. var radiusExtent = polar.getRadiusAxis().getExtent();
  56003. var ticksAngles = angleAxis.getTicksCoords();
  56004. if (angleAxis.type !== 'category') {
  56005. // Remove the last tick which will overlap the first tick
  56006. ticksAngles.pop();
  56007. }
  56008. each$1(elementList$1, function (name) {
  56009. if (angleAxisModel.get(name +'.show')
  56010. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  56011. ) {
  56012. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent);
  56013. }
  56014. }, this);
  56015. },
  56016. /**
  56017. * @private
  56018. */
  56019. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56020. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  56021. var circle = new Circle({
  56022. shape: {
  56023. cx: polar.cx,
  56024. cy: polar.cy,
  56025. r: radiusExtent[getRadiusIdx(polar)]
  56026. },
  56027. style: lineStyleModel.getLineStyle(),
  56028. z2: 1,
  56029. silent: true
  56030. });
  56031. circle.style.fill = null;
  56032. this.group.add(circle);
  56033. },
  56034. /**
  56035. * @private
  56036. */
  56037. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56038. var tickModel = angleAxisModel.getModel('axisTick');
  56039. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  56040. var radius = radiusExtent[getRadiusIdx(polar)];
  56041. var lines = map(ticksAngles, function (tickAngle) {
  56042. return new Line({
  56043. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngle)
  56044. });
  56045. });
  56046. this.group.add(mergePath(
  56047. lines, {
  56048. style: defaults(
  56049. tickModel.getModel('lineStyle').getLineStyle(),
  56050. {
  56051. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  56052. }
  56053. )
  56054. }
  56055. ));
  56056. },
  56057. /**
  56058. * @private
  56059. */
  56060. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56061. var axis = angleAxisModel.axis;
  56062. var categoryData = angleAxisModel.getCategories();
  56063. var labelModel = angleAxisModel.getModel('axisLabel');
  56064. var labels = angleAxisModel.getFormattedLabels();
  56065. var labelMargin = labelModel.get('margin');
  56066. var labelsAngles = axis.getLabelsCoords();
  56067. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  56068. for (var i = 0; i < ticksAngles.length; i++) {
  56069. var r = radiusExtent[getRadiusIdx(polar)];
  56070. var p = polar.coordToPoint([r + labelMargin, labelsAngles[i]]);
  56071. var cx = polar.cx;
  56072. var cy = polar.cy;
  56073. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  56074. ? 'center' : (p[0] > cx ? 'left' : 'right');
  56075. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  56076. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  56077. if (categoryData && categoryData[i] && categoryData[i].textStyle) {
  56078. labelModel = new Model(categoryData[i].textStyle, labelModel, labelModel.ecModel);
  56079. }
  56080. var textEl = new Text({silent: true});
  56081. this.group.add(textEl);
  56082. setTextStyle(textEl.style, labelModel, {
  56083. x: p[0],
  56084. y: p[1],
  56085. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  56086. text: labels[i],
  56087. textAlign: labelTextAlign,
  56088. textVerticalAlign: labelTextVerticalAlign
  56089. });
  56090. }
  56091. },
  56092. /**
  56093. * @private
  56094. */
  56095. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56096. var splitLineModel = angleAxisModel.getModel('splitLine');
  56097. var lineStyleModel = splitLineModel.getModel('lineStyle');
  56098. var lineColors = lineStyleModel.get('color');
  56099. var lineCount = 0;
  56100. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  56101. var splitLines = [];
  56102. for (var i = 0; i < ticksAngles.length; i++) {
  56103. var colorIndex = (lineCount++) % lineColors.length;
  56104. splitLines[colorIndex] = splitLines[colorIndex] || [];
  56105. splitLines[colorIndex].push(new Line({
  56106. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i])
  56107. }));
  56108. }
  56109. // Simple optimization
  56110. // Batching the lines if color are the same
  56111. for (var i = 0; i < splitLines.length; i++) {
  56112. this.group.add(mergePath(splitLines[i], {
  56113. style: defaults({
  56114. stroke: lineColors[i % lineColors.length]
  56115. }, lineStyleModel.getLineStyle()),
  56116. silent: true,
  56117. z: angleAxisModel.get('z')
  56118. }));
  56119. }
  56120. },
  56121. /**
  56122. * @private
  56123. */
  56124. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  56125. var splitAreaModel = angleAxisModel.getModel('splitArea');
  56126. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  56127. var areaColors = areaStyleModel.get('color');
  56128. var lineCount = 0;
  56129. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  56130. var splitAreas = [];
  56131. var RADIAN = Math.PI / 180;
  56132. var prevAngle = -ticksAngles[0] * RADIAN;
  56133. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  56134. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  56135. var clockwise = angleAxisModel.get('clockwise');
  56136. for (var i = 1; i < ticksAngles.length; i++) {
  56137. var colorIndex = (lineCount++) % areaColors.length;
  56138. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  56139. splitAreas[colorIndex].push(new Sector({
  56140. shape: {
  56141. cx: polar.cx,
  56142. cy: polar.cy,
  56143. r0: r0,
  56144. r: r1,
  56145. startAngle: prevAngle,
  56146. endAngle: -ticksAngles[i] * RADIAN,
  56147. clockwise: clockwise
  56148. },
  56149. silent: true
  56150. }));
  56151. prevAngle = -ticksAngles[i] * RADIAN;
  56152. }
  56153. // Simple optimization
  56154. // Batching the lines if color are the same
  56155. for (var i = 0; i < splitAreas.length; i++) {
  56156. this.group.add(mergePath(splitAreas[i], {
  56157. style: defaults({
  56158. fill: areaColors[i % areaColors.length]
  56159. }, areaStyleModel.getAreaStyle()),
  56160. silent: true
  56161. }));
  56162. }
  56163. }
  56164. });
  56165. var axisBuilderAttrs$3 = [
  56166. 'axisLine', 'axisTickLabel', 'axisName'
  56167. ];
  56168. var selfBuilderAttrs$1 = [
  56169. 'splitLine', 'splitArea'
  56170. ];
  56171. AxisView.extend({
  56172. type: 'radiusAxis',
  56173. axisPointerClass: 'PolarAxisPointer',
  56174. render: function (radiusAxisModel, ecModel) {
  56175. this.group.removeAll();
  56176. if (!radiusAxisModel.get('show')) {
  56177. return;
  56178. }
  56179. var radiusAxis = radiusAxisModel.axis;
  56180. var polar = radiusAxis.polar;
  56181. var angleAxis = polar.getAngleAxis();
  56182. var ticksCoords = radiusAxis.getTicksCoords();
  56183. var axisAngle = angleAxis.getExtent()[0];
  56184. var radiusExtent = radiusAxis.getExtent();
  56185. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  56186. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  56187. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  56188. this.group.add(axisBuilder.getGroup());
  56189. each$1(selfBuilderAttrs$1, function (name) {
  56190. if (radiusAxisModel.get(name +'.show') && !radiusAxis.scale.isBlank()) {
  56191. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  56192. }
  56193. }, this);
  56194. },
  56195. /**
  56196. * @private
  56197. */
  56198. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  56199. var splitLineModel = radiusAxisModel.getModel('splitLine');
  56200. var lineStyleModel = splitLineModel.getModel('lineStyle');
  56201. var lineColors = lineStyleModel.get('color');
  56202. var lineCount = 0;
  56203. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  56204. var splitLines = [];
  56205. for (var i = 0; i < ticksCoords.length; i++) {
  56206. var colorIndex = (lineCount++) % lineColors.length;
  56207. splitLines[colorIndex] = splitLines[colorIndex] || [];
  56208. splitLines[colorIndex].push(new Circle({
  56209. shape: {
  56210. cx: polar.cx,
  56211. cy: polar.cy,
  56212. r: ticksCoords[i]
  56213. },
  56214. silent: true
  56215. }));
  56216. }
  56217. // Simple optimization
  56218. // Batching the lines if color are the same
  56219. for (var i = 0; i < splitLines.length; i++) {
  56220. this.group.add(mergePath(splitLines[i], {
  56221. style: defaults({
  56222. stroke: lineColors[i % lineColors.length],
  56223. fill: null
  56224. }, lineStyleModel.getLineStyle()),
  56225. silent: true
  56226. }));
  56227. }
  56228. },
  56229. /**
  56230. * @private
  56231. */
  56232. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  56233. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  56234. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  56235. var areaColors = areaStyleModel.get('color');
  56236. var lineCount = 0;
  56237. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  56238. var splitAreas = [];
  56239. var prevRadius = ticksCoords[0];
  56240. for (var i = 1; i < ticksCoords.length; i++) {
  56241. var colorIndex = (lineCount++) % areaColors.length;
  56242. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  56243. splitAreas[colorIndex].push(new Sector({
  56244. shape: {
  56245. cx: polar.cx,
  56246. cy: polar.cy,
  56247. r0: prevRadius,
  56248. r: ticksCoords[i],
  56249. startAngle: 0,
  56250. endAngle: Math.PI * 2
  56251. },
  56252. silent: true
  56253. }));
  56254. prevRadius = ticksCoords[i];
  56255. }
  56256. // Simple optimization
  56257. // Batching the lines if color are the same
  56258. for (var i = 0; i < splitAreas.length; i++) {
  56259. this.group.add(mergePath(splitAreas[i], {
  56260. style: defaults({
  56261. fill: areaColors[i % areaColors.length]
  56262. }, areaStyleModel.getAreaStyle()),
  56263. silent: true
  56264. }));
  56265. }
  56266. }
  56267. });
  56268. /**
  56269. * @inner
  56270. */
  56271. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  56272. return {
  56273. position: [polar.cx, polar.cy],
  56274. rotation: axisAngle / 180 * Math.PI,
  56275. labelDirection: -1,
  56276. tickDirection: -1,
  56277. nameDirection: 1,
  56278. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  56279. // Over splitLine and splitArea
  56280. z2: 1
  56281. };
  56282. }
  56283. var PolarAxisPointer = BaseAxisPointer.extend({
  56284. /**
  56285. * @override
  56286. */
  56287. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  56288. var axis = axisModel.axis;
  56289. if (axis.dim === 'angle') {
  56290. this.animationThreshold = Math.PI / 18;
  56291. }
  56292. var polar = axis.polar;
  56293. var otherAxis = polar.getOtherAxis(axis);
  56294. var otherExtent = otherAxis.getExtent();
  56295. var coordValue;
  56296. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  56297. var axisPointerType = axisPointerModel.get('type');
  56298. if (axisPointerType && axisPointerType !== 'none') {
  56299. var elStyle = buildElStyle(axisPointerModel);
  56300. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  56301. axis, polar, coordValue, otherExtent, elStyle
  56302. );
  56303. pointerOption.style = elStyle;
  56304. elOption.graphicKey = pointerOption.type;
  56305. elOption.pointer = pointerOption;
  56306. }
  56307. var labelMargin = axisPointerModel.get('label.margin');
  56308. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  56309. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  56310. }
  56311. // Do not support handle, utill any user requires it.
  56312. });
  56313. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  56314. var axis = axisModel.axis;
  56315. var coord = axis.dataToCoord(value);
  56316. var axisAngle = polar.getAngleAxis().getExtent()[0];
  56317. axisAngle = axisAngle / 180 * Math.PI;
  56318. var radiusExtent = polar.getRadiusAxis().getExtent();
  56319. var position;
  56320. var align;
  56321. var verticalAlign;
  56322. if (axis.dim === 'radius') {
  56323. var transform = create$1();
  56324. rotate(transform, transform, axisAngle);
  56325. translate(transform, transform, [polar.cx, polar.cy]);
  56326. position = applyTransform$1([coord, -labelMargin], transform);
  56327. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  56328. var labelLayout = AxisBuilder.innerTextLayout(
  56329. axisAngle, labelRotation * Math.PI / 180, -1
  56330. );
  56331. align = labelLayout.textAlign;
  56332. verticalAlign = labelLayout.textVerticalAlign;
  56333. }
  56334. else { // angle axis
  56335. var r = radiusExtent[1];
  56336. position = polar.coordToPoint([r + labelMargin, coord]);
  56337. var cx = polar.cx;
  56338. var cy = polar.cy;
  56339. align = Math.abs(position[0] - cx) / r < 0.3
  56340. ? 'center' : (position[0] > cx ? 'left' : 'right');
  56341. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  56342. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  56343. }
  56344. return {
  56345. position: position,
  56346. align: align,
  56347. verticalAlign: verticalAlign
  56348. };
  56349. }
  56350. var pointerShapeBuilder$2 = {
  56351. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  56352. return axis.dim === 'angle'
  56353. ? {
  56354. type: 'Line',
  56355. shape: makeLineShape(
  56356. polar.coordToPoint([otherExtent[0], coordValue]),
  56357. polar.coordToPoint([otherExtent[1], coordValue])
  56358. )
  56359. }
  56360. : {
  56361. type: 'Circle',
  56362. shape: {
  56363. cx: polar.cx,
  56364. cy: polar.cy,
  56365. r: coordValue
  56366. }
  56367. };
  56368. },
  56369. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  56370. var bandWidth = axis.getBandWidth();
  56371. var radian = Math.PI / 180;
  56372. return axis.dim === 'angle'
  56373. ? {
  56374. type: 'Sector',
  56375. shape: makeSectorShape(
  56376. polar.cx, polar.cy,
  56377. otherExtent[0], otherExtent[1],
  56378. // In ECharts y is negative if angle is positive
  56379. (-coordValue - bandWidth / 2) * radian,
  56380. (-coordValue + bandWidth / 2) * radian
  56381. )
  56382. }
  56383. : {
  56384. type: 'Sector',
  56385. shape: makeSectorShape(
  56386. polar.cx, polar.cy,
  56387. coordValue - bandWidth / 2,
  56388. coordValue + bandWidth / 2,
  56389. 0, Math.PI * 2
  56390. )
  56391. };
  56392. }
  56393. };
  56394. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  56395. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  56396. registerLayout(curry(barLayoutPolar, 'bar'));
  56397. // Polar view
  56398. extendComponentView({
  56399. type: 'polar'
  56400. });
  56401. var GeoModel = ComponentModel.extend({
  56402. type: 'geo',
  56403. /**
  56404. * @type {module:echarts/coord/geo/Geo}
  56405. */
  56406. coordinateSystem: null,
  56407. layoutMode: 'box',
  56408. init: function (option) {
  56409. ComponentModel.prototype.init.apply(this, arguments);
  56410. // Default label emphasis `show`
  56411. defaultEmphasis(option, 'label', ['show']);
  56412. },
  56413. optionUpdated: function () {
  56414. var option = this.option;
  56415. var self = this;
  56416. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  56417. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  56418. if (regionOpt.name) {
  56419. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  56420. }
  56421. return optionModelMap;
  56422. }, createHashMap());
  56423. this.updateSelectedMap(option.regions);
  56424. },
  56425. defaultOption: {
  56426. zlevel: 0,
  56427. z: 0,
  56428. show: true,
  56429. left: 'center',
  56430. top: 'center',
  56431. // width:,
  56432. // height:,
  56433. // right
  56434. // bottom
  56435. // Aspect is width / height. Inited to be geoJson bbox aspect
  56436. // This parameter is used for scale this aspect
  56437. aspectScale: 0.75,
  56438. ///// Layout with center and size
  56439. // If you wan't to put map in a fixed size box with right aspect ratio
  56440. // This two properties may more conveninet
  56441. // layoutCenter: [50%, 50%]
  56442. // layoutSize: 100
  56443. silent: false,
  56444. // Map type
  56445. map: '',
  56446. // Define left-top, right-bottom coords to control view
  56447. // For example, [ [180, 90], [-180, -90] ]
  56448. boundingCoords: null,
  56449. // Default on center of map
  56450. center: null,
  56451. zoom: 1,
  56452. scaleLimit: null,
  56453. // selectedMode: false
  56454. label: {
  56455. show: false,
  56456. color: '#000'
  56457. },
  56458. itemStyle: {
  56459. // color: 各异,
  56460. borderWidth: 0.5,
  56461. borderColor: '#444',
  56462. color: '#eee'
  56463. },
  56464. emphasis: {
  56465. label: {
  56466. show: true,
  56467. color: 'rgb(100,0,0)'
  56468. },
  56469. itemStyle: {
  56470. color: 'rgba(255,215,0,0.8)'
  56471. }
  56472. },
  56473. regions: []
  56474. },
  56475. /**
  56476. * Get model of region
  56477. * @param {string} name
  56478. * @return {module:echarts/model/Model}
  56479. */
  56480. getRegionModel: function (name) {
  56481. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  56482. },
  56483. /**
  56484. * Format label
  56485. * @param {string} name Region name
  56486. * @param {string} [status='normal'] 'normal' or 'emphasis'
  56487. * @return {string}
  56488. */
  56489. getFormattedLabel: function (name, status) {
  56490. var regionModel = this.getRegionModel(name);
  56491. var formatter = regionModel.get('label.' + status + '.formatter');
  56492. var params = {
  56493. name: name
  56494. };
  56495. if (typeof formatter === 'function') {
  56496. params.status = status;
  56497. return formatter(params);
  56498. }
  56499. else if (typeof formatter === 'string') {
  56500. return formatter.replace('{a}', name != null ? name : '');
  56501. }
  56502. },
  56503. setZoom: function (zoom) {
  56504. this.option.zoom = zoom;
  56505. },
  56506. setCenter: function (center) {
  56507. this.option.center = center;
  56508. }
  56509. });
  56510. mixin(GeoModel, selectableMixin);
  56511. extendComponentView({
  56512. type: 'geo',
  56513. init: function (ecModel, api) {
  56514. var mapDraw = new MapDraw(api, true);
  56515. this._mapDraw = mapDraw;
  56516. this.group.add(mapDraw.group);
  56517. },
  56518. render: function (geoModel, ecModel, api, payload) {
  56519. // Not render if it is an toggleSelect action from self
  56520. if (payload && payload.type === 'geoToggleSelect'
  56521. && payload.from === this.uid
  56522. ) {
  56523. return;
  56524. }
  56525. var mapDraw = this._mapDraw;
  56526. if (geoModel.get('show')) {
  56527. mapDraw.draw(geoModel, ecModel, api, this, payload);
  56528. }
  56529. else {
  56530. this._mapDraw.group.removeAll();
  56531. }
  56532. this.group.silent = geoModel.get('silent');
  56533. },
  56534. dispose: function () {
  56535. this._mapDraw && this._mapDraw.remove();
  56536. }
  56537. });
  56538. function makeAction(method, actionInfo) {
  56539. actionInfo.update = 'updateView';
  56540. registerAction(actionInfo, function (payload, ecModel) {
  56541. var selected = {};
  56542. ecModel.eachComponent(
  56543. { mainType: 'geo', query: payload},
  56544. function (geoModel) {
  56545. geoModel[method](payload.name);
  56546. var geo = geoModel.coordinateSystem;
  56547. each$1(geo.regions, function (region) {
  56548. selected[region.name] = geoModel.isSelected(region.name) || false;
  56549. });
  56550. }
  56551. );
  56552. return {
  56553. selected: selected,
  56554. name: payload.name
  56555. };
  56556. });
  56557. }
  56558. makeAction('toggleSelected', {
  56559. type: 'geoToggleSelect',
  56560. event: 'geoselectchanged'
  56561. });
  56562. makeAction('select', {
  56563. type: 'geoSelect',
  56564. event: 'geoselected'
  56565. });
  56566. makeAction('unSelect', {
  56567. type: 'geoUnSelect',
  56568. event: 'geounselected'
  56569. });
  56570. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  56571. var preprocessor$1 = function (option, isNew) {
  56572. var brushComponents = option && option.brush;
  56573. if (!isArray(brushComponents)) {
  56574. brushComponents = brushComponents ? [brushComponents] : [];
  56575. }
  56576. if (!brushComponents.length) {
  56577. return;
  56578. }
  56579. var brushComponentSpecifiedBtns = [];
  56580. each$1(brushComponents, function (brushOpt) {
  56581. var tbs = brushOpt.hasOwnProperty('toolbox')
  56582. ? brushOpt.toolbox : [];
  56583. if (tbs instanceof Array) {
  56584. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  56585. }
  56586. });
  56587. var toolbox = option && option.toolbox;
  56588. if (isArray(toolbox)) {
  56589. toolbox = toolbox[0];
  56590. }
  56591. if (!toolbox) {
  56592. toolbox = {feature: {}};
  56593. option.toolbox = [toolbox];
  56594. }
  56595. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  56596. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  56597. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  56598. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  56599. removeDuplicate(brushTypes);
  56600. if (isNew && !brushTypes.length) {
  56601. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  56602. }
  56603. };
  56604. function removeDuplicate(arr) {
  56605. var map$$1 = {};
  56606. each$1(arr, function (val) {
  56607. map$$1[val] = 1;
  56608. });
  56609. arr.length = 0;
  56610. each$1(map$$1, function (flag, val) {
  56611. arr.push(val);
  56612. });
  56613. }
  56614. /**
  56615. * @file Visual solution, for consistent option specification.
  56616. */
  56617. var each$20 = each$1;
  56618. function hasKeys(obj) {
  56619. if (obj) {
  56620. for (var name in obj){
  56621. if (obj.hasOwnProperty(name)) {
  56622. return true;
  56623. }
  56624. }
  56625. }
  56626. }
  56627. /**
  56628. * @param {Object} option
  56629. * @param {Array.<string>} stateList
  56630. * @param {Function} [supplementVisualOption]
  56631. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  56632. */
  56633. function createVisualMappings(option, stateList, supplementVisualOption) {
  56634. var visualMappings = {};
  56635. each$20(stateList, function (state) {
  56636. var mappings = visualMappings[state] = createMappings();
  56637. each$20(option[state], function (visualData, visualType) {
  56638. if (!VisualMapping.isValidType(visualType)) {
  56639. return;
  56640. }
  56641. var mappingOption = {
  56642. type: visualType,
  56643. visual: visualData
  56644. };
  56645. supplementVisualOption && supplementVisualOption(mappingOption, state);
  56646. mappings[visualType] = new VisualMapping(mappingOption);
  56647. // Prepare a alpha for opacity, for some case that opacity
  56648. // is not supported, such as rendering using gradient color.
  56649. if (visualType === 'opacity') {
  56650. mappingOption = clone(mappingOption);
  56651. mappingOption.type = 'colorAlpha';
  56652. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  56653. }
  56654. });
  56655. });
  56656. return visualMappings;
  56657. function createMappings() {
  56658. var Creater = function () {};
  56659. // Make sure hidden fields will not be visited by
  56660. // object iteration (with hasOwnProperty checking).
  56661. Creater.prototype.__hidden = Creater.prototype;
  56662. var obj = new Creater();
  56663. return obj;
  56664. }
  56665. }
  56666. /**
  56667. * @param {Object} thisOption
  56668. * @param {Object} newOption
  56669. * @param {Array.<string>} keys
  56670. */
  56671. function replaceVisualOption(thisOption, newOption, keys) {
  56672. // Visual attributes merge is not supported, otherwise it
  56673. // brings overcomplicated merge logic. See #2853. So if
  56674. // newOption has anyone of these keys, all of these keys
  56675. // will be reset. Otherwise, all keys remain.
  56676. var has;
  56677. each$1(keys, function (key) {
  56678. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  56679. has = true;
  56680. }
  56681. });
  56682. has && each$1(keys, function (key) {
  56683. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  56684. thisOption[key] = clone(newOption[key]);
  56685. }
  56686. else {
  56687. delete thisOption[key];
  56688. }
  56689. });
  56690. }
  56691. /**
  56692. * @param {Array.<string>} stateList
  56693. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  56694. * @param {module:echarts/data/List} list
  56695. * @param {Function} getValueState param: valueOrIndex, return: state.
  56696. * @param {object} [scope] Scope for getValueState
  56697. * @param {string} [dimension] Concrete dimension, if used.
  56698. */
  56699. // ???! handle brush?
  56700. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  56701. var visualTypesMap = {};
  56702. each$1(stateList, function (state) {
  56703. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  56704. visualTypesMap[state] = visualTypes;
  56705. });
  56706. var dataIndex;
  56707. function getVisual(key) {
  56708. return data.getItemVisual(dataIndex, key);
  56709. }
  56710. function setVisual(key, value) {
  56711. data.setItemVisual(dataIndex, key, value);
  56712. }
  56713. if (dimension == null) {
  56714. data.each(eachItem);
  56715. }
  56716. else {
  56717. data.each([dimension], eachItem);
  56718. }
  56719. function eachItem(valueOrIndex, index) {
  56720. dataIndex = dimension == null ? valueOrIndex : index;
  56721. var rawDataItem = data.getRawDataItem(dataIndex);
  56722. // Consider performance
  56723. if (rawDataItem && rawDataItem.visualMap === false) {
  56724. return;
  56725. }
  56726. var valueState = getValueState.call(scope, valueOrIndex);
  56727. var mappings = visualMappings[valueState];
  56728. var visualTypes = visualTypesMap[valueState];
  56729. for (var i = 0, len = visualTypes.length; i < len; i++) {
  56730. var type = visualTypes[i];
  56731. mappings[type] && mappings[type].applyVisual(
  56732. valueOrIndex, getVisual, setVisual
  56733. );
  56734. }
  56735. }
  56736. }
  56737. /**
  56738. * @param {module:echarts/data/List} data
  56739. * @param {Array.<string>} stateList
  56740. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  56741. * @param {Function} getValueState param: valueOrIndex, return: state.
  56742. * @param {number} [dim] dimension or dimension index.
  56743. */
  56744. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  56745. var visualTypesMap = {};
  56746. each$1(stateList, function (state) {
  56747. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  56748. visualTypesMap[state] = visualTypes;
  56749. });
  56750. function progress(params, data) {
  56751. if (dim != null) {
  56752. dim = data.getDimension(dim);
  56753. }
  56754. function getVisual(key) {
  56755. return data.getItemVisual(dataIndex, key);
  56756. }
  56757. function setVisual(key, value) {
  56758. data.setItemVisual(dataIndex, key, value);
  56759. }
  56760. for (var dataIndex = params.start; dataIndex < params.end; dataIndex++) {
  56761. var rawDataItem = data.getRawDataItem(dataIndex);
  56762. // Consider performance
  56763. if (rawDataItem && rawDataItem.visualMap === false) {
  56764. return;
  56765. }
  56766. var value = dim != null
  56767. ? data.get(dim, dataIndex, true)
  56768. : dataIndex;
  56769. var valueState = getValueState(value);
  56770. var mappings = visualMappings[valueState];
  56771. var visualTypes = visualTypesMap[valueState];
  56772. for (var i = 0, len = visualTypes.length; i < len; i++) {
  56773. var type = visualTypes[i];
  56774. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  56775. }
  56776. }
  56777. }
  56778. return {progress: progress};
  56779. }
  56780. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  56781. // Key of the second level is chart element type: `point`, `rect`.
  56782. // See moudule:echarts/component/helper/BrushController
  56783. // function param:
  56784. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  56785. // {Object} selectors {point: selector, rect: selector, ...}
  56786. // {Object} area {range: [[], [], ..], boudingRect}
  56787. // function return:
  56788. // {boolean} Whether in the given brush.
  56789. var selector = {
  56790. lineX: getLineSelectors(0),
  56791. lineY: getLineSelectors(1),
  56792. rect: {
  56793. point: function (itemLayout, selectors, area) {
  56794. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  56795. },
  56796. rect: function (itemLayout, selectors, area) {
  56797. return itemLayout && area.boundingRect.intersect(itemLayout);
  56798. }
  56799. },
  56800. polygon: {
  56801. point: function (itemLayout, selectors, area) {
  56802. return itemLayout
  56803. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  56804. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  56805. },
  56806. rect: function (itemLayout, selectors, area) {
  56807. var points = area.range;
  56808. if (!itemLayout || points.length <= 1) {
  56809. return false;
  56810. }
  56811. var x = itemLayout.x;
  56812. var y = itemLayout.y;
  56813. var width = itemLayout.width;
  56814. var height = itemLayout.height;
  56815. var p = points[0];
  56816. if (contain$1(points, x, y)
  56817. || contain$1(points, x + width, y)
  56818. || contain$1(points, x, y + height)
  56819. || contain$1(points, x + width, y + height)
  56820. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  56821. || lineIntersectPolygon(x, y, x + width, y, points)
  56822. || lineIntersectPolygon(x, y, x, y + height, points)
  56823. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  56824. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  56825. ) {
  56826. return true;
  56827. }
  56828. }
  56829. }
  56830. };
  56831. function getLineSelectors(xyIndex) {
  56832. var xy = ['x', 'y'];
  56833. var wh = ['width', 'height'];
  56834. return {
  56835. point: function (itemLayout, selectors, area) {
  56836. if (itemLayout) {
  56837. var range = area.range;
  56838. var p = itemLayout[xyIndex];
  56839. return inLineRange(p, range);
  56840. }
  56841. },
  56842. rect: function (itemLayout, selectors, area) {
  56843. if (itemLayout) {
  56844. var range = area.range;
  56845. var layoutRange = [
  56846. itemLayout[xy[xyIndex]],
  56847. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  56848. ];
  56849. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  56850. return inLineRange(layoutRange[0], range)
  56851. || inLineRange(layoutRange[1], range)
  56852. || inLineRange(range[0], layoutRange)
  56853. || inLineRange(range[1], layoutRange);
  56854. }
  56855. }
  56856. };
  56857. }
  56858. function inLineRange(p, range) {
  56859. return range[0] <= p && p <= range[1];
  56860. }
  56861. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  56862. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  56863. var p = points[i];
  56864. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  56865. return true;
  56866. }
  56867. p2 = p;
  56868. }
  56869. }
  56870. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  56871. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  56872. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  56873. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  56874. if (nearZero(delta)) { // parallel
  56875. return false;
  56876. }
  56877. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  56878. if (namenda < 0 || namenda > 1) {
  56879. return false;
  56880. }
  56881. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  56882. if (miu < 0 || miu > 1) {
  56883. return false;
  56884. }
  56885. return true;
  56886. }
  56887. function nearZero(val) {
  56888. return val <= (1e-6) && val >= -(1e-6);
  56889. }
  56890. function determinant(v1, v2, v3, v4) {
  56891. return v1 * v4 - v2 * v3;
  56892. }
  56893. var each$21 = each$1;
  56894. var indexOf$1 = indexOf;
  56895. var curry$5 = curry;
  56896. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  56897. // FIXME
  56898. // how to genarialize to more coordinate systems.
  56899. var INCLUDE_FINDER_MAIN_TYPES = [
  56900. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  56901. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  56902. ];
  56903. /**
  56904. * [option in constructor]:
  56905. * {
  56906. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  56907. * }
  56908. *
  56909. *
  56910. * [targetInfo]:
  56911. *
  56912. * There can be multiple axes in a single targetInfo. Consider the case
  56913. * of `grid` component, a targetInfo represents a grid which contains one or more
  56914. * cartesian and one or more axes. And consider the case of parallel system,
  56915. * which has multiple axes in a coordinate system.
  56916. * Can be {
  56917. * panelId: ...,
  56918. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  56919. * coordSyses: all cartesians.
  56920. * gridModel: <grid component>
  56921. * xAxes: correspond to coordSyses on index
  56922. * yAxes: correspond to coordSyses on index
  56923. * }
  56924. * or {
  56925. * panelId: ...,
  56926. * coordSys: <geo coord sys>
  56927. * coordSyses: [<geo coord sys>]
  56928. * geoModel: <geo component>
  56929. * }
  56930. *
  56931. *
  56932. * [panelOpt]:
  56933. *
  56934. * Make from targetInfo. Input to BrushController.
  56935. * {
  56936. * panelId: ...,
  56937. * rect: ...
  56938. * }
  56939. *
  56940. *
  56941. * [area]:
  56942. *
  56943. * Generated by BrushController or user input.
  56944. * {
  56945. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  56946. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  56947. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  56948. * range: pixel range.
  56949. * coordRange: representitive coord range (the first one of coordRanges).
  56950. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  56951. * }
  56952. */
  56953. /**
  56954. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  56955. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  56956. * @param {module:echarts/model/Global} ecModel
  56957. * @param {Object} [opt]
  56958. * @param {Array.<string>} [opt.include] include coordinate system types.
  56959. */
  56960. function BrushTargetManager(option, ecModel, opt) {
  56961. /**
  56962. * @private
  56963. * @type {Array.<Object>}
  56964. */
  56965. var targetInfoList = this._targetInfoList = [];
  56966. var info = {};
  56967. var foundCpts = parseFinder$1(ecModel, option);
  56968. each$21(targetInfoBuilders, function (builder, type) {
  56969. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  56970. builder(foundCpts, targetInfoList, info);
  56971. }
  56972. });
  56973. }
  56974. var proto$2 = BrushTargetManager.prototype;
  56975. proto$2.setOutputRanges = function (areas, ecModel) {
  56976. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  56977. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  56978. // area.coordRange is the first of area.coordRanges
  56979. if (!area.coordRange) {
  56980. area.coordRange = coordRange;
  56981. // In 'category' axis, coord to pixel is not reversible, so we can not
  56982. // rebuild range by coordRange accrately, which may bring trouble when
  56983. // brushing only one item. So we use __rangeOffset to rebuilding range
  56984. // by coordRange. And this it only used in brush component so it is no
  56985. // need to be adapted to coordRanges.
  56986. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  56987. area.__rangeOffset = {
  56988. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  56989. xyMinMax: result.xyMinMax
  56990. };
  56991. }
  56992. });
  56993. };
  56994. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  56995. each$21(areas, function (area) {
  56996. var targetInfo = this.findTargetInfo(area, ecModel);
  56997. if (targetInfo && targetInfo !== true) {
  56998. each$1(
  56999. targetInfo.coordSyses,
  57000. function (coordSys) {
  57001. var result = coordConvert[area.brushType](1, coordSys, area.range);
  57002. cb(area, result.values, coordSys, ecModel);
  57003. }
  57004. );
  57005. }
  57006. }, this);
  57007. };
  57008. proto$2.setInputRanges = function (areas, ecModel) {
  57009. each$21(areas, function (area) {
  57010. var targetInfo = this.findTargetInfo(area, ecModel);
  57011. if (__DEV__) {
  57012. assert$1(
  57013. !targetInfo || targetInfo === true || area.coordRange,
  57014. 'coordRange must be specified when coord index specified.'
  57015. );
  57016. assert$1(
  57017. !targetInfo || targetInfo !== true || area.range,
  57018. 'range must be specified in global brush.'
  57019. );
  57020. }
  57021. area.range = area.range || [];
  57022. // convert coordRange to global range and set panelId.
  57023. if (targetInfo && targetInfo !== true) {
  57024. area.panelId = targetInfo.panelId;
  57025. // (1) area.range shoule always be calculate from coordRange but does
  57026. // not keep its original value, for the sake of the dataZoom scenario,
  57027. // where area.coordRange remains unchanged but area.range may be changed.
  57028. // (2) Only support converting one coordRange to pixel range in brush
  57029. // component. So do not consider `coordRanges`.
  57030. // (3) About __rangeOffset, see comment above.
  57031. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  57032. var rangeOffset = area.__rangeOffset;
  57033. area.range = rangeOffset
  57034. ? diffProcessor[area.brushType](
  57035. result.values,
  57036. rangeOffset.offset,
  57037. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  57038. )
  57039. : result.values;
  57040. }
  57041. }, this);
  57042. };
  57043. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  57044. return map(this._targetInfoList, function (targetInfo) {
  57045. var rect = targetInfo.getPanelRect();
  57046. return {
  57047. panelId: targetInfo.panelId,
  57048. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  57049. clipPath: makeRectPanelClipPath(rect),
  57050. isTargetByCursor: makeRectIsTargetByCursor(
  57051. rect, api, targetInfo.coordSysModel
  57052. ),
  57053. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  57054. };
  57055. });
  57056. };
  57057. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  57058. // Check whether area is bound in coord, and series do not belong to that coord.
  57059. // If do not do this check, some brush (like lineX) will controll all axes.
  57060. var targetInfo = this.findTargetInfo(area, ecModel);
  57061. return targetInfo === true || (
  57062. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  57063. );
  57064. };
  57065. /**
  57066. * If return Object, a coord found.
  57067. * If reutrn true, global found.
  57068. * Otherwise nothing found.
  57069. *
  57070. * @param {Object} area
  57071. * @param {Array} targetInfoList
  57072. * @return {Object|boolean}
  57073. */
  57074. proto$2.findTargetInfo = function (area, ecModel) {
  57075. var targetInfoList = this._targetInfoList;
  57076. var foundCpts = parseFinder$1(ecModel, area);
  57077. for (var i = 0; i < targetInfoList.length; i++) {
  57078. var targetInfo = targetInfoList[i];
  57079. var areaPanelId = area.panelId;
  57080. if (areaPanelId) {
  57081. if (targetInfo.panelId === areaPanelId) {
  57082. return targetInfo;
  57083. }
  57084. }
  57085. else {
  57086. for (var i = 0; i < targetInfoMatchers.length; i++) {
  57087. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  57088. return targetInfo;
  57089. }
  57090. }
  57091. }
  57092. }
  57093. return true;
  57094. };
  57095. function formatMinMax(minMax) {
  57096. minMax[0] > minMax[1] && minMax.reverse();
  57097. return minMax;
  57098. }
  57099. function parseFinder$1(ecModel, option) {
  57100. return parseFinder(
  57101. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  57102. );
  57103. }
  57104. var targetInfoBuilders = {
  57105. grid: function (foundCpts, targetInfoList) {
  57106. var xAxisModels = foundCpts.xAxisModels;
  57107. var yAxisModels = foundCpts.yAxisModels;
  57108. var gridModels = foundCpts.gridModels;
  57109. // Remove duplicated.
  57110. var gridModelMap = createHashMap();
  57111. var xAxesHas = {};
  57112. var yAxesHas = {};
  57113. if (!xAxisModels && !yAxisModels && !gridModels) {
  57114. return;
  57115. }
  57116. each$21(xAxisModels, function (axisModel) {
  57117. var gridModel = axisModel.axis.grid.model;
  57118. gridModelMap.set(gridModel.id, gridModel);
  57119. xAxesHas[gridModel.id] = true;
  57120. });
  57121. each$21(yAxisModels, function (axisModel) {
  57122. var gridModel = axisModel.axis.grid.model;
  57123. gridModelMap.set(gridModel.id, gridModel);
  57124. yAxesHas[gridModel.id] = true;
  57125. });
  57126. each$21(gridModels, function (gridModel) {
  57127. gridModelMap.set(gridModel.id, gridModel);
  57128. xAxesHas[gridModel.id] = true;
  57129. yAxesHas[gridModel.id] = true;
  57130. });
  57131. gridModelMap.each(function (gridModel) {
  57132. var grid = gridModel.coordinateSystem;
  57133. var cartesians = [];
  57134. each$21(grid.getCartesians(), function (cartesian, index) {
  57135. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  57136. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  57137. ) {
  57138. cartesians.push(cartesian);
  57139. }
  57140. });
  57141. targetInfoList.push({
  57142. panelId: 'grid--' + gridModel.id,
  57143. gridModel: gridModel,
  57144. coordSysModel: gridModel,
  57145. // Use the first one as the representitive coordSys.
  57146. coordSys: cartesians[0],
  57147. coordSyses: cartesians,
  57148. getPanelRect: panelRectBuilder.grid,
  57149. xAxisDeclared: xAxesHas[gridModel.id],
  57150. yAxisDeclared: yAxesHas[gridModel.id]
  57151. });
  57152. });
  57153. },
  57154. geo: function (foundCpts, targetInfoList) {
  57155. each$21(foundCpts.geoModels, function (geoModel) {
  57156. var coordSys = geoModel.coordinateSystem;
  57157. targetInfoList.push({
  57158. panelId: 'geo--' + geoModel.id,
  57159. geoModel: geoModel,
  57160. coordSysModel: geoModel,
  57161. coordSys: coordSys,
  57162. coordSyses: [coordSys],
  57163. getPanelRect: panelRectBuilder.geo
  57164. });
  57165. });
  57166. }
  57167. };
  57168. var targetInfoMatchers = [
  57169. // grid
  57170. function (foundCpts, targetInfo) {
  57171. var xAxisModel = foundCpts.xAxisModel;
  57172. var yAxisModel = foundCpts.yAxisModel;
  57173. var gridModel = foundCpts.gridModel;
  57174. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  57175. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  57176. return gridModel && gridModel === targetInfo.gridModel;
  57177. },
  57178. // geo
  57179. function (foundCpts, targetInfo) {
  57180. var geoModel = foundCpts.geoModel;
  57181. return geoModel && geoModel === targetInfo.geoModel;
  57182. }
  57183. ];
  57184. var panelRectBuilder = {
  57185. grid: function () {
  57186. // grid is not Transformable.
  57187. return this.coordSys.grid.getRect().clone();
  57188. },
  57189. geo: function () {
  57190. var coordSys = this.coordSys;
  57191. var rect = coordSys.getBoundingRect().clone();
  57192. // geo roam and zoom transform
  57193. rect.applyTransform(getTransform(coordSys));
  57194. return rect;
  57195. }
  57196. };
  57197. var coordConvert = {
  57198. lineX: curry$5(axisConvert, 0),
  57199. lineY: curry$5(axisConvert, 1),
  57200. rect: function (to, coordSys, rangeOrCoordRange) {
  57201. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  57202. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  57203. var values = [
  57204. formatMinMax([xminymin[0], xmaxymax[0]]),
  57205. formatMinMax([xminymin[1], xmaxymax[1]])
  57206. ];
  57207. return {values: values, xyMinMax: values};
  57208. },
  57209. polygon: function (to, coordSys, rangeOrCoordRange) {
  57210. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  57211. var values = map(rangeOrCoordRange, function (item) {
  57212. var p = coordSys[COORD_CONVERTS[to]](item);
  57213. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  57214. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  57215. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  57216. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  57217. return p;
  57218. });
  57219. return {values: values, xyMinMax: xyMinMax};
  57220. }
  57221. };
  57222. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  57223. if (__DEV__) {
  57224. assert$1(
  57225. coordSys.type === 'cartesian2d',
  57226. 'lineX/lineY brush is available only in cartesian2d.'
  57227. );
  57228. }
  57229. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  57230. var values = formatMinMax(map([0, 1], function (i) {
  57231. return to
  57232. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  57233. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  57234. }));
  57235. var xyMinMax = [];
  57236. xyMinMax[axisNameIndex] = values;
  57237. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  57238. return {values: values, xyMinMax: xyMinMax};
  57239. }
  57240. var diffProcessor = {
  57241. lineX: curry$5(axisDiffProcessor, 0),
  57242. lineY: curry$5(axisDiffProcessor, 1),
  57243. rect: function (values, refer, scales) {
  57244. return [
  57245. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  57246. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  57247. ];
  57248. },
  57249. polygon: function (values, refer, scales) {
  57250. return map(values, function (item, idx) {
  57251. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  57252. });
  57253. }
  57254. };
  57255. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  57256. return [
  57257. values[0] - scales[axisNameIndex] * refer[0],
  57258. values[1] - scales[axisNameIndex] * refer[1]
  57259. ];
  57260. }
  57261. // We have to process scale caused by dataZoom manually,
  57262. // although it might be not accurate.
  57263. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  57264. var sizeCurr = getSize(xyMinMaxCurr);
  57265. var sizeOrigin = getSize(xyMinMaxOrigin);
  57266. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  57267. isNaN(scales[0]) && (scales[0] = 1);
  57268. isNaN(scales[1]) && (scales[1] = 1);
  57269. return scales;
  57270. }
  57271. function getSize(xyMinMax) {
  57272. return xyMinMax
  57273. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  57274. : [NaN, NaN];
  57275. }
  57276. var STATE_LIST = ['inBrush', 'outOfBrush'];
  57277. var DISPATCH_METHOD = '__ecBrushSelect';
  57278. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  57279. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  57280. /**
  57281. * Layout for visual, the priority higher than other layout, and before brush visual.
  57282. */
  57283. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  57284. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  57285. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  57286. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  57287. );
  57288. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  57289. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  57290. });
  57291. });
  57292. /**
  57293. * Register the visual encoding if this modules required.
  57294. */
  57295. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  57296. var brushSelected = [];
  57297. var throttleType;
  57298. var throttleDelay;
  57299. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  57300. var thisBrushSelected = {
  57301. brushId: brushModel.id,
  57302. brushIndex: brushIndex,
  57303. brushName: brushModel.name,
  57304. areas: clone(brushModel.areas),
  57305. selected: []
  57306. };
  57307. // Every brush component exists in event params, convenient
  57308. // for user to find by index.
  57309. brushSelected.push(thisBrushSelected);
  57310. var brushOption = brushModel.option;
  57311. var brushLink = brushOption.brushLink;
  57312. var linkedSeriesMap = [];
  57313. var selectedDataIndexForLink = [];
  57314. var rangeInfoBySeries = [];
  57315. var hasBrushExists = 0;
  57316. if (!brushIndex) { // Only the first throttle setting works.
  57317. throttleType = brushOption.throttleType;
  57318. throttleDelay = brushOption.throttleDelay;
  57319. }
  57320. // Add boundingRect and selectors to range.
  57321. var areas = map(brushModel.areas, function (area) {
  57322. return bindSelector(
  57323. defaults(
  57324. {boundingRect: boundingRectBuilders[area.brushType](area)},
  57325. area
  57326. )
  57327. );
  57328. });
  57329. var visualMappings = createVisualMappings(
  57330. brushModel.option, STATE_LIST, function (mappingOption) {
  57331. mappingOption.mappingMethod = 'fixed';
  57332. }
  57333. );
  57334. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  57335. linkedSeriesMap[seriesIndex] = 1;
  57336. });
  57337. function linkOthers(seriesIndex) {
  57338. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  57339. }
  57340. // If no supported brush or no brush on the series,
  57341. // all visuals should be in original state.
  57342. function brushed(rangeInfoList) {
  57343. return !!rangeInfoList.length;
  57344. }
  57345. /**
  57346. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  57347. *
  57348. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  57349. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  57350. * └!hasBrushExist┘ └nothing.
  57351. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  57352. * └!hasBrushExist┘ └nothing.
  57353. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  57354. * !brushed┘ └nothing.
  57355. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  57356. */
  57357. // Step A
  57358. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  57359. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  57360. seriesModel.subType === 'parallel'
  57361. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  57362. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  57363. });
  57364. function stepAParallel(seriesModel, seriesIndex) {
  57365. var coordSys = seriesModel.coordinateSystem;
  57366. hasBrushExists |= coordSys.hasAxisBrushed();
  57367. linkOthers(seriesIndex) && coordSys.eachActiveState(
  57368. seriesModel.getData(),
  57369. function (activeState, dataIndex) {
  57370. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  57371. }
  57372. );
  57373. }
  57374. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  57375. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  57376. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  57377. return;
  57378. }
  57379. each$1(areas, function (area) {
  57380. selectorsByBrushType[area.brushType]
  57381. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  57382. && rangeInfoList.push(area);
  57383. hasBrushExists |= brushed(rangeInfoList);
  57384. });
  57385. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  57386. var data = seriesModel.getData();
  57387. data.each(function (dataIndex) {
  57388. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  57389. selectedDataIndexForLink[dataIndex] = 1;
  57390. }
  57391. });
  57392. }
  57393. }
  57394. // Step B
  57395. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  57396. var seriesBrushSelected = {
  57397. seriesId: seriesModel.id,
  57398. seriesIndex: seriesIndex,
  57399. seriesName: seriesModel.name,
  57400. dataIndex: []
  57401. };
  57402. // Every series exists in event params, convenient
  57403. // for user to find series by seriesIndex.
  57404. thisBrushSelected.selected.push(seriesBrushSelected);
  57405. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  57406. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  57407. var data = seriesModel.getData();
  57408. var getValueState = linkOthers(seriesIndex)
  57409. ? function (dataIndex) {
  57410. return selectedDataIndexForLink[dataIndex]
  57411. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  57412. : 'outOfBrush';
  57413. }
  57414. : function (dataIndex) {
  57415. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  57416. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  57417. : 'outOfBrush';
  57418. };
  57419. // If no supported brush or no brush, all visuals are in original state.
  57420. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  57421. && applyVisual(
  57422. STATE_LIST, visualMappings, data, getValueState
  57423. );
  57424. });
  57425. });
  57426. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  57427. });
  57428. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  57429. // This event will not be triggered when `setOpion`, otherwise dead lock may
  57430. // triggered when do `setOption` in event listener, which we do not find
  57431. // satisfactory way to solve yet. Some considered resolutions:
  57432. // (a) Diff with prevoius selected data ant only trigger event when changed.
  57433. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  57434. // also detect value changes in selected data) might bring complexity or fragility.
  57435. // (b) Use spectial param like `silent` to suppress event triggering.
  57436. // But such kind of volatile param may be weird in `setOption`.
  57437. if (!payload) {
  57438. return;
  57439. }
  57440. var zr = api.getZr();
  57441. if (zr[DISPATCH_FLAG]) {
  57442. return;
  57443. }
  57444. if (!zr[DISPATCH_METHOD]) {
  57445. zr[DISPATCH_METHOD] = doDispatch;
  57446. }
  57447. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  57448. fn(api, brushSelected);
  57449. }
  57450. function doDispatch(api, brushSelected) {
  57451. if (!api.isDisposed()) {
  57452. var zr = api.getZr();
  57453. zr[DISPATCH_FLAG] = true;
  57454. api.dispatchAction({
  57455. type: 'brushSelect',
  57456. batch: brushSelected
  57457. });
  57458. zr[DISPATCH_FLAG] = false;
  57459. }
  57460. }
  57461. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  57462. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  57463. var area = rangeInfoList[i];
  57464. if (selectorsByBrushType[area.brushType](
  57465. dataIndex, data, area.selectors, area
  57466. )) {
  57467. return true;
  57468. }
  57469. }
  57470. }
  57471. function getSelectorsByBrushType(seriesModel) {
  57472. var brushSelector = seriesModel.brushSelector;
  57473. if (isString(brushSelector)) {
  57474. var sels = [];
  57475. each$1(selector, function (selectorsByElementType, brushType) {
  57476. sels[brushType] = function (dataIndex, data, selectors, area) {
  57477. var itemLayout = data.getItemLayout(dataIndex);
  57478. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  57479. };
  57480. });
  57481. return sels;
  57482. }
  57483. else if (isFunction$1(brushSelector)) {
  57484. var bSelector = {};
  57485. each$1(selector, function (sel, brushType) {
  57486. bSelector[brushType] = brushSelector;
  57487. });
  57488. return bSelector;
  57489. }
  57490. return brushSelector;
  57491. }
  57492. function brushModelNotControll(brushModel, seriesIndex) {
  57493. var seriesIndices = brushModel.option.seriesIndex;
  57494. return seriesIndices != null
  57495. && seriesIndices !== 'all'
  57496. && (
  57497. isArray(seriesIndices)
  57498. ? indexOf(seriesIndices, seriesIndex) < 0
  57499. : seriesIndex !== seriesIndices
  57500. );
  57501. }
  57502. function bindSelector(area) {
  57503. var selectors = area.selectors = {};
  57504. each$1(selector[area.brushType], function (selFn, elType) {
  57505. // Do not use function binding or curry for performance.
  57506. selectors[elType] = function (itemLayout) {
  57507. return selFn(itemLayout, selectors, area);
  57508. };
  57509. });
  57510. return area;
  57511. }
  57512. var boundingRectBuilders = {
  57513. lineX: noop,
  57514. lineY: noop,
  57515. rect: function (area) {
  57516. return getBoundingRectFromMinMax(area.range);
  57517. },
  57518. polygon: function (area) {
  57519. var minMax;
  57520. var range = area.range;
  57521. for (var i = 0, len = range.length; i < len; i++) {
  57522. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  57523. var rg = range[i];
  57524. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  57525. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  57526. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  57527. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  57528. }
  57529. return minMax && getBoundingRectFromMinMax(minMax);
  57530. }
  57531. };
  57532. function getBoundingRectFromMinMax(minMax) {
  57533. return new BoundingRect(
  57534. minMax[0][0],
  57535. minMax[1][0],
  57536. minMax[0][1] - minMax[0][0],
  57537. minMax[1][1] - minMax[1][0]
  57538. );
  57539. }
  57540. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  57541. var BrushModel = extendComponentModel({
  57542. type: 'brush',
  57543. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  57544. /**
  57545. * @protected
  57546. */
  57547. defaultOption: {
  57548. // inBrush: null,
  57549. // outOfBrush: null,
  57550. toolbox: null, // Default value see preprocessor.
  57551. brushLink: null, // Series indices array, broadcast using dataIndex.
  57552. // or 'all', which means all series. 'none' or null means no series.
  57553. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  57554. geoIndex: null, //
  57555. xAxisIndex: null,
  57556. yAxisIndex: null,
  57557. brushType: 'rect', // Default brushType, see BrushController.
  57558. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  57559. transformable: true, // Default transformable.
  57560. brushStyle: { // Default brushStyle
  57561. borderWidth: 1,
  57562. color: 'rgba(120,140,180,0.3)',
  57563. borderColor: 'rgba(120,140,180,0.8)'
  57564. },
  57565. throttleType: 'fixRate',// Throttle in brushSelected event. 'fixRate' or 'debounce'.
  57566. // If null, no throttle. Valid only in the first brush component
  57567. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  57568. // FIXME
  57569. // 试验效果
  57570. removeOnClick: true,
  57571. z: 10000
  57572. },
  57573. /**
  57574. * @readOnly
  57575. * @type {Array.<Object>}
  57576. */
  57577. areas: [],
  57578. /**
  57579. * Current activated brush type.
  57580. * If null, brush is inactived.
  57581. * see module:echarts/component/helper/BrushController
  57582. * @readOnly
  57583. * @type {string}
  57584. */
  57585. brushType: null,
  57586. /**
  57587. * Current brush opt.
  57588. * see module:echarts/component/helper/BrushController
  57589. * @readOnly
  57590. * @type {Object}
  57591. */
  57592. brushOption: {},
  57593. /**
  57594. * @readOnly
  57595. * @type {Array.<Object>}
  57596. */
  57597. coordInfoList: [],
  57598. optionUpdated: function (newOption, isInit) {
  57599. var thisOption = this.option;
  57600. !isInit && replaceVisualOption(
  57601. thisOption, newOption, ['inBrush', 'outOfBrush']
  57602. );
  57603. thisOption.inBrush = thisOption.inBrush || {};
  57604. // Always give default visual, consider setOption at the second time.
  57605. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  57606. },
  57607. /**
  57608. * If ranges is null/undefined, range state remain.
  57609. *
  57610. * @param {Array.<Object>} [ranges]
  57611. */
  57612. setAreas: function (areas) {
  57613. if (__DEV__) {
  57614. assert$1(isArray(areas));
  57615. each$1(areas, function (area) {
  57616. assert$1(area.brushType, 'Illegal areas');
  57617. });
  57618. }
  57619. // If ranges is null/undefined, range state remain.
  57620. // This helps user to dispatchAction({type: 'brush'}) with no areas
  57621. // set but just want to get the current brush select info from a `brush` event.
  57622. if (!areas) {
  57623. return;
  57624. }
  57625. this.areas = map(areas, function (area) {
  57626. return generateBrushOption(this.option, area);
  57627. }, this);
  57628. },
  57629. /**
  57630. * see module:echarts/component/helper/BrushController
  57631. * @param {Object} brushOption
  57632. */
  57633. setBrushOption: function (brushOption) {
  57634. this.brushOption = generateBrushOption(this.option, brushOption);
  57635. this.brushType = this.brushOption.brushType;
  57636. }
  57637. });
  57638. function generateBrushOption(option, brushOption) {
  57639. return merge(
  57640. {
  57641. brushType: option.brushType,
  57642. brushMode: option.brushMode,
  57643. transformable: option.transformable,
  57644. brushStyle: new Model(option.brushStyle).getItemStyle(),
  57645. removeOnClick: option.removeOnClick,
  57646. z: option.z
  57647. },
  57648. brushOption,
  57649. true
  57650. );
  57651. }
  57652. extendComponentView({
  57653. type: 'brush',
  57654. init: function (ecModel, api) {
  57655. /**
  57656. * @readOnly
  57657. * @type {module:echarts/model/Global}
  57658. */
  57659. this.ecModel = ecModel;
  57660. /**
  57661. * @readOnly
  57662. * @type {module:echarts/ExtensionAPI}
  57663. */
  57664. this.api = api;
  57665. /**
  57666. * @readOnly
  57667. * @type {module:echarts/component/brush/BrushModel}
  57668. */
  57669. this.model;
  57670. /**
  57671. * @private
  57672. * @type {module:echarts/component/helper/BrushController}
  57673. */
  57674. (this._brushController = new BrushController(api.getZr()))
  57675. .on('brush', bind(this._onBrush, this))
  57676. .mount();
  57677. },
  57678. /**
  57679. * @override
  57680. */
  57681. render: function (brushModel) {
  57682. this.model = brushModel;
  57683. return updateController.apply(this, arguments);
  57684. },
  57685. /**
  57686. * @override
  57687. */
  57688. updateTransform: updateController,
  57689. /**
  57690. * @override
  57691. */
  57692. updateView: updateController,
  57693. // /**
  57694. // * @override
  57695. // */
  57696. // updateLayout: updateController,
  57697. // /**
  57698. // * @override
  57699. // */
  57700. // updateVisual: updateController,
  57701. /**
  57702. * @override
  57703. */
  57704. dispose: function () {
  57705. this._brushController.dispose();
  57706. },
  57707. /**
  57708. * @private
  57709. */
  57710. _onBrush: function (areas, opt) {
  57711. var modelId = this.model.id;
  57712. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  57713. // Action is not dispatched on drag end, because the drag end
  57714. // emits the same params with the last drag move event, and
  57715. // may have some delay when using touch pad, which makes
  57716. // animation not smooth (when using debounce).
  57717. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  57718. type: 'brush',
  57719. brushId: modelId,
  57720. areas: clone(areas),
  57721. $from: modelId
  57722. });
  57723. }
  57724. });
  57725. function updateController(brushModel, ecModel, api, payload) {
  57726. // Do not update controller when drawing.
  57727. (!payload || payload.$from !== brushModel.id) && this._brushController
  57728. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  57729. .enableBrush(brushModel.brushOption)
  57730. .updateCovers(brushModel.areas.slice());
  57731. }
  57732. /**
  57733. * payload: {
  57734. * brushIndex: number, or,
  57735. * brushId: string, or,
  57736. * brushName: string,
  57737. * globalRanges: Array
  57738. * }
  57739. */
  57740. registerAction(
  57741. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  57742. function (payload, ecModel) {
  57743. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  57744. brushModel.setAreas(payload.areas);
  57745. });
  57746. }
  57747. );
  57748. /**
  57749. * payload: {
  57750. * brushComponents: [
  57751. * {
  57752. * brushId,
  57753. * brushIndex,
  57754. * brushName,
  57755. * series: [
  57756. * {
  57757. * seriesId,
  57758. * seriesIndex,
  57759. * seriesName,
  57760. * rawIndices: [21, 34, ...]
  57761. * },
  57762. * ...
  57763. * ]
  57764. * },
  57765. * ...
  57766. * ]
  57767. * }
  57768. */
  57769. registerAction(
  57770. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  57771. function () {}
  57772. );
  57773. var features = {};
  57774. function register$1(name, ctor) {
  57775. features[name] = ctor;
  57776. }
  57777. function get$1(name) {
  57778. return features[name];
  57779. }
  57780. var brushLang = lang.toolbox.brush;
  57781. function Brush(model, ecModel, api) {
  57782. this.model = model;
  57783. this.ecModel = ecModel;
  57784. this.api = api;
  57785. /**
  57786. * @private
  57787. * @type {string}
  57788. */
  57789. this._brushType;
  57790. /**
  57791. * @private
  57792. * @type {string}
  57793. */
  57794. this._brushMode;
  57795. }
  57796. Brush.defaultOption = {
  57797. show: true,
  57798. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  57799. icon: {
  57800. rect: 'M7.3,34.7 M0.4,10V-0.2h9.8 M89.6,10V-0.2h-9.8 M0.4,60v10.2h9.8 M89.6,60v10.2h-9.8 M12.3,22.4V10.5h13.1 M33.6,10.5h7.8 M49.1,10.5h7.8 M77.5,22.4V10.5h-13 M12.3,31.1v8.2 M77.7,31.1v8.2 M12.3,47.6v11.9h13.1 M33.6,59.5h7.6 M49.1,59.5 h7.7 M77.5,47.6v11.9h-13', // jshint ignore:line
  57801. polygon: 'M55.2,34.9c1.7,0,3.1,1.4,3.1,3.1s-1.4,3.1-3.1,3.1 s-3.1-1.4-3.1-3.1S53.5,34.9,55.2,34.9z M50.4,51c1.7,0,3.1,1.4,3.1,3.1c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1 C47.3,52.4,48.7,51,50.4,51z M55.6,37.1l1.5-7.8 M60.1,13.5l1.6-8.7l-7.8,4 M59,19l-1,5.3 M24,16.1l6.4,4.9l6.4-3.3 M48.5,11.6 l-5.9,3.1 M19.1,12.8L9.7,5.1l1.1,7.7 M13.4,29.8l1,7.3l6.6,1.6 M11.6,18.4l1,6.1 M32.8,41.9 M26.6,40.4 M27.3,40.2l6.1,1.6 M49.9,52.1l-5.6-7.6l-4.9-1.2', // jshint ignore:line
  57802. lineX: 'M15.2,30 M19.7,15.6V1.9H29 M34.8,1.9H40.4 M55.3,15.6V1.9H45.9 M19.7,44.4V58.1H29 M34.8,58.1H40.4 M55.3,44.4 V58.1H45.9 M12.5,20.3l-9.4,9.6l9.6,9.8 M3.1,29.9h16.5 M62.5,20.3l9.4,9.6L62.3,39.7 M71.9,29.9H55.4', // jshint ignore:line
  57803. lineY: 'M38.8,7.7 M52.7,12h13.2v9 M65.9,26.6V32 M52.7,46.3h13.2v-9 M24.9,12H11.8v9 M11.8,26.6V32 M24.9,46.3H11.8v-9 M48.2,5.1l-9.3-9l-9.4,9.2 M38.9-3.9V12 M48.2,53.3l-9.3,9l-9.4-9.2 M38.9,62.3V46.4', // jshint ignore:line
  57804. keep: 'M4,10.5V1h10.3 M20.7,1h6.1 M33,1h6.1 M55.4,10.5V1H45.2 M4,17.3v6.6 M55.6,17.3v6.6 M4,30.5V40h10.3 M20.7,40 h6.1 M33,40h6.1 M55.4,30.5V40H45.2 M21,18.9h62.9v48.6H21V18.9z', // jshint ignore:line
  57805. clear: 'M22,14.7l30.9,31 M52.9,14.7L22,45.7 M4.7,16.8V4.2h13.1 M26,4.2h7.8 M41.6,4.2h7.8 M70.3,16.8V4.2H57.2 M4.7,25.9v8.6 M70.3,25.9v8.6 M4.7,43.2v12.6h13.1 M26,55.8h7.8 M41.6,55.8h7.8 M70.3,43.2v12.6H57.2' // jshint ignore:line
  57806. },
  57807. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  57808. title: clone(brushLang.title)
  57809. };
  57810. var proto$3 = Brush.prototype;
  57811. // proto.updateLayout = function (featureModel, ecModel, api) {
  57812. proto$3.render =
  57813. proto$3.updateView = function (featureModel, ecModel, api) {
  57814. var brushType;
  57815. var brushMode;
  57816. var isBrushed;
  57817. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  57818. brushType = brushModel.brushType;
  57819. brushMode = brushModel.brushOption.brushMode || 'single';
  57820. isBrushed |= brushModel.areas.length;
  57821. });
  57822. this._brushType = brushType;
  57823. this._brushMode = brushMode;
  57824. each$1(featureModel.get('type', true), function (type) {
  57825. featureModel.setIconStatus(
  57826. type,
  57827. (
  57828. type === 'keep'
  57829. ? brushMode === 'multiple'
  57830. : type === 'clear'
  57831. ? isBrushed
  57832. : type === brushType
  57833. ) ? 'emphasis' : 'normal'
  57834. );
  57835. });
  57836. };
  57837. proto$3.getIcons = function () {
  57838. var model = this.model;
  57839. var availableIcons = model.get('icon', true);
  57840. var icons = {};
  57841. each$1(model.get('type', true), function (type) {
  57842. if (availableIcons[type]) {
  57843. icons[type] = availableIcons[type];
  57844. }
  57845. });
  57846. return icons;
  57847. };
  57848. proto$3.onclick = function (ecModel, api, type) {
  57849. var brushType = this._brushType;
  57850. var brushMode = this._brushMode;
  57851. if (type === 'clear') {
  57852. // Trigger parallel action firstly
  57853. api.dispatchAction({
  57854. type: 'axisAreaSelect',
  57855. intervals: []
  57856. });
  57857. api.dispatchAction({
  57858. type: 'brush',
  57859. command: 'clear',
  57860. // Clear all areas of all brush components.
  57861. areas: []
  57862. });
  57863. }
  57864. else {
  57865. api.dispatchAction({
  57866. type: 'takeGlobalCursor',
  57867. key: 'brush',
  57868. brushOption: {
  57869. brushType: type === 'keep'
  57870. ? brushType
  57871. : (brushType === type ? false : type),
  57872. brushMode: type === 'keep'
  57873. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  57874. : brushMode
  57875. }
  57876. });
  57877. }
  57878. };
  57879. register$1('brush', Brush);
  57880. /**
  57881. * Brush component entry
  57882. */
  57883. registerPreprocessor(preprocessor$1);
  57884. // (24*60*60*1000)
  57885. var PROXIMATE_ONE_DAY = 86400000;
  57886. /**
  57887. * Calendar
  57888. *
  57889. * @constructor
  57890. *
  57891. * @param {Object} calendarModel calendarModel
  57892. * @param {Object} ecModel ecModel
  57893. * @param {Object} api api
  57894. */
  57895. function Calendar(calendarModel, ecModel, api) {
  57896. this._model = calendarModel;
  57897. }
  57898. Calendar.prototype = {
  57899. constructor: Calendar,
  57900. type: 'calendar',
  57901. dimensions: ['time', 'value'],
  57902. // Required in createListFromData
  57903. getDimensionsInfo: function () {
  57904. return [{name: 'time', type: 'time'}, 'value'];
  57905. },
  57906. getRangeInfo: function () {
  57907. return this._rangeInfo;
  57908. },
  57909. getModel: function () {
  57910. return this._model;
  57911. },
  57912. getRect: function () {
  57913. return this._rect;
  57914. },
  57915. getCellWidth: function () {
  57916. return this._sw;
  57917. },
  57918. getCellHeight: function () {
  57919. return this._sh;
  57920. },
  57921. getOrient: function () {
  57922. return this._orient;
  57923. },
  57924. /**
  57925. * getFirstDayOfWeek
  57926. *
  57927. * @example
  57928. * 0 : start at Sunday
  57929. * 1 : start at Monday
  57930. *
  57931. * @return {number}
  57932. */
  57933. getFirstDayOfWeek: function () {
  57934. return this._firstDayOfWeek;
  57935. },
  57936. /**
  57937. * get date info
  57938. *
  57939. * @param {string|number} date date
  57940. * @return {Object}
  57941. * {
  57942. * y: string, local full year, eg., '1940',
  57943. * m: string, local month, from '01' ot '12',
  57944. * d: string, local date, from '01' to '31' (if exists),
  57945. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  57946. * time: timestamp,
  57947. * formatedDate: string, yyyy-MM-dd,
  57948. * date: original date object.
  57949. * }
  57950. */
  57951. getDateInfo: function (date) {
  57952. date = parseDate(date);
  57953. var y = date.getFullYear();
  57954. var m = date.getMonth() + 1;
  57955. m = m < 10 ? '0' + m : m;
  57956. var d = date.getDate();
  57957. d = d < 10 ? '0' + d : d;
  57958. var day = date.getDay();
  57959. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  57960. return {
  57961. y: y,
  57962. m: m,
  57963. d: d,
  57964. day: day,
  57965. time: date.getTime(),
  57966. formatedDate: y + '-' + m + '-' + d,
  57967. date: date
  57968. };
  57969. },
  57970. getNextNDay: function (date, n) {
  57971. n = n || 0;
  57972. if (n === 0) {
  57973. return this.getDateInfo(date);
  57974. }
  57975. date = new Date(this.getDateInfo(date).time);
  57976. date.setDate(date.getDate() + n);
  57977. return this.getDateInfo(date);
  57978. },
  57979. update: function (ecModel, api) {
  57980. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  57981. this._orient = this._model.get('orient');
  57982. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  57983. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  57984. var weeks = this._rangeInfo.weeks || 1;
  57985. var whNames = ['width', 'height'];
  57986. var cellSize = this._model.get('cellSize').slice();
  57987. var layoutParams = this._model.getBoxLayoutParams();
  57988. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  57989. each$1([0, 1], function (idx) {
  57990. if (cellSizeSpecified(cellSize, idx)) {
  57991. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  57992. }
  57993. });
  57994. var whGlobal = {
  57995. width: api.getWidth(),
  57996. height: api.getHeight()
  57997. };
  57998. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  57999. each$1([0, 1], function (idx) {
  58000. if (!cellSizeSpecified(cellSize, idx)) {
  58001. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  58002. }
  58003. });
  58004. function cellSizeSpecified(cellSize, idx) {
  58005. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  58006. }
  58007. this._sw = cellSize[0];
  58008. this._sh = cellSize[1];
  58009. },
  58010. /**
  58011. * Convert a time data(time, value) item to (x, y) point.
  58012. *
  58013. * @override
  58014. * @param {Array|number} data data
  58015. * @param {boolean} [clamp=true] out of range
  58016. * @return {Array} point
  58017. */
  58018. dataToPoint: function (data, clamp) {
  58019. isArray(data) && (data = data[0]);
  58020. clamp == null && (clamp = true);
  58021. var dayInfo = this.getDateInfo(data);
  58022. var range = this._rangeInfo;
  58023. var date = dayInfo.formatedDate;
  58024. // if not in range return [NaN, NaN]
  58025. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time <= range.end.time)) {
  58026. return [NaN, NaN];
  58027. }
  58028. var week = dayInfo.day;
  58029. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  58030. if (this._orient === 'vertical') {
  58031. return [
  58032. this._rect.x + week * this._sw + this._sw / 2,
  58033. this._rect.y + nthWeek * this._sh + this._sh / 2
  58034. ];
  58035. }
  58036. return [
  58037. this._rect.x + nthWeek * this._sw + this._sw / 2,
  58038. this._rect.y + week * this._sh + this._sh / 2
  58039. ];
  58040. },
  58041. /**
  58042. * Convert a (x, y) point to time data
  58043. *
  58044. * @override
  58045. * @param {string} point point
  58046. * @return {string} data
  58047. */
  58048. pointToData: function (point) {
  58049. var date = this.pointToDate(point);
  58050. return date && date.time;
  58051. },
  58052. /**
  58053. * Convert a time date item to (x, y) four point.
  58054. *
  58055. * @param {Array} data date[0] is date
  58056. * @param {boolean} [clamp=true] out of range
  58057. * @return {Object} point
  58058. */
  58059. dataToRect: function (data, clamp) {
  58060. var point = this.dataToPoint(data, clamp);
  58061. return {
  58062. contentShape: {
  58063. x: point[0] - (this._sw - this._lineWidth) / 2,
  58064. y: point[1] - (this._sh - this._lineWidth) / 2,
  58065. width: this._sw - this._lineWidth,
  58066. height: this._sh - this._lineWidth
  58067. },
  58068. center: point,
  58069. tl: [
  58070. point[0] - this._sw / 2,
  58071. point[1] - this._sh / 2
  58072. ],
  58073. tr: [
  58074. point[0] + this._sw / 2,
  58075. point[1] - this._sh / 2
  58076. ],
  58077. br: [
  58078. point[0] + this._sw / 2,
  58079. point[1] + this._sh / 2
  58080. ],
  58081. bl: [
  58082. point[0] - this._sw / 2,
  58083. point[1] + this._sh / 2
  58084. ]
  58085. };
  58086. },
  58087. /**
  58088. * Convert a (x, y) point to time date
  58089. *
  58090. * @param {Array} point point
  58091. * @return {Object} date
  58092. */
  58093. pointToDate: function (point) {
  58094. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  58095. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  58096. var range = this._rangeInfo.range;
  58097. if (this._orient === 'vertical') {
  58098. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  58099. }
  58100. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  58101. },
  58102. /**
  58103. * @inheritDoc
  58104. */
  58105. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  58106. /**
  58107. * @inheritDoc
  58108. */
  58109. convertFromPixel: curry(doConvert$2, 'pointToData'),
  58110. /**
  58111. * initRange
  58112. *
  58113. * @private
  58114. * @return {Array} [start, end]
  58115. */
  58116. _initRangeOption: function () {
  58117. var range = this._model.get('range');
  58118. var rg = range;
  58119. if (isArray(rg) && rg.length === 1) {
  58120. rg = rg[0];
  58121. }
  58122. if (/^\d{4}$/.test(rg)) {
  58123. range = [rg + '-01-01', rg + '-12-31'];
  58124. }
  58125. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  58126. var start = this.getDateInfo(rg);
  58127. var firstDay = start.date;
  58128. firstDay.setMonth(firstDay.getMonth() + 1);
  58129. var end = this.getNextNDay(firstDay, -1);
  58130. range = [start.formatedDate, end.formatedDate];
  58131. }
  58132. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  58133. range = [rg, rg];
  58134. }
  58135. var tmp = this._getRangeInfo(range);
  58136. if (tmp.start.time > tmp.end.time) {
  58137. range.reverse();
  58138. }
  58139. return range;
  58140. },
  58141. /**
  58142. * range info
  58143. *
  58144. * @private
  58145. * @param {Array} range range ['2017-01-01', '2017-07-08']
  58146. * If range[0] > range[1], they will not be reversed.
  58147. * @return {Object} obj
  58148. */
  58149. _getRangeInfo: function (range) {
  58150. range = [
  58151. this.getDateInfo(range[0]),
  58152. this.getDateInfo(range[1])
  58153. ];
  58154. var reversed;
  58155. if (range[0].time > range[1].time) {
  58156. reversed = true;
  58157. range.reverse();
  58158. }
  58159. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  58160. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  58161. // Consider case:
  58162. // Firstly set system timezone as "Time Zone: America/Toronto",
  58163. // ```
  58164. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  58165. // var second = new Date(1478412000000);
  58166. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  58167. // ```
  58168. // will get wrong result because of DST. So we should fix it.
  58169. var date = new Date(range[0].time);
  58170. var startDateNum = date.getDate();
  58171. var endDateNum = range[1].date.getDate();
  58172. date.setDate(startDateNum + allDay - 1);
  58173. // The bias can not over a month, so just compare date.
  58174. if (date.getDate() !== endDateNum) {
  58175. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  58176. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  58177. allDay -= sign;
  58178. date.setDate(startDateNum + allDay - 1);
  58179. }
  58180. }
  58181. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  58182. var nthWeek = reversed ? -weeks + 1: weeks - 1;
  58183. reversed && range.reverse();
  58184. return {
  58185. range: [range[0].formatedDate, range[1].formatedDate],
  58186. start: range[0],
  58187. end: range[1],
  58188. allDay: allDay,
  58189. weeks: weeks,
  58190. // From 0.
  58191. nthWeek: nthWeek,
  58192. fweek: range[0].day,
  58193. lweek: range[1].day
  58194. };
  58195. },
  58196. /**
  58197. * get date by nthWeeks and week day in range
  58198. *
  58199. * @private
  58200. * @param {number} nthWeek the week
  58201. * @param {number} day the week day
  58202. * @param {Array} range [d1, d2]
  58203. * @return {Object}
  58204. */
  58205. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  58206. var rangeInfo = this._getRangeInfo(range);
  58207. if (nthWeek > rangeInfo.weeks
  58208. || (nthWeek === 0 && day < rangeInfo.fweek)
  58209. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  58210. ) {
  58211. return false;
  58212. }
  58213. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  58214. var date = new Date(rangeInfo.start.time);
  58215. date.setDate(rangeInfo.start.d + nthDay);
  58216. return this.getDateInfo(date);
  58217. }
  58218. };
  58219. Calendar.dimensions = Calendar.prototype.dimensions;
  58220. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  58221. Calendar.create = function (ecModel, api) {
  58222. var calendarList = [];
  58223. ecModel.eachComponent('calendar', function (calendarModel) {
  58224. var calendar = new Calendar(calendarModel, ecModel, api);
  58225. calendarList.push(calendar);
  58226. calendarModel.coordinateSystem = calendar;
  58227. });
  58228. ecModel.eachSeries(function (calendarSeries) {
  58229. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  58230. // Inject coordinate system
  58231. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  58232. }
  58233. });
  58234. return calendarList;
  58235. };
  58236. function doConvert$2(methodName, ecModel, finder, value) {
  58237. var calendarModel = finder.calendarModel;
  58238. var seriesModel = finder.seriesModel;
  58239. var coordSys = calendarModel
  58240. ? calendarModel.coordinateSystem
  58241. : seriesModel
  58242. ? seriesModel.coordinateSystem
  58243. : null;
  58244. return coordSys === this ? coordSys[methodName](value) : null;
  58245. }
  58246. CoordinateSystemManager.register('calendar', Calendar);
  58247. var CalendarModel = ComponentModel.extend({
  58248. type: 'calendar',
  58249. /**
  58250. * @type {module:echarts/coord/calendar/Calendar}
  58251. */
  58252. coordinateSystem: null,
  58253. defaultOption: {
  58254. zlevel: 0,
  58255. z: 2,
  58256. left: 80,
  58257. top: 60,
  58258. cellSize: 20,
  58259. // horizontal vertical
  58260. orient: 'horizontal',
  58261. // month separate line style
  58262. splitLine: {
  58263. show: true,
  58264. lineStyle: {
  58265. color: '#000',
  58266. width: 1,
  58267. type: 'solid'
  58268. }
  58269. },
  58270. // rect style temporarily unused emphasis
  58271. itemStyle: {
  58272. color: '#fff',
  58273. borderWidth: 1,
  58274. borderColor: '#ccc'
  58275. },
  58276. // week text style
  58277. dayLabel: {
  58278. show: true,
  58279. // a week first day
  58280. firstDay: 0,
  58281. // start end
  58282. position: 'start',
  58283. margin: '50%', // 50% of cellSize
  58284. nameMap: 'en',
  58285. color: '#000'
  58286. },
  58287. // month text style
  58288. monthLabel: {
  58289. show: true,
  58290. // start end
  58291. position: 'start',
  58292. margin: 5,
  58293. // center or left
  58294. align: 'center',
  58295. // cn en []
  58296. nameMap: 'en',
  58297. formatter: null,
  58298. color: '#000'
  58299. },
  58300. // year text style
  58301. yearLabel: {
  58302. show: true,
  58303. // top bottom left right
  58304. position: null,
  58305. margin: 30,
  58306. formatter: null,
  58307. color: '#ccc',
  58308. fontFamily: 'sans-serif',
  58309. fontWeight: 'bolder',
  58310. fontSize: 20
  58311. }
  58312. },
  58313. /**
  58314. * @override
  58315. */
  58316. init: function (option, parentModel, ecModel, extraOpt) {
  58317. var inputPositionParams = getLayoutParams(option);
  58318. CalendarModel.superApply(this, 'init', arguments);
  58319. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  58320. },
  58321. /**
  58322. * @override
  58323. */
  58324. mergeOption: function (option, extraOpt) {
  58325. CalendarModel.superApply(this, 'mergeOption', arguments);
  58326. mergeAndNormalizeLayoutParams$1(this.option, option);
  58327. }
  58328. });
  58329. function mergeAndNormalizeLayoutParams$1(target, raw) {
  58330. // Normalize cellSize
  58331. var cellSize = target.cellSize;
  58332. if (!isArray(cellSize)) {
  58333. cellSize = target.cellSize = [cellSize, cellSize];
  58334. }
  58335. else if (cellSize.length === 1) {
  58336. cellSize[1] = cellSize[0];
  58337. }
  58338. var ignoreSize = map([0, 1], function (hvIdx) {
  58339. // If user have set `width` or both `left` and `right`, cellSize
  58340. // will be automatically set to 'auto', otherwise the default
  58341. // setting of cellSize will make `width` setting not work.
  58342. if (sizeCalculable(raw, hvIdx)) {
  58343. cellSize[hvIdx] = 'auto';
  58344. }
  58345. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  58346. });
  58347. mergeLayoutParam(target, raw, {
  58348. type: 'box', ignoreSize: ignoreSize
  58349. });
  58350. }
  58351. var MONTH_TEXT = {
  58352. EN: [
  58353. 'Jan', 'Feb', 'Mar',
  58354. 'Apr', 'May', 'Jun',
  58355. 'Jul', 'Aug', 'Sep',
  58356. 'Oct', 'Nov', 'Dec'
  58357. ],
  58358. CN: [
  58359. '一月', '二月', '三月',
  58360. '四月', '五月', '六月',
  58361. '七月', '八月', '九月',
  58362. '十月', '十一月', '十二月'
  58363. ]
  58364. };
  58365. var WEEK_TEXT = {
  58366. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  58367. CN: ['日', '一', '二', '三', '四', '五', '六']
  58368. };
  58369. extendComponentView({
  58370. type: 'calendar',
  58371. /**
  58372. * top/left line points
  58373. * @private
  58374. */
  58375. _tlpoints: null,
  58376. /**
  58377. * bottom/right line points
  58378. * @private
  58379. */
  58380. _blpoints: null,
  58381. /**
  58382. * first day of month
  58383. * @private
  58384. */
  58385. _firstDayOfMonth: null,
  58386. /**
  58387. * first day point of month
  58388. * @private
  58389. */
  58390. _firstDayPoints: null,
  58391. render: function (calendarModel, ecModel, api) {
  58392. var group = this.group;
  58393. group.removeAll();
  58394. var coordSys = calendarModel.coordinateSystem;
  58395. // range info
  58396. var rangeData = coordSys.getRangeInfo();
  58397. var orient = coordSys.getOrient();
  58398. this._renderDayRect(calendarModel, rangeData, group);
  58399. // _renderLines must be called prior to following function
  58400. this._renderLines(calendarModel, rangeData, orient, group);
  58401. this._renderYearText(calendarModel, rangeData, orient, group);
  58402. this._renderMonthText(calendarModel, orient, group);
  58403. this._renderWeekText(calendarModel, rangeData, orient, group);
  58404. },
  58405. // render day rect
  58406. _renderDayRect: function (calendarModel, rangeData, group) {
  58407. var coordSys = calendarModel.coordinateSystem;
  58408. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  58409. var sw = coordSys.getCellWidth();
  58410. var sh = coordSys.getCellHeight();
  58411. for (var i = rangeData.start.time;
  58412. i <= rangeData.end.time;
  58413. i = coordSys.getNextNDay(i, 1).time
  58414. ) {
  58415. var point = coordSys.dataToRect([i], false).tl;
  58416. // every rect
  58417. var rect = new Rect({
  58418. shape: {
  58419. x: point[0],
  58420. y: point[1],
  58421. width: sw,
  58422. height: sh
  58423. },
  58424. cursor: 'default',
  58425. style: itemRectStyleModel
  58426. });
  58427. group.add(rect);
  58428. }
  58429. },
  58430. // render separate line
  58431. _renderLines: function (calendarModel, rangeData, orient, group) {
  58432. var self = this;
  58433. var coordSys = calendarModel.coordinateSystem;
  58434. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  58435. var show = calendarModel.get('splitLine.show');
  58436. var lineWidth = lineStyleModel.lineWidth;
  58437. this._tlpoints = [];
  58438. this._blpoints = [];
  58439. this._firstDayOfMonth = [];
  58440. this._firstDayPoints = [];
  58441. var firstDay = rangeData.start;
  58442. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  58443. addPoints(firstDay.formatedDate);
  58444. if (i === 0) {
  58445. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  58446. }
  58447. var date = firstDay.date;
  58448. date.setMonth(date.getMonth() + 1);
  58449. firstDay = coordSys.getDateInfo(date);
  58450. }
  58451. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  58452. function addPoints(date) {
  58453. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  58454. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  58455. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  58456. self._tlpoints.push(points[0]);
  58457. self._blpoints.push(points[points.length - 1]);
  58458. show && self._drawSplitline(points, lineStyleModel, group);
  58459. }
  58460. // render top/left line
  58461. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  58462. // render bottom/right line
  58463. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  58464. },
  58465. // get points at both ends
  58466. _getEdgesPoints: function (points, lineWidth, orient) {
  58467. var rs = [points[0].slice(), points[points.length - 1].slice()];
  58468. var idx = orient === 'horizontal' ? 0 : 1;
  58469. // both ends of the line are extend half lineWidth
  58470. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  58471. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  58472. return rs;
  58473. },
  58474. // render split line
  58475. _drawSplitline: function (points, lineStyleModel, group) {
  58476. var poyline = new Polyline({
  58477. z2: 20,
  58478. shape: {
  58479. points: points
  58480. },
  58481. style: lineStyleModel
  58482. });
  58483. group.add(poyline);
  58484. },
  58485. // render month line of one week points
  58486. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  58487. var coordSys = calendarModel.coordinateSystem;
  58488. date = coordSys.getDateInfo(date);
  58489. var points = [];
  58490. for (var i = 0; i < 7; i++) {
  58491. var tmpD = coordSys.getNextNDay(date.time, i);
  58492. var point = coordSys.dataToRect([tmpD.time], false);
  58493. points[2 * tmpD.day] = point.tl;
  58494. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  58495. }
  58496. return points;
  58497. },
  58498. _formatterLabel: function (formatter, params) {
  58499. if (typeof formatter === 'string' && formatter) {
  58500. return formatTplSimple(formatter, params);
  58501. }
  58502. if (typeof formatter === 'function') {
  58503. return formatter(params);
  58504. }
  58505. return params.nameMap;
  58506. },
  58507. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  58508. point = point.slice();
  58509. var aligns = ['center', 'bottom'];
  58510. if (position === 'bottom') {
  58511. point[1] += margin;
  58512. aligns = ['center', 'top'];
  58513. }
  58514. else if (position === 'left') {
  58515. point[0] -= margin;
  58516. }
  58517. else if (position === 'right') {
  58518. point[0] += margin;
  58519. aligns = ['center', 'top'];
  58520. }
  58521. else { // top
  58522. point[1] -= margin;
  58523. }
  58524. var rotate = 0;
  58525. if (position === 'left' || position === 'right') {
  58526. rotate = Math.PI / 2;
  58527. }
  58528. return {
  58529. rotation: rotate,
  58530. position: point,
  58531. style: {
  58532. textAlign: aligns[0],
  58533. textVerticalAlign: aligns[1]
  58534. }
  58535. };
  58536. },
  58537. // render year
  58538. _renderYearText: function (calendarModel, rangeData, orient, group) {
  58539. var yearLabel = calendarModel.getModel('yearLabel');
  58540. if (!yearLabel.get('show')) {
  58541. return;
  58542. }
  58543. var margin = yearLabel.get('margin');
  58544. var pos = yearLabel.get('position');
  58545. if (!pos) {
  58546. pos = orient !== 'horizontal' ? 'top' : 'left';
  58547. }
  58548. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  58549. var xc = (points[0][0] + points[1][0]) / 2;
  58550. var yc = (points[0][1] + points[1][1]) / 2;
  58551. var idx = orient === 'horizontal' ? 0 : 1;
  58552. var posPoints = {
  58553. top: [xc, points[idx][1]],
  58554. bottom: [xc, points[1 - idx][1]],
  58555. left: [points[1 - idx][0], yc],
  58556. right: [points[idx][0], yc]
  58557. };
  58558. var name = rangeData.start.y;
  58559. if (+rangeData.end.y > +rangeData.start.y) {
  58560. name = name + '-' + rangeData.end.y;
  58561. }
  58562. var formatter = yearLabel.get('formatter');
  58563. var params = {
  58564. start: rangeData.start.y,
  58565. end: rangeData.end.y,
  58566. nameMap: name
  58567. };
  58568. var content = this._formatterLabel(formatter, params);
  58569. var yearText = new Text({z2: 30});
  58570. setTextStyle(yearText.style, yearLabel, {text: content}),
  58571. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  58572. group.add(yearText);
  58573. },
  58574. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  58575. var align = 'left';
  58576. var vAlign = 'top';
  58577. var x = point[0];
  58578. var y = point[1];
  58579. if (orient === 'horizontal') {
  58580. y = y + margin;
  58581. if (isCenter) {
  58582. align = 'center';
  58583. }
  58584. if (position === 'start') {
  58585. vAlign = 'bottom';
  58586. }
  58587. }
  58588. else {
  58589. x = x + margin;
  58590. if (isCenter) {
  58591. vAlign = 'middle';
  58592. }
  58593. if (position === 'start') {
  58594. align = 'right';
  58595. }
  58596. }
  58597. return {
  58598. x: x,
  58599. y: y,
  58600. textAlign: align,
  58601. textVerticalAlign: vAlign
  58602. };
  58603. },
  58604. // render month and year text
  58605. _renderMonthText: function (calendarModel, orient, group) {
  58606. var monthLabel = calendarModel.getModel('monthLabel');
  58607. if (!monthLabel.get('show')) {
  58608. return;
  58609. }
  58610. var nameMap = monthLabel.get('nameMap');
  58611. var margin = monthLabel.get('margin');
  58612. var pos = monthLabel.get('position');
  58613. var align = monthLabel.get('align');
  58614. var termPoints = [this._tlpoints, this._blpoints];
  58615. if (isString(nameMap)) {
  58616. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  58617. }
  58618. var idx = pos === 'start' ? 0 : 1;
  58619. var axis = orient === 'horizontal' ? 0 : 1;
  58620. margin = pos === 'start' ? -margin : margin;
  58621. var isCenter = (align === 'center');
  58622. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  58623. var tmp = termPoints[idx][i].slice();
  58624. var firstDay = this._firstDayOfMonth[i];
  58625. if (isCenter) {
  58626. var firstDayPoints = this._firstDayPoints[i];
  58627. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  58628. }
  58629. var formatter = monthLabel.get('formatter');
  58630. var name = nameMap[+firstDay.m - 1];
  58631. var params = {
  58632. yyyy: firstDay.y,
  58633. yy: (firstDay.y + '').slice(2),
  58634. MM: firstDay.m,
  58635. M: +firstDay.m,
  58636. nameMap: name
  58637. };
  58638. var content = this._formatterLabel(formatter, params);
  58639. var monthText = new Text({z2: 30});
  58640. extend(
  58641. setTextStyle(monthText.style, monthLabel, {text: content}),
  58642. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  58643. );
  58644. group.add(monthText);
  58645. }
  58646. },
  58647. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  58648. var align = 'center';
  58649. var vAlign = 'middle';
  58650. var x = point[0];
  58651. var y = point[1];
  58652. var isStart = position === 'start';
  58653. if (orient === 'horizontal') {
  58654. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  58655. align = isStart ? 'right' : 'left';
  58656. }
  58657. else {
  58658. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  58659. vAlign = isStart ? 'bottom' : 'top';
  58660. }
  58661. return {
  58662. x: x,
  58663. y: y,
  58664. textAlign: align,
  58665. textVerticalAlign: vAlign
  58666. };
  58667. },
  58668. // render weeks
  58669. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  58670. var dayLabel = calendarModel.getModel('dayLabel');
  58671. if (!dayLabel.get('show')) {
  58672. return;
  58673. }
  58674. var coordSys = calendarModel.coordinateSystem;
  58675. var pos = dayLabel.get('position');
  58676. var nameMap = dayLabel.get('nameMap');
  58677. var margin = dayLabel.get('margin');
  58678. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  58679. if (isString(nameMap)) {
  58680. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  58681. }
  58682. var start = coordSys.getNextNDay(
  58683. rangeData.end.time, (7 - rangeData.lweek)
  58684. ).time;
  58685. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  58686. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  58687. if (pos === 'start') {
  58688. start = coordSys.getNextNDay(
  58689. rangeData.start.time, -(7 + rangeData.fweek)
  58690. ).time;
  58691. margin = -margin;
  58692. }
  58693. for (var i = 0; i < 7; i++) {
  58694. var tmpD = coordSys.getNextNDay(start, i);
  58695. var point = coordSys.dataToRect([tmpD.time], false).center;
  58696. var day = i;
  58697. day = Math.abs((i + firstDayOfWeek) % 7);
  58698. var weekText = new Text({z2: 30});
  58699. extend(
  58700. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  58701. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  58702. );
  58703. group.add(weekText);
  58704. }
  58705. }
  58706. });
  58707. /**
  58708. * @file calendar.js
  58709. * @author dxh
  58710. */
  58711. // Model
  58712. extendComponentModel({
  58713. type: 'title',
  58714. layoutMode: {type: 'box', ignoreSize: true},
  58715. defaultOption: {
  58716. // 一级层叠
  58717. zlevel: 0,
  58718. // 二级层叠
  58719. z: 6,
  58720. show: true,
  58721. text: '',
  58722. // 超链接跳转
  58723. // link: null,
  58724. // 仅支持self | blank
  58725. target: 'blank',
  58726. subtext: '',
  58727. // 超链接跳转
  58728. // sublink: null,
  58729. // 仅支持self | blank
  58730. subtarget: 'blank',
  58731. // 'center' ¦ 'left' ¦ 'right'
  58732. // ¦ {number}(x坐标,单位px)
  58733. left: 0,
  58734. // 'top' ¦ 'bottom' ¦ 'center'
  58735. // ¦ {number}(y坐标,单位px)
  58736. top: 0,
  58737. // 水平对齐
  58738. // 'auto' | 'left' | 'right' | 'center'
  58739. // 默认根据 left 的位置判断是左对齐还是右对齐
  58740. // textAlign: null
  58741. //
  58742. // 垂直对齐
  58743. // 'auto' | 'top' | 'bottom' | 'middle'
  58744. // 默认根据 top 位置判断是上对齐还是下对齐
  58745. // textBaseline: null
  58746. backgroundColor: 'rgba(0,0,0,0)',
  58747. // 标题边框颜色
  58748. borderColor: '#ccc',
  58749. // 标题边框线宽,单位px,默认为0(无边框)
  58750. borderWidth: 0,
  58751. // 标题内边距,单位px,默认各方向内边距为5,
  58752. // 接受数组分别设定上右下左边距,同css
  58753. padding: 5,
  58754. // 主副标题纵向间隔,单位px,默认为10,
  58755. itemGap: 10,
  58756. textStyle: {
  58757. fontSize: 18,
  58758. fontWeight: 'bolder',
  58759. color: '#333'
  58760. },
  58761. subtextStyle: {
  58762. color: '#aaa'
  58763. }
  58764. }
  58765. });
  58766. // View
  58767. extendComponentView({
  58768. type: 'title',
  58769. render: function (titleModel, ecModel, api) {
  58770. this.group.removeAll();
  58771. if (!titleModel.get('show')) {
  58772. return;
  58773. }
  58774. var group = this.group;
  58775. var textStyleModel = titleModel.getModel('textStyle');
  58776. var subtextStyleModel = titleModel.getModel('subtextStyle');
  58777. var textAlign = titleModel.get('textAlign');
  58778. var textBaseline = titleModel.get('textBaseline');
  58779. var textEl = new Text({
  58780. style: setTextStyle({}, textStyleModel, {
  58781. text: titleModel.get('text'),
  58782. textFill: textStyleModel.getTextColor()
  58783. }, {disableBox: true}),
  58784. z2: 10
  58785. });
  58786. var textRect = textEl.getBoundingRect();
  58787. var subText = titleModel.get('subtext');
  58788. var subTextEl = new Text({
  58789. style: setTextStyle({}, subtextStyleModel, {
  58790. text: subText,
  58791. textFill: subtextStyleModel.getTextColor(),
  58792. y: textRect.height + titleModel.get('itemGap'),
  58793. textVerticalAlign: 'top'
  58794. }, {disableBox: true}),
  58795. z2: 10
  58796. });
  58797. var link = titleModel.get('link');
  58798. var sublink = titleModel.get('sublink');
  58799. textEl.silent = !link;
  58800. subTextEl.silent = !sublink;
  58801. if (link) {
  58802. textEl.on('click', function () {
  58803. window.open(link, '_' + titleModel.get('target'));
  58804. });
  58805. }
  58806. if (sublink) {
  58807. subTextEl.on('click', function () {
  58808. window.open(sublink, '_' + titleModel.get('subtarget'));
  58809. });
  58810. }
  58811. group.add(textEl);
  58812. subText && group.add(subTextEl);
  58813. // If no subText, but add subTextEl, there will be an empty line.
  58814. var groupRect = group.getBoundingRect();
  58815. var layoutOption = titleModel.getBoxLayoutParams();
  58816. layoutOption.width = groupRect.width;
  58817. layoutOption.height = groupRect.height;
  58818. var layoutRect = getLayoutRect(
  58819. layoutOption, {
  58820. width: api.getWidth(),
  58821. height: api.getHeight()
  58822. }, titleModel.get('padding')
  58823. );
  58824. // Adjust text align based on position
  58825. if (!textAlign) {
  58826. // Align left if title is on the left. center and right is same
  58827. textAlign = titleModel.get('left') || titleModel.get('right');
  58828. if (textAlign === 'middle') {
  58829. textAlign = 'center';
  58830. }
  58831. // Adjust layout by text align
  58832. if (textAlign === 'right') {
  58833. layoutRect.x += layoutRect.width;
  58834. }
  58835. else if (textAlign === 'center') {
  58836. layoutRect.x += layoutRect.width / 2;
  58837. }
  58838. }
  58839. if (!textBaseline) {
  58840. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  58841. if (textBaseline === 'center') {
  58842. textBaseline = 'middle';
  58843. }
  58844. if (textBaseline === 'bottom') {
  58845. layoutRect.y += layoutRect.height;
  58846. }
  58847. else if (textBaseline === 'middle') {
  58848. layoutRect.y += layoutRect.height / 2;
  58849. }
  58850. textBaseline = textBaseline || 'top';
  58851. }
  58852. group.attr('position', [layoutRect.x, layoutRect.y]);
  58853. var alignStyle = {
  58854. textAlign: textAlign,
  58855. textVerticalAlign: textBaseline
  58856. };
  58857. textEl.setStyle(alignStyle);
  58858. subTextEl.setStyle(alignStyle);
  58859. // Render background
  58860. // Get groupRect again because textAlign has been changed
  58861. groupRect = group.getBoundingRect();
  58862. var padding = layoutRect.margin;
  58863. var style = titleModel.getItemStyle(['color', 'opacity']);
  58864. style.fill = titleModel.get('backgroundColor');
  58865. var rect = new Rect({
  58866. shape: {
  58867. x: groupRect.x - padding[3],
  58868. y: groupRect.y - padding[0],
  58869. width: groupRect.width + padding[1] + padding[3],
  58870. height: groupRect.height + padding[0] + padding[2],
  58871. r: titleModel.get('borderRadius')
  58872. },
  58873. style: style,
  58874. silent: true
  58875. });
  58876. subPixelOptimizeRect(rect);
  58877. group.add(rect);
  58878. }
  58879. });
  58880. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  58881. // Default 'slider' when no type specified.
  58882. return 'slider';
  58883. });
  58884. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  58885. // Supported coords.
  58886. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  58887. /**
  58888. * @param {string} coordType
  58889. * @return {boolean}
  58890. */
  58891. function isCoordSupported(coordType) {
  58892. return indexOf(COORDS, coordType) >= 0;
  58893. }
  58894. /**
  58895. * Create "each" method to iterate names.
  58896. *
  58897. * @pubilc
  58898. * @param {Array.<string>} names
  58899. * @param {Array.<string>=} attrs
  58900. * @return {Function}
  58901. */
  58902. function createNameEach(names, attrs) {
  58903. names = names.slice();
  58904. var capitalNames = map(names, capitalFirst);
  58905. attrs = (attrs || []).slice();
  58906. var capitalAttrs = map(attrs, capitalFirst);
  58907. return function (callback, context) {
  58908. each$1(names, function (name, index) {
  58909. var nameObj = {name: name, capital: capitalNames[index]};
  58910. for (var j = 0; j < attrs.length; j++) {
  58911. nameObj[attrs[j]] = name + capitalAttrs[j];
  58912. }
  58913. callback.call(context, nameObj);
  58914. });
  58915. };
  58916. }
  58917. /**
  58918. * Iterate each dimension name.
  58919. *
  58920. * @public
  58921. * @param {Function} callback The parameter is like:
  58922. * {
  58923. * name: 'angle',
  58924. * capital: 'Angle',
  58925. * axis: 'angleAxis',
  58926. * axisIndex: 'angleAixs',
  58927. * index: 'angleIndex'
  58928. * }
  58929. * @param {Object} context
  58930. */
  58931. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  58932. /**
  58933. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  58934. * dataZoomModels and 'links' make up one or more graphics.
  58935. * This function finds the graphic where the source dataZoomModel is in.
  58936. *
  58937. * @public
  58938. * @param {Function} forEachNode Node iterator.
  58939. * @param {Function} forEachEdgeType edgeType iterator
  58940. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  58941. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  58942. */
  58943. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  58944. return function (sourceNode) {
  58945. var result = {
  58946. nodes: [],
  58947. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  58948. };
  58949. forEachEdgeType(function (edgeType) {
  58950. result.records[edgeType.name] = {};
  58951. });
  58952. if (!sourceNode) {
  58953. return result;
  58954. }
  58955. absorb(sourceNode, result);
  58956. var existsLink;
  58957. do {
  58958. existsLink = false;
  58959. forEachNode(processSingleNode);
  58960. }
  58961. while (existsLink);
  58962. function processSingleNode(node) {
  58963. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  58964. absorb(node, result);
  58965. existsLink = true;
  58966. }
  58967. }
  58968. return result;
  58969. };
  58970. function isNodeAbsorded(node, result) {
  58971. return indexOf(result.nodes, node) >= 0;
  58972. }
  58973. function isLinked(node, result) {
  58974. var hasLink = false;
  58975. forEachEdgeType(function (edgeType) {
  58976. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  58977. result.records[edgeType.name][edgeId] && (hasLink = true);
  58978. });
  58979. });
  58980. return hasLink;
  58981. }
  58982. function absorb(node, result) {
  58983. result.nodes.push(node);
  58984. forEachEdgeType(function (edgeType) {
  58985. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  58986. result.records[edgeType.name][edgeId] = true;
  58987. });
  58988. });
  58989. }
  58990. }
  58991. var each$23 = each$1;
  58992. var asc$1 = asc;
  58993. /**
  58994. * Operate single axis.
  58995. * One axis can only operated by one axis operator.
  58996. * Different dataZoomModels may be defined to operate the same axis.
  58997. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  58998. * So dataZoomModels share one axisProxy in that case.
  58999. *
  59000. * @class
  59001. */
  59002. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  59003. /**
  59004. * @private
  59005. * @type {string}
  59006. */
  59007. this._dimName = dimName;
  59008. /**
  59009. * @private
  59010. */
  59011. this._axisIndex = axisIndex;
  59012. /**
  59013. * @private
  59014. * @type {Array.<number>}
  59015. */
  59016. this._valueWindow;
  59017. /**
  59018. * @private
  59019. * @type {Array.<number>}
  59020. */
  59021. this._percentWindow;
  59022. /**
  59023. * @private
  59024. * @type {Array.<number>}
  59025. */
  59026. this._dataExtent;
  59027. /**
  59028. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  59029. * @private
  59030. * @type {Object}
  59031. */
  59032. this._minMaxSpan;
  59033. /**
  59034. * @readOnly
  59035. * @type {module: echarts/model/Global}
  59036. */
  59037. this.ecModel = ecModel;
  59038. /**
  59039. * @private
  59040. * @type {module: echarts/component/dataZoom/DataZoomModel}
  59041. */
  59042. this._dataZoomModel = dataZoomModel;
  59043. // /**
  59044. // * @readOnly
  59045. // * @private
  59046. // */
  59047. // this.hasSeriesStacked;
  59048. };
  59049. AxisProxy.prototype = {
  59050. constructor: AxisProxy,
  59051. /**
  59052. * Whether the axisProxy is hosted by dataZoomModel.
  59053. *
  59054. * @public
  59055. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  59056. * @return {boolean}
  59057. */
  59058. hostedBy: function (dataZoomModel) {
  59059. return this._dataZoomModel === dataZoomModel;
  59060. },
  59061. /**
  59062. * @return {Array.<number>} Value can only be NaN or finite value.
  59063. */
  59064. getDataValueWindow: function () {
  59065. return this._valueWindow.slice();
  59066. },
  59067. /**
  59068. * @return {Array.<number>}
  59069. */
  59070. getDataPercentWindow: function () {
  59071. return this._percentWindow.slice();
  59072. },
  59073. /**
  59074. * @public
  59075. * @param {number} axisIndex
  59076. * @return {Array} seriesModels
  59077. */
  59078. getTargetSeriesModels: function () {
  59079. var seriesModels = [];
  59080. var ecModel = this.ecModel;
  59081. ecModel.eachSeries(function (seriesModel) {
  59082. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  59083. var dimName = this._dimName;
  59084. var axisModel = ecModel.queryComponents({
  59085. mainType: dimName + 'Axis',
  59086. index: seriesModel.get(dimName + 'AxisIndex'),
  59087. id: seriesModel.get(dimName + 'AxisId')
  59088. })[0];
  59089. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  59090. seriesModels.push(seriesModel);
  59091. }
  59092. }
  59093. }, this);
  59094. return seriesModels;
  59095. },
  59096. getAxisModel: function () {
  59097. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  59098. },
  59099. getOtherAxisModel: function () {
  59100. var axisDim = this._dimName;
  59101. var ecModel = this.ecModel;
  59102. var axisModel = this.getAxisModel();
  59103. var isCartesian = axisDim === 'x' || axisDim === 'y';
  59104. var otherAxisDim;
  59105. var coordSysIndexName;
  59106. if (isCartesian) {
  59107. coordSysIndexName = 'gridIndex';
  59108. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  59109. }
  59110. else {
  59111. coordSysIndexName = 'polarIndex';
  59112. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  59113. }
  59114. var foundOtherAxisModel;
  59115. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  59116. if ((otherAxisModel.get(coordSysIndexName) || 0)
  59117. === (axisModel.get(coordSysIndexName) || 0)
  59118. ) {
  59119. foundOtherAxisModel = otherAxisModel;
  59120. }
  59121. });
  59122. return foundOtherAxisModel;
  59123. },
  59124. getMinMaxSpan: function () {
  59125. return clone(this._minMaxSpan);
  59126. },
  59127. /**
  59128. * Only calculate by given range and this._dataExtent, do not change anything.
  59129. *
  59130. * @param {Object} opt
  59131. * @param {number} [opt.start]
  59132. * @param {number} [opt.end]
  59133. * @param {number} [opt.startValue]
  59134. * @param {number} [opt.endValue]
  59135. */
  59136. calculateDataWindow: function (opt) {
  59137. var dataExtent = this._dataExtent;
  59138. var axisModel = this.getAxisModel();
  59139. var scale = axisModel.axis.scale;
  59140. var rangePropMode = this._dataZoomModel.getRangePropMode();
  59141. var percentExtent = [0, 100];
  59142. var percentWindow = [
  59143. opt.start,
  59144. opt.end
  59145. ];
  59146. var valueWindow = [];
  59147. each$23(['startValue', 'endValue'], function (prop) {
  59148. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  59149. });
  59150. // Normalize bound.
  59151. each$23([0, 1], function (idx) {
  59152. var boundValue = valueWindow[idx];
  59153. var boundPercent = percentWindow[idx];
  59154. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  59155. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  59156. // for cases that a dataZoom component controls multiple axes with different
  59157. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  59158. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  59159. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  59160. // accurately (because all of values that are overflow the `dataExtent` will
  59161. // be calculated to percent '100%'). So we have to use
  59162. // `dataZoom.getRangePropMode()` to mark which prop is used.
  59163. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  59164. // it remains its original value.
  59165. if (rangePropMode[idx] === 'percent') {
  59166. if (boundPercent == null) {
  59167. boundPercent = percentExtent[idx];
  59168. }
  59169. // Use scale.parse to math round for category or time axis.
  59170. boundValue = scale.parse(linearMap(
  59171. boundPercent, percentExtent, dataExtent, true
  59172. ));
  59173. }
  59174. else {
  59175. // Calculating `percent` from `value` may be not accurate, because
  59176. // This calculation can not be inversed, because all of values that
  59177. // are overflow the `dataExtent` will be calculated to percent '100%'
  59178. boundPercent = linearMap(
  59179. boundValue, dataExtent, percentExtent, true
  59180. );
  59181. }
  59182. // valueWindow[idx] = round(boundValue);
  59183. // percentWindow[idx] = round(boundPercent);
  59184. valueWindow[idx] = boundValue;
  59185. percentWindow[idx] = boundPercent;
  59186. });
  59187. return {
  59188. valueWindow: asc$1(valueWindow),
  59189. percentWindow: asc$1(percentWindow)
  59190. };
  59191. },
  59192. /**
  59193. * Notice: reset should not be called before series.restoreData() called,
  59194. * so it is recommanded to be called in "process stage" but not "model init
  59195. * stage".
  59196. *
  59197. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  59198. */
  59199. reset: function (dataZoomModel) {
  59200. if (dataZoomModel !== this._dataZoomModel) {
  59201. return;
  59202. }
  59203. var targetSeries = this.getTargetSeriesModels();
  59204. // Culculate data window and data extent, and record them.
  59205. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  59206. // this.hasSeriesStacked = false;
  59207. // each(targetSeries, function (series) {
  59208. // var data = series.getData();
  59209. // var dataDim = data.mapDimension(this._dimName);
  59210. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  59211. // if (stackedDimension && stackedDimension === dataDim) {
  59212. // this.hasSeriesStacked = true;
  59213. // }
  59214. // }, this);
  59215. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  59216. this._valueWindow = dataWindow.valueWindow;
  59217. this._percentWindow = dataWindow.percentWindow;
  59218. setMinMaxSpan(this);
  59219. // Update axis setting then.
  59220. setAxisModel(this);
  59221. },
  59222. /**
  59223. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  59224. */
  59225. restore: function (dataZoomModel) {
  59226. if (dataZoomModel !== this._dataZoomModel) {
  59227. return;
  59228. }
  59229. this._valueWindow = this._percentWindow = null;
  59230. setAxisModel(this, true);
  59231. },
  59232. /**
  59233. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  59234. */
  59235. filterData: function (dataZoomModel, api) {
  59236. if (dataZoomModel !== this._dataZoomModel) {
  59237. return;
  59238. }
  59239. var axisDim = this._dimName;
  59240. var seriesModels = this.getTargetSeriesModels();
  59241. var filterMode = dataZoomModel.get('filterMode');
  59242. var valueWindow = this._valueWindow;
  59243. if (filterMode === 'none') {
  59244. return;
  59245. }
  59246. // FIXME
  59247. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  59248. // with NaN data, NaN will be filtered and stack will be wrong.
  59249. // So we need to force the mode to be set empty.
  59250. // In fect, it is not a big deal that do not support filterMode-'filter'
  59251. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  59252. // selection" some day, which might need "adapt to data extent on the
  59253. // otherAxis", which is disabled by filterMode-'empty'.
  59254. // But currently, stack has been fixed to based on value but not index,
  59255. // so this is not an issue any more.
  59256. // var otherAxisModel = this.getOtherAxisModel();
  59257. // if (dataZoomModel.get('$fromToolbox')
  59258. // && otherAxisModel
  59259. // && otherAxisModel.hasSeriesStacked
  59260. // ) {
  59261. // filterMode = 'empty';
  59262. // }
  59263. // TODO
  59264. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  59265. // Process series data
  59266. each$23(seriesModels, function (seriesModel) {
  59267. var seriesData = seriesModel.getData();
  59268. var dataDims = seriesData.mapDimension(axisDim, true);
  59269. if (filterMode === 'weakFilter') {
  59270. seriesData.filterSelf(function (dataIndex) {
  59271. var leftOut;
  59272. var rightOut;
  59273. var hasValue;
  59274. for (var i = 0; i < dataDims.length; i++) {
  59275. var value = seriesData.get(dataDims[i], dataIndex);
  59276. var thisHasValue = !isNaN(value);
  59277. var thisLeftOut = value < valueWindow[0];
  59278. var thisRightOut = value > valueWindow[1];
  59279. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  59280. return true;
  59281. }
  59282. thisHasValue && (hasValue = true);
  59283. thisLeftOut && (leftOut = true);
  59284. thisRightOut && (rightOut = true);
  59285. }
  59286. // If both left out and right out, do not filter.
  59287. return hasValue && leftOut && rightOut;
  59288. });
  59289. }
  59290. else {
  59291. each$23(dataDims, function (dim) {
  59292. if (filterMode === 'empty') {
  59293. seriesModel.setData(
  59294. seriesData.map(dim, function (value) {
  59295. return !isInWindow(value) ? NaN : value;
  59296. })
  59297. );
  59298. }
  59299. else {
  59300. var range = {};
  59301. range[dim] = valueWindow;
  59302. // console.time('select');
  59303. seriesData.selectRange(range);
  59304. // console.timeEnd('select');
  59305. }
  59306. });
  59307. }
  59308. each$23(dataDims, function (dim) {
  59309. seriesData.setApproximateExtent(valueWindow, dim);
  59310. });
  59311. });
  59312. function isInWindow(value) {
  59313. return value >= valueWindow[0] && value <= valueWindow[1];
  59314. }
  59315. }
  59316. };
  59317. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  59318. var dataExtent = [Infinity, -Infinity];
  59319. each$23(seriesModels, function (seriesModel) {
  59320. var seriesData = seriesModel.getData();
  59321. if (seriesData) {
  59322. each$23(seriesData.mapDimension(axisDim, true), function (dim) {
  59323. var seriesExtent = seriesData.getApproximateExtent(dim);
  59324. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  59325. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  59326. });
  59327. }
  59328. });
  59329. if (dataExtent[1] < dataExtent[0]) {
  59330. dataExtent = [NaN, NaN];
  59331. }
  59332. // It is important to get "consistent" extent when more then one axes is
  59333. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  59334. // when zooming. But it is difficult to know what is "consistent", considering
  59335. // axes have different type or even different meanings (For example, two
  59336. // time axes are used to compare data of the same date in different years).
  59337. // So basically dataZoom just obtains extent by series.data (in category axis
  59338. // extent can be obtained from axis.data).
  59339. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  59340. // consistent.
  59341. fixExtentByAxis(axisProxy, dataExtent);
  59342. return dataExtent;
  59343. }
  59344. function fixExtentByAxis(axisProxy, dataExtent) {
  59345. var axisModel = axisProxy.getAxisModel();
  59346. var min = axisModel.getMin(true);
  59347. // For category axis, if min/max/scale are not set, extent is determined
  59348. // by axis.data by default.
  59349. var isCategoryAxis = axisModel.get('type') === 'category';
  59350. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  59351. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  59352. dataExtent[0] = min;
  59353. }
  59354. else if (isCategoryAxis) {
  59355. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  59356. }
  59357. var max = axisModel.getMax(true);
  59358. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  59359. dataExtent[1] = max;
  59360. }
  59361. else if (isCategoryAxis) {
  59362. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  59363. }
  59364. if (!axisModel.get('scale', true)) {
  59365. dataExtent[0] > 0 && (dataExtent[0] = 0);
  59366. dataExtent[1] < 0 && (dataExtent[1] = 0);
  59367. }
  59368. // For value axis, if min/max/scale are not set, we just use the extent obtained
  59369. // by series data, which may be a little different from the extent calculated by
  59370. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  59371. // little when zooming. So it will not be fixed until some users require it strongly.
  59372. return dataExtent;
  59373. }
  59374. function setAxisModel(axisProxy, isRestore) {
  59375. var axisModel = axisProxy.getAxisModel();
  59376. var percentWindow = axisProxy._percentWindow;
  59377. var valueWindow = axisProxy._valueWindow;
  59378. if (!percentWindow) {
  59379. return;
  59380. }
  59381. // [0, 500]: arbitrary value, guess axis extent.
  59382. var precision = getPixelPrecision(valueWindow, [0, 500]);
  59383. precision = Math.min(precision, 20);
  59384. // isRestore or isFull
  59385. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  59386. axisModel.setRange(
  59387. useOrigin ? null : +valueWindow[0].toFixed(precision),
  59388. useOrigin ? null : +valueWindow[1].toFixed(precision)
  59389. );
  59390. }
  59391. function setMinMaxSpan(axisProxy) {
  59392. var minMaxSpan = axisProxy._minMaxSpan = {};
  59393. var dataZoomModel = axisProxy._dataZoomModel;
  59394. each$23(['min', 'max'], function (minMax) {
  59395. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  59396. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  59397. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  59398. if (valueSpan != null) {
  59399. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  59400. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  59401. if (valueSpan != null) {
  59402. var dataExtent = axisProxy._dataExtent;
  59403. minMaxSpan[minMax + 'Span'] = linearMap(
  59404. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  59405. );
  59406. }
  59407. }
  59408. });
  59409. }
  59410. var each$22 = each$1;
  59411. var eachAxisDim = eachAxisDim$1;
  59412. var DataZoomModel = extendComponentModel({
  59413. type: 'dataZoom',
  59414. dependencies: [
  59415. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  59416. ],
  59417. /**
  59418. * @protected
  59419. */
  59420. defaultOption: {
  59421. zlevel: 0,
  59422. z: 4, // Higher than normal component (z: 2).
  59423. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  59424. xAxisIndex: null, // Default the first horizontal category axis.
  59425. yAxisIndex: null, // Default the first vertical category axis.
  59426. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  59427. // 'filter': data items which are out of window will be removed. This option is
  59428. // applicable when filtering outliers. For each data item, it will be
  59429. // filtered if one of the relevant dimensions is out of the window.
  59430. // 'weakFilter': data items which are out of window will be removed. This option
  59431. // is applicable when filtering outliers. For each data item, it will be
  59432. // filtered only if all of the relevant dimensions are out of the same
  59433. // side of the window.
  59434. // 'empty': data items which are out of window will be set to empty.
  59435. // This option is applicable when user should not neglect
  59436. // that there are some data items out of window.
  59437. // 'none': Do not filter.
  59438. // Taking line chart as an example, line will be broken in
  59439. // the filtered points when filterModel is set to 'empty', but
  59440. // be connected when set to 'filter'.
  59441. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  59442. // default 100. Do not throttle when use null/undefined.
  59443. // If animation === true and animationDurationUpdate > 0,
  59444. // default value is 100, otherwise 20.
  59445. start: 0, // Start percent. 0 ~ 100
  59446. end: 100, // End percent. 0 ~ 100
  59447. startValue: null, // Start value. If startValue specified, start is ignored.
  59448. endValue: null, // End value. If endValue specified, end is ignored.
  59449. minSpan: null, // 0 ~ 100
  59450. maxSpan: null, // 0 ~ 100
  59451. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  59452. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  59453. rangeMode: null // Array, can be 'value' or 'percent'.
  59454. },
  59455. /**
  59456. * @override
  59457. */
  59458. init: function (option, parentModel, ecModel) {
  59459. /**
  59460. * key like x_0, y_1
  59461. * @private
  59462. * @type {Object}
  59463. */
  59464. this._dataIntervalByAxis = {};
  59465. /**
  59466. * @private
  59467. */
  59468. this._dataInfo = {};
  59469. /**
  59470. * key like x_0, y_1
  59471. * @private
  59472. */
  59473. this._axisProxies = {};
  59474. /**
  59475. * @readOnly
  59476. */
  59477. this.textStyleModel;
  59478. /**
  59479. * @private
  59480. */
  59481. this._autoThrottle = true;
  59482. /**
  59483. * 'percent' or 'value'
  59484. * @private
  59485. */
  59486. this._rangePropMode = ['percent', 'percent'];
  59487. var rawOption = retrieveRaw(option);
  59488. this.mergeDefaultAndTheme(option, ecModel);
  59489. this.doInit(rawOption);
  59490. },
  59491. /**
  59492. * @override
  59493. */
  59494. mergeOption: function (newOption) {
  59495. var rawOption = retrieveRaw(newOption);
  59496. //FIX #2591
  59497. merge(this.option, newOption, true);
  59498. this.doInit(rawOption);
  59499. },
  59500. /**
  59501. * @protected
  59502. */
  59503. doInit: function (rawOption) {
  59504. var thisOption = this.option;
  59505. // Disable realtime view update if canvas is not supported.
  59506. if (!env$1.canvasSupported) {
  59507. thisOption.realtime = false;
  59508. }
  59509. this._setDefaultThrottle(rawOption);
  59510. updateRangeUse(this, rawOption);
  59511. each$22([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  59512. // start/end has higher priority over startValue/endValue if they
  59513. // both set, but we should make chart.setOption({endValue: 1000})
  59514. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  59515. if (this._rangePropMode[index] === 'value') {
  59516. thisOption[names[0]] = null;
  59517. }
  59518. // Otherwise do nothing and use the merge result.
  59519. }, this);
  59520. this.textStyleModel = this.getModel('textStyle');
  59521. this._resetTarget();
  59522. this._giveAxisProxies();
  59523. },
  59524. /**
  59525. * @private
  59526. */
  59527. _giveAxisProxies: function () {
  59528. var axisProxies = this._axisProxies;
  59529. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  59530. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  59531. // If exists, share axisProxy with other dataZoomModels.
  59532. var axisProxy = axisModel.__dzAxisProxy || (
  59533. // Use the first dataZoomModel as the main model of axisProxy.
  59534. axisModel.__dzAxisProxy = new AxisProxy(
  59535. dimNames.name, axisIndex, this, ecModel
  59536. )
  59537. );
  59538. // FIXME
  59539. // dispose __dzAxisProxy
  59540. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  59541. }, this);
  59542. },
  59543. /**
  59544. * @private
  59545. */
  59546. _resetTarget: function () {
  59547. var thisOption = this.option;
  59548. var autoMode = this._judgeAutoMode();
  59549. eachAxisDim(function (dimNames) {
  59550. var axisIndexName = dimNames.axisIndex;
  59551. thisOption[axisIndexName] = normalizeToArray(
  59552. thisOption[axisIndexName]
  59553. );
  59554. }, this);
  59555. if (autoMode === 'axisIndex') {
  59556. this._autoSetAxisIndex();
  59557. }
  59558. else if (autoMode === 'orient') {
  59559. this._autoSetOrient();
  59560. }
  59561. },
  59562. /**
  59563. * @private
  59564. */
  59565. _judgeAutoMode: function () {
  59566. // Auto set only works for setOption at the first time.
  59567. // The following is user's reponsibility. So using merged
  59568. // option is OK.
  59569. var thisOption = this.option;
  59570. var hasIndexSpecified = false;
  59571. eachAxisDim(function (dimNames) {
  59572. // When user set axisIndex as a empty array, we think that user specify axisIndex
  59573. // but do not want use auto mode. Because empty array may be encountered when
  59574. // some error occured.
  59575. if (thisOption[dimNames.axisIndex] != null) {
  59576. hasIndexSpecified = true;
  59577. }
  59578. }, this);
  59579. var orient = thisOption.orient;
  59580. if (orient == null && hasIndexSpecified) {
  59581. return 'orient';
  59582. }
  59583. else if (!hasIndexSpecified) {
  59584. if (orient == null) {
  59585. thisOption.orient = 'horizontal';
  59586. }
  59587. return 'axisIndex';
  59588. }
  59589. },
  59590. /**
  59591. * @private
  59592. */
  59593. _autoSetAxisIndex: function () {
  59594. var autoAxisIndex = true;
  59595. var orient = this.get('orient', true);
  59596. var thisOption = this.option;
  59597. var dependentModels = this.dependentModels;
  59598. if (autoAxisIndex) {
  59599. // Find axis that parallel to dataZoom as default.
  59600. var dimName = orient === 'vertical' ? 'y' : 'x';
  59601. if (dependentModels[dimName + 'Axis'].length) {
  59602. thisOption[dimName + 'AxisIndex'] = [0];
  59603. autoAxisIndex = false;
  59604. }
  59605. else {
  59606. each$22(dependentModels.singleAxis, function (singleAxisModel) {
  59607. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  59608. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  59609. autoAxisIndex = false;
  59610. }
  59611. });
  59612. }
  59613. }
  59614. if (autoAxisIndex) {
  59615. // Find the first category axis as default. (consider polar)
  59616. eachAxisDim(function (dimNames) {
  59617. if (!autoAxisIndex) {
  59618. return;
  59619. }
  59620. var axisIndices = [];
  59621. var axisModels = this.dependentModels[dimNames.axis];
  59622. if (axisModels.length && !axisIndices.length) {
  59623. for (var i = 0, len = axisModels.length; i < len; i++) {
  59624. if (axisModels[i].get('type') === 'category') {
  59625. axisIndices.push(i);
  59626. }
  59627. }
  59628. }
  59629. thisOption[dimNames.axisIndex] = axisIndices;
  59630. if (axisIndices.length) {
  59631. autoAxisIndex = false;
  59632. }
  59633. }, this);
  59634. }
  59635. if (autoAxisIndex) {
  59636. // FIXME
  59637. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  59638. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  59639. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  59640. // dataZoom component auto adopts series that reference to
  59641. // both xAxis and yAxis which type is 'value'.
  59642. this.ecModel.eachSeries(function (seriesModel) {
  59643. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  59644. eachAxisDim(function (dimNames) {
  59645. var axisIndices = thisOption[dimNames.axisIndex];
  59646. var axisIndex = seriesModel.get(dimNames.axisIndex);
  59647. var axisId = seriesModel.get(dimNames.axisId);
  59648. var axisModel = seriesModel.ecModel.queryComponents({
  59649. mainType: dimNames.axis,
  59650. index: axisIndex,
  59651. id: axisId
  59652. })[0];
  59653. if (__DEV__) {
  59654. if (!axisModel) {
  59655. throw new Error(
  59656. dimNames.axis + ' "' + retrieve(
  59657. axisIndex,
  59658. axisId,
  59659. 0
  59660. ) + '" not found'
  59661. );
  59662. }
  59663. }
  59664. axisIndex = axisModel.componentIndex;
  59665. if (indexOf(axisIndices, axisIndex) < 0) {
  59666. axisIndices.push(axisIndex);
  59667. }
  59668. });
  59669. }
  59670. }, this);
  59671. }
  59672. },
  59673. /**
  59674. * @private
  59675. */
  59676. _autoSetOrient: function () {
  59677. var dim;
  59678. // Find the first axis
  59679. this.eachTargetAxis(function (dimNames) {
  59680. !dim && (dim = dimNames.name);
  59681. }, this);
  59682. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  59683. },
  59684. /**
  59685. * @private
  59686. */
  59687. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  59688. // FIXME
  59689. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  59690. // 例如series.type === scatter时。
  59691. var is = true;
  59692. eachAxisDim(function (dimNames) {
  59693. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  59694. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  59695. if (!axisModel || axisModel.get('type') !== axisType) {
  59696. is = false;
  59697. }
  59698. }, this);
  59699. return is;
  59700. },
  59701. /**
  59702. * @private
  59703. */
  59704. _setDefaultThrottle: function (rawOption) {
  59705. // When first time user set throttle, auto throttle ends.
  59706. if (rawOption.hasOwnProperty('throttle')) {
  59707. this._autoThrottle = false;
  59708. }
  59709. if (this._autoThrottle) {
  59710. var globalOption = this.ecModel.option;
  59711. this.option.throttle =
  59712. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  59713. ? 100 : 20;
  59714. }
  59715. },
  59716. /**
  59717. * @public
  59718. */
  59719. getFirstTargetAxisModel: function () {
  59720. var firstAxisModel;
  59721. eachAxisDim(function (dimNames) {
  59722. if (firstAxisModel == null) {
  59723. var indices = this.get(dimNames.axisIndex);
  59724. if (indices.length) {
  59725. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  59726. }
  59727. }
  59728. }, this);
  59729. return firstAxisModel;
  59730. },
  59731. /**
  59732. * @public
  59733. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  59734. */
  59735. eachTargetAxis: function (callback, context) {
  59736. var ecModel = this.ecModel;
  59737. eachAxisDim(function (dimNames) {
  59738. each$22(
  59739. this.get(dimNames.axisIndex),
  59740. function (axisIndex) {
  59741. callback.call(context, dimNames, axisIndex, this, ecModel);
  59742. },
  59743. this
  59744. );
  59745. }, this);
  59746. },
  59747. /**
  59748. * @param {string} dimName
  59749. * @param {number} axisIndex
  59750. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  59751. */
  59752. getAxisProxy: function (dimName, axisIndex) {
  59753. return this._axisProxies[dimName + '_' + axisIndex];
  59754. },
  59755. /**
  59756. * @param {string} dimName
  59757. * @param {number} axisIndex
  59758. * @return {module:echarts/model/Model} If not found, return null/undefined.
  59759. */
  59760. getAxisModel: function (dimName, axisIndex) {
  59761. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  59762. return axisProxy && axisProxy.getAxisModel();
  59763. },
  59764. /**
  59765. * If not specified, set to undefined.
  59766. *
  59767. * @public
  59768. * @param {Object} opt
  59769. * @param {number} [opt.start]
  59770. * @param {number} [opt.end]
  59771. * @param {number} [opt.startValue]
  59772. * @param {number} [opt.endValue]
  59773. * @param {boolean} [ignoreUpdateRangeUsg=false]
  59774. */
  59775. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  59776. var option = this.option;
  59777. each$22([['start', 'startValue'], ['end', 'endValue']], function (names) {
  59778. // If only one of 'start' and 'startValue' is not null/undefined, the other
  59779. // should be cleared, which enable clear the option.
  59780. // If both of them are not set, keep option with the original value, which
  59781. // enable use only set start but not set end when calling `dispatchAction`.
  59782. // The same as 'end' and 'endValue'.
  59783. if (opt[names[0]] != null || opt[names[1]] != null) {
  59784. option[names[0]] = opt[names[0]];
  59785. option[names[1]] = opt[names[1]];
  59786. }
  59787. }, this);
  59788. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  59789. },
  59790. /**
  59791. * @public
  59792. * @return {Array.<number>} [startPercent, endPercent]
  59793. */
  59794. getPercentRange: function () {
  59795. var axisProxy = this.findRepresentativeAxisProxy();
  59796. if (axisProxy) {
  59797. return axisProxy.getDataPercentWindow();
  59798. }
  59799. },
  59800. /**
  59801. * @public
  59802. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  59803. *
  59804. * @param {string} [axisDimName]
  59805. * @param {number} [axisIndex]
  59806. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  59807. */
  59808. getValueRange: function (axisDimName, axisIndex) {
  59809. if (axisDimName == null && axisIndex == null) {
  59810. var axisProxy = this.findRepresentativeAxisProxy();
  59811. if (axisProxy) {
  59812. return axisProxy.getDataValueWindow();
  59813. }
  59814. }
  59815. else {
  59816. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  59817. }
  59818. },
  59819. /**
  59820. * @public
  59821. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  59822. * corresponding to the axisModel
  59823. * @return {module:echarts/component/dataZoom/AxisProxy}
  59824. */
  59825. findRepresentativeAxisProxy: function (axisModel) {
  59826. if (axisModel) {
  59827. return axisModel.__dzAxisProxy;
  59828. }
  59829. // Find the first hosted axisProxy
  59830. var axisProxies = this._axisProxies;
  59831. for (var key in axisProxies) {
  59832. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  59833. return axisProxies[key];
  59834. }
  59835. }
  59836. // If no hosted axis find not hosted axisProxy.
  59837. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  59838. // and the option.start or option.end settings are different. The percentRange
  59839. // should follow axisProxy.
  59840. // (We encounter this problem in toolbox data zoom.)
  59841. for (var key in axisProxies) {
  59842. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  59843. return axisProxies[key];
  59844. }
  59845. }
  59846. },
  59847. /**
  59848. * @return {Array.<string>}
  59849. */
  59850. getRangePropMode: function () {
  59851. return this._rangePropMode.slice();
  59852. }
  59853. });
  59854. function retrieveRaw(option) {
  59855. var ret = {};
  59856. each$22(
  59857. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  59858. function (name) {
  59859. option.hasOwnProperty(name) && (ret[name] = option[name]);
  59860. }
  59861. );
  59862. return ret;
  59863. }
  59864. function updateRangeUse(dataZoomModel, rawOption) {
  59865. var rangePropMode = dataZoomModel._rangePropMode;
  59866. var rangeModeInOption = dataZoomModel.get('rangeMode');
  59867. each$22([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  59868. var percentSpecified = rawOption[names[0]] != null;
  59869. var valueSpecified = rawOption[names[1]] != null;
  59870. if (percentSpecified && !valueSpecified) {
  59871. rangePropMode[index] = 'percent';
  59872. }
  59873. else if (!percentSpecified && valueSpecified) {
  59874. rangePropMode[index] = 'value';
  59875. }
  59876. else if (rangeModeInOption) {
  59877. rangePropMode[index] = rangeModeInOption[index];
  59878. }
  59879. else if (percentSpecified) { // percentSpecified && valueSpecified
  59880. rangePropMode[index] = 'percent';
  59881. }
  59882. // else remain its original setting.
  59883. });
  59884. }
  59885. var DataZoomView = Component.extend({
  59886. type: 'dataZoom',
  59887. render: function (dataZoomModel, ecModel, api, payload) {
  59888. this.dataZoomModel = dataZoomModel;
  59889. this.ecModel = ecModel;
  59890. this.api = api;
  59891. },
  59892. /**
  59893. * Find the first target coordinate system.
  59894. *
  59895. * @protected
  59896. * @return {Object} {
  59897. * grid: [
  59898. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  59899. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  59900. * ...
  59901. * ], // cartesians must not be null/undefined.
  59902. * polar: [
  59903. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  59904. * ...
  59905. * ], // polars must not be null/undefined.
  59906. * singleAxis: [
  59907. * {model: coord0, axisModels: [], coordIndex: 0}
  59908. * ]
  59909. */
  59910. getTargetCoordInfo: function () {
  59911. var dataZoomModel = this.dataZoomModel;
  59912. var ecModel = this.ecModel;
  59913. var coordSysLists = {};
  59914. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  59915. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  59916. if (axisModel) {
  59917. var coordModel = axisModel.getCoordSysModel();
  59918. coordModel && save(
  59919. coordModel,
  59920. axisModel,
  59921. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  59922. coordModel.componentIndex
  59923. );
  59924. }
  59925. }, this);
  59926. function save(coordModel, axisModel, store, coordIndex) {
  59927. var item;
  59928. for (var i = 0; i < store.length; i++) {
  59929. if (store[i].model === coordModel) {
  59930. item = store[i];
  59931. break;
  59932. }
  59933. }
  59934. if (!item) {
  59935. store.push(item = {
  59936. model: coordModel, axisModels: [], coordIndex: coordIndex
  59937. });
  59938. }
  59939. item.axisModels.push(axisModel);
  59940. }
  59941. return coordSysLists;
  59942. }
  59943. });
  59944. var SliderZoomModel = DataZoomModel.extend({
  59945. type: 'dataZoom.slider',
  59946. layoutMode: 'box',
  59947. /**
  59948. * @protected
  59949. */
  59950. defaultOption: {
  59951. show: true,
  59952. // ph => placeholder. Using placehoder here because
  59953. // deault value can only be drived in view stage.
  59954. right: 'ph', // Default align to grid rect.
  59955. top: 'ph', // Default align to grid rect.
  59956. width: 'ph', // Default align to grid rect.
  59957. height: 'ph', // Default align to grid rect.
  59958. left: null, // Default align to grid rect.
  59959. bottom: null, // Default align to grid rect.
  59960. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  59961. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  59962. // highest priority, remain for compatibility of
  59963. // previous version, but not recommended any more.
  59964. dataBackground: {
  59965. lineStyle: {
  59966. color: '#2f4554',
  59967. width: 0.5,
  59968. opacity: 0.3
  59969. },
  59970. areaStyle: {
  59971. color: 'rgba(47,69,84,0.3)',
  59972. opacity: 0.3
  59973. }
  59974. },
  59975. borderColor: '#ddd', // border color of the box. For compatibility,
  59976. // if dataBackgroundColor is set, borderColor
  59977. // is ignored.
  59978. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  59979. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  59980. // 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',
  59981. 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',
  59982. // Percent of the slider height
  59983. handleSize: '100%',
  59984. handleStyle: {
  59985. color: '#a7b7cc'
  59986. },
  59987. labelPrecision: null,
  59988. labelFormatter: null,
  59989. showDetail: true,
  59990. showDataShadow: 'auto', // Default auto decision.
  59991. realtime: true,
  59992. zoomLock: false, // Whether disable zoom.
  59993. textStyle: {
  59994. color: '#333'
  59995. }
  59996. }
  59997. });
  59998. var Rect$2 = Rect;
  59999. var linearMap$2 = linearMap;
  60000. var asc$2 = asc;
  60001. var bind$4 = bind;
  60002. var each$24 = each$1;
  60003. // Constants
  60004. var DEFAULT_LOCATION_EDGE_GAP = 7;
  60005. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  60006. var DEFAULT_FILLER_SIZE = 30;
  60007. var HORIZONTAL = 'horizontal';
  60008. var VERTICAL = 'vertical';
  60009. var LABEL_GAP = 5;
  60010. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  60011. var SliderZoomView = DataZoomView.extend({
  60012. type: 'dataZoom.slider',
  60013. init: function (ecModel, api) {
  60014. /**
  60015. * @private
  60016. * @type {Object}
  60017. */
  60018. this._displayables = {};
  60019. /**
  60020. * @private
  60021. * @type {string}
  60022. */
  60023. this._orient;
  60024. /**
  60025. * [0, 100]
  60026. * @private
  60027. */
  60028. this._range;
  60029. /**
  60030. * [coord of the first handle, coord of the second handle]
  60031. * @private
  60032. */
  60033. this._handleEnds;
  60034. /**
  60035. * [length, thick]
  60036. * @private
  60037. * @type {Array.<number>}
  60038. */
  60039. this._size;
  60040. /**
  60041. * @private
  60042. * @type {number}
  60043. */
  60044. this._handleWidth;
  60045. /**
  60046. * @private
  60047. * @type {number}
  60048. */
  60049. this._handleHeight;
  60050. /**
  60051. * @private
  60052. */
  60053. this._location;
  60054. /**
  60055. * @private
  60056. */
  60057. this._dragging;
  60058. /**
  60059. * @private
  60060. */
  60061. this._dataShadowInfo;
  60062. this.api = api;
  60063. },
  60064. /**
  60065. * @override
  60066. */
  60067. render: function (dataZoomModel, ecModel, api, payload) {
  60068. SliderZoomView.superApply(this, 'render', arguments);
  60069. createOrUpdate(
  60070. this,
  60071. '_dispatchZoomAction',
  60072. this.dataZoomModel.get('throttle'),
  60073. 'fixRate'
  60074. );
  60075. this._orient = dataZoomModel.get('orient');
  60076. if (this.dataZoomModel.get('show') === false) {
  60077. this.group.removeAll();
  60078. return;
  60079. }
  60080. // Notice: this._resetInterval() should not be executed when payload.type
  60081. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  60082. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  60083. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  60084. this._buildView();
  60085. }
  60086. this._updateView();
  60087. },
  60088. /**
  60089. * @override
  60090. */
  60091. remove: function () {
  60092. SliderZoomView.superApply(this, 'remove', arguments);
  60093. clear(this, '_dispatchZoomAction');
  60094. },
  60095. /**
  60096. * @override
  60097. */
  60098. dispose: function () {
  60099. SliderZoomView.superApply(this, 'dispose', arguments);
  60100. clear(this, '_dispatchZoomAction');
  60101. },
  60102. _buildView: function () {
  60103. var thisGroup = this.group;
  60104. thisGroup.removeAll();
  60105. this._resetLocation();
  60106. this._resetInterval();
  60107. var barGroup = this._displayables.barGroup = new Group();
  60108. this._renderBackground();
  60109. this._renderHandle();
  60110. this._renderDataShadow();
  60111. thisGroup.add(barGroup);
  60112. this._positionGroup();
  60113. },
  60114. /**
  60115. * @private
  60116. */
  60117. _resetLocation: function () {
  60118. var dataZoomModel = this.dataZoomModel;
  60119. var api = this.api;
  60120. // If some of x/y/width/height are not specified,
  60121. // auto-adapt according to target grid.
  60122. var coordRect = this._findCoordRect();
  60123. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  60124. // Default align by coordinate system rect.
  60125. var positionInfo = this._orient === HORIZONTAL
  60126. ? {
  60127. // Why using 'right', because right should be used in vertical,
  60128. // and it is better to be consistent for dealing with position param merge.
  60129. right: ecSize.width - coordRect.x - coordRect.width,
  60130. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  60131. width: coordRect.width,
  60132. height: DEFAULT_FILLER_SIZE
  60133. }
  60134. : { // vertical
  60135. right: DEFAULT_LOCATION_EDGE_GAP,
  60136. top: coordRect.y,
  60137. width: DEFAULT_FILLER_SIZE,
  60138. height: coordRect.height
  60139. };
  60140. // Do not write back to option and replace value 'ph', because
  60141. // the 'ph' value should be recalculated when resize.
  60142. var layoutParams = getLayoutParams(dataZoomModel.option);
  60143. // Replace the placeholder value.
  60144. each$1(['right', 'top', 'width', 'height'], function (name) {
  60145. if (layoutParams[name] === 'ph') {
  60146. layoutParams[name] = positionInfo[name];
  60147. }
  60148. });
  60149. var layoutRect = getLayoutRect(
  60150. layoutParams,
  60151. ecSize,
  60152. dataZoomModel.padding
  60153. );
  60154. this._location = {x: layoutRect.x, y: layoutRect.y};
  60155. this._size = [layoutRect.width, layoutRect.height];
  60156. this._orient === VERTICAL && this._size.reverse();
  60157. },
  60158. /**
  60159. * @private
  60160. */
  60161. _positionGroup: function () {
  60162. var thisGroup = this.group;
  60163. var location = this._location;
  60164. var orient = this._orient;
  60165. // Just use the first axis to determine mapping.
  60166. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  60167. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  60168. var barGroup = this._displayables.barGroup;
  60169. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  60170. // Transform barGroup.
  60171. barGroup.attr(
  60172. (orient === HORIZONTAL && !inverse)
  60173. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  60174. : (orient === HORIZONTAL && inverse)
  60175. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  60176. : (orient === VERTICAL && !inverse)
  60177. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  60178. // Dont use Math.PI, considering shadow direction.
  60179. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  60180. );
  60181. // Position barGroup
  60182. var rect = thisGroup.getBoundingRect([barGroup]);
  60183. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  60184. },
  60185. /**
  60186. * @private
  60187. */
  60188. _getViewExtent: function () {
  60189. return [0, this._size[0]];
  60190. },
  60191. _renderBackground: function () {
  60192. var dataZoomModel = this.dataZoomModel;
  60193. var size = this._size;
  60194. var barGroup = this._displayables.barGroup;
  60195. barGroup.add(new Rect$2({
  60196. silent: true,
  60197. shape: {
  60198. x: 0, y: 0, width: size[0], height: size[1]
  60199. },
  60200. style: {
  60201. fill: dataZoomModel.get('backgroundColor')
  60202. },
  60203. z2: -40
  60204. }));
  60205. // Click panel, over shadow, below handles.
  60206. barGroup.add(new Rect$2({
  60207. shape: {
  60208. x: 0, y: 0, width: size[0], height: size[1]
  60209. },
  60210. style: {
  60211. fill: 'transparent'
  60212. },
  60213. z2: 0,
  60214. onclick: bind(this._onClickPanelClick, this)
  60215. }));
  60216. },
  60217. _renderDataShadow: function () {
  60218. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  60219. if (!info) {
  60220. return;
  60221. }
  60222. var size = this._size;
  60223. var seriesModel = info.series;
  60224. var data = seriesModel.getRawData();
  60225. var otherDim = seriesModel.getShadowDim
  60226. ? seriesModel.getShadowDim() // @see candlestick
  60227. : info.otherDim;
  60228. if (otherDim == null) {
  60229. return;
  60230. }
  60231. var otherDataExtent = data.getDataExtent(otherDim);
  60232. // Nice extent.
  60233. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  60234. otherDataExtent = [
  60235. otherDataExtent[0] - otherOffset,
  60236. otherDataExtent[1] + otherOffset
  60237. ];
  60238. var otherShadowExtent = [0, size[1]];
  60239. var thisShadowExtent = [0, size[0]];
  60240. var areaPoints = [[size[0], 0], [0, 0]];
  60241. var linePoints = [];
  60242. var step = thisShadowExtent[1] / (data.count() - 1);
  60243. var thisCoord = 0;
  60244. // Optimize for large data shadow
  60245. var stride = Math.round(data.count() / size[0]);
  60246. var lastIsEmpty;
  60247. data.each([otherDim], function (value, index) {
  60248. if (stride > 0 && (index % stride)) {
  60249. thisCoord += step;
  60250. return;
  60251. }
  60252. // FIXME
  60253. // Should consider axis.min/axis.max when drawing dataShadow.
  60254. // FIXME
  60255. // 应该使用统一的空判断?还是在list里进行空判断?
  60256. var isEmpty = value == null || isNaN(value) || value === '';
  60257. // See #4235.
  60258. var otherCoord = isEmpty
  60259. ? 0 : linearMap$2(value, otherDataExtent, otherShadowExtent, true);
  60260. // Attempt to draw data shadow precisely when there are empty value.
  60261. if (isEmpty && !lastIsEmpty && index) {
  60262. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  60263. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  60264. }
  60265. else if (!isEmpty && lastIsEmpty) {
  60266. areaPoints.push([thisCoord, 0]);
  60267. linePoints.push([thisCoord, 0]);
  60268. }
  60269. areaPoints.push([thisCoord, otherCoord]);
  60270. linePoints.push([thisCoord, otherCoord]);
  60271. thisCoord += step;
  60272. lastIsEmpty = isEmpty;
  60273. });
  60274. var dataZoomModel = this.dataZoomModel;
  60275. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  60276. this._displayables.barGroup.add(new Polygon({
  60277. shape: {points: areaPoints},
  60278. style: defaults(
  60279. {fill: dataZoomModel.get('dataBackgroundColor')},
  60280. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  60281. ),
  60282. silent: true,
  60283. z2: -20
  60284. }));
  60285. this._displayables.barGroup.add(new Polyline({
  60286. shape: {points: linePoints},
  60287. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  60288. silent: true,
  60289. z2: -19
  60290. }));
  60291. },
  60292. _prepareDataShadowInfo: function () {
  60293. var dataZoomModel = this.dataZoomModel;
  60294. var showDataShadow = dataZoomModel.get('showDataShadow');
  60295. if (showDataShadow === false) {
  60296. return;
  60297. }
  60298. // Find a representative series.
  60299. var result;
  60300. var ecModel = this.ecModel;
  60301. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  60302. var seriesModels = dataZoomModel
  60303. .getAxisProxy(dimNames.name, axisIndex)
  60304. .getTargetSeriesModels();
  60305. each$1(seriesModels, function (seriesModel) {
  60306. if (result) {
  60307. return;
  60308. }
  60309. if (showDataShadow !== true && indexOf(
  60310. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  60311. ) < 0
  60312. ) {
  60313. return;
  60314. }
  60315. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  60316. var otherDim = getOtherDim(dimNames.name);
  60317. var otherAxisInverse;
  60318. var coordSys = seriesModel.coordinateSystem;
  60319. if (otherDim != null && coordSys.getOtherAxis) {
  60320. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  60321. }
  60322. otherDim = seriesModel.getData().mapDimension(otherDim);
  60323. result = {
  60324. thisAxis: thisAxis,
  60325. series: seriesModel,
  60326. thisDim: dimNames.name,
  60327. otherDim: otherDim,
  60328. otherAxisInverse: otherAxisInverse
  60329. };
  60330. }, this);
  60331. }, this);
  60332. return result;
  60333. },
  60334. _renderHandle: function () {
  60335. var displaybles = this._displayables;
  60336. var handles = displaybles.handles = [];
  60337. var handleLabels = displaybles.handleLabels = [];
  60338. var barGroup = this._displayables.barGroup;
  60339. var size = this._size;
  60340. var dataZoomModel = this.dataZoomModel;
  60341. barGroup.add(displaybles.filler = new Rect$2({
  60342. draggable: true,
  60343. cursor: getCursor(this._orient),
  60344. drift: bind$4(this._onDragMove, this, 'all'),
  60345. onmousemove: function (e) {
  60346. // Fot mobile devicem, prevent screen slider on the button.
  60347. stop(e.event);
  60348. },
  60349. ondragstart: bind$4(this._showDataInfo, this, true),
  60350. ondragend: bind$4(this._onDragEnd, this),
  60351. onmouseover: bind$4(this._showDataInfo, this, true),
  60352. onmouseout: bind$4(this._showDataInfo, this, false),
  60353. style: {
  60354. fill: dataZoomModel.get('fillerColor'),
  60355. textPosition : 'inside'
  60356. }
  60357. }));
  60358. // Frame border.
  60359. barGroup.add(new Rect$2(subPixelOptimizeRect({
  60360. silent: true,
  60361. shape: {
  60362. x: 0,
  60363. y: 0,
  60364. width: size[0],
  60365. height: size[1]
  60366. },
  60367. style: {
  60368. stroke: dataZoomModel.get('dataBackgroundColor')
  60369. || dataZoomModel.get('borderColor'),
  60370. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  60371. fill: 'rgba(0,0,0,0)'
  60372. }
  60373. })));
  60374. each$24([0, 1], function (handleIndex) {
  60375. var path = createIcon(
  60376. dataZoomModel.get('handleIcon'),
  60377. {
  60378. cursor: getCursor(this._orient),
  60379. draggable: true,
  60380. drift: bind$4(this._onDragMove, this, handleIndex),
  60381. onmousemove: function (e) {
  60382. // Fot mobile devicem, prevent screen slider on the button.
  60383. stop(e.event);
  60384. },
  60385. ondragend: bind$4(this._onDragEnd, this),
  60386. onmouseover: bind$4(this._showDataInfo, this, true),
  60387. onmouseout: bind$4(this._showDataInfo, this, false)
  60388. },
  60389. {x: -1, y: 0, width: 2, height: 2}
  60390. );
  60391. var bRect = path.getBoundingRect();
  60392. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  60393. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  60394. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  60395. var handleColor = dataZoomModel.get('handleColor');
  60396. // Compatitable with previous version
  60397. if (handleColor != null) {
  60398. path.style.fill = handleColor;
  60399. }
  60400. barGroup.add(handles[handleIndex] = path);
  60401. var textStyleModel = dataZoomModel.textStyleModel;
  60402. this.group.add(
  60403. handleLabels[handleIndex] = new Text({
  60404. silent: true,
  60405. invisible: true,
  60406. style: {
  60407. x: 0, y: 0, text: '',
  60408. textVerticalAlign: 'middle',
  60409. textAlign: 'center',
  60410. textFill: textStyleModel.getTextColor(),
  60411. textFont: textStyleModel.getFont()
  60412. },
  60413. z2: 10
  60414. }));
  60415. }, this);
  60416. },
  60417. /**
  60418. * @private
  60419. */
  60420. _resetInterval: function () {
  60421. var range = this._range = this.dataZoomModel.getPercentRange();
  60422. var viewExtent = this._getViewExtent();
  60423. this._handleEnds = [
  60424. linearMap$2(range[0], [0, 100], viewExtent, true),
  60425. linearMap$2(range[1], [0, 100], viewExtent, true)
  60426. ];
  60427. },
  60428. /**
  60429. * @private
  60430. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  60431. * @param {number} delta
  60432. */
  60433. _updateInterval: function (handleIndex, delta) {
  60434. var dataZoomModel = this.dataZoomModel;
  60435. var handleEnds = this._handleEnds;
  60436. var viewExtend = this._getViewExtent();
  60437. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  60438. var percentExtent = [0, 100];
  60439. sliderMove(
  60440. delta,
  60441. handleEnds,
  60442. viewExtend,
  60443. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  60444. minMaxSpan.minSpan != null
  60445. ? linearMap$2(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  60446. minMaxSpan.maxSpan != null
  60447. ? linearMap$2(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  60448. );
  60449. this._range = asc$2([
  60450. linearMap$2(handleEnds[0], viewExtend, percentExtent, true),
  60451. linearMap$2(handleEnds[1], viewExtend, percentExtent, true)
  60452. ]);
  60453. },
  60454. /**
  60455. * @private
  60456. */
  60457. _updateView: function (nonRealtime) {
  60458. var displaybles = this._displayables;
  60459. var handleEnds = this._handleEnds;
  60460. var handleInterval = asc$2(handleEnds.slice());
  60461. var size = this._size;
  60462. each$24([0, 1], function (handleIndex) {
  60463. // Handles
  60464. var handle = displaybles.handles[handleIndex];
  60465. var handleHeight = this._handleHeight;
  60466. handle.attr({
  60467. scale: [handleHeight / 2, handleHeight / 2],
  60468. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  60469. });
  60470. }, this);
  60471. // Filler
  60472. displaybles.filler.setShape({
  60473. x: handleInterval[0],
  60474. y: 0,
  60475. width: handleInterval[1] - handleInterval[0],
  60476. height: size[1]
  60477. });
  60478. this._updateDataInfo(nonRealtime);
  60479. },
  60480. /**
  60481. * @private
  60482. */
  60483. _updateDataInfo: function (nonRealtime) {
  60484. var dataZoomModel = this.dataZoomModel;
  60485. var displaybles = this._displayables;
  60486. var handleLabels = displaybles.handleLabels;
  60487. var orient = this._orient;
  60488. var labelTexts = ['', ''];
  60489. // FIXME
  60490. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  60491. if (dataZoomModel.get('showDetail')) {
  60492. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  60493. if (axisProxy) {
  60494. var axis = axisProxy.getAxisModel().axis;
  60495. var range = this._range;
  60496. var dataInterval = nonRealtime
  60497. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  60498. ? axisProxy.calculateDataWindow({
  60499. start: range[0], end: range[1]
  60500. }).valueWindow
  60501. : axisProxy.getDataValueWindow();
  60502. labelTexts = [
  60503. this._formatLabel(dataInterval[0], axis),
  60504. this._formatLabel(dataInterval[1], axis)
  60505. ];
  60506. }
  60507. }
  60508. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  60509. setLabel.call(this, 0);
  60510. setLabel.call(this, 1);
  60511. function setLabel(handleIndex) {
  60512. // Label
  60513. // Text should not transform by barGroup.
  60514. // Ignore handlers transform
  60515. var barTransform = getTransform(
  60516. displaybles.handles[handleIndex].parent, this.group
  60517. );
  60518. var direction = transformDirection(
  60519. handleIndex === 0 ? 'right' : 'left', barTransform
  60520. );
  60521. var offset = this._handleWidth / 2 + LABEL_GAP;
  60522. var textPoint = applyTransform$1(
  60523. [
  60524. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  60525. this._size[1] / 2
  60526. ],
  60527. barTransform
  60528. );
  60529. handleLabels[handleIndex].setStyle({
  60530. x: textPoint[0],
  60531. y: textPoint[1],
  60532. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  60533. textAlign: orient === HORIZONTAL ? direction : 'center',
  60534. text: labelTexts[handleIndex]
  60535. });
  60536. }
  60537. },
  60538. /**
  60539. * @private
  60540. */
  60541. _formatLabel: function (value, axis) {
  60542. var dataZoomModel = this.dataZoomModel;
  60543. var labelFormatter = dataZoomModel.get('labelFormatter');
  60544. var labelPrecision = dataZoomModel.get('labelPrecision');
  60545. if (labelPrecision == null || labelPrecision === 'auto') {
  60546. labelPrecision = axis.getPixelPrecision();
  60547. }
  60548. var valueStr = (value == null || isNaN(value))
  60549. ? ''
  60550. // FIXME Glue code
  60551. : (axis.type === 'category' || axis.type === 'time')
  60552. ? axis.scale.getLabel(Math.round(value))
  60553. // param of toFixed should less then 20.
  60554. : value.toFixed(Math.min(labelPrecision, 20));
  60555. return isFunction$1(labelFormatter)
  60556. ? labelFormatter(value, valueStr)
  60557. : isString(labelFormatter)
  60558. ? labelFormatter.replace('{value}', valueStr)
  60559. : valueStr;
  60560. },
  60561. /**
  60562. * @private
  60563. * @param {boolean} showOrHide true: show, false: hide
  60564. */
  60565. _showDataInfo: function (showOrHide) {
  60566. // Always show when drgging.
  60567. showOrHide = this._dragging || showOrHide;
  60568. var handleLabels = this._displayables.handleLabels;
  60569. handleLabels[0].attr('invisible', !showOrHide);
  60570. handleLabels[1].attr('invisible', !showOrHide);
  60571. },
  60572. _onDragMove: function (handleIndex, dx, dy) {
  60573. this._dragging = true;
  60574. // Transform dx, dy to bar coordination.
  60575. var barTransform = this._displayables.barGroup.getLocalTransform();
  60576. var vertex = applyTransform$1([dx, dy], barTransform, true);
  60577. this._updateInterval(handleIndex, vertex[0]);
  60578. var realtime = this.dataZoomModel.get('realtime');
  60579. this._updateView(!realtime);
  60580. realtime && this._dispatchZoomAction();
  60581. },
  60582. _onDragEnd: function () {
  60583. this._dragging = false;
  60584. this._showDataInfo(false);
  60585. // While in realtime mode and stream mode, dispatch action when
  60586. // drag end will cause the whole view rerender, which is unnecessary.
  60587. var realtime = this.dataZoomModel.get('realtime');
  60588. !realtime && this._dispatchZoomAction();
  60589. },
  60590. _onClickPanelClick: function (e) {
  60591. var size = this._size;
  60592. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  60593. if (localPoint[0] < 0 || localPoint[0] > size[0]
  60594. || localPoint[1] < 0 || localPoint[1] > size[1]
  60595. ) {
  60596. return;
  60597. }
  60598. var handleEnds = this._handleEnds;
  60599. var center = (handleEnds[0] + handleEnds[1]) / 2;
  60600. this._updateInterval('all', localPoint[0] - center);
  60601. this._updateView();
  60602. this._dispatchZoomAction();
  60603. },
  60604. /**
  60605. * This action will be throttled.
  60606. * @private
  60607. */
  60608. _dispatchZoomAction: function () {
  60609. var range = this._range;
  60610. this.api.dispatchAction({
  60611. type: 'dataZoom',
  60612. from: this.uid,
  60613. dataZoomId: this.dataZoomModel.id,
  60614. start: range[0],
  60615. end: range[1]
  60616. });
  60617. },
  60618. /**
  60619. * @private
  60620. */
  60621. _findCoordRect: function () {
  60622. // Find the grid coresponding to the first axis referred by dataZoom.
  60623. var rect;
  60624. each$24(this.getTargetCoordInfo(), function (coordInfoList) {
  60625. if (!rect && coordInfoList.length) {
  60626. var coordSys = coordInfoList[0].model.coordinateSystem;
  60627. rect = coordSys.getRect && coordSys.getRect();
  60628. }
  60629. });
  60630. if (!rect) {
  60631. var width = this.api.getWidth();
  60632. var height = this.api.getHeight();
  60633. rect = {
  60634. x: width * 0.2,
  60635. y: height * 0.2,
  60636. width: width * 0.6,
  60637. height: height * 0.6
  60638. };
  60639. }
  60640. return rect;
  60641. }
  60642. });
  60643. function getOtherDim(thisDim) {
  60644. // FIXME
  60645. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  60646. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  60647. return map$$1[thisDim];
  60648. }
  60649. function getCursor(orient) {
  60650. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  60651. }
  60652. DataZoomModel.extend({
  60653. type: 'dataZoom.inside',
  60654. /**
  60655. * @protected
  60656. */
  60657. defaultOption: {
  60658. disabled: false, // Whether disable this inside zoom.
  60659. zoomLock: false, // Whether disable zoom but only pan.
  60660. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  60661. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  60662. preventDefaultMouseMove: true
  60663. }
  60664. });
  60665. // Only create one roam controller for each coordinate system.
  60666. // one roam controller might be refered by two inside data zoom
  60667. // components (for example, one for x and one for y). When user
  60668. // pan or zoom, only dispatch one action for those data zoom
  60669. // components.
  60670. var curry$6 = curry;
  60671. var ATTR$1 = '\0_ec_dataZoom_roams';
  60672. /**
  60673. * @public
  60674. * @param {module:echarts/ExtensionAPI} api
  60675. * @param {Object} dataZoomInfo
  60676. * @param {string} dataZoomInfo.coordId
  60677. * @param {Function} dataZoomInfo.containsPoint
  60678. * @param {Array.<string>} dataZoomInfo.allCoordIds
  60679. * @param {string} dataZoomInfo.dataZoomId
  60680. * @param {number} dataZoomInfo.throttleRate
  60681. * @param {Function} dataZoomInfo.panGetRange
  60682. * @param {Function} dataZoomInfo.zoomGetRange
  60683. * @param {boolean} [dataZoomInfo.zoomLock]
  60684. * @param {boolean} [dataZoomInfo.disabled]
  60685. */
  60686. function register$2(api, dataZoomInfo) {
  60687. var store = giveStore(api);
  60688. var theDataZoomId = dataZoomInfo.dataZoomId;
  60689. var theCoordId = dataZoomInfo.coordId;
  60690. // Do clean when a dataZoom changes its target coordnate system.
  60691. // Avoid memory leak, dispose all not-used-registered.
  60692. each$1(store, function (record, coordId) {
  60693. var dataZoomInfos = record.dataZoomInfos;
  60694. if (dataZoomInfos[theDataZoomId]
  60695. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  60696. ) {
  60697. delete dataZoomInfos[theDataZoomId];
  60698. record.count--;
  60699. }
  60700. });
  60701. cleanStore(store);
  60702. var record = store[theCoordId];
  60703. // Create if needed.
  60704. if (!record) {
  60705. record = store[theCoordId] = {
  60706. coordId: theCoordId,
  60707. dataZoomInfos: {},
  60708. count: 0
  60709. };
  60710. record.controller = createController(api, record);
  60711. record.dispatchAction = curry(dispatchAction$1, api);
  60712. }
  60713. // Update reference of dataZoom.
  60714. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  60715. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  60716. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  60717. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  60718. // Consider resize, area should be always updated.
  60719. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  60720. // Update throttle.
  60721. createOrUpdate(
  60722. record,
  60723. 'dispatchAction',
  60724. dataZoomInfo.throttleRate,
  60725. 'fixRate'
  60726. );
  60727. }
  60728. /**
  60729. * @public
  60730. * @param {module:echarts/ExtensionAPI} api
  60731. * @param {string} dataZoomId
  60732. */
  60733. function unregister$1(api, dataZoomId) {
  60734. var store = giveStore(api);
  60735. each$1(store, function (record) {
  60736. record.controller.dispose();
  60737. var dataZoomInfos = record.dataZoomInfos;
  60738. if (dataZoomInfos[dataZoomId]) {
  60739. delete dataZoomInfos[dataZoomId];
  60740. record.count--;
  60741. }
  60742. });
  60743. cleanStore(store);
  60744. }
  60745. /**
  60746. * @public
  60747. */
  60748. function shouldRecordRange(payload, dataZoomId) {
  60749. if (payload && payload.type === 'dataZoom' && payload.batch) {
  60750. for (var i = 0, len = payload.batch.length; i < len; i++) {
  60751. if (payload.batch[i].dataZoomId === dataZoomId) {
  60752. return false;
  60753. }
  60754. }
  60755. }
  60756. return true;
  60757. }
  60758. /**
  60759. * @public
  60760. */
  60761. function generateCoordId(coordModel) {
  60762. return coordModel.type + '\0_' + coordModel.id;
  60763. }
  60764. /**
  60765. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  60766. * @type {Array.<Object>}
  60767. */
  60768. function giveStore(api) {
  60769. // Mount store on zrender instance, so that we do not
  60770. // need to worry about dispose.
  60771. var zr = api.getZr();
  60772. return zr[ATTR$1] || (zr[ATTR$1] = {});
  60773. }
  60774. function createController(api, newRecord) {
  60775. var controller = new RoamController(api.getZr());
  60776. controller.on('pan', curry$6(onPan, newRecord));
  60777. controller.on('zoom', curry$6(onZoom, newRecord));
  60778. return controller;
  60779. }
  60780. function cleanStore(store) {
  60781. each$1(store, function (record, coordId) {
  60782. if (!record.count) {
  60783. record.controller.dispose();
  60784. delete store[coordId];
  60785. }
  60786. });
  60787. }
  60788. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  60789. wrapAndDispatch(record, function (info) {
  60790. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  60791. });
  60792. }
  60793. function onZoom(record, scale, mouseX, mouseY) {
  60794. wrapAndDispatch(record, function (info) {
  60795. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  60796. });
  60797. }
  60798. function wrapAndDispatch(record, getRange) {
  60799. var batch = [];
  60800. each$1(record.dataZoomInfos, function (info) {
  60801. var range = getRange(info);
  60802. !info.disabled && range && batch.push({
  60803. dataZoomId: info.dataZoomId,
  60804. start: range[0],
  60805. end: range[1]
  60806. });
  60807. });
  60808. record.dispatchAction(batch);
  60809. }
  60810. /**
  60811. * This action will be throttled.
  60812. */
  60813. function dispatchAction$1(api, batch) {
  60814. api.dispatchAction({
  60815. type: 'dataZoom',
  60816. batch: batch
  60817. });
  60818. }
  60819. /**
  60820. * Merge roamController settings when multiple dataZooms share one roamController.
  60821. */
  60822. function mergeControllerParams(dataZoomInfos) {
  60823. var controlType;
  60824. var opt = {};
  60825. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  60826. // as string, it is probably revert to reserved word by compress tool. See #7411.
  60827. var prefix = 'type_';
  60828. var typePriority = {
  60829. 'type_true': 2,
  60830. 'type_move': 1,
  60831. 'type_false': 0,
  60832. 'type_undefined': -1
  60833. };
  60834. each$1(dataZoomInfos, function (dataZoomInfo) {
  60835. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  60836. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  60837. controlType = oneType;
  60838. }
  60839. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  60840. extend(opt, dataZoomInfo.roamControllerOpt);
  60841. });
  60842. return {
  60843. controlType: controlType,
  60844. opt: opt
  60845. };
  60846. }
  60847. var bind$5 = bind;
  60848. var InsideZoomView = DataZoomView.extend({
  60849. type: 'dataZoom.inside',
  60850. /**
  60851. * @override
  60852. */
  60853. init: function (ecModel, api) {
  60854. /**
  60855. * 'throttle' is used in this.dispatchAction, so we save range
  60856. * to avoid missing some 'pan' info.
  60857. * @private
  60858. * @type {Array.<number>}
  60859. */
  60860. this._range;
  60861. },
  60862. /**
  60863. * @override
  60864. */
  60865. render: function (dataZoomModel, ecModel, api, payload) {
  60866. InsideZoomView.superApply(this, 'render', arguments);
  60867. // Notice: origin this._range should be maintained, and should not be re-fetched
  60868. // from dataZoomModel when payload.type is 'dataZoom', otherwise 'pan' or 'zoom'
  60869. // info will be missed because of 'throttle' of this.dispatchAction.
  60870. if (shouldRecordRange(payload, dataZoomModel.id)) {
  60871. this._range = dataZoomModel.getPercentRange();
  60872. }
  60873. // Reset controllers.
  60874. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  60875. var allCoordIds = map(coordInfoList, function (coordInfo) {
  60876. return generateCoordId(coordInfo.model);
  60877. });
  60878. each$1(coordInfoList, function (coordInfo) {
  60879. var coordModel = coordInfo.model;
  60880. var dataZoomOption = dataZoomModel.option;
  60881. register$2(
  60882. api,
  60883. {
  60884. coordId: generateCoordId(coordModel),
  60885. allCoordIds: allCoordIds,
  60886. containsPoint: function (e, x, y) {
  60887. return coordModel.coordinateSystem.containPoint([x, y]);
  60888. },
  60889. dataZoomId: dataZoomModel.id,
  60890. throttleRate: dataZoomModel.get('throttle', true),
  60891. panGetRange: bind$5(this._onPan, this, coordInfo, coordSysName),
  60892. zoomGetRange: bind$5(this._onZoom, this, coordInfo, coordSysName),
  60893. zoomLock: dataZoomOption.zoomLock,
  60894. disabled: dataZoomOption.disabled,
  60895. roamControllerOpt: {
  60896. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  60897. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  60898. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  60899. }
  60900. }
  60901. );
  60902. }, this);
  60903. }, this);
  60904. },
  60905. /**
  60906. * @override
  60907. */
  60908. dispose: function () {
  60909. unregister$1(this.api, this.dataZoomModel.id);
  60910. InsideZoomView.superApply(this, 'dispose', arguments);
  60911. this._range = null;
  60912. },
  60913. /**
  60914. * @private
  60915. */
  60916. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  60917. var range = this._range.slice();
  60918. // Calculate transform by the first axis.
  60919. var axisModel = coordInfo.axisModels[0];
  60920. if (!axisModel) {
  60921. return;
  60922. }
  60923. var directionInfo = getDirectionInfo[coordSysName](
  60924. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  60925. );
  60926. var percentDelta = directionInfo.signal
  60927. * (range[1] - range[0])
  60928. * directionInfo.pixel / directionInfo.pixelLength;
  60929. sliderMove(percentDelta, range, [0, 100], 'all');
  60930. return (this._range = range);
  60931. },
  60932. /**
  60933. * @private
  60934. */
  60935. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  60936. var range = this._range.slice();
  60937. // Calculate transform by the first axis.
  60938. var axisModel = coordInfo.axisModels[0];
  60939. if (!axisModel) {
  60940. return;
  60941. }
  60942. var directionInfo = getDirectionInfo[coordSysName](
  60943. null, [mouseX, mouseY], axisModel, controller, coordInfo
  60944. );
  60945. var percentPoint = (
  60946. directionInfo.signal > 0
  60947. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  60948. : (directionInfo.pixel - directionInfo.pixelStart)
  60949. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  60950. scale = Math.max(1 / scale, 0);
  60951. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  60952. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  60953. // Restrict range.
  60954. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  60955. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  60956. return (this._range = range);
  60957. }
  60958. });
  60959. var getDirectionInfo = {
  60960. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  60961. var axis = axisModel.axis;
  60962. var ret = {};
  60963. var rect = coordInfo.model.coordinateSystem.getRect();
  60964. oldPoint = oldPoint || [0, 0];
  60965. if (axis.dim === 'x') {
  60966. ret.pixel = newPoint[0] - oldPoint[0];
  60967. ret.pixelLength = rect.width;
  60968. ret.pixelStart = rect.x;
  60969. ret.signal = axis.inverse ? 1 : -1;
  60970. }
  60971. else { // axis.dim === 'y'
  60972. ret.pixel = newPoint[1] - oldPoint[1];
  60973. ret.pixelLength = rect.height;
  60974. ret.pixelStart = rect.y;
  60975. ret.signal = axis.inverse ? -1 : 1;
  60976. }
  60977. return ret;
  60978. },
  60979. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  60980. var axis = axisModel.axis;
  60981. var ret = {};
  60982. var polar = coordInfo.model.coordinateSystem;
  60983. var radiusExtent = polar.getRadiusAxis().getExtent();
  60984. var angleExtent = polar.getAngleAxis().getExtent();
  60985. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  60986. newPoint = polar.pointToCoord(newPoint);
  60987. if (axisModel.mainType === 'radiusAxis') {
  60988. ret.pixel = newPoint[0] - oldPoint[0];
  60989. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  60990. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  60991. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  60992. ret.pixelStart = radiusExtent[0];
  60993. ret.signal = axis.inverse ? 1 : -1;
  60994. }
  60995. else { // 'angleAxis'
  60996. ret.pixel = newPoint[1] - oldPoint[1];
  60997. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  60998. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  60999. ret.pixelLength = angleExtent[1] - angleExtent[0];
  61000. ret.pixelStart = angleExtent[0];
  61001. ret.signal = axis.inverse ? -1 : 1;
  61002. }
  61003. return ret;
  61004. },
  61005. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  61006. var axis = axisModel.axis;
  61007. var rect = coordInfo.model.coordinateSystem.getRect();
  61008. var ret = {};
  61009. oldPoint = oldPoint || [0, 0];
  61010. if (axis.orient === 'horizontal') {
  61011. ret.pixel = newPoint[0] - oldPoint[0];
  61012. ret.pixelLength = rect.width;
  61013. ret.pixelStart = rect.x;
  61014. ret.signal = axis.inverse ? 1 : -1;
  61015. }
  61016. else { // 'vertical'
  61017. ret.pixel = newPoint[1] - oldPoint[1];
  61018. ret.pixelLength = rect.height;
  61019. ret.pixelStart = rect.y;
  61020. ret.signal = axis.inverse ? -1 : 1;
  61021. }
  61022. return ret;
  61023. }
  61024. };
  61025. registerProcessor({
  61026. getTargetSeries: function (ecModel) {
  61027. var seriesModelMap = createHashMap();
  61028. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  61029. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  61030. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  61031. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  61032. seriesModelMap.set(seriesModel.uid, seriesModel);
  61033. });
  61034. });
  61035. });
  61036. return seriesModelMap;
  61037. },
  61038. isOverallFilter: true,
  61039. // Consider appendData, where filter should be performed. Because data process is
  61040. // in block mode currently, it is not need to worry about that the overallProgress
  61041. // execute every frame.
  61042. overallReset: function (ecModel, api) {
  61043. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  61044. // We calculate window and reset axis here but not in model
  61045. // init stage and not after action dispatch handler, because
  61046. // reset should be called after seriesData.restoreData.
  61047. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  61048. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  61049. });
  61050. // Caution: data zoom filtering is order sensitive when using
  61051. // percent range and no min/max/scale set on axis.
  61052. // For example, we have dataZoom definition:
  61053. // [
  61054. // {xAxisIndex: 0, start: 30, end: 70},
  61055. // {yAxisIndex: 0, start: 20, end: 80}
  61056. // ]
  61057. // In this case, [20, 80] of y-dataZoom should be based on data
  61058. // that have filtered by x-dataZoom using range of [30, 70],
  61059. // but should not be based on full raw data. Thus sliding
  61060. // x-dataZoom will change both ranges of xAxis and yAxis,
  61061. // while sliding y-dataZoom will only change the range of yAxis.
  61062. // So we should filter x-axis after reset x-axis immediately,
  61063. // and then reset y-axis and filter y-axis.
  61064. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  61065. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  61066. });
  61067. });
  61068. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  61069. // Fullfill all of the range props so that user
  61070. // is able to get them from chart.getOption().
  61071. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  61072. var percentRange = axisProxy.getDataPercentWindow();
  61073. var valueRange = axisProxy.getDataValueWindow();
  61074. dataZoomModel.setRawRange({
  61075. start: percentRange[0],
  61076. end: percentRange[1],
  61077. startValue: valueRange[0],
  61078. endValue: valueRange[1]
  61079. }, true);
  61080. });
  61081. }
  61082. });
  61083. registerAction('dataZoom', function (payload, ecModel) {
  61084. var linkedNodesFinder = createLinkedNodesFinder(
  61085. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  61086. eachAxisDim$1,
  61087. function (model, dimNames) {
  61088. return model.get(dimNames.axisIndex);
  61089. }
  61090. );
  61091. var effectedModels = [];
  61092. ecModel.eachComponent(
  61093. {mainType: 'dataZoom', query: payload},
  61094. function (model, index) {
  61095. effectedModels.push.apply(
  61096. effectedModels, linkedNodesFinder(model).nodes
  61097. );
  61098. }
  61099. );
  61100. each$1(effectedModels, function (dataZoomModel, index) {
  61101. dataZoomModel.setRawRange({
  61102. start: payload.start,
  61103. end: payload.end,
  61104. startValue: payload.startValue,
  61105. endValue: payload.endValue
  61106. });
  61107. });
  61108. });
  61109. /**
  61110. * DataZoom component entry
  61111. */
  61112. var each$25 = each$1;
  61113. var preprocessor$2 = function (option) {
  61114. var visualMap = option && option.visualMap;
  61115. if (!isArray(visualMap)) {
  61116. visualMap = visualMap ? [visualMap] : [];
  61117. }
  61118. each$25(visualMap, function (opt) {
  61119. if (!opt) {
  61120. return;
  61121. }
  61122. // rename splitList to pieces
  61123. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  61124. opt.pieces = opt.splitList;
  61125. delete opt.splitList;
  61126. }
  61127. var pieces = opt.pieces;
  61128. if (pieces && isArray(pieces)) {
  61129. each$25(pieces, function (piece) {
  61130. if (isObject$1(piece)) {
  61131. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  61132. piece.min = piece.start;
  61133. }
  61134. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  61135. piece.max = piece.end;
  61136. }
  61137. }
  61138. });
  61139. }
  61140. });
  61141. };
  61142. function has$1(obj, name) {
  61143. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  61144. }
  61145. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  61146. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  61147. return (
  61148. !option.categories
  61149. && (
  61150. !(
  61151. option.pieces
  61152. ? option.pieces.length > 0
  61153. : option.splitNumber > 0
  61154. )
  61155. || option.calculable
  61156. )
  61157. )
  61158. ? 'continuous' : 'piecewise';
  61159. });
  61160. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  61161. registerVisual(VISUAL_PRIORITY, {
  61162. createOnAllSeries: true,
  61163. reset: function (seriesModel, ecModel) {
  61164. var resetDefines = [];
  61165. ecModel.eachComponent('visualMap', function (visualMapModel) {
  61166. if (!visualMapModel.isTargetSeries(seriesModel)) {
  61167. return;
  61168. }
  61169. resetDefines.push(incrementalApplyVisual(
  61170. visualMapModel.stateList,
  61171. visualMapModel.targetVisuals,
  61172. bind(visualMapModel.getValueState, visualMapModel),
  61173. visualMapModel.getDataDimension(seriesModel.getData())
  61174. ));
  61175. });
  61176. return resetDefines;
  61177. }
  61178. });
  61179. // Only support color.
  61180. registerVisual(VISUAL_PRIORITY, {
  61181. createOnAllSeries: true,
  61182. reset: function (seriesModel, ecModel) {
  61183. var data = seriesModel.getData();
  61184. var visualMetaList = [];
  61185. ecModel.eachComponent('visualMap', function (visualMapModel) {
  61186. if (visualMapModel.isTargetSeries(seriesModel)) {
  61187. var visualMeta = visualMapModel.getVisualMeta(
  61188. bind(getColorVisual, null, seriesModel, visualMapModel)
  61189. ) || {stops: [], outerColors: []};
  61190. var concreteDim = visualMapModel.getDataDimension(data);
  61191. var dimInfo = data.getDimensionInfo(concreteDim);
  61192. if (dimInfo != null) {
  61193. // visualMeta.dimension should be dimension index, but not concrete dimension.
  61194. visualMeta.dimension = dimInfo.index;
  61195. visualMetaList.push(visualMeta);
  61196. }
  61197. }
  61198. });
  61199. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  61200. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  61201. }
  61202. });
  61203. // FIXME
  61204. // performance and export for heatmap?
  61205. // value can be Infinity or -Infinity
  61206. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  61207. var mappings = visualMapModel.targetVisuals[valueState];
  61208. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  61209. var resultVisual = {
  61210. color: seriesModel.getData().getVisual('color') // default color.
  61211. };
  61212. for (var i = 0, len = visualTypes.length; i < len; i++) {
  61213. var type = visualTypes[i];
  61214. var mapping = mappings[
  61215. type === 'opacity' ? '__alphaForOpacity' : type
  61216. ];
  61217. mapping && mapping.applyVisual(value, getVisual, setVisual);
  61218. }
  61219. return resultVisual.color;
  61220. function getVisual(key) {
  61221. return resultVisual[key];
  61222. }
  61223. function setVisual(key, value) {
  61224. resultVisual[key] = value;
  61225. }
  61226. }
  61227. /**
  61228. * @file Visual mapping.
  61229. */
  61230. var visualDefault = {
  61231. /**
  61232. * @public
  61233. */
  61234. get: function (visualType, key, isCategory) {
  61235. var value = clone(
  61236. (defaultOption$3[visualType] || {})[key]
  61237. );
  61238. return isCategory
  61239. ? (isArray(value) ? value[value.length - 1] : value)
  61240. : value;
  61241. }
  61242. };
  61243. var defaultOption$3 = {
  61244. color: {
  61245. active: ['#006edd', '#e0ffff'],
  61246. inactive: ['rgba(0,0,0,0)']
  61247. },
  61248. colorHue: {
  61249. active: [0, 360],
  61250. inactive: [0, 0]
  61251. },
  61252. colorSaturation: {
  61253. active: [0.3, 1],
  61254. inactive: [0, 0]
  61255. },
  61256. colorLightness: {
  61257. active: [0.9, 0.5],
  61258. inactive: [0, 0]
  61259. },
  61260. colorAlpha: {
  61261. active: [0.3, 1],
  61262. inactive: [0, 0]
  61263. },
  61264. opacity: {
  61265. active: [0.3, 1],
  61266. inactive: [0, 0]
  61267. },
  61268. symbol: {
  61269. active: ['circle', 'roundRect', 'diamond'],
  61270. inactive: ['none']
  61271. },
  61272. symbolSize: {
  61273. active: [10, 50],
  61274. inactive: [0, 0]
  61275. }
  61276. };
  61277. var mapVisual$2 = VisualMapping.mapVisual;
  61278. var eachVisual = VisualMapping.eachVisual;
  61279. var isArray$3 = isArray;
  61280. var each$26 = each$1;
  61281. var asc$3 = asc;
  61282. var linearMap$3 = linearMap;
  61283. var noop$2 = noop;
  61284. var VisualMapModel = extendComponentModel({
  61285. type: 'visualMap',
  61286. dependencies: ['series'],
  61287. /**
  61288. * @readOnly
  61289. * @type {Array.<string>}
  61290. */
  61291. stateList: ['inRange', 'outOfRange'],
  61292. /**
  61293. * @readOnly
  61294. * @type {Array.<string>}
  61295. */
  61296. replacableOptionKeys: [
  61297. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  61298. ],
  61299. /**
  61300. * [lowerBound, upperBound]
  61301. *
  61302. * @readOnly
  61303. * @type {Array.<number>}
  61304. */
  61305. dataBound: [-Infinity, Infinity],
  61306. /**
  61307. * @readOnly
  61308. * @type {string|Object}
  61309. */
  61310. layoutMode: {type: 'box', ignoreSize: true},
  61311. /**
  61312. * @protected
  61313. */
  61314. defaultOption: {
  61315. show: true,
  61316. zlevel: 0,
  61317. z: 4,
  61318. seriesIndex: 'all', // 'all' or null/undefined: all series.
  61319. // A number or an array of number: the specified series.
  61320. // set min: 0, max: 200, only for campatible with ec2.
  61321. // In fact min max should not have default value.
  61322. min: 0, // min value, must specified if pieces is not specified.
  61323. max: 200, // max value, must specified if pieces is not specified.
  61324. dimension: null,
  61325. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  61326. // 'symbol', 'symbolSize'
  61327. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  61328. // 'colorLightness', 'colorAlpha',
  61329. // 'symbol', 'symbolSize'
  61330. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  61331. right: null, // The same as left.
  61332. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  61333. bottom: 0, // The same as top.
  61334. itemWidth: null,
  61335. itemHeight: null,
  61336. inverse: false,
  61337. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  61338. backgroundColor: 'rgba(0,0,0,0)',
  61339. borderColor: '#ccc', // 值域边框颜色
  61340. contentColor: '#5793f3',
  61341. inactiveColor: '#aaa',
  61342. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  61343. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  61344. // 接受数组分别设定上右下左边距,同css
  61345. textGap: 10, //
  61346. precision: 0, // 小数精度,默认为0,无小数点
  61347. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  61348. formatter: null,
  61349. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  61350. textStyle: {
  61351. color: '#333' // 值域文字颜色
  61352. }
  61353. },
  61354. /**
  61355. * @protected
  61356. */
  61357. init: function (option, parentModel, ecModel) {
  61358. /**
  61359. * @private
  61360. * @type {Array.<number>}
  61361. */
  61362. this._dataExtent;
  61363. /**
  61364. * @readOnly
  61365. */
  61366. this.targetVisuals = {};
  61367. /**
  61368. * @readOnly
  61369. */
  61370. this.controllerVisuals = {};
  61371. /**
  61372. * @readOnly
  61373. */
  61374. this.textStyleModel;
  61375. /**
  61376. * [width, height]
  61377. * @readOnly
  61378. * @type {Array.<number>}
  61379. */
  61380. this.itemSize;
  61381. this.mergeDefaultAndTheme(option, ecModel);
  61382. },
  61383. /**
  61384. * @protected
  61385. */
  61386. optionUpdated: function (newOption, isInit) {
  61387. var thisOption = this.option;
  61388. // FIXME
  61389. // necessary?
  61390. // Disable realtime view update if canvas is not supported.
  61391. if (!env$1.canvasSupported) {
  61392. thisOption.realtime = false;
  61393. }
  61394. !isInit && replaceVisualOption(
  61395. thisOption, newOption, this.replacableOptionKeys
  61396. );
  61397. this.textStyleModel = this.getModel('textStyle');
  61398. this.resetItemSize();
  61399. this.completeVisualOption();
  61400. },
  61401. /**
  61402. * @protected
  61403. */
  61404. resetVisual: function (supplementVisualOption) {
  61405. var stateList = this.stateList;
  61406. supplementVisualOption = bind(supplementVisualOption, this);
  61407. this.controllerVisuals = createVisualMappings(
  61408. this.option.controller, stateList, supplementVisualOption
  61409. );
  61410. this.targetVisuals = createVisualMappings(
  61411. this.option.target, stateList, supplementVisualOption
  61412. );
  61413. },
  61414. /**
  61415. * @protected
  61416. * @return {Array.<number>} An array of series indices.
  61417. */
  61418. getTargetSeriesIndices: function () {
  61419. var optionSeriesIndex = this.option.seriesIndex;
  61420. var seriesIndices = [];
  61421. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  61422. this.ecModel.eachSeries(function (seriesModel, index) {
  61423. seriesIndices.push(index);
  61424. });
  61425. }
  61426. else {
  61427. seriesIndices = normalizeToArray(optionSeriesIndex);
  61428. }
  61429. return seriesIndices;
  61430. },
  61431. /**
  61432. * @public
  61433. */
  61434. eachTargetSeries: function (callback, context) {
  61435. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  61436. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  61437. }, this);
  61438. },
  61439. /**
  61440. * @pubilc
  61441. */
  61442. isTargetSeries: function (seriesModel) {
  61443. var is = false;
  61444. this.eachTargetSeries(function (model) {
  61445. model === seriesModel && (is = true);
  61446. });
  61447. return is;
  61448. },
  61449. /**
  61450. * @example
  61451. * this.formatValueText(someVal); // format single numeric value to text.
  61452. * this.formatValueText(someVal, true); // format single category value to text.
  61453. * this.formatValueText([min, max]); // format numeric min-max to text.
  61454. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  61455. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  61456. *
  61457. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  61458. * @param {boolean} [isCategory=false] Only available when value is number.
  61459. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  61460. * @return {string}
  61461. * @protected
  61462. */
  61463. formatValueText: function(value, isCategory, edgeSymbols) {
  61464. var option = this.option;
  61465. var precision = option.precision;
  61466. var dataBound = this.dataBound;
  61467. var formatter = option.formatter;
  61468. var isMinMax;
  61469. var textValue;
  61470. edgeSymbols = edgeSymbols || ['<', '>'];
  61471. if (isArray(value)) {
  61472. value = value.slice();
  61473. isMinMax = true;
  61474. }
  61475. textValue = isCategory
  61476. ? value
  61477. : (isMinMax
  61478. ? [toFixed(value[0]), toFixed(value[1])]
  61479. : toFixed(value)
  61480. );
  61481. if (isString(formatter)) {
  61482. return formatter
  61483. .replace('{value}', isMinMax ? textValue[0] : textValue)
  61484. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  61485. }
  61486. else if (isFunction$1(formatter)) {
  61487. return isMinMax
  61488. ? formatter(value[0], value[1])
  61489. : formatter(value);
  61490. }
  61491. if (isMinMax) {
  61492. if (value[0] === dataBound[0]) {
  61493. return edgeSymbols[0] + ' ' + textValue[1];
  61494. }
  61495. else if (value[1] === dataBound[1]) {
  61496. return edgeSymbols[1] + ' ' + textValue[0];
  61497. }
  61498. else {
  61499. return textValue[0] + ' - ' + textValue[1];
  61500. }
  61501. }
  61502. else { // Format single value (includes category case).
  61503. return textValue;
  61504. }
  61505. function toFixed(val) {
  61506. return val === dataBound[0]
  61507. ? 'min'
  61508. : val === dataBound[1]
  61509. ? 'max'
  61510. : (+val).toFixed(Math.min(precision, 20));
  61511. }
  61512. },
  61513. /**
  61514. * @protected
  61515. */
  61516. resetExtent: function () {
  61517. var thisOption = this.option;
  61518. // Can not calculate data extent by data here.
  61519. // Because series and data may be modified in processing stage.
  61520. // So we do not support the feature "auto min/max".
  61521. var extent = asc$3([thisOption.min, thisOption.max]);
  61522. this._dataExtent = extent;
  61523. },
  61524. /**
  61525. * @public
  61526. * @param {module:echarts/data/List} list
  61527. * @return {string} Concrete dimention. If return null/undefined,
  61528. * no dimension used.
  61529. */
  61530. getDataDimension: function (list) {
  61531. var optDim = this.option.dimension;
  61532. var listDimensions = list.dimensions;
  61533. if (optDim == null && !listDimensions.length) {
  61534. return;
  61535. }
  61536. if (optDim != null) {
  61537. return list.getDimension(optDim);
  61538. }
  61539. var dimNames = list.dimensions;
  61540. for (var i = dimNames.length - 1; i >= 0; i--) {
  61541. var dimName = dimNames[i];
  61542. var dimInfo = list.getDimensionInfo(dimName);
  61543. if (!dimInfo.isCalculationCoord) {
  61544. return dimName;
  61545. }
  61546. }
  61547. },
  61548. /**
  61549. * @public
  61550. * @override
  61551. */
  61552. getExtent: function () {
  61553. return this._dataExtent.slice();
  61554. },
  61555. /**
  61556. * @protected
  61557. */
  61558. completeVisualOption: function () {
  61559. var ecModel = this.ecModel;
  61560. var thisOption = this.option;
  61561. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  61562. var target = thisOption.target || (thisOption.target = {});
  61563. var controller = thisOption.controller || (thisOption.controller = {});
  61564. merge(target, base); // Do not override
  61565. merge(controller, base); // Do not override
  61566. var isCategory = this.isCategory();
  61567. completeSingle.call(this, target);
  61568. completeSingle.call(this, controller);
  61569. completeInactive.call(this, target, 'inRange', 'outOfRange');
  61570. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  61571. completeController.call(this, controller);
  61572. function completeSingle(base) {
  61573. // Compatible with ec2 dataRange.color.
  61574. // The mapping order of dataRange.color is: [high value, ..., low value]
  61575. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  61576. // Notice: ec2 has no inverse.
  61577. if (isArray$3(thisOption.color)
  61578. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  61579. // So adding color only when no inRange defined.
  61580. && !base.inRange
  61581. ) {
  61582. base.inRange = {color: thisOption.color.slice().reverse()};
  61583. }
  61584. // Compatible with previous logic, always give a defautl color, otherwise
  61585. // simple config with no inRange and outOfRange will not work.
  61586. // Originally we use visualMap.color as the default color, but setOption at
  61587. // the second time the default color will be erased. So we change to use
  61588. // constant DEFAULT_COLOR.
  61589. // If user do not want the defualt color, set inRange: {color: null}.
  61590. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  61591. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  61592. each$26(this.stateList, function (state) {
  61593. var visualType = base[state];
  61594. if (isString(visualType)) {
  61595. var defa = visualDefault.get(visualType, 'active', isCategory);
  61596. if (defa) {
  61597. base[state] = {};
  61598. base[state][visualType] = defa;
  61599. }
  61600. else {
  61601. // Mark as not specified.
  61602. delete base[state];
  61603. }
  61604. }
  61605. }, this);
  61606. }
  61607. function completeInactive(base, stateExist, stateAbsent) {
  61608. var optExist = base[stateExist];
  61609. var optAbsent = base[stateAbsent];
  61610. if (optExist && !optAbsent) {
  61611. optAbsent = base[stateAbsent] = {};
  61612. each$26(optExist, function (visualData, visualType) {
  61613. if (!VisualMapping.isValidType(visualType)) {
  61614. return;
  61615. }
  61616. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  61617. if (defa != null) {
  61618. optAbsent[visualType] = defa;
  61619. // Compatibable with ec2:
  61620. // Only inactive color to rgba(0,0,0,0) can not
  61621. // make label transparent, so use opacity also.
  61622. if (visualType === 'color'
  61623. && !optAbsent.hasOwnProperty('opacity')
  61624. && !optAbsent.hasOwnProperty('colorAlpha')
  61625. ) {
  61626. optAbsent.opacity = [0, 0];
  61627. }
  61628. }
  61629. });
  61630. }
  61631. }
  61632. function completeController(controller) {
  61633. var symbolExists = (controller.inRange || {}).symbol
  61634. || (controller.outOfRange || {}).symbol;
  61635. var symbolSizeExists = (controller.inRange || {}).symbolSize
  61636. || (controller.outOfRange || {}).symbolSize;
  61637. var inactiveColor = this.get('inactiveColor');
  61638. each$26(this.stateList, function (state) {
  61639. var itemSize = this.itemSize;
  61640. var visuals = controller[state];
  61641. // Set inactive color for controller if no other color
  61642. // attr (like colorAlpha) specified.
  61643. if (!visuals) {
  61644. visuals = controller[state] = {
  61645. color: isCategory ? inactiveColor : [inactiveColor]
  61646. };
  61647. }
  61648. // Consistent symbol and symbolSize if not specified.
  61649. if (visuals.symbol == null) {
  61650. visuals.symbol = symbolExists
  61651. && clone(symbolExists)
  61652. || (isCategory ? 'roundRect' : ['roundRect']);
  61653. }
  61654. if (visuals.symbolSize == null) {
  61655. visuals.symbolSize = symbolSizeExists
  61656. && clone(symbolSizeExists)
  61657. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  61658. }
  61659. // Filter square and none.
  61660. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  61661. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  61662. });
  61663. // Normalize symbolSize
  61664. var symbolSize = visuals.symbolSize;
  61665. if (symbolSize != null) {
  61666. var max = -Infinity;
  61667. // symbolSize can be object when categories defined.
  61668. eachVisual(symbolSize, function (value) {
  61669. value > max && (max = value);
  61670. });
  61671. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  61672. return linearMap$3(value, [0, max], [0, itemSize[0]], true);
  61673. });
  61674. }
  61675. }, this);
  61676. }
  61677. },
  61678. /**
  61679. * @protected
  61680. */
  61681. resetItemSize: function () {
  61682. this.itemSize = [
  61683. parseFloat(this.get('itemWidth')),
  61684. parseFloat(this.get('itemHeight'))
  61685. ];
  61686. },
  61687. /**
  61688. * @public
  61689. */
  61690. isCategory: function () {
  61691. return !!this.option.categories;
  61692. },
  61693. /**
  61694. * @public
  61695. * @abstract
  61696. */
  61697. setSelected: noop$2,
  61698. /**
  61699. * @public
  61700. * @abstract
  61701. * @param {*|module:echarts/data/List} valueOrData
  61702. * @param {number} dataIndex
  61703. * @return {string} state See this.stateList
  61704. */
  61705. getValueState: noop$2,
  61706. /**
  61707. * FIXME
  61708. * Do not publish to thirt-part-dev temporarily
  61709. * util the interface is stable. (Should it return
  61710. * a function but not visual meta?)
  61711. *
  61712. * @pubilc
  61713. * @abstract
  61714. * @param {Function} getColorVisual
  61715. * params: value, valueState
  61716. * return: color
  61717. * @return {Object} visualMeta
  61718. * should includes {stops, outerColors}
  61719. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  61720. */
  61721. getVisualMeta: noop$2
  61722. });
  61723. // Constant
  61724. var DEFAULT_BAR_BOUND = [20, 140];
  61725. var ContinuousModel = VisualMapModel.extend({
  61726. type: 'visualMap.continuous',
  61727. /**
  61728. * @protected
  61729. */
  61730. defaultOption: {
  61731. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  61732. calculable: false, // This prop effect default component type determine,
  61733. // See echarts/component/visualMap/typeDefaulter.
  61734. range: null, // selected range. In default case `range` is [min, max]
  61735. // and can auto change along with modification of min max,
  61736. // util use specifid a range.
  61737. realtime: true, // Whether realtime update.
  61738. itemHeight: null, // The length of the range control edge.
  61739. itemWidth: null, // The length of the other side.
  61740. hoverLink: true, // Enable hover highlight.
  61741. hoverLinkDataSize: null,// The size of hovered data.
  61742. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  61743. // If not specified, follow the value of `realtime`.
  61744. },
  61745. /**
  61746. * @override
  61747. */
  61748. optionUpdated: function (newOption, isInit) {
  61749. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  61750. this.resetExtent();
  61751. this.resetVisual(function (mappingOption) {
  61752. mappingOption.mappingMethod = 'linear';
  61753. mappingOption.dataExtent = this.getExtent();
  61754. });
  61755. this._resetRange();
  61756. },
  61757. /**
  61758. * @protected
  61759. * @override
  61760. */
  61761. resetItemSize: function () {
  61762. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  61763. var itemSize = this.itemSize;
  61764. this._orient === 'horizontal' && itemSize.reverse();
  61765. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  61766. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  61767. },
  61768. /**
  61769. * @private
  61770. */
  61771. _resetRange: function () {
  61772. var dataExtent = this.getExtent();
  61773. var range = this.option.range;
  61774. if (!range || range.auto) {
  61775. // `range` should always be array (so we dont use other
  61776. // value like 'auto') for user-friend. (consider getOption).
  61777. dataExtent.auto = 1;
  61778. this.option.range = dataExtent;
  61779. }
  61780. else if (isArray(range)) {
  61781. if (range[0] > range[1]) {
  61782. range.reverse();
  61783. }
  61784. range[0] = Math.max(range[0], dataExtent[0]);
  61785. range[1] = Math.min(range[1], dataExtent[1]);
  61786. }
  61787. },
  61788. /**
  61789. * @protected
  61790. * @override
  61791. */
  61792. completeVisualOption: function () {
  61793. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  61794. each$1(this.stateList, function (state) {
  61795. var symbolSize = this.option.controller[state].symbolSize;
  61796. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  61797. symbolSize[0] = 0; // For good looking.
  61798. }
  61799. }, this);
  61800. },
  61801. /**
  61802. * @override
  61803. */
  61804. setSelected: function (selected) {
  61805. this.option.range = selected.slice();
  61806. this._resetRange();
  61807. },
  61808. /**
  61809. * @public
  61810. */
  61811. getSelected: function () {
  61812. var dataExtent = this.getExtent();
  61813. var dataInterval = asc(
  61814. (this.get('range') || []).slice()
  61815. );
  61816. // Clamp
  61817. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  61818. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  61819. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  61820. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  61821. return dataInterval;
  61822. },
  61823. /**
  61824. * @override
  61825. */
  61826. getValueState: function (value) {
  61827. var range = this.option.range;
  61828. var dataExtent = this.getExtent();
  61829. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  61830. // range[1] is processed likewise.
  61831. return (
  61832. (range[0] <= dataExtent[0] || range[0] <= value)
  61833. && (range[1] >= dataExtent[1] || value <= range[1])
  61834. ) ? 'inRange' : 'outOfRange';
  61835. },
  61836. /**
  61837. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  61838. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  61839. */
  61840. findTargetDataIndices: function (range) {
  61841. var result = [];
  61842. this.eachTargetSeries(function (seriesModel) {
  61843. var dataIndices = [];
  61844. var data = seriesModel.getData();
  61845. data.each(this.getDataDimension(data), function (value, dataIndex) {
  61846. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  61847. }, this);
  61848. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  61849. }, this);
  61850. return result;
  61851. },
  61852. /**
  61853. * @implement
  61854. */
  61855. getVisualMeta: function (getColorVisual) {
  61856. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  61857. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  61858. var stops = [];
  61859. function setStop(value, valueState) {
  61860. stops.push({
  61861. value: value,
  61862. color: getColorVisual(value, valueState)
  61863. });
  61864. }
  61865. // Format to: outOfRange -- inRange -- outOfRange.
  61866. var iIdx = 0;
  61867. var oIdx = 0;
  61868. var iLen = iVals.length;
  61869. var oLen = oVals.length;
  61870. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  61871. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  61872. if (oVals[oIdx] < iVals[iIdx]) {
  61873. setStop(oVals[oIdx], 'outOfRange');
  61874. }
  61875. }
  61876. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  61877. // If range is full, value beyond min, max will be clamped.
  61878. // make a singularity
  61879. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  61880. setStop(iVals[iIdx], 'inRange');
  61881. }
  61882. for (var first = 1; oIdx < oLen; oIdx++) {
  61883. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  61884. // make a singularity
  61885. if (first) {
  61886. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  61887. first = 0;
  61888. }
  61889. setStop(oVals[oIdx], 'outOfRange');
  61890. }
  61891. }
  61892. var stopsLen = stops.length;
  61893. return {
  61894. stops: stops,
  61895. outerColors: [
  61896. stopsLen ? stops[0].color : 'transparent',
  61897. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  61898. ]
  61899. };
  61900. }
  61901. });
  61902. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  61903. if (dataExtent[0] === dataExtent[1]) {
  61904. return dataExtent.slice();
  61905. }
  61906. // When using colorHue mapping, it is not linear color any more.
  61907. // Moreover, canvas gradient seems not to be accurate linear.
  61908. // FIXME
  61909. // Should be arbitrary value 100? or based on pixel size?
  61910. var count = 200;
  61911. var step = (dataExtent[1] - dataExtent[0]) / count;
  61912. var value = dataExtent[0];
  61913. var stopValues = [];
  61914. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  61915. stopValues.push(value);
  61916. value += step;
  61917. }
  61918. stopValues.push(dataExtent[1]);
  61919. return stopValues;
  61920. }
  61921. var VisualMapView = extendComponentView({
  61922. type: 'visualMap',
  61923. /**
  61924. * @readOnly
  61925. * @type {Object}
  61926. */
  61927. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  61928. init: function (ecModel, api) {
  61929. /**
  61930. * @readOnly
  61931. * @type {module:echarts/model/Global}
  61932. */
  61933. this.ecModel = ecModel;
  61934. /**
  61935. * @readOnly
  61936. * @type {module:echarts/ExtensionAPI}
  61937. */
  61938. this.api = api;
  61939. /**
  61940. * @readOnly
  61941. * @type {module:echarts/component/visualMap/visualMapModel}
  61942. */
  61943. this.visualMapModel;
  61944. },
  61945. /**
  61946. * @protected
  61947. */
  61948. render: function (visualMapModel, ecModel, api, payload) {
  61949. this.visualMapModel = visualMapModel;
  61950. if (visualMapModel.get('show') === false) {
  61951. this.group.removeAll();
  61952. return;
  61953. }
  61954. this.doRender.apply(this, arguments);
  61955. },
  61956. /**
  61957. * @protected
  61958. */
  61959. renderBackground: function (group) {
  61960. var visualMapModel = this.visualMapModel;
  61961. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  61962. var rect = group.getBoundingRect();
  61963. group.add(new Rect({
  61964. z2: -1, // Lay background rect on the lowest layer.
  61965. silent: true,
  61966. shape: {
  61967. x: rect.x - padding[3],
  61968. y: rect.y - padding[0],
  61969. width: rect.width + padding[3] + padding[1],
  61970. height: rect.height + padding[0] + padding[2]
  61971. },
  61972. style: {
  61973. fill: visualMapModel.get('backgroundColor'),
  61974. stroke: visualMapModel.get('borderColor'),
  61975. lineWidth: visualMapModel.get('borderWidth')
  61976. }
  61977. }));
  61978. },
  61979. /**
  61980. * @protected
  61981. * @param {number} targetValue can be Infinity or -Infinity
  61982. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  61983. * @param {Object} [opts]
  61984. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  61985. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  61986. * @return {*} Visual value.
  61987. */
  61988. getControllerVisual: function (targetValue, visualCluster, opts) {
  61989. opts = opts || {};
  61990. var forceState = opts.forceState;
  61991. var visualMapModel = this.visualMapModel;
  61992. var visualObj = {};
  61993. // Default values.
  61994. if (visualCluster === 'symbol') {
  61995. visualObj.symbol = visualMapModel.get('itemSymbol');
  61996. }
  61997. if (visualCluster === 'color') {
  61998. var defaultColor = visualMapModel.get('contentColor');
  61999. visualObj.color = defaultColor;
  62000. }
  62001. function getter(key) {
  62002. return visualObj[key];
  62003. }
  62004. function setter(key, value) {
  62005. visualObj[key] = value;
  62006. }
  62007. var mappings = visualMapModel.controllerVisuals[
  62008. forceState || visualMapModel.getValueState(targetValue)
  62009. ];
  62010. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  62011. each$1(visualTypes, function (type) {
  62012. var visualMapping = mappings[type];
  62013. if (opts.convertOpacityToAlpha && type === 'opacity') {
  62014. type = 'colorAlpha';
  62015. visualMapping = mappings.__alphaForOpacity;
  62016. }
  62017. if (VisualMapping.dependsOn(type, visualCluster)) {
  62018. visualMapping && visualMapping.applyVisual(
  62019. targetValue, getter, setter
  62020. );
  62021. }
  62022. });
  62023. return visualObj[visualCluster];
  62024. },
  62025. /**
  62026. * @protected
  62027. */
  62028. positionGroup: function (group) {
  62029. var model = this.visualMapModel;
  62030. var api = this.api;
  62031. positionElement(
  62032. group,
  62033. model.getBoxLayoutParams(),
  62034. {width: api.getWidth(), height: api.getHeight()}
  62035. );
  62036. },
  62037. /**
  62038. * @protected
  62039. * @abstract
  62040. */
  62041. doRender: noop
  62042. });
  62043. /**
  62044. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  62045. * @param {module:echarts/ExtensionAPI} api
  62046. * @param {Array.<number>} itemSize always [short, long]
  62047. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  62048. */
  62049. function getItemAlign(visualMapModel, api, itemSize) {
  62050. var modelOption = visualMapModel.option;
  62051. var itemAlign = modelOption.align;
  62052. if (itemAlign != null && itemAlign !== 'auto') {
  62053. return itemAlign;
  62054. }
  62055. // Auto decision align.
  62056. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  62057. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  62058. var paramsSet = [
  62059. ['left', 'right', 'width'],
  62060. ['top', 'bottom', 'height']
  62061. ];
  62062. var reals = paramsSet[realIndex];
  62063. var fakeValue = [0, null, 10];
  62064. var layoutInput = {};
  62065. for (var i = 0; i < 3; i++) {
  62066. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  62067. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  62068. }
  62069. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  62070. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  62071. return reals[
  62072. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  62073. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  62074. ];
  62075. }
  62076. /**
  62077. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  62078. * dataIndexInside means filtered index.
  62079. */
  62080. function convertDataIndex(batch) {
  62081. each$1(batch || [], function (batchItem) {
  62082. if (batch.dataIndex != null) {
  62083. batch.dataIndexInside = batch.dataIndex;
  62084. batch.dataIndex = null;
  62085. }
  62086. });
  62087. return batch;
  62088. }
  62089. var linearMap$4 = linearMap;
  62090. var each$27 = each$1;
  62091. var mathMin$7 = Math.min;
  62092. var mathMax$7 = Math.max;
  62093. // Arbitrary value
  62094. var HOVER_LINK_SIZE = 12;
  62095. var HOVER_LINK_OUT = 6;
  62096. // Notice:
  62097. // Any "interval" should be by the order of [low, high].
  62098. // "handle0" (handleIndex === 0) maps to
  62099. // low data value: this._dataInterval[0] and has low coord.
  62100. // "handle1" (handleIndex === 1) maps to
  62101. // high data value: this._dataInterval[1] and has high coord.
  62102. // The logic of transform is implemented in this._createBarGroup.
  62103. var ContinuousView = VisualMapView.extend({
  62104. type: 'visualMap.continuous',
  62105. /**
  62106. * @override
  62107. */
  62108. init: function () {
  62109. ContinuousView.superApply(this, 'init', arguments);
  62110. /**
  62111. * @private
  62112. */
  62113. this._shapes = {};
  62114. /**
  62115. * @private
  62116. */
  62117. this._dataInterval = [];
  62118. /**
  62119. * @private
  62120. */
  62121. this._handleEnds = [];
  62122. /**
  62123. * @private
  62124. */
  62125. this._orient;
  62126. /**
  62127. * @private
  62128. */
  62129. this._useHandle;
  62130. /**
  62131. * @private
  62132. */
  62133. this._hoverLinkDataIndices = [];
  62134. /**
  62135. * @private
  62136. */
  62137. this._dragging;
  62138. /**
  62139. * @private
  62140. */
  62141. this._hovering;
  62142. },
  62143. /**
  62144. * @protected
  62145. * @override
  62146. */
  62147. doRender: function (visualMapModel, ecModel, api, payload) {
  62148. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  62149. this._buildView();
  62150. }
  62151. },
  62152. /**
  62153. * @private
  62154. */
  62155. _buildView: function () {
  62156. this.group.removeAll();
  62157. var visualMapModel = this.visualMapModel;
  62158. var thisGroup = this.group;
  62159. this._orient = visualMapModel.get('orient');
  62160. this._useHandle = visualMapModel.get('calculable');
  62161. this._resetInterval();
  62162. this._renderBar(thisGroup);
  62163. var dataRangeText = visualMapModel.get('text');
  62164. this._renderEndsText(thisGroup, dataRangeText, 0);
  62165. this._renderEndsText(thisGroup, dataRangeText, 1);
  62166. // Do this for background size calculation.
  62167. this._updateView(true);
  62168. // After updating view, inner shapes is built completely,
  62169. // and then background can be rendered.
  62170. this.renderBackground(thisGroup);
  62171. // Real update view
  62172. this._updateView();
  62173. this._enableHoverLinkToSeries();
  62174. this._enableHoverLinkFromSeries();
  62175. this.positionGroup(thisGroup);
  62176. },
  62177. /**
  62178. * @private
  62179. */
  62180. _renderEndsText: function (group, dataRangeText, endsIndex) {
  62181. if (!dataRangeText) {
  62182. return;
  62183. }
  62184. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  62185. var text = dataRangeText[1 - endsIndex];
  62186. text = text != null ? text + '' : '';
  62187. var visualMapModel = this.visualMapModel;
  62188. var textGap = visualMapModel.get('textGap');
  62189. var itemSize = visualMapModel.itemSize;
  62190. var barGroup = this._shapes.barGroup;
  62191. var position = this._applyTransform(
  62192. [
  62193. itemSize[0] / 2,
  62194. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  62195. ],
  62196. barGroup
  62197. );
  62198. var align = this._applyTransform(
  62199. endsIndex === 0 ? 'bottom' : 'top',
  62200. barGroup
  62201. );
  62202. var orient = this._orient;
  62203. var textStyleModel = this.visualMapModel.textStyleModel;
  62204. this.group.add(new Text({
  62205. style: {
  62206. x: position[0],
  62207. y: position[1],
  62208. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  62209. textAlign: orient === 'horizontal' ? align : 'center',
  62210. text: text,
  62211. textFont: textStyleModel.getFont(),
  62212. textFill: textStyleModel.getTextColor()
  62213. }
  62214. }));
  62215. },
  62216. /**
  62217. * @private
  62218. */
  62219. _renderBar: function (targetGroup) {
  62220. var visualMapModel = this.visualMapModel;
  62221. var shapes = this._shapes;
  62222. var itemSize = visualMapModel.itemSize;
  62223. var orient = this._orient;
  62224. var useHandle = this._useHandle;
  62225. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  62226. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  62227. // Bar
  62228. barGroup.add(shapes.outOfRange = createPolygon());
  62229. barGroup.add(shapes.inRange = createPolygon(
  62230. null,
  62231. useHandle ? getCursor$1(this._orient) : null,
  62232. bind(this._dragHandle, this, 'all', false),
  62233. bind(this._dragHandle, this, 'all', true)
  62234. ));
  62235. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  62236. var textSize = mathMax$7(textRect.width, textRect.height);
  62237. // Handle
  62238. if (useHandle) {
  62239. shapes.handleThumbs = [];
  62240. shapes.handleLabels = [];
  62241. shapes.handleLabelPoints = [];
  62242. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  62243. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  62244. }
  62245. this._createIndicator(barGroup, itemSize, textSize, orient);
  62246. targetGroup.add(barGroup);
  62247. },
  62248. /**
  62249. * @private
  62250. */
  62251. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  62252. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  62253. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  62254. var handleThumb = createPolygon(
  62255. createHandlePoints(handleIndex, textSize),
  62256. getCursor$1(this._orient),
  62257. onDrift,
  62258. onDragEnd
  62259. );
  62260. handleThumb.position[0] = itemSize[0];
  62261. barGroup.add(handleThumb);
  62262. // Text is always horizontal layout but should not be effected by
  62263. // transform (orient/inverse). So label is built separately but not
  62264. // use zrender/graphic/helper/RectText, and is located based on view
  62265. // group (according to handleLabelPoint) but not barGroup.
  62266. var textStyleModel = this.visualMapModel.textStyleModel;
  62267. var handleLabel = new Text({
  62268. draggable: true,
  62269. drift: onDrift,
  62270. onmousemove: function (e) {
  62271. // Fot mobile devicem, prevent screen slider on the button.
  62272. stop(e.event);
  62273. },
  62274. ondragend: onDragEnd,
  62275. style: {
  62276. x: 0, y: 0, text: '',
  62277. textFont: textStyleModel.getFont(),
  62278. textFill: textStyleModel.getTextColor()
  62279. }
  62280. });
  62281. this.group.add(handleLabel);
  62282. var handleLabelPoint = [
  62283. orient === 'horizontal'
  62284. ? textSize / 2
  62285. : textSize * 1.5,
  62286. orient === 'horizontal'
  62287. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  62288. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  62289. ];
  62290. var shapes = this._shapes;
  62291. shapes.handleThumbs[handleIndex] = handleThumb;
  62292. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  62293. shapes.handleLabels[handleIndex] = handleLabel;
  62294. },
  62295. /**
  62296. * @private
  62297. */
  62298. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  62299. var indicator = createPolygon([[0, 0]], 'move');
  62300. indicator.position[0] = itemSize[0];
  62301. indicator.attr({invisible: true, silent: true});
  62302. barGroup.add(indicator);
  62303. var textStyleModel = this.visualMapModel.textStyleModel;
  62304. var indicatorLabel = new Text({
  62305. silent: true,
  62306. invisible: true,
  62307. style: {
  62308. x: 0, y: 0, text: '',
  62309. textFont: textStyleModel.getFont(),
  62310. textFill: textStyleModel.getTextColor()
  62311. }
  62312. });
  62313. this.group.add(indicatorLabel);
  62314. var indicatorLabelPoint = [
  62315. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  62316. 0
  62317. ];
  62318. var shapes = this._shapes;
  62319. shapes.indicator = indicator;
  62320. shapes.indicatorLabel = indicatorLabel;
  62321. shapes.indicatorLabelPoint = indicatorLabelPoint;
  62322. },
  62323. /**
  62324. * @private
  62325. */
  62326. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  62327. if (!this._useHandle) {
  62328. return;
  62329. }
  62330. this._dragging = !isEnd;
  62331. if (!isEnd) {
  62332. // Transform dx, dy to bar coordination.
  62333. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  62334. this._updateInterval(handleIndex, vertex[1]);
  62335. // Considering realtime, update view should be executed
  62336. // before dispatch action.
  62337. this._updateView();
  62338. }
  62339. // dragEnd do not dispatch action when realtime.
  62340. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  62341. this.api.dispatchAction({
  62342. type: 'selectDataRange',
  62343. from: this.uid,
  62344. visualMapId: this.visualMapModel.id,
  62345. selected: this._dataInterval.slice()
  62346. });
  62347. }
  62348. if (isEnd) {
  62349. !this._hovering && this._clearHoverLinkToSeries();
  62350. }
  62351. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  62352. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  62353. }
  62354. },
  62355. /**
  62356. * @private
  62357. */
  62358. _resetInterval: function () {
  62359. var visualMapModel = this.visualMapModel;
  62360. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  62361. var dataExtent = visualMapModel.getExtent();
  62362. var sizeExtent = [0, visualMapModel.itemSize[1]];
  62363. this._handleEnds = [
  62364. linearMap$4(dataInterval[0], dataExtent, sizeExtent, true),
  62365. linearMap$4(dataInterval[1], dataExtent, sizeExtent, true)
  62366. ];
  62367. },
  62368. /**
  62369. * @private
  62370. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  62371. * @param {number} dx
  62372. * @param {number} dy
  62373. */
  62374. _updateInterval: function (handleIndex, delta) {
  62375. delta = delta || 0;
  62376. var visualMapModel = this.visualMapModel;
  62377. var handleEnds = this._handleEnds;
  62378. var sizeExtent = [0, visualMapModel.itemSize[1]];
  62379. sliderMove(
  62380. delta,
  62381. handleEnds,
  62382. sizeExtent,
  62383. handleIndex,
  62384. // cross is forbiden
  62385. 0
  62386. );
  62387. var dataExtent = visualMapModel.getExtent();
  62388. // Update data interval.
  62389. this._dataInterval = [
  62390. linearMap$4(handleEnds[0], sizeExtent, dataExtent, true),
  62391. linearMap$4(handleEnds[1], sizeExtent, dataExtent, true)
  62392. ];
  62393. },
  62394. /**
  62395. * @private
  62396. */
  62397. _updateView: function (forSketch) {
  62398. var visualMapModel = this.visualMapModel;
  62399. var dataExtent = visualMapModel.getExtent();
  62400. var shapes = this._shapes;
  62401. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  62402. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  62403. var visualInRange = this._createBarVisual(
  62404. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  62405. );
  62406. var visualOutOfRange = this._createBarVisual(
  62407. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  62408. );
  62409. shapes.inRange
  62410. .setStyle({
  62411. fill: visualInRange.barColor,
  62412. opacity: visualInRange.opacity
  62413. })
  62414. .setShape('points', visualInRange.barPoints);
  62415. shapes.outOfRange
  62416. .setStyle({
  62417. fill: visualOutOfRange.barColor,
  62418. opacity: visualOutOfRange.opacity
  62419. })
  62420. .setShape('points', visualOutOfRange.barPoints);
  62421. this._updateHandle(inRangeHandleEnds, visualInRange);
  62422. },
  62423. /**
  62424. * @private
  62425. */
  62426. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  62427. var opts = {
  62428. forceState: forceState,
  62429. convertOpacityToAlpha: true
  62430. };
  62431. var colorStops = this._makeColorGradient(dataInterval, opts);
  62432. var symbolSizes = [
  62433. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  62434. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  62435. ];
  62436. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  62437. return {
  62438. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  62439. barPoints: barPoints,
  62440. handlesColor: [
  62441. colorStops[0].color,
  62442. colorStops[colorStops.length - 1].color
  62443. ]
  62444. };
  62445. },
  62446. /**
  62447. * @private
  62448. */
  62449. _makeColorGradient: function (dataInterval, opts) {
  62450. // Considering colorHue, which is not linear, so we have to sample
  62451. // to calculate gradient color stops, but not only caculate head
  62452. // and tail.
  62453. var sampleNumber = 100; // Arbitrary value.
  62454. var colorStops = [];
  62455. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  62456. colorStops.push({
  62457. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  62458. offset: 0
  62459. });
  62460. for (var i = 1; i < sampleNumber; i++) {
  62461. var currValue = dataInterval[0] + step * i;
  62462. if (currValue > dataInterval[1]) {
  62463. break;
  62464. }
  62465. colorStops.push({
  62466. color: this.getControllerVisual(currValue, 'color', opts),
  62467. offset: i / sampleNumber
  62468. });
  62469. }
  62470. colorStops.push({
  62471. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  62472. offset: 1
  62473. });
  62474. return colorStops;
  62475. },
  62476. /**
  62477. * @private
  62478. */
  62479. _createBarPoints: function (handleEnds, symbolSizes) {
  62480. var itemSize = this.visualMapModel.itemSize;
  62481. return [
  62482. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  62483. [itemSize[0], handleEnds[0]],
  62484. [itemSize[0], handleEnds[1]],
  62485. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  62486. ];
  62487. },
  62488. /**
  62489. * @private
  62490. */
  62491. _createBarGroup: function (itemAlign) {
  62492. var orient = this._orient;
  62493. var inverse = this.visualMapModel.get('inverse');
  62494. return new Group(
  62495. (orient === 'horizontal' && !inverse)
  62496. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  62497. : (orient === 'horizontal' && inverse)
  62498. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  62499. : (orient === 'vertical' && !inverse)
  62500. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  62501. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  62502. );
  62503. },
  62504. /**
  62505. * @private
  62506. */
  62507. _updateHandle: function (handleEnds, visualInRange) {
  62508. if (!this._useHandle) {
  62509. return;
  62510. }
  62511. var shapes = this._shapes;
  62512. var visualMapModel = this.visualMapModel;
  62513. var handleThumbs = shapes.handleThumbs;
  62514. var handleLabels = shapes.handleLabels;
  62515. each$27([0, 1], function (handleIndex) {
  62516. var handleThumb = handleThumbs[handleIndex];
  62517. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  62518. handleThumb.position[1] = handleEnds[handleIndex];
  62519. // Update handle label position.
  62520. var textPoint = applyTransform$1(
  62521. shapes.handleLabelPoints[handleIndex],
  62522. getTransform(handleThumb, this.group)
  62523. );
  62524. handleLabels[handleIndex].setStyle({
  62525. x: textPoint[0],
  62526. y: textPoint[1],
  62527. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  62528. textVerticalAlign: 'middle',
  62529. textAlign: this._applyTransform(
  62530. this._orient === 'horizontal'
  62531. ? (handleIndex === 0 ? 'bottom' : 'top')
  62532. : 'left',
  62533. shapes.barGroup
  62534. )
  62535. });
  62536. }, this);
  62537. },
  62538. /**
  62539. * @private
  62540. * @param {number} cursorValue
  62541. * @param {number} textValue
  62542. * @param {string} [rangeSymbol]
  62543. * @param {number} [halfHoverLinkSize]
  62544. */
  62545. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  62546. var visualMapModel = this.visualMapModel;
  62547. var dataExtent = visualMapModel.getExtent();
  62548. var itemSize = visualMapModel.itemSize;
  62549. var sizeExtent = [0, itemSize[1]];
  62550. var pos = linearMap$4(cursorValue, dataExtent, sizeExtent, true);
  62551. var shapes = this._shapes;
  62552. var indicator = shapes.indicator;
  62553. if (!indicator) {
  62554. return;
  62555. }
  62556. indicator.position[1] = pos;
  62557. indicator.attr('invisible', false);
  62558. indicator.setShape('points', createIndicatorPoints(
  62559. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  62560. ));
  62561. var opts = {convertOpacityToAlpha: true};
  62562. var color = this.getControllerVisual(cursorValue, 'color', opts);
  62563. indicator.setStyle('fill', color);
  62564. // Update handle label position.
  62565. var textPoint = applyTransform$1(
  62566. shapes.indicatorLabelPoint,
  62567. getTransform(indicator, this.group)
  62568. );
  62569. var indicatorLabel = shapes.indicatorLabel;
  62570. indicatorLabel.attr('invisible', false);
  62571. var align = this._applyTransform('left', shapes.barGroup);
  62572. var orient = this._orient;
  62573. indicatorLabel.setStyle({
  62574. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  62575. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  62576. textAlign: orient === 'horizontal' ? 'center' : align,
  62577. x: textPoint[0],
  62578. y: textPoint[1]
  62579. });
  62580. },
  62581. /**
  62582. * @private
  62583. */
  62584. _enableHoverLinkToSeries: function () {
  62585. var self = this;
  62586. this._shapes.barGroup
  62587. .on('mousemove', function (e) {
  62588. self._hovering = true;
  62589. if (!self._dragging) {
  62590. var itemSize = self.visualMapModel.itemSize;
  62591. var pos = self._applyTransform(
  62592. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  62593. );
  62594. // For hover link show when hover handle, which might be
  62595. // below or upper than sizeExtent.
  62596. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  62597. self._doHoverLinkToSeries(
  62598. pos[1],
  62599. 0 <= pos[0] && pos[0] <= itemSize[0]
  62600. );
  62601. }
  62602. })
  62603. .on('mouseout', function () {
  62604. // When mouse is out of handle, hoverLink still need
  62605. // to be displayed when realtime is set as false.
  62606. self._hovering = false;
  62607. !self._dragging && self._clearHoverLinkToSeries();
  62608. });
  62609. },
  62610. /**
  62611. * @private
  62612. */
  62613. _enableHoverLinkFromSeries: function () {
  62614. var zr = this.api.getZr();
  62615. if (this.visualMapModel.option.hoverLink) {
  62616. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  62617. zr.on('mouseout', this._hideIndicator, this);
  62618. }
  62619. else {
  62620. this._clearHoverLinkFromSeries();
  62621. }
  62622. },
  62623. /**
  62624. * @private
  62625. */
  62626. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  62627. var visualMapModel = this.visualMapModel;
  62628. var itemSize = visualMapModel.itemSize;
  62629. if (!visualMapModel.option.hoverLink) {
  62630. return;
  62631. }
  62632. var sizeExtent = [0, itemSize[1]];
  62633. var dataExtent = visualMapModel.getExtent();
  62634. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  62635. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  62636. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  62637. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  62638. var cursorValue = linearMap$4(cursorPos, sizeExtent, dataExtent, true);
  62639. var valueRange = [
  62640. linearMap$4(hoverRange[0], sizeExtent, dataExtent, true),
  62641. linearMap$4(hoverRange[1], sizeExtent, dataExtent, true)
  62642. ];
  62643. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  62644. // where china and india has very large population.
  62645. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  62646. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  62647. // Do not show indicator when mouse is over handle,
  62648. // otherwise labels overlap, especially when dragging.
  62649. if (hoverOnBar) {
  62650. if (valueRange[0] === -Infinity) {
  62651. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  62652. }
  62653. else if (valueRange[1] === Infinity) {
  62654. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  62655. }
  62656. else {
  62657. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  62658. }
  62659. }
  62660. // When realtime is set as false, handles, which are in barGroup,
  62661. // also trigger hoverLink, which help user to realize where they
  62662. // focus on when dragging. (see test/heatmap-large.html)
  62663. // When realtime is set as true, highlight will not show when hover
  62664. // handle, because the label on handle, which displays a exact value
  62665. // but not range, might mislead users.
  62666. var oldBatch = this._hoverLinkDataIndices;
  62667. var newBatch = [];
  62668. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  62669. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  62670. }
  62671. var resultBatches = compressBatches(oldBatch, newBatch);
  62672. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  62673. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  62674. },
  62675. /**
  62676. * @private
  62677. */
  62678. _hoverLinkFromSeriesMouseOver: function (e) {
  62679. var el = e.target;
  62680. var visualMapModel = this.visualMapModel;
  62681. if (!el || el.dataIndex == null) {
  62682. return;
  62683. }
  62684. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  62685. if (!visualMapModel.isTargetSeries(dataModel)) {
  62686. return;
  62687. }
  62688. var data = dataModel.getData(el.dataType);
  62689. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  62690. if (!isNaN(value)) {
  62691. this._showIndicator(value, value);
  62692. }
  62693. },
  62694. /**
  62695. * @private
  62696. */
  62697. _hideIndicator: function () {
  62698. var shapes = this._shapes;
  62699. shapes.indicator && shapes.indicator.attr('invisible', true);
  62700. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  62701. },
  62702. /**
  62703. * @private
  62704. */
  62705. _clearHoverLinkToSeries: function () {
  62706. this._hideIndicator();
  62707. var indices = this._hoverLinkDataIndices;
  62708. this._dispatchHighDown('downplay', convertDataIndex(indices));
  62709. indices.length = 0;
  62710. },
  62711. /**
  62712. * @private
  62713. */
  62714. _clearHoverLinkFromSeries: function () {
  62715. this._hideIndicator();
  62716. var zr = this.api.getZr();
  62717. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  62718. zr.off('mouseout', this._hideIndicator);
  62719. },
  62720. /**
  62721. * @private
  62722. */
  62723. _applyTransform: function (vertex, element, inverse, global) {
  62724. var transform = getTransform(element, global ? null : this.group);
  62725. return graphic[
  62726. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  62727. ](vertex, transform, inverse);
  62728. },
  62729. /**
  62730. * @private
  62731. */
  62732. _dispatchHighDown: function (type, batch) {
  62733. batch && batch.length && this.api.dispatchAction({
  62734. type: type,
  62735. batch: batch
  62736. });
  62737. },
  62738. /**
  62739. * @override
  62740. */
  62741. dispose: function () {
  62742. this._clearHoverLinkFromSeries();
  62743. this._clearHoverLinkToSeries();
  62744. },
  62745. /**
  62746. * @override
  62747. */
  62748. remove: function () {
  62749. this._clearHoverLinkFromSeries();
  62750. this._clearHoverLinkToSeries();
  62751. }
  62752. });
  62753. function createPolygon(points, cursor, onDrift, onDragEnd) {
  62754. return new Polygon({
  62755. shape: {points: points},
  62756. draggable: !!onDrift,
  62757. cursor: cursor,
  62758. drift: onDrift,
  62759. onmousemove: function (e) {
  62760. // Fot mobile devicem, prevent screen slider on the button.
  62761. stop(e.event);
  62762. },
  62763. ondragend: onDragEnd
  62764. });
  62765. }
  62766. function createHandlePoints(handleIndex, textSize) {
  62767. return handleIndex === 0
  62768. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  62769. : [[0, 0], [textSize, 0], [textSize, textSize]];
  62770. }
  62771. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  62772. return isRange
  62773. ? [ // indicate range
  62774. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  62775. [HOVER_LINK_OUT, 0],
  62776. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  62777. ]
  62778. : [ // indicate single value
  62779. [0, 0], [5, -5], [5, 5]
  62780. ];
  62781. }
  62782. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  62783. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  62784. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  62785. if (hoverLinkDataSize) {
  62786. halfHoverLinkSize = linearMap$4(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  62787. }
  62788. return halfHoverLinkSize;
  62789. }
  62790. function useHoverLinkOnHandle(visualMapModel) {
  62791. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  62792. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  62793. }
  62794. function getCursor$1(orient) {
  62795. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  62796. }
  62797. var actionInfo$2 = {
  62798. type: 'selectDataRange',
  62799. event: 'dataRangeSelected',
  62800. // FIXME use updateView appears wrong
  62801. update: 'update'
  62802. };
  62803. registerAction(actionInfo$2, function (payload, ecModel) {
  62804. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  62805. model.setSelected(payload.selected);
  62806. });
  62807. });
  62808. /**
  62809. * DataZoom component entry
  62810. */
  62811. registerPreprocessor(preprocessor$2);
  62812. var PiecewiseModel = VisualMapModel.extend({
  62813. type: 'visualMap.piecewise',
  62814. /**
  62815. * Order Rule:
  62816. *
  62817. * option.categories / option.pieces / option.text / option.selected:
  62818. * If !option.inverse,
  62819. * Order when vertical: ['top', ..., 'bottom'].
  62820. * Order when horizontal: ['left', ..., 'right'].
  62821. * If option.inverse, the meaning of
  62822. * the order should be reversed.
  62823. *
  62824. * this._pieceList:
  62825. * The order is always [low, ..., high].
  62826. *
  62827. * Mapping from location to low-high:
  62828. * If !option.inverse
  62829. * When vertical, top is high.
  62830. * When horizontal, right is high.
  62831. * If option.inverse, reverse.
  62832. */
  62833. /**
  62834. * @protected
  62835. */
  62836. defaultOption: {
  62837. selected: null, // Object. If not specified, means selected.
  62838. // When pieces and splitNumber: {'0': true, '5': true}
  62839. // When categories: {'cate1': false, 'cate3': true}
  62840. // When selected === false, means all unselected.
  62841. minOpen: false, // Whether include values that smaller than `min`.
  62842. maxOpen: false, // Whether include values that bigger than `max`.
  62843. align: 'auto', // 'auto', 'left', 'right'
  62844. itemWidth: 20, // When put the controller vertically, it is the length of
  62845. // horizontal side of each item. Otherwise, vertical side.
  62846. itemHeight: 14, // When put the controller vertically, it is the length of
  62847. // vertical side of each item. Otherwise, horizontal side.
  62848. itemSymbol: 'roundRect',
  62849. pieceList: null, // Each item is Object, with some of those attrs:
  62850. // {min, max, lt, gt, lte, gte, value,
  62851. // color, colorSaturation, colorAlpha, opacity,
  62852. // symbol, symbolSize}, which customize the range or visual
  62853. // coding of the certain piece. Besides, see "Order Rule".
  62854. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  62855. // Attr min/max are ignored when categories set. See "Order Rule"
  62856. splitNumber: 5, // If set to 5, auto split five pieces equally.
  62857. // If set to 0 and component type not set, component type will be
  62858. // determined as "continuous". (It is less reasonable but for ec2
  62859. // compatibility, see echarts/component/visualMap/typeDefaulter)
  62860. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  62861. itemGap: 10, // The gap between two items, in px.
  62862. hoverLink: true, // Enable hover highlight.
  62863. showLabel: null // By default, when text is used, label will hide (the logic
  62864. // is remained for compatibility reason)
  62865. },
  62866. /**
  62867. * @override
  62868. */
  62869. optionUpdated: function (newOption, isInit) {
  62870. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  62871. /**
  62872. * The order is always [low, ..., high].
  62873. * [{text: string, interval: Array.<number>}, ...]
  62874. * @private
  62875. * @type {Array.<Object>}
  62876. */
  62877. this._pieceList = [];
  62878. this.resetExtent();
  62879. /**
  62880. * 'pieces', 'categories', 'splitNumber'
  62881. * @type {string}
  62882. */
  62883. var mode = this._mode = this._determineMode();
  62884. resetMethods[this._mode].call(this);
  62885. this._resetSelected(newOption, isInit);
  62886. var categories = this.option.categories;
  62887. this.resetVisual(function (mappingOption, state) {
  62888. if (mode === 'categories') {
  62889. mappingOption.mappingMethod = 'category';
  62890. mappingOption.categories = clone(categories);
  62891. }
  62892. else {
  62893. mappingOption.dataExtent = this.getExtent();
  62894. mappingOption.mappingMethod = 'piecewise';
  62895. mappingOption.pieceList = map(this._pieceList, function (piece) {
  62896. var piece = clone(piece);
  62897. if (state !== 'inRange') {
  62898. // FIXME
  62899. // outOfRange do not support special visual in pieces.
  62900. piece.visual = null;
  62901. }
  62902. return piece;
  62903. });
  62904. }
  62905. });
  62906. },
  62907. /**
  62908. * @protected
  62909. * @override
  62910. */
  62911. completeVisualOption: function () {
  62912. // Consider this case:
  62913. // visualMap: {
  62914. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  62915. // }
  62916. // where no inRange/outOfRange set but only pieces. So we should make
  62917. // default inRange/outOfRange for this case, otherwise visuals that only
  62918. // appear in `pieces` will not be taken into account in visual encoding.
  62919. var option = this.option;
  62920. var visualTypesInPieces = {};
  62921. var visualTypes = VisualMapping.listVisualTypes();
  62922. var isCategory = this.isCategory();
  62923. each$1(option.pieces, function (piece) {
  62924. each$1(visualTypes, function (visualType) {
  62925. if (piece.hasOwnProperty(visualType)) {
  62926. visualTypesInPieces[visualType] = 1;
  62927. }
  62928. });
  62929. });
  62930. each$1(visualTypesInPieces, function (v, visualType) {
  62931. var exists = 0;
  62932. each$1(this.stateList, function (state) {
  62933. exists |= has(option, state, visualType)
  62934. || has(option.target, state, visualType);
  62935. }, this);
  62936. !exists && each$1(this.stateList, function (state) {
  62937. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  62938. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  62939. );
  62940. });
  62941. }, this);
  62942. function has(obj, state, visualType) {
  62943. return obj && obj[state] && (
  62944. isObject$1(obj[state])
  62945. ? obj[state].hasOwnProperty(visualType)
  62946. : obj[state] === visualType // e.g., inRange: 'symbol'
  62947. );
  62948. }
  62949. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  62950. },
  62951. _resetSelected: function (newOption, isInit) {
  62952. var thisOption = this.option;
  62953. var pieceList = this._pieceList;
  62954. // Selected do not merge but all override.
  62955. var selected = (isInit ? thisOption : newOption).selected || {};
  62956. thisOption.selected = selected;
  62957. // Consider 'not specified' means true.
  62958. each$1(pieceList, function (piece, index) {
  62959. var key = this.getSelectedMapKey(piece);
  62960. if (!selected.hasOwnProperty(key)) {
  62961. selected[key] = true;
  62962. }
  62963. }, this);
  62964. if (thisOption.selectedMode === 'single') {
  62965. // Ensure there is only one selected.
  62966. var hasSel = false;
  62967. each$1(pieceList, function (piece, index) {
  62968. var key = this.getSelectedMapKey(piece);
  62969. if (selected[key]) {
  62970. hasSel
  62971. ? (selected[key] = false)
  62972. : (hasSel = true);
  62973. }
  62974. }, this);
  62975. }
  62976. // thisOption.selectedMode === 'multiple', default: all selected.
  62977. },
  62978. /**
  62979. * @public
  62980. */
  62981. getSelectedMapKey: function (piece) {
  62982. return this._mode === 'categories'
  62983. ? piece.value + '' : piece.index + '';
  62984. },
  62985. /**
  62986. * @public
  62987. */
  62988. getPieceList: function () {
  62989. return this._pieceList;
  62990. },
  62991. /**
  62992. * @private
  62993. * @return {string}
  62994. */
  62995. _determineMode: function () {
  62996. var option = this.option;
  62997. return option.pieces && option.pieces.length > 0
  62998. ? 'pieces'
  62999. : this.option.categories
  63000. ? 'categories'
  63001. : 'splitNumber';
  63002. },
  63003. /**
  63004. * @public
  63005. * @override
  63006. */
  63007. setSelected: function (selected) {
  63008. this.option.selected = clone(selected);
  63009. },
  63010. /**
  63011. * @public
  63012. * @override
  63013. */
  63014. getValueState: function (value) {
  63015. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  63016. return index != null
  63017. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  63018. ? 'inRange' : 'outOfRange'
  63019. )
  63020. : 'outOfRange';
  63021. },
  63022. /**
  63023. * @public
  63024. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  63025. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  63026. */
  63027. findTargetDataIndices: function (pieceIndex) {
  63028. var result = [];
  63029. this.eachTargetSeries(function (seriesModel) {
  63030. var dataIndices = [];
  63031. var data = seriesModel.getData();
  63032. data.each(this.getDataDimension(data), function (value, dataIndex) {
  63033. // Should always base on model pieceList, because it is order sensitive.
  63034. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  63035. pIdx === pieceIndex && dataIndices.push(dataIndex);
  63036. }, this);
  63037. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  63038. }, this);
  63039. return result;
  63040. },
  63041. /**
  63042. * @private
  63043. * @param {Object} piece piece.value or piece.interval is required.
  63044. * @return {number} Can be Infinity or -Infinity
  63045. */
  63046. getRepresentValue: function (piece) {
  63047. var representValue;
  63048. if (this.isCategory()) {
  63049. representValue = piece.value;
  63050. }
  63051. else {
  63052. if (piece.value != null) {
  63053. representValue = piece.value;
  63054. }
  63055. else {
  63056. var pieceInterval = piece.interval || [];
  63057. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  63058. ? 0
  63059. : (pieceInterval[0] + pieceInterval[1]) / 2;
  63060. }
  63061. }
  63062. return representValue;
  63063. },
  63064. getVisualMeta: function (getColorVisual) {
  63065. // Do not support category. (category axis is ordinal, numerical)
  63066. if (this.isCategory()) {
  63067. return;
  63068. }
  63069. var stops = [];
  63070. var outerColors = [];
  63071. var visualMapModel = this;
  63072. function setStop(interval, valueState) {
  63073. var representValue = visualMapModel.getRepresentValue({interval: interval});
  63074. if (!valueState) {
  63075. valueState = visualMapModel.getValueState(representValue);
  63076. }
  63077. var color = getColorVisual(representValue, valueState);
  63078. if (interval[0] === -Infinity) {
  63079. outerColors[0] = color;
  63080. }
  63081. else if (interval[1] === Infinity) {
  63082. outerColors[1] = color;
  63083. }
  63084. else {
  63085. stops.push(
  63086. {value: interval[0], color: color},
  63087. {value: interval[1], color: color}
  63088. );
  63089. }
  63090. }
  63091. // Suplement
  63092. var pieceList = this._pieceList.slice();
  63093. if (!pieceList.length) {
  63094. pieceList.push({interval: [-Infinity, Infinity]});
  63095. }
  63096. else {
  63097. var edge = pieceList[0].interval[0];
  63098. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  63099. edge = pieceList[pieceList.length - 1].interval[1];
  63100. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  63101. }
  63102. var curr = -Infinity;
  63103. each$1(pieceList, function (piece) {
  63104. var interval = piece.interval;
  63105. if (interval) {
  63106. // Fulfill gap.
  63107. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  63108. setStop(interval.slice());
  63109. curr = interval[1];
  63110. }
  63111. }, this);
  63112. return {stops: stops, outerColors: outerColors};
  63113. }
  63114. });
  63115. /**
  63116. * Key is this._mode
  63117. * @type {Object}
  63118. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  63119. */
  63120. var resetMethods = {
  63121. splitNumber: function () {
  63122. var thisOption = this.option;
  63123. var pieceList = this._pieceList;
  63124. var precision = Math.min(thisOption.precision, 20);
  63125. var dataExtent = this.getExtent();
  63126. var splitNumber = thisOption.splitNumber;
  63127. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  63128. thisOption.splitNumber = splitNumber;
  63129. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  63130. // Precision auto-adaption
  63131. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  63132. precision++;
  63133. }
  63134. thisOption.precision = precision;
  63135. splitStep = +splitStep.toFixed(precision);
  63136. var index = 0;
  63137. if (thisOption.minOpen) {
  63138. pieceList.push({
  63139. index: index++,
  63140. interval: [-Infinity, dataExtent[0]],
  63141. close: [0, 0]
  63142. });
  63143. }
  63144. for (
  63145. var curr = dataExtent[0], len = index + splitNumber;
  63146. index < len;
  63147. curr += splitStep
  63148. ) {
  63149. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  63150. pieceList.push({
  63151. index: index++,
  63152. interval: [curr, max],
  63153. close: [1, 1]
  63154. });
  63155. }
  63156. if (thisOption.maxOpen) {
  63157. pieceList.push({
  63158. index: index++,
  63159. interval: [dataExtent[1], Infinity],
  63160. close: [0, 0]
  63161. });
  63162. }
  63163. reformIntervals(pieceList);
  63164. each$1(pieceList, function (piece) {
  63165. piece.text = this.formatValueText(piece.interval);
  63166. }, this);
  63167. },
  63168. categories: function () {
  63169. var thisOption = this.option;
  63170. each$1(thisOption.categories, function (cate) {
  63171. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  63172. // 是否改一致。
  63173. this._pieceList.push({
  63174. text: this.formatValueText(cate, true),
  63175. value: cate
  63176. });
  63177. }, this);
  63178. // See "Order Rule".
  63179. normalizeReverse(thisOption, this._pieceList);
  63180. },
  63181. pieces: function () {
  63182. var thisOption = this.option;
  63183. var pieceList = this._pieceList;
  63184. each$1(thisOption.pieces, function (pieceListItem, index) {
  63185. if (!isObject$1(pieceListItem)) {
  63186. pieceListItem = {value: pieceListItem};
  63187. }
  63188. var item = {text: '', index: index};
  63189. if (pieceListItem.label != null) {
  63190. item.text = pieceListItem.label;
  63191. }
  63192. if (pieceListItem.hasOwnProperty('value')) {
  63193. var value = item.value = pieceListItem.value;
  63194. item.interval = [value, value];
  63195. item.close = [1, 1];
  63196. }
  63197. else {
  63198. // `min` `max` is legacy option.
  63199. // `lt` `gt` `lte` `gte` is recommanded.
  63200. var interval = item.interval = [];
  63201. var close = item.close = [0, 0];
  63202. var closeList = [1, 0, 1];
  63203. var infinityList = [-Infinity, Infinity];
  63204. var useMinMax = [];
  63205. for (var lg = 0; lg < 2; lg++) {
  63206. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  63207. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  63208. interval[lg] = pieceListItem[names[i]];
  63209. close[lg] = closeList[i];
  63210. useMinMax[lg] = i === 2;
  63211. }
  63212. interval[lg] == null && (interval[lg] = infinityList[lg]);
  63213. }
  63214. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  63215. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  63216. if (__DEV__) {
  63217. if (interval[0] > interval[1]) {
  63218. console.warn(
  63219. 'Piece ' + index + 'is illegal: ' + interval
  63220. + ' lower bound should not greater then uppper bound.'
  63221. );
  63222. }
  63223. }
  63224. if (interval[0] === interval[1] && close[0] && close[1]) {
  63225. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  63226. // we use value to lift the priority when min === max
  63227. item.value = interval[0];
  63228. }
  63229. }
  63230. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  63231. pieceList.push(item);
  63232. }, this);
  63233. // See "Order Rule".
  63234. normalizeReverse(thisOption, pieceList);
  63235. // Only pieces
  63236. reformIntervals(pieceList);
  63237. each$1(pieceList, function (piece) {
  63238. var close = piece.close;
  63239. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  63240. piece.text = piece.text || this.formatValueText(
  63241. piece.value != null ? piece.value : piece.interval,
  63242. false,
  63243. edgeSymbols
  63244. );
  63245. }, this);
  63246. }
  63247. };
  63248. function normalizeReverse(thisOption, pieceList) {
  63249. var inverse = thisOption.inverse;
  63250. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  63251. pieceList.reverse();
  63252. }
  63253. }
  63254. var PiecewiseVisualMapView = VisualMapView.extend({
  63255. type: 'visualMap.piecewise',
  63256. /**
  63257. * @protected
  63258. * @override
  63259. */
  63260. doRender: function () {
  63261. var thisGroup = this.group;
  63262. thisGroup.removeAll();
  63263. var visualMapModel = this.visualMapModel;
  63264. var textGap = visualMapModel.get('textGap');
  63265. var textStyleModel = visualMapModel.textStyleModel;
  63266. var textFont = textStyleModel.getFont();
  63267. var textFill = textStyleModel.getTextColor();
  63268. var itemAlign = this._getItemAlign();
  63269. var itemSize = visualMapModel.itemSize;
  63270. var viewData = this._getViewData();
  63271. var endsText = viewData.endsText;
  63272. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  63273. endsText && this._renderEndsText(
  63274. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  63275. );
  63276. each$1(viewData.viewPieceList, renderItem, this);
  63277. endsText && this._renderEndsText(
  63278. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  63279. );
  63280. box(
  63281. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  63282. );
  63283. this.renderBackground(thisGroup);
  63284. this.positionGroup(thisGroup);
  63285. function renderItem(item) {
  63286. var piece = item.piece;
  63287. var itemGroup = new Group();
  63288. itemGroup.onclick = bind(this._onItemClick, this, piece);
  63289. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  63290. var representValue = visualMapModel.getRepresentValue(piece);
  63291. this._createItemSymbol(
  63292. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  63293. );
  63294. if (showLabel) {
  63295. var visualState = this.visualMapModel.getValueState(representValue);
  63296. itemGroup.add(new Text({
  63297. style: {
  63298. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  63299. y: itemSize[1] / 2,
  63300. text: piece.text,
  63301. textVerticalAlign: 'middle',
  63302. textAlign: itemAlign,
  63303. textFont: textFont,
  63304. textFill: textFill,
  63305. opacity: visualState === 'outOfRange' ? 0.5 : 1
  63306. }
  63307. }));
  63308. }
  63309. thisGroup.add(itemGroup);
  63310. }
  63311. },
  63312. /**
  63313. * @private
  63314. */
  63315. _enableHoverLink: function (itemGroup, pieceIndex) {
  63316. itemGroup
  63317. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  63318. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  63319. function onHoverLink(method) {
  63320. var visualMapModel = this.visualMapModel;
  63321. visualMapModel.option.hoverLink && this.api.dispatchAction({
  63322. type: method,
  63323. batch: convertDataIndex(
  63324. visualMapModel.findTargetDataIndices(pieceIndex)
  63325. )
  63326. });
  63327. }
  63328. },
  63329. /**
  63330. * @private
  63331. */
  63332. _getItemAlign: function () {
  63333. var visualMapModel = this.visualMapModel;
  63334. var modelOption = visualMapModel.option;
  63335. if (modelOption.orient === 'vertical') {
  63336. return getItemAlign(
  63337. visualMapModel, this.api, visualMapModel.itemSize
  63338. );
  63339. }
  63340. else { // horizontal, most case left unless specifying right.
  63341. var align = modelOption.align;
  63342. if (!align || align === 'auto') {
  63343. align = 'left';
  63344. }
  63345. return align;
  63346. }
  63347. },
  63348. /**
  63349. * @private
  63350. */
  63351. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  63352. if (!text) {
  63353. return;
  63354. }
  63355. var itemGroup = new Group();
  63356. var textStyleModel = this.visualMapModel.textStyleModel;
  63357. itemGroup.add(new Text({
  63358. style: {
  63359. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  63360. y: itemSize[1] / 2,
  63361. textVerticalAlign: 'middle',
  63362. textAlign: showLabel ? itemAlign : 'center',
  63363. text: text,
  63364. textFont: textStyleModel.getFont(),
  63365. textFill: textStyleModel.getTextColor()
  63366. }
  63367. }));
  63368. group.add(itemGroup);
  63369. },
  63370. /**
  63371. * @private
  63372. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  63373. */
  63374. _getViewData: function () {
  63375. var visualMapModel = this.visualMapModel;
  63376. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  63377. return {piece: piece, indexInModelPieceList: index};
  63378. });
  63379. var endsText = visualMapModel.get('text');
  63380. // Consider orient and inverse.
  63381. var orient = visualMapModel.get('orient');
  63382. var inverse = visualMapModel.get('inverse');
  63383. // Order of model pieceList is always [low, ..., high]
  63384. if (orient === 'horizontal' ? inverse : !inverse) {
  63385. viewPieceList.reverse();
  63386. }
  63387. // Origin order of endsText is [high, low]
  63388. else if (endsText) {
  63389. endsText = endsText.slice().reverse();
  63390. }
  63391. return {viewPieceList: viewPieceList, endsText: endsText};
  63392. },
  63393. /**
  63394. * @private
  63395. */
  63396. _createItemSymbol: function (group, representValue, shapeParam) {
  63397. group.add(createSymbol(
  63398. this.getControllerVisual(representValue, 'symbol'),
  63399. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  63400. this.getControllerVisual(representValue, 'color')
  63401. ));
  63402. },
  63403. /**
  63404. * @private
  63405. */
  63406. _onItemClick: function (piece) {
  63407. var visualMapModel = this.visualMapModel;
  63408. var option = visualMapModel.option;
  63409. var selected = clone(option.selected);
  63410. var newKey = visualMapModel.getSelectedMapKey(piece);
  63411. if (option.selectedMode === 'single') {
  63412. selected[newKey] = true;
  63413. each$1(selected, function (o, key) {
  63414. selected[key] = key === newKey;
  63415. });
  63416. }
  63417. else {
  63418. selected[newKey] = !selected[newKey];
  63419. }
  63420. this.api.dispatchAction({
  63421. type: 'selectDataRange',
  63422. from: this.uid,
  63423. visualMapId: this.visualMapModel.id,
  63424. selected: selected
  63425. });
  63426. }
  63427. });
  63428. /**
  63429. * DataZoom component entry
  63430. */
  63431. registerPreprocessor(preprocessor$2);
  63432. /**
  63433. * visualMap component entry
  63434. */
  63435. var addCommas$1 = addCommas;
  63436. var encodeHTML$1 = encodeHTML;
  63437. function fillLabel(opt) {
  63438. defaultEmphasis(opt, 'label', ['show']);
  63439. }
  63440. var MarkerModel = extendComponentModel({
  63441. type: 'marker',
  63442. dependencies: ['series', 'grid', 'polar', 'geo'],
  63443. /**
  63444. * @overrite
  63445. */
  63446. init: function (option, parentModel, ecModel, extraOpt) {
  63447. if (__DEV__) {
  63448. if (this.type === 'marker') {
  63449. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  63450. }
  63451. }
  63452. this.mergeDefaultAndTheme(option, ecModel);
  63453. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  63454. },
  63455. /**
  63456. * @return {boolean}
  63457. */
  63458. isAnimationEnabled: function () {
  63459. if (env$1.node) {
  63460. return false;
  63461. }
  63462. var hostSeries = this.__hostSeries;
  63463. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  63464. },
  63465. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  63466. var MarkerModel = this.constructor;
  63467. var modelPropName = this.mainType + 'Model';
  63468. if (!createdBySelf) {
  63469. ecModel.eachSeries(function (seriesModel) {
  63470. var markerOpt = seriesModel.get(this.mainType);
  63471. var markerModel = seriesModel[modelPropName];
  63472. if (!markerOpt || !markerOpt.data) {
  63473. seriesModel[modelPropName] = null;
  63474. return;
  63475. }
  63476. if (!markerModel) {
  63477. if (isInit) {
  63478. // Default label emphasis `position` and `show`
  63479. fillLabel(markerOpt);
  63480. }
  63481. each$1(markerOpt.data, function (item) {
  63482. // FIXME Overwrite fillLabel method ?
  63483. if (item instanceof Array) {
  63484. fillLabel(item[0]);
  63485. fillLabel(item[1]);
  63486. }
  63487. else {
  63488. fillLabel(item);
  63489. }
  63490. });
  63491. markerModel = new MarkerModel(
  63492. markerOpt, this, ecModel
  63493. );
  63494. extend(markerModel, {
  63495. mainType: this.mainType,
  63496. // Use the same series index and name
  63497. seriesIndex: seriesModel.seriesIndex,
  63498. name: seriesModel.name,
  63499. createdBySelf: true
  63500. });
  63501. markerModel.__hostSeries = seriesModel;
  63502. }
  63503. else {
  63504. markerModel.mergeOption(markerOpt, ecModel, true);
  63505. }
  63506. seriesModel[modelPropName] = markerModel;
  63507. }, this);
  63508. }
  63509. },
  63510. formatTooltip: function (dataIndex) {
  63511. var data = this.getData();
  63512. var value = this.getRawValue(dataIndex);
  63513. var formattedValue = isArray(value)
  63514. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  63515. var name = data.getName(dataIndex);
  63516. var html = encodeHTML$1(this.name);
  63517. if (value != null || name) {
  63518. html += '<br />';
  63519. }
  63520. if (name) {
  63521. html += encodeHTML$1(name);
  63522. if (value != null) {
  63523. html += ' : ';
  63524. }
  63525. }
  63526. if (value != null) {
  63527. html += encodeHTML$1(formattedValue);
  63528. }
  63529. return html;
  63530. },
  63531. getData: function () {
  63532. return this._data;
  63533. },
  63534. setData: function (data) {
  63535. this._data = data;
  63536. }
  63537. });
  63538. mixin(MarkerModel, dataFormatMixin);
  63539. MarkerModel.extend({
  63540. type: 'markPoint',
  63541. defaultOption: {
  63542. zlevel: 0,
  63543. z: 5,
  63544. symbol: 'pin',
  63545. symbolSize: 50,
  63546. //symbolRotate: 0,
  63547. //symbolOffset: [0, 0]
  63548. tooltip: {
  63549. trigger: 'item'
  63550. },
  63551. label: {
  63552. show: true,
  63553. position: 'inside'
  63554. },
  63555. itemStyle: {
  63556. borderWidth: 2
  63557. },
  63558. emphasis: {
  63559. label: {
  63560. show: true
  63561. }
  63562. }
  63563. }
  63564. });
  63565. var indexOf$2 = indexOf;
  63566. function hasXOrY(item) {
  63567. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  63568. }
  63569. function hasXAndY(item) {
  63570. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  63571. }
  63572. // Make it simple, do not visit all stacked value to count precision.
  63573. // function getPrecision(data, valueAxisDim, dataIndex) {
  63574. // var precision = -1;
  63575. // var stackedDim = data.mapDimension(valueAxisDim);
  63576. // do {
  63577. // precision = Math.max(
  63578. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  63579. // precision
  63580. // );
  63581. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  63582. // if (stackedOnSeries) {
  63583. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  63584. // data = stackedOnSeries.getData();
  63585. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  63586. // stackedDim = data.getCalculationInfo('stackedDimension');
  63587. // }
  63588. // else {
  63589. // data = null;
  63590. // }
  63591. // } while (data);
  63592. // return precision;
  63593. // }
  63594. function markerTypeCalculatorWithExtent(
  63595. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  63596. ) {
  63597. var coordArr = [];
  63598. var stacked = isDimensionStacked(data, targetDataDim, otherDataDim);
  63599. var calcDataDim = stacked
  63600. ? data.getCalculationInfo('stackResultDimension')
  63601. : targetDataDim;
  63602. var value = numCalculate(data, calcDataDim, mlType);
  63603. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  63604. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  63605. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  63606. // Make it simple, do not visit all stacked value to count precision.
  63607. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  63608. precision = Math.min(precision, 20);
  63609. if (precision >= 0) {
  63610. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  63611. }
  63612. return coordArr;
  63613. }
  63614. var curry$7 = curry;
  63615. // TODO Specified percent
  63616. var markerTypeCalculator = {
  63617. /**
  63618. * @method
  63619. * @param {module:echarts/data/List} data
  63620. * @param {string} baseAxisDim
  63621. * @param {string} valueAxisDim
  63622. */
  63623. min: curry$7(markerTypeCalculatorWithExtent, 'min'),
  63624. /**
  63625. * @method
  63626. * @param {module:echarts/data/List} data
  63627. * @param {string} baseAxisDim
  63628. * @param {string} valueAxisDim
  63629. */
  63630. max: curry$7(markerTypeCalculatorWithExtent, 'max'),
  63631. /**
  63632. * @method
  63633. * @param {module:echarts/data/List} data
  63634. * @param {string} baseAxisDim
  63635. * @param {string} valueAxisDim
  63636. */
  63637. average: curry$7(markerTypeCalculatorWithExtent, 'average')
  63638. };
  63639. /**
  63640. * Transform markPoint data item to format used in List by do the following
  63641. * 1. Calculate statistic like `max`, `min`, `average`
  63642. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  63643. * @param {module:echarts/model/Series} seriesModel
  63644. * @param {module:echarts/coord/*} [coordSys]
  63645. * @param {Object} item
  63646. * @return {Object}
  63647. */
  63648. function dataTransform(seriesModel, item) {
  63649. var data = seriesModel.getData();
  63650. var coordSys = seriesModel.coordinateSystem;
  63651. // 1. If not specify the position with pixel directly
  63652. // 2. If `coord` is not a data array. Which uses `xAxis`,
  63653. // `yAxis` to specify the coord on each dimension
  63654. // parseFloat first because item.x and item.y can be percent string like '20%'
  63655. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  63656. var dims = coordSys.dimensions;
  63657. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  63658. // Clone the option
  63659. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  63660. item = clone(item);
  63661. if (item.type
  63662. && markerTypeCalculator[item.type]
  63663. && axisInfo.baseAxis && axisInfo.valueAxis
  63664. ) {
  63665. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  63666. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  63667. item.coord = markerTypeCalculator[item.type](
  63668. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  63669. otherCoordIndex, targetCoordIndex
  63670. );
  63671. // Force to use the value of calculated value.
  63672. item.value = item.coord[targetCoordIndex];
  63673. }
  63674. else {
  63675. // FIXME Only has one of xAxis and yAxis.
  63676. var coord = [
  63677. item.xAxis != null ? item.xAxis : item.radiusAxis,
  63678. item.yAxis != null ? item.yAxis : item.angleAxis
  63679. ];
  63680. // Each coord support max, min, average
  63681. for (var i = 0; i < 2; i++) {
  63682. if (markerTypeCalculator[coord[i]]) {
  63683. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  63684. }
  63685. }
  63686. item.coord = coord;
  63687. }
  63688. }
  63689. return item;
  63690. }
  63691. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  63692. var ret = {};
  63693. if (item.valueIndex != null || item.valueDim != null) {
  63694. ret.valueDataDim = item.valueIndex != null
  63695. ? data.getDimension(item.valueIndex) : item.valueDim;
  63696. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  63697. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  63698. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  63699. }
  63700. else {
  63701. ret.baseAxis = seriesModel.getBaseAxis();
  63702. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  63703. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  63704. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  63705. }
  63706. return ret;
  63707. }
  63708. function dataDimToCoordDim(seriesModel, dataDim) {
  63709. var data = seriesModel.getData();
  63710. var dimensions = data.dimensions;
  63711. dataDim = data.getDimension(dataDim);
  63712. for (var i = 0; i < dimensions.length; i++) {
  63713. var dimItem = data.getDimensionInfo(dimensions[i]);
  63714. if (dimItem.name === dataDim) {
  63715. return dimItem.coordDim;
  63716. }
  63717. }
  63718. }
  63719. /**
  63720. * Filter data which is out of coordinateSystem range
  63721. * [dataFilter description]
  63722. * @param {module:echarts/coord/*} [coordSys]
  63723. * @param {Object} item
  63724. * @return {boolean}
  63725. */
  63726. function dataFilter$1(coordSys, item) {
  63727. // Alwalys return true if there is no coordSys
  63728. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  63729. ? coordSys.containData(item.coord) : true;
  63730. }
  63731. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  63732. // x, y, radius, angle
  63733. if (dimIndex < 2) {
  63734. return item.coord && item.coord[dimIndex];
  63735. }
  63736. return item.value;
  63737. }
  63738. function numCalculate(data, valueDataDim, type) {
  63739. if (type === 'average') {
  63740. var sum = 0;
  63741. var count = 0;
  63742. data.each(valueDataDim, function (val, idx) {
  63743. if (!isNaN(val)) {
  63744. sum += val;
  63745. count++;
  63746. }
  63747. });
  63748. return sum / count;
  63749. }
  63750. else {
  63751. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  63752. }
  63753. }
  63754. var MarkerView = extendComponentView({
  63755. type: 'marker',
  63756. init: function () {
  63757. /**
  63758. * Markline grouped by series
  63759. * @private
  63760. * @type {module:zrender/core/util.HashMap}
  63761. */
  63762. this.markerGroupMap = createHashMap();
  63763. },
  63764. render: function (markerModel, ecModel, api) {
  63765. var markerGroupMap = this.markerGroupMap;
  63766. markerGroupMap.each(function (item) {
  63767. item.__keep = false;
  63768. });
  63769. var markerModelKey = this.type + 'Model';
  63770. ecModel.eachSeries(function (seriesModel) {
  63771. var markerModel = seriesModel[markerModelKey];
  63772. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  63773. }, this);
  63774. markerGroupMap.each(function (item) {
  63775. !item.__keep && this.group.remove(item.group);
  63776. }, this);
  63777. },
  63778. renderSeries: function () {}
  63779. });
  63780. function updateMarkerLayout(mpData, seriesModel, api) {
  63781. var coordSys = seriesModel.coordinateSystem;
  63782. mpData.each(function (idx) {
  63783. var itemModel = mpData.getItemModel(idx);
  63784. var point;
  63785. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  63786. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  63787. if (!isNaN(xPx) && !isNaN(yPx)) {
  63788. point = [xPx, yPx];
  63789. }
  63790. // Chart like bar may have there own marker positioning logic
  63791. else if (seriesModel.getMarkerPosition) {
  63792. // Use the getMarkerPoisition
  63793. point = seriesModel.getMarkerPosition(
  63794. mpData.getValues(mpData.dimensions, idx)
  63795. );
  63796. }
  63797. else if (coordSys) {
  63798. var x = mpData.get(coordSys.dimensions[0], idx);
  63799. var y = mpData.get(coordSys.dimensions[1], idx);
  63800. point = coordSys.dataToPoint([x, y]);
  63801. }
  63802. // Use x, y if has any
  63803. if (!isNaN(xPx)) {
  63804. point[0] = xPx;
  63805. }
  63806. if (!isNaN(yPx)) {
  63807. point[1] = yPx;
  63808. }
  63809. mpData.setItemLayout(idx, point);
  63810. });
  63811. }
  63812. MarkerView.extend({
  63813. type: 'markPoint',
  63814. // updateLayout: function (markPointModel, ecModel, api) {
  63815. // ecModel.eachSeries(function (seriesModel) {
  63816. // var mpModel = seriesModel.markPointModel;
  63817. // if (mpModel) {
  63818. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  63819. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  63820. // }
  63821. // }, this);
  63822. // },
  63823. updateTransform: function (markPointModel, ecModel, api) {
  63824. ecModel.eachSeries(function (seriesModel) {
  63825. var mpModel = seriesModel.markPointModel;
  63826. if (mpModel) {
  63827. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  63828. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  63829. }
  63830. }, this);
  63831. },
  63832. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  63833. var coordSys = seriesModel.coordinateSystem;
  63834. var seriesId = seriesModel.id;
  63835. var seriesData = seriesModel.getData();
  63836. var symbolDrawMap = this.markerGroupMap;
  63837. var symbolDraw = symbolDrawMap.get(seriesId)
  63838. || symbolDrawMap.set(seriesId, new SymbolDraw());
  63839. var mpData = createList$1(coordSys, seriesModel, mpModel);
  63840. // FIXME
  63841. mpModel.setData(mpData);
  63842. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  63843. mpData.each(function (idx) {
  63844. var itemModel = mpData.getItemModel(idx);
  63845. var symbolSize = itemModel.getShallow('symbolSize');
  63846. if (typeof symbolSize === 'function') {
  63847. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  63848. symbolSize = symbolSize(
  63849. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  63850. );
  63851. }
  63852. mpData.setItemVisual(idx, {
  63853. symbolSize: symbolSize,
  63854. color: itemModel.get('itemStyle.color')
  63855. || seriesData.getVisual('color'),
  63856. symbol: itemModel.getShallow('symbol')
  63857. });
  63858. });
  63859. // TODO Text are wrong
  63860. symbolDraw.updateData(mpData);
  63861. this.group.add(symbolDraw.group);
  63862. // Set host model for tooltip
  63863. // FIXME
  63864. mpData.eachItemGraphicEl(function (el) {
  63865. el.traverse(function (child) {
  63866. child.dataModel = mpModel;
  63867. });
  63868. });
  63869. symbolDraw.__keep = true;
  63870. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  63871. }
  63872. });
  63873. /**
  63874. * @inner
  63875. * @param {module:echarts/coord/*} [coordSys]
  63876. * @param {module:echarts/model/Series} seriesModel
  63877. * @param {module:echarts/model/Model} mpModel
  63878. */
  63879. function createList$1(coordSys, seriesModel, mpModel) {
  63880. var coordDimsInfos;
  63881. if (coordSys) {
  63882. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  63883. var info = seriesModel.getData().getDimensionInfo(
  63884. seriesModel.getData().mapDimension(coordDim)
  63885. ) || {};
  63886. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  63887. return defaults({name: coordDim}, info);
  63888. });
  63889. }
  63890. else {
  63891. coordDimsInfos =[{
  63892. name: 'value',
  63893. type: 'float'
  63894. }];
  63895. }
  63896. var mpData = new List(coordDimsInfos, mpModel);
  63897. var dataOpt = map(mpModel.get('data'), curry(
  63898. dataTransform, seriesModel
  63899. ));
  63900. if (coordSys) {
  63901. dataOpt = filter(
  63902. dataOpt, curry(dataFilter$1, coordSys)
  63903. );
  63904. }
  63905. mpData.initData(dataOpt, null,
  63906. coordSys ? dimValueGetter : function (item) {
  63907. return item.value;
  63908. }
  63909. );
  63910. return mpData;
  63911. }
  63912. // HINT Markpoint can't be used too much
  63913. registerPreprocessor(function (opt) {
  63914. // Make sure markPoint component is enabled
  63915. opt.markPoint = opt.markPoint || {};
  63916. });
  63917. MarkerModel.extend({
  63918. type: 'markLine',
  63919. defaultOption: {
  63920. zlevel: 0,
  63921. z: 5,
  63922. symbol: ['circle', 'arrow'],
  63923. symbolSize: [8, 16],
  63924. //symbolRotate: 0,
  63925. precision: 2,
  63926. tooltip: {
  63927. trigger: 'item'
  63928. },
  63929. label: {
  63930. show: true,
  63931. position: 'end'
  63932. },
  63933. lineStyle: {
  63934. type: 'dashed'
  63935. },
  63936. emphasis: {
  63937. label: {
  63938. show: true
  63939. },
  63940. lineStyle: {
  63941. width: 3
  63942. }
  63943. },
  63944. animationEasing: 'linear'
  63945. }
  63946. });
  63947. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  63948. var data = seriesModel.getData();
  63949. // Special type markLine like 'min', 'max', 'average'
  63950. var mlType = item.type;
  63951. if (!isArray(item)
  63952. && (
  63953. mlType === 'min' || mlType === 'max' || mlType === 'average'
  63954. // In case
  63955. // data: [{
  63956. // yAxis: 10
  63957. // }]
  63958. || (item.xAxis != null || item.yAxis != null)
  63959. )
  63960. ) {
  63961. var valueAxis;
  63962. var valueDataDim;
  63963. var value;
  63964. if (item.yAxis != null || item.xAxis != null) {
  63965. valueDataDim = item.yAxis != null ? 'y' : 'x';
  63966. valueAxis = coordSys.getAxis(valueDataDim);
  63967. value = retrieve(item.yAxis, item.xAxis);
  63968. }
  63969. else {
  63970. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  63971. valueDataDim = axisInfo.valueDataDim;
  63972. valueAxis = axisInfo.valueAxis;
  63973. value = numCalculate(data, valueDataDim, mlType);
  63974. }
  63975. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  63976. var baseIndex = 1 - valueIndex;
  63977. var mlFrom = clone(item);
  63978. var mlTo = {};
  63979. mlFrom.type = null;
  63980. mlFrom.coord = [];
  63981. mlTo.coord = [];
  63982. mlFrom.coord[baseIndex] = -Infinity;
  63983. mlTo.coord[baseIndex] = Infinity;
  63984. var precision = mlModel.get('precision');
  63985. if (precision >= 0 && typeof value === 'number') {
  63986. value = +value.toFixed(Math.min(precision, 20));
  63987. }
  63988. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  63989. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  63990. type: mlType,
  63991. valueIndex: item.valueIndex,
  63992. // Force to use the value of calculated value.
  63993. value: value
  63994. }];
  63995. }
  63996. item = [
  63997. dataTransform(seriesModel, item[0]),
  63998. dataTransform(seriesModel, item[1]),
  63999. extend({}, item[2])
  64000. ];
  64001. // Avoid line data type is extended by from(to) data type
  64002. item[2].type = item[2].type || '';
  64003. // Merge from option and to option into line option
  64004. merge(item[2], item[0]);
  64005. merge(item[2], item[1]);
  64006. return item;
  64007. };
  64008. function isInifinity(val) {
  64009. return !isNaN(val) && !isFinite(val);
  64010. }
  64011. // If a markLine has one dim
  64012. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  64013. var otherDimIndex = 1 - dimIndex;
  64014. var dimName = coordSys.dimensions[dimIndex];
  64015. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  64016. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  64017. }
  64018. function markLineFilter(coordSys, item) {
  64019. if (coordSys.type === 'cartesian2d') {
  64020. var fromCoord = item[0].coord;
  64021. var toCoord = item[1].coord;
  64022. // In case
  64023. // {
  64024. // markLine: {
  64025. // data: [{ yAxis: 2 }]
  64026. // }
  64027. // }
  64028. if (
  64029. fromCoord && toCoord &&
  64030. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  64031. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  64032. ) {
  64033. return true;
  64034. }
  64035. }
  64036. return dataFilter$1(coordSys, item[0])
  64037. && dataFilter$1(coordSys, item[1]);
  64038. }
  64039. function updateSingleMarkerEndLayout(
  64040. data, idx, isFrom, seriesModel, api
  64041. ) {
  64042. var coordSys = seriesModel.coordinateSystem;
  64043. var itemModel = data.getItemModel(idx);
  64044. var point;
  64045. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  64046. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  64047. if (!isNaN(xPx) && !isNaN(yPx)) {
  64048. point = [xPx, yPx];
  64049. }
  64050. else {
  64051. // Chart like bar may have there own marker positioning logic
  64052. if (seriesModel.getMarkerPosition) {
  64053. // Use the getMarkerPoisition
  64054. point = seriesModel.getMarkerPosition(
  64055. data.getValues(data.dimensions, idx)
  64056. );
  64057. }
  64058. else {
  64059. var dims = coordSys.dimensions;
  64060. var x = data.get(dims[0], idx);
  64061. var y = data.get(dims[1], idx);
  64062. point = coordSys.dataToPoint([x, y]);
  64063. }
  64064. // Expand line to the edge of grid if value on one axis is Inifnity
  64065. // In case
  64066. // markLine: {
  64067. // data: [{
  64068. // yAxis: 2
  64069. // // or
  64070. // type: 'average'
  64071. // }]
  64072. // }
  64073. if (coordSys.type === 'cartesian2d') {
  64074. var xAxis = coordSys.getAxis('x');
  64075. var yAxis = coordSys.getAxis('y');
  64076. var dims = coordSys.dimensions;
  64077. if (isInifinity(data.get(dims[0], idx))) {
  64078. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  64079. }
  64080. else if (isInifinity(data.get(dims[1], idx))) {
  64081. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  64082. }
  64083. }
  64084. // Use x, y if has any
  64085. if (!isNaN(xPx)) {
  64086. point[0] = xPx;
  64087. }
  64088. if (!isNaN(yPx)) {
  64089. point[1] = yPx;
  64090. }
  64091. }
  64092. data.setItemLayout(idx, point);
  64093. }
  64094. MarkerView.extend({
  64095. type: 'markLine',
  64096. // updateLayout: function (markLineModel, ecModel, api) {
  64097. // ecModel.eachSeries(function (seriesModel) {
  64098. // var mlModel = seriesModel.markLineModel;
  64099. // if (mlModel) {
  64100. // var mlData = mlModel.getData();
  64101. // var fromData = mlModel.__from;
  64102. // var toData = mlModel.__to;
  64103. // // Update visual and layout of from symbol and to symbol
  64104. // fromData.each(function (idx) {
  64105. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  64106. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  64107. // });
  64108. // // Update layout of line
  64109. // mlData.each(function (idx) {
  64110. // mlData.setItemLayout(idx, [
  64111. // fromData.getItemLayout(idx),
  64112. // toData.getItemLayout(idx)
  64113. // ]);
  64114. // });
  64115. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  64116. // }
  64117. // }, this);
  64118. // },
  64119. updateTransform: function (markLineModel, ecModel, api) {
  64120. ecModel.eachSeries(function (seriesModel) {
  64121. var mlModel = seriesModel.markLineModel;
  64122. if (mlModel) {
  64123. var mlData = mlModel.getData();
  64124. var fromData = mlModel.__from;
  64125. var toData = mlModel.__to;
  64126. // Update visual and layout of from symbol and to symbol
  64127. fromData.each(function (idx) {
  64128. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  64129. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  64130. });
  64131. // Update layout of line
  64132. mlData.each(function (idx) {
  64133. mlData.setItemLayout(idx, [
  64134. fromData.getItemLayout(idx),
  64135. toData.getItemLayout(idx)
  64136. ]);
  64137. });
  64138. this.markerGroupMap.get(seriesModel.id).updateLayout();
  64139. }
  64140. }, this);
  64141. },
  64142. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  64143. var coordSys = seriesModel.coordinateSystem;
  64144. var seriesId = seriesModel.id;
  64145. var seriesData = seriesModel.getData();
  64146. var lineDrawMap = this.markerGroupMap;
  64147. var lineDraw = lineDrawMap.get(seriesId)
  64148. || lineDrawMap.set(seriesId, new LineDraw());
  64149. this.group.add(lineDraw.group);
  64150. var mlData = createList$2(coordSys, seriesModel, mlModel);
  64151. var fromData = mlData.from;
  64152. var toData = mlData.to;
  64153. var lineData = mlData.line;
  64154. mlModel.__from = fromData;
  64155. mlModel.__to = toData;
  64156. // Line data for tooltip and formatter
  64157. mlModel.setData(lineData);
  64158. var symbolType = mlModel.get('symbol');
  64159. var symbolSize = mlModel.get('symbolSize');
  64160. if (!isArray(symbolType)) {
  64161. symbolType = [symbolType, symbolType];
  64162. }
  64163. if (typeof symbolSize === 'number') {
  64164. symbolSize = [symbolSize, symbolSize];
  64165. }
  64166. // Update visual and layout of from symbol and to symbol
  64167. mlData.from.each(function (idx) {
  64168. updateDataVisualAndLayout(fromData, idx, true);
  64169. updateDataVisualAndLayout(toData, idx, false);
  64170. });
  64171. // Update visual and layout of line
  64172. lineData.each(function (idx) {
  64173. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  64174. lineData.setItemVisual(idx, {
  64175. color: lineColor || fromData.getItemVisual(idx, 'color')
  64176. });
  64177. lineData.setItemLayout(idx, [
  64178. fromData.getItemLayout(idx),
  64179. toData.getItemLayout(idx)
  64180. ]);
  64181. lineData.setItemVisual(idx, {
  64182. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  64183. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  64184. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  64185. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  64186. });
  64187. });
  64188. lineDraw.updateData(lineData);
  64189. // Set host model for tooltip
  64190. // FIXME
  64191. mlData.line.eachItemGraphicEl(function (el, idx) {
  64192. el.traverse(function (child) {
  64193. child.dataModel = mlModel;
  64194. });
  64195. });
  64196. function updateDataVisualAndLayout(data, idx, isFrom) {
  64197. var itemModel = data.getItemModel(idx);
  64198. updateSingleMarkerEndLayout(
  64199. data, idx, isFrom, seriesModel, api
  64200. );
  64201. data.setItemVisual(idx, {
  64202. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  64203. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  64204. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  64205. });
  64206. }
  64207. lineDraw.__keep = true;
  64208. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  64209. }
  64210. });
  64211. /**
  64212. * @inner
  64213. * @param {module:echarts/coord/*} coordSys
  64214. * @param {module:echarts/model/Series} seriesModel
  64215. * @param {module:echarts/model/Model} mpModel
  64216. */
  64217. function createList$2(coordSys, seriesModel, mlModel) {
  64218. var coordDimsInfos;
  64219. if (coordSys) {
  64220. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  64221. var info = seriesModel.getData().getDimensionInfo(
  64222. seriesModel.getData().mapDimension(coordDim)
  64223. ) || {};
  64224. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  64225. return defaults({name: coordDim}, info);
  64226. });
  64227. }
  64228. else {
  64229. coordDimsInfos =[{
  64230. name: 'value',
  64231. type: 'float'
  64232. }];
  64233. }
  64234. var fromData = new List(coordDimsInfos, mlModel);
  64235. var toData = new List(coordDimsInfos, mlModel);
  64236. // No dimensions
  64237. var lineData = new List([], mlModel);
  64238. var optData = map(mlModel.get('data'), curry(
  64239. markLineTransform, seriesModel, coordSys, mlModel
  64240. ));
  64241. if (coordSys) {
  64242. optData = filter(
  64243. optData, curry(markLineFilter, coordSys)
  64244. );
  64245. }
  64246. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  64247. return item.value;
  64248. };
  64249. fromData.initData(
  64250. map(optData, function (item) { return item[0]; }),
  64251. null, dimValueGetter$$1
  64252. );
  64253. toData.initData(
  64254. map(optData, function (item) { return item[1]; }),
  64255. null, dimValueGetter$$1
  64256. );
  64257. lineData.initData(
  64258. map(optData, function (item) { return item[2]; })
  64259. );
  64260. lineData.hasItemOption = true;
  64261. return {
  64262. from: fromData,
  64263. to: toData,
  64264. line: lineData
  64265. };
  64266. }
  64267. registerPreprocessor(function (opt) {
  64268. // Make sure markLine component is enabled
  64269. opt.markLine = opt.markLine || {};
  64270. });
  64271. MarkerModel.extend({
  64272. type: 'markArea',
  64273. defaultOption: {
  64274. zlevel: 0,
  64275. // PENDING
  64276. z: 1,
  64277. tooltip: {
  64278. trigger: 'item'
  64279. },
  64280. // markArea should fixed on the coordinate system
  64281. animation: false,
  64282. label: {
  64283. show: true,
  64284. position: 'top'
  64285. },
  64286. itemStyle: {
  64287. // color and borderColor default to use color from series
  64288. // color: 'auto'
  64289. // borderColor: 'auto'
  64290. borderWidth: 0
  64291. },
  64292. emphasis: {
  64293. label: {
  64294. show: true,
  64295. position: 'top'
  64296. }
  64297. }
  64298. }
  64299. });
  64300. // TODO Better on polar
  64301. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  64302. var lt = dataTransform(seriesModel, item[0]);
  64303. var rb = dataTransform(seriesModel, item[1]);
  64304. var retrieve$$1 = retrieve;
  64305. // FIXME make sure lt is less than rb
  64306. var ltCoord = lt.coord;
  64307. var rbCoord = rb.coord;
  64308. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  64309. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  64310. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  64311. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  64312. // Merge option into one
  64313. var result = mergeAll([{}, lt, rb]);
  64314. result.coord = [
  64315. lt.coord, rb.coord
  64316. ];
  64317. result.x0 = lt.x;
  64318. result.y0 = lt.y;
  64319. result.x1 = rb.x;
  64320. result.y1 = rb.y;
  64321. return result;
  64322. };
  64323. function isInifinity$1(val) {
  64324. return !isNaN(val) && !isFinite(val);
  64325. }
  64326. // If a markArea has one dim
  64327. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  64328. var otherDimIndex = 1 - dimIndex;
  64329. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  64330. }
  64331. function markAreaFilter(coordSys, item) {
  64332. var fromCoord = item.coord[0];
  64333. var toCoord = item.coord[1];
  64334. if (coordSys.type === 'cartesian2d') {
  64335. // In case
  64336. // {
  64337. // markArea: {
  64338. // data: [{ yAxis: 2 }]
  64339. // }
  64340. // }
  64341. if (
  64342. fromCoord && toCoord &&
  64343. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  64344. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  64345. ) {
  64346. return true;
  64347. }
  64348. }
  64349. return dataFilter$1(coordSys, {
  64350. coord: fromCoord,
  64351. x: item.x0,
  64352. y: item.y0
  64353. })
  64354. || dataFilter$1(coordSys, {
  64355. coord: toCoord,
  64356. x: item.x1,
  64357. y: item.y1
  64358. });
  64359. }
  64360. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  64361. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  64362. var coordSys = seriesModel.coordinateSystem;
  64363. var itemModel = data.getItemModel(idx);
  64364. var point;
  64365. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  64366. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  64367. if (!isNaN(xPx) && !isNaN(yPx)) {
  64368. point = [xPx, yPx];
  64369. }
  64370. else {
  64371. // Chart like bar may have there own marker positioning logic
  64372. if (seriesModel.getMarkerPosition) {
  64373. // Use the getMarkerPoisition
  64374. point = seriesModel.getMarkerPosition(
  64375. data.getValues(dims, idx)
  64376. );
  64377. }
  64378. else {
  64379. var x = data.get(dims[0], idx);
  64380. var y = data.get(dims[1], idx);
  64381. var pt = [x, y];
  64382. coordSys.clampData && coordSys.clampData(pt, pt);
  64383. point = coordSys.dataToPoint(pt, true);
  64384. }
  64385. if (coordSys.type === 'cartesian2d') {
  64386. var xAxis = coordSys.getAxis('x');
  64387. var yAxis = coordSys.getAxis('y');
  64388. var x = data.get(dims[0], idx);
  64389. var y = data.get(dims[1], idx);
  64390. if (isInifinity$1(x)) {
  64391. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  64392. }
  64393. else if (isInifinity$1(y)) {
  64394. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  64395. }
  64396. }
  64397. // Use x, y if has any
  64398. if (!isNaN(xPx)) {
  64399. point[0] = xPx;
  64400. }
  64401. if (!isNaN(yPx)) {
  64402. point[1] = yPx;
  64403. }
  64404. }
  64405. return point;
  64406. }
  64407. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  64408. MarkerView.extend({
  64409. type: 'markArea',
  64410. // updateLayout: function (markAreaModel, ecModel, api) {
  64411. // ecModel.eachSeries(function (seriesModel) {
  64412. // var maModel = seriesModel.markAreaModel;
  64413. // if (maModel) {
  64414. // var areaData = maModel.getData();
  64415. // areaData.each(function (idx) {
  64416. // var points = zrUtil.map(dimPermutations, function (dim) {
  64417. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  64418. // });
  64419. // // Layout
  64420. // areaData.setItemLayout(idx, points);
  64421. // var el = areaData.getItemGraphicEl(idx);
  64422. // el.setShape('points', points);
  64423. // });
  64424. // }
  64425. // }, this);
  64426. // },
  64427. updateTransform: function (markAreaModel, ecModel, api) {
  64428. ecModel.eachSeries(function (seriesModel) {
  64429. var maModel = seriesModel.markAreaModel;
  64430. if (maModel) {
  64431. var areaData = maModel.getData();
  64432. areaData.each(function (idx) {
  64433. var points = map(dimPermutations, function (dim) {
  64434. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  64435. });
  64436. // Layout
  64437. areaData.setItemLayout(idx, points);
  64438. var el = areaData.getItemGraphicEl(idx);
  64439. el.setShape('points', points);
  64440. });
  64441. }
  64442. }, this);
  64443. },
  64444. renderSeries: function (seriesModel, maModel, ecModel, api) {
  64445. var coordSys = seriesModel.coordinateSystem;
  64446. var seriesName = seriesModel.name;
  64447. var seriesData = seriesModel.getData();
  64448. var areaGroupMap = this.markerGroupMap;
  64449. var polygonGroup = areaGroupMap.get(seriesName)
  64450. || areaGroupMap.set(seriesName, {group: new Group()});
  64451. this.group.add(polygonGroup.group);
  64452. polygonGroup.__keep = true;
  64453. var areaData = createList$3(coordSys, seriesModel, maModel);
  64454. // Line data for tooltip and formatter
  64455. maModel.setData(areaData);
  64456. // Update visual and layout of line
  64457. areaData.each(function (idx) {
  64458. // Layout
  64459. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  64460. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  64461. }));
  64462. // Visual
  64463. areaData.setItemVisual(idx, {
  64464. color: seriesData.getVisual('color')
  64465. });
  64466. });
  64467. areaData.diff(polygonGroup.__data)
  64468. .add(function (idx) {
  64469. var polygon = new Polygon({
  64470. shape: {
  64471. points: areaData.getItemLayout(idx)
  64472. }
  64473. });
  64474. areaData.setItemGraphicEl(idx, polygon);
  64475. polygonGroup.group.add(polygon);
  64476. })
  64477. .update(function (newIdx, oldIdx) {
  64478. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  64479. updateProps(polygon, {
  64480. shape: {
  64481. points: areaData.getItemLayout(newIdx)
  64482. }
  64483. }, maModel, newIdx);
  64484. polygonGroup.group.add(polygon);
  64485. areaData.setItemGraphicEl(newIdx, polygon);
  64486. })
  64487. .remove(function (idx) {
  64488. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  64489. polygonGroup.group.remove(polygon);
  64490. })
  64491. .execute();
  64492. areaData.eachItemGraphicEl(function (polygon, idx) {
  64493. var itemModel = areaData.getItemModel(idx);
  64494. var labelModel = itemModel.getModel('label');
  64495. var labelHoverModel = itemModel.getModel('emphasis.label');
  64496. var color = areaData.getItemVisual(idx, 'color');
  64497. polygon.useStyle(
  64498. defaults(
  64499. itemModel.getModel('itemStyle').getItemStyle(),
  64500. {
  64501. fill: modifyAlpha(color, 0.4),
  64502. stroke: color
  64503. }
  64504. )
  64505. );
  64506. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  64507. setLabelStyle(
  64508. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  64509. {
  64510. labelFetcher: maModel,
  64511. labelDataIndex: idx,
  64512. defaultText: areaData.getName(idx) || '',
  64513. isRectText: true,
  64514. autoColor: color
  64515. }
  64516. );
  64517. setHoverStyle(polygon, {});
  64518. polygon.dataModel = maModel;
  64519. });
  64520. polygonGroup.__data = areaData;
  64521. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  64522. }
  64523. });
  64524. /**
  64525. * @inner
  64526. * @param {module:echarts/coord/*} coordSys
  64527. * @param {module:echarts/model/Series} seriesModel
  64528. * @param {module:echarts/model/Model} mpModel
  64529. */
  64530. function createList$3(coordSys, seriesModel, maModel) {
  64531. var coordDimsInfos;
  64532. var areaData;
  64533. var dims = ['x0', 'y0', 'x1', 'y1'];
  64534. if (coordSys) {
  64535. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  64536. var data = seriesModel.getData();
  64537. var info = data.getDimensionInfo(
  64538. data.mapDimension(coordDim)
  64539. ) || {};
  64540. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  64541. return defaults({name: coordDim}, info);
  64542. });
  64543. areaData = new List(map(dims, function (dim, idx) {
  64544. return {
  64545. name: dim,
  64546. type: coordDimsInfos[idx % 2].type
  64547. };
  64548. }), maModel);
  64549. }
  64550. else {
  64551. coordDimsInfos =[{
  64552. name: 'value',
  64553. type: 'float'
  64554. }];
  64555. areaData = new List(coordDimsInfos, maModel);
  64556. }
  64557. var optData = map(maModel.get('data'), curry(
  64558. markAreaTransform, seriesModel, coordSys, maModel
  64559. ));
  64560. if (coordSys) {
  64561. optData = filter(
  64562. optData, curry(markAreaFilter, coordSys)
  64563. );
  64564. }
  64565. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  64566. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  64567. } : function (item) {
  64568. return item.value;
  64569. };
  64570. areaData.initData(optData, null, dimValueGetter$$1);
  64571. areaData.hasItemOption = true;
  64572. return areaData;
  64573. }
  64574. registerPreprocessor(function (opt) {
  64575. // Make sure markArea component is enabled
  64576. opt.markArea = opt.markArea || {};
  64577. });
  64578. var preprocessor$3 = function (option) {
  64579. var timelineOpt = option && option.timeline;
  64580. if (!isArray(timelineOpt)) {
  64581. timelineOpt = timelineOpt ? [timelineOpt] : [];
  64582. }
  64583. each$1(timelineOpt, function (opt) {
  64584. if (!opt) {
  64585. return;
  64586. }
  64587. compatibleEC2(opt);
  64588. });
  64589. };
  64590. function compatibleEC2(opt) {
  64591. var type = opt.type;
  64592. var ec2Types = {'number': 'value', 'time': 'time'};
  64593. // Compatible with ec2
  64594. if (ec2Types[type]) {
  64595. opt.axisType = ec2Types[type];
  64596. delete opt.type;
  64597. }
  64598. transferItem(opt);
  64599. if (has$2(opt, 'controlPosition')) {
  64600. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  64601. if (!has$2(controlStyle, 'position')) {
  64602. controlStyle.position = opt.controlPosition;
  64603. }
  64604. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  64605. controlStyle.show = false;
  64606. delete controlStyle.position;
  64607. }
  64608. delete opt.controlPosition;
  64609. }
  64610. each$1(opt.data || [], function (dataItem) {
  64611. if (isObject$1(dataItem) && !isArray(dataItem)) {
  64612. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  64613. // In ec2, using name as value.
  64614. dataItem.value = dataItem.name;
  64615. }
  64616. transferItem(dataItem);
  64617. }
  64618. });
  64619. }
  64620. function transferItem(opt) {
  64621. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  64622. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  64623. // Transfer label out
  64624. var label = opt.label || (opt.label || {});
  64625. var labelNormal = label.normal || (label.normal = {});
  64626. var excludeLabelAttr = {normal: 1, emphasis: 1};
  64627. each$1(label, function (value, name) {
  64628. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  64629. labelNormal[name] = value;
  64630. }
  64631. });
  64632. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  64633. label.emphasis = itemStyleEmphasis.label;
  64634. delete itemStyleEmphasis.label;
  64635. }
  64636. }
  64637. function has$2(obj, attr) {
  64638. return obj.hasOwnProperty(attr);
  64639. }
  64640. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  64641. // Only slider now.
  64642. return 'slider';
  64643. });
  64644. registerAction(
  64645. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  64646. function (payload, ecModel) {
  64647. var timelineModel = ecModel.getComponent('timeline');
  64648. if (timelineModel && payload.currentIndex != null) {
  64649. timelineModel.setCurrentIndex(payload.currentIndex);
  64650. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  64651. timelineModel.setPlayState(false);
  64652. }
  64653. }
  64654. // Set normalized currentIndex to payload.
  64655. ecModel.resetOption('timeline');
  64656. return defaults({
  64657. currentIndex: timelineModel.option.currentIndex
  64658. }, payload);
  64659. }
  64660. );
  64661. registerAction(
  64662. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  64663. function (payload, ecModel) {
  64664. var timelineModel = ecModel.getComponent('timeline');
  64665. if (timelineModel && payload.playState != null) {
  64666. timelineModel.setPlayState(payload.playState);
  64667. }
  64668. }
  64669. );
  64670. var TimelineModel = ComponentModel.extend({
  64671. type: 'timeline',
  64672. layoutMode: 'box',
  64673. /**
  64674. * @protected
  64675. */
  64676. defaultOption: {
  64677. zlevel: 0, // 一级层叠
  64678. z: 4, // 二级层叠
  64679. show: true,
  64680. axisType: 'time', // 模式是时间类型,支持 value, category
  64681. realtime: true,
  64682. left: '20%',
  64683. top: null,
  64684. right: '20%',
  64685. bottom: 0,
  64686. width: null,
  64687. height: 40,
  64688. padding: 5,
  64689. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  64690. autoPlay: false,
  64691. rewind: false, // 反向播放
  64692. loop: true,
  64693. playInterval: 2000, // 播放时间间隔,单位ms
  64694. currentIndex: 0,
  64695. itemStyle: {},
  64696. label: {
  64697. color: '#000'
  64698. },
  64699. data: []
  64700. },
  64701. /**
  64702. * @override
  64703. */
  64704. init: function (option, parentModel, ecModel) {
  64705. /**
  64706. * @private
  64707. * @type {module:echarts/data/List}
  64708. */
  64709. this._data;
  64710. /**
  64711. * @private
  64712. * @type {Array.<string>}
  64713. */
  64714. this._names;
  64715. this.mergeDefaultAndTheme(option, ecModel);
  64716. this._initData();
  64717. },
  64718. /**
  64719. * @override
  64720. */
  64721. mergeOption: function (option) {
  64722. TimelineModel.superApply(this, 'mergeOption', arguments);
  64723. this._initData();
  64724. },
  64725. /**
  64726. * @param {number} [currentIndex]
  64727. */
  64728. setCurrentIndex: function (currentIndex) {
  64729. if (currentIndex == null) {
  64730. currentIndex = this.option.currentIndex;
  64731. }
  64732. var count = this._data.count();
  64733. if (this.option.loop) {
  64734. currentIndex = (currentIndex % count + count) % count;
  64735. }
  64736. else {
  64737. currentIndex >= count && (currentIndex = count - 1);
  64738. currentIndex < 0 && (currentIndex = 0);
  64739. }
  64740. this.option.currentIndex = currentIndex;
  64741. },
  64742. /**
  64743. * @return {number} currentIndex
  64744. */
  64745. getCurrentIndex: function () {
  64746. return this.option.currentIndex;
  64747. },
  64748. /**
  64749. * @return {boolean}
  64750. */
  64751. isIndexMax: function () {
  64752. return this.getCurrentIndex() >= this._data.count() - 1;
  64753. },
  64754. /**
  64755. * @param {boolean} state true: play, false: stop
  64756. */
  64757. setPlayState: function (state) {
  64758. this.option.autoPlay = !!state;
  64759. },
  64760. /**
  64761. * @return {boolean} true: play, false: stop
  64762. */
  64763. getPlayState: function () {
  64764. return !!this.option.autoPlay;
  64765. },
  64766. /**
  64767. * @private
  64768. */
  64769. _initData: function () {
  64770. var thisOption = this.option;
  64771. var dataArr = thisOption.data || [];
  64772. var axisType = thisOption.axisType;
  64773. var names = this._names = [];
  64774. if (axisType === 'category') {
  64775. var idxArr = [];
  64776. each$1(dataArr, function (item, index) {
  64777. var value = getDataItemValue(item);
  64778. var newItem;
  64779. if (isObject$1(item)) {
  64780. newItem = clone(item);
  64781. newItem.value = index;
  64782. }
  64783. else {
  64784. newItem = index;
  64785. }
  64786. idxArr.push(newItem);
  64787. if (!isString(value) && (value == null || isNaN(value))) {
  64788. value = '';
  64789. }
  64790. names.push(value + '');
  64791. });
  64792. dataArr = idxArr;
  64793. }
  64794. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  64795. var data = this._data = new List([{name: 'value', type: dimType}], this);
  64796. data.initData(dataArr, names);
  64797. },
  64798. getData: function () {
  64799. return this._data;
  64800. },
  64801. /**
  64802. * @public
  64803. * @return {Array.<string>} categoreis
  64804. */
  64805. getCategories: function () {
  64806. if (this.get('axisType') === 'category') {
  64807. return this._names.slice();
  64808. }
  64809. }
  64810. });
  64811. var SliderTimelineModel = TimelineModel.extend({
  64812. type: 'timeline.slider',
  64813. /**
  64814. * @protected
  64815. */
  64816. defaultOption: {
  64817. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  64818. borderColor: '#ccc', // 时间轴边框颜色
  64819. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  64820. orient: 'horizontal', // 'vertical'
  64821. inverse: false,
  64822. tooltip: { // boolean or Object
  64823. trigger: 'item' // data item may also have tootip attr.
  64824. },
  64825. symbol: 'emptyCircle',
  64826. symbolSize: 10,
  64827. lineStyle: {
  64828. show: true,
  64829. width: 2,
  64830. color: '#304654'
  64831. },
  64832. label: { // 文本标签
  64833. position: 'auto', // auto left right top bottom
  64834. // When using number, label position is not
  64835. // restricted by viewRect.
  64836. // positive: right/bottom, negative: left/top
  64837. show: true,
  64838. interval: 'auto',
  64839. rotate: 0,
  64840. // formatter: null,
  64841. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  64842. color: '#304654'
  64843. },
  64844. itemStyle: {
  64845. color: '#304654',
  64846. borderWidth: 1
  64847. },
  64848. checkpointStyle: {
  64849. symbol: 'circle',
  64850. symbolSize: 13,
  64851. color: '#c23531',
  64852. borderWidth: 5,
  64853. borderColor: 'rgba(194,53,49, 0.5)',
  64854. animation: true,
  64855. animationDuration: 300,
  64856. animationEasing: 'quinticInOut'
  64857. },
  64858. controlStyle: {
  64859. show: true,
  64860. showPlayBtn: true,
  64861. showPrevBtn: true,
  64862. showNextBtn: true,
  64863. itemSize: 22,
  64864. itemGap: 12,
  64865. position: 'left', // 'left' 'right' 'top' 'bottom'
  64866. playIcon: 'path://M31.6,53C17.5,53,6,41.5,6,27.4S17.5,1.8,31.6,1.8C45.7,1.8,57.2,13.3,57.2,27.4S45.7,53,31.6,53z M31.6,3.3 C18.4,3.3,7.5,14.1,7.5,27.4c0,13.3,10.8,24.1,24.1,24.1C44.9,51.5,55.7,40.7,55.7,27.4C55.7,14.1,44.9,3.3,31.6,3.3z M24.9,21.3 c0-2.2,1.6-3.1,3.5-2l10.5,6.1c1.899,1.1,1.899,2.9,0,4l-10.5,6.1c-1.9,1.1-3.5,0.2-3.5-2V21.3z', // jshint ignore:line
  64867. stopIcon: 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z', // jshint ignore:line
  64868. nextIcon: 'path://M18.6,50.8l22.5-22.5c0.2-0.2,0.3-0.4,0.3-0.7c0-0.3-0.1-0.5-0.3-0.7L18.7,4.4c-0.1-0.1-0.2-0.3-0.2-0.5 c0-0.4,0.3-0.8,0.8-0.8c0.2,0,0.5,0.1,0.6,0.3l23.5,23.5l0,0c0.2,0.2,0.3,0.4,0.3,0.7c0,0.3-0.1,0.5-0.3,0.7l-0.1,0.1L19.7,52 c-0.1,0.1-0.3,0.2-0.5,0.2c-0.4,0-0.8-0.3-0.8-0.8C18.4,51.2,18.5,51,18.6,50.8z', // jshint ignore:line
  64869. prevIcon: 'path://M43,52.8L20.4,30.3c-0.2-0.2-0.3-0.4-0.3-0.7c0-0.3,0.1-0.5,0.3-0.7L42.9,6.4c0.1-0.1,0.2-0.3,0.2-0.5 c0-0.4-0.3-0.8-0.8-0.8c-0.2,0-0.5,0.1-0.6,0.3L18.3,28.8l0,0c-0.2,0.2-0.3,0.4-0.3,0.7c0,0.3,0.1,0.5,0.3,0.7l0.1,0.1L41.9,54 c0.1,0.1,0.3,0.2,0.5,0.2c0.4,0,0.8-0.3,0.8-0.8C43.2,53.2,43.1,53,43,52.8z', // jshint ignore:line
  64870. color: '#304654',
  64871. borderColor: '#304654',
  64872. borderWidth: 1
  64873. },
  64874. emphasis: {
  64875. label: {
  64876. show: true,
  64877. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  64878. color: '#c23531'
  64879. },
  64880. itemStyle: {
  64881. color: '#c23531'
  64882. },
  64883. controlStyle: {
  64884. color: '#c23531',
  64885. borderColor: '#c23531',
  64886. borderWidth: 2
  64887. }
  64888. },
  64889. data: []
  64890. }
  64891. });
  64892. mixin(SliderTimelineModel, dataFormatMixin);
  64893. var TimelineView = Component.extend({
  64894. type: 'timeline'
  64895. });
  64896. /**
  64897. * Extend axis 2d
  64898. * @constructor module:echarts/coord/cartesian/Axis2D
  64899. * @extends {module:echarts/coord/cartesian/Axis}
  64900. * @param {string} dim
  64901. * @param {*} scale
  64902. * @param {Array.<number>} coordExtent
  64903. * @param {string} axisType
  64904. * @param {string} position
  64905. */
  64906. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  64907. Axis.call(this, dim, scale, coordExtent);
  64908. /**
  64909. * Axis type
  64910. * - 'category'
  64911. * - 'value'
  64912. * - 'time'
  64913. * - 'log'
  64914. * @type {string}
  64915. */
  64916. this.type = axisType || 'value';
  64917. /**
  64918. * @private
  64919. * @type {number}
  64920. */
  64921. this._autoLabelInterval;
  64922. /**
  64923. * Axis model
  64924. * @param {module:echarts/component/TimelineModel}
  64925. */
  64926. this.model = null;
  64927. };
  64928. TimelineAxis.prototype = {
  64929. constructor: TimelineAxis,
  64930. /**
  64931. * @public
  64932. * @return {number}
  64933. */
  64934. getLabelInterval: function () {
  64935. var timelineModel = this.model;
  64936. var labelModel = timelineModel.getModel('label');
  64937. var labelInterval = labelModel.get('interval');
  64938. if (labelInterval != null && labelInterval != 'auto') {
  64939. return labelInterval;
  64940. }
  64941. var labelInterval = this._autoLabelInterval;
  64942. if (!labelInterval) {
  64943. labelInterval = this._autoLabelInterval = getAxisLabelInterval(
  64944. map(this.scale.getTicks(), this.dataToCoord, this),
  64945. getFormattedLabels(this, labelModel.get('formatter')),
  64946. labelModel.getFont(),
  64947. timelineModel.get('orient') === 'horizontal' ? 0 : 90,
  64948. labelModel.get('rotate')
  64949. );
  64950. }
  64951. return labelInterval;
  64952. },
  64953. /**
  64954. * If label is ignored.
  64955. * Automatically used when axis is category and label can not be all shown
  64956. * @public
  64957. * @param {number} idx
  64958. * @return {boolean}
  64959. */
  64960. isLabelIgnored: function (idx) {
  64961. if (this.type === 'category') {
  64962. var labelInterval = this.getLabelInterval();
  64963. return ((typeof labelInterval === 'function')
  64964. && !labelInterval(idx, this.scale.getLabel(idx)))
  64965. || idx % (labelInterval + 1);
  64966. }
  64967. }
  64968. };
  64969. inherits(TimelineAxis, Axis);
  64970. var bind$6 = bind;
  64971. var each$28 = each$1;
  64972. var PI$4 = Math.PI;
  64973. TimelineView.extend({
  64974. type: 'timeline.slider',
  64975. init: function (ecModel, api) {
  64976. this.api = api;
  64977. /**
  64978. * @private
  64979. * @type {module:echarts/component/timeline/TimelineAxis}
  64980. */
  64981. this._axis;
  64982. /**
  64983. * @private
  64984. * @type {module:zrender/core/BoundingRect}
  64985. */
  64986. this._viewRect;
  64987. /**
  64988. * @type {number}
  64989. */
  64990. this._timer;
  64991. /**
  64992. * @type {module:zrender/Element}
  64993. */
  64994. this._currentPointer;
  64995. /**
  64996. * @type {module:zrender/container/Group}
  64997. */
  64998. this._mainGroup;
  64999. /**
  65000. * @type {module:zrender/container/Group}
  65001. */
  65002. this._labelGroup;
  65003. },
  65004. /**
  65005. * @override
  65006. */
  65007. render: function (timelineModel, ecModel, api, payload) {
  65008. this.model = timelineModel;
  65009. this.api = api;
  65010. this.ecModel = ecModel;
  65011. this.group.removeAll();
  65012. if (timelineModel.get('show', true)) {
  65013. var layoutInfo = this._layout(timelineModel, api);
  65014. var mainGroup = this._createGroup('mainGroup');
  65015. var labelGroup = this._createGroup('labelGroup');
  65016. /**
  65017. * @private
  65018. * @type {module:echarts/component/timeline/TimelineAxis}
  65019. */
  65020. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  65021. timelineModel.formatTooltip = function (dataIndex) {
  65022. return encodeHTML(axis.scale.getLabel(dataIndex));
  65023. };
  65024. each$28(
  65025. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  65026. function (name) {
  65027. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  65028. },
  65029. this
  65030. );
  65031. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  65032. this._position(layoutInfo, timelineModel);
  65033. }
  65034. this._doPlayStop();
  65035. },
  65036. /**
  65037. * @override
  65038. */
  65039. remove: function () {
  65040. this._clearTimer();
  65041. this.group.removeAll();
  65042. },
  65043. /**
  65044. * @override
  65045. */
  65046. dispose: function () {
  65047. this._clearTimer();
  65048. },
  65049. _layout: function (timelineModel, api) {
  65050. var labelPosOpt = timelineModel.get('label.position');
  65051. var orient = timelineModel.get('orient');
  65052. var viewRect = getViewRect$4(timelineModel, api);
  65053. // Auto label offset.
  65054. if (labelPosOpt == null || labelPosOpt === 'auto') {
  65055. labelPosOpt = orient === 'horizontal'
  65056. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  65057. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  65058. }
  65059. else if (isNaN(labelPosOpt)) {
  65060. labelPosOpt = ({
  65061. horizontal: {top: '-', bottom: '+'},
  65062. vertical: {left: '-', right: '+'}
  65063. })[orient][labelPosOpt];
  65064. }
  65065. var labelAlignMap = {
  65066. horizontal: 'center',
  65067. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  65068. };
  65069. var labelBaselineMap = {
  65070. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  65071. vertical: 'middle'
  65072. };
  65073. var rotationMap = {
  65074. horizontal: 0,
  65075. vertical: PI$4 / 2
  65076. };
  65077. // Position
  65078. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  65079. var controlModel = timelineModel.getModel('controlStyle');
  65080. var showControl = controlModel.get('show', true);
  65081. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  65082. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  65083. var sizePlusGap = controlSize + controlGap;
  65084. // Special label rotate.
  65085. var labelRotation = timelineModel.get('label.rotate') || 0;
  65086. labelRotation = labelRotation * PI$4 / 180; // To radian.
  65087. var playPosition;
  65088. var prevBtnPosition;
  65089. var nextBtnPosition;
  65090. var axisExtent;
  65091. var controlPosition = controlModel.get('position', true);
  65092. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  65093. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  65094. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  65095. var xLeft = 0;
  65096. var xRight = mainLength;
  65097. // position[0] means left, position[1] means middle.
  65098. if (controlPosition === 'left' || controlPosition === 'bottom') {
  65099. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  65100. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  65101. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  65102. }
  65103. else { // 'top' 'right'
  65104. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  65105. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  65106. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  65107. }
  65108. axisExtent = [xLeft, xRight];
  65109. if (timelineModel.get('inverse')) {
  65110. axisExtent.reverse();
  65111. }
  65112. return {
  65113. viewRect: viewRect,
  65114. mainLength: mainLength,
  65115. orient: orient,
  65116. rotation: rotationMap[orient],
  65117. labelRotation: labelRotation,
  65118. labelPosOpt: labelPosOpt,
  65119. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  65120. labelBaseline: timelineModel.get('label.verticalAlign')
  65121. || timelineModel.get('label.baseline')
  65122. || labelBaselineMap[orient],
  65123. // Based on mainGroup.
  65124. playPosition: playPosition,
  65125. prevBtnPosition: prevBtnPosition,
  65126. nextBtnPosition: nextBtnPosition,
  65127. axisExtent: axisExtent,
  65128. controlSize: controlSize,
  65129. controlGap: controlGap
  65130. };
  65131. },
  65132. _position: function (layoutInfo, timelineModel) {
  65133. // Position is be called finally, because bounding rect is needed for
  65134. // adapt content to fill viewRect (auto adapt offset).
  65135. // Timeline may be not all in the viewRect when 'offset' is specified
  65136. // as a number, because it is more appropriate that label aligns at
  65137. // 'offset' but not the other edge defined by viewRect.
  65138. var mainGroup = this._mainGroup;
  65139. var labelGroup = this._labelGroup;
  65140. var viewRect = layoutInfo.viewRect;
  65141. if (layoutInfo.orient === 'vertical') {
  65142. // transform to horizontal, inverse rotate by left-top point.
  65143. var m = create$1();
  65144. var rotateOriginX = viewRect.x;
  65145. var rotateOriginY = viewRect.y + viewRect.height;
  65146. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  65147. rotate(m, m, -PI$4 / 2);
  65148. translate(m, m, [rotateOriginX, rotateOriginY]);
  65149. viewRect = viewRect.clone();
  65150. viewRect.applyTransform(m);
  65151. }
  65152. var viewBound = getBound(viewRect);
  65153. var mainBound = getBound(mainGroup.getBoundingRect());
  65154. var labelBound = getBound(labelGroup.getBoundingRect());
  65155. var mainPosition = mainGroup.position;
  65156. var labelsPosition = labelGroup.position;
  65157. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  65158. var labelPosOpt = layoutInfo.labelPosOpt;
  65159. if (isNaN(labelPosOpt)) { // '+' or '-'
  65160. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  65161. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  65162. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  65163. }
  65164. else {
  65165. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  65166. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  65167. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  65168. }
  65169. mainGroup.attr('position', mainPosition);
  65170. labelGroup.attr('position', labelsPosition);
  65171. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  65172. setOrigin(mainGroup);
  65173. setOrigin(labelGroup);
  65174. function setOrigin(targetGroup) {
  65175. var pos = targetGroup.position;
  65176. targetGroup.origin = [
  65177. viewBound[0][0] - pos[0],
  65178. viewBound[1][0] - pos[1]
  65179. ];
  65180. }
  65181. function getBound(rect) {
  65182. // [[xmin, xmax], [ymin, ymax]]
  65183. return [
  65184. [rect.x, rect.x + rect.width],
  65185. [rect.y, rect.y + rect.height]
  65186. ];
  65187. }
  65188. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  65189. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  65190. }
  65191. },
  65192. _createAxis: function (layoutInfo, timelineModel) {
  65193. var data = timelineModel.getData();
  65194. var axisType = timelineModel.get('axisType');
  65195. var scale = createScaleByModel(timelineModel, axisType);
  65196. var dataExtent = data.getDataExtent('value');
  65197. scale.setExtent(dataExtent[0], dataExtent[1]);
  65198. this._customizeScale(scale, data);
  65199. scale.niceTicks();
  65200. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  65201. axis.model = timelineModel;
  65202. return axis;
  65203. },
  65204. _customizeScale: function (scale, data) {
  65205. scale.getTicks = function () {
  65206. return data.mapArray(['value'], function (value) {
  65207. return value;
  65208. });
  65209. };
  65210. scale.getTicksLabels = function () {
  65211. return map(this.getTicks(), scale.getLabel, scale);
  65212. };
  65213. },
  65214. _createGroup: function (name) {
  65215. var newGroup = this['_' + name] = new Group();
  65216. this.group.add(newGroup);
  65217. return newGroup;
  65218. },
  65219. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  65220. var axisExtent = axis.getExtent();
  65221. if (!timelineModel.get('lineStyle.show')) {
  65222. return;
  65223. }
  65224. group.add(new Line({
  65225. shape: {
  65226. x1: axisExtent[0], y1: 0,
  65227. x2: axisExtent[1], y2: 0
  65228. },
  65229. style: extend(
  65230. {lineCap: 'round'},
  65231. timelineModel.getModel('lineStyle').getLineStyle()
  65232. ),
  65233. silent: true,
  65234. z2: 1
  65235. }));
  65236. },
  65237. /**
  65238. * @private
  65239. */
  65240. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  65241. var data = timelineModel.getData();
  65242. var ticks = axis.scale.getTicks();
  65243. each$28(ticks, function (value, dataIndex) {
  65244. var tickCoord = axis.dataToCoord(value);
  65245. var itemModel = data.getItemModel(dataIndex);
  65246. var itemStyleModel = itemModel.getModel('itemStyle');
  65247. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  65248. var symbolOpt = {
  65249. position: [tickCoord, 0],
  65250. onclick: bind$6(this._changeTimeline, this, dataIndex)
  65251. };
  65252. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  65253. setHoverStyle(el, hoverStyleModel.getItemStyle());
  65254. if (itemModel.get('tooltip')) {
  65255. el.dataIndex = dataIndex;
  65256. el.dataModel = timelineModel;
  65257. }
  65258. else {
  65259. el.dataIndex = el.dataModel = null;
  65260. }
  65261. }, this);
  65262. },
  65263. /**
  65264. * @private
  65265. */
  65266. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  65267. var labelModel = timelineModel.getModel('label');
  65268. if (!labelModel.get('show')) {
  65269. return;
  65270. }
  65271. var data = timelineModel.getData();
  65272. var ticks = axis.scale.getTicks();
  65273. var labels = getFormattedLabels(
  65274. axis, labelModel.get('formatter')
  65275. );
  65276. var labelInterval = axis.getLabelInterval();
  65277. each$28(ticks, function (tick, dataIndex) {
  65278. if (axis.isLabelIgnored(dataIndex, labelInterval)) {
  65279. return;
  65280. }
  65281. var itemModel = data.getItemModel(dataIndex);
  65282. var normalLabelModel = itemModel.getModel('label');
  65283. var hoverLabelModel = itemModel.getModel('emphasis.label');
  65284. var tickCoord = axis.dataToCoord(tick);
  65285. var textEl = new Text({
  65286. position: [tickCoord, 0],
  65287. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  65288. onclick: bind$6(this._changeTimeline, this, dataIndex),
  65289. silent: false
  65290. });
  65291. setTextStyle(textEl.style, normalLabelModel, {
  65292. text: labels[dataIndex],
  65293. textAlign: layoutInfo.labelAlign,
  65294. textVerticalAlign: layoutInfo.labelBaseline
  65295. });
  65296. group.add(textEl);
  65297. setHoverStyle(
  65298. textEl, setTextStyle({}, hoverLabelModel)
  65299. );
  65300. }, this);
  65301. },
  65302. /**
  65303. * @private
  65304. */
  65305. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  65306. var controlSize = layoutInfo.controlSize;
  65307. var rotation = layoutInfo.rotation;
  65308. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  65309. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  65310. var rect = [0, -controlSize / 2, controlSize, controlSize];
  65311. var playState = timelineModel.getPlayState();
  65312. var inverse = timelineModel.get('inverse', true);
  65313. makeBtn(
  65314. layoutInfo.nextBtnPosition,
  65315. 'controlStyle.nextIcon',
  65316. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  65317. );
  65318. makeBtn(
  65319. layoutInfo.prevBtnPosition,
  65320. 'controlStyle.prevIcon',
  65321. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  65322. );
  65323. makeBtn(
  65324. layoutInfo.playPosition,
  65325. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  65326. bind$6(this._handlePlayClick, this, !playState),
  65327. true
  65328. );
  65329. function makeBtn(position, iconPath, onclick, willRotate) {
  65330. if (!position) {
  65331. return;
  65332. }
  65333. var opt = {
  65334. position: position,
  65335. origin: [controlSize / 2, 0],
  65336. rotation: willRotate ? -rotation : 0,
  65337. rectHover: true,
  65338. style: itemStyle,
  65339. onclick: onclick
  65340. };
  65341. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  65342. group.add(btn);
  65343. setHoverStyle(btn, hoverStyle);
  65344. }
  65345. },
  65346. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  65347. var data = timelineModel.getData();
  65348. var currentIndex = timelineModel.getCurrentIndex();
  65349. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  65350. var me = this;
  65351. var callback = {
  65352. onCreate: function (pointer) {
  65353. pointer.draggable = true;
  65354. pointer.drift = bind$6(me._handlePointerDrag, me);
  65355. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  65356. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  65357. },
  65358. onUpdate: function (pointer) {
  65359. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  65360. }
  65361. };
  65362. // Reuse when exists, for animation and drag.
  65363. this._currentPointer = giveSymbol(
  65364. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  65365. );
  65366. },
  65367. _handlePlayClick: function (nextState) {
  65368. this._clearTimer();
  65369. this.api.dispatchAction({
  65370. type: 'timelinePlayChange',
  65371. playState: nextState,
  65372. from: this.uid
  65373. });
  65374. },
  65375. _handlePointerDrag: function (dx, dy, e) {
  65376. this._clearTimer();
  65377. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  65378. },
  65379. _handlePointerDragend: function (e) {
  65380. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  65381. },
  65382. _pointerChangeTimeline: function (mousePos, trigger) {
  65383. var toCoord = this._toAxisCoord(mousePos)[0];
  65384. var axis = this._axis;
  65385. var axisExtent = asc(axis.getExtent().slice());
  65386. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  65387. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  65388. this._currentPointer.position[0] = toCoord;
  65389. this._currentPointer.dirty();
  65390. var targetDataIndex = this._findNearestTick(toCoord);
  65391. var timelineModel = this.model;
  65392. if (trigger || (
  65393. targetDataIndex !== timelineModel.getCurrentIndex()
  65394. && timelineModel.get('realtime')
  65395. )) {
  65396. this._changeTimeline(targetDataIndex);
  65397. }
  65398. },
  65399. _doPlayStop: function () {
  65400. this._clearTimer();
  65401. if (this.model.getPlayState()) {
  65402. this._timer = setTimeout(
  65403. bind$6(handleFrame, this),
  65404. this.model.get('playInterval')
  65405. );
  65406. }
  65407. function handleFrame() {
  65408. // Do not cache
  65409. var timelineModel = this.model;
  65410. this._changeTimeline(
  65411. timelineModel.getCurrentIndex()
  65412. + (timelineModel.get('rewind', true) ? -1 : 1)
  65413. );
  65414. }
  65415. },
  65416. _toAxisCoord: function (vertex) {
  65417. var trans = this._mainGroup.getLocalTransform();
  65418. return applyTransform$1(vertex, trans, true);
  65419. },
  65420. _findNearestTick: function (axisCoord) {
  65421. var data = this.model.getData();
  65422. var dist = Infinity;
  65423. var targetDataIndex;
  65424. var axis = this._axis;
  65425. data.each(['value'], function (value, dataIndex) {
  65426. var coord = axis.dataToCoord(value);
  65427. var d = Math.abs(coord - axisCoord);
  65428. if (d < dist) {
  65429. dist = d;
  65430. targetDataIndex = dataIndex;
  65431. }
  65432. });
  65433. return targetDataIndex;
  65434. },
  65435. _clearTimer: function () {
  65436. if (this._timer) {
  65437. clearTimeout(this._timer);
  65438. this._timer = null;
  65439. }
  65440. },
  65441. _changeTimeline: function (nextIndex) {
  65442. var currentIndex = this.model.getCurrentIndex();
  65443. if (nextIndex === '+') {
  65444. nextIndex = currentIndex + 1;
  65445. }
  65446. else if (nextIndex === '-') {
  65447. nextIndex = currentIndex - 1;
  65448. }
  65449. this.api.dispatchAction({
  65450. type: 'timelineChange',
  65451. currentIndex: nextIndex,
  65452. from: this.uid
  65453. });
  65454. }
  65455. });
  65456. function getViewRect$4(model, api) {
  65457. return getLayoutRect(
  65458. model.getBoxLayoutParams(),
  65459. {
  65460. width: api.getWidth(),
  65461. height: api.getHeight()
  65462. },
  65463. model.get('padding')
  65464. );
  65465. }
  65466. function makeIcon(timelineModel, objPath, rect, opts) {
  65467. var icon = makePath(
  65468. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  65469. clone(opts || {}),
  65470. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  65471. 'center'
  65472. );
  65473. return icon;
  65474. }
  65475. /**
  65476. * Create symbol or update symbol
  65477. * opt: basic position and event handlers
  65478. */
  65479. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  65480. var color = itemStyleModel.get('color');
  65481. if (!symbol) {
  65482. var symbolType = hostModel.get('symbol');
  65483. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  65484. symbol.setStyle('strokeNoScale', true);
  65485. group.add(symbol);
  65486. callback && callback.onCreate(symbol);
  65487. }
  65488. else {
  65489. symbol.setColor(color);
  65490. group.add(symbol); // Group may be new, also need to add.
  65491. callback && callback.onUpdate(symbol);
  65492. }
  65493. // Style
  65494. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  65495. symbol.setStyle(itemStyle);
  65496. // Transform and events.
  65497. opt = merge({
  65498. rectHover: true,
  65499. z2: 100
  65500. }, opt, true);
  65501. var symbolSize = hostModel.get('symbolSize');
  65502. symbolSize = symbolSize instanceof Array
  65503. ? symbolSize.slice()
  65504. : [+symbolSize, +symbolSize];
  65505. symbolSize[0] /= 2;
  65506. symbolSize[1] /= 2;
  65507. opt.scale = symbolSize;
  65508. var symbolOffset = hostModel.get('symbolOffset');
  65509. if (symbolOffset) {
  65510. var pos = opt.position = opt.position || [0, 0];
  65511. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  65512. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  65513. }
  65514. var symbolRotate = hostModel.get('symbolRotate');
  65515. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  65516. symbol.attr(opt);
  65517. // FIXME
  65518. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  65519. // getBoundingRect will return wrong result.
  65520. // (This is supposed to be resolved in zrender, but it is a little difficult to
  65521. // leverage performance and auto updateTransform)
  65522. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  65523. symbol.updateTransform();
  65524. return symbol;
  65525. }
  65526. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  65527. if (pointer.dragging) {
  65528. return;
  65529. }
  65530. var pointerModel = timelineModel.getModel('checkpointStyle');
  65531. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  65532. if (noAnimation || !pointerModel.get('animation', true)) {
  65533. pointer.attr({position: [toCoord, 0]});
  65534. }
  65535. else {
  65536. pointer.stopAnimation(true);
  65537. pointer.animateTo(
  65538. {position: [toCoord, 0]},
  65539. pointerModel.get('animationDuration', true),
  65540. pointerModel.get('animationEasing', true)
  65541. );
  65542. }
  65543. }
  65544. /**
  65545. * DataZoom component entry
  65546. */
  65547. registerPreprocessor(preprocessor$3);
  65548. var ToolboxModel = extendComponentModel({
  65549. type: 'toolbox',
  65550. layoutMode: {
  65551. type: 'box',
  65552. ignoreSize: true
  65553. },
  65554. mergeDefaultAndTheme: function (option) {
  65555. ToolboxModel.superApply(this, 'mergeDefaultAndTheme', arguments);
  65556. each$1(this.option.feature, function (featureOpt, featureName) {
  65557. var Feature = get$1(featureName);
  65558. Feature && merge(featureOpt, Feature.defaultOption);
  65559. });
  65560. },
  65561. defaultOption: {
  65562. show: true,
  65563. z: 6,
  65564. zlevel: 0,
  65565. orient: 'horizontal',
  65566. left: 'right',
  65567. top: 'top',
  65568. // right
  65569. // bottom
  65570. backgroundColor: 'transparent',
  65571. borderColor: '#ccc',
  65572. borderRadius: 0,
  65573. borderWidth: 0,
  65574. padding: 5,
  65575. itemSize: 15,
  65576. itemGap: 8,
  65577. showTitle: true,
  65578. iconStyle: {
  65579. borderColor: '#666',
  65580. color: 'none'
  65581. },
  65582. emphasis: {
  65583. iconStyle: {
  65584. borderColor: '#3E98C5'
  65585. }
  65586. }
  65587. // textStyle: {},
  65588. // feature
  65589. }
  65590. });
  65591. extendComponentView({
  65592. type: 'toolbox',
  65593. render: function (toolboxModel, ecModel, api, payload) {
  65594. var group = this.group;
  65595. group.removeAll();
  65596. if (!toolboxModel.get('show')) {
  65597. return;
  65598. }
  65599. var itemSize = +toolboxModel.get('itemSize');
  65600. var featureOpts = toolboxModel.get('feature') || {};
  65601. var features = this._features || (this._features = {});
  65602. var featureNames = [];
  65603. each$1(featureOpts, function (opt, name) {
  65604. featureNames.push(name);
  65605. });
  65606. (new DataDiffer(this._featureNames || [], featureNames))
  65607. .add(processFeature)
  65608. .update(processFeature)
  65609. .remove(curry(processFeature, null))
  65610. .execute();
  65611. // Keep for diff.
  65612. this._featureNames = featureNames;
  65613. function processFeature(newIndex, oldIndex) {
  65614. var featureName = featureNames[newIndex];
  65615. var oldName = featureNames[oldIndex];
  65616. var featureOpt = featureOpts[featureName];
  65617. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  65618. var feature;
  65619. if (featureName && !oldName) { // Create
  65620. if (isUserFeatureName(featureName)) {
  65621. feature = {
  65622. model: featureModel,
  65623. onclick: featureModel.option.onclick,
  65624. featureName: featureName
  65625. };
  65626. }
  65627. else {
  65628. var Feature = get$1(featureName);
  65629. if (!Feature) {
  65630. return;
  65631. }
  65632. feature = new Feature(featureModel, ecModel, api);
  65633. }
  65634. features[featureName] = feature;
  65635. }
  65636. else {
  65637. feature = features[oldName];
  65638. // If feature does not exsit.
  65639. if (!feature) {
  65640. return;
  65641. }
  65642. feature.model = featureModel;
  65643. feature.ecModel = ecModel;
  65644. feature.api = api;
  65645. }
  65646. if (!featureName && oldName) {
  65647. feature.dispose && feature.dispose(ecModel, api);
  65648. return;
  65649. }
  65650. if (!featureModel.get('show') || feature.unusable) {
  65651. feature.remove && feature.remove(ecModel, api);
  65652. return;
  65653. }
  65654. createIconPaths(featureModel, feature, featureName);
  65655. featureModel.setIconStatus = function (iconName, status) {
  65656. var option = this.option;
  65657. var iconPaths = this.iconPaths;
  65658. option.iconStatus = option.iconStatus || {};
  65659. option.iconStatus[iconName] = status;
  65660. // FIXME
  65661. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  65662. };
  65663. if (feature.render) {
  65664. feature.render(featureModel, ecModel, api, payload);
  65665. }
  65666. }
  65667. function createIconPaths(featureModel, feature, featureName) {
  65668. var iconStyleModel = featureModel.getModel('iconStyle');
  65669. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  65670. // If one feature has mutiple icon. they are orginaized as
  65671. // {
  65672. // icon: {
  65673. // foo: '',
  65674. // bar: ''
  65675. // },
  65676. // title: {
  65677. // foo: '',
  65678. // bar: ''
  65679. // }
  65680. // }
  65681. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  65682. var titles = featureModel.get('title') || {};
  65683. if (typeof icons === 'string') {
  65684. var icon = icons;
  65685. var title = titles;
  65686. icons = {};
  65687. titles = {};
  65688. icons[featureName] = icon;
  65689. titles[featureName] = title;
  65690. }
  65691. var iconPaths = featureModel.iconPaths = {};
  65692. each$1(icons, function (iconStr, iconName) {
  65693. var path = createIcon(
  65694. iconStr,
  65695. {},
  65696. {
  65697. x: -itemSize / 2,
  65698. y: -itemSize / 2,
  65699. width: itemSize,
  65700. height: itemSize
  65701. }
  65702. );
  65703. path.setStyle(iconStyleModel.getItemStyle());
  65704. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  65705. setHoverStyle(path);
  65706. if (toolboxModel.get('showTitle')) {
  65707. path.__title = titles[iconName];
  65708. path.on('mouseover', function () {
  65709. // Should not reuse above hoverStyle, which might be modified.
  65710. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  65711. path.setStyle({
  65712. text: titles[iconName],
  65713. textPosition: hoverStyle.textPosition || 'bottom',
  65714. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  65715. textAlign: hoverStyle.textAlign || 'center'
  65716. });
  65717. })
  65718. .on('mouseout', function () {
  65719. path.setStyle({
  65720. textFill: null
  65721. });
  65722. });
  65723. }
  65724. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  65725. group.add(path);
  65726. path.on('click', bind(
  65727. feature.onclick, feature, ecModel, api, iconName
  65728. ));
  65729. iconPaths[iconName] = path;
  65730. });
  65731. }
  65732. layout$3(group, toolboxModel, api);
  65733. // Render background after group is layout
  65734. // FIXME
  65735. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  65736. // Adjust icon title positions to avoid them out of screen
  65737. group.eachChild(function (icon) {
  65738. var titleText = icon.__title;
  65739. var hoverStyle = icon.hoverStyle;
  65740. // May be background element
  65741. if (hoverStyle && titleText) {
  65742. var rect = getBoundingRect(
  65743. titleText, makeFont(hoverStyle)
  65744. );
  65745. var offsetX = icon.position[0] + group.position[0];
  65746. var offsetY = icon.position[1] + group.position[1] + itemSize;
  65747. var needPutOnTop = false;
  65748. if (offsetY + rect.height > api.getHeight()) {
  65749. hoverStyle.textPosition = 'top';
  65750. needPutOnTop = true;
  65751. }
  65752. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  65753. if (offsetX + rect.width / 2 > api.getWidth()) {
  65754. hoverStyle.textPosition = ['100%', topOffset];
  65755. hoverStyle.textAlign = 'right';
  65756. }
  65757. else if (offsetX - rect.width / 2 < 0) {
  65758. hoverStyle.textPosition = [0, topOffset];
  65759. hoverStyle.textAlign = 'left';
  65760. }
  65761. }
  65762. });
  65763. },
  65764. updateView: function (toolboxModel, ecModel, api, payload) {
  65765. each$1(this._features, function (feature) {
  65766. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  65767. });
  65768. },
  65769. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  65770. // zrUtil.each(this._features, function (feature) {
  65771. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  65772. // });
  65773. // },
  65774. remove: function (ecModel, api) {
  65775. each$1(this._features, function (feature) {
  65776. feature.remove && feature.remove(ecModel, api);
  65777. });
  65778. this.group.removeAll();
  65779. },
  65780. dispose: function (ecModel, api) {
  65781. each$1(this._features, function (feature) {
  65782. feature.dispose && feature.dispose(ecModel, api);
  65783. });
  65784. }
  65785. });
  65786. function isUserFeatureName(featureName) {
  65787. return featureName.indexOf('my') === 0;
  65788. }
  65789. var saveAsImageLang = lang.toolbox.saveAsImage;
  65790. function SaveAsImage(model) {
  65791. this.model = model;
  65792. }
  65793. SaveAsImage.defaultOption = {
  65794. show: true,
  65795. 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',
  65796. title: saveAsImageLang.title,
  65797. type: 'png',
  65798. // Default use option.backgroundColor
  65799. // backgroundColor: '#fff',
  65800. name: '',
  65801. excludeComponents: ['toolbox'],
  65802. pixelRatio: 1,
  65803. lang: saveAsImageLang.lang.slice()
  65804. };
  65805. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  65806. var proto$4 = SaveAsImage.prototype;
  65807. proto$4.onclick = function (ecModel, api) {
  65808. var model = this.model;
  65809. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  65810. var $a = document.createElement('a');
  65811. var type = model.get('type', true) || 'png';
  65812. $a.download = title + '.' + type;
  65813. $a.target = '_blank';
  65814. var url = api.getConnectedDataURL({
  65815. type: type,
  65816. backgroundColor: model.get('backgroundColor', true)
  65817. || ecModel.get('backgroundColor') || '#fff',
  65818. excludeComponents: model.get('excludeComponents'),
  65819. pixelRatio: model.get('pixelRatio')
  65820. });
  65821. $a.href = url;
  65822. // Chrome and Firefox
  65823. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  65824. var evt = new MouseEvent('click', {
  65825. view: window,
  65826. bubbles: true,
  65827. cancelable: false
  65828. });
  65829. $a.dispatchEvent(evt);
  65830. }
  65831. // IE
  65832. else {
  65833. if (window.navigator.msSaveOrOpenBlob) {
  65834. var bstr = atob(url.split(',')[1]);
  65835. var n = bstr.length;
  65836. var u8arr = new Uint8Array(n);
  65837. while(n--) {
  65838. u8arr[n] = bstr.charCodeAt(n);
  65839. }
  65840. var blob = new Blob([u8arr]);
  65841. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  65842. }
  65843. else {
  65844. var lang$$1 = model.get('lang');
  65845. var html = '' +
  65846. '<body style="margin:0;">' +
  65847. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  65848. '</body>';
  65849. var tab = window.open();
  65850. tab.document.write(html);
  65851. }
  65852. }
  65853. };
  65854. register$1(
  65855. 'saveAsImage', SaveAsImage
  65856. );
  65857. var magicTypeLang = lang.toolbox.magicType;
  65858. function MagicType(model) {
  65859. this.model = model;
  65860. }
  65861. MagicType.defaultOption = {
  65862. show: true,
  65863. type: [],
  65864. // Icon group
  65865. icon: {
  65866. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  65867. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  65868. 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
  65869. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  65870. },
  65871. // `line`, `bar`, `stack`, `tiled`
  65872. title: clone(magicTypeLang.title),
  65873. option: {},
  65874. seriesIndex: {}
  65875. };
  65876. var proto$5 = MagicType.prototype;
  65877. proto$5.getIcons = function () {
  65878. var model = this.model;
  65879. var availableIcons = model.get('icon');
  65880. var icons = {};
  65881. each$1(model.get('type'), function (type) {
  65882. if (availableIcons[type]) {
  65883. icons[type] = availableIcons[type];
  65884. }
  65885. });
  65886. return icons;
  65887. };
  65888. var seriesOptGenreator = {
  65889. 'line': function (seriesType, seriesId, seriesModel, model) {
  65890. if (seriesType === 'bar') {
  65891. return merge({
  65892. id: seriesId,
  65893. type: 'line',
  65894. // Preserve data related option
  65895. data: seriesModel.get('data'),
  65896. stack: seriesModel.get('stack'),
  65897. markPoint: seriesModel.get('markPoint'),
  65898. markLine: seriesModel.get('markLine')
  65899. }, model.get('option.line') || {}, true);
  65900. }
  65901. },
  65902. 'bar': function (seriesType, seriesId, seriesModel, model) {
  65903. if (seriesType === 'line') {
  65904. return merge({
  65905. id: seriesId,
  65906. type: 'bar',
  65907. // Preserve data related option
  65908. data: seriesModel.get('data'),
  65909. stack: seriesModel.get('stack'),
  65910. markPoint: seriesModel.get('markPoint'),
  65911. markLine: seriesModel.get('markLine')
  65912. }, model.get('option.bar') || {}, true);
  65913. }
  65914. },
  65915. 'stack': function (seriesType, seriesId, seriesModel, model) {
  65916. if (seriesType === 'line' || seriesType === 'bar') {
  65917. return merge({
  65918. id: seriesId,
  65919. stack: '__ec_magicType_stack__'
  65920. }, model.get('option.stack') || {}, true);
  65921. }
  65922. },
  65923. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  65924. if (seriesType === 'line' || seriesType === 'bar') {
  65925. return merge({
  65926. id: seriesId,
  65927. stack: ''
  65928. }, model.get('option.tiled') || {}, true);
  65929. }
  65930. }
  65931. };
  65932. var radioTypes = [
  65933. ['line', 'bar'],
  65934. ['stack', 'tiled']
  65935. ];
  65936. proto$5.onclick = function (ecModel, api, type) {
  65937. var model = this.model;
  65938. var seriesIndex = model.get('seriesIndex.' + type);
  65939. // Not supported magicType
  65940. if (!seriesOptGenreator[type]) {
  65941. return;
  65942. }
  65943. var newOption = {
  65944. series: []
  65945. };
  65946. var generateNewSeriesTypes = function (seriesModel) {
  65947. var seriesType = seriesModel.subType;
  65948. var seriesId = seriesModel.id;
  65949. var newSeriesOpt = seriesOptGenreator[type](
  65950. seriesType, seriesId, seriesModel, model
  65951. );
  65952. if (newSeriesOpt) {
  65953. // PENDING If merge original option?
  65954. defaults(newSeriesOpt, seriesModel.option);
  65955. newOption.series.push(newSeriesOpt);
  65956. }
  65957. // Modify boundaryGap
  65958. var coordSys = seriesModel.coordinateSystem;
  65959. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  65960. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  65961. if (categoryAxis) {
  65962. var axisDim = categoryAxis.dim;
  65963. var axisType = axisDim + 'Axis';
  65964. var axisModel = ecModel.queryComponents({
  65965. mainType: axisType,
  65966. index: seriesModel.get(name + 'Index'),
  65967. id: seriesModel.get(name + 'Id')
  65968. })[0];
  65969. var axisIndex = axisModel.componentIndex;
  65970. newOption[axisType] = newOption[axisType] || [];
  65971. for (var i = 0; i <= axisIndex; i++) {
  65972. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  65973. }
  65974. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  65975. }
  65976. }
  65977. };
  65978. each$1(radioTypes, function (radio) {
  65979. if (indexOf(radio, type) >= 0) {
  65980. each$1(radio, function (item) {
  65981. model.setIconStatus(item, 'normal');
  65982. });
  65983. }
  65984. });
  65985. model.setIconStatus(type, 'emphasis');
  65986. ecModel.eachComponent(
  65987. {
  65988. mainType: 'series',
  65989. query: seriesIndex == null ? null : {
  65990. seriesIndex: seriesIndex
  65991. }
  65992. }, generateNewSeriesTypes
  65993. );
  65994. api.dispatchAction({
  65995. type: 'changeMagicType',
  65996. currentType: type,
  65997. newOption: newOption
  65998. });
  65999. };
  66000. registerAction({
  66001. type: 'changeMagicType',
  66002. event: 'magicTypeChanged',
  66003. update: 'prepareAndUpdate'
  66004. }, function (payload, ecModel) {
  66005. ecModel.mergeOption(payload.newOption);
  66006. });
  66007. register$1('magicType', MagicType);
  66008. var dataViewLang = lang.toolbox.dataView;
  66009. var BLOCK_SPLITER = new Array(60).join('-');
  66010. var ITEM_SPLITER = '\t';
  66011. /**
  66012. * Group series into two types
  66013. * 1. on category axis, like line, bar
  66014. * 2. others, like scatter, pie
  66015. * @param {module:echarts/model/Global} ecModel
  66016. * @return {Object}
  66017. * @inner
  66018. */
  66019. function groupSeries(ecModel) {
  66020. var seriesGroupByCategoryAxis = {};
  66021. var otherSeries = [];
  66022. var meta = [];
  66023. ecModel.eachRawSeries(function (seriesModel) {
  66024. var coordSys = seriesModel.coordinateSystem;
  66025. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  66026. var baseAxis = coordSys.getBaseAxis();
  66027. if (baseAxis.type === 'category') {
  66028. var key = baseAxis.dim + '_' + baseAxis.index;
  66029. if (!seriesGroupByCategoryAxis[key]) {
  66030. seriesGroupByCategoryAxis[key] = {
  66031. categoryAxis: baseAxis,
  66032. valueAxis: coordSys.getOtherAxis(baseAxis),
  66033. series: []
  66034. };
  66035. meta.push({
  66036. axisDim: baseAxis.dim,
  66037. axisIndex: baseAxis.index
  66038. });
  66039. }
  66040. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  66041. }
  66042. else {
  66043. otherSeries.push(seriesModel);
  66044. }
  66045. }
  66046. else {
  66047. otherSeries.push(seriesModel);
  66048. }
  66049. });
  66050. return {
  66051. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  66052. other: otherSeries,
  66053. meta: meta
  66054. };
  66055. }
  66056. /**
  66057. * Assemble content of series on cateogory axis
  66058. * @param {Array.<module:echarts/model/Series>} series
  66059. * @return {string}
  66060. * @inner
  66061. */
  66062. function assembleSeriesWithCategoryAxis(series) {
  66063. var tables = [];
  66064. each$1(series, function (group, key) {
  66065. var categoryAxis = group.categoryAxis;
  66066. var valueAxis = group.valueAxis;
  66067. var valueAxisDim = valueAxis.dim;
  66068. var headers = [' '].concat(map(group.series, function (series) {
  66069. return series.name;
  66070. }));
  66071. var columns = [categoryAxis.model.getCategories()];
  66072. each$1(group.series, function (series) {
  66073. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  66074. return val;
  66075. }));
  66076. });
  66077. // Assemble table content
  66078. var lines = [headers.join(ITEM_SPLITER)];
  66079. for (var i = 0; i < columns[0].length; i++) {
  66080. var items = [];
  66081. for (var j = 0; j < columns.length; j++) {
  66082. items.push(columns[j][i]);
  66083. }
  66084. lines.push(items.join(ITEM_SPLITER));
  66085. }
  66086. tables.push(lines.join('\n'));
  66087. });
  66088. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  66089. }
  66090. /**
  66091. * Assemble content of other series
  66092. * @param {Array.<module:echarts/model/Series>} series
  66093. * @return {string}
  66094. * @inner
  66095. */
  66096. function assembleOtherSeries(series) {
  66097. return map(series, function (series) {
  66098. var data = series.getRawData();
  66099. var lines = [series.name];
  66100. var vals = [];
  66101. data.each(data.dimensions, function () {
  66102. var argLen = arguments.length;
  66103. var dataIndex = arguments[argLen - 1];
  66104. var name = data.getName(dataIndex);
  66105. for (var i = 0; i < argLen - 1; i++) {
  66106. vals[i] = arguments[i];
  66107. }
  66108. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  66109. });
  66110. return lines.join('\n');
  66111. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  66112. }
  66113. /**
  66114. * @param {module:echarts/model/Global}
  66115. * @return {Object}
  66116. * @inner
  66117. */
  66118. function getContentFromModel(ecModel) {
  66119. var result = groupSeries(ecModel);
  66120. return {
  66121. value: filter([
  66122. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  66123. assembleOtherSeries(result.other)
  66124. ], function (str) {
  66125. return str.replace(/[\n\t\s]/g, '');
  66126. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  66127. meta: result.meta
  66128. };
  66129. }
  66130. function trim$1(str) {
  66131. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  66132. }
  66133. /**
  66134. * If a block is tsv format
  66135. */
  66136. function isTSVFormat(block) {
  66137. // Simple method to find out if a block is tsv format
  66138. var firstLine = block.slice(0, block.indexOf('\n'));
  66139. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  66140. return true;
  66141. }
  66142. }
  66143. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  66144. /**
  66145. * @param {string} tsv
  66146. * @return {Object}
  66147. */
  66148. function parseTSVContents(tsv) {
  66149. var tsvLines = tsv.split(/\n+/g);
  66150. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  66151. var categories = [];
  66152. var series = map(headers, function (header) {
  66153. return {
  66154. name: header,
  66155. data: []
  66156. };
  66157. });
  66158. for (var i = 0; i < tsvLines.length; i++) {
  66159. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  66160. categories.push(items.shift());
  66161. for (var j = 0; j < items.length; j++) {
  66162. series[j] && (series[j].data[i] = items[j]);
  66163. }
  66164. }
  66165. return {
  66166. series: series,
  66167. categories: categories
  66168. };
  66169. }
  66170. /**
  66171. * @param {string} str
  66172. * @return {Array.<Object>}
  66173. * @inner
  66174. */
  66175. function parseListContents(str) {
  66176. var lines = str.split(/\n+/g);
  66177. var seriesName = trim$1(lines.shift());
  66178. var data = [];
  66179. for (var i = 0; i < lines.length; i++) {
  66180. var items = trim$1(lines[i]).split(itemSplitRegex);
  66181. var name = '';
  66182. var value;
  66183. var hasName = false;
  66184. if (isNaN(items[0])) { // First item is name
  66185. hasName = true;
  66186. name = items[0];
  66187. items = items.slice(1);
  66188. data[i] = {
  66189. name: name,
  66190. value: []
  66191. };
  66192. value = data[i].value;
  66193. }
  66194. else {
  66195. value = data[i] = [];
  66196. }
  66197. for (var j = 0; j < items.length; j++) {
  66198. value.push(+items[j]);
  66199. }
  66200. if (value.length === 1) {
  66201. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  66202. }
  66203. }
  66204. return {
  66205. name: seriesName,
  66206. data: data
  66207. };
  66208. }
  66209. /**
  66210. * @param {string} str
  66211. * @param {Array.<Object>} blockMetaList
  66212. * @return {Object}
  66213. * @inner
  66214. */
  66215. function parseContents(str, blockMetaList) {
  66216. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  66217. var newOption = {
  66218. series: []
  66219. };
  66220. each$1(blocks, function (block, idx) {
  66221. if (isTSVFormat(block)) {
  66222. var result = parseTSVContents(block);
  66223. var blockMeta = blockMetaList[idx];
  66224. var axisKey = blockMeta.axisDim + 'Axis';
  66225. if (blockMeta) {
  66226. newOption[axisKey] = newOption[axisKey] || [];
  66227. newOption[axisKey][blockMeta.axisIndex] = {
  66228. data: result.categories
  66229. };
  66230. newOption.series = newOption.series.concat(result.series);
  66231. }
  66232. }
  66233. else {
  66234. var result = parseListContents(block);
  66235. newOption.series.push(result);
  66236. }
  66237. });
  66238. return newOption;
  66239. }
  66240. /**
  66241. * @alias {module:echarts/component/toolbox/feature/DataView}
  66242. * @constructor
  66243. * @param {module:echarts/model/Model} model
  66244. */
  66245. function DataView(model) {
  66246. this._dom = null;
  66247. this.model = model;
  66248. }
  66249. DataView.defaultOption = {
  66250. show: true,
  66251. readOnly: false,
  66252. optionToContent: null,
  66253. contentToOption: null,
  66254. 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',
  66255. title: clone(dataViewLang.title),
  66256. lang: clone(dataViewLang.lang),
  66257. backgroundColor: '#fff',
  66258. textColor: '#000',
  66259. textareaColor: '#fff',
  66260. textareaBorderColor: '#333',
  66261. buttonColor: '#c23531',
  66262. buttonTextColor: '#fff'
  66263. };
  66264. DataView.prototype.onclick = function (ecModel, api) {
  66265. var container = api.getDom();
  66266. var model = this.model;
  66267. if (this._dom) {
  66268. container.removeChild(this._dom);
  66269. }
  66270. var root = document.createElement('div');
  66271. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  66272. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  66273. // Create elements
  66274. var header = document.createElement('h4');
  66275. var lang$$1 = model.get('lang') || [];
  66276. header.innerHTML = lang$$1[0] || model.get('title');
  66277. header.style.cssText = 'margin: 10px 20px;';
  66278. header.style.color = model.get('textColor');
  66279. var viewMain = document.createElement('div');
  66280. var textarea = document.createElement('textarea');
  66281. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  66282. var optionToContent = model.get('optionToContent');
  66283. var contentToOption = model.get('contentToOption');
  66284. var result = getContentFromModel(ecModel);
  66285. if (typeof optionToContent === 'function') {
  66286. var htmlOrDom = optionToContent(api.getOption());
  66287. if (typeof htmlOrDom === 'string') {
  66288. viewMain.innerHTML = htmlOrDom;
  66289. }
  66290. else if (isDom(htmlOrDom)) {
  66291. viewMain.appendChild(htmlOrDom);
  66292. }
  66293. }
  66294. else {
  66295. // Use default textarea
  66296. viewMain.appendChild(textarea);
  66297. textarea.readOnly = model.get('readOnly');
  66298. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  66299. textarea.style.color = model.get('textColor');
  66300. textarea.style.borderColor = model.get('textareaBorderColor');
  66301. textarea.style.backgroundColor = model.get('textareaColor');
  66302. textarea.value = result.value;
  66303. }
  66304. var blockMetaList = result.meta;
  66305. var buttonContainer = document.createElement('div');
  66306. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  66307. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  66308. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  66309. var closeButton = document.createElement('div');
  66310. var refreshButton = document.createElement('div');
  66311. buttonStyle += ';background-color:' + model.get('buttonColor');
  66312. buttonStyle += ';color:' + model.get('buttonTextColor');
  66313. var self = this;
  66314. function close() {
  66315. container.removeChild(root);
  66316. self._dom = null;
  66317. }
  66318. addEventListener(closeButton, 'click', close);
  66319. addEventListener(refreshButton, 'click', function () {
  66320. var newOption;
  66321. try {
  66322. if (typeof contentToOption === 'function') {
  66323. newOption = contentToOption(viewMain, api.getOption());
  66324. }
  66325. else {
  66326. newOption = parseContents(textarea.value, blockMetaList);
  66327. }
  66328. }
  66329. catch (e) {
  66330. close();
  66331. throw new Error('Data view format error ' + e);
  66332. }
  66333. if (newOption) {
  66334. api.dispatchAction({
  66335. type: 'changeDataView',
  66336. newOption: newOption
  66337. });
  66338. }
  66339. close();
  66340. });
  66341. closeButton.innerHTML = lang$$1[1];
  66342. refreshButton.innerHTML = lang$$1[2];
  66343. refreshButton.style.cssText = buttonStyle;
  66344. closeButton.style.cssText = buttonStyle;
  66345. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  66346. buttonContainer.appendChild(closeButton);
  66347. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  66348. addEventListener(textarea, 'keydown', function (e) {
  66349. if ((e.keyCode || e.which) === 9) {
  66350. // get caret position/selection
  66351. var val = this.value;
  66352. var start = this.selectionStart;
  66353. var end = this.selectionEnd;
  66354. // set textarea value to: text before caret + tab + text after caret
  66355. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  66356. // put caret at right position again
  66357. this.selectionStart = this.selectionEnd = start + 1;
  66358. // prevent the focus lose
  66359. stop(e);
  66360. }
  66361. });
  66362. root.appendChild(header);
  66363. root.appendChild(viewMain);
  66364. root.appendChild(buttonContainer);
  66365. viewMain.style.height = (container.clientHeight - 80) + 'px';
  66366. container.appendChild(root);
  66367. this._dom = root;
  66368. };
  66369. DataView.prototype.remove = function (ecModel, api) {
  66370. this._dom && api.getDom().removeChild(this._dom);
  66371. };
  66372. DataView.prototype.dispose = function (ecModel, api) {
  66373. this.remove(ecModel, api);
  66374. };
  66375. /**
  66376. * @inner
  66377. */
  66378. function tryMergeDataOption(newData, originalData) {
  66379. return map(newData, function (newVal, idx) {
  66380. var original = originalData && originalData[idx];
  66381. if (isObject$1(original) && !isArray(original)) {
  66382. if (isObject$1(newVal) && !isArray(newVal)) {
  66383. newVal = newVal.value;
  66384. }
  66385. // Original data has option
  66386. return defaults({
  66387. value: newVal
  66388. }, original);
  66389. }
  66390. else {
  66391. return newVal;
  66392. }
  66393. });
  66394. }
  66395. register$1('dataView', DataView);
  66396. registerAction({
  66397. type: 'changeDataView',
  66398. event: 'dataViewChanged',
  66399. update: 'prepareAndUpdate'
  66400. }, function (payload, ecModel) {
  66401. var newSeriesOptList = [];
  66402. each$1(payload.newOption.series, function (seriesOpt) {
  66403. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  66404. if (!seriesModel) {
  66405. // New created series
  66406. // Geuss the series type
  66407. newSeriesOptList.push(extend({
  66408. // Default is scatter
  66409. type: 'scatter'
  66410. }, seriesOpt));
  66411. }
  66412. else {
  66413. var originalData = seriesModel.get('data');
  66414. newSeriesOptList.push({
  66415. name: seriesOpt.name,
  66416. data: tryMergeDataOption(seriesOpt.data, originalData)
  66417. });
  66418. }
  66419. });
  66420. ecModel.mergeOption(defaults({
  66421. series: newSeriesOptList
  66422. }, payload.newOption));
  66423. });
  66424. var each$30 = each$1;
  66425. var ATTR$2 = '\0_ec_hist_store';
  66426. /**
  66427. * @param {module:echarts/model/Global} ecModel
  66428. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  66429. */
  66430. function push(ecModel, newSnapshot) {
  66431. var store = giveStore$1(ecModel);
  66432. // If previous dataZoom can not be found,
  66433. // complete an range with current range.
  66434. each$30(newSnapshot, function (batchItem, dataZoomId) {
  66435. var i = store.length - 1;
  66436. for (; i >= 0; i--) {
  66437. var snapshot = store[i];
  66438. if (snapshot[dataZoomId]) {
  66439. break;
  66440. }
  66441. }
  66442. if (i < 0) {
  66443. // No origin range set, create one by current range.
  66444. var dataZoomModel = ecModel.queryComponents(
  66445. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  66446. )[0];
  66447. if (dataZoomModel) {
  66448. var percentRange = dataZoomModel.getPercentRange();
  66449. store[0][dataZoomId] = {
  66450. dataZoomId: dataZoomId,
  66451. start: percentRange[0],
  66452. end: percentRange[1]
  66453. };
  66454. }
  66455. }
  66456. });
  66457. store.push(newSnapshot);
  66458. }
  66459. /**
  66460. * @param {module:echarts/model/Global} ecModel
  66461. * @return {Object} snapshot
  66462. */
  66463. function pop(ecModel) {
  66464. var store = giveStore$1(ecModel);
  66465. var head = store[store.length - 1];
  66466. store.length > 1 && store.pop();
  66467. // Find top for all dataZoom.
  66468. var snapshot = {};
  66469. each$30(head, function (batchItem, dataZoomId) {
  66470. for (var i = store.length - 1; i >= 0; i--) {
  66471. var batchItem = store[i][dataZoomId];
  66472. if (batchItem) {
  66473. snapshot[dataZoomId] = batchItem;
  66474. break;
  66475. }
  66476. }
  66477. });
  66478. return snapshot;
  66479. }
  66480. /**
  66481. * @param {module:echarts/model/Global} ecModel
  66482. */
  66483. function clear$1(ecModel) {
  66484. ecModel[ATTR$2] = null;
  66485. }
  66486. /**
  66487. * @param {module:echarts/model/Global} ecModel
  66488. * @return {number} records. always >= 1.
  66489. */
  66490. function count(ecModel) {
  66491. return giveStore$1(ecModel).length;
  66492. }
  66493. /**
  66494. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  66495. * History length of each dataZoom may be different.
  66496. * this._history[0] is used to store origin range.
  66497. * @type {Array.<Object>}
  66498. */
  66499. function giveStore$1(ecModel) {
  66500. var store = ecModel[ATTR$2];
  66501. if (!store) {
  66502. store = ecModel[ATTR$2] = [{}];
  66503. }
  66504. return store;
  66505. }
  66506. DataZoomModel.extend({
  66507. type: 'dataZoom.select'
  66508. });
  66509. DataZoomView.extend({
  66510. type: 'dataZoom.select'
  66511. });
  66512. /**
  66513. * DataZoom component entry
  66514. */
  66515. // Use dataZoomSelect
  66516. var dataZoomLang = lang.toolbox.dataZoom;
  66517. var each$29 = each$1;
  66518. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  66519. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  66520. function DataZoom(model, ecModel, api) {
  66521. /**
  66522. * @private
  66523. * @type {module:echarts/component/helper/BrushController}
  66524. */
  66525. (this._brushController = new BrushController(api.getZr()))
  66526. .on('brush', bind(this._onBrush, this))
  66527. .mount();
  66528. /**
  66529. * @private
  66530. * @type {boolean}
  66531. */
  66532. this._isZoomActive;
  66533. }
  66534. DataZoom.defaultOption = {
  66535. show: true,
  66536. // Icon group
  66537. icon: {
  66538. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  66539. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  66540. },
  66541. // `zoom`, `back`
  66542. title: clone(dataZoomLang.title)
  66543. };
  66544. var proto$6 = DataZoom.prototype;
  66545. proto$6.render = function (featureModel, ecModel, api, payload) {
  66546. this.model = featureModel;
  66547. this.ecModel = ecModel;
  66548. this.api = api;
  66549. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  66550. updateBackBtnStatus(featureModel, ecModel);
  66551. };
  66552. proto$6.onclick = function (ecModel, api, type) {
  66553. handlers$1[type].call(this);
  66554. };
  66555. proto$6.remove = function (ecModel, api) {
  66556. this._brushController.unmount();
  66557. };
  66558. proto$6.dispose = function (ecModel, api) {
  66559. this._brushController.dispose();
  66560. };
  66561. /**
  66562. * @private
  66563. */
  66564. var handlers$1 = {
  66565. zoom: function () {
  66566. var nextActive = !this._isZoomActive;
  66567. this.api.dispatchAction({
  66568. type: 'takeGlobalCursor',
  66569. key: 'dataZoomSelect',
  66570. dataZoomSelectActive: nextActive
  66571. });
  66572. },
  66573. back: function () {
  66574. this._dispatchZoomAction(pop(this.ecModel));
  66575. }
  66576. };
  66577. /**
  66578. * @private
  66579. */
  66580. proto$6._onBrush = function (areas, opt) {
  66581. if (!opt.isEnd || !areas.length) {
  66582. return;
  66583. }
  66584. var snapshot = {};
  66585. var ecModel = this.ecModel;
  66586. this._brushController.updateCovers([]); // remove cover
  66587. var brushTargetManager = new BrushTargetManager(
  66588. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  66589. );
  66590. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  66591. if (coordSys.type !== 'cartesian2d') {
  66592. return;
  66593. }
  66594. var brushType = area.brushType;
  66595. if (brushType === 'rect') {
  66596. setBatch('x', coordSys, coordRange[0]);
  66597. setBatch('y', coordSys, coordRange[1]);
  66598. }
  66599. else {
  66600. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  66601. }
  66602. });
  66603. push(ecModel, snapshot);
  66604. this._dispatchZoomAction(snapshot);
  66605. function setBatch(dimName, coordSys, minMax) {
  66606. var axis = coordSys.getAxis(dimName);
  66607. var axisModel = axis.model;
  66608. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  66609. // Restrict range.
  66610. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  66611. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  66612. minMax = sliderMove(
  66613. 0, minMax.slice(), axis.scale.getExtent(), 0,
  66614. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  66615. );
  66616. }
  66617. dataZoomModel && (snapshot[dataZoomModel.id] = {
  66618. dataZoomId: dataZoomModel.id,
  66619. startValue: minMax[0],
  66620. endValue: minMax[1]
  66621. });
  66622. }
  66623. function findDataZoom(dimName, axisModel, ecModel) {
  66624. var found;
  66625. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  66626. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  66627. has && (found = dzModel);
  66628. });
  66629. return found;
  66630. }
  66631. };
  66632. /**
  66633. * @private
  66634. */
  66635. proto$6._dispatchZoomAction = function (snapshot) {
  66636. var batch = [];
  66637. // Convert from hash map to array.
  66638. each$29(snapshot, function (batchItem, dataZoomId) {
  66639. batch.push(clone(batchItem));
  66640. });
  66641. batch.length && this.api.dispatchAction({
  66642. type: 'dataZoom',
  66643. from: this.uid,
  66644. batch: batch
  66645. });
  66646. };
  66647. function retrieveAxisSetting(option) {
  66648. var setting = {};
  66649. // Compatible with previous setting: null => all axis, false => no axis.
  66650. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  66651. setting[name] = option[name];
  66652. setting[name] == null && (setting[name] = 'all');
  66653. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  66654. });
  66655. return setting;
  66656. }
  66657. function updateBackBtnStatus(featureModel, ecModel) {
  66658. featureModel.setIconStatus(
  66659. 'back',
  66660. count(ecModel) > 1 ? 'emphasis' : 'normal'
  66661. );
  66662. }
  66663. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  66664. var zoomActive = view._isZoomActive;
  66665. if (payload && payload.type === 'takeGlobalCursor') {
  66666. zoomActive = payload.key === 'dataZoomSelect'
  66667. ? payload.dataZoomSelectActive : false;
  66668. }
  66669. view._isZoomActive = zoomActive;
  66670. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  66671. var brushTargetManager = new BrushTargetManager(
  66672. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  66673. );
  66674. view._brushController
  66675. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  66676. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  66677. ? 'lineX'
  66678. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  66679. ? 'lineY'
  66680. : 'rect';
  66681. }))
  66682. .enableBrush(
  66683. zoomActive
  66684. ? {
  66685. brushType: 'auto',
  66686. brushStyle: {
  66687. // FIXME user customized?
  66688. lineWidth: 0,
  66689. fill: 'rgba(0,0,0,0.2)'
  66690. }
  66691. }
  66692. : false
  66693. );
  66694. }
  66695. register$1('dataZoom', DataZoom);
  66696. // Create special dataZoom option for select
  66697. registerPreprocessor(function (option) {
  66698. if (!option) {
  66699. return;
  66700. }
  66701. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  66702. if (!isArray(dataZoomOpts)) {
  66703. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  66704. }
  66705. var toolboxOpt = option.toolbox;
  66706. if (toolboxOpt) {
  66707. // Assume there is only one toolbox
  66708. if (isArray(toolboxOpt)) {
  66709. toolboxOpt = toolboxOpt[0];
  66710. }
  66711. if (toolboxOpt && toolboxOpt.feature) {
  66712. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  66713. addForAxis('xAxis', dataZoomOpt);
  66714. addForAxis('yAxis', dataZoomOpt);
  66715. }
  66716. }
  66717. function addForAxis(axisName, dataZoomOpt) {
  66718. if (!dataZoomOpt) {
  66719. return;
  66720. }
  66721. // Try not to modify model, because it is not merged yet.
  66722. var axisIndicesName = axisName + 'Index';
  66723. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  66724. if (givenAxisIndices != null
  66725. && givenAxisIndices != 'all'
  66726. && !isArray(givenAxisIndices)
  66727. ) {
  66728. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  66729. }
  66730. forEachComponent(axisName, function (axisOpt, axisIndex) {
  66731. if (givenAxisIndices != null
  66732. && givenAxisIndices != 'all'
  66733. && indexOf(givenAxisIndices, axisIndex) === -1
  66734. ) {
  66735. return;
  66736. }
  66737. var newOpt = {
  66738. type: 'select',
  66739. $fromToolbox: true,
  66740. // Id for merge mapping.
  66741. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  66742. };
  66743. // FIXME
  66744. // Only support one axis now.
  66745. newOpt[axisIndicesName] = axisIndex;
  66746. dataZoomOpts.push(newOpt);
  66747. });
  66748. }
  66749. function forEachComponent(mainType, cb) {
  66750. var opts = option[mainType];
  66751. if (!isArray(opts)) {
  66752. opts = opts ? [opts] : [];
  66753. }
  66754. each$29(opts, cb);
  66755. }
  66756. });
  66757. var restoreLang = lang.toolbox.restore;
  66758. function Restore(model) {
  66759. this.model = model;
  66760. }
  66761. Restore.defaultOption = {
  66762. show: true,
  66763. 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',
  66764. title: restoreLang.title
  66765. };
  66766. var proto$7 = Restore.prototype;
  66767. proto$7.onclick = function (ecModel, api, type) {
  66768. clear$1(ecModel);
  66769. api.dispatchAction({
  66770. type: 'restore',
  66771. from: this.uid
  66772. });
  66773. };
  66774. register$1('restore', Restore);
  66775. registerAction(
  66776. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  66777. function (payload, ecModel) {
  66778. ecModel.resetOption('recreate');
  66779. }
  66780. );
  66781. var urn = 'urn:schemas-microsoft-com:vml';
  66782. var win = typeof window === 'undefined' ? null : window;
  66783. var vmlInited = false;
  66784. var doc = win && win.document;
  66785. function createNode(tagName) {
  66786. return doCreateNode(tagName);
  66787. }
  66788. // Avoid assign to an exported variable, for transforming to cjs.
  66789. var doCreateNode;
  66790. if (doc && !env$1.canvasSupported) {
  66791. try {
  66792. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  66793. doCreateNode = function (tagName) {
  66794. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  66795. };
  66796. }
  66797. catch (e) {
  66798. doCreateNode = function (tagName) {
  66799. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  66800. };
  66801. }
  66802. }
  66803. // From raphael
  66804. function initVML() {
  66805. if (vmlInited || !doc) {
  66806. return;
  66807. }
  66808. vmlInited = true;
  66809. var styleSheets = doc.styleSheets;
  66810. if (styleSheets.length < 31) {
  66811. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  66812. }
  66813. else {
  66814. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  66815. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  66816. }
  66817. }
  66818. // http://www.w3.org/TR/NOTE-VML
  66819. // TODO Use proxy like svg instead of overwrite brush methods
  66820. var CMD$3 = PathProxy.CMD;
  66821. var round$3 = Math.round;
  66822. var sqrt = Math.sqrt;
  66823. var abs$1 = Math.abs;
  66824. var cos = Math.cos;
  66825. var sin = Math.sin;
  66826. var mathMax$8 = Math.max;
  66827. if (!env$1.canvasSupported) {
  66828. var comma = ',';
  66829. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  66830. var Z = 21600;
  66831. var Z2 = Z / 2;
  66832. var ZLEVEL_BASE = 100000;
  66833. var Z_BASE$1 = 1000;
  66834. var initRootElStyle = function (el) {
  66835. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  66836. el.coordsize = Z + ',' + Z;
  66837. el.coordorigin = '0,0';
  66838. };
  66839. var encodeHtmlAttribute = function (s) {
  66840. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  66841. };
  66842. var rgb2Str = function (r, g, b) {
  66843. return 'rgb(' + [r, g, b].join(',') + ')';
  66844. };
  66845. var append = function (parent, child) {
  66846. if (child && parent && child.parentNode !== parent) {
  66847. parent.appendChild(child);
  66848. }
  66849. };
  66850. var remove = function (parent, child) {
  66851. if (child && parent && child.parentNode === parent) {
  66852. parent.removeChild(child);
  66853. }
  66854. };
  66855. var getZIndex = function (zlevel, z, z2) {
  66856. // z 的取值范围为 [0, 1000]
  66857. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  66858. };
  66859. var parsePercent$3 = function (value, maxValue) {
  66860. if (typeof value === 'string') {
  66861. if (value.lastIndexOf('%') >= 0) {
  66862. return parseFloat(value) / 100 * maxValue;
  66863. }
  66864. return parseFloat(value);
  66865. }
  66866. return value;
  66867. };
  66868. /***************************************************
  66869. * PATH
  66870. **************************************************/
  66871. var setColorAndOpacity = function (el, color, opacity) {
  66872. var colorArr = parse(color);
  66873. opacity = +opacity;
  66874. if (isNaN(opacity)) {
  66875. opacity = 1;
  66876. }
  66877. if (colorArr) {
  66878. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  66879. el.opacity = opacity * colorArr[3];
  66880. }
  66881. };
  66882. var getColorAndAlpha = function (color) {
  66883. var colorArr = parse(color);
  66884. return [
  66885. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  66886. colorArr[3]
  66887. ];
  66888. };
  66889. var updateFillNode = function (el, style, zrEl) {
  66890. // TODO pattern
  66891. var fill = style.fill;
  66892. if (fill != null) {
  66893. // Modified from excanvas
  66894. if (fill instanceof Gradient) {
  66895. var gradientType;
  66896. var angle = 0;
  66897. var focus = [0, 0];
  66898. // additional offset
  66899. var shift = 0;
  66900. // scale factor for offset
  66901. var expansion = 1;
  66902. var rect = zrEl.getBoundingRect();
  66903. var rectWidth = rect.width;
  66904. var rectHeight = rect.height;
  66905. if (fill.type === 'linear') {
  66906. gradientType = 'gradient';
  66907. var transform = zrEl.transform;
  66908. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  66909. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  66910. if (transform) {
  66911. applyTransform(p0, p0, transform);
  66912. applyTransform(p1, p1, transform);
  66913. }
  66914. var dx = p1[0] - p0[0];
  66915. var dy = p1[1] - p0[1];
  66916. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  66917. // The angle should be a non-negative number.
  66918. if (angle < 0) {
  66919. angle += 360;
  66920. }
  66921. // Very small angles produce an unexpected result because they are
  66922. // converted to a scientific notation string.
  66923. if (angle < 1e-6) {
  66924. angle = 0;
  66925. }
  66926. }
  66927. else {
  66928. gradientType = 'gradientradial';
  66929. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  66930. var transform = zrEl.transform;
  66931. var scale$$1 = zrEl.scale;
  66932. var width = rectWidth;
  66933. var height = rectHeight;
  66934. focus = [
  66935. // Percent in bounding rect
  66936. (p0[0] - rect.x) / width,
  66937. (p0[1] - rect.y) / height
  66938. ];
  66939. if (transform) {
  66940. applyTransform(p0, p0, transform);
  66941. }
  66942. width /= scale$$1[0] * Z;
  66943. height /= scale$$1[1] * Z;
  66944. var dimension = mathMax$8(width, height);
  66945. shift = 2 * 0 / dimension;
  66946. expansion = 2 * fill.r / dimension - shift;
  66947. }
  66948. // We need to sort the color stops in ascending order by offset,
  66949. // otherwise IE won't interpret it correctly.
  66950. var stops = fill.colorStops.slice();
  66951. stops.sort(function(cs1, cs2) {
  66952. return cs1.offset - cs2.offset;
  66953. });
  66954. var length$$1 = stops.length;
  66955. // Color and alpha list of first and last stop
  66956. var colorAndAlphaList = [];
  66957. var colors = [];
  66958. for (var i = 0; i < length$$1; i++) {
  66959. var stop = stops[i];
  66960. var colorAndAlpha = getColorAndAlpha(stop.color);
  66961. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  66962. if (i === 0 || i === length$$1 - 1) {
  66963. colorAndAlphaList.push(colorAndAlpha);
  66964. }
  66965. }
  66966. if (length$$1 >= 2) {
  66967. var color1 = colorAndAlphaList[0][0];
  66968. var color2 = colorAndAlphaList[1][0];
  66969. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  66970. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  66971. el.type = gradientType;
  66972. el.method = 'none';
  66973. el.focus = '100%';
  66974. el.angle = angle;
  66975. el.color = color1;
  66976. el.color2 = color2;
  66977. el.colors = colors.join(',');
  66978. // When colors attribute is used, the meanings of opacity and o:opacity2
  66979. // are reversed.
  66980. el.opacity = opacity2;
  66981. // FIXME g_o_:opacity ?
  66982. el.opacity2 = opacity1;
  66983. }
  66984. if (gradientType === 'radial') {
  66985. el.focusposition = focus.join(',');
  66986. }
  66987. }
  66988. else {
  66989. // FIXME Change from Gradient fill to color fill
  66990. setColorAndOpacity(el, fill, style.opacity);
  66991. }
  66992. }
  66993. };
  66994. var updateStrokeNode = function (el, style) {
  66995. // if (style.lineJoin != null) {
  66996. // el.joinstyle = style.lineJoin;
  66997. // }
  66998. // if (style.miterLimit != null) {
  66999. // el.miterlimit = style.miterLimit * Z;
  67000. // }
  67001. // if (style.lineCap != null) {
  67002. // el.endcap = style.lineCap;
  67003. // }
  67004. if (style.lineDash != null) {
  67005. el.dashstyle = style.lineDash.join(' ');
  67006. }
  67007. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  67008. setColorAndOpacity(el, style.stroke, style.opacity);
  67009. }
  67010. };
  67011. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  67012. var isFill = type == 'fill';
  67013. var el = vmlEl.getElementsByTagName(type)[0];
  67014. // Stroke must have lineWidth
  67015. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  67016. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  67017. // FIXME Remove before updating, or set `colors` will throw error
  67018. if (style[type] instanceof Gradient) {
  67019. remove(vmlEl, el);
  67020. }
  67021. if (!el) {
  67022. el = createNode(type);
  67023. }
  67024. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  67025. append(vmlEl, el);
  67026. }
  67027. else {
  67028. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  67029. remove(vmlEl, el);
  67030. }
  67031. };
  67032. var points$3 = [[], [], []];
  67033. var pathDataToString = function (path, m) {
  67034. var M = CMD$3.M;
  67035. var C = CMD$3.C;
  67036. var L = CMD$3.L;
  67037. var A = CMD$3.A;
  67038. var Q = CMD$3.Q;
  67039. var str = [];
  67040. var nPoint;
  67041. var cmdStr;
  67042. var cmd;
  67043. var i;
  67044. var xi;
  67045. var yi;
  67046. var data = path.data;
  67047. var dataLength = path.len();
  67048. for (i = 0; i < dataLength;) {
  67049. cmd = data[i++];
  67050. cmdStr = '';
  67051. nPoint = 0;
  67052. switch (cmd) {
  67053. case M:
  67054. cmdStr = ' m ';
  67055. nPoint = 1;
  67056. xi = data[i++];
  67057. yi = data[i++];
  67058. points$3[0][0] = xi;
  67059. points$3[0][1] = yi;
  67060. break;
  67061. case L:
  67062. cmdStr = ' l ';
  67063. nPoint = 1;
  67064. xi = data[i++];
  67065. yi = data[i++];
  67066. points$3[0][0] = xi;
  67067. points$3[0][1] = yi;
  67068. break;
  67069. case Q:
  67070. case C:
  67071. cmdStr = ' c ';
  67072. nPoint = 3;
  67073. var x1 = data[i++];
  67074. var y1 = data[i++];
  67075. var x2 = data[i++];
  67076. var y2 = data[i++];
  67077. var x3;
  67078. var y3;
  67079. if (cmd === Q) {
  67080. // Convert quadratic to cubic using degree elevation
  67081. x3 = x2;
  67082. y3 = y2;
  67083. x2 = (x2 + 2 * x1) / 3;
  67084. y2 = (y2 + 2 * y1) / 3;
  67085. x1 = (xi + 2 * x1) / 3;
  67086. y1 = (yi + 2 * y1) / 3;
  67087. }
  67088. else {
  67089. x3 = data[i++];
  67090. y3 = data[i++];
  67091. }
  67092. points$3[0][0] = x1;
  67093. points$3[0][1] = y1;
  67094. points$3[1][0] = x2;
  67095. points$3[1][1] = y2;
  67096. points$3[2][0] = x3;
  67097. points$3[2][1] = y3;
  67098. xi = x3;
  67099. yi = y3;
  67100. break;
  67101. case A:
  67102. var x = 0;
  67103. var y = 0;
  67104. var sx = 1;
  67105. var sy = 1;
  67106. var angle = 0;
  67107. if (m) {
  67108. // Extract SRT from matrix
  67109. x = m[4];
  67110. y = m[5];
  67111. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  67112. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  67113. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  67114. }
  67115. var cx = data[i++];
  67116. var cy = data[i++];
  67117. var rx = data[i++];
  67118. var ry = data[i++];
  67119. var startAngle = data[i++] + angle;
  67120. var endAngle = data[i++] + startAngle + angle;
  67121. // FIXME
  67122. // var psi = data[i++];
  67123. i++;
  67124. var clockwise = data[i++];
  67125. var x0 = cx + cos(startAngle) * rx;
  67126. var y0 = cy + sin(startAngle) * ry;
  67127. var x1 = cx + cos(endAngle) * rx;
  67128. var y1 = cy + sin(endAngle) * ry;
  67129. var type = clockwise ? ' wa ' : ' at ';
  67130. if (Math.abs(x0 - x1) < 1e-4) {
  67131. // IE won't render arches drawn counter clockwise if x0 == x1.
  67132. if (Math.abs(endAngle - startAngle) > 1e-2) {
  67133. // Offset x0 by 1/80 of a pixel. Use something
  67134. // that can be represented in binary
  67135. if (clockwise) {
  67136. x0 += 270 / Z;
  67137. }
  67138. }
  67139. else {
  67140. // Avoid case draw full circle
  67141. if (Math.abs(y0 - cy) < 1e-4) {
  67142. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  67143. y1 -= 270 / Z;
  67144. }
  67145. else {
  67146. y1 += 270 / Z;
  67147. }
  67148. }
  67149. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  67150. x1 += 270 / Z;
  67151. }
  67152. else {
  67153. x1 -= 270 / Z;
  67154. }
  67155. }
  67156. }
  67157. str.push(
  67158. type,
  67159. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  67160. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  67161. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  67162. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  67163. round$3((x0 * sx + x) * Z - Z2), comma,
  67164. round$3((y0 * sy + y) * Z - Z2), comma,
  67165. round$3((x1 * sx + x) * Z - Z2), comma,
  67166. round$3((y1 * sy + y) * Z - Z2)
  67167. );
  67168. xi = x1;
  67169. yi = y1;
  67170. break;
  67171. case CMD$3.R:
  67172. var p0 = points$3[0];
  67173. var p1 = points$3[1];
  67174. // x0, y0
  67175. p0[0] = data[i++];
  67176. p0[1] = data[i++];
  67177. // x1, y1
  67178. p1[0] = p0[0] + data[i++];
  67179. p1[1] = p0[1] + data[i++];
  67180. if (m) {
  67181. applyTransform(p0, p0, m);
  67182. applyTransform(p1, p1, m);
  67183. }
  67184. p0[0] = round$3(p0[0] * Z - Z2);
  67185. p1[0] = round$3(p1[0] * Z - Z2);
  67186. p0[1] = round$3(p0[1] * Z - Z2);
  67187. p1[1] = round$3(p1[1] * Z - Z2);
  67188. str.push(
  67189. // x0, y0
  67190. ' m ', p0[0], comma, p0[1],
  67191. // x1, y0
  67192. ' l ', p1[0], comma, p0[1],
  67193. // x1, y1
  67194. ' l ', p1[0], comma, p1[1],
  67195. // x0, y1
  67196. ' l ', p0[0], comma, p1[1]
  67197. );
  67198. break;
  67199. case CMD$3.Z:
  67200. // FIXME Update xi, yi
  67201. str.push(' x ');
  67202. }
  67203. if (nPoint > 0) {
  67204. str.push(cmdStr);
  67205. for (var k = 0; k < nPoint; k++) {
  67206. var p = points$3[k];
  67207. m && applyTransform(p, p, m);
  67208. // 不 round 会非常慢
  67209. str.push(
  67210. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  67211. k < nPoint - 1 ? comma : ''
  67212. );
  67213. }
  67214. }
  67215. }
  67216. return str.join('');
  67217. };
  67218. // Rewrite the original path method
  67219. Path.prototype.brushVML = function (vmlRoot) {
  67220. var style = this.style;
  67221. var vmlEl = this._vmlEl;
  67222. if (!vmlEl) {
  67223. vmlEl = createNode('shape');
  67224. initRootElStyle(vmlEl);
  67225. this._vmlEl = vmlEl;
  67226. }
  67227. updateFillAndStroke(vmlEl, 'fill', style, this);
  67228. updateFillAndStroke(vmlEl, 'stroke', style, this);
  67229. var m = this.transform;
  67230. var needTransform = m != null;
  67231. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  67232. if (strokeEl) {
  67233. var lineWidth = style.lineWidth;
  67234. // Get the line scale.
  67235. // Determinant of this.m_ means how much the area is enlarged by the
  67236. // transformation. So its square root can be used as a scale factor
  67237. // for width.
  67238. if (needTransform && !style.strokeNoScale) {
  67239. var det = m[0] * m[3] - m[1] * m[2];
  67240. lineWidth *= sqrt(abs$1(det));
  67241. }
  67242. strokeEl.weight = lineWidth + 'px';
  67243. }
  67244. var path = this.path || (this.path = new PathProxy());
  67245. if (this.__dirtyPath) {
  67246. path.beginPath();
  67247. this.buildPath(path, this.shape);
  67248. path.toStatic();
  67249. this.__dirtyPath = false;
  67250. }
  67251. vmlEl.path = pathDataToString(path, this.transform);
  67252. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  67253. // Append to root
  67254. append(vmlRoot, vmlEl);
  67255. // Text
  67256. if (style.text != null) {
  67257. this.drawRectText(vmlRoot, this.getBoundingRect());
  67258. }
  67259. else {
  67260. this.removeRectText(vmlRoot);
  67261. }
  67262. };
  67263. Path.prototype.onRemove = function (vmlRoot) {
  67264. remove(vmlRoot, this._vmlEl);
  67265. this.removeRectText(vmlRoot);
  67266. };
  67267. Path.prototype.onAdd = function (vmlRoot) {
  67268. append(vmlRoot, this._vmlEl);
  67269. this.appendRectText(vmlRoot);
  67270. };
  67271. /***************************************************
  67272. * IMAGE
  67273. **************************************************/
  67274. var isImage = function (img) {
  67275. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  67276. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  67277. // return img instanceof Image;
  67278. };
  67279. // Rewrite the original path method
  67280. ZImage.prototype.brushVML = function (vmlRoot) {
  67281. var style = this.style;
  67282. var image = style.image;
  67283. // Image original width, height
  67284. var ow;
  67285. var oh;
  67286. if (isImage(image)) {
  67287. var src = image.src;
  67288. if (src === this._imageSrc) {
  67289. ow = this._imageWidth;
  67290. oh = this._imageHeight;
  67291. }
  67292. else {
  67293. var imageRuntimeStyle = image.runtimeStyle;
  67294. var oldRuntimeWidth = imageRuntimeStyle.width;
  67295. var oldRuntimeHeight = imageRuntimeStyle.height;
  67296. imageRuntimeStyle.width = 'auto';
  67297. imageRuntimeStyle.height = 'auto';
  67298. // get the original size
  67299. ow = image.width;
  67300. oh = image.height;
  67301. // and remove overides
  67302. imageRuntimeStyle.width = oldRuntimeWidth;
  67303. imageRuntimeStyle.height = oldRuntimeHeight;
  67304. // Caching image original width, height and src
  67305. this._imageSrc = src;
  67306. this._imageWidth = ow;
  67307. this._imageHeight = oh;
  67308. }
  67309. image = src;
  67310. }
  67311. else {
  67312. if (image === this._imageSrc) {
  67313. ow = this._imageWidth;
  67314. oh = this._imageHeight;
  67315. }
  67316. }
  67317. if (!image) {
  67318. return;
  67319. }
  67320. var x = style.x || 0;
  67321. var y = style.y || 0;
  67322. var dw = style.width;
  67323. var dh = style.height;
  67324. var sw = style.sWidth;
  67325. var sh = style.sHeight;
  67326. var sx = style.sx || 0;
  67327. var sy = style.sy || 0;
  67328. var hasCrop = sw && sh;
  67329. var vmlEl = this._vmlEl;
  67330. if (!vmlEl) {
  67331. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  67332. // vmlEl = vmlCore.createNode('group');
  67333. vmlEl = doc.createElement('div');
  67334. initRootElStyle(vmlEl);
  67335. this._vmlEl = vmlEl;
  67336. }
  67337. var vmlElStyle = vmlEl.style;
  67338. var hasRotation = false;
  67339. var m;
  67340. var scaleX = 1;
  67341. var scaleY = 1;
  67342. if (this.transform) {
  67343. m = this.transform;
  67344. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  67345. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  67346. hasRotation = m[1] || m[2];
  67347. }
  67348. if (hasRotation) {
  67349. // If filters are necessary (rotation exists), create them
  67350. // filters are bog-slow, so only create them if abbsolutely necessary
  67351. // The following check doesn't account for skews (which don't exist
  67352. // in the canvas spec (yet) anyway.
  67353. // From excanvas
  67354. var p0 = [x, y];
  67355. var p1 = [x + dw, y];
  67356. var p2 = [x, y + dh];
  67357. var p3 = [x + dw, y + dh];
  67358. applyTransform(p0, p0, m);
  67359. applyTransform(p1, p1, m);
  67360. applyTransform(p2, p2, m);
  67361. applyTransform(p3, p3, m);
  67362. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  67363. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  67364. var transformFilter = [];
  67365. transformFilter.push('M11=', m[0] / scaleX, comma,
  67366. 'M12=', m[2] / scaleY, comma,
  67367. 'M21=', m[1] / scaleX, comma,
  67368. 'M22=', m[3] / scaleY, comma,
  67369. 'Dx=', round$3(x * scaleX + m[4]), comma,
  67370. 'Dy=', round$3(y * scaleY + m[5]));
  67371. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  67372. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  67373. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  67374. + transformFilter.join('') + ', SizingMethod=clip)';
  67375. }
  67376. else {
  67377. if (m) {
  67378. x = x * scaleX + m[4];
  67379. y = y * scaleY + m[5];
  67380. }
  67381. vmlElStyle.filter = '';
  67382. vmlElStyle.left = round$3(x) + 'px';
  67383. vmlElStyle.top = round$3(y) + 'px';
  67384. }
  67385. var imageEl = this._imageEl;
  67386. var cropEl = this._cropEl;
  67387. if (!imageEl) {
  67388. imageEl = doc.createElement('div');
  67389. this._imageEl = imageEl;
  67390. }
  67391. var imageELStyle = imageEl.style;
  67392. if (hasCrop) {
  67393. // Needs know image original width and height
  67394. if (! (ow && oh)) {
  67395. var tmpImage = new Image();
  67396. var self = this;
  67397. tmpImage.onload = function () {
  67398. tmpImage.onload = null;
  67399. ow = tmpImage.width;
  67400. oh = tmpImage.height;
  67401. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  67402. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  67403. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  67404. // Caching image original width, height and src
  67405. self._imageWidth = ow;
  67406. self._imageHeight = oh;
  67407. self._imageSrc = image;
  67408. };
  67409. tmpImage.src = image;
  67410. }
  67411. else {
  67412. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  67413. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  67414. }
  67415. if (! cropEl) {
  67416. cropEl = doc.createElement('div');
  67417. cropEl.style.overflow = 'hidden';
  67418. this._cropEl = cropEl;
  67419. }
  67420. var cropElStyle = cropEl.style;
  67421. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  67422. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  67423. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  67424. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  67425. if (! cropEl.parentNode) {
  67426. vmlEl.appendChild(cropEl);
  67427. }
  67428. if (imageEl.parentNode != cropEl) {
  67429. cropEl.appendChild(imageEl);
  67430. }
  67431. }
  67432. else {
  67433. imageELStyle.width = round$3(scaleX * dw) + 'px';
  67434. imageELStyle.height = round$3(scaleY * dh) + 'px';
  67435. vmlEl.appendChild(imageEl);
  67436. if (cropEl && cropEl.parentNode) {
  67437. vmlEl.removeChild(cropEl);
  67438. this._cropEl = null;
  67439. }
  67440. }
  67441. var filterStr = '';
  67442. var alpha = style.opacity;
  67443. if (alpha < 1) {
  67444. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  67445. }
  67446. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  67447. imageELStyle.filter = filterStr;
  67448. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  67449. // Append to root
  67450. append(vmlRoot, vmlEl);
  67451. // Text
  67452. if (style.text != null) {
  67453. this.drawRectText(vmlRoot, this.getBoundingRect());
  67454. }
  67455. };
  67456. ZImage.prototype.onRemove = function (vmlRoot) {
  67457. remove(vmlRoot, this._vmlEl);
  67458. this._vmlEl = null;
  67459. this._cropEl = null;
  67460. this._imageEl = null;
  67461. this.removeRectText(vmlRoot);
  67462. };
  67463. ZImage.prototype.onAdd = function (vmlRoot) {
  67464. append(vmlRoot, this._vmlEl);
  67465. this.appendRectText(vmlRoot);
  67466. };
  67467. /***************************************************
  67468. * TEXT
  67469. **************************************************/
  67470. var DEFAULT_STYLE_NORMAL = 'normal';
  67471. var fontStyleCache = {};
  67472. var fontStyleCacheCount = 0;
  67473. var MAX_FONT_CACHE_SIZE = 100;
  67474. var fontEl = document.createElement('div');
  67475. var getFontStyle = function (fontString) {
  67476. var fontStyle = fontStyleCache[fontString];
  67477. if (!fontStyle) {
  67478. // Clear cache
  67479. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  67480. fontStyleCacheCount = 0;
  67481. fontStyleCache = {};
  67482. }
  67483. var style = fontEl.style;
  67484. var fontFamily;
  67485. try {
  67486. style.font = fontString;
  67487. fontFamily = style.fontFamily.split(',')[0];
  67488. }
  67489. catch (e) {
  67490. }
  67491. fontStyle = {
  67492. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  67493. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  67494. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  67495. size: parseFloat(style.fontSize || 12) | 0,
  67496. family: fontFamily || 'Microsoft YaHei'
  67497. };
  67498. fontStyleCache[fontString] = fontStyle;
  67499. fontStyleCacheCount++;
  67500. }
  67501. return fontStyle;
  67502. };
  67503. var textMeasureEl;
  67504. // Overwrite measure text method
  67505. $override$1('measureText', function (text, textFont) {
  67506. var doc$$1 = doc;
  67507. if (!textMeasureEl) {
  67508. textMeasureEl = doc$$1.createElement('div');
  67509. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  67510. + 'padding:0;margin:0;border:none;white-space:pre;';
  67511. doc.body.appendChild(textMeasureEl);
  67512. }
  67513. try {
  67514. textMeasureEl.style.font = textFont;
  67515. } catch (ex) {
  67516. // Ignore failures to set to invalid font.
  67517. }
  67518. textMeasureEl.innerHTML = '';
  67519. // Don't use innerHTML or innerText because they allow markup/whitespace.
  67520. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  67521. return {
  67522. width: textMeasureEl.offsetWidth
  67523. };
  67524. });
  67525. var tmpRect$2 = new BoundingRect();
  67526. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  67527. var style = this.style;
  67528. // Optimize, avoid normalize every time.
  67529. this.__dirty && normalizeTextStyle(style, true);
  67530. var text = style.text;
  67531. // Convert to string
  67532. text != null && (text += '');
  67533. if (!text) {
  67534. return;
  67535. }
  67536. // Convert rich text to plain text. Rich text is not supported in
  67537. // IE8-, but tags in rich text template will be removed.
  67538. if (style.rich) {
  67539. var contentBlock = parseRichText(text, style);
  67540. text = [];
  67541. for (var i = 0; i < contentBlock.lines.length; i++) {
  67542. var tokens = contentBlock.lines[i].tokens;
  67543. var textLine = [];
  67544. for (var j = 0; j < tokens.length; j++) {
  67545. textLine.push(tokens[j].text);
  67546. }
  67547. text.push(textLine.join(''));
  67548. }
  67549. text = text.join('\n');
  67550. }
  67551. var x;
  67552. var y;
  67553. var align = style.textAlign;
  67554. var verticalAlign = style.textVerticalAlign;
  67555. var fontStyle = getFontStyle(style.font);
  67556. // FIXME encodeHtmlAttribute ?
  67557. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  67558. + fontStyle.size + 'px "' + fontStyle.family + '"';
  67559. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  67560. // Transform rect to view space
  67561. var m = this.transform;
  67562. // Ignore transform for text in other element
  67563. if (m && !fromTextEl) {
  67564. tmpRect$2.copy(rect);
  67565. tmpRect$2.applyTransform(m);
  67566. rect = tmpRect$2;
  67567. }
  67568. if (!fromTextEl) {
  67569. var textPosition = style.textPosition;
  67570. var distance$$1 = style.textDistance;
  67571. // Text position represented by coord
  67572. if (textPosition instanceof Array) {
  67573. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  67574. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  67575. align = align || 'left';
  67576. }
  67577. else {
  67578. var res = adjustTextPositionOnRect(
  67579. textPosition, rect, distance$$1
  67580. );
  67581. x = res.x;
  67582. y = res.y;
  67583. // Default align and baseline when has textPosition
  67584. align = align || res.textAlign;
  67585. verticalAlign = verticalAlign || res.textVerticalAlign;
  67586. }
  67587. }
  67588. else {
  67589. x = rect.x;
  67590. y = rect.y;
  67591. }
  67592. x = adjustTextX(x, textRect.width, align);
  67593. y = adjustTextY(y, textRect.height, verticalAlign);
  67594. // Force baseline 'middle'
  67595. y += textRect.height / 2;
  67596. // var fontSize = fontStyle.size;
  67597. // 1.75 is an arbitrary number, as there is no info about the text baseline
  67598. // switch (baseline) {
  67599. // case 'hanging':
  67600. // case 'top':
  67601. // y += fontSize / 1.75;
  67602. // break;
  67603. // case 'middle':
  67604. // break;
  67605. // default:
  67606. // // case null:
  67607. // // case 'alphabetic':
  67608. // // case 'ideographic':
  67609. // // case 'bottom':
  67610. // y -= fontSize / 2.25;
  67611. // break;
  67612. // }
  67613. // switch (align) {
  67614. // case 'left':
  67615. // break;
  67616. // case 'center':
  67617. // x -= textRect.width / 2;
  67618. // break;
  67619. // case 'right':
  67620. // x -= textRect.width;
  67621. // break;
  67622. // case 'end':
  67623. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  67624. // break;
  67625. // case 'start':
  67626. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  67627. // break;
  67628. // default:
  67629. // align = 'left';
  67630. // }
  67631. var createNode$$1 = createNode;
  67632. var textVmlEl = this._textVmlEl;
  67633. var pathEl;
  67634. var textPathEl;
  67635. var skewEl;
  67636. if (!textVmlEl) {
  67637. textVmlEl = createNode$$1('line');
  67638. pathEl = createNode$$1('path');
  67639. textPathEl = createNode$$1('textpath');
  67640. skewEl = createNode$$1('skew');
  67641. // FIXME Why here is not cammel case
  67642. // Align 'center' seems wrong
  67643. textPathEl.style['v-text-align'] = 'left';
  67644. initRootElStyle(textVmlEl);
  67645. pathEl.textpathok = true;
  67646. textPathEl.on = true;
  67647. textVmlEl.from = '0 0';
  67648. textVmlEl.to = '1000 0.05';
  67649. append(textVmlEl, skewEl);
  67650. append(textVmlEl, pathEl);
  67651. append(textVmlEl, textPathEl);
  67652. this._textVmlEl = textVmlEl;
  67653. }
  67654. else {
  67655. // 这里是在前面 appendChild 保证顺序的前提下
  67656. skewEl = textVmlEl.firstChild;
  67657. pathEl = skewEl.nextSibling;
  67658. textPathEl = pathEl.nextSibling;
  67659. }
  67660. var coords = [x, y];
  67661. var textVmlElStyle = textVmlEl.style;
  67662. // Ignore transform for text in other element
  67663. if (m && fromTextEl) {
  67664. applyTransform(coords, coords, m);
  67665. skewEl.on = true;
  67666. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  67667. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  67668. // Text position
  67669. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  67670. // Left top point as origin
  67671. skewEl.origin = '0 0';
  67672. textVmlElStyle.left = '0px';
  67673. textVmlElStyle.top = '0px';
  67674. }
  67675. else {
  67676. skewEl.on = false;
  67677. textVmlElStyle.left = round$3(x) + 'px';
  67678. textVmlElStyle.top = round$3(y) + 'px';
  67679. }
  67680. textPathEl.string = encodeHtmlAttribute(text);
  67681. // TODO
  67682. try {
  67683. textPathEl.style.font = font;
  67684. }
  67685. // Error font format
  67686. catch (e) {}
  67687. updateFillAndStroke(textVmlEl, 'fill', {
  67688. fill: style.textFill,
  67689. opacity: style.opacity
  67690. }, this);
  67691. updateFillAndStroke(textVmlEl, 'stroke', {
  67692. stroke: style.textStroke,
  67693. opacity: style.opacity,
  67694. lineDash: style.lineDash
  67695. }, this);
  67696. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  67697. // Attached to root
  67698. append(vmlRoot, textVmlEl);
  67699. };
  67700. var removeRectText = function (vmlRoot) {
  67701. remove(vmlRoot, this._textVmlEl);
  67702. this._textVmlEl = null;
  67703. };
  67704. var appendRectText = function (vmlRoot) {
  67705. append(vmlRoot, this._textVmlEl);
  67706. };
  67707. var list = [RectText, Displayable, ZImage, Path, Text];
  67708. // In case Displayable has been mixed in RectText
  67709. for (var i$3 = 0; i$3 < list.length; i$3++) {
  67710. var proto$8 = list[i$3].prototype;
  67711. proto$8.drawRectText = drawRectText;
  67712. proto$8.removeRectText = removeRectText;
  67713. proto$8.appendRectText = appendRectText;
  67714. }
  67715. Text.prototype.brushVML = function (vmlRoot) {
  67716. var style = this.style;
  67717. if (style.text != null) {
  67718. this.drawRectText(vmlRoot, {
  67719. x: style.x || 0, y: style.y || 0,
  67720. width: 0, height: 0
  67721. }, this.getBoundingRect(), true);
  67722. }
  67723. else {
  67724. this.removeRectText(vmlRoot);
  67725. }
  67726. };
  67727. Text.prototype.onRemove = function (vmlRoot) {
  67728. this.removeRectText(vmlRoot);
  67729. };
  67730. Text.prototype.onAdd = function (vmlRoot) {
  67731. this.appendRectText(vmlRoot);
  67732. };
  67733. }
  67734. /**
  67735. * VML Painter.
  67736. *
  67737. * @module zrender/vml/Painter
  67738. */
  67739. function parseInt10$1(val) {
  67740. return parseInt(val, 10);
  67741. }
  67742. /**
  67743. * @alias module:zrender/vml/Painter
  67744. */
  67745. function VMLPainter(root, storage) {
  67746. initVML();
  67747. this.root = root;
  67748. this.storage = storage;
  67749. var vmlViewport = document.createElement('div');
  67750. var vmlRoot = document.createElement('div');
  67751. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  67752. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  67753. root.appendChild(vmlViewport);
  67754. this._vmlRoot = vmlRoot;
  67755. this._vmlViewport = vmlViewport;
  67756. this.resize();
  67757. // Modify storage
  67758. var oldDelFromStorage = storage.delFromStorage;
  67759. var oldAddToStorage = storage.addToStorage;
  67760. storage.delFromStorage = function (el) {
  67761. oldDelFromStorage.call(storage, el);
  67762. if (el) {
  67763. el.onRemove && el.onRemove(vmlRoot);
  67764. }
  67765. };
  67766. storage.addToStorage = function (el) {
  67767. // Displayable already has a vml node
  67768. el.onAdd && el.onAdd(vmlRoot);
  67769. oldAddToStorage.call(storage, el);
  67770. };
  67771. this._firstPaint = true;
  67772. }
  67773. VMLPainter.prototype = {
  67774. constructor: VMLPainter,
  67775. getType: function () {
  67776. return 'vml';
  67777. },
  67778. /**
  67779. * @return {HTMLDivElement}
  67780. */
  67781. getViewportRoot: function () {
  67782. return this._vmlViewport;
  67783. },
  67784. getViewportRootOffset: function () {
  67785. var viewportRoot = this.getViewportRoot();
  67786. if (viewportRoot) {
  67787. return {
  67788. offsetLeft: viewportRoot.offsetLeft || 0,
  67789. offsetTop: viewportRoot.offsetTop || 0
  67790. };
  67791. }
  67792. },
  67793. /**
  67794. * 刷新
  67795. */
  67796. refresh: function () {
  67797. var list = this.storage.getDisplayList(true, true);
  67798. this._paintList(list);
  67799. },
  67800. _paintList: function (list) {
  67801. var vmlRoot = this._vmlRoot;
  67802. for (var i = 0; i < list.length; i++) {
  67803. var el = list[i];
  67804. if (el.invisible || el.ignore) {
  67805. if (!el.__alreadyNotVisible) {
  67806. el.onRemove(vmlRoot);
  67807. }
  67808. // Set as already invisible
  67809. el.__alreadyNotVisible = true;
  67810. }
  67811. else {
  67812. if (el.__alreadyNotVisible) {
  67813. el.onAdd(vmlRoot);
  67814. }
  67815. el.__alreadyNotVisible = false;
  67816. if (el.__dirty) {
  67817. el.beforeBrush && el.beforeBrush();
  67818. (el.brushVML || el.brush).call(el, vmlRoot);
  67819. el.afterBrush && el.afterBrush();
  67820. }
  67821. }
  67822. el.__dirty = false;
  67823. }
  67824. if (this._firstPaint) {
  67825. // Detached from document at first time
  67826. // to avoid page refreshing too many times
  67827. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  67828. this._vmlViewport.appendChild(vmlRoot);
  67829. this._firstPaint = false;
  67830. }
  67831. },
  67832. resize: function (width, height) {
  67833. var width = width == null ? this._getWidth() : width;
  67834. var height = height == null ? this._getHeight() : height;
  67835. if (this._width != width || this._height != height) {
  67836. this._width = width;
  67837. this._height = height;
  67838. var vmlViewportStyle = this._vmlViewport.style;
  67839. vmlViewportStyle.width = width + 'px';
  67840. vmlViewportStyle.height = height + 'px';
  67841. }
  67842. },
  67843. dispose: function () {
  67844. this.root.innerHTML = '';
  67845. this._vmlRoot =
  67846. this._vmlViewport =
  67847. this.storage = null;
  67848. },
  67849. getWidth: function () {
  67850. return this._width;
  67851. },
  67852. getHeight: function () {
  67853. return this._height;
  67854. },
  67855. clear: function () {
  67856. if (this._vmlViewport) {
  67857. this.root.removeChild(this._vmlViewport);
  67858. }
  67859. },
  67860. _getWidth: function () {
  67861. var root = this.root;
  67862. var stl = root.currentStyle;
  67863. return ((root.clientWidth || parseInt10$1(stl.width))
  67864. - parseInt10$1(stl.paddingLeft)
  67865. - parseInt10$1(stl.paddingRight)) | 0;
  67866. },
  67867. _getHeight: function () {
  67868. var root = this.root;
  67869. var stl = root.currentStyle;
  67870. return ((root.clientHeight || parseInt10$1(stl.height))
  67871. - parseInt10$1(stl.paddingTop)
  67872. - parseInt10$1(stl.paddingBottom)) | 0;
  67873. }
  67874. };
  67875. // Not supported methods
  67876. function createMethodNotSupport(method) {
  67877. return function () {
  67878. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  67879. };
  67880. }
  67881. // Unsupported methods
  67882. each$1([
  67883. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  67884. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  67885. ], function (name) {
  67886. VMLPainter.prototype[name] = createMethodNotSupport(name);
  67887. });
  67888. registerPainter('vml', VMLPainter);
  67889. var svgURI = 'http://www.w3.org/2000/svg';
  67890. function createElement(name) {
  67891. return document.createElementNS(svgURI, name);
  67892. }
  67893. // TODO
  67894. // 1. shadow
  67895. // 2. Image: sx, sy, sw, sh
  67896. var CMD$4 = PathProxy.CMD;
  67897. var arrayJoin = Array.prototype.join;
  67898. var NONE = 'none';
  67899. var mathRound = Math.round;
  67900. var mathSin$3 = Math.sin;
  67901. var mathCos$3 = Math.cos;
  67902. var PI$5 = Math.PI;
  67903. var PI2$7 = Math.PI * 2;
  67904. var degree = 180 / PI$5;
  67905. var EPSILON$4 = 1e-4;
  67906. function round4(val) {
  67907. return mathRound(val * 1e4) / 1e4;
  67908. }
  67909. function isAroundZero$1(val) {
  67910. return val < EPSILON$4 && val > -EPSILON$4;
  67911. }
  67912. function pathHasFill(style, isText) {
  67913. var fill = isText ? style.textFill : style.fill;
  67914. return fill != null && fill !== NONE;
  67915. }
  67916. function pathHasStroke(style, isText) {
  67917. var stroke = isText ? style.textStroke : style.stroke;
  67918. return stroke != null && stroke !== NONE;
  67919. }
  67920. function setTransform(svgEl, m) {
  67921. if (m) {
  67922. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  67923. }
  67924. }
  67925. function attr(el, key, val) {
  67926. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  67927. // Don't set attribute for gradient, since it need new dom nodes
  67928. el.setAttribute(key, val);
  67929. }
  67930. }
  67931. function attrXLink(el, key, val) {
  67932. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  67933. }
  67934. function bindStyle(svgEl, style, isText) {
  67935. if (pathHasFill(style, isText)) {
  67936. var fill = isText ? style.textFill : style.fill;
  67937. fill = fill === 'transparent' ? NONE : fill;
  67938. /**
  67939. * FIXME:
  67940. * This is a temporary fix for Chrome's clipping bug
  67941. * that happens when a clip-path is referring another one.
  67942. * This fix should be used before Chrome's bug is fixed.
  67943. * For an element that has clip-path, and fill is none,
  67944. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  67945. * Otherwise, it will show black fill color.
  67946. * 0.002 is used because this won't work for alpha values smaller
  67947. * than 0.002.
  67948. *
  67949. * See
  67950. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  67951. * for more information.
  67952. */
  67953. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  67954. fill = 'rgba(0, 0, 0, 0.002)';
  67955. }
  67956. attr(svgEl, 'fill', fill);
  67957. attr(svgEl, 'fill-opacity', style.opacity);
  67958. }
  67959. else {
  67960. attr(svgEl, 'fill', NONE);
  67961. }
  67962. if (pathHasStroke(style, isText)) {
  67963. var stroke = isText ? style.textStroke : style.stroke;
  67964. stroke = stroke === 'transparent' ? NONE : stroke;
  67965. attr(svgEl, 'stroke', stroke);
  67966. var strokeWidth = isText
  67967. ? style.textStrokeWidth
  67968. : style.lineWidth;
  67969. var strokeScale = !isText && style.strokeNoScale
  67970. ? style.host.getLineScale()
  67971. : 1;
  67972. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  67973. // stroke then fill for text; fill then stroke for others
  67974. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  67975. attr(svgEl, 'stroke-opacity', style.opacity);
  67976. var lineDash = style.lineDash;
  67977. if (lineDash) {
  67978. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  67979. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  67980. }
  67981. else {
  67982. attr(svgEl, 'stroke-dasharray', '');
  67983. }
  67984. // PENDING
  67985. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  67986. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  67987. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  67988. }
  67989. else {
  67990. attr(svgEl, 'stroke', NONE);
  67991. }
  67992. }
  67993. /***************************************************
  67994. * PATH
  67995. **************************************************/
  67996. function pathDataToString$1(path) {
  67997. var str = [];
  67998. var data = path.data;
  67999. var dataLength = path.len();
  68000. for (var i = 0; i < dataLength;) {
  68001. var cmd = data[i++];
  68002. var cmdStr = '';
  68003. var nData = 0;
  68004. switch (cmd) {
  68005. case CMD$4.M:
  68006. cmdStr = 'M';
  68007. nData = 2;
  68008. break;
  68009. case CMD$4.L:
  68010. cmdStr = 'L';
  68011. nData = 2;
  68012. break;
  68013. case CMD$4.Q:
  68014. cmdStr = 'Q';
  68015. nData = 4;
  68016. break;
  68017. case CMD$4.C:
  68018. cmdStr = 'C';
  68019. nData = 6;
  68020. break;
  68021. case CMD$4.A:
  68022. var cx = data[i++];
  68023. var cy = data[i++];
  68024. var rx = data[i++];
  68025. var ry = data[i++];
  68026. var theta = data[i++];
  68027. var dTheta = data[i++];
  68028. var psi = data[i++];
  68029. var clockwise = data[i++];
  68030. var dThetaPositive = Math.abs(dTheta);
  68031. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  68032. && !isAroundZero$1(dThetaPositive);
  68033. var large = false;
  68034. if (dThetaPositive >= PI2$7) {
  68035. large = true;
  68036. }
  68037. else if (isAroundZero$1(dThetaPositive)) {
  68038. large = false;
  68039. }
  68040. else {
  68041. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  68042. === !!clockwise;
  68043. }
  68044. var x0 = round4(cx + rx * mathCos$3(theta));
  68045. var y0 = round4(cy + ry * mathSin$3(theta));
  68046. // It will not draw if start point and end point are exactly the same
  68047. // We need to shift the end point with a small value
  68048. // FIXME A better way to draw circle ?
  68049. if (isCircle) {
  68050. if (clockwise) {
  68051. dTheta = PI2$7 - 1e-4;
  68052. }
  68053. else {
  68054. dTheta = -PI2$7 + 1e-4;
  68055. }
  68056. large = true;
  68057. if (i === 9) {
  68058. // Move to (x0, y0) only when CMD.A comes at the
  68059. // first position of a shape.
  68060. // For instance, when drawing a ring, CMD.A comes
  68061. // after CMD.M, so it's unnecessary to move to
  68062. // (x0, y0).
  68063. str.push('M', x0, y0);
  68064. }
  68065. }
  68066. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  68067. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  68068. // FIXME Ellipse
  68069. str.push('A', round4(rx), round4(ry),
  68070. mathRound(psi * degree), +large, +clockwise, x, y);
  68071. break;
  68072. case CMD$4.Z:
  68073. cmdStr = 'Z';
  68074. break;
  68075. case CMD$4.R:
  68076. var x = round4(data[i++]);
  68077. var y = round4(data[i++]);
  68078. var w = round4(data[i++]);
  68079. var h = round4(data[i++]);
  68080. str.push(
  68081. 'M', x, y,
  68082. 'L', x + w, y,
  68083. 'L', x + w, y + h,
  68084. 'L', x, y + h,
  68085. 'L', x, y
  68086. );
  68087. break;
  68088. }
  68089. cmdStr && str.push(cmdStr);
  68090. for (var j = 0; j < nData; j++) {
  68091. // PENDING With scale
  68092. str.push(round4(data[i++]));
  68093. }
  68094. }
  68095. return str.join(' ');
  68096. }
  68097. var svgPath = {};
  68098. svgPath.brush = function (el) {
  68099. var style = el.style;
  68100. var svgEl = el.__svgEl;
  68101. if (!svgEl) {
  68102. svgEl = createElement('path');
  68103. el.__svgEl = svgEl;
  68104. }
  68105. if (!el.path) {
  68106. el.createPathProxy();
  68107. }
  68108. var path = el.path;
  68109. if (el.__dirtyPath) {
  68110. path.beginPath();
  68111. el.buildPath(path, el.shape);
  68112. el.__dirtyPath = false;
  68113. var pathStr = pathDataToString$1(path);
  68114. if (pathStr.indexOf('NaN') < 0) {
  68115. // Ignore illegal path, which may happen such in out-of-range
  68116. // data in Calendar series.
  68117. attr(svgEl, 'd', pathStr);
  68118. }
  68119. }
  68120. bindStyle(svgEl, style);
  68121. setTransform(svgEl, el.transform);
  68122. if (style.text != null) {
  68123. svgTextDrawRectText(el, el.getBoundingRect());
  68124. }
  68125. };
  68126. /***************************************************
  68127. * IMAGE
  68128. **************************************************/
  68129. var svgImage = {};
  68130. svgImage.brush = function (el) {
  68131. var style = el.style;
  68132. var image = style.image;
  68133. if (image instanceof HTMLImageElement) {
  68134. var src = image.src;
  68135. image = src;
  68136. }
  68137. if (! image) {
  68138. return;
  68139. }
  68140. var x = style.x || 0;
  68141. var y = style.y || 0;
  68142. var dw = style.width;
  68143. var dh = style.height;
  68144. var svgEl = el.__svgEl;
  68145. if (! svgEl) {
  68146. svgEl = createElement('image');
  68147. el.__svgEl = svgEl;
  68148. }
  68149. if (image !== el.__imageSrc) {
  68150. attrXLink(svgEl, 'href', image);
  68151. // Caching image src
  68152. el.__imageSrc = image;
  68153. }
  68154. attr(svgEl, 'width', dw);
  68155. attr(svgEl, 'height', dh);
  68156. attr(svgEl, 'x', x);
  68157. attr(svgEl, 'y', y);
  68158. setTransform(svgEl, el.transform);
  68159. if (style.text != null) {
  68160. svgTextDrawRectText(el, el.getBoundingRect());
  68161. }
  68162. };
  68163. /***************************************************
  68164. * TEXT
  68165. **************************************************/
  68166. var svgText = {};
  68167. var tmpRect$3 = new BoundingRect();
  68168. var svgTextDrawRectText = function (el, rect, textRect) {
  68169. var style = el.style;
  68170. el.__dirty && normalizeTextStyle(style, true);
  68171. var text = style.text;
  68172. // Convert to string
  68173. if (text == null) {
  68174. // Draw no text only when text is set to null, but not ''
  68175. return;
  68176. }
  68177. else {
  68178. text += '';
  68179. }
  68180. var textSvgEl = el.__textSvgEl;
  68181. if (! textSvgEl) {
  68182. textSvgEl = createElement('text');
  68183. el.__textSvgEl = textSvgEl;
  68184. }
  68185. var x;
  68186. var y;
  68187. var textPosition = style.textPosition;
  68188. var distance = style.textDistance;
  68189. var align = style.textAlign || 'left';
  68190. if (typeof style.fontSize === 'number') {
  68191. style.fontSize += 'px';
  68192. }
  68193. var font = style.font
  68194. || [
  68195. style.fontStyle || '',
  68196. style.fontWeight || '',
  68197. style.fontSize || '',
  68198. style.fontFamily || ''
  68199. ].join(' ')
  68200. || DEFAULT_FONT;
  68201. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  68202. textRect = getBoundingRect(text, font, align,
  68203. verticalAlign);
  68204. var lineHeight = textRect.lineHeight;
  68205. // Text position represented by coord
  68206. if (textPosition instanceof Array) {
  68207. x = rect.x + textPosition[0];
  68208. y = rect.y + textPosition[1];
  68209. }
  68210. else {
  68211. var newPos = adjustTextPositionOnRect(
  68212. textPosition, rect, distance
  68213. );
  68214. x = newPos.x;
  68215. y = newPos.y;
  68216. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  68217. align = newPos.textAlign;
  68218. }
  68219. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  68220. if (font) {
  68221. textSvgEl.style.font = font;
  68222. }
  68223. var textPadding = style.textPadding;
  68224. // Make baseline top
  68225. attr(textSvgEl, 'x', x);
  68226. attr(textSvgEl, 'y', y);
  68227. bindStyle(textSvgEl, style, true);
  68228. if (el instanceof Text || el.style.transformText) {
  68229. // Transform text with element
  68230. setTransform(textSvgEl, el.transform);
  68231. }
  68232. else {
  68233. if (el.transform) {
  68234. tmpRect$3.copy(rect);
  68235. tmpRect$3.applyTransform(el.transform);
  68236. rect = tmpRect$3;
  68237. }
  68238. else {
  68239. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  68240. rect.x = pos[0];
  68241. rect.y = pos[1];
  68242. }
  68243. // Text rotation, but no element transform
  68244. var origin = style.textOrigin;
  68245. if (origin === 'center') {
  68246. x = textRect.width / 2 + x;
  68247. y = textRect.height / 2 + y;
  68248. }
  68249. else if (origin) {
  68250. x = origin[0] + x;
  68251. y = origin[1] + y;
  68252. }
  68253. var rotate = -style.textRotation * 180 / Math.PI;
  68254. attr(textSvgEl, 'transform', 'rotate(' + rotate + ','
  68255. + x + ',' + y + ')');
  68256. }
  68257. var textLines = text.split('\n');
  68258. var nTextLines = textLines.length;
  68259. var textAnchor = align;
  68260. // PENDING
  68261. if (textAnchor === 'left') {
  68262. textAnchor = 'start';
  68263. textPadding && (x += textPadding[3]);
  68264. }
  68265. else if (textAnchor === 'right') {
  68266. textAnchor = 'end';
  68267. textPadding && (x -= textPadding[1]);
  68268. }
  68269. else if (textAnchor === 'center') {
  68270. textAnchor = 'middle';
  68271. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  68272. }
  68273. var dy = 0;
  68274. if (verticalAlign === 'baseline') {
  68275. dy = -textRect.height + lineHeight;
  68276. textPadding && (dy -= textPadding[2]);
  68277. }
  68278. else if (verticalAlign === 'middle') {
  68279. dy = (-textRect.height + lineHeight) / 2;
  68280. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  68281. }
  68282. else {
  68283. textPadding && (dy += textPadding[0]);
  68284. }
  68285. // Font may affect position of each tspan elements
  68286. if (el.__text !== text || el.__textFont !== font) {
  68287. var tspanList = el.__tspanList || [];
  68288. el.__tspanList = tspanList;
  68289. for (var i = 0; i < nTextLines; i++) {
  68290. // Using cached tspan elements
  68291. var tspan = tspanList[i];
  68292. if (! tspan) {
  68293. tspan = tspanList[i] = createElement('tspan');
  68294. textSvgEl.appendChild(tspan);
  68295. attr(tspan, 'alignment-baseline', verticalAlign);
  68296. attr(tspan, 'text-anchor', textAnchor);
  68297. }
  68298. else {
  68299. tspan.innerHTML = '';
  68300. }
  68301. attr(tspan, 'x', x);
  68302. attr(tspan, 'y', y + i * lineHeight + dy);
  68303. tspan.appendChild(document.createTextNode(textLines[i]));
  68304. }
  68305. // Remove unsed tspan elements
  68306. for (; i < tspanList.length; i++) {
  68307. textSvgEl.removeChild(tspanList[i]);
  68308. }
  68309. tspanList.length = nTextLines;
  68310. el.__text = text;
  68311. el.__textFont = font;
  68312. }
  68313. else if (el.__tspanList.length) {
  68314. // Update span x and y
  68315. var len = el.__tspanList.length;
  68316. for (var i = 0; i < len; ++i) {
  68317. var tspan = el.__tspanList[i];
  68318. if (tspan) {
  68319. attr(tspan, 'x', x);
  68320. attr(tspan, 'y', y + i * lineHeight + dy);
  68321. }
  68322. }
  68323. }
  68324. };
  68325. function getVerticalAlignForSvg(verticalAlign) {
  68326. if (verticalAlign === 'middle') {
  68327. return 'middle';
  68328. }
  68329. else if (verticalAlign === 'bottom') {
  68330. return 'baseline';
  68331. }
  68332. else {
  68333. return 'hanging';
  68334. }
  68335. }
  68336. svgText.drawRectText = svgTextDrawRectText;
  68337. svgText.brush = function (el) {
  68338. var style = el.style;
  68339. if (style.text != null) {
  68340. // 强制设置 textPosition
  68341. style.textPosition = [0, 0];
  68342. svgTextDrawRectText(el, {
  68343. x: style.x || 0, y: style.y || 0,
  68344. width: 0, height: 0
  68345. }, el.getBoundingRect());
  68346. }
  68347. };
  68348. // Myers' Diff Algorithm
  68349. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  68350. function Diff() {}
  68351. Diff.prototype = {
  68352. diff: function (oldArr, newArr, equals) {
  68353. if (!equals) {
  68354. equals = function (a, b) {
  68355. return a === b;
  68356. };
  68357. }
  68358. this.equals = equals;
  68359. var self = this;
  68360. oldArr = oldArr.slice();
  68361. newArr = newArr.slice();
  68362. // Allow subclasses to massage the input prior to running
  68363. var newLen = newArr.length;
  68364. var oldLen = oldArr.length;
  68365. var editLength = 1;
  68366. var maxEditLength = newLen + oldLen;
  68367. var bestPath = [{ newPos: -1, components: [] }];
  68368. // Seed editLength = 0, i.e. the content starts with the same values
  68369. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  68370. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  68371. var indices = [];
  68372. for (var i = 0; i < newArr.length; i++) {
  68373. indices.push(i);
  68374. }
  68375. // Identity per the equality and tokenizer
  68376. return [{
  68377. indices: indices, count: newArr.length
  68378. }];
  68379. }
  68380. // Main worker method. checks all permutations of a given edit length for acceptance.
  68381. function execEditLength() {
  68382. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  68383. var basePath;
  68384. var addPath = bestPath[diagonalPath - 1];
  68385. var removePath = bestPath[diagonalPath + 1];
  68386. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  68387. if (addPath) {
  68388. // No one else is going to attempt to use this value, clear it
  68389. bestPath[diagonalPath - 1] = undefined;
  68390. }
  68391. var canAdd = addPath && addPath.newPos + 1 < newLen;
  68392. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  68393. if (!canAdd && !canRemove) {
  68394. // If this path is a terminal then prune
  68395. bestPath[diagonalPath] = undefined;
  68396. continue;
  68397. }
  68398. // Select the diagonal that we want to branch from. We select the prior
  68399. // path whose position in the new string is the farthest from the origin
  68400. // and does not pass the bounds of the diff graph
  68401. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  68402. basePath = clonePath(removePath);
  68403. self.pushComponent(basePath.components, undefined, true);
  68404. }
  68405. else {
  68406. basePath = addPath; // No need to clone, we've pulled it from the list
  68407. basePath.newPos++;
  68408. self.pushComponent(basePath.components, true, undefined);
  68409. }
  68410. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  68411. // If we have hit the end of both strings, then we are done
  68412. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  68413. return buildValues(self, basePath.components, newArr, oldArr);
  68414. }
  68415. else {
  68416. // Otherwise track this path as a potential candidate and continue.
  68417. bestPath[diagonalPath] = basePath;
  68418. }
  68419. }
  68420. editLength++;
  68421. }
  68422. while (editLength <= maxEditLength) {
  68423. var ret = execEditLength();
  68424. if (ret) {
  68425. return ret;
  68426. }
  68427. }
  68428. },
  68429. pushComponent: function (components, added, removed) {
  68430. var last = components[components.length - 1];
  68431. if (last && last.added === added && last.removed === removed) {
  68432. // We need to clone here as the component clone operation is just
  68433. // as shallow array clone
  68434. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  68435. }
  68436. else {
  68437. components.push({count: 1, added: added, removed: removed });
  68438. }
  68439. },
  68440. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  68441. var newLen = newArr.length;
  68442. var oldLen = oldArr.length;
  68443. var newPos = basePath.newPos;
  68444. var oldPos = newPos - diagonalPath;
  68445. var commonCount = 0;
  68446. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  68447. newPos++;
  68448. oldPos++;
  68449. commonCount++;
  68450. }
  68451. if (commonCount) {
  68452. basePath.components.push({count: commonCount});
  68453. }
  68454. basePath.newPos = newPos;
  68455. return oldPos;
  68456. },
  68457. tokenize: function (value) {
  68458. return value.slice();
  68459. },
  68460. join: function (value) {
  68461. return value.slice();
  68462. }
  68463. };
  68464. function buildValues(diff, components, newArr, oldArr) {
  68465. var componentPos = 0;
  68466. var componentLen = components.length;
  68467. var newPos = 0;
  68468. var oldPos = 0;
  68469. for (; componentPos < componentLen; componentPos++) {
  68470. var component = components[componentPos];
  68471. if (!component.removed) {
  68472. var indices = [];
  68473. for (var i = newPos; i < newPos + component.count; i++) {
  68474. indices.push(i);
  68475. }
  68476. component.indices = indices;
  68477. newPos += component.count;
  68478. // Common case
  68479. if (!component.added) {
  68480. oldPos += component.count;
  68481. }
  68482. }
  68483. else {
  68484. var indices = [];
  68485. for (var i = oldPos; i < oldPos + component.count; i++) {
  68486. indices.push(i);
  68487. }
  68488. component.indices = indices;
  68489. oldPos += component.count;
  68490. }
  68491. }
  68492. return components;
  68493. }
  68494. function clonePath(path) {
  68495. return { newPos: path.newPos, components: path.components.slice(0) };
  68496. }
  68497. var arrayDiff = new Diff();
  68498. var arrayDiff$1 = function (oldArr, newArr, callback) {
  68499. return arrayDiff.diff(oldArr, newArr, callback);
  68500. };
  68501. /**
  68502. * @file Manages elements that can be defined in <defs> in SVG,
  68503. * e.g., gradients, clip path, etc.
  68504. * @author Zhang Wenli
  68505. */
  68506. var MARK_UNUSED = '0';
  68507. var MARK_USED = '1';
  68508. /**
  68509. * Manages elements that can be defined in <defs> in SVG,
  68510. * e.g., gradients, clip path, etc.
  68511. *
  68512. * @class
  68513. * @param {number} zrId zrender instance id
  68514. * @param {SVGElement} svgRoot root of SVG document
  68515. * @param {string|string[]} tagNames possible tag names
  68516. * @param {string} markLabel label name to make if the element
  68517. * is used
  68518. */
  68519. function Definable(
  68520. zrId,
  68521. svgRoot,
  68522. tagNames,
  68523. markLabel,
  68524. domName
  68525. ) {
  68526. this._zrId = zrId;
  68527. this._svgRoot = svgRoot;
  68528. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  68529. this._markLabel = markLabel;
  68530. this._domName = domName || '_dom';
  68531. this.nextId = 0;
  68532. }
  68533. Definable.prototype.createElement = createElement;
  68534. /**
  68535. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  68536. *
  68537. * @param {boolean} isForceCreating if need to create when not exists
  68538. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  68539. * exist and isForceCreating is false
  68540. */
  68541. Definable.prototype.getDefs = function (isForceCreating) {
  68542. var svgRoot = this._svgRoot;
  68543. var defs = this._svgRoot.getElementsByTagName('defs');
  68544. if (defs.length === 0) {
  68545. // Not exist
  68546. if (isForceCreating) {
  68547. defs = svgRoot.insertBefore(
  68548. this.createElement('defs'), // Create new tag
  68549. svgRoot.firstChild // Insert in the front of svg
  68550. );
  68551. if (!defs.contains) {
  68552. // IE doesn't support contains method
  68553. defs.contains = function (el) {
  68554. var children = defs.children;
  68555. if (!children) {
  68556. return false;
  68557. }
  68558. for (var i = children.length - 1; i >= 0; --i) {
  68559. if (children[i] === el) {
  68560. return true;
  68561. }
  68562. }
  68563. return false;
  68564. };
  68565. }
  68566. return defs;
  68567. }
  68568. else {
  68569. return null;
  68570. }
  68571. }
  68572. else {
  68573. return defs[0];
  68574. }
  68575. };
  68576. /**
  68577. * Update DOM element if necessary.
  68578. *
  68579. * @param {Object|string} element style element. e.g., for gradient,
  68580. * it may be '#ccc' or {type: 'linear', ...}
  68581. * @param {Function|undefined} onUpdate update callback
  68582. */
  68583. Definable.prototype.update = function (element, onUpdate) {
  68584. if (!element) {
  68585. return;
  68586. }
  68587. var defs = this.getDefs(false);
  68588. if (element[this._domName] && defs.contains(element[this._domName])) {
  68589. // Update DOM
  68590. if (typeof onUpdate === 'function') {
  68591. onUpdate(element);
  68592. }
  68593. }
  68594. else {
  68595. // No previous dom, create new
  68596. var dom = this.add(element);
  68597. if (dom) {
  68598. element[this._domName] = dom;
  68599. }
  68600. }
  68601. };
  68602. /**
  68603. * Add gradient dom to defs
  68604. *
  68605. * @param {SVGElement} dom DOM to be added to <defs>
  68606. */
  68607. Definable.prototype.addDom = function (dom) {
  68608. var defs = this.getDefs(true);
  68609. defs.appendChild(dom);
  68610. };
  68611. /**
  68612. * Remove DOM of a given element.
  68613. *
  68614. * @param {SVGElement} element element to remove dom
  68615. */
  68616. Definable.prototype.removeDom = function (element) {
  68617. var defs = this.getDefs(false);
  68618. if (defs && element[this._domName]) {
  68619. defs.removeChild(element[this._domName]);
  68620. element[this._domName] = null;
  68621. }
  68622. };
  68623. /**
  68624. * Get DOMs of this element.
  68625. *
  68626. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  68627. */
  68628. Definable.prototype.getDoms = function () {
  68629. var defs = this.getDefs(false);
  68630. if (!defs) {
  68631. // No dom when defs is not defined
  68632. return [];
  68633. }
  68634. var doms = [];
  68635. each$1(this._tagNames, function (tagName) {
  68636. var tags = defs.getElementsByTagName(tagName);
  68637. // Note that tags is HTMLCollection, which is array-like
  68638. // rather than real array.
  68639. // So `doms.concat(tags)` add tags as one object.
  68640. doms = doms.concat([].slice.call(tags));
  68641. });
  68642. return doms;
  68643. };
  68644. /**
  68645. * Mark DOMs to be unused before painting, and clear unused ones at the end
  68646. * of the painting.
  68647. */
  68648. Definable.prototype.markAllUnused = function () {
  68649. var doms = this.getDoms();
  68650. var that = this;
  68651. each$1(doms, function (dom) {
  68652. dom[that._markLabel] = MARK_UNUSED;
  68653. });
  68654. };
  68655. /**
  68656. * Mark a single DOM to be used.
  68657. *
  68658. * @param {SVGElement} dom DOM to mark
  68659. */
  68660. Definable.prototype.markUsed = function (dom) {
  68661. if (dom) {
  68662. dom[this._markLabel] = MARK_USED;
  68663. }
  68664. };
  68665. /**
  68666. * Remove unused DOMs defined in <defs>
  68667. */
  68668. Definable.prototype.removeUnused = function () {
  68669. var defs = this.getDefs(false);
  68670. if (!defs) {
  68671. // Nothing to remove
  68672. return;
  68673. }
  68674. var doms = this.getDoms();
  68675. var that = this;
  68676. each$1(doms, function (dom) {
  68677. if (dom[that._markLabel] !== MARK_USED) {
  68678. // Remove gradient
  68679. defs.removeChild(dom);
  68680. }
  68681. });
  68682. };
  68683. /**
  68684. * Get SVG proxy.
  68685. *
  68686. * @param {Displayable} displayable displayable element
  68687. * @return {Path|Image|Text} svg proxy of given element
  68688. */
  68689. Definable.prototype.getSvgProxy = function (displayable) {
  68690. if (displayable instanceof Path) {
  68691. return svgPath;
  68692. }
  68693. else if (displayable instanceof ZImage) {
  68694. return svgImage;
  68695. }
  68696. else if (displayable instanceof Text) {
  68697. return svgText;
  68698. }
  68699. else {
  68700. return svgPath;
  68701. }
  68702. };
  68703. /**
  68704. * Get text SVG element.
  68705. *
  68706. * @param {Displayable} displayable displayable element
  68707. * @return {SVGElement} SVG element of text
  68708. */
  68709. Definable.prototype.getTextSvgElement = function (displayable) {
  68710. return displayable.__textSvgEl;
  68711. };
  68712. /**
  68713. * Get SVG element.
  68714. *
  68715. * @param {Displayable} displayable displayable element
  68716. * @return {SVGElement} SVG element
  68717. */
  68718. Definable.prototype.getSvgElement = function (displayable) {
  68719. return displayable.__svgEl;
  68720. };
  68721. /**
  68722. * @file Manages SVG gradient elements.
  68723. * @author Zhang Wenli
  68724. */
  68725. /**
  68726. * Manages SVG gradient elements.
  68727. *
  68728. * @class
  68729. * @extends Definable
  68730. * @param {number} zrId zrender instance id
  68731. * @param {SVGElement} svgRoot root of SVG document
  68732. */
  68733. function GradientManager(zrId, svgRoot) {
  68734. Definable.call(
  68735. this,
  68736. zrId,
  68737. svgRoot,
  68738. ['linearGradient', 'radialGradient'],
  68739. '__gradient_in_use__'
  68740. );
  68741. }
  68742. inherits(GradientManager, Definable);
  68743. /**
  68744. * Create new gradient DOM for fill or stroke if not exist,
  68745. * but will not update gradient if exists.
  68746. *
  68747. * @param {SvgElement} svgElement SVG element to paint
  68748. * @param {Displayable} displayable zrender displayable element
  68749. */
  68750. GradientManager.prototype.addWithoutUpdate = function (
  68751. svgElement,
  68752. displayable
  68753. ) {
  68754. if (displayable && displayable.style) {
  68755. var that = this;
  68756. each$1(['fill', 'stroke'], function (fillOrStroke) {
  68757. if (displayable.style[fillOrStroke]
  68758. && (displayable.style[fillOrStroke].type === 'linear'
  68759. || displayable.style[fillOrStroke].type === 'radial')
  68760. ) {
  68761. var gradient = displayable.style[fillOrStroke];
  68762. var defs = that.getDefs(true);
  68763. // Create dom in <defs> if not exists
  68764. var dom;
  68765. if (gradient._dom) {
  68766. // Gradient exists
  68767. dom = gradient._dom;
  68768. if (!defs.contains(gradient._dom)) {
  68769. // _dom is no longer in defs, recreate
  68770. that.addDom(dom);
  68771. }
  68772. }
  68773. else {
  68774. // New dom
  68775. dom = that.add(gradient);
  68776. }
  68777. that.markUsed(displayable);
  68778. var id = dom.getAttribute('id');
  68779. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  68780. }
  68781. });
  68782. }
  68783. };
  68784. /**
  68785. * Add a new gradient tag in <defs>
  68786. *
  68787. * @param {Gradient} gradient zr gradient instance
  68788. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  68789. * created DOM
  68790. */
  68791. GradientManager.prototype.add = function (gradient) {
  68792. var dom;
  68793. if (gradient.type === 'linear') {
  68794. dom = this.createElement('linearGradient');
  68795. }
  68796. else if (gradient.type === 'radial') {
  68797. dom = this.createElement('radialGradient');
  68798. }
  68799. else {
  68800. zrLog('Illegal gradient type.');
  68801. return null;
  68802. }
  68803. // Set dom id with gradient id, since each gradient instance
  68804. // will have no more than one dom element.
  68805. // id may exists before for those dirty elements, in which case
  68806. // id should remain the same, and other attributes should be
  68807. // updated.
  68808. gradient.id = gradient.id || this.nextId++;
  68809. dom.setAttribute('id', 'zr' + this._zrId
  68810. + '-gradient-' + gradient.id);
  68811. this.updateDom(gradient, dom);
  68812. this.addDom(dom);
  68813. return dom;
  68814. };
  68815. /**
  68816. * Update gradient.
  68817. *
  68818. * @param {Gradient} gradient zr gradient instance
  68819. */
  68820. GradientManager.prototype.update = function (gradient) {
  68821. var that = this;
  68822. Definable.prototype.update.call(this, gradient, function () {
  68823. var type = gradient.type;
  68824. var tagName = gradient._dom.tagName;
  68825. if (type === 'linear' && tagName === 'linearGradient'
  68826. || type === 'radial' && tagName === 'radialGradient'
  68827. ) {
  68828. // Gradient type is not changed, update gradient
  68829. that.updateDom(gradient, gradient._dom);
  68830. }
  68831. else {
  68832. // Remove and re-create if type is changed
  68833. that.removeDom(gradient);
  68834. that.add(gradient);
  68835. }
  68836. });
  68837. };
  68838. /**
  68839. * Update gradient dom
  68840. *
  68841. * @param {Gradient} gradient zr gradient instance
  68842. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  68843. * DOM to update
  68844. */
  68845. GradientManager.prototype.updateDom = function (gradient, dom) {
  68846. if (gradient.type === 'linear') {
  68847. dom.setAttribute('x1', gradient.x);
  68848. dom.setAttribute('y1', gradient.y);
  68849. dom.setAttribute('x2', gradient.x2);
  68850. dom.setAttribute('y2', gradient.y2);
  68851. }
  68852. else if (gradient.type === 'radial') {
  68853. dom.setAttribute('cx', gradient.x);
  68854. dom.setAttribute('cy', gradient.y);
  68855. dom.setAttribute('r', gradient.r);
  68856. }
  68857. else {
  68858. zrLog('Illegal gradient type.');
  68859. return;
  68860. }
  68861. if (gradient.global) {
  68862. // x1, x2, y1, y2 in range of 0 to canvas width or height
  68863. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  68864. }
  68865. else {
  68866. // x1, x2, y1, y2 in range of 0 to 1
  68867. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  68868. }
  68869. // Remove color stops if exists
  68870. dom.innerHTML = '';
  68871. // Add color stops
  68872. var colors = gradient.colorStops;
  68873. for (var i = 0, len = colors.length; i < len; ++i) {
  68874. var stop = this.createElement('stop');
  68875. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  68876. stop.setAttribute('stop-color', colors[i].color);
  68877. dom.appendChild(stop);
  68878. }
  68879. // Store dom element in gradient, to avoid creating multiple
  68880. // dom instances for the same gradient element
  68881. gradient._dom = dom;
  68882. };
  68883. /**
  68884. * Mark a single gradient to be used
  68885. *
  68886. * @param {Displayable} displayable displayable element
  68887. */
  68888. GradientManager.prototype.markUsed = function (displayable) {
  68889. if (displayable.style) {
  68890. var gradient = displayable.style.fill;
  68891. if (gradient && gradient._dom) {
  68892. Definable.prototype.markUsed.call(this, gradient._dom);
  68893. }
  68894. gradient = displayable.style.stroke;
  68895. if (gradient && gradient._dom) {
  68896. Definable.prototype.markUsed.call(this, gradient._dom);
  68897. }
  68898. }
  68899. };
  68900. /**
  68901. * @file Manages SVG clipPath elements.
  68902. * @author Zhang Wenli
  68903. */
  68904. /**
  68905. * Manages SVG clipPath elements.
  68906. *
  68907. * @class
  68908. * @extends Definable
  68909. * @param {number} zrId zrender instance id
  68910. * @param {SVGElement} svgRoot root of SVG document
  68911. */
  68912. function ClippathManager(zrId, svgRoot) {
  68913. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  68914. }
  68915. inherits(ClippathManager, Definable);
  68916. /**
  68917. * Update clipPath.
  68918. *
  68919. * @param {Displayable} displayable displayable element
  68920. */
  68921. ClippathManager.prototype.update = function (displayable) {
  68922. var svgEl = this.getSvgElement(displayable);
  68923. if (svgEl) {
  68924. this.updateDom(svgEl, displayable.__clipPaths, false);
  68925. }
  68926. var textEl = this.getTextSvgElement(displayable);
  68927. if (textEl) {
  68928. // Make another clipPath for text, since it's transform
  68929. // matrix is not the same with svgElement
  68930. this.updateDom(textEl, displayable.__clipPaths, true);
  68931. }
  68932. this.markUsed(displayable);
  68933. };
  68934. /**
  68935. * Create an SVGElement of displayable and create a <clipPath> of its
  68936. * clipPath
  68937. *
  68938. * @param {Displayable} parentEl parent element
  68939. * @param {ClipPath[]} clipPaths clipPaths of parent element
  68940. * @param {boolean} isText if parent element is Text
  68941. */
  68942. ClippathManager.prototype.updateDom = function (
  68943. parentEl,
  68944. clipPaths,
  68945. isText
  68946. ) {
  68947. if (clipPaths && clipPaths.length > 0) {
  68948. // Has clipPath, create <clipPath> with the first clipPath
  68949. var defs = this.getDefs(true);
  68950. var clipPath = clipPaths[0];
  68951. var clipPathEl;
  68952. var id;
  68953. var dom = isText ? '_textDom' : '_dom';
  68954. if (clipPath[dom]) {
  68955. // Use a dom that is already in <defs>
  68956. id = clipPath[dom].getAttribute('id');
  68957. clipPathEl = clipPath[dom];
  68958. // Use a dom that is already in <defs>
  68959. if (!defs.contains(clipPathEl)) {
  68960. // This happens when set old clipPath that has
  68961. // been previously removed
  68962. defs.appendChild(clipPathEl);
  68963. }
  68964. }
  68965. else {
  68966. // New <clipPath>
  68967. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  68968. ++this.nextId;
  68969. clipPathEl = this.createElement('clipPath');
  68970. clipPathEl.setAttribute('id', id);
  68971. defs.appendChild(clipPathEl);
  68972. clipPath[dom] = clipPathEl;
  68973. }
  68974. // Build path and add to <clipPath>
  68975. var svgProxy = this.getSvgProxy(clipPath);
  68976. if (clipPath.transform
  68977. && clipPath.parent.invTransform
  68978. && !isText
  68979. ) {
  68980. /**
  68981. * If a clipPath has a parent with transform, the transform
  68982. * of parent should not be considered when setting transform
  68983. * of clipPath. So we need to transform back from parent's
  68984. * transform, which is done by multiplying parent's inverse
  68985. * transform.
  68986. */
  68987. // Store old transform
  68988. var transform = Array.prototype.slice.call(
  68989. clipPath.transform
  68990. );
  68991. // Transform back from parent, and brush path
  68992. mul$1(
  68993. clipPath.transform,
  68994. clipPath.parent.invTransform,
  68995. clipPath.transform
  68996. );
  68997. svgProxy.brush(clipPath);
  68998. // Set back transform of clipPath
  68999. clipPath.transform = transform;
  69000. }
  69001. else {
  69002. svgProxy.brush(clipPath);
  69003. }
  69004. var pathEl = this.getSvgElement(clipPath);
  69005. clipPathEl.innerHTML = '';
  69006. /**
  69007. * Use `cloneNode()` here to appendChild to multiple parents,
  69008. * which may happend when Text and other shapes are using the same
  69009. * clipPath. Since Text will create an extra clipPath DOM due to
  69010. * different transform rules.
  69011. */
  69012. clipPathEl.appendChild(pathEl.cloneNode());
  69013. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  69014. if (clipPaths.length > 1) {
  69015. // Make the other clipPaths recursively
  69016. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  69017. }
  69018. }
  69019. else {
  69020. // No clipPath
  69021. if (parentEl) {
  69022. parentEl.setAttribute('clip-path', 'none');
  69023. }
  69024. }
  69025. };
  69026. /**
  69027. * Mark a single clipPath to be used
  69028. *
  69029. * @param {Displayable} displayable displayable element
  69030. */
  69031. ClippathManager.prototype.markUsed = function (displayable) {
  69032. var that = this;
  69033. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  69034. each$1(displayable.__clipPaths, function (clipPath) {
  69035. if (clipPath._dom) {
  69036. Definable.prototype.markUsed.call(that, clipPath._dom);
  69037. }
  69038. if (clipPath._textDom) {
  69039. Definable.prototype.markUsed.call(that, clipPath._textDom);
  69040. }
  69041. });
  69042. }
  69043. };
  69044. /**
  69045. * @file Manages SVG shadow elements.
  69046. * @author Zhang Wenli
  69047. */
  69048. /**
  69049. * Manages SVG shadow elements.
  69050. *
  69051. * @class
  69052. * @extends Definable
  69053. * @param {number} zrId zrender instance id
  69054. * @param {SVGElement} svgRoot root of SVG document
  69055. */
  69056. function ShadowManager(zrId, svgRoot) {
  69057. Definable.call(
  69058. this,
  69059. zrId,
  69060. svgRoot,
  69061. ['filter'],
  69062. '__filter_in_use__',
  69063. '_shadowDom'
  69064. );
  69065. }
  69066. inherits(ShadowManager, Definable);
  69067. /**
  69068. * Create new shadow DOM for fill or stroke if not exist,
  69069. * but will not update shadow if exists.
  69070. *
  69071. * @param {SvgElement} svgElement SVG element to paint
  69072. * @param {Displayable} displayable zrender displayable element
  69073. */
  69074. ShadowManager.prototype.addWithoutUpdate = function (
  69075. svgElement,
  69076. displayable
  69077. ) {
  69078. if (displayable && hasShadow(displayable.style)) {
  69079. var style = displayable.style;
  69080. // Create dom in <defs> if not exists
  69081. var dom;
  69082. if (style._shadowDom) {
  69083. // Gradient exists
  69084. dom = style._shadowDom;
  69085. var defs = this.getDefs(true);
  69086. if (!defs.contains(style._shadowDom)) {
  69087. // _shadowDom is no longer in defs, recreate
  69088. this.addDom(dom);
  69089. }
  69090. }
  69091. else {
  69092. // New dom
  69093. dom = this.add(displayable);
  69094. }
  69095. this.markUsed(displayable);
  69096. var id = dom.getAttribute('id');
  69097. svgElement.style.filter = 'url(#' + id + ')';
  69098. }
  69099. };
  69100. /**
  69101. * Add a new shadow tag in <defs>
  69102. *
  69103. * @param {Displayable} displayable zrender displayable element
  69104. * @return {SVGFilterElement} created DOM
  69105. */
  69106. ShadowManager.prototype.add = function (displayable) {
  69107. var dom = this.createElement('filter');
  69108. var style = displayable.style;
  69109. // Set dom id with shadow id, since each shadow instance
  69110. // will have no more than one dom element.
  69111. // id may exists before for those dirty elements, in which case
  69112. // id should remain the same, and other attributes should be
  69113. // updated.
  69114. style._shadowDomId = style._shadowDomId || this.nextId++;
  69115. dom.setAttribute('id', 'zr' + this._zrId
  69116. + '-shadow-' + style._shadowDomId);
  69117. this.updateDom(displayable, dom);
  69118. this.addDom(dom);
  69119. return dom;
  69120. };
  69121. /**
  69122. * Update shadow.
  69123. *
  69124. * @param {Displayable} displayable zrender displayable element
  69125. */
  69126. ShadowManager.prototype.update = function (svgElement, displayable) {
  69127. var style = displayable.style;
  69128. if (hasShadow(style)) {
  69129. var that = this;
  69130. Definable.prototype.update.call(this, displayable, function (style) {
  69131. that.updateDom(displayable, style._shadowDom);
  69132. });
  69133. }
  69134. else {
  69135. // Remove shadow
  69136. this.remove(svgElement, style);
  69137. }
  69138. };
  69139. /**
  69140. * Remove DOM and clear parent filter
  69141. */
  69142. ShadowManager.prototype.remove = function (svgElement, style) {
  69143. if (style._shadowDomId != null) {
  69144. this.removeDom(style);
  69145. svgElement.style.filter = '';
  69146. }
  69147. };
  69148. /**
  69149. * Update shadow dom
  69150. *
  69151. * @param {Displayable} displayable zrender displayable element
  69152. * @param {SVGFilterElement} dom DOM to update
  69153. */
  69154. ShadowManager.prototype.updateDom = function (displayable, dom) {
  69155. var domChild = dom.getElementsByTagName('feDropShadow');
  69156. if (domChild.length === 0) {
  69157. domChild = this.createElement('feDropShadow');
  69158. }
  69159. else {
  69160. domChild = domChild[0];
  69161. }
  69162. var style = displayable.style;
  69163. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  69164. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  69165. // TODO: textBoxShadowBlur is not supported yet
  69166. var offsetX, offsetY, blur, color;
  69167. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  69168. offsetX = style.shadowOffsetX || 0;
  69169. offsetY = style.shadowOffsetY || 0;
  69170. blur = style.shadowBlur;
  69171. color = style.shadowColor;
  69172. }
  69173. else if (style.textShadowBlur) {
  69174. offsetX = style.textShadowOffsetX || 0;
  69175. offsetY = style.textShadowOffsetY || 0;
  69176. blur = style.textShadowBlur;
  69177. color = style.textShadowColor;
  69178. }
  69179. else {
  69180. // Remove shadow
  69181. this.removeDom(dom, style);
  69182. return;
  69183. }
  69184. domChild.setAttribute('dx', offsetX / scaleX);
  69185. domChild.setAttribute('dy', offsetY / scaleY);
  69186. domChild.setAttribute('flood-color', color);
  69187. // Divide by two here so that it looks the same as in canvas
  69188. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  69189. var stdDx = blur / 2 / scaleX;
  69190. var stdDy = blur / 2 / scaleY;
  69191. var stdDeviation = stdDx + ' ' + stdDy;
  69192. domChild.setAttribute('stdDeviation', stdDeviation);
  69193. // Fix filter clipping problem
  69194. dom.setAttribute('x', '-100%');
  69195. dom.setAttribute('y', '-100%');
  69196. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  69197. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  69198. dom.appendChild(domChild);
  69199. // Store dom element in shadow, to avoid creating multiple
  69200. // dom instances for the same shadow element
  69201. style._shadowDom = dom;
  69202. };
  69203. /**
  69204. * Mark a single shadow to be used
  69205. *
  69206. * @param {Displayable} displayable displayable element
  69207. */
  69208. ShadowManager.prototype.markUsed = function (displayable) {
  69209. var style = displayable.style;
  69210. if (style && style._shadowDom) {
  69211. Definable.prototype.markUsed.call(this, style._shadowDom);
  69212. }
  69213. };
  69214. function hasShadow(style) {
  69215. // TODO: textBoxShadowBlur is not supported yet
  69216. return style
  69217. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  69218. || style.textShadowBlur || style.textShadowOffsetX
  69219. || style.textShadowOffsetY);
  69220. }
  69221. /**
  69222. * SVG Painter
  69223. * @module zrender/svg/Painter
  69224. */
  69225. function parseInt10$2(val) {
  69226. return parseInt(val, 10);
  69227. }
  69228. function getSvgProxy(el) {
  69229. if (el instanceof Path) {
  69230. return svgPath;
  69231. }
  69232. else if (el instanceof ZImage) {
  69233. return svgImage;
  69234. }
  69235. else if (el instanceof Text) {
  69236. return svgText;
  69237. }
  69238. else {
  69239. return svgPath;
  69240. }
  69241. }
  69242. function checkParentAvailable(parent, child) {
  69243. return child && parent && child.parentNode !== parent;
  69244. }
  69245. function insertAfter(parent, child, prevSibling) {
  69246. if (checkParentAvailable(parent, child) && prevSibling) {
  69247. var nextSibling = prevSibling.nextSibling;
  69248. nextSibling ? parent.insertBefore(child, nextSibling)
  69249. : parent.appendChild(child);
  69250. }
  69251. }
  69252. function prepend(parent, child) {
  69253. if (checkParentAvailable(parent, child)) {
  69254. var firstChild = parent.firstChild;
  69255. firstChild ? parent.insertBefore(child, firstChild)
  69256. : parent.appendChild(child);
  69257. }
  69258. }
  69259. function remove$1(parent, child) {
  69260. if (child && parent && child.parentNode === parent) {
  69261. parent.removeChild(child);
  69262. }
  69263. }
  69264. function getTextSvgElement(displayable) {
  69265. return displayable.__textSvgEl;
  69266. }
  69267. function getSvgElement(displayable) {
  69268. return displayable.__svgEl;
  69269. }
  69270. /**
  69271. * @alias module:zrender/svg/Painter
  69272. * @constructor
  69273. * @param {HTMLElement} root 绘图容器
  69274. * @param {module:zrender/Storage} storage
  69275. * @param {Object} opts
  69276. */
  69277. var SVGPainter = function (root, storage, opts, zrId) {
  69278. this.root = root;
  69279. this.storage = storage;
  69280. this._opts = opts = extend({}, opts || {});
  69281. var svgRoot = createElement('svg');
  69282. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  69283. svgRoot.setAttribute('version', '1.1');
  69284. svgRoot.setAttribute('baseProfile', 'full');
  69285. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  69286. this.gradientManager = new GradientManager(zrId, svgRoot);
  69287. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  69288. this.shadowManager = new ShadowManager(zrId, svgRoot);
  69289. var viewport = document.createElement('div');
  69290. viewport.style.cssText = 'overflow:hidden;position:relative';
  69291. this._svgRoot = svgRoot;
  69292. this._viewport = viewport;
  69293. root.appendChild(viewport);
  69294. viewport.appendChild(svgRoot);
  69295. this.resize(opts.width, opts.height);
  69296. this._visibleList = [];
  69297. };
  69298. SVGPainter.prototype = {
  69299. constructor: SVGPainter,
  69300. getType: function () {
  69301. return 'svg';
  69302. },
  69303. getViewportRoot: function () {
  69304. return this._viewport;
  69305. },
  69306. getViewportRootOffset: function () {
  69307. var viewportRoot = this.getViewportRoot();
  69308. if (viewportRoot) {
  69309. return {
  69310. offsetLeft: viewportRoot.offsetLeft || 0,
  69311. offsetTop: viewportRoot.offsetTop || 0
  69312. };
  69313. }
  69314. },
  69315. refresh: function () {
  69316. var list = this.storage.getDisplayList(true);
  69317. this._paintList(list);
  69318. },
  69319. setBackgroundColor: function (backgroundColor) {
  69320. // TODO gradient
  69321. this._viewport.style.background = backgroundColor;
  69322. },
  69323. _paintList: function (list) {
  69324. this.gradientManager.markAllUnused();
  69325. this.clipPathManager.markAllUnused();
  69326. this.shadowManager.markAllUnused();
  69327. var svgRoot = this._svgRoot;
  69328. var visibleList = this._visibleList;
  69329. var listLen = list.length;
  69330. var newVisibleList = [];
  69331. var i;
  69332. for (i = 0; i < listLen; i++) {
  69333. var displayable = list[i];
  69334. var svgProxy = getSvgProxy(displayable);
  69335. var svgElement = getSvgElement(displayable)
  69336. || getTextSvgElement(displayable);
  69337. if (!displayable.invisible) {
  69338. if (displayable.__dirty) {
  69339. svgProxy && svgProxy.brush(displayable);
  69340. // Update clipPath
  69341. this.clipPathManager.update(displayable);
  69342. // Update gradient and shadow
  69343. if (displayable.style) {
  69344. this.gradientManager
  69345. .update(displayable.style.fill);
  69346. this.gradientManager
  69347. .update(displayable.style.stroke);
  69348. this.shadowManager
  69349. .update(svgElement, displayable);
  69350. }
  69351. displayable.__dirty = false;
  69352. }
  69353. newVisibleList.push(displayable);
  69354. }
  69355. }
  69356. var diff = arrayDiff$1(visibleList, newVisibleList);
  69357. var prevSvgElement;
  69358. // First do remove, in case element moved to the head and do remove
  69359. // after add
  69360. for (i = 0; i < diff.length; i++) {
  69361. var item = diff[i];
  69362. if (item.removed) {
  69363. for (var k = 0; k < item.count; k++) {
  69364. var displayable = visibleList[item.indices[k]];
  69365. var svgElement = getSvgElement(displayable);
  69366. var textSvgElement = getTextSvgElement(displayable);
  69367. remove$1(svgRoot, svgElement);
  69368. remove$1(svgRoot, textSvgElement);
  69369. }
  69370. }
  69371. }
  69372. for (i = 0; i < diff.length; i++) {
  69373. var item = diff[i];
  69374. if (item.added) {
  69375. for (var k = 0; k < item.count; k++) {
  69376. var displayable = newVisibleList[item.indices[k]];
  69377. var svgElement = getSvgElement(displayable);
  69378. var textSvgElement = getTextSvgElement(displayable);
  69379. prevSvgElement
  69380. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  69381. : prepend(svgRoot, svgElement);
  69382. if (svgElement) {
  69383. insertAfter(svgRoot, textSvgElement, svgElement);
  69384. }
  69385. else if (prevSvgElement) {
  69386. insertAfter(
  69387. svgRoot, textSvgElement, prevSvgElement
  69388. );
  69389. }
  69390. else {
  69391. prepend(svgRoot, textSvgElement);
  69392. }
  69393. // Insert text
  69394. insertAfter(svgRoot, textSvgElement, svgElement);
  69395. prevSvgElement = textSvgElement || svgElement
  69396. || prevSvgElement;
  69397. this.gradientManager
  69398. .addWithoutUpdate(svgElement, displayable);
  69399. this.shadowManager
  69400. .addWithoutUpdate(prevSvgElement, displayable);
  69401. this.clipPathManager.markUsed(displayable);
  69402. }
  69403. }
  69404. else if (!item.removed) {
  69405. for (var k = 0; k < item.count; k++) {
  69406. var displayable = newVisibleList[item.indices[k]];
  69407. prevSvgElement
  69408. = svgElement
  69409. = getTextSvgElement(displayable)
  69410. || getSvgElement(displayable)
  69411. || prevSvgElement;
  69412. this.gradientManager.markUsed(displayable);
  69413. this.gradientManager
  69414. .addWithoutUpdate(svgElement, displayable);
  69415. this.shadowManager.markUsed(displayable);
  69416. this.shadowManager
  69417. .addWithoutUpdate(svgElement, displayable);
  69418. this.clipPathManager.markUsed(displayable);
  69419. }
  69420. }
  69421. }
  69422. this.gradientManager.removeUnused();
  69423. this.clipPathManager.removeUnused();
  69424. this.shadowManager.removeUnused();
  69425. this._visibleList = newVisibleList;
  69426. },
  69427. _getDefs: function (isForceCreating) {
  69428. var svgRoot = this._svgRoot;
  69429. var defs = this._svgRoot.getElementsByTagName('defs');
  69430. if (defs.length === 0) {
  69431. // Not exist
  69432. if (isForceCreating) {
  69433. var defs = svgRoot.insertBefore(
  69434. createElement('defs'), // Create new tag
  69435. svgRoot.firstChild // Insert in the front of svg
  69436. );
  69437. if (!defs.contains) {
  69438. // IE doesn't support contains method
  69439. defs.contains = function (el) {
  69440. var children = defs.children;
  69441. if (!children) {
  69442. return false;
  69443. }
  69444. for (var i = children.length - 1; i >= 0; --i) {
  69445. if (children[i] === el) {
  69446. return true;
  69447. }
  69448. }
  69449. return false;
  69450. };
  69451. }
  69452. return defs;
  69453. }
  69454. else {
  69455. return null;
  69456. }
  69457. }
  69458. else {
  69459. return defs[0];
  69460. }
  69461. },
  69462. resize: function (width, height) {
  69463. var viewport = this._viewport;
  69464. // FIXME Why ?
  69465. viewport.style.display = 'none';
  69466. // Save input w/h
  69467. var opts = this._opts;
  69468. width != null && (opts.width = width);
  69469. height != null && (opts.height = height);
  69470. width = this._getSize(0);
  69471. height = this._getSize(1);
  69472. viewport.style.display = '';
  69473. if (this._width !== width || this._height !== height) {
  69474. this._width = width;
  69475. this._height = height;
  69476. var viewportStyle = viewport.style;
  69477. viewportStyle.width = width + 'px';
  69478. viewportStyle.height = height + 'px';
  69479. var svgRoot = this._svgRoot;
  69480. // Set width by 'svgRoot.width = width' is invalid
  69481. svgRoot.setAttribute('width', width);
  69482. svgRoot.setAttribute('height', height);
  69483. }
  69484. },
  69485. /**
  69486. * 获取绘图区域宽度
  69487. */
  69488. getWidth: function () {
  69489. return this._width;
  69490. },
  69491. /**
  69492. * 获取绘图区域高度
  69493. */
  69494. getHeight: function () {
  69495. return this._height;
  69496. },
  69497. _getSize: function (whIdx) {
  69498. var opts = this._opts;
  69499. var wh = ['width', 'height'][whIdx];
  69500. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  69501. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  69502. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  69503. if (opts[wh] != null && opts[wh] !== 'auto') {
  69504. return parseFloat(opts[wh]);
  69505. }
  69506. var root = this.root;
  69507. // IE8 does not support getComputedStyle, but it use VML.
  69508. var stl = document.defaultView.getComputedStyle(root);
  69509. return (
  69510. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  69511. - (parseInt10$2(stl[plt]) || 0)
  69512. - (parseInt10$2(stl[prb]) || 0)
  69513. ) | 0;
  69514. },
  69515. dispose: function () {
  69516. this.root.innerHTML = '';
  69517. this._svgRoot
  69518. = this._viewport
  69519. = this.storage
  69520. = null;
  69521. },
  69522. clear: function () {
  69523. if (this._viewport) {
  69524. this.root.removeChild(this._viewport);
  69525. }
  69526. },
  69527. pathToDataUrl: function () {
  69528. this.refresh();
  69529. var html = this._svgRoot.outerHTML;
  69530. return 'data:image/svg+xml;charset=UTF-8,' + html;
  69531. }
  69532. };
  69533. // Not supported methods
  69534. function createMethodNotSupport$1(method) {
  69535. return function () {
  69536. zrLog('In SVG mode painter not support method "' + method + '"');
  69537. };
  69538. }
  69539. // Unsuppoted methods
  69540. each$1([
  69541. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  69542. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  69543. 'toDataURL', 'pathToImage'
  69544. ], function (name) {
  69545. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  69546. });
  69547. registerPainter('svg', SVGPainter);
  69548. // Import all charts and components
  69549. exports.version = version;
  69550. exports.dependencies = dependencies;
  69551. exports.PRIORITY = PRIORITY;
  69552. exports.init = init;
  69553. exports.connect = connect;
  69554. exports.disConnect = disConnect;
  69555. exports.disconnect = disconnect;
  69556. exports.dispose = dispose;
  69557. exports.getInstanceByDom = getInstanceByDom;
  69558. exports.getInstanceById = getInstanceById;
  69559. exports.registerTheme = registerTheme;
  69560. exports.registerPreprocessor = registerPreprocessor;
  69561. exports.registerProcessor = registerProcessor;
  69562. exports.registerPostUpdate = registerPostUpdate;
  69563. exports.registerAction = registerAction;
  69564. exports.registerCoordinateSystem = registerCoordinateSystem;
  69565. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  69566. exports.registerLayout = registerLayout;
  69567. exports.registerVisual = registerVisual;
  69568. exports.registerLoading = registerLoading;
  69569. exports.extendComponentModel = extendComponentModel;
  69570. exports.extendComponentView = extendComponentView;
  69571. exports.extendSeriesModel = extendSeriesModel;
  69572. exports.extendChartView = extendChartView;
  69573. exports.setCanvasCreator = setCanvasCreator;
  69574. exports.registerMap = registerMap;
  69575. exports.getMap = getMap;
  69576. exports.dataTool = dataTool;
  69577. exports.zrender = zrender;
  69578. exports.graphic = graphic;
  69579. exports.number = number;
  69580. exports.format = format;
  69581. exports.throttle = throttle;
  69582. exports.helper = helper;
  69583. exports.matrix = matrix;
  69584. exports.vector = vector;
  69585. exports.color = color;
  69586. exports.parseGeoJSON = parseGeoJson$1;
  69587. exports.parseGeoJson = parseGeoJson;
  69588. exports.util = ecUtil;
  69589. exports.List = List;
  69590. exports.Model = Model;
  69591. exports.Axis = Axis;
  69592. exports.env = env$1;
  69593. })));
  69594. //# sourceMappingURL=echarts-en.js.map