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.
 
 
 
 
 
 

90303 regels
2.6 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. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. var env = {};
  59. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  60. // In Weixin Application
  61. env = {
  62. browser: {},
  63. os: {},
  64. node: false,
  65. wxa: true, // Weixin Application
  66. canvasSupported: true,
  67. svgSupported: false,
  68. touchEventsSupported: true
  69. };
  70. }
  71. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  72. // In worker
  73. env = {
  74. browser: {},
  75. os: {},
  76. node: false,
  77. worker: true,
  78. canvasSupported: true
  79. };
  80. }
  81. else if (typeof navigator === 'undefined') {
  82. // In node
  83. env = {
  84. browser: {},
  85. os: {},
  86. node: true,
  87. worker: false,
  88. // Assume canvas is supported
  89. canvasSupported: true,
  90. svgSupported: true
  91. };
  92. }
  93. else {
  94. env = detect(navigator.userAgent);
  95. }
  96. var env$1 = env;
  97. // Zepto.js
  98. // (c) 2010-2013 Thomas Fuchs
  99. // Zepto.js may be freely distributed under the MIT license.
  100. function detect(ua) {
  101. var os = {};
  102. var browser = {};
  103. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  104. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  105. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  106. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  107. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  108. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  109. // var touchpad = webos && ua.match(/TouchPad/);
  110. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  111. // var silk = ua.match(/Silk\/([\d._]+)/);
  112. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  113. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  114. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  115. // var playbook = ua.match(/PlayBook/);
  116. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  117. var firefox = ua.match(/Firefox\/([\d.]+)/);
  118. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  119. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  120. var ie = ua.match(/MSIE\s([\d.]+)/)
  121. // IE 11 Trident/7.0; rv:11.0
  122. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  123. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  124. var weChat = (/micromessenger/i).test(ua);
  125. // Todo: clean this up with a better OS/browser seperation:
  126. // - discern (more) between multiple browsers on android
  127. // - decide if kindle fire in silk mode is android or not
  128. // - Firefox on Android doesn't specify the Android version
  129. // - possibly devide in os, device and browser hashes
  130. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  131. // if (android) os.android = true, os.version = android[2];
  132. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  133. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  134. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  135. // if (webos) os.webos = true, os.version = webos[2];
  136. // if (touchpad) os.touchpad = true;
  137. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  138. // if (bb10) os.bb10 = true, os.version = bb10[2];
  139. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  140. // if (playbook) browser.playbook = true;
  141. // if (kindle) os.kindle = true, os.version = kindle[1];
  142. // if (silk) browser.silk = true, browser.version = silk[1];
  143. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  144. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  145. if (firefox) {
  146. browser.firefox = true;
  147. browser.version = firefox[1];
  148. }
  149. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  150. // if (webview) browser.webview = true;
  151. if (ie) {
  152. browser.ie = true;
  153. browser.version = ie[1];
  154. }
  155. if (edge) {
  156. browser.edge = true;
  157. browser.version = edge[1];
  158. }
  159. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  160. // not be set on win phone. So we do not consider Win Phone.
  161. if (weChat) {
  162. browser.weChat = true;
  163. }
  164. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  165. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  166. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  167. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  168. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  169. return {
  170. browser: browser,
  171. os: os,
  172. node: false,
  173. // 原生canvas支持,改极端点了
  174. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  175. canvasSupported: !!document.createElement('canvas').getContext,
  176. svgSupported: typeof SVGRect !== 'undefined',
  177. // works on most browsers
  178. // IE10/11 does not support touch event, and MS Edge supports them but not by
  179. // default, so we dont check navigator.maxTouchPoints for them here.
  180. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  181. // <http://caniuse.com/#search=pointer%20event>.
  182. pointerEventsSupported: 'onpointerdown' in window
  183. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  184. // events currently. So we dont use that on other browsers unless tested sufficiently.
  185. // Although IE 10 supports pointer event, it use old style and is different from the
  186. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  187. && (browser.edge || (browser.ie && browser.version >= 11))
  188. // passiveSupported: detectPassiveSupport()
  189. };
  190. }
  191. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  192. // function detectPassiveSupport() {
  193. // // Test via a getter in the options object to see if the passive property is accessed
  194. // var supportsPassive = false;
  195. // try {
  196. // var opts = Object.defineProperty({}, 'passive', {
  197. // get: function() {
  198. // supportsPassive = true;
  199. // }
  200. // });
  201. // window.addEventListener('testPassive', function() {}, opts);
  202. // } catch (e) {
  203. // }
  204. // return supportsPassive;
  205. // }
  206. /**
  207. * @module zrender/core/util
  208. */
  209. // 用于处理merge时无法遍历Date等对象的问题
  210. var BUILTIN_OBJECT = {
  211. '[object Function]': 1,
  212. '[object RegExp]': 1,
  213. '[object Date]': 1,
  214. '[object Error]': 1,
  215. '[object CanvasGradient]': 1,
  216. '[object CanvasPattern]': 1,
  217. // For node-canvas
  218. '[object Image]': 1,
  219. '[object Canvas]': 1
  220. };
  221. var TYPED_ARRAY = {
  222. '[object Int8Array]': 1,
  223. '[object Uint8Array]': 1,
  224. '[object Uint8ClampedArray]': 1,
  225. '[object Int16Array]': 1,
  226. '[object Uint16Array]': 1,
  227. '[object Int32Array]': 1,
  228. '[object Uint32Array]': 1,
  229. '[object Float32Array]': 1,
  230. '[object Float64Array]': 1
  231. };
  232. var objToString = Object.prototype.toString;
  233. var arrayProto = Array.prototype;
  234. var nativeForEach = arrayProto.forEach;
  235. var nativeFilter = arrayProto.filter;
  236. var nativeSlice = arrayProto.slice;
  237. var nativeMap = arrayProto.map;
  238. var nativeReduce = arrayProto.reduce;
  239. // Avoid assign to an exported variable, for transforming to cjs.
  240. var methods = {};
  241. function $override(name, fn) {
  242. // Clear ctx instance for different environment
  243. if (name === 'createCanvas') {
  244. _ctx = null;
  245. }
  246. methods[name] = fn;
  247. }
  248. /**
  249. * Those data types can be cloned:
  250. * Plain object, Array, TypedArray, number, string, null, undefined.
  251. * Those data types will be assgined using the orginal data:
  252. * BUILTIN_OBJECT
  253. * Instance of user defined class will be cloned to a plain object, without
  254. * properties in prototype.
  255. * Other data types is not supported (not sure what will happen).
  256. *
  257. * Caution: do not support clone Date, for performance consideration.
  258. * (There might be a large number of date in `series.data`).
  259. * So date should not be modified in and out of echarts.
  260. *
  261. * @param {*} source
  262. * @return {*} new
  263. */
  264. function clone(source) {
  265. if (source == null || typeof source != 'object') {
  266. return source;
  267. }
  268. var result = source;
  269. var typeStr = objToString.call(source);
  270. if (typeStr === '[object Array]') {
  271. if (!isPrimitive(source)) {
  272. result = [];
  273. for (var i = 0, len = source.length; i < len; i++) {
  274. result[i] = clone(source[i]);
  275. }
  276. }
  277. }
  278. else if (TYPED_ARRAY[typeStr]) {
  279. if (!isPrimitive(source)) {
  280. var Ctor = source.constructor;
  281. if (source.constructor.from) {
  282. result = Ctor.from(source);
  283. }
  284. else {
  285. result = new Ctor(source.length);
  286. for (var i = 0, len = source.length; i < len; i++) {
  287. result[i] = clone(source[i]);
  288. }
  289. }
  290. }
  291. }
  292. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  293. result = {};
  294. for (var key in source) {
  295. if (source.hasOwnProperty(key)) {
  296. result[key] = clone(source[key]);
  297. }
  298. }
  299. }
  300. return result;
  301. }
  302. /**
  303. * @memberOf module:zrender/core/util
  304. * @param {*} target
  305. * @param {*} source
  306. * @param {boolean} [overwrite=false]
  307. */
  308. function merge(target, source, overwrite) {
  309. // We should escapse that source is string
  310. // and enter for ... in ...
  311. if (!isObject$1(source) || !isObject$1(target)) {
  312. return overwrite ? clone(source) : target;
  313. }
  314. for (var key in source) {
  315. if (source.hasOwnProperty(key)) {
  316. var targetProp = target[key];
  317. var sourceProp = source[key];
  318. if (isObject$1(sourceProp)
  319. && isObject$1(targetProp)
  320. && !isArray(sourceProp)
  321. && !isArray(targetProp)
  322. && !isDom(sourceProp)
  323. && !isDom(targetProp)
  324. && !isBuiltInObject(sourceProp)
  325. && !isBuiltInObject(targetProp)
  326. && !isPrimitive(sourceProp)
  327. && !isPrimitive(targetProp)
  328. ) {
  329. // 如果需要递归覆盖,就递归调用merge
  330. merge(targetProp, sourceProp, overwrite);
  331. }
  332. else if (overwrite || !(key in target)) {
  333. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  334. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  335. target[key] = clone(source[key], true);
  336. }
  337. }
  338. }
  339. return target;
  340. }
  341. /**
  342. * @param {Array} targetAndSources The first item is target, and the rests are source.
  343. * @param {boolean} [overwrite=false]
  344. * @return {*} target
  345. */
  346. function mergeAll(targetAndSources, overwrite) {
  347. var result = targetAndSources[0];
  348. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  349. result = merge(result, targetAndSources[i], overwrite);
  350. }
  351. return result;
  352. }
  353. /**
  354. * @param {*} target
  355. * @param {*} source
  356. * @memberOf module:zrender/core/util
  357. */
  358. function extend(target, source) {
  359. for (var key in source) {
  360. if (source.hasOwnProperty(key)) {
  361. target[key] = source[key];
  362. }
  363. }
  364. return target;
  365. }
  366. /**
  367. * @param {*} target
  368. * @param {*} source
  369. * @param {boolean} [overlay=false]
  370. * @memberOf module:zrender/core/util
  371. */
  372. function defaults(target, source, overlay) {
  373. for (var key in source) {
  374. if (source.hasOwnProperty(key)
  375. && (overlay ? source[key] != null : target[key] == null)
  376. ) {
  377. target[key] = source[key];
  378. }
  379. }
  380. return target;
  381. }
  382. var createCanvas = function () {
  383. return methods.createCanvas();
  384. };
  385. methods.createCanvas = function () {
  386. return document.createElement('canvas');
  387. };
  388. // FIXME
  389. var _ctx;
  390. function getContext() {
  391. if (!_ctx) {
  392. // Use util.createCanvas instead of createCanvas
  393. // because createCanvas may be overwritten in different environment
  394. _ctx = createCanvas().getContext('2d');
  395. }
  396. return _ctx;
  397. }
  398. /**
  399. * 查询数组中元素的index
  400. * @memberOf module:zrender/core/util
  401. */
  402. function indexOf(array, value) {
  403. if (array) {
  404. if (array.indexOf) {
  405. return array.indexOf(value);
  406. }
  407. for (var i = 0, len = array.length; i < len; i++) {
  408. if (array[i] === value) {
  409. return i;
  410. }
  411. }
  412. }
  413. return -1;
  414. }
  415. /**
  416. * 构造类继承关系
  417. *
  418. * @memberOf module:zrender/core/util
  419. * @param {Function} clazz 源类
  420. * @param {Function} baseClazz 基类
  421. */
  422. function inherits(clazz, baseClazz) {
  423. var clazzPrototype = clazz.prototype;
  424. function F() {}
  425. F.prototype = baseClazz.prototype;
  426. clazz.prototype = new F();
  427. for (var prop in clazzPrototype) {
  428. clazz.prototype[prop] = clazzPrototype[prop];
  429. }
  430. clazz.prototype.constructor = clazz;
  431. clazz.superClass = baseClazz;
  432. }
  433. /**
  434. * @memberOf module:zrender/core/util
  435. * @param {Object|Function} target
  436. * @param {Object|Function} sorce
  437. * @param {boolean} overlay
  438. */
  439. function mixin(target, source, overlay) {
  440. target = 'prototype' in target ? target.prototype : target;
  441. source = 'prototype' in source ? source.prototype : source;
  442. defaults(target, source, overlay);
  443. }
  444. /**
  445. * Consider typed array.
  446. * @param {Array|TypedArray} data
  447. */
  448. function isArrayLike(data) {
  449. if (! data) {
  450. return;
  451. }
  452. if (typeof data == 'string') {
  453. return false;
  454. }
  455. return typeof data.length == 'number';
  456. }
  457. /**
  458. * 数组或对象遍历
  459. * @memberOf module:zrender/core/util
  460. * @param {Object|Array} obj
  461. * @param {Function} cb
  462. * @param {*} [context]
  463. */
  464. function each$1(obj, cb, context) {
  465. if (!(obj && cb)) {
  466. return;
  467. }
  468. if (obj.forEach && obj.forEach === nativeForEach) {
  469. obj.forEach(cb, context);
  470. }
  471. else if (obj.length === +obj.length) {
  472. for (var i = 0, len = obj.length; i < len; i++) {
  473. cb.call(context, obj[i], i, obj);
  474. }
  475. }
  476. else {
  477. for (var key in obj) {
  478. if (obj.hasOwnProperty(key)) {
  479. cb.call(context, obj[key], key, obj);
  480. }
  481. }
  482. }
  483. }
  484. /**
  485. * 数组映射
  486. * @memberOf module:zrender/core/util
  487. * @param {Array} obj
  488. * @param {Function} cb
  489. * @param {*} [context]
  490. * @return {Array}
  491. */
  492. function map(obj, cb, context) {
  493. if (!(obj && cb)) {
  494. return;
  495. }
  496. if (obj.map && obj.map === nativeMap) {
  497. return obj.map(cb, context);
  498. }
  499. else {
  500. var result = [];
  501. for (var i = 0, len = obj.length; i < len; i++) {
  502. result.push(cb.call(context, obj[i], i, obj));
  503. }
  504. return result;
  505. }
  506. }
  507. /**
  508. * @memberOf module:zrender/core/util
  509. * @param {Array} obj
  510. * @param {Function} cb
  511. * @param {Object} [memo]
  512. * @param {*} [context]
  513. * @return {Array}
  514. */
  515. function reduce(obj, cb, memo, context) {
  516. if (!(obj && cb)) {
  517. return;
  518. }
  519. if (obj.reduce && obj.reduce === nativeReduce) {
  520. return obj.reduce(cb, memo, context);
  521. }
  522. else {
  523. for (var i = 0, len = obj.length; i < len; i++) {
  524. memo = cb.call(context, memo, obj[i], i, obj);
  525. }
  526. return memo;
  527. }
  528. }
  529. /**
  530. * 数组过滤
  531. * @memberOf module:zrender/core/util
  532. * @param {Array} obj
  533. * @param {Function} cb
  534. * @param {*} [context]
  535. * @return {Array}
  536. */
  537. function filter(obj, cb, context) {
  538. if (!(obj && cb)) {
  539. return;
  540. }
  541. if (obj.filter && obj.filter === nativeFilter) {
  542. return obj.filter(cb, context);
  543. }
  544. else {
  545. var result = [];
  546. for (var i = 0, len = obj.length; i < len; i++) {
  547. if (cb.call(context, obj[i], i, obj)) {
  548. result.push(obj[i]);
  549. }
  550. }
  551. return result;
  552. }
  553. }
  554. /**
  555. * 数组项查找
  556. * @memberOf module:zrender/core/util
  557. * @param {Array} obj
  558. * @param {Function} cb
  559. * @param {*} [context]
  560. * @return {*}
  561. */
  562. function find(obj, cb, context) {
  563. if (!(obj && cb)) {
  564. return;
  565. }
  566. for (var i = 0, len = obj.length; i < len; i++) {
  567. if (cb.call(context, obj[i], i, obj)) {
  568. return obj[i];
  569. }
  570. }
  571. }
  572. /**
  573. * @memberOf module:zrender/core/util
  574. * @param {Function} func
  575. * @param {*} context
  576. * @return {Function}
  577. */
  578. function bind(func, context) {
  579. var args = nativeSlice.call(arguments, 2);
  580. return function () {
  581. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  582. };
  583. }
  584. /**
  585. * @memberOf module:zrender/core/util
  586. * @param {Function} func
  587. * @return {Function}
  588. */
  589. function curry(func) {
  590. var args = nativeSlice.call(arguments, 1);
  591. return function () {
  592. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  593. };
  594. }
  595. /**
  596. * @memberOf module:zrender/core/util
  597. * @param {*} value
  598. * @return {boolean}
  599. */
  600. function isArray(value) {
  601. return objToString.call(value) === '[object Array]';
  602. }
  603. /**
  604. * @memberOf module:zrender/core/util
  605. * @param {*} value
  606. * @return {boolean}
  607. */
  608. function isFunction$1(value) {
  609. return typeof value === 'function';
  610. }
  611. /**
  612. * @memberOf module:zrender/core/util
  613. * @param {*} value
  614. * @return {boolean}
  615. */
  616. function isString(value) {
  617. return objToString.call(value) === '[object String]';
  618. }
  619. /**
  620. * @memberOf module:zrender/core/util
  621. * @param {*} value
  622. * @return {boolean}
  623. */
  624. function isObject$1(value) {
  625. // Avoid a V8 JIT bug in Chrome 19-20.
  626. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  627. var type = typeof value;
  628. return type === 'function' || (!!value && type == 'object');
  629. }
  630. /**
  631. * @memberOf module:zrender/core/util
  632. * @param {*} value
  633. * @return {boolean}
  634. */
  635. function isBuiltInObject(value) {
  636. return !!BUILTIN_OBJECT[objToString.call(value)];
  637. }
  638. /**
  639. * @memberOf module:zrender/core/util
  640. * @param {*} value
  641. * @return {boolean}
  642. */
  643. function isTypedArray(value) {
  644. return !!TYPED_ARRAY[objToString.call(value)];
  645. }
  646. /**
  647. * @memberOf module:zrender/core/util
  648. * @param {*} value
  649. * @return {boolean}
  650. */
  651. function isDom(value) {
  652. return typeof value === 'object'
  653. && typeof value.nodeType === 'number'
  654. && typeof value.ownerDocument === 'object';
  655. }
  656. /**
  657. * Whether is exactly NaN. Notice isNaN('a') returns true.
  658. * @param {*} value
  659. * @return {boolean}
  660. */
  661. function eqNaN(value) {
  662. return value !== value;
  663. }
  664. /**
  665. * If value1 is not null, then return value1, otherwise judget rest of values.
  666. * Low performance.
  667. * @memberOf module:zrender/core/util
  668. * @return {*} Final value
  669. */
  670. function retrieve(values) {
  671. for (var i = 0, len = arguments.length; i < len; i++) {
  672. if (arguments[i] != null) {
  673. return arguments[i];
  674. }
  675. }
  676. }
  677. function retrieve2(value0, value1) {
  678. return value0 != null
  679. ? value0
  680. : value1;
  681. }
  682. function retrieve3(value0, value1, value2) {
  683. return value0 != null
  684. ? value0
  685. : value1 != null
  686. ? value1
  687. : value2;
  688. }
  689. /**
  690. * @memberOf module:zrender/core/util
  691. * @param {Array} arr
  692. * @param {number} startIndex
  693. * @param {number} endIndex
  694. * @return {Array}
  695. */
  696. function slice() {
  697. return Function.call.apply(nativeSlice, arguments);
  698. }
  699. /**
  700. * Normalize css liked array configuration
  701. * e.g.
  702. * 3 => [3, 3, 3, 3]
  703. * [4, 2] => [4, 2, 4, 2]
  704. * [4, 3, 2] => [4, 3, 2, 3]
  705. * @param {number|Array.<number>} val
  706. * @return {Array.<number>}
  707. */
  708. function normalizeCssArray(val) {
  709. if (typeof (val) === 'number') {
  710. return [val, val, val, val];
  711. }
  712. var len = val.length;
  713. if (len === 2) {
  714. // vertical | horizontal
  715. return [val[0], val[1], val[0], val[1]];
  716. }
  717. else if (len === 3) {
  718. // top | horizontal | bottom
  719. return [val[0], val[1], val[2], val[1]];
  720. }
  721. return val;
  722. }
  723. /**
  724. * @memberOf module:zrender/core/util
  725. * @param {boolean} condition
  726. * @param {string} message
  727. */
  728. function assert$1(condition, message) {
  729. if (!condition) {
  730. throw new Error(message);
  731. }
  732. }
  733. /**
  734. * @memberOf module:zrender/core/util
  735. * @param {string} str string to be trimed
  736. * @return {string} trimed string
  737. */
  738. function trim(str) {
  739. if (str == null) {
  740. return null;
  741. }
  742. else if (typeof str.trim === 'function') {
  743. return str.trim();
  744. }
  745. else {
  746. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  747. }
  748. }
  749. var primitiveKey = '__ec_primitive__';
  750. /**
  751. * Set an object as primitive to be ignored traversing children in clone or merge
  752. */
  753. function setAsPrimitive(obj) {
  754. obj[primitiveKey] = true;
  755. }
  756. function isPrimitive(obj) {
  757. return obj[primitiveKey];
  758. }
  759. /**
  760. * @constructor
  761. * @param {Object} obj Only apply `ownProperty`.
  762. */
  763. function HashMap(obj) {
  764. var isArr = isArray(obj);
  765. var thisMap = this;
  766. (obj instanceof HashMap)
  767. ? obj.each(visit)
  768. : (obj && each$1(obj, visit));
  769. function visit(value, key) {
  770. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  771. }
  772. }
  773. // Add prefix to avoid conflict with Object.prototype.
  774. HashMap.prototype = {
  775. constructor: HashMap,
  776. // Do not provide `has` method to avoid defining what is `has`.
  777. // (We usually treat `null` and `undefined` as the same, different
  778. // from ES6 Map).
  779. get: function (key) {
  780. return this.hasOwnProperty(key) ? this[key] : null;
  781. },
  782. set: function (key, value) {
  783. // Comparing with invocation chaining, `return value` is more commonly
  784. // used in this case: `var someVal = map.set('a', genVal());`
  785. return (this[key] = value);
  786. },
  787. // Although util.each can be performed on this hashMap directly, user
  788. // should not use the exposed keys, who are prefixed.
  789. each: function (cb, context) {
  790. context !== void 0 && (cb = bind(cb, context));
  791. for (var key in this) {
  792. this.hasOwnProperty(key) && cb(this[key], key);
  793. }
  794. },
  795. // Do not use this method if performance sensitive.
  796. removeKey: function (key) {
  797. delete this[key];
  798. }
  799. };
  800. function createHashMap(obj) {
  801. return new HashMap(obj);
  802. }
  803. function concatArray(a, b) {
  804. var newArray = new a.constructor(a.length + b.length);
  805. for (var i = 0; i < a.length; i++) {
  806. newArray[i] = a[i];
  807. }
  808. var offset = a.length;
  809. for (i = 0; i < b.length; i++) {
  810. newArray[i + offset] = b[i];
  811. }
  812. return newArray;
  813. }
  814. function noop() {}
  815. var zrUtil = (Object.freeze || Object)({
  816. $override: $override,
  817. clone: clone,
  818. merge: merge,
  819. mergeAll: mergeAll,
  820. extend: extend,
  821. defaults: defaults,
  822. createCanvas: createCanvas,
  823. getContext: getContext,
  824. indexOf: indexOf,
  825. inherits: inherits,
  826. mixin: mixin,
  827. isArrayLike: isArrayLike,
  828. each: each$1,
  829. map: map,
  830. reduce: reduce,
  831. filter: filter,
  832. find: find,
  833. bind: bind,
  834. curry: curry,
  835. isArray: isArray,
  836. isFunction: isFunction$1,
  837. isString: isString,
  838. isObject: isObject$1,
  839. isBuiltInObject: isBuiltInObject,
  840. isTypedArray: isTypedArray,
  841. isDom: isDom,
  842. eqNaN: eqNaN,
  843. retrieve: retrieve,
  844. retrieve2: retrieve2,
  845. retrieve3: retrieve3,
  846. slice: slice,
  847. normalizeCssArray: normalizeCssArray,
  848. assert: assert$1,
  849. trim: trim,
  850. setAsPrimitive: setAsPrimitive,
  851. isPrimitive: isPrimitive,
  852. createHashMap: createHashMap,
  853. concatArray: concatArray,
  854. noop: noop
  855. });
  856. var ArrayCtor = typeof Float32Array === 'undefined'
  857. ? Array
  858. : Float32Array;
  859. /**
  860. * 创建一个向量
  861. * @param {number} [x=0]
  862. * @param {number} [y=0]
  863. * @return {Vector2}
  864. */
  865. function create(x, y) {
  866. var out = new ArrayCtor(2);
  867. if (x == null) {
  868. x = 0;
  869. }
  870. if (y == null) {
  871. y = 0;
  872. }
  873. out[0] = x;
  874. out[1] = y;
  875. return out;
  876. }
  877. /**
  878. * 复制向量数据
  879. * @param {Vector2} out
  880. * @param {Vector2} v
  881. * @return {Vector2}
  882. */
  883. function copy(out, v) {
  884. out[0] = v[0];
  885. out[1] = v[1];
  886. return out;
  887. }
  888. /**
  889. * 克隆一个向量
  890. * @param {Vector2} v
  891. * @return {Vector2}
  892. */
  893. function clone$1(v) {
  894. var out = new ArrayCtor(2);
  895. out[0] = v[0];
  896. out[1] = v[1];
  897. return out;
  898. }
  899. /**
  900. * 设置向量的两个项
  901. * @param {Vector2} out
  902. * @param {number} a
  903. * @param {number} b
  904. * @return {Vector2} 结果
  905. */
  906. function set(out, a, b) {
  907. out[0] = a;
  908. out[1] = b;
  909. return out;
  910. }
  911. /**
  912. * 向量相加
  913. * @param {Vector2} out
  914. * @param {Vector2} v1
  915. * @param {Vector2} v2
  916. */
  917. function add(out, v1, v2) {
  918. out[0] = v1[0] + v2[0];
  919. out[1] = v1[1] + v2[1];
  920. return out;
  921. }
  922. /**
  923. * 向量缩放后相加
  924. * @param {Vector2} out
  925. * @param {Vector2} v1
  926. * @param {Vector2} v2
  927. * @param {number} a
  928. */
  929. function scaleAndAdd(out, v1, v2, a) {
  930. out[0] = v1[0] + v2[0] * a;
  931. out[1] = v1[1] + v2[1] * a;
  932. return out;
  933. }
  934. /**
  935. * 向量相减
  936. * @param {Vector2} out
  937. * @param {Vector2} v1
  938. * @param {Vector2} v2
  939. */
  940. function sub(out, v1, v2) {
  941. out[0] = v1[0] - v2[0];
  942. out[1] = v1[1] - v2[1];
  943. return out;
  944. }
  945. /**
  946. * 向量长度
  947. * @param {Vector2} v
  948. * @return {number}
  949. */
  950. function len(v) {
  951. return Math.sqrt(lenSquare(v));
  952. }
  953. var length = len; // jshint ignore:line
  954. /**
  955. * 向量长度平方
  956. * @param {Vector2} v
  957. * @return {number}
  958. */
  959. function lenSquare(v) {
  960. return v[0] * v[0] + v[1] * v[1];
  961. }
  962. var lengthSquare = lenSquare;
  963. /**
  964. * 向量乘法
  965. * @param {Vector2} out
  966. * @param {Vector2} v1
  967. * @param {Vector2} v2
  968. */
  969. function mul(out, v1, v2) {
  970. out[0] = v1[0] * v2[0];
  971. out[1] = v1[1] * v2[1];
  972. return out;
  973. }
  974. /**
  975. * 向量除法
  976. * @param {Vector2} out
  977. * @param {Vector2} v1
  978. * @param {Vector2} v2
  979. */
  980. function div(out, v1, v2) {
  981. out[0] = v1[0] / v2[0];
  982. out[1] = v1[1] / v2[1];
  983. return out;
  984. }
  985. /**
  986. * 向量点乘
  987. * @param {Vector2} v1
  988. * @param {Vector2} v2
  989. * @return {number}
  990. */
  991. function dot(v1, v2) {
  992. return v1[0] * v2[0] + v1[1] * v2[1];
  993. }
  994. /**
  995. * 向量缩放
  996. * @param {Vector2} out
  997. * @param {Vector2} v
  998. * @param {number} s
  999. */
  1000. function scale(out, v, s) {
  1001. out[0] = v[0] * s;
  1002. out[1] = v[1] * s;
  1003. return out;
  1004. }
  1005. /**
  1006. * 向量归一化
  1007. * @param {Vector2} out
  1008. * @param {Vector2} v
  1009. */
  1010. function normalize(out, v) {
  1011. var d = len(v);
  1012. if (d === 0) {
  1013. out[0] = 0;
  1014. out[1] = 0;
  1015. }
  1016. else {
  1017. out[0] = v[0] / d;
  1018. out[1] = v[1] / d;
  1019. }
  1020. return out;
  1021. }
  1022. /**
  1023. * 计算向量间距离
  1024. * @param {Vector2} v1
  1025. * @param {Vector2} v2
  1026. * @return {number}
  1027. */
  1028. function distance(v1, v2) {
  1029. return Math.sqrt(
  1030. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1031. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1032. );
  1033. }
  1034. var dist = distance;
  1035. /**
  1036. * 向量距离平方
  1037. * @param {Vector2} v1
  1038. * @param {Vector2} v2
  1039. * @return {number}
  1040. */
  1041. function distanceSquare(v1, v2) {
  1042. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1043. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1044. }
  1045. var distSquare = distanceSquare;
  1046. /**
  1047. * 求负向量
  1048. * @param {Vector2} out
  1049. * @param {Vector2} v
  1050. */
  1051. function negate(out, v) {
  1052. out[0] = -v[0];
  1053. out[1] = -v[1];
  1054. return out;
  1055. }
  1056. /**
  1057. * 插值两个点
  1058. * @param {Vector2} out
  1059. * @param {Vector2} v1
  1060. * @param {Vector2} v2
  1061. * @param {number} t
  1062. */
  1063. function lerp(out, v1, v2, t) {
  1064. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1065. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1066. return out;
  1067. }
  1068. /**
  1069. * 矩阵左乘向量
  1070. * @param {Vector2} out
  1071. * @param {Vector2} v
  1072. * @param {Vector2} m
  1073. */
  1074. function applyTransform(out, v, m) {
  1075. var x = v[0];
  1076. var y = v[1];
  1077. out[0] = m[0] * x + m[2] * y + m[4];
  1078. out[1] = m[1] * x + m[3] * y + m[5];
  1079. return out;
  1080. }
  1081. /**
  1082. * 求两个向量最小值
  1083. * @param {Vector2} out
  1084. * @param {Vector2} v1
  1085. * @param {Vector2} v2
  1086. */
  1087. function min(out, v1, v2) {
  1088. out[0] = Math.min(v1[0], v2[0]);
  1089. out[1] = Math.min(v1[1], v2[1]);
  1090. return out;
  1091. }
  1092. /**
  1093. * 求两个向量最大值
  1094. * @param {Vector2} out
  1095. * @param {Vector2} v1
  1096. * @param {Vector2} v2
  1097. */
  1098. function max(out, v1, v2) {
  1099. out[0] = Math.max(v1[0], v2[0]);
  1100. out[1] = Math.max(v1[1], v2[1]);
  1101. return out;
  1102. }
  1103. var vector = (Object.freeze || Object)({
  1104. create: create,
  1105. copy: copy,
  1106. clone: clone$1,
  1107. set: set,
  1108. add: add,
  1109. scaleAndAdd: scaleAndAdd,
  1110. sub: sub,
  1111. len: len,
  1112. length: length,
  1113. lenSquare: lenSquare,
  1114. lengthSquare: lengthSquare,
  1115. mul: mul,
  1116. div: div,
  1117. dot: dot,
  1118. scale: scale,
  1119. normalize: normalize,
  1120. distance: distance,
  1121. dist: dist,
  1122. distanceSquare: distanceSquare,
  1123. distSquare: distSquare,
  1124. negate: negate,
  1125. lerp: lerp,
  1126. applyTransform: applyTransform,
  1127. min: min,
  1128. max: max
  1129. });
  1130. // TODO Draggable for group
  1131. // FIXME Draggable on element which has parent rotation or scale
  1132. function Draggable() {
  1133. this.on('mousedown', this._dragStart, this);
  1134. this.on('mousemove', this._drag, this);
  1135. this.on('mouseup', this._dragEnd, this);
  1136. this.on('globalout', this._dragEnd, this);
  1137. // this._dropTarget = null;
  1138. // this._draggingTarget = null;
  1139. // this._x = 0;
  1140. // this._y = 0;
  1141. }
  1142. Draggable.prototype = {
  1143. constructor: Draggable,
  1144. _dragStart: function (e) {
  1145. var draggingTarget = e.target;
  1146. if (draggingTarget && draggingTarget.draggable) {
  1147. this._draggingTarget = draggingTarget;
  1148. draggingTarget.dragging = true;
  1149. this._x = e.offsetX;
  1150. this._y = e.offsetY;
  1151. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1152. }
  1153. },
  1154. _drag: function (e) {
  1155. var draggingTarget = this._draggingTarget;
  1156. if (draggingTarget) {
  1157. var x = e.offsetX;
  1158. var y = e.offsetY;
  1159. var dx = x - this._x;
  1160. var dy = y - this._y;
  1161. this._x = x;
  1162. this._y = y;
  1163. draggingTarget.drift(dx, dy, e);
  1164. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1165. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1166. var lastDropTarget = this._dropTarget;
  1167. this._dropTarget = dropTarget;
  1168. if (draggingTarget !== dropTarget) {
  1169. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1170. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1171. }
  1172. if (dropTarget && dropTarget !== lastDropTarget) {
  1173. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1174. }
  1175. }
  1176. }
  1177. },
  1178. _dragEnd: function (e) {
  1179. var draggingTarget = this._draggingTarget;
  1180. if (draggingTarget) {
  1181. draggingTarget.dragging = false;
  1182. }
  1183. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1184. if (this._dropTarget) {
  1185. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1186. }
  1187. this._draggingTarget = null;
  1188. this._dropTarget = null;
  1189. }
  1190. };
  1191. function param(target, e) {
  1192. return {target: target, topTarget: e && e.topTarget};
  1193. }
  1194. /**
  1195. * 事件扩展
  1196. * @module zrender/mixin/Eventful
  1197. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1198. * pissang (https://www.github.com/pissang)
  1199. */
  1200. var arrySlice = Array.prototype.slice;
  1201. /**
  1202. * 事件分发器
  1203. * @alias module:zrender/mixin/Eventful
  1204. * @constructor
  1205. */
  1206. var Eventful = function () {
  1207. this._$handlers = {};
  1208. };
  1209. Eventful.prototype = {
  1210. constructor: Eventful,
  1211. /**
  1212. * 单次触发绑定,trigger后销毁
  1213. *
  1214. * @param {string} event 事件名
  1215. * @param {Function} handler 响应函数
  1216. * @param {Object} context
  1217. */
  1218. one: function (event, handler, context) {
  1219. var _h = this._$handlers;
  1220. if (!handler || !event) {
  1221. return this;
  1222. }
  1223. if (!_h[event]) {
  1224. _h[event] = [];
  1225. }
  1226. for (var i = 0; i < _h[event].length; i++) {
  1227. if (_h[event][i].h === handler) {
  1228. return this;
  1229. }
  1230. }
  1231. _h[event].push({
  1232. h: handler,
  1233. one: true,
  1234. ctx: context || this
  1235. });
  1236. return this;
  1237. },
  1238. /**
  1239. * 绑定事件
  1240. * @param {string} event 事件名
  1241. * @param {Function} handler 事件处理函数
  1242. * @param {Object} [context]
  1243. */
  1244. on: function (event, handler, context) {
  1245. var _h = this._$handlers;
  1246. if (!handler || !event) {
  1247. return this;
  1248. }
  1249. if (!_h[event]) {
  1250. _h[event] = [];
  1251. }
  1252. for (var i = 0; i < _h[event].length; i++) {
  1253. if (_h[event][i].h === handler) {
  1254. return this;
  1255. }
  1256. }
  1257. _h[event].push({
  1258. h: handler,
  1259. one: false,
  1260. ctx: context || this
  1261. });
  1262. return this;
  1263. },
  1264. /**
  1265. * 是否绑定了事件
  1266. * @param {string} event
  1267. * @return {boolean}
  1268. */
  1269. isSilent: function (event) {
  1270. var _h = this._$handlers;
  1271. return _h[event] && _h[event].length;
  1272. },
  1273. /**
  1274. * 解绑事件
  1275. * @param {string} event 事件名
  1276. * @param {Function} [handler] 事件处理函数
  1277. */
  1278. off: function (event, handler) {
  1279. var _h = this._$handlers;
  1280. if (!event) {
  1281. this._$handlers = {};
  1282. return this;
  1283. }
  1284. if (handler) {
  1285. if (_h[event]) {
  1286. var newList = [];
  1287. for (var i = 0, l = _h[event].length; i < l; i++) {
  1288. if (_h[event][i]['h'] != handler) {
  1289. newList.push(_h[event][i]);
  1290. }
  1291. }
  1292. _h[event] = newList;
  1293. }
  1294. if (_h[event] && _h[event].length === 0) {
  1295. delete _h[event];
  1296. }
  1297. }
  1298. else {
  1299. delete _h[event];
  1300. }
  1301. return this;
  1302. },
  1303. /**
  1304. * 事件分发
  1305. *
  1306. * @param {string} type 事件类型
  1307. */
  1308. trigger: function (type) {
  1309. if (this._$handlers[type]) {
  1310. var args = arguments;
  1311. var argLen = args.length;
  1312. if (argLen > 3) {
  1313. args = arrySlice.call(args, 1);
  1314. }
  1315. var _h = this._$handlers[type];
  1316. var len = _h.length;
  1317. for (var i = 0; i < len;) {
  1318. // Optimize advise from backbone
  1319. switch (argLen) {
  1320. case 1:
  1321. _h[i]['h'].call(_h[i]['ctx']);
  1322. break;
  1323. case 2:
  1324. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1325. break;
  1326. case 3:
  1327. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1328. break;
  1329. default:
  1330. // have more than 2 given arguments
  1331. _h[i]['h'].apply(_h[i]['ctx'], args);
  1332. break;
  1333. }
  1334. if (_h[i]['one']) {
  1335. _h.splice(i, 1);
  1336. len--;
  1337. }
  1338. else {
  1339. i++;
  1340. }
  1341. }
  1342. }
  1343. return this;
  1344. },
  1345. /**
  1346. * 带有context的事件分发, 最后一个参数是事件回调的context
  1347. * @param {string} type 事件类型
  1348. */
  1349. triggerWithContext: function (type) {
  1350. if (this._$handlers[type]) {
  1351. var args = arguments;
  1352. var argLen = args.length;
  1353. if (argLen > 4) {
  1354. args = arrySlice.call(args, 1, args.length - 1);
  1355. }
  1356. var ctx = args[args.length - 1];
  1357. var _h = this._$handlers[type];
  1358. var len = _h.length;
  1359. for (var i = 0; i < len;) {
  1360. // Optimize advise from backbone
  1361. switch (argLen) {
  1362. case 1:
  1363. _h[i]['h'].call(ctx);
  1364. break;
  1365. case 2:
  1366. _h[i]['h'].call(ctx, args[1]);
  1367. break;
  1368. case 3:
  1369. _h[i]['h'].call(ctx, args[1], args[2]);
  1370. break;
  1371. default:
  1372. // have more than 2 given arguments
  1373. _h[i]['h'].apply(ctx, args);
  1374. break;
  1375. }
  1376. if (_h[i]['one']) {
  1377. _h.splice(i, 1);
  1378. len--;
  1379. }
  1380. else {
  1381. i++;
  1382. }
  1383. }
  1384. }
  1385. return this;
  1386. }
  1387. };
  1388. var SILENT = 'silent';
  1389. function makeEventPacket(eveType, targetInfo, event) {
  1390. return {
  1391. type: eveType,
  1392. event: event,
  1393. // target can only be an element that is not silent.
  1394. target: targetInfo.target,
  1395. // topTarget can be a silent element.
  1396. topTarget: targetInfo.topTarget,
  1397. cancelBubble: false,
  1398. offsetX: event.zrX,
  1399. offsetY: event.zrY,
  1400. gestureEvent: event.gestureEvent,
  1401. pinchX: event.pinchX,
  1402. pinchY: event.pinchY,
  1403. pinchScale: event.pinchScale,
  1404. wheelDelta: event.zrDelta,
  1405. zrByTouch: event.zrByTouch,
  1406. which: event.which
  1407. };
  1408. }
  1409. function EmptyProxy () {}
  1410. EmptyProxy.prototype.dispose = function () {};
  1411. var handlerNames = [
  1412. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1413. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1414. ];
  1415. /**
  1416. * @alias module:zrender/Handler
  1417. * @constructor
  1418. * @extends module:zrender/mixin/Eventful
  1419. * @param {module:zrender/Storage} storage Storage instance.
  1420. * @param {module:zrender/Painter} painter Painter instance.
  1421. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1422. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1423. */
  1424. var Handler = function(storage, painter, proxy, painterRoot) {
  1425. Eventful.call(this);
  1426. this.storage = storage;
  1427. this.painter = painter;
  1428. this.painterRoot = painterRoot;
  1429. proxy = proxy || new EmptyProxy();
  1430. /**
  1431. * Proxy of event. can be Dom, WebGLSurface, etc.
  1432. */
  1433. this.proxy = null;
  1434. /**
  1435. * {target, topTarget, x, y}
  1436. * @private
  1437. * @type {Object}
  1438. */
  1439. this._hovered = {};
  1440. /**
  1441. * @private
  1442. * @type {Date}
  1443. */
  1444. this._lastTouchMoment;
  1445. /**
  1446. * @private
  1447. * @type {number}
  1448. */
  1449. this._lastX;
  1450. /**
  1451. * @private
  1452. * @type {number}
  1453. */
  1454. this._lastY;
  1455. Draggable.call(this);
  1456. this.setHandlerProxy(proxy);
  1457. };
  1458. Handler.prototype = {
  1459. constructor: Handler,
  1460. setHandlerProxy: function (proxy) {
  1461. if (this.proxy) {
  1462. this.proxy.dispose();
  1463. }
  1464. if (proxy) {
  1465. each$1(handlerNames, function (name) {
  1466. proxy.on && proxy.on(name, this[name], this);
  1467. }, this);
  1468. // Attach handler
  1469. proxy.handler = this;
  1470. }
  1471. this.proxy = proxy;
  1472. },
  1473. mousemove: function (event) {
  1474. var x = event.zrX;
  1475. var y = event.zrY;
  1476. var lastHovered = this._hovered;
  1477. var lastHoveredTarget = lastHovered.target;
  1478. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1479. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1480. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1481. // See #6198.
  1482. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1483. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1484. lastHoveredTarget = lastHovered.target;
  1485. }
  1486. var hovered = this._hovered = this.findHover(x, y);
  1487. var hoveredTarget = hovered.target;
  1488. var proxy = this.proxy;
  1489. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1490. // Mouse out on previous hovered element
  1491. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1492. this.dispatchToElement(lastHovered, 'mouseout', event);
  1493. }
  1494. // Mouse moving on one element
  1495. this.dispatchToElement(hovered, 'mousemove', event);
  1496. // Mouse over on a new element
  1497. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1498. this.dispatchToElement(hovered, 'mouseover', event);
  1499. }
  1500. },
  1501. mouseout: function (event) {
  1502. this.dispatchToElement(this._hovered, 'mouseout', event);
  1503. // There might be some doms created by upper layer application
  1504. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1505. // dom created by echarts), where 'globalout' event should not
  1506. // be triggered when mouse enters these doms. (But 'mouseout'
  1507. // should be triggered at the original hovered element as usual).
  1508. var element = event.toElement || event.relatedTarget;
  1509. var innerDom;
  1510. do {
  1511. element = element && element.parentNode;
  1512. }
  1513. while (element && element.nodeType != 9 && !(
  1514. innerDom = element === this.painterRoot
  1515. ));
  1516. !innerDom && this.trigger('globalout', {event: event});
  1517. },
  1518. /**
  1519. * Resize
  1520. */
  1521. resize: function (event) {
  1522. this._hovered = {};
  1523. },
  1524. /**
  1525. * Dispatch event
  1526. * @param {string} eventName
  1527. * @param {event=} eventArgs
  1528. */
  1529. dispatch: function (eventName, eventArgs) {
  1530. var handler = this[eventName];
  1531. handler && handler.call(this, eventArgs);
  1532. },
  1533. /**
  1534. * Dispose
  1535. */
  1536. dispose: function () {
  1537. this.proxy.dispose();
  1538. this.storage =
  1539. this.proxy =
  1540. this.painter = null;
  1541. },
  1542. /**
  1543. * 设置默认的cursor style
  1544. * @param {string} [cursorStyle='default'] 例如 crosshair
  1545. */
  1546. setCursorStyle: function (cursorStyle) {
  1547. var proxy = this.proxy;
  1548. proxy.setCursor && proxy.setCursor(cursorStyle);
  1549. },
  1550. /**
  1551. * 事件分发代理
  1552. *
  1553. * @private
  1554. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1555. * @param {string} eventName 事件名称
  1556. * @param {Object} event 事件对象
  1557. */
  1558. dispatchToElement: function (targetInfo, eventName, event) {
  1559. targetInfo = targetInfo || {};
  1560. var el = targetInfo.target;
  1561. if (el && el.silent) {
  1562. return;
  1563. }
  1564. var eventHandler = 'on' + eventName;
  1565. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1566. while (el) {
  1567. el[eventHandler]
  1568. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1569. el.trigger(eventName, eventPacket);
  1570. el = el.parent;
  1571. if (eventPacket.cancelBubble) {
  1572. break;
  1573. }
  1574. }
  1575. if (!eventPacket.cancelBubble) {
  1576. // 冒泡到顶级 zrender 对象
  1577. this.trigger(eventName, eventPacket);
  1578. // 分发事件到用户自定义层
  1579. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1580. this.painter && this.painter.eachOtherLayer(function (layer) {
  1581. if (typeof(layer[eventHandler]) == 'function') {
  1582. layer[eventHandler].call(layer, eventPacket);
  1583. }
  1584. if (layer.trigger) {
  1585. layer.trigger(eventName, eventPacket);
  1586. }
  1587. });
  1588. }
  1589. },
  1590. /**
  1591. * @private
  1592. * @param {number} x
  1593. * @param {number} y
  1594. * @param {module:zrender/graphic/Displayable} exclude
  1595. * @return {model:zrender/Element}
  1596. * @method
  1597. */
  1598. findHover: function(x, y, exclude) {
  1599. var list = this.storage.getDisplayList();
  1600. var out = {x: x, y: y};
  1601. for (var i = list.length - 1; i >= 0 ; i--) {
  1602. var hoverCheckResult;
  1603. if (list[i] !== exclude
  1604. // getDisplayList may include ignored item in VML mode
  1605. && !list[i].ignore
  1606. && (hoverCheckResult = isHover(list[i], x, y))
  1607. ) {
  1608. !out.topTarget && (out.topTarget = list[i]);
  1609. if (hoverCheckResult !== SILENT) {
  1610. out.target = list[i];
  1611. break;
  1612. }
  1613. }
  1614. }
  1615. return out;
  1616. }
  1617. };
  1618. // Common handlers
  1619. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1620. Handler.prototype[name] = function (event) {
  1621. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1622. var hovered = this.findHover(event.zrX, event.zrY);
  1623. var hoveredTarget = hovered.target;
  1624. if (name === 'mousedown') {
  1625. this._downEl = hoveredTarget;
  1626. this._downPoint = [event.zrX, event.zrY];
  1627. // In case click triggered before mouseup
  1628. this._upEl = hoveredTarget;
  1629. }
  1630. else if (name === 'mouseup') {
  1631. this._upEl = hoveredTarget;
  1632. }
  1633. else if (name === 'click') {
  1634. if (this._downEl !== this._upEl
  1635. // Original click event is triggered on the whole canvas element,
  1636. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1637. // which should be filtered, otherwise it will bring trouble to
  1638. // pan and zoom.
  1639. || !this._downPoint
  1640. // Arbitrary value
  1641. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1642. ) {
  1643. return;
  1644. }
  1645. this._downPoint = null;
  1646. }
  1647. this.dispatchToElement(hovered, name, event);
  1648. };
  1649. });
  1650. function isHover(displayable, x, y) {
  1651. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1652. var el = displayable;
  1653. var isSilent;
  1654. while (el) {
  1655. // If clipped by ancestor.
  1656. // FIXME: If clipPath has neither stroke nor fill,
  1657. // el.clipPath.contain(x, y) will always return false.
  1658. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1659. return false;
  1660. }
  1661. if (el.silent) {
  1662. isSilent = true;
  1663. }
  1664. el = el.parent;
  1665. }
  1666. return isSilent ? SILENT : true;
  1667. }
  1668. return false;
  1669. }
  1670. mixin(Handler, Eventful);
  1671. mixin(Handler, Draggable);
  1672. /**
  1673. * 3x2矩阵操作类
  1674. * @exports zrender/tool/matrix
  1675. */
  1676. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1677. ? Array
  1678. : Float32Array;
  1679. /**
  1680. * Create a identity matrix.
  1681. * @return {Float32Array|Array.<number>}
  1682. */
  1683. function create$1() {
  1684. var out = new ArrayCtor$1(6);
  1685. identity(out);
  1686. return out;
  1687. }
  1688. /**
  1689. * 设置矩阵为单位矩阵
  1690. * @param {Float32Array|Array.<number>} out
  1691. */
  1692. function identity(out) {
  1693. out[0] = 1;
  1694. out[1] = 0;
  1695. out[2] = 0;
  1696. out[3] = 1;
  1697. out[4] = 0;
  1698. out[5] = 0;
  1699. return out;
  1700. }
  1701. /**
  1702. * 复制矩阵
  1703. * @param {Float32Array|Array.<number>} out
  1704. * @param {Float32Array|Array.<number>} m
  1705. */
  1706. function copy$1(out, m) {
  1707. out[0] = m[0];
  1708. out[1] = m[1];
  1709. out[2] = m[2];
  1710. out[3] = m[3];
  1711. out[4] = m[4];
  1712. out[5] = m[5];
  1713. return out;
  1714. }
  1715. /**
  1716. * 矩阵相乘
  1717. * @param {Float32Array|Array.<number>} out
  1718. * @param {Float32Array|Array.<number>} m1
  1719. * @param {Float32Array|Array.<number>} m2
  1720. */
  1721. function mul$1(out, m1, m2) {
  1722. // Consider matrix.mul(m, m2, m);
  1723. // where out is the same as m2.
  1724. // So use temp variable to escape error.
  1725. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1726. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1727. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1728. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1729. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1730. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1731. out[0] = out0;
  1732. out[1] = out1;
  1733. out[2] = out2;
  1734. out[3] = out3;
  1735. out[4] = out4;
  1736. out[5] = out5;
  1737. return out;
  1738. }
  1739. /**
  1740. * 平移变换
  1741. * @param {Float32Array|Array.<number>} out
  1742. * @param {Float32Array|Array.<number>} a
  1743. * @param {Float32Array|Array.<number>} v
  1744. */
  1745. function translate(out, a, v) {
  1746. out[0] = a[0];
  1747. out[1] = a[1];
  1748. out[2] = a[2];
  1749. out[3] = a[3];
  1750. out[4] = a[4] + v[0];
  1751. out[5] = a[5] + v[1];
  1752. return out;
  1753. }
  1754. /**
  1755. * 旋转变换
  1756. * @param {Float32Array|Array.<number>} out
  1757. * @param {Float32Array|Array.<number>} a
  1758. * @param {number} rad
  1759. */
  1760. function rotate(out, a, rad) {
  1761. var aa = a[0];
  1762. var ac = a[2];
  1763. var atx = a[4];
  1764. var ab = a[1];
  1765. var ad = a[3];
  1766. var aty = a[5];
  1767. var st = Math.sin(rad);
  1768. var ct = Math.cos(rad);
  1769. out[0] = aa * ct + ab * st;
  1770. out[1] = -aa * st + ab * ct;
  1771. out[2] = ac * ct + ad * st;
  1772. out[3] = -ac * st + ct * ad;
  1773. out[4] = ct * atx + st * aty;
  1774. out[5] = ct * aty - st * atx;
  1775. return out;
  1776. }
  1777. /**
  1778. * 缩放变换
  1779. * @param {Float32Array|Array.<number>} out
  1780. * @param {Float32Array|Array.<number>} a
  1781. * @param {Float32Array|Array.<number>} v
  1782. */
  1783. function scale$1(out, a, v) {
  1784. var vx = v[0];
  1785. var vy = v[1];
  1786. out[0] = a[0] * vx;
  1787. out[1] = a[1] * vy;
  1788. out[2] = a[2] * vx;
  1789. out[3] = a[3] * vy;
  1790. out[4] = a[4] * vx;
  1791. out[5] = a[5] * vy;
  1792. return out;
  1793. }
  1794. /**
  1795. * 求逆矩阵
  1796. * @param {Float32Array|Array.<number>} out
  1797. * @param {Float32Array|Array.<number>} a
  1798. */
  1799. function invert(out, a) {
  1800. var aa = a[0];
  1801. var ac = a[2];
  1802. var atx = a[4];
  1803. var ab = a[1];
  1804. var ad = a[3];
  1805. var aty = a[5];
  1806. var det = aa * ad - ab * ac;
  1807. if (!det) {
  1808. return null;
  1809. }
  1810. det = 1.0 / det;
  1811. out[0] = ad * det;
  1812. out[1] = -ab * det;
  1813. out[2] = -ac * det;
  1814. out[3] = aa * det;
  1815. out[4] = (ac * aty - ad * atx) * det;
  1816. out[5] = (ab * atx - aa * aty) * det;
  1817. return out;
  1818. }
  1819. /**
  1820. * Clone a new matrix.
  1821. * @param {Float32Array|Array.<number>} a
  1822. */
  1823. function clone$2(a) {
  1824. var b = create$1();
  1825. copy$1(b, a);
  1826. return b;
  1827. }
  1828. var matrix = (Object.freeze || Object)({
  1829. create: create$1,
  1830. identity: identity,
  1831. copy: copy$1,
  1832. mul: mul$1,
  1833. translate: translate,
  1834. rotate: rotate,
  1835. scale: scale$1,
  1836. invert: invert,
  1837. clone: clone$2
  1838. });
  1839. /**
  1840. * 提供变换扩展
  1841. * @module zrender/mixin/Transformable
  1842. * @author pissang (https://www.github.com/pissang)
  1843. */
  1844. var mIdentity = identity;
  1845. var EPSILON = 5e-5;
  1846. function isNotAroundZero(val) {
  1847. return val > EPSILON || val < -EPSILON;
  1848. }
  1849. /**
  1850. * @alias module:zrender/mixin/Transformable
  1851. * @constructor
  1852. */
  1853. var Transformable = function (opts) {
  1854. opts = opts || {};
  1855. // If there are no given position, rotation, scale
  1856. if (!opts.position) {
  1857. /**
  1858. * 平移
  1859. * @type {Array.<number>}
  1860. * @default [0, 0]
  1861. */
  1862. this.position = [0, 0];
  1863. }
  1864. if (opts.rotation == null) {
  1865. /**
  1866. * 旋转
  1867. * @type {Array.<number>}
  1868. * @default 0
  1869. */
  1870. this.rotation = 0;
  1871. }
  1872. if (!opts.scale) {
  1873. /**
  1874. * 缩放
  1875. * @type {Array.<number>}
  1876. * @default [1, 1]
  1877. */
  1878. this.scale = [1, 1];
  1879. }
  1880. /**
  1881. * 旋转和缩放的原点
  1882. * @type {Array.<number>}
  1883. * @default null
  1884. */
  1885. this.origin = this.origin || null;
  1886. };
  1887. var transformableProto = Transformable.prototype;
  1888. transformableProto.transform = null;
  1889. /**
  1890. * 判断是否需要有坐标变换
  1891. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1892. */
  1893. transformableProto.needLocalTransform = function () {
  1894. return isNotAroundZero(this.rotation)
  1895. || isNotAroundZero(this.position[0])
  1896. || isNotAroundZero(this.position[1])
  1897. || isNotAroundZero(this.scale[0] - 1)
  1898. || isNotAroundZero(this.scale[1] - 1);
  1899. };
  1900. transformableProto.updateTransform = function () {
  1901. var parent = this.parent;
  1902. var parentHasTransform = parent && parent.transform;
  1903. var needLocalTransform = this.needLocalTransform();
  1904. var m = this.transform;
  1905. if (!(needLocalTransform || parentHasTransform)) {
  1906. m && mIdentity(m);
  1907. return;
  1908. }
  1909. m = m || create$1();
  1910. if (needLocalTransform) {
  1911. this.getLocalTransform(m);
  1912. }
  1913. else {
  1914. mIdentity(m);
  1915. }
  1916. // 应用父节点变换
  1917. if (parentHasTransform) {
  1918. if (needLocalTransform) {
  1919. mul$1(m, parent.transform, m);
  1920. }
  1921. else {
  1922. copy$1(m, parent.transform);
  1923. }
  1924. }
  1925. // 保存这个变换矩阵
  1926. this.transform = m;
  1927. this.invTransform = this.invTransform || create$1();
  1928. invert(this.invTransform, m);
  1929. };
  1930. transformableProto.getLocalTransform = function (m) {
  1931. return Transformable.getLocalTransform(this, m);
  1932. };
  1933. /**
  1934. * 将自己的transform应用到context上
  1935. * @param {CanvasRenderingContext2D} ctx
  1936. */
  1937. transformableProto.setTransform = function (ctx) {
  1938. var m = this.transform;
  1939. var dpr = ctx.dpr || 1;
  1940. if (m) {
  1941. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1942. }
  1943. else {
  1944. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1945. }
  1946. };
  1947. transformableProto.restoreTransform = function (ctx) {
  1948. var dpr = ctx.dpr || 1;
  1949. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1950. };
  1951. var tmpTransform = [];
  1952. /**
  1953. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1954. */
  1955. transformableProto.decomposeTransform = function () {
  1956. if (!this.transform) {
  1957. return;
  1958. }
  1959. var parent = this.parent;
  1960. var m = this.transform;
  1961. if (parent && parent.transform) {
  1962. // Get local transform and decompose them to position, scale, rotation
  1963. mul$1(tmpTransform, parent.invTransform, m);
  1964. m = tmpTransform;
  1965. }
  1966. var sx = m[0] * m[0] + m[1] * m[1];
  1967. var sy = m[2] * m[2] + m[3] * m[3];
  1968. var position = this.position;
  1969. var scale$$1 = this.scale;
  1970. if (isNotAroundZero(sx - 1)) {
  1971. sx = Math.sqrt(sx);
  1972. }
  1973. if (isNotAroundZero(sy - 1)) {
  1974. sy = Math.sqrt(sy);
  1975. }
  1976. if (m[0] < 0) {
  1977. sx = -sx;
  1978. }
  1979. if (m[3] < 0) {
  1980. sy = -sy;
  1981. }
  1982. position[0] = m[4];
  1983. position[1] = m[5];
  1984. scale$$1[0] = sx;
  1985. scale$$1[1] = sy;
  1986. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1987. };
  1988. /**
  1989. * Get global scale
  1990. * @return {Array.<number>}
  1991. */
  1992. transformableProto.getGlobalScale = function () {
  1993. var m = this.transform;
  1994. if (!m) {
  1995. return [1, 1];
  1996. }
  1997. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1998. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1999. if (m[0] < 0) {
  2000. sx = -sx;
  2001. }
  2002. if (m[3] < 0) {
  2003. sy = -sy;
  2004. }
  2005. return [sx, sy];
  2006. };
  2007. /**
  2008. * 变换坐标位置到 shape 的局部坐标空间
  2009. * @method
  2010. * @param {number} x
  2011. * @param {number} y
  2012. * @return {Array.<number>}
  2013. */
  2014. transformableProto.transformCoordToLocal = function (x, y) {
  2015. var v2 = [x, y];
  2016. var invTransform = this.invTransform;
  2017. if (invTransform) {
  2018. applyTransform(v2, v2, invTransform);
  2019. }
  2020. return v2;
  2021. };
  2022. /**
  2023. * 变换局部坐标位置到全局坐标空间
  2024. * @method
  2025. * @param {number} x
  2026. * @param {number} y
  2027. * @return {Array.<number>}
  2028. */
  2029. transformableProto.transformCoordToGlobal = function (x, y) {
  2030. var v2 = [x, y];
  2031. var transform = this.transform;
  2032. if (transform) {
  2033. applyTransform(v2, v2, transform);
  2034. }
  2035. return v2;
  2036. };
  2037. /**
  2038. * @static
  2039. * @param {Object} target
  2040. * @param {Array.<number>} target.origin
  2041. * @param {number} target.rotation
  2042. * @param {Array.<number>} target.position
  2043. * @param {Array.<number>} [m]
  2044. */
  2045. Transformable.getLocalTransform = function (target, m) {
  2046. m = m || [];
  2047. mIdentity(m);
  2048. var origin = target.origin;
  2049. var scale$$1 = target.scale || [1, 1];
  2050. var rotation = target.rotation || 0;
  2051. var position = target.position || [0, 0];
  2052. if (origin) {
  2053. // Translate to origin
  2054. m[4] -= origin[0];
  2055. m[5] -= origin[1];
  2056. }
  2057. scale$1(m, m, scale$$1);
  2058. if (rotation) {
  2059. rotate(m, m, rotation);
  2060. }
  2061. if (origin) {
  2062. // Translate back from origin
  2063. m[4] += origin[0];
  2064. m[5] += origin[1];
  2065. }
  2066. m[4] += position[0];
  2067. m[5] += position[1];
  2068. return m;
  2069. };
  2070. /**
  2071. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2072. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2073. * @exports zrender/animation/easing
  2074. */
  2075. var easing = {
  2076. /**
  2077. * @param {number} k
  2078. * @return {number}
  2079. */
  2080. linear: function (k) {
  2081. return k;
  2082. },
  2083. /**
  2084. * @param {number} k
  2085. * @return {number}
  2086. */
  2087. quadraticIn: function (k) {
  2088. return k * k;
  2089. },
  2090. /**
  2091. * @param {number} k
  2092. * @return {number}
  2093. */
  2094. quadraticOut: function (k) {
  2095. return k * (2 - k);
  2096. },
  2097. /**
  2098. * @param {number} k
  2099. * @return {number}
  2100. */
  2101. quadraticInOut: function (k) {
  2102. if ((k *= 2) < 1) {
  2103. return 0.5 * k * k;
  2104. }
  2105. return -0.5 * (--k * (k - 2) - 1);
  2106. },
  2107. // 三次方的缓动(t^3)
  2108. /**
  2109. * @param {number} k
  2110. * @return {number}
  2111. */
  2112. cubicIn: function (k) {
  2113. return k * k * k;
  2114. },
  2115. /**
  2116. * @param {number} k
  2117. * @return {number}
  2118. */
  2119. cubicOut: function (k) {
  2120. return --k * k * k + 1;
  2121. },
  2122. /**
  2123. * @param {number} k
  2124. * @return {number}
  2125. */
  2126. cubicInOut: function (k) {
  2127. if ((k *= 2) < 1) {
  2128. return 0.5 * k * k * k;
  2129. }
  2130. return 0.5 * ((k -= 2) * k * k + 2);
  2131. },
  2132. // 四次方的缓动(t^4)
  2133. /**
  2134. * @param {number} k
  2135. * @return {number}
  2136. */
  2137. quarticIn: function (k) {
  2138. return k * k * k * k;
  2139. },
  2140. /**
  2141. * @param {number} k
  2142. * @return {number}
  2143. */
  2144. quarticOut: function (k) {
  2145. return 1 - (--k * k * k * k);
  2146. },
  2147. /**
  2148. * @param {number} k
  2149. * @return {number}
  2150. */
  2151. quarticInOut: function (k) {
  2152. if ((k *= 2) < 1) {
  2153. return 0.5 * k * k * k * k;
  2154. }
  2155. return -0.5 * ((k -= 2) * k * k * k - 2);
  2156. },
  2157. // 五次方的缓动(t^5)
  2158. /**
  2159. * @param {number} k
  2160. * @return {number}
  2161. */
  2162. quinticIn: function (k) {
  2163. return k * k * k * k * k;
  2164. },
  2165. /**
  2166. * @param {number} k
  2167. * @return {number}
  2168. */
  2169. quinticOut: function (k) {
  2170. return --k * k * k * k * k + 1;
  2171. },
  2172. /**
  2173. * @param {number} k
  2174. * @return {number}
  2175. */
  2176. quinticInOut: function (k) {
  2177. if ((k *= 2) < 1) {
  2178. return 0.5 * k * k * k * k * k;
  2179. }
  2180. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2181. },
  2182. // 正弦曲线的缓动(sin(t))
  2183. /**
  2184. * @param {number} k
  2185. * @return {number}
  2186. */
  2187. sinusoidalIn: function (k) {
  2188. return 1 - Math.cos(k * Math.PI / 2);
  2189. },
  2190. /**
  2191. * @param {number} k
  2192. * @return {number}
  2193. */
  2194. sinusoidalOut: function (k) {
  2195. return Math.sin(k * Math.PI / 2);
  2196. },
  2197. /**
  2198. * @param {number} k
  2199. * @return {number}
  2200. */
  2201. sinusoidalInOut: function (k) {
  2202. return 0.5 * (1 - Math.cos(Math.PI * k));
  2203. },
  2204. // 指数曲线的缓动(2^t)
  2205. /**
  2206. * @param {number} k
  2207. * @return {number}
  2208. */
  2209. exponentialIn: function (k) {
  2210. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2211. },
  2212. /**
  2213. * @param {number} k
  2214. * @return {number}
  2215. */
  2216. exponentialOut: function (k) {
  2217. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2218. },
  2219. /**
  2220. * @param {number} k
  2221. * @return {number}
  2222. */
  2223. exponentialInOut: function (k) {
  2224. if (k === 0) {
  2225. return 0;
  2226. }
  2227. if (k === 1) {
  2228. return 1;
  2229. }
  2230. if ((k *= 2) < 1) {
  2231. return 0.5 * Math.pow(1024, k - 1);
  2232. }
  2233. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2234. },
  2235. // 圆形曲线的缓动(sqrt(1-t^2))
  2236. /**
  2237. * @param {number} k
  2238. * @return {number}
  2239. */
  2240. circularIn: function (k) {
  2241. return 1 - Math.sqrt(1 - k * k);
  2242. },
  2243. /**
  2244. * @param {number} k
  2245. * @return {number}
  2246. */
  2247. circularOut: function (k) {
  2248. return Math.sqrt(1 - (--k * k));
  2249. },
  2250. /**
  2251. * @param {number} k
  2252. * @return {number}
  2253. */
  2254. circularInOut: function (k) {
  2255. if ((k *= 2) < 1) {
  2256. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2257. }
  2258. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2259. },
  2260. // 创建类似于弹簧在停止前来回振荡的动画
  2261. /**
  2262. * @param {number} k
  2263. * @return {number}
  2264. */
  2265. elasticIn: function (k) {
  2266. var s;
  2267. var a = 0.1;
  2268. var p = 0.4;
  2269. if (k === 0) {
  2270. return 0;
  2271. }
  2272. if (k === 1) {
  2273. return 1;
  2274. }
  2275. if (!a || a < 1) {
  2276. a = 1; s = p / 4;
  2277. }
  2278. else {
  2279. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2280. }
  2281. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2282. Math.sin((k - s) * (2 * Math.PI) / p));
  2283. },
  2284. /**
  2285. * @param {number} k
  2286. * @return {number}
  2287. */
  2288. elasticOut: function (k) {
  2289. var s;
  2290. var a = 0.1;
  2291. var p = 0.4;
  2292. if (k === 0) {
  2293. return 0;
  2294. }
  2295. if (k === 1) {
  2296. return 1;
  2297. }
  2298. if (!a || a < 1) {
  2299. a = 1; s = p / 4;
  2300. }
  2301. else {
  2302. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2303. }
  2304. return (a * Math.pow(2, -10 * k) *
  2305. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2306. },
  2307. /**
  2308. * @param {number} k
  2309. * @return {number}
  2310. */
  2311. elasticInOut: function (k) {
  2312. var s;
  2313. var a = 0.1;
  2314. var p = 0.4;
  2315. if (k === 0) {
  2316. return 0;
  2317. }
  2318. if (k === 1) {
  2319. return 1;
  2320. }
  2321. if (!a || a < 1) {
  2322. a = 1; s = p / 4;
  2323. }
  2324. else {
  2325. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2326. }
  2327. if ((k *= 2) < 1) {
  2328. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2329. * Math.sin((k - s) * (2 * Math.PI) / p));
  2330. }
  2331. return a * Math.pow(2, -10 * (k -= 1))
  2332. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2333. },
  2334. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2335. /**
  2336. * @param {number} k
  2337. * @return {number}
  2338. */
  2339. backIn: function (k) {
  2340. var s = 1.70158;
  2341. return k * k * ((s + 1) * k - s);
  2342. },
  2343. /**
  2344. * @param {number} k
  2345. * @return {number}
  2346. */
  2347. backOut: function (k) {
  2348. var s = 1.70158;
  2349. return --k * k * ((s + 1) * k + s) + 1;
  2350. },
  2351. /**
  2352. * @param {number} k
  2353. * @return {number}
  2354. */
  2355. backInOut: function (k) {
  2356. var s = 1.70158 * 1.525;
  2357. if ((k *= 2) < 1) {
  2358. return 0.5 * (k * k * ((s + 1) * k - s));
  2359. }
  2360. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2361. },
  2362. // 创建弹跳效果
  2363. /**
  2364. * @param {number} k
  2365. * @return {number}
  2366. */
  2367. bounceIn: function (k) {
  2368. return 1 - easing.bounceOut(1 - k);
  2369. },
  2370. /**
  2371. * @param {number} k
  2372. * @return {number}
  2373. */
  2374. bounceOut: function (k) {
  2375. if (k < (1 / 2.75)) {
  2376. return 7.5625 * k * k;
  2377. }
  2378. else if (k < (2 / 2.75)) {
  2379. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2380. }
  2381. else if (k < (2.5 / 2.75)) {
  2382. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2383. }
  2384. else {
  2385. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2386. }
  2387. },
  2388. /**
  2389. * @param {number} k
  2390. * @return {number}
  2391. */
  2392. bounceInOut: function (k) {
  2393. if (k < 0.5) {
  2394. return easing.bounceIn(k * 2) * 0.5;
  2395. }
  2396. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2397. }
  2398. };
  2399. /**
  2400. * 动画主控制器
  2401. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2402. * @config life(1000) 动画时长
  2403. * @config delay(0) 动画延迟时间
  2404. * @config loop(true)
  2405. * @config gap(0) 循环的间隔时间
  2406. * @config onframe
  2407. * @config easing(optional)
  2408. * @config ondestroy(optional)
  2409. * @config onrestart(optional)
  2410. *
  2411. * TODO pause
  2412. */
  2413. function Clip(options) {
  2414. this._target = options.target;
  2415. // 生命周期
  2416. this._life = options.life || 1000;
  2417. // 延时
  2418. this._delay = options.delay || 0;
  2419. // 开始时间
  2420. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2421. this._initialized = false;
  2422. // 是否循环
  2423. this.loop = options.loop == null ? false : options.loop;
  2424. this.gap = options.gap || 0;
  2425. this.easing = options.easing || 'Linear';
  2426. this.onframe = options.onframe;
  2427. this.ondestroy = options.ondestroy;
  2428. this.onrestart = options.onrestart;
  2429. this._pausedTime = 0;
  2430. this._paused = false;
  2431. }
  2432. Clip.prototype = {
  2433. constructor: Clip,
  2434. step: function (globalTime, deltaTime) {
  2435. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2436. // PENDING
  2437. if (!this._initialized) {
  2438. this._startTime = globalTime + this._delay;
  2439. this._initialized = true;
  2440. }
  2441. if (this._paused) {
  2442. this._pausedTime += deltaTime;
  2443. return;
  2444. }
  2445. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2446. // 还没开始
  2447. if (percent < 0) {
  2448. return;
  2449. }
  2450. percent = Math.min(percent, 1);
  2451. var easing$$1 = this.easing;
  2452. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2453. var schedule = typeof easingFunc === 'function'
  2454. ? easingFunc(percent)
  2455. : percent;
  2456. this.fire('frame', schedule);
  2457. // 结束
  2458. if (percent == 1) {
  2459. if (this.loop) {
  2460. this.restart (globalTime);
  2461. // 重新开始周期
  2462. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2463. return 'restart';
  2464. }
  2465. // 动画完成将这个控制器标识为待删除
  2466. // 在Animation.update中进行批量删除
  2467. this._needsRemove = true;
  2468. return 'destroy';
  2469. }
  2470. return null;
  2471. },
  2472. restart: function (globalTime) {
  2473. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2474. this._startTime = globalTime - remainder + this.gap;
  2475. this._pausedTime = 0;
  2476. this._needsRemove = false;
  2477. },
  2478. fire: function (eventType, arg) {
  2479. eventType = 'on' + eventType;
  2480. if (this[eventType]) {
  2481. this[eventType](this._target, arg);
  2482. }
  2483. },
  2484. pause: function () {
  2485. this._paused = true;
  2486. },
  2487. resume: function () {
  2488. this._paused = false;
  2489. }
  2490. };
  2491. // Simple LRU cache use doubly linked list
  2492. // @module zrender/core/LRU
  2493. /**
  2494. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2495. * @constructor
  2496. */
  2497. var LinkedList = function () {
  2498. /**
  2499. * @type {module:zrender/core/LRU~Entry}
  2500. */
  2501. this.head = null;
  2502. /**
  2503. * @type {module:zrender/core/LRU~Entry}
  2504. */
  2505. this.tail = null;
  2506. this._len = 0;
  2507. };
  2508. var linkedListProto = LinkedList.prototype;
  2509. /**
  2510. * Insert a new value at the tail
  2511. * @param {} val
  2512. * @return {module:zrender/core/LRU~Entry}
  2513. */
  2514. linkedListProto.insert = function (val) {
  2515. var entry = new Entry(val);
  2516. this.insertEntry(entry);
  2517. return entry;
  2518. };
  2519. /**
  2520. * Insert an entry at the tail
  2521. * @param {module:zrender/core/LRU~Entry} entry
  2522. */
  2523. linkedListProto.insertEntry = function (entry) {
  2524. if (!this.head) {
  2525. this.head = this.tail = entry;
  2526. }
  2527. else {
  2528. this.tail.next = entry;
  2529. entry.prev = this.tail;
  2530. entry.next = null;
  2531. this.tail = entry;
  2532. }
  2533. this._len++;
  2534. };
  2535. /**
  2536. * Remove entry.
  2537. * @param {module:zrender/core/LRU~Entry} entry
  2538. */
  2539. linkedListProto.remove = function (entry) {
  2540. var prev = entry.prev;
  2541. var next = entry.next;
  2542. if (prev) {
  2543. prev.next = next;
  2544. }
  2545. else {
  2546. // Is head
  2547. this.head = next;
  2548. }
  2549. if (next) {
  2550. next.prev = prev;
  2551. }
  2552. else {
  2553. // Is tail
  2554. this.tail = prev;
  2555. }
  2556. entry.next = entry.prev = null;
  2557. this._len--;
  2558. };
  2559. /**
  2560. * @return {number}
  2561. */
  2562. linkedListProto.len = function () {
  2563. return this._len;
  2564. };
  2565. /**
  2566. * Clear list
  2567. */
  2568. linkedListProto.clear = function () {
  2569. this.head = this.tail = null;
  2570. this._len = 0;
  2571. };
  2572. /**
  2573. * @constructor
  2574. * @param {} val
  2575. */
  2576. var Entry = function (val) {
  2577. /**
  2578. * @type {}
  2579. */
  2580. this.value = val;
  2581. /**
  2582. * @type {module:zrender/core/LRU~Entry}
  2583. */
  2584. this.next;
  2585. /**
  2586. * @type {module:zrender/core/LRU~Entry}
  2587. */
  2588. this.prev;
  2589. };
  2590. /**
  2591. * LRU Cache
  2592. * @constructor
  2593. * @alias module:zrender/core/LRU
  2594. */
  2595. var LRU = function (maxSize) {
  2596. this._list = new LinkedList();
  2597. this._map = {};
  2598. this._maxSize = maxSize || 10;
  2599. this._lastRemovedEntry = null;
  2600. };
  2601. var LRUProto = LRU.prototype;
  2602. /**
  2603. * @param {string} key
  2604. * @param {} value
  2605. * @return {} Removed value
  2606. */
  2607. LRUProto.put = function (key, value) {
  2608. var list = this._list;
  2609. var map = this._map;
  2610. var removed = null;
  2611. if (map[key] == null) {
  2612. var len = list.len();
  2613. // Reuse last removed entry
  2614. var entry = this._lastRemovedEntry;
  2615. if (len >= this._maxSize && len > 0) {
  2616. // Remove the least recently used
  2617. var leastUsedEntry = list.head;
  2618. list.remove(leastUsedEntry);
  2619. delete map[leastUsedEntry.key];
  2620. removed = leastUsedEntry.value;
  2621. this._lastRemovedEntry = leastUsedEntry;
  2622. }
  2623. if (entry) {
  2624. entry.value = value;
  2625. }
  2626. else {
  2627. entry = new Entry(value);
  2628. }
  2629. entry.key = key;
  2630. list.insertEntry(entry);
  2631. map[key] = entry;
  2632. }
  2633. return removed;
  2634. };
  2635. /**
  2636. * @param {string} key
  2637. * @return {}
  2638. */
  2639. LRUProto.get = function (key) {
  2640. var entry = this._map[key];
  2641. var list = this._list;
  2642. if (entry != null) {
  2643. // Put the latest used entry in the tail
  2644. if (entry !== list.tail) {
  2645. list.remove(entry);
  2646. list.insertEntry(entry);
  2647. }
  2648. return entry.value;
  2649. }
  2650. };
  2651. /**
  2652. * Clear the cache
  2653. */
  2654. LRUProto.clear = function () {
  2655. this._list.clear();
  2656. this._map = {};
  2657. };
  2658. var kCSSColorTable = {
  2659. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2660. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2661. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2662. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2663. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2664. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2665. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2666. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2667. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2668. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2669. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2670. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2671. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2672. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2673. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2674. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2675. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2676. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2677. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2678. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2679. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2680. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2681. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2682. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2683. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2684. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2685. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2686. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2687. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2688. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2689. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2690. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2691. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2692. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2693. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2694. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2695. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2696. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2697. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2698. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2699. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2700. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2701. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2702. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2703. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2704. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2705. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2706. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2707. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2708. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2709. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2710. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2711. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2712. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2713. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2714. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2715. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2716. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2717. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2718. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2719. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2720. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2721. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2722. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2723. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2724. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2725. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2726. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2727. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2728. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2729. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2730. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2731. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2732. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2733. };
  2734. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2735. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2736. return i < 0 ? 0 : i > 255 ? 255 : i;
  2737. }
  2738. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2739. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2740. return i < 0 ? 0 : i > 360 ? 360 : i;
  2741. }
  2742. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2743. return f < 0 ? 0 : f > 1 ? 1 : f;
  2744. }
  2745. function parseCssInt(str) { // int or percentage.
  2746. if (str.length && str.charAt(str.length - 1) === '%') {
  2747. return clampCssByte(parseFloat(str) / 100 * 255);
  2748. }
  2749. return clampCssByte(parseInt(str, 10));
  2750. }
  2751. function parseCssFloat(str) { // float or percentage.
  2752. if (str.length && str.charAt(str.length - 1) === '%') {
  2753. return clampCssFloat(parseFloat(str) / 100);
  2754. }
  2755. return clampCssFloat(parseFloat(str));
  2756. }
  2757. function cssHueToRgb(m1, m2, h) {
  2758. if (h < 0) {
  2759. h += 1;
  2760. }
  2761. else if (h > 1) {
  2762. h -= 1;
  2763. }
  2764. if (h * 6 < 1) {
  2765. return m1 + (m2 - m1) * h * 6;
  2766. }
  2767. if (h * 2 < 1) {
  2768. return m2;
  2769. }
  2770. if (h * 3 < 2) {
  2771. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2772. }
  2773. return m1;
  2774. }
  2775. function lerpNumber(a, b, p) {
  2776. return a + (b - a) * p;
  2777. }
  2778. function setRgba(out, r, g, b, a) {
  2779. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2780. return out;
  2781. }
  2782. function copyRgba(out, a) {
  2783. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2784. return out;
  2785. }
  2786. var colorCache = new LRU(20);
  2787. var lastRemovedArr = null;
  2788. function putToCache(colorStr, rgbaArr) {
  2789. // Reuse removed array
  2790. if (lastRemovedArr) {
  2791. copyRgba(lastRemovedArr, rgbaArr);
  2792. }
  2793. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2794. }
  2795. /**
  2796. * @param {string} colorStr
  2797. * @param {Array.<number>} out
  2798. * @return {Array.<number>}
  2799. * @memberOf module:zrender/util/color
  2800. */
  2801. function parse(colorStr, rgbaArr) {
  2802. if (!colorStr) {
  2803. return;
  2804. }
  2805. rgbaArr = rgbaArr || [];
  2806. var cached = colorCache.get(colorStr);
  2807. if (cached) {
  2808. return copyRgba(rgbaArr, cached);
  2809. }
  2810. // colorStr may be not string
  2811. colorStr = colorStr + '';
  2812. // Remove all whitespace, not compliant, but should just be more accepting.
  2813. var str = colorStr.replace(/ /g, '').toLowerCase();
  2814. // Color keywords (and transparent) lookup.
  2815. if (str in kCSSColorTable) {
  2816. copyRgba(rgbaArr, kCSSColorTable[str]);
  2817. putToCache(colorStr, rgbaArr);
  2818. return rgbaArr;
  2819. }
  2820. // #abc and #abc123 syntax.
  2821. if (str.charAt(0) === '#') {
  2822. if (str.length === 4) {
  2823. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2824. if (!(iv >= 0 && iv <= 0xfff)) {
  2825. setRgba(rgbaArr, 0, 0, 0, 1);
  2826. return; // Covers NaN.
  2827. }
  2828. setRgba(rgbaArr,
  2829. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2830. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2831. (iv & 0xf) | ((iv & 0xf) << 4),
  2832. 1
  2833. );
  2834. putToCache(colorStr, rgbaArr);
  2835. return rgbaArr;
  2836. }
  2837. else if (str.length === 7) {
  2838. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2839. if (!(iv >= 0 && iv <= 0xffffff)) {
  2840. setRgba(rgbaArr, 0, 0, 0, 1);
  2841. return; // Covers NaN.
  2842. }
  2843. setRgba(rgbaArr,
  2844. (iv & 0xff0000) >> 16,
  2845. (iv & 0xff00) >> 8,
  2846. iv & 0xff,
  2847. 1
  2848. );
  2849. putToCache(colorStr, rgbaArr);
  2850. return rgbaArr;
  2851. }
  2852. return;
  2853. }
  2854. var op = str.indexOf('('), ep = str.indexOf(')');
  2855. if (op !== -1 && ep + 1 === str.length) {
  2856. var fname = str.substr(0, op);
  2857. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2858. var alpha = 1; // To allow case fallthrough.
  2859. switch (fname) {
  2860. case 'rgba':
  2861. if (params.length !== 4) {
  2862. setRgba(rgbaArr, 0, 0, 0, 1);
  2863. return;
  2864. }
  2865. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2866. // Fall through.
  2867. case 'rgb':
  2868. if (params.length !== 3) {
  2869. setRgba(rgbaArr, 0, 0, 0, 1);
  2870. return;
  2871. }
  2872. setRgba(rgbaArr,
  2873. parseCssInt(params[0]),
  2874. parseCssInt(params[1]),
  2875. parseCssInt(params[2]),
  2876. alpha
  2877. );
  2878. putToCache(colorStr, rgbaArr);
  2879. return rgbaArr;
  2880. case 'hsla':
  2881. if (params.length !== 4) {
  2882. setRgba(rgbaArr, 0, 0, 0, 1);
  2883. return;
  2884. }
  2885. params[3] = parseCssFloat(params[3]);
  2886. hsla2rgba(params, rgbaArr);
  2887. putToCache(colorStr, rgbaArr);
  2888. return rgbaArr;
  2889. case 'hsl':
  2890. if (params.length !== 3) {
  2891. setRgba(rgbaArr, 0, 0, 0, 1);
  2892. return;
  2893. }
  2894. hsla2rgba(params, rgbaArr);
  2895. putToCache(colorStr, rgbaArr);
  2896. return rgbaArr;
  2897. default:
  2898. return;
  2899. }
  2900. }
  2901. setRgba(rgbaArr, 0, 0, 0, 1);
  2902. return;
  2903. }
  2904. /**
  2905. * @param {Array.<number>} hsla
  2906. * @param {Array.<number>} rgba
  2907. * @return {Array.<number>} rgba
  2908. */
  2909. function hsla2rgba(hsla, rgba) {
  2910. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2911. // NOTE(deanm): According to the CSS spec s/l should only be
  2912. // percentages, but we don't bother and let float or percentage.
  2913. var s = parseCssFloat(hsla[1]);
  2914. var l = parseCssFloat(hsla[2]);
  2915. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2916. var m1 = l * 2 - m2;
  2917. rgba = rgba || [];
  2918. setRgba(rgba,
  2919. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2920. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2921. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2922. 1
  2923. );
  2924. if (hsla.length === 4) {
  2925. rgba[3] = hsla[3];
  2926. }
  2927. return rgba;
  2928. }
  2929. /**
  2930. * @param {Array.<number>} rgba
  2931. * @return {Array.<number>} hsla
  2932. */
  2933. function rgba2hsla(rgba) {
  2934. if (!rgba) {
  2935. return;
  2936. }
  2937. // RGB from 0 to 255
  2938. var R = rgba[0] / 255;
  2939. var G = rgba[1] / 255;
  2940. var B = rgba[2] / 255;
  2941. var vMin = Math.min(R, G, B); // Min. value of RGB
  2942. var vMax = Math.max(R, G, B); // Max. value of RGB
  2943. var delta = vMax - vMin; // Delta RGB value
  2944. var L = (vMax + vMin) / 2;
  2945. var H;
  2946. var S;
  2947. // HSL results from 0 to 1
  2948. if (delta === 0) {
  2949. H = 0;
  2950. S = 0;
  2951. }
  2952. else {
  2953. if (L < 0.5) {
  2954. S = delta / (vMax + vMin);
  2955. }
  2956. else {
  2957. S = delta / (2 - vMax - vMin);
  2958. }
  2959. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2960. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2961. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2962. if (R === vMax) {
  2963. H = deltaB - deltaG;
  2964. }
  2965. else if (G === vMax) {
  2966. H = (1 / 3) + deltaR - deltaB;
  2967. }
  2968. else if (B === vMax) {
  2969. H = (2 / 3) + deltaG - deltaR;
  2970. }
  2971. if (H < 0) {
  2972. H += 1;
  2973. }
  2974. if (H > 1) {
  2975. H -= 1;
  2976. }
  2977. }
  2978. var hsla = [H * 360, S, L];
  2979. if (rgba[3] != null) {
  2980. hsla.push(rgba[3]);
  2981. }
  2982. return hsla;
  2983. }
  2984. /**
  2985. * @param {string} color
  2986. * @param {number} level
  2987. * @return {string}
  2988. * @memberOf module:zrender/util/color
  2989. */
  2990. function lift(color, level) {
  2991. var colorArr = parse(color);
  2992. if (colorArr) {
  2993. for (var i = 0; i < 3; i++) {
  2994. if (level < 0) {
  2995. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2996. }
  2997. else {
  2998. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2999. }
  3000. if (colorArr[i] > 255) {
  3001. colorArr[i] = 255;
  3002. }
  3003. else if (color[i] < 0) {
  3004. colorArr[i] = 0;
  3005. }
  3006. }
  3007. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3008. }
  3009. }
  3010. /**
  3011. * @param {string} color
  3012. * @return {string}
  3013. * @memberOf module:zrender/util/color
  3014. */
  3015. function toHex(color) {
  3016. var colorArr = parse(color);
  3017. if (colorArr) {
  3018. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3019. }
  3020. }
  3021. /**
  3022. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3023. * @param {number} normalizedValue A float between 0 and 1.
  3024. * @param {Array.<Array.<number>>} colors List of rgba color array
  3025. * @param {Array.<number>} [out] Mapped gba color array
  3026. * @return {Array.<number>} will be null/undefined if input illegal.
  3027. */
  3028. function fastLerp(normalizedValue, colors, out) {
  3029. if (!(colors && colors.length)
  3030. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3031. ) {
  3032. return;
  3033. }
  3034. out = out || [];
  3035. var value = normalizedValue * (colors.length - 1);
  3036. var leftIndex = Math.floor(value);
  3037. var rightIndex = Math.ceil(value);
  3038. var leftColor = colors[leftIndex];
  3039. var rightColor = colors[rightIndex];
  3040. var dv = value - leftIndex;
  3041. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3042. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3043. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3044. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3045. return out;
  3046. }
  3047. /**
  3048. * @deprecated
  3049. */
  3050. var fastMapToColor = fastLerp;
  3051. /**
  3052. * @param {number} normalizedValue A float between 0 and 1.
  3053. * @param {Array.<string>} colors Color list.
  3054. * @param {boolean=} fullOutput Default false.
  3055. * @return {(string|Object)} Result color. If fullOutput,
  3056. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3057. * @memberOf module:zrender/util/color
  3058. */
  3059. function lerp$1(normalizedValue, colors, fullOutput) {
  3060. if (!(colors && colors.length)
  3061. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3062. ) {
  3063. return;
  3064. }
  3065. var value = normalizedValue * (colors.length - 1);
  3066. var leftIndex = Math.floor(value);
  3067. var rightIndex = Math.ceil(value);
  3068. var leftColor = parse(colors[leftIndex]);
  3069. var rightColor = parse(colors[rightIndex]);
  3070. var dv = value - leftIndex;
  3071. var color = stringify(
  3072. [
  3073. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3074. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3075. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3076. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3077. ],
  3078. 'rgba'
  3079. );
  3080. return fullOutput
  3081. ? {
  3082. color: color,
  3083. leftIndex: leftIndex,
  3084. rightIndex: rightIndex,
  3085. value: value
  3086. }
  3087. : color;
  3088. }
  3089. /**
  3090. * @deprecated
  3091. */
  3092. var mapToColor = lerp$1;
  3093. /**
  3094. * @param {string} color
  3095. * @param {number=} h 0 ~ 360, ignore when null.
  3096. * @param {number=} s 0 ~ 1, ignore when null.
  3097. * @param {number=} l 0 ~ 1, ignore when null.
  3098. * @return {string} Color string in rgba format.
  3099. * @memberOf module:zrender/util/color
  3100. */
  3101. function modifyHSL(color, h, s, l) {
  3102. color = parse(color);
  3103. if (color) {
  3104. color = rgba2hsla(color);
  3105. h != null && (color[0] = clampCssAngle(h));
  3106. s != null && (color[1] = parseCssFloat(s));
  3107. l != null && (color[2] = parseCssFloat(l));
  3108. return stringify(hsla2rgba(color), 'rgba');
  3109. }
  3110. }
  3111. /**
  3112. * @param {string} color
  3113. * @param {number=} alpha 0 ~ 1
  3114. * @return {string} Color string in rgba format.
  3115. * @memberOf module:zrender/util/color
  3116. */
  3117. function modifyAlpha(color, alpha) {
  3118. color = parse(color);
  3119. if (color && alpha != null) {
  3120. color[3] = clampCssFloat(alpha);
  3121. return stringify(color, 'rgba');
  3122. }
  3123. }
  3124. /**
  3125. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3126. * @param {string} type 'rgba', 'hsva', ...
  3127. * @return {string} Result color. (If input illegal, return undefined).
  3128. */
  3129. function stringify(arrColor, type) {
  3130. if (!arrColor || !arrColor.length) {
  3131. return;
  3132. }
  3133. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3134. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3135. colorStr += ',' + arrColor[3];
  3136. }
  3137. return type + '(' + colorStr + ')';
  3138. }
  3139. var color = (Object.freeze || Object)({
  3140. parse: parse,
  3141. lift: lift,
  3142. toHex: toHex,
  3143. fastLerp: fastLerp,
  3144. fastMapToColor: fastMapToColor,
  3145. lerp: lerp$1,
  3146. mapToColor: mapToColor,
  3147. modifyHSL: modifyHSL,
  3148. modifyAlpha: modifyAlpha,
  3149. stringify: stringify
  3150. });
  3151. /**
  3152. * @module echarts/animation/Animator
  3153. */
  3154. var arraySlice = Array.prototype.slice;
  3155. function defaultGetter(target, key) {
  3156. return target[key];
  3157. }
  3158. function defaultSetter(target, key, value) {
  3159. target[key] = value;
  3160. }
  3161. /**
  3162. * @param {number} p0
  3163. * @param {number} p1
  3164. * @param {number} percent
  3165. * @return {number}
  3166. */
  3167. function interpolateNumber(p0, p1, percent) {
  3168. return (p1 - p0) * percent + p0;
  3169. }
  3170. /**
  3171. * @param {string} p0
  3172. * @param {string} p1
  3173. * @param {number} percent
  3174. * @return {string}
  3175. */
  3176. function interpolateString(p0, p1, percent) {
  3177. return percent > 0.5 ? p1 : p0;
  3178. }
  3179. /**
  3180. * @param {Array} p0
  3181. * @param {Array} p1
  3182. * @param {number} percent
  3183. * @param {Array} out
  3184. * @param {number} arrDim
  3185. */
  3186. function interpolateArray(p0, p1, percent, out, arrDim) {
  3187. var len = p0.length;
  3188. if (arrDim == 1) {
  3189. for (var i = 0; i < len; i++) {
  3190. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3191. }
  3192. }
  3193. else {
  3194. var len2 = len && p0[0].length;
  3195. for (var i = 0; i < len; i++) {
  3196. for (var j = 0; j < len2; j++) {
  3197. out[i][j] = interpolateNumber(
  3198. p0[i][j], p1[i][j], percent
  3199. );
  3200. }
  3201. }
  3202. }
  3203. }
  3204. // arr0 is source array, arr1 is target array.
  3205. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3206. function fillArr(arr0, arr1, arrDim) {
  3207. var arr0Len = arr0.length;
  3208. var arr1Len = arr1.length;
  3209. if (arr0Len !== arr1Len) {
  3210. // FIXME Not work for TypedArray
  3211. var isPreviousLarger = arr0Len > arr1Len;
  3212. if (isPreviousLarger) {
  3213. // Cut the previous
  3214. arr0.length = arr1Len;
  3215. }
  3216. else {
  3217. // Fill the previous
  3218. for (var i = arr0Len; i < arr1Len; i++) {
  3219. arr0.push(
  3220. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3221. );
  3222. }
  3223. }
  3224. }
  3225. // Handling NaN value
  3226. var len2 = arr0[0] && arr0[0].length;
  3227. for (var i = 0; i < arr0.length; i++) {
  3228. if (arrDim === 1) {
  3229. if (isNaN(arr0[i])) {
  3230. arr0[i] = arr1[i];
  3231. }
  3232. }
  3233. else {
  3234. for (var j = 0; j < len2; j++) {
  3235. if (isNaN(arr0[i][j])) {
  3236. arr0[i][j] = arr1[i][j];
  3237. }
  3238. }
  3239. }
  3240. }
  3241. }
  3242. /**
  3243. * @param {Array} arr0
  3244. * @param {Array} arr1
  3245. * @param {number} arrDim
  3246. * @return {boolean}
  3247. */
  3248. function isArraySame(arr0, arr1, arrDim) {
  3249. if (arr0 === arr1) {
  3250. return true;
  3251. }
  3252. var len = arr0.length;
  3253. if (len !== arr1.length) {
  3254. return false;
  3255. }
  3256. if (arrDim === 1) {
  3257. for (var i = 0; i < len; i++) {
  3258. if (arr0[i] !== arr1[i]) {
  3259. return false;
  3260. }
  3261. }
  3262. }
  3263. else {
  3264. var len2 = arr0[0].length;
  3265. for (var i = 0; i < len; i++) {
  3266. for (var j = 0; j < len2; j++) {
  3267. if (arr0[i][j] !== arr1[i][j]) {
  3268. return false;
  3269. }
  3270. }
  3271. }
  3272. }
  3273. return true;
  3274. }
  3275. /**
  3276. * Catmull Rom interpolate array
  3277. * @param {Array} p0
  3278. * @param {Array} p1
  3279. * @param {Array} p2
  3280. * @param {Array} p3
  3281. * @param {number} t
  3282. * @param {number} t2
  3283. * @param {number} t3
  3284. * @param {Array} out
  3285. * @param {number} arrDim
  3286. */
  3287. function catmullRomInterpolateArray(
  3288. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3289. ) {
  3290. var len = p0.length;
  3291. if (arrDim == 1) {
  3292. for (var i = 0; i < len; i++) {
  3293. out[i] = catmullRomInterpolate(
  3294. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3295. );
  3296. }
  3297. }
  3298. else {
  3299. var len2 = p0[0].length;
  3300. for (var i = 0; i < len; i++) {
  3301. for (var j = 0; j < len2; j++) {
  3302. out[i][j] = catmullRomInterpolate(
  3303. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3304. t, t2, t3
  3305. );
  3306. }
  3307. }
  3308. }
  3309. }
  3310. /**
  3311. * Catmull Rom interpolate number
  3312. * @param {number} p0
  3313. * @param {number} p1
  3314. * @param {number} p2
  3315. * @param {number} p3
  3316. * @param {number} t
  3317. * @param {number} t2
  3318. * @param {number} t3
  3319. * @return {number}
  3320. */
  3321. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3322. var v0 = (p2 - p0) * 0.5;
  3323. var v1 = (p3 - p1) * 0.5;
  3324. return (2 * (p1 - p2) + v0 + v1) * t3
  3325. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3326. + v0 * t + p1;
  3327. }
  3328. function cloneValue(value) {
  3329. if (isArrayLike(value)) {
  3330. var len = value.length;
  3331. if (isArrayLike(value[0])) {
  3332. var ret = [];
  3333. for (var i = 0; i < len; i++) {
  3334. ret.push(arraySlice.call(value[i]));
  3335. }
  3336. return ret;
  3337. }
  3338. return arraySlice.call(value);
  3339. }
  3340. return value;
  3341. }
  3342. function rgba2String(rgba) {
  3343. rgba[0] = Math.floor(rgba[0]);
  3344. rgba[1] = Math.floor(rgba[1]);
  3345. rgba[2] = Math.floor(rgba[2]);
  3346. return 'rgba(' + rgba.join(',') + ')';
  3347. }
  3348. function getArrayDim(keyframes) {
  3349. var lastValue = keyframes[keyframes.length - 1].value;
  3350. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3351. }
  3352. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3353. var getter = animator._getter;
  3354. var setter = animator._setter;
  3355. var useSpline = easing === 'spline';
  3356. var trackLen = keyframes.length;
  3357. if (!trackLen) {
  3358. return;
  3359. }
  3360. // Guess data type
  3361. var firstVal = keyframes[0].value;
  3362. var isValueArray = isArrayLike(firstVal);
  3363. var isValueColor = false;
  3364. var isValueString = false;
  3365. // For vertices morphing
  3366. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3367. var trackMaxTime;
  3368. // Sort keyframe as ascending
  3369. keyframes.sort(function(a, b) {
  3370. return a.time - b.time;
  3371. });
  3372. trackMaxTime = keyframes[trackLen - 1].time;
  3373. // Percents of each keyframe
  3374. var kfPercents = [];
  3375. // Value of each keyframe
  3376. var kfValues = [];
  3377. var prevValue = keyframes[0].value;
  3378. var isAllValueEqual = true;
  3379. for (var i = 0; i < trackLen; i++) {
  3380. kfPercents.push(keyframes[i].time / trackMaxTime);
  3381. // Assume value is a color when it is a string
  3382. var value = keyframes[i].value;
  3383. // Check if value is equal, deep check if value is array
  3384. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3385. || (!isValueArray && value === prevValue))) {
  3386. isAllValueEqual = false;
  3387. }
  3388. prevValue = value;
  3389. // Try converting a string to a color array
  3390. if (typeof value == 'string') {
  3391. var colorArray = parse(value);
  3392. if (colorArray) {
  3393. value = colorArray;
  3394. isValueColor = true;
  3395. }
  3396. else {
  3397. isValueString = true;
  3398. }
  3399. }
  3400. kfValues.push(value);
  3401. }
  3402. if (!forceAnimate && isAllValueEqual) {
  3403. return;
  3404. }
  3405. var lastValue = kfValues[trackLen - 1];
  3406. // Polyfill array and NaN value
  3407. for (var i = 0; i < trackLen - 1; i++) {
  3408. if (isValueArray) {
  3409. fillArr(kfValues[i], lastValue, arrDim);
  3410. }
  3411. else {
  3412. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3413. kfValues[i] = lastValue;
  3414. }
  3415. }
  3416. }
  3417. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3418. // Cache the key of last frame to speed up when
  3419. // animation playback is sequency
  3420. var lastFrame = 0;
  3421. var lastFramePercent = 0;
  3422. var start;
  3423. var w;
  3424. var p0;
  3425. var p1;
  3426. var p2;
  3427. var p3;
  3428. if (isValueColor) {
  3429. var rgba = [0, 0, 0, 0];
  3430. }
  3431. var onframe = function (target, percent) {
  3432. // Find the range keyframes
  3433. // kf1-----kf2---------current--------kf3
  3434. // find kf2 and kf3 and do interpolation
  3435. var frame;
  3436. // In the easing function like elasticOut, percent may less than 0
  3437. if (percent < 0) {
  3438. frame = 0;
  3439. }
  3440. else if (percent < lastFramePercent) {
  3441. // Start from next key
  3442. // PENDING start from lastFrame ?
  3443. start = Math.min(lastFrame + 1, trackLen - 1);
  3444. for (frame = start; frame >= 0; frame--) {
  3445. if (kfPercents[frame] <= percent) {
  3446. break;
  3447. }
  3448. }
  3449. // PENDING really need to do this ?
  3450. frame = Math.min(frame, trackLen - 2);
  3451. }
  3452. else {
  3453. for (frame = lastFrame; frame < trackLen; frame++) {
  3454. if (kfPercents[frame] > percent) {
  3455. break;
  3456. }
  3457. }
  3458. frame = Math.min(frame - 1, trackLen - 2);
  3459. }
  3460. lastFrame = frame;
  3461. lastFramePercent = percent;
  3462. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3463. if (range === 0) {
  3464. return;
  3465. }
  3466. else {
  3467. w = (percent - kfPercents[frame]) / range;
  3468. }
  3469. if (useSpline) {
  3470. p1 = kfValues[frame];
  3471. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3472. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3473. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3474. if (isValueArray) {
  3475. catmullRomInterpolateArray(
  3476. p0, p1, p2, p3, w, w * w, w * w * w,
  3477. getter(target, propName),
  3478. arrDim
  3479. );
  3480. }
  3481. else {
  3482. var value;
  3483. if (isValueColor) {
  3484. value = catmullRomInterpolateArray(
  3485. p0, p1, p2, p3, w, w * w, w * w * w,
  3486. rgba, 1
  3487. );
  3488. value = rgba2String(rgba);
  3489. }
  3490. else if (isValueString) {
  3491. // String is step(0.5)
  3492. return interpolateString(p1, p2, w);
  3493. }
  3494. else {
  3495. value = catmullRomInterpolate(
  3496. p0, p1, p2, p3, w, w * w, w * w * w
  3497. );
  3498. }
  3499. setter(
  3500. target,
  3501. propName,
  3502. value
  3503. );
  3504. }
  3505. }
  3506. else {
  3507. if (isValueArray) {
  3508. interpolateArray(
  3509. kfValues[frame], kfValues[frame + 1], w,
  3510. getter(target, propName),
  3511. arrDim
  3512. );
  3513. }
  3514. else {
  3515. var value;
  3516. if (isValueColor) {
  3517. interpolateArray(
  3518. kfValues[frame], kfValues[frame + 1], w,
  3519. rgba, 1
  3520. );
  3521. value = rgba2String(rgba);
  3522. }
  3523. else if (isValueString) {
  3524. // String is step(0.5)
  3525. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3526. }
  3527. else {
  3528. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3529. }
  3530. setter(
  3531. target,
  3532. propName,
  3533. value
  3534. );
  3535. }
  3536. }
  3537. };
  3538. var clip = new Clip({
  3539. target: animator._target,
  3540. life: trackMaxTime,
  3541. loop: animator._loop,
  3542. delay: animator._delay,
  3543. onframe: onframe,
  3544. ondestroy: oneTrackDone
  3545. });
  3546. if (easing && easing !== 'spline') {
  3547. clip.easing = easing;
  3548. }
  3549. return clip;
  3550. }
  3551. /**
  3552. * @alias module:zrender/animation/Animator
  3553. * @constructor
  3554. * @param {Object} target
  3555. * @param {boolean} loop
  3556. * @param {Function} getter
  3557. * @param {Function} setter
  3558. */
  3559. var Animator = function(target, loop, getter, setter) {
  3560. this._tracks = {};
  3561. this._target = target;
  3562. this._loop = loop || false;
  3563. this._getter = getter || defaultGetter;
  3564. this._setter = setter || defaultSetter;
  3565. this._clipCount = 0;
  3566. this._delay = 0;
  3567. this._doneList = [];
  3568. this._onframeList = [];
  3569. this._clipList = [];
  3570. };
  3571. Animator.prototype = {
  3572. /**
  3573. * 设置动画关键帧
  3574. * @param {number} time 关键帧时间,单位是ms
  3575. * @param {Object} props 关键帧的属性值,key-value表示
  3576. * @return {module:zrender/animation/Animator}
  3577. */
  3578. when: function(time /* ms */, props) {
  3579. var tracks = this._tracks;
  3580. for (var propName in props) {
  3581. if (!props.hasOwnProperty(propName)) {
  3582. continue;
  3583. }
  3584. if (!tracks[propName]) {
  3585. tracks[propName] = [];
  3586. // Invalid value
  3587. var value = this._getter(this._target, propName);
  3588. if (value == null) {
  3589. // zrLog('Invalid property ' + propName);
  3590. continue;
  3591. }
  3592. // If time is 0
  3593. // Then props is given initialize value
  3594. // Else
  3595. // Initialize value from current prop value
  3596. if (time !== 0) {
  3597. tracks[propName].push({
  3598. time: 0,
  3599. value: cloneValue(value)
  3600. });
  3601. }
  3602. }
  3603. tracks[propName].push({
  3604. time: time,
  3605. value: props[propName]
  3606. });
  3607. }
  3608. return this;
  3609. },
  3610. /**
  3611. * 添加动画每一帧的回调函数
  3612. * @param {Function} callback
  3613. * @return {module:zrender/animation/Animator}
  3614. */
  3615. during: function (callback) {
  3616. this._onframeList.push(callback);
  3617. return this;
  3618. },
  3619. pause: function () {
  3620. for (var i = 0; i < this._clipList.length; i++) {
  3621. this._clipList[i].pause();
  3622. }
  3623. this._paused = true;
  3624. },
  3625. resume: function () {
  3626. for (var i = 0; i < this._clipList.length; i++) {
  3627. this._clipList[i].resume();
  3628. }
  3629. this._paused = false;
  3630. },
  3631. isPaused: function () {
  3632. return !!this._paused;
  3633. },
  3634. _doneCallback: function () {
  3635. // Clear all tracks
  3636. this._tracks = {};
  3637. // Clear all clips
  3638. this._clipList.length = 0;
  3639. var doneList = this._doneList;
  3640. var len = doneList.length;
  3641. for (var i = 0; i < len; i++) {
  3642. doneList[i].call(this);
  3643. }
  3644. },
  3645. /**
  3646. * 开始执行动画
  3647. * @param {string|Function} [easing]
  3648. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3649. * @param {boolean} forceAnimate
  3650. * @return {module:zrender/animation/Animator}
  3651. */
  3652. start: function (easing, forceAnimate) {
  3653. var self = this;
  3654. var clipCount = 0;
  3655. var oneTrackDone = function() {
  3656. clipCount--;
  3657. if (!clipCount) {
  3658. self._doneCallback();
  3659. }
  3660. };
  3661. var lastClip;
  3662. for (var propName in this._tracks) {
  3663. if (!this._tracks.hasOwnProperty(propName)) {
  3664. continue;
  3665. }
  3666. var clip = createTrackClip(
  3667. this, easing, oneTrackDone,
  3668. this._tracks[propName], propName, forceAnimate
  3669. );
  3670. if (clip) {
  3671. this._clipList.push(clip);
  3672. clipCount++;
  3673. // If start after added to animation
  3674. if (this.animation) {
  3675. this.animation.addClip(clip);
  3676. }
  3677. lastClip = clip;
  3678. }
  3679. }
  3680. // Add during callback on the last clip
  3681. if (lastClip) {
  3682. var oldOnFrame = lastClip.onframe;
  3683. lastClip.onframe = function (target, percent) {
  3684. oldOnFrame(target, percent);
  3685. for (var i = 0; i < self._onframeList.length; i++) {
  3686. self._onframeList[i](target, percent);
  3687. }
  3688. };
  3689. }
  3690. // This optimization will help the case that in the upper application
  3691. // the view may be refreshed frequently, where animation will be
  3692. // called repeatly but nothing changed.
  3693. if (!clipCount) {
  3694. this._doneCallback();
  3695. }
  3696. return this;
  3697. },
  3698. /**
  3699. * 停止动画
  3700. * @param {boolean} forwardToLast If move to last frame before stop
  3701. */
  3702. stop: function (forwardToLast) {
  3703. var clipList = this._clipList;
  3704. var animation = this.animation;
  3705. for (var i = 0; i < clipList.length; i++) {
  3706. var clip = clipList[i];
  3707. if (forwardToLast) {
  3708. // Move to last frame before stop
  3709. clip.onframe(this._target, 1);
  3710. }
  3711. animation && animation.removeClip(clip);
  3712. }
  3713. clipList.length = 0;
  3714. },
  3715. /**
  3716. * 设置动画延迟开始的时间
  3717. * @param {number} time 单位ms
  3718. * @return {module:zrender/animation/Animator}
  3719. */
  3720. delay: function (time) {
  3721. this._delay = time;
  3722. return this;
  3723. },
  3724. /**
  3725. * 添加动画结束的回调
  3726. * @param {Function} cb
  3727. * @return {module:zrender/animation/Animator}
  3728. */
  3729. done: function(cb) {
  3730. if (cb) {
  3731. this._doneList.push(cb);
  3732. }
  3733. return this;
  3734. },
  3735. /**
  3736. * @return {Array.<module:zrender/animation/Clip>}
  3737. */
  3738. getClips: function () {
  3739. return this._clipList;
  3740. }
  3741. };
  3742. var dpr = 1;
  3743. // If in browser environment
  3744. if (typeof window !== 'undefined') {
  3745. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3746. }
  3747. /**
  3748. * config默认配置项
  3749. * @exports zrender/config
  3750. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3751. */
  3752. /**
  3753. * debug日志选项:catchBrushException为true下有效
  3754. * 0 : 不生成debug数据,发布用
  3755. * 1 : 异常抛出,调试用
  3756. * 2 : 控制台输出,调试用
  3757. */
  3758. var debugMode = 0;
  3759. // retina 屏幕优化
  3760. var devicePixelRatio = dpr;
  3761. var log = function () {
  3762. };
  3763. if (debugMode === 1) {
  3764. log = function () {
  3765. for (var k in arguments) {
  3766. throw new Error(arguments[k]);
  3767. }
  3768. };
  3769. }
  3770. else if (debugMode > 1) {
  3771. log = function () {
  3772. for (var k in arguments) {
  3773. console.log(arguments[k]);
  3774. }
  3775. };
  3776. }
  3777. var zrLog = log;
  3778. /**
  3779. * @alias modue:zrender/mixin/Animatable
  3780. * @constructor
  3781. */
  3782. var Animatable = function () {
  3783. /**
  3784. * @type {Array.<module:zrender/animation/Animator>}
  3785. * @readOnly
  3786. */
  3787. this.animators = [];
  3788. };
  3789. Animatable.prototype = {
  3790. constructor: Animatable,
  3791. /**
  3792. * 动画
  3793. *
  3794. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3795. * @param {boolean} [loop] Whether to loop animation.
  3796. * @return {module:zrender/animation/Animator}
  3797. * @example:
  3798. * el.animate('style', false)
  3799. * .when(1000, {x: 10} )
  3800. * .done(function(){ // Animation done })
  3801. * .start()
  3802. */
  3803. animate: function (path, loop) {
  3804. var target;
  3805. var animatingShape = false;
  3806. var el = this;
  3807. var zr = this.__zr;
  3808. if (path) {
  3809. var pathSplitted = path.split('.');
  3810. var prop = el;
  3811. // If animating shape
  3812. animatingShape = pathSplitted[0] === 'shape';
  3813. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3814. if (!prop) {
  3815. continue;
  3816. }
  3817. prop = prop[pathSplitted[i]];
  3818. }
  3819. if (prop) {
  3820. target = prop;
  3821. }
  3822. }
  3823. else {
  3824. target = el;
  3825. }
  3826. if (!target) {
  3827. zrLog(
  3828. 'Property "'
  3829. + path
  3830. + '" is not existed in element '
  3831. + el.id
  3832. );
  3833. return;
  3834. }
  3835. var animators = el.animators;
  3836. var animator = new Animator(target, loop);
  3837. animator.during(function (target) {
  3838. el.dirty(animatingShape);
  3839. })
  3840. .done(function () {
  3841. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3842. animators.splice(indexOf(animators, animator), 1);
  3843. });
  3844. animators.push(animator);
  3845. // If animate after added to the zrender
  3846. if (zr) {
  3847. zr.animation.addAnimator(animator);
  3848. }
  3849. return animator;
  3850. },
  3851. /**
  3852. * 停止动画
  3853. * @param {boolean} forwardToLast If move to last frame before stop
  3854. */
  3855. stopAnimation: function (forwardToLast) {
  3856. var animators = this.animators;
  3857. var len = animators.length;
  3858. for (var i = 0; i < len; i++) {
  3859. animators[i].stop(forwardToLast);
  3860. }
  3861. animators.length = 0;
  3862. return this;
  3863. },
  3864. /**
  3865. * Caution: this method will stop previous animation.
  3866. * So do not use this method to one element twice before
  3867. * animation starts, unless you know what you are doing.
  3868. * @param {Object} target
  3869. * @param {number} [time=500] Time in ms
  3870. * @param {string} [easing='linear']
  3871. * @param {number} [delay=0]
  3872. * @param {Function} [callback]
  3873. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3874. * immediently when target values are the same as current values.
  3875. *
  3876. * @example
  3877. * // Animate position
  3878. * el.animateTo({
  3879. * position: [10, 10]
  3880. * }, function () { // done })
  3881. *
  3882. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3883. * el.animateTo({
  3884. * shape: {
  3885. * width: 500
  3886. * },
  3887. * style: {
  3888. * fill: 'red'
  3889. * }
  3890. * position: [10, 10]
  3891. * }, 100, 100, 'cubicOut', function () { // done })
  3892. */
  3893. // TODO Return animation key
  3894. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3895. // animateTo(target, time, easing, callback);
  3896. if (isString(delay)) {
  3897. callback = easing;
  3898. easing = delay;
  3899. delay = 0;
  3900. }
  3901. // animateTo(target, time, delay, callback);
  3902. else if (isFunction$1(easing)) {
  3903. callback = easing;
  3904. easing = 'linear';
  3905. delay = 0;
  3906. }
  3907. // animateTo(target, time, callback);
  3908. else if (isFunction$1(delay)) {
  3909. callback = delay;
  3910. delay = 0;
  3911. }
  3912. // animateTo(target, callback)
  3913. else if (isFunction$1(time)) {
  3914. callback = time;
  3915. time = 500;
  3916. }
  3917. // animateTo(target)
  3918. else if (!time) {
  3919. time = 500;
  3920. }
  3921. // Stop all previous animations
  3922. this.stopAnimation();
  3923. this._animateToShallow('', this, target, time, delay);
  3924. // Animators may be removed immediately after start
  3925. // if there is nothing to animate
  3926. var animators = this.animators.slice();
  3927. var count = animators.length;
  3928. function done() {
  3929. count--;
  3930. if (!count) {
  3931. callback && callback();
  3932. }
  3933. }
  3934. // No animators. This should be checked before animators[i].start(),
  3935. // because 'done' may be executed immediately if no need to animate.
  3936. if (!count) {
  3937. callback && callback();
  3938. }
  3939. // Start after all animators created
  3940. // Incase any animator is done immediately when all animation properties are not changed
  3941. for (var i = 0; i < animators.length; i++) {
  3942. animators[i]
  3943. .done(done)
  3944. .start(easing, forceAnimate);
  3945. }
  3946. },
  3947. /**
  3948. * @private
  3949. * @param {string} path=''
  3950. * @param {Object} source=this
  3951. * @param {Object} target
  3952. * @param {number} [time=500]
  3953. * @param {number} [delay=0]
  3954. *
  3955. * @example
  3956. * // Animate position
  3957. * el._animateToShallow({
  3958. * position: [10, 10]
  3959. * })
  3960. *
  3961. * // Animate shape, style and position in 100ms, delayed 100ms
  3962. * el._animateToShallow({
  3963. * shape: {
  3964. * width: 500
  3965. * },
  3966. * style: {
  3967. * fill: 'red'
  3968. * }
  3969. * position: [10, 10]
  3970. * }, 100, 100)
  3971. */
  3972. _animateToShallow: function (path, source, target, time, delay) {
  3973. var objShallow = {};
  3974. var propertyCount = 0;
  3975. for (var name in target) {
  3976. if (!target.hasOwnProperty(name)) {
  3977. continue;
  3978. }
  3979. if (source[name] != null) {
  3980. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  3981. this._animateToShallow(
  3982. path ? path + '.' + name : name,
  3983. source[name],
  3984. target[name],
  3985. time,
  3986. delay
  3987. );
  3988. }
  3989. else {
  3990. objShallow[name] = target[name];
  3991. propertyCount++;
  3992. }
  3993. }
  3994. else if (target[name] != null) {
  3995. // Attr directly if not has property
  3996. // FIXME, if some property not needed for element ?
  3997. if (!path) {
  3998. this.attr(name, target[name]);
  3999. }
  4000. else { // Shape or style
  4001. var props = {};
  4002. props[path] = {};
  4003. props[path][name] = target[name];
  4004. this.attr(props);
  4005. }
  4006. }
  4007. }
  4008. if (propertyCount > 0) {
  4009. this.animate(path, false)
  4010. .when(time == null ? 500 : time, objShallow)
  4011. .delay(delay || 0);
  4012. }
  4013. return this;
  4014. }
  4015. };
  4016. /**
  4017. * @alias module:zrender/Element
  4018. * @constructor
  4019. * @extends {module:zrender/mixin/Animatable}
  4020. * @extends {module:zrender/mixin/Transformable}
  4021. * @extends {module:zrender/mixin/Eventful}
  4022. */
  4023. var Element = function (opts) { // jshint ignore:line
  4024. Transformable.call(this, opts);
  4025. Eventful.call(this, opts);
  4026. Animatable.call(this, opts);
  4027. /**
  4028. * 画布元素ID
  4029. * @type {string}
  4030. */
  4031. this.id = opts.id || guid();
  4032. };
  4033. Element.prototype = {
  4034. /**
  4035. * 元素类型
  4036. * Element type
  4037. * @type {string}
  4038. */
  4039. type: 'element',
  4040. /**
  4041. * 元素名字
  4042. * Element name
  4043. * @type {string}
  4044. */
  4045. name: '',
  4046. /**
  4047. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4048. * ZRender instance will be assigned when element is associated with zrender
  4049. * @name module:/zrender/Element#__zr
  4050. * @type {module:zrender/ZRender}
  4051. */
  4052. __zr: null,
  4053. /**
  4054. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4055. * If ignore drawing and events of the element object
  4056. * @name module:/zrender/Element#ignore
  4057. * @type {boolean}
  4058. * @default false
  4059. */
  4060. ignore: false,
  4061. /**
  4062. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4063. * 该路径会继承被裁减对象的变换
  4064. * @type {module:zrender/graphic/Path}
  4065. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4066. * @readOnly
  4067. */
  4068. clipPath: null,
  4069. /**
  4070. * 是否是 Group
  4071. * @type {boolean}
  4072. */
  4073. isGroup: false,
  4074. /**
  4075. * Drift element
  4076. * @param {number} dx dx on the global space
  4077. * @param {number} dy dy on the global space
  4078. */
  4079. drift: function (dx, dy) {
  4080. switch (this.draggable) {
  4081. case 'horizontal':
  4082. dy = 0;
  4083. break;
  4084. case 'vertical':
  4085. dx = 0;
  4086. break;
  4087. }
  4088. var m = this.transform;
  4089. if (!m) {
  4090. m = this.transform = [1, 0, 0, 1, 0, 0];
  4091. }
  4092. m[4] += dx;
  4093. m[5] += dy;
  4094. this.decomposeTransform();
  4095. this.dirty(false);
  4096. },
  4097. /**
  4098. * Hook before update
  4099. */
  4100. beforeUpdate: function () {},
  4101. /**
  4102. * Hook after update
  4103. */
  4104. afterUpdate: function () {},
  4105. /**
  4106. * Update each frame
  4107. */
  4108. update: function () {
  4109. this.updateTransform();
  4110. },
  4111. /**
  4112. * @param {Function} cb
  4113. * @param {} context
  4114. */
  4115. traverse: function (cb, context) {},
  4116. /**
  4117. * @protected
  4118. */
  4119. attrKV: function (key, value) {
  4120. if (key === 'position' || key === 'scale' || key === 'origin') {
  4121. // Copy the array
  4122. if (value) {
  4123. var target = this[key];
  4124. if (!target) {
  4125. target = this[key] = [];
  4126. }
  4127. target[0] = value[0];
  4128. target[1] = value[1];
  4129. }
  4130. }
  4131. else {
  4132. this[key] = value;
  4133. }
  4134. },
  4135. /**
  4136. * Hide the element
  4137. */
  4138. hide: function () {
  4139. this.ignore = true;
  4140. this.__zr && this.__zr.refresh();
  4141. },
  4142. /**
  4143. * Show the element
  4144. */
  4145. show: function () {
  4146. this.ignore = false;
  4147. this.__zr && this.__zr.refresh();
  4148. },
  4149. /**
  4150. * @param {string|Object} key
  4151. * @param {*} value
  4152. */
  4153. attr: function (key, value) {
  4154. if (typeof key === 'string') {
  4155. this.attrKV(key, value);
  4156. }
  4157. else if (isObject$1(key)) {
  4158. for (var name in key) {
  4159. if (key.hasOwnProperty(name)) {
  4160. this.attrKV(name, key[name]);
  4161. }
  4162. }
  4163. }
  4164. this.dirty(false);
  4165. return this;
  4166. },
  4167. /**
  4168. * @param {module:zrender/graphic/Path} clipPath
  4169. */
  4170. setClipPath: function (clipPath) {
  4171. var zr = this.__zr;
  4172. if (zr) {
  4173. clipPath.addSelfToZr(zr);
  4174. }
  4175. // Remove previous clip path
  4176. if (this.clipPath && this.clipPath !== clipPath) {
  4177. this.removeClipPath();
  4178. }
  4179. this.clipPath = clipPath;
  4180. clipPath.__zr = zr;
  4181. clipPath.__clipTarget = this;
  4182. this.dirty(false);
  4183. },
  4184. /**
  4185. */
  4186. removeClipPath: function () {
  4187. var clipPath = this.clipPath;
  4188. if (clipPath) {
  4189. if (clipPath.__zr) {
  4190. clipPath.removeSelfFromZr(clipPath.__zr);
  4191. }
  4192. clipPath.__zr = null;
  4193. clipPath.__clipTarget = null;
  4194. this.clipPath = null;
  4195. this.dirty(false);
  4196. }
  4197. },
  4198. /**
  4199. * Add 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. addSelfToZr: function (zr) {
  4204. this.__zr = zr;
  4205. // 添加动画
  4206. var animators = this.animators;
  4207. if (animators) {
  4208. for (var i = 0; i < animators.length; i++) {
  4209. zr.animation.addAnimator(animators[i]);
  4210. }
  4211. }
  4212. if (this.clipPath) {
  4213. this.clipPath.addSelfToZr(zr);
  4214. }
  4215. },
  4216. /**
  4217. * Remove self from zrender instance.
  4218. * Not recursively because it will be invoked when element added to storage.
  4219. * @param {module:zrender/ZRender} zr
  4220. */
  4221. removeSelfFromZr: function (zr) {
  4222. this.__zr = null;
  4223. // 移除动画
  4224. var animators = this.animators;
  4225. if (animators) {
  4226. for (var i = 0; i < animators.length; i++) {
  4227. zr.animation.removeAnimator(animators[i]);
  4228. }
  4229. }
  4230. if (this.clipPath) {
  4231. this.clipPath.removeSelfFromZr(zr);
  4232. }
  4233. }
  4234. };
  4235. mixin(Element, Animatable);
  4236. mixin(Element, Transformable);
  4237. mixin(Element, Eventful);
  4238. /**
  4239. * @module echarts/core/BoundingRect
  4240. */
  4241. var v2ApplyTransform = applyTransform;
  4242. var mathMin = Math.min;
  4243. var mathMax = Math.max;
  4244. /**
  4245. * @alias module:echarts/core/BoundingRect
  4246. */
  4247. function BoundingRect(x, y, width, height) {
  4248. if (width < 0) {
  4249. x = x + width;
  4250. width = -width;
  4251. }
  4252. if (height < 0) {
  4253. y = y + height;
  4254. height = -height;
  4255. }
  4256. /**
  4257. * @type {number}
  4258. */
  4259. this.x = x;
  4260. /**
  4261. * @type {number}
  4262. */
  4263. this.y = y;
  4264. /**
  4265. * @type {number}
  4266. */
  4267. this.width = width;
  4268. /**
  4269. * @type {number}
  4270. */
  4271. this.height = height;
  4272. }
  4273. BoundingRect.prototype = {
  4274. constructor: BoundingRect,
  4275. /**
  4276. * @param {module:echarts/core/BoundingRect} other
  4277. */
  4278. union: function (other) {
  4279. var x = mathMin(other.x, this.x);
  4280. var y = mathMin(other.y, this.y);
  4281. this.width = mathMax(
  4282. other.x + other.width,
  4283. this.x + this.width
  4284. ) - x;
  4285. this.height = mathMax(
  4286. other.y + other.height,
  4287. this.y + this.height
  4288. ) - y;
  4289. this.x = x;
  4290. this.y = y;
  4291. },
  4292. /**
  4293. * @param {Array.<number>} m
  4294. * @methods
  4295. */
  4296. applyTransform: (function () {
  4297. var lt = [];
  4298. var rb = [];
  4299. var lb = [];
  4300. var rt = [];
  4301. return function (m) {
  4302. // In case usage like this
  4303. // el.getBoundingRect().applyTransform(el.transform)
  4304. // And element has no transform
  4305. if (!m) {
  4306. return;
  4307. }
  4308. lt[0] = lb[0] = this.x;
  4309. lt[1] = rt[1] = this.y;
  4310. rb[0] = rt[0] = this.x + this.width;
  4311. rb[1] = lb[1] = this.y + this.height;
  4312. v2ApplyTransform(lt, lt, m);
  4313. v2ApplyTransform(rb, rb, m);
  4314. v2ApplyTransform(lb, lb, m);
  4315. v2ApplyTransform(rt, rt, m);
  4316. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4317. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4318. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4319. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4320. this.width = maxX - this.x;
  4321. this.height = maxY - this.y;
  4322. };
  4323. })(),
  4324. /**
  4325. * Calculate matrix of transforming from self to target rect
  4326. * @param {module:zrender/core/BoundingRect} b
  4327. * @return {Array.<number>}
  4328. */
  4329. calculateTransform: function (b) {
  4330. var a = this;
  4331. var sx = b.width / a.width;
  4332. var sy = b.height / a.height;
  4333. var m = create$1();
  4334. // 矩阵右乘
  4335. translate(m, m, [-a.x, -a.y]);
  4336. scale$1(m, m, [sx, sy]);
  4337. translate(m, m, [b.x, b.y]);
  4338. return m;
  4339. },
  4340. /**
  4341. * @param {(module:echarts/core/BoundingRect|Object)} b
  4342. * @return {boolean}
  4343. */
  4344. intersect: function (b) {
  4345. if (!b) {
  4346. return false;
  4347. }
  4348. if (!(b instanceof BoundingRect)) {
  4349. // Normalize negative width/height.
  4350. b = BoundingRect.create(b);
  4351. }
  4352. var a = this;
  4353. var ax0 = a.x;
  4354. var ax1 = a.x + a.width;
  4355. var ay0 = a.y;
  4356. var ay1 = a.y + a.height;
  4357. var bx0 = b.x;
  4358. var bx1 = b.x + b.width;
  4359. var by0 = b.y;
  4360. var by1 = b.y + b.height;
  4361. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4362. },
  4363. contain: function (x, y) {
  4364. var rect = this;
  4365. return x >= rect.x
  4366. && x <= (rect.x + rect.width)
  4367. && y >= rect.y
  4368. && y <= (rect.y + rect.height);
  4369. },
  4370. /**
  4371. * @return {module:echarts/core/BoundingRect}
  4372. */
  4373. clone: function () {
  4374. return new BoundingRect(this.x, this.y, this.width, this.height);
  4375. },
  4376. /**
  4377. * Copy from another rect
  4378. */
  4379. copy: function (other) {
  4380. this.x = other.x;
  4381. this.y = other.y;
  4382. this.width = other.width;
  4383. this.height = other.height;
  4384. },
  4385. plain: function () {
  4386. return {
  4387. x: this.x,
  4388. y: this.y,
  4389. width: this.width,
  4390. height: this.height
  4391. };
  4392. }
  4393. };
  4394. /**
  4395. * @param {Object|module:zrender/core/BoundingRect} rect
  4396. * @param {number} rect.x
  4397. * @param {number} rect.y
  4398. * @param {number} rect.width
  4399. * @param {number} rect.height
  4400. * @return {module:zrender/core/BoundingRect}
  4401. */
  4402. BoundingRect.create = function (rect) {
  4403. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4404. };
  4405. /**
  4406. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4407. * @module zrender/graphic/Group
  4408. * @example
  4409. * var Group = require('zrender/container/Group');
  4410. * var Circle = require('zrender/graphic/shape/Circle');
  4411. * var g = new Group();
  4412. * g.position[0] = 100;
  4413. * g.position[1] = 100;
  4414. * g.add(new Circle({
  4415. * style: {
  4416. * x: 100,
  4417. * y: 100,
  4418. * r: 20,
  4419. * }
  4420. * }));
  4421. * zr.add(g);
  4422. */
  4423. /**
  4424. * @alias module:zrender/graphic/Group
  4425. * @constructor
  4426. * @extends module:zrender/mixin/Transformable
  4427. * @extends module:zrender/mixin/Eventful
  4428. */
  4429. var Group = function (opts) {
  4430. opts = opts || {};
  4431. Element.call(this, opts);
  4432. for (var key in opts) {
  4433. if (opts.hasOwnProperty(key)) {
  4434. this[key] = opts[key];
  4435. }
  4436. }
  4437. this._children = [];
  4438. this.__storage = null;
  4439. this.__dirty = true;
  4440. };
  4441. Group.prototype = {
  4442. constructor: Group,
  4443. isGroup: true,
  4444. /**
  4445. * @type {string}
  4446. */
  4447. type: 'group',
  4448. /**
  4449. * 所有子孙元素是否响应鼠标事件
  4450. * @name module:/zrender/container/Group#silent
  4451. * @type {boolean}
  4452. * @default false
  4453. */
  4454. silent: false,
  4455. /**
  4456. * @return {Array.<module:zrender/Element>}
  4457. */
  4458. children: function () {
  4459. return this._children.slice();
  4460. },
  4461. /**
  4462. * 获取指定 index 的儿子节点
  4463. * @param {number} idx
  4464. * @return {module:zrender/Element}
  4465. */
  4466. childAt: function (idx) {
  4467. return this._children[idx];
  4468. },
  4469. /**
  4470. * 获取指定名字的儿子节点
  4471. * @param {string} name
  4472. * @return {module:zrender/Element}
  4473. */
  4474. childOfName: function (name) {
  4475. var children = this._children;
  4476. for (var i = 0; i < children.length; i++) {
  4477. if (children[i].name === name) {
  4478. return children[i];
  4479. }
  4480. }
  4481. },
  4482. /**
  4483. * @return {number}
  4484. */
  4485. childCount: function () {
  4486. return this._children.length;
  4487. },
  4488. /**
  4489. * 添加子节点到最后
  4490. * @param {module:zrender/Element} child
  4491. */
  4492. add: function (child) {
  4493. if (child && child !== this && child.parent !== this) {
  4494. this._children.push(child);
  4495. this._doAdd(child);
  4496. }
  4497. return this;
  4498. },
  4499. /**
  4500. * 添加子节点在 nextSibling 之前
  4501. * @param {module:zrender/Element} child
  4502. * @param {module:zrender/Element} nextSibling
  4503. */
  4504. addBefore: function (child, nextSibling) {
  4505. if (child && child !== this && child.parent !== this
  4506. && nextSibling && nextSibling.parent === this) {
  4507. var children = this._children;
  4508. var idx = children.indexOf(nextSibling);
  4509. if (idx >= 0) {
  4510. children.splice(idx, 0, child);
  4511. this._doAdd(child);
  4512. }
  4513. }
  4514. return this;
  4515. },
  4516. _doAdd: function (child) {
  4517. if (child.parent) {
  4518. child.parent.remove(child);
  4519. }
  4520. child.parent = this;
  4521. var storage = this.__storage;
  4522. var zr = this.__zr;
  4523. if (storage && storage !== child.__storage) {
  4524. storage.addToStorage(child);
  4525. if (child instanceof Group) {
  4526. child.addChildrenToStorage(storage);
  4527. }
  4528. }
  4529. zr && zr.refresh();
  4530. },
  4531. /**
  4532. * 移除子节点
  4533. * @param {module:zrender/Element} child
  4534. */
  4535. remove: function (child) {
  4536. var zr = this.__zr;
  4537. var storage = this.__storage;
  4538. var children = this._children;
  4539. var idx = indexOf(children, child);
  4540. if (idx < 0) {
  4541. return this;
  4542. }
  4543. children.splice(idx, 1);
  4544. child.parent = null;
  4545. if (storage) {
  4546. storage.delFromStorage(child);
  4547. if (child instanceof Group) {
  4548. child.delChildrenFromStorage(storage);
  4549. }
  4550. }
  4551. zr && zr.refresh();
  4552. return this;
  4553. },
  4554. /**
  4555. * 移除所有子节点
  4556. */
  4557. removeAll: function () {
  4558. var children = this._children;
  4559. var storage = this.__storage;
  4560. var child;
  4561. var i;
  4562. for (i = 0; i < children.length; i++) {
  4563. child = children[i];
  4564. if (storage) {
  4565. storage.delFromStorage(child);
  4566. if (child instanceof Group) {
  4567. child.delChildrenFromStorage(storage);
  4568. }
  4569. }
  4570. child.parent = null;
  4571. }
  4572. children.length = 0;
  4573. return this;
  4574. },
  4575. /**
  4576. * 遍历所有子节点
  4577. * @param {Function} cb
  4578. * @param {} context
  4579. */
  4580. eachChild: function (cb, context) {
  4581. var children = this._children;
  4582. for (var i = 0; i < children.length; i++) {
  4583. var child = children[i];
  4584. cb.call(context, child, i);
  4585. }
  4586. return this;
  4587. },
  4588. /**
  4589. * 深度优先遍历所有子孙节点
  4590. * @param {Function} cb
  4591. * @param {} context
  4592. */
  4593. traverse: function (cb, context) {
  4594. for (var i = 0; i < this._children.length; i++) {
  4595. var child = this._children[i];
  4596. cb.call(context, child);
  4597. if (child.type === 'group') {
  4598. child.traverse(cb, context);
  4599. }
  4600. }
  4601. return this;
  4602. },
  4603. addChildrenToStorage: function (storage) {
  4604. for (var i = 0; i < this._children.length; i++) {
  4605. var child = this._children[i];
  4606. storage.addToStorage(child);
  4607. if (child instanceof Group) {
  4608. child.addChildrenToStorage(storage);
  4609. }
  4610. }
  4611. },
  4612. delChildrenFromStorage: function (storage) {
  4613. for (var i = 0; i < this._children.length; i++) {
  4614. var child = this._children[i];
  4615. storage.delFromStorage(child);
  4616. if (child instanceof Group) {
  4617. child.delChildrenFromStorage(storage);
  4618. }
  4619. }
  4620. },
  4621. dirty: function () {
  4622. this.__dirty = true;
  4623. this.__zr && this.__zr.refresh();
  4624. return this;
  4625. },
  4626. /**
  4627. * @return {module:zrender/core/BoundingRect}
  4628. */
  4629. getBoundingRect: function (includeChildren) {
  4630. // TODO Caching
  4631. var rect = null;
  4632. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4633. var children = includeChildren || this._children;
  4634. var tmpMat = [];
  4635. for (var i = 0; i < children.length; i++) {
  4636. var child = children[i];
  4637. if (child.ignore || child.invisible) {
  4638. continue;
  4639. }
  4640. var childRect = child.getBoundingRect();
  4641. var transform = child.getLocalTransform(tmpMat);
  4642. // TODO
  4643. // The boundingRect cacluated by transforming original
  4644. // rect may be bigger than the actual bundingRect when rotation
  4645. // is used. (Consider a circle rotated aginst its center, where
  4646. // the actual boundingRect should be the same as that not be
  4647. // rotated.) But we can not find better approach to calculate
  4648. // actual boundingRect yet, considering performance.
  4649. if (transform) {
  4650. tmpRect.copy(childRect);
  4651. tmpRect.applyTransform(transform);
  4652. rect = rect || tmpRect.clone();
  4653. rect.union(tmpRect);
  4654. }
  4655. else {
  4656. rect = rect || childRect.clone();
  4657. rect.union(childRect);
  4658. }
  4659. }
  4660. return rect || tmpRect;
  4661. }
  4662. };
  4663. inherits(Group, Element);
  4664. // https://github.com/mziccard/node-timsort
  4665. var DEFAULT_MIN_MERGE = 32;
  4666. var DEFAULT_MIN_GALLOPING = 7;
  4667. function minRunLength(n) {
  4668. var r = 0;
  4669. while (n >= DEFAULT_MIN_MERGE) {
  4670. r |= n & 1;
  4671. n >>= 1;
  4672. }
  4673. return n + r;
  4674. }
  4675. function makeAscendingRun(array, lo, hi, compare) {
  4676. var runHi = lo + 1;
  4677. if (runHi === hi) {
  4678. return 1;
  4679. }
  4680. if (compare(array[runHi++], array[lo]) < 0) {
  4681. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4682. runHi++;
  4683. }
  4684. reverseRun(array, lo, runHi);
  4685. }
  4686. else {
  4687. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4688. runHi++;
  4689. }
  4690. }
  4691. return runHi - lo;
  4692. }
  4693. function reverseRun(array, lo, hi) {
  4694. hi--;
  4695. while (lo < hi) {
  4696. var t = array[lo];
  4697. array[lo++] = array[hi];
  4698. array[hi--] = t;
  4699. }
  4700. }
  4701. function binaryInsertionSort(array, lo, hi, start, compare) {
  4702. if (start === lo) {
  4703. start++;
  4704. }
  4705. for (; start < hi; start++) {
  4706. var pivot = array[start];
  4707. var left = lo;
  4708. var right = start;
  4709. var mid;
  4710. while (left < right) {
  4711. mid = left + right >>> 1;
  4712. if (compare(pivot, array[mid]) < 0) {
  4713. right = mid;
  4714. }
  4715. else {
  4716. left = mid + 1;
  4717. }
  4718. }
  4719. var n = start - left;
  4720. switch (n) {
  4721. case 3:
  4722. array[left + 3] = array[left + 2];
  4723. case 2:
  4724. array[left + 2] = array[left + 1];
  4725. case 1:
  4726. array[left + 1] = array[left];
  4727. break;
  4728. default:
  4729. while (n > 0) {
  4730. array[left + n] = array[left + n - 1];
  4731. n--;
  4732. }
  4733. }
  4734. array[left] = pivot;
  4735. }
  4736. }
  4737. function gallopLeft(value, array, start, length, hint, compare) {
  4738. var lastOffset = 0;
  4739. var maxOffset = 0;
  4740. var offset = 1;
  4741. if (compare(value, array[start + hint]) > 0) {
  4742. maxOffset = length - hint;
  4743. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4744. lastOffset = offset;
  4745. offset = (offset << 1) + 1;
  4746. if (offset <= 0) {
  4747. offset = maxOffset;
  4748. }
  4749. }
  4750. if (offset > maxOffset) {
  4751. offset = maxOffset;
  4752. }
  4753. lastOffset += hint;
  4754. offset += hint;
  4755. }
  4756. else {
  4757. maxOffset = hint + 1;
  4758. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4759. lastOffset = offset;
  4760. offset = (offset << 1) + 1;
  4761. if (offset <= 0) {
  4762. offset = maxOffset;
  4763. }
  4764. }
  4765. if (offset > maxOffset) {
  4766. offset = maxOffset;
  4767. }
  4768. var tmp = lastOffset;
  4769. lastOffset = hint - offset;
  4770. offset = hint - tmp;
  4771. }
  4772. lastOffset++;
  4773. while (lastOffset < offset) {
  4774. var m = lastOffset + (offset - lastOffset >>> 1);
  4775. if (compare(value, array[start + m]) > 0) {
  4776. lastOffset = m + 1;
  4777. }
  4778. else {
  4779. offset = m;
  4780. }
  4781. }
  4782. return offset;
  4783. }
  4784. function gallopRight(value, array, start, length, hint, compare) {
  4785. var lastOffset = 0;
  4786. var maxOffset = 0;
  4787. var offset = 1;
  4788. if (compare(value, array[start + hint]) < 0) {
  4789. maxOffset = hint + 1;
  4790. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4791. lastOffset = offset;
  4792. offset = (offset << 1) + 1;
  4793. if (offset <= 0) {
  4794. offset = maxOffset;
  4795. }
  4796. }
  4797. if (offset > maxOffset) {
  4798. offset = maxOffset;
  4799. }
  4800. var tmp = lastOffset;
  4801. lastOffset = hint - offset;
  4802. offset = hint - tmp;
  4803. }
  4804. else {
  4805. maxOffset = length - hint;
  4806. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4807. lastOffset = offset;
  4808. offset = (offset << 1) + 1;
  4809. if (offset <= 0) {
  4810. offset = maxOffset;
  4811. }
  4812. }
  4813. if (offset > maxOffset) {
  4814. offset = maxOffset;
  4815. }
  4816. lastOffset += hint;
  4817. offset += hint;
  4818. }
  4819. lastOffset++;
  4820. while (lastOffset < offset) {
  4821. var m = lastOffset + (offset - lastOffset >>> 1);
  4822. if (compare(value, array[start + m]) < 0) {
  4823. offset = m;
  4824. }
  4825. else {
  4826. lastOffset = m + 1;
  4827. }
  4828. }
  4829. return offset;
  4830. }
  4831. function TimSort(array, compare) {
  4832. var minGallop = DEFAULT_MIN_GALLOPING;
  4833. var runStart;
  4834. var runLength;
  4835. var stackSize = 0;
  4836. var tmp = [];
  4837. runStart = [];
  4838. runLength = [];
  4839. function pushRun(_runStart, _runLength) {
  4840. runStart[stackSize] = _runStart;
  4841. runLength[stackSize] = _runLength;
  4842. stackSize += 1;
  4843. }
  4844. function mergeRuns() {
  4845. while (stackSize > 1) {
  4846. var n = stackSize - 2;
  4847. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4848. if (runLength[n - 1] < runLength[n + 1]) {
  4849. n--;
  4850. }
  4851. }
  4852. else if (runLength[n] > runLength[n + 1]) {
  4853. break;
  4854. }
  4855. mergeAt(n);
  4856. }
  4857. }
  4858. function forceMergeRuns() {
  4859. while (stackSize > 1) {
  4860. var n = stackSize - 2;
  4861. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4862. n--;
  4863. }
  4864. mergeAt(n);
  4865. }
  4866. }
  4867. function mergeAt(i) {
  4868. var start1 = runStart[i];
  4869. var length1 = runLength[i];
  4870. var start2 = runStart[i + 1];
  4871. var length2 = runLength[i + 1];
  4872. runLength[i] = length1 + length2;
  4873. if (i === stackSize - 3) {
  4874. runStart[i + 1] = runStart[i + 2];
  4875. runLength[i + 1] = runLength[i + 2];
  4876. }
  4877. stackSize--;
  4878. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4879. start1 += k;
  4880. length1 -= k;
  4881. if (length1 === 0) {
  4882. return;
  4883. }
  4884. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4885. if (length2 === 0) {
  4886. return;
  4887. }
  4888. if (length1 <= length2) {
  4889. mergeLow(start1, length1, start2, length2);
  4890. }
  4891. else {
  4892. mergeHigh(start1, length1, start2, length2);
  4893. }
  4894. }
  4895. function mergeLow(start1, length1, start2, length2) {
  4896. var i = 0;
  4897. for (i = 0; i < length1; i++) {
  4898. tmp[i] = array[start1 + i];
  4899. }
  4900. var cursor1 = 0;
  4901. var cursor2 = start2;
  4902. var dest = start1;
  4903. array[dest++] = array[cursor2++];
  4904. if (--length2 === 0) {
  4905. for (i = 0; i < length1; i++) {
  4906. array[dest + i] = tmp[cursor1 + i];
  4907. }
  4908. return;
  4909. }
  4910. if (length1 === 1) {
  4911. for (i = 0; i < length2; i++) {
  4912. array[dest + i] = array[cursor2 + i];
  4913. }
  4914. array[dest + length2] = tmp[cursor1];
  4915. return;
  4916. }
  4917. var _minGallop = minGallop;
  4918. var count1, count2, exit;
  4919. while (1) {
  4920. count1 = 0;
  4921. count2 = 0;
  4922. exit = false;
  4923. do {
  4924. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4925. array[dest++] = array[cursor2++];
  4926. count2++;
  4927. count1 = 0;
  4928. if (--length2 === 0) {
  4929. exit = true;
  4930. break;
  4931. }
  4932. }
  4933. else {
  4934. array[dest++] = tmp[cursor1++];
  4935. count1++;
  4936. count2 = 0;
  4937. if (--length1 === 1) {
  4938. exit = true;
  4939. break;
  4940. }
  4941. }
  4942. } while ((count1 | count2) < _minGallop);
  4943. if (exit) {
  4944. break;
  4945. }
  4946. do {
  4947. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4948. if (count1 !== 0) {
  4949. for (i = 0; i < count1; i++) {
  4950. array[dest + i] = tmp[cursor1 + i];
  4951. }
  4952. dest += count1;
  4953. cursor1 += count1;
  4954. length1 -= count1;
  4955. if (length1 <= 1) {
  4956. exit = true;
  4957. break;
  4958. }
  4959. }
  4960. array[dest++] = array[cursor2++];
  4961. if (--length2 === 0) {
  4962. exit = true;
  4963. break;
  4964. }
  4965. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4966. if (count2 !== 0) {
  4967. for (i = 0; i < count2; i++) {
  4968. array[dest + i] = array[cursor2 + i];
  4969. }
  4970. dest += count2;
  4971. cursor2 += count2;
  4972. length2 -= count2;
  4973. if (length2 === 0) {
  4974. exit = true;
  4975. break;
  4976. }
  4977. }
  4978. array[dest++] = tmp[cursor1++];
  4979. if (--length1 === 1) {
  4980. exit = true;
  4981. break;
  4982. }
  4983. _minGallop--;
  4984. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4985. if (exit) {
  4986. break;
  4987. }
  4988. if (_minGallop < 0) {
  4989. _minGallop = 0;
  4990. }
  4991. _minGallop += 2;
  4992. }
  4993. minGallop = _minGallop;
  4994. minGallop < 1 && (minGallop = 1);
  4995. if (length1 === 1) {
  4996. for (i = 0; i < length2; i++) {
  4997. array[dest + i] = array[cursor2 + i];
  4998. }
  4999. array[dest + length2] = tmp[cursor1];
  5000. }
  5001. else if (length1 === 0) {
  5002. throw new Error();
  5003. // throw new Error('mergeLow preconditions were not respected');
  5004. }
  5005. else {
  5006. for (i = 0; i < length1; i++) {
  5007. array[dest + i] = tmp[cursor1 + i];
  5008. }
  5009. }
  5010. }
  5011. function mergeHigh (start1, length1, start2, length2) {
  5012. var i = 0;
  5013. for (i = 0; i < length2; i++) {
  5014. tmp[i] = array[start2 + i];
  5015. }
  5016. var cursor1 = start1 + length1 - 1;
  5017. var cursor2 = length2 - 1;
  5018. var dest = start2 + length2 - 1;
  5019. var customCursor = 0;
  5020. var customDest = 0;
  5021. array[dest--] = array[cursor1--];
  5022. if (--length1 === 0) {
  5023. customCursor = dest - (length2 - 1);
  5024. for (i = 0; i < length2; i++) {
  5025. array[customCursor + i] = tmp[i];
  5026. }
  5027. return;
  5028. }
  5029. if (length2 === 1) {
  5030. dest -= length1;
  5031. cursor1 -= length1;
  5032. customDest = dest + 1;
  5033. customCursor = cursor1 + 1;
  5034. for (i = length1 - 1; i >= 0; i--) {
  5035. array[customDest + i] = array[customCursor + i];
  5036. }
  5037. array[dest] = tmp[cursor2];
  5038. return;
  5039. }
  5040. var _minGallop = minGallop;
  5041. while (true) {
  5042. var count1 = 0;
  5043. var count2 = 0;
  5044. var exit = false;
  5045. do {
  5046. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5047. array[dest--] = array[cursor1--];
  5048. count1++;
  5049. count2 = 0;
  5050. if (--length1 === 0) {
  5051. exit = true;
  5052. break;
  5053. }
  5054. }
  5055. else {
  5056. array[dest--] = tmp[cursor2--];
  5057. count2++;
  5058. count1 = 0;
  5059. if (--length2 === 1) {
  5060. exit = true;
  5061. break;
  5062. }
  5063. }
  5064. } while ((count1 | count2) < _minGallop);
  5065. if (exit) {
  5066. break;
  5067. }
  5068. do {
  5069. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5070. if (count1 !== 0) {
  5071. dest -= count1;
  5072. cursor1 -= count1;
  5073. length1 -= count1;
  5074. customDest = dest + 1;
  5075. customCursor = cursor1 + 1;
  5076. for (i = count1 - 1; i >= 0; i--) {
  5077. array[customDest + i] = array[customCursor + i];
  5078. }
  5079. if (length1 === 0) {
  5080. exit = true;
  5081. break;
  5082. }
  5083. }
  5084. array[dest--] = tmp[cursor2--];
  5085. if (--length2 === 1) {
  5086. exit = true;
  5087. break;
  5088. }
  5089. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5090. if (count2 !== 0) {
  5091. dest -= count2;
  5092. cursor2 -= count2;
  5093. length2 -= count2;
  5094. customDest = dest + 1;
  5095. customCursor = cursor2 + 1;
  5096. for (i = 0; i < count2; i++) {
  5097. array[customDest + i] = tmp[customCursor + i];
  5098. }
  5099. if (length2 <= 1) {
  5100. exit = true;
  5101. break;
  5102. }
  5103. }
  5104. array[dest--] = array[cursor1--];
  5105. if (--length1 === 0) {
  5106. exit = true;
  5107. break;
  5108. }
  5109. _minGallop--;
  5110. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5111. if (exit) {
  5112. break;
  5113. }
  5114. if (_minGallop < 0) {
  5115. _minGallop = 0;
  5116. }
  5117. _minGallop += 2;
  5118. }
  5119. minGallop = _minGallop;
  5120. if (minGallop < 1) {
  5121. minGallop = 1;
  5122. }
  5123. if (length2 === 1) {
  5124. dest -= length1;
  5125. cursor1 -= length1;
  5126. customDest = dest + 1;
  5127. customCursor = cursor1 + 1;
  5128. for (i = length1 - 1; i >= 0; i--) {
  5129. array[customDest + i] = array[customCursor + i];
  5130. }
  5131. array[dest] = tmp[cursor2];
  5132. }
  5133. else if (length2 === 0) {
  5134. throw new Error();
  5135. // throw new Error('mergeHigh preconditions were not respected');
  5136. }
  5137. else {
  5138. customCursor = dest - (length2 - 1);
  5139. for (i = 0; i < length2; i++) {
  5140. array[customCursor + i] = tmp[i];
  5141. }
  5142. }
  5143. }
  5144. this.mergeRuns = mergeRuns;
  5145. this.forceMergeRuns = forceMergeRuns;
  5146. this.pushRun = pushRun;
  5147. }
  5148. function sort(array, compare, lo, hi) {
  5149. if (!lo) {
  5150. lo = 0;
  5151. }
  5152. if (!hi) {
  5153. hi = array.length;
  5154. }
  5155. var remaining = hi - lo;
  5156. if (remaining < 2) {
  5157. return;
  5158. }
  5159. var runLength = 0;
  5160. if (remaining < DEFAULT_MIN_MERGE) {
  5161. runLength = makeAscendingRun(array, lo, hi, compare);
  5162. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5163. return;
  5164. }
  5165. var ts = new TimSort(array, compare);
  5166. var minRun = minRunLength(remaining);
  5167. do {
  5168. runLength = makeAscendingRun(array, lo, hi, compare);
  5169. if (runLength < minRun) {
  5170. var force = remaining;
  5171. if (force > minRun) {
  5172. force = minRun;
  5173. }
  5174. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5175. runLength = force;
  5176. }
  5177. ts.pushRun(lo, runLength);
  5178. ts.mergeRuns();
  5179. remaining -= runLength;
  5180. lo += runLength;
  5181. } while (remaining !== 0);
  5182. ts.forceMergeRuns();
  5183. }
  5184. // Use timsort because in most case elements are partially sorted
  5185. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5186. function shapeCompareFunc(a, b) {
  5187. if (a.zlevel === b.zlevel) {
  5188. if (a.z === b.z) {
  5189. // if (a.z2 === b.z2) {
  5190. // // FIXME Slow has renderidx compare
  5191. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5192. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5193. // return a.__renderidx - b.__renderidx;
  5194. // }
  5195. return a.z2 - b.z2;
  5196. }
  5197. return a.z - b.z;
  5198. }
  5199. return a.zlevel - b.zlevel;
  5200. }
  5201. /**
  5202. * 内容仓库 (M)
  5203. * @alias module:zrender/Storage
  5204. * @constructor
  5205. */
  5206. var Storage = function () { // jshint ignore:line
  5207. this._roots = [];
  5208. this._displayList = [];
  5209. this._displayListLen = 0;
  5210. };
  5211. Storage.prototype = {
  5212. constructor: Storage,
  5213. /**
  5214. * @param {Function} cb
  5215. *
  5216. */
  5217. traverse: function (cb, context) {
  5218. for (var i = 0; i < this._roots.length; i++) {
  5219. this._roots[i].traverse(cb, context);
  5220. }
  5221. },
  5222. /**
  5223. * 返回所有图形的绘制队列
  5224. * @param {boolean} [update=false] 是否在返回前更新该数组
  5225. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5226. *
  5227. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5228. * @return {Array.<module:zrender/graphic/Displayable>}
  5229. */
  5230. getDisplayList: function (update, includeIgnore) {
  5231. includeIgnore = includeIgnore || false;
  5232. if (update) {
  5233. this.updateDisplayList(includeIgnore);
  5234. }
  5235. return this._displayList;
  5236. },
  5237. /**
  5238. * 更新图形的绘制队列。
  5239. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5240. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5241. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5242. */
  5243. updateDisplayList: function (includeIgnore) {
  5244. this._displayListLen = 0;
  5245. var roots = this._roots;
  5246. var displayList = this._displayList;
  5247. for (var i = 0, len = roots.length; i < len; i++) {
  5248. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5249. }
  5250. displayList.length = this._displayListLen;
  5251. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5252. },
  5253. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5254. if (el.ignore && !includeIgnore) {
  5255. return;
  5256. }
  5257. el.beforeUpdate();
  5258. if (el.__dirty) {
  5259. el.update();
  5260. }
  5261. el.afterUpdate();
  5262. var userSetClipPath = el.clipPath;
  5263. if (userSetClipPath) {
  5264. // FIXME 效率影响
  5265. if (clipPaths) {
  5266. clipPaths = clipPaths.slice();
  5267. }
  5268. else {
  5269. clipPaths = [];
  5270. }
  5271. var currentClipPath = userSetClipPath;
  5272. var parentClipPath = el;
  5273. // Recursively add clip path
  5274. while (currentClipPath) {
  5275. // clipPath 的变换是基于使用这个 clipPath 的元素
  5276. currentClipPath.parent = parentClipPath;
  5277. currentClipPath.updateTransform();
  5278. clipPaths.push(currentClipPath);
  5279. parentClipPath = currentClipPath;
  5280. currentClipPath = currentClipPath.clipPath;
  5281. }
  5282. }
  5283. if (el.isGroup) {
  5284. var children = el._children;
  5285. for (var i = 0; i < children.length; i++) {
  5286. var child = children[i];
  5287. // Force to mark as dirty if group is dirty
  5288. // FIXME __dirtyPath ?
  5289. if (el.__dirty) {
  5290. child.__dirty = true;
  5291. }
  5292. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5293. }
  5294. // Mark group clean here
  5295. el.__dirty = false;
  5296. }
  5297. else {
  5298. el.__clipPaths = clipPaths;
  5299. this._displayList[this._displayListLen++] = el;
  5300. }
  5301. },
  5302. /**
  5303. * 添加图形(Shape)或者组(Group)到根节点
  5304. * @param {module:zrender/Element} el
  5305. */
  5306. addRoot: function (el) {
  5307. if (el.__storage === this) {
  5308. return;
  5309. }
  5310. if (el instanceof Group) {
  5311. el.addChildrenToStorage(this);
  5312. }
  5313. this.addToStorage(el);
  5314. this._roots.push(el);
  5315. },
  5316. /**
  5317. * 删除指定的图形(Shape)或者组(Group)
  5318. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5319. */
  5320. delRoot: function (el) {
  5321. if (el == null) {
  5322. // 不指定el清空
  5323. for (var i = 0; i < this._roots.length; i++) {
  5324. var root = this._roots[i];
  5325. if (root instanceof Group) {
  5326. root.delChildrenFromStorage(this);
  5327. }
  5328. }
  5329. this._roots = [];
  5330. this._displayList = [];
  5331. this._displayListLen = 0;
  5332. return;
  5333. }
  5334. if (el instanceof Array) {
  5335. for (var i = 0, l = el.length; i < l; i++) {
  5336. this.delRoot(el[i]);
  5337. }
  5338. return;
  5339. }
  5340. var idx = indexOf(this._roots, el);
  5341. if (idx >= 0) {
  5342. this.delFromStorage(el);
  5343. this._roots.splice(idx, 1);
  5344. if (el instanceof Group) {
  5345. el.delChildrenFromStorage(this);
  5346. }
  5347. }
  5348. },
  5349. addToStorage: function (el) {
  5350. if (el) {
  5351. el.__storage = this;
  5352. el.dirty(false);
  5353. }
  5354. return this;
  5355. },
  5356. delFromStorage: function (el) {
  5357. if (el) {
  5358. el.__storage = null;
  5359. }
  5360. return this;
  5361. },
  5362. /**
  5363. * 清空并且释放Storage
  5364. */
  5365. dispose: function () {
  5366. this._renderList =
  5367. this._roots = null;
  5368. },
  5369. displayableSortFunc: shapeCompareFunc
  5370. };
  5371. var SHADOW_PROPS = {
  5372. 'shadowBlur': 1,
  5373. 'shadowOffsetX': 1,
  5374. 'shadowOffsetY': 1,
  5375. 'textShadowBlur': 1,
  5376. 'textShadowOffsetX': 1,
  5377. 'textShadowOffsetY': 1,
  5378. 'textBoxShadowBlur': 1,
  5379. 'textBoxShadowOffsetX': 1,
  5380. 'textBoxShadowOffsetY': 1
  5381. };
  5382. var fixShadow = function (ctx, propName, value) {
  5383. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5384. return value *= ctx.dpr;
  5385. }
  5386. return value;
  5387. };
  5388. var STYLE_COMMON_PROPS = [
  5389. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5390. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5391. ];
  5392. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5393. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5394. var Style = function (opts, host) {
  5395. this.extendFrom(opts, false);
  5396. this.host = host;
  5397. };
  5398. function createLinearGradient(ctx, obj, rect) {
  5399. var x = obj.x == null ? 0 : obj.x;
  5400. var x2 = obj.x2 == null ? 1 : obj.x2;
  5401. var y = obj.y == null ? 0 : obj.y;
  5402. var y2 = obj.y2 == null ? 0 : obj.y2;
  5403. if (!obj.global) {
  5404. x = x * rect.width + rect.x;
  5405. x2 = x2 * rect.width + rect.x;
  5406. y = y * rect.height + rect.y;
  5407. y2 = y2 * rect.height + rect.y;
  5408. }
  5409. // Fix NaN when rect is Infinity
  5410. x = isNaN(x) ? 0 : x;
  5411. x2 = isNaN(x2) ? 1 : x2;
  5412. y = isNaN(y) ? 0 : y;
  5413. y2 = isNaN(y2) ? 0 : y2;
  5414. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5415. return canvasGradient;
  5416. }
  5417. function createRadialGradient(ctx, obj, rect) {
  5418. var width = rect.width;
  5419. var height = rect.height;
  5420. var min = Math.min(width, height);
  5421. var x = obj.x == null ? 0.5 : obj.x;
  5422. var y = obj.y == null ? 0.5 : obj.y;
  5423. var r = obj.r == null ? 0.5 : obj.r;
  5424. if (!obj.global) {
  5425. x = x * width + rect.x;
  5426. y = y * height + rect.y;
  5427. r = r * min;
  5428. }
  5429. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5430. return canvasGradient;
  5431. }
  5432. Style.prototype = {
  5433. constructor: Style,
  5434. /**
  5435. * @type {module:zrender/graphic/Displayable}
  5436. */
  5437. host: null,
  5438. /**
  5439. * @type {string}
  5440. */
  5441. fill: '#000',
  5442. /**
  5443. * @type {string}
  5444. */
  5445. stroke: null,
  5446. /**
  5447. * @type {number}
  5448. */
  5449. opacity: 1,
  5450. /**
  5451. * @type {Array.<number>}
  5452. */
  5453. lineDash: null,
  5454. /**
  5455. * @type {number}
  5456. */
  5457. lineDashOffset: 0,
  5458. /**
  5459. * @type {number}
  5460. */
  5461. shadowBlur: 0,
  5462. /**
  5463. * @type {number}
  5464. */
  5465. shadowOffsetX: 0,
  5466. /**
  5467. * @type {number}
  5468. */
  5469. shadowOffsetY: 0,
  5470. /**
  5471. * @type {number}
  5472. */
  5473. lineWidth: 1,
  5474. /**
  5475. * If stroke ignore scale
  5476. * @type {Boolean}
  5477. */
  5478. strokeNoScale: false,
  5479. // Bounding rect text configuration
  5480. // Not affected by element transform
  5481. /**
  5482. * @type {string}
  5483. */
  5484. text: null,
  5485. /**
  5486. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5487. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5488. * So do not visit it directly in upper application (like echarts),
  5489. * but use `contain/text#makeFont` instead.
  5490. * @type {string}
  5491. */
  5492. font: null,
  5493. /**
  5494. * The same as font. Use font please.
  5495. * @deprecated
  5496. * @type {string}
  5497. */
  5498. textFont: null,
  5499. /**
  5500. * It helps merging respectively, rather than parsing an entire font string.
  5501. * @type {string}
  5502. */
  5503. fontStyle: null,
  5504. /**
  5505. * It helps merging respectively, rather than parsing an entire font string.
  5506. * @type {string}
  5507. */
  5508. fontWeight: null,
  5509. /**
  5510. * It helps merging respectively, rather than parsing an entire font string.
  5511. * Should be 12 but not '12px'.
  5512. * @type {number}
  5513. */
  5514. fontSize: null,
  5515. /**
  5516. * It helps merging respectively, rather than parsing an entire font string.
  5517. * @type {string}
  5518. */
  5519. fontFamily: null,
  5520. /**
  5521. * Reserved for special functinality, like 'hr'.
  5522. * @type {string}
  5523. */
  5524. textTag: null,
  5525. /**
  5526. * @type {string}
  5527. */
  5528. textFill: '#000',
  5529. /**
  5530. * @type {string}
  5531. */
  5532. textStroke: null,
  5533. /**
  5534. * @type {number}
  5535. */
  5536. textWidth: null,
  5537. /**
  5538. * Only for textBackground.
  5539. * @type {number}
  5540. */
  5541. textHeight: null,
  5542. /**
  5543. * textStroke may be set as some color as a default
  5544. * value in upper applicaion, where the default value
  5545. * of textStrokeWidth should be 0 to make sure that
  5546. * user can choose to do not use text stroke.
  5547. * @type {number}
  5548. */
  5549. textStrokeWidth: 0,
  5550. /**
  5551. * @type {number}
  5552. */
  5553. textLineHeight: null,
  5554. /**
  5555. * 'inside', 'left', 'right', 'top', 'bottom'
  5556. * [x, y]
  5557. * Based on x, y of rect.
  5558. * @type {string|Array.<number>}
  5559. * @default 'inside'
  5560. */
  5561. textPosition: 'inside',
  5562. /**
  5563. * If not specified, use the boundingRect of a `displayable`.
  5564. * @type {Object}
  5565. */
  5566. textRect: null,
  5567. /**
  5568. * [x, y]
  5569. * @type {Array.<number>}
  5570. */
  5571. textOffset: null,
  5572. /**
  5573. * @type {string}
  5574. */
  5575. textAlign: null,
  5576. /**
  5577. * @type {string}
  5578. */
  5579. textVerticalAlign: null,
  5580. /**
  5581. * @type {number}
  5582. */
  5583. textDistance: 5,
  5584. /**
  5585. * @type {string}
  5586. */
  5587. textShadowColor: 'transparent',
  5588. /**
  5589. * @type {number}
  5590. */
  5591. textShadowBlur: 0,
  5592. /**
  5593. * @type {number}
  5594. */
  5595. textShadowOffsetX: 0,
  5596. /**
  5597. * @type {number}
  5598. */
  5599. textShadowOffsetY: 0,
  5600. /**
  5601. * @type {string}
  5602. */
  5603. textBoxShadowColor: 'transparent',
  5604. /**
  5605. * @type {number}
  5606. */
  5607. textBoxShadowBlur: 0,
  5608. /**
  5609. * @type {number}
  5610. */
  5611. textBoxShadowOffsetX: 0,
  5612. /**
  5613. * @type {number}
  5614. */
  5615. textBoxShadowOffsetY: 0,
  5616. /**
  5617. * Whether transform text.
  5618. * Only useful in Path and Image element
  5619. * @type {boolean}
  5620. */
  5621. transformText: false,
  5622. /**
  5623. * Text rotate around position of Path or Image
  5624. * Only useful in Path and Image element and transformText is false.
  5625. */
  5626. textRotation: 0,
  5627. /**
  5628. * Text origin of text rotation, like [10, 40].
  5629. * Based on x, y of rect.
  5630. * Useful in label rotation of circular symbol.
  5631. * By default, this origin is textPosition.
  5632. * Can be 'center'.
  5633. * @type {string|Array.<number>}
  5634. */
  5635. textOrigin: null,
  5636. /**
  5637. * @type {string}
  5638. */
  5639. textBackgroundColor: null,
  5640. /**
  5641. * @type {string}
  5642. */
  5643. textBorderColor: null,
  5644. /**
  5645. * @type {number}
  5646. */
  5647. textBorderWidth: 0,
  5648. /**
  5649. * @type {number}
  5650. */
  5651. textBorderRadius: 0,
  5652. /**
  5653. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5654. * @type {number|Array.<number>}
  5655. */
  5656. textPadding: null,
  5657. /**
  5658. * Text styles for rich text.
  5659. * @type {Object}
  5660. */
  5661. rich: null,
  5662. /**
  5663. * {outerWidth, outerHeight, ellipsis, placeholder}
  5664. * @type {Object}
  5665. */
  5666. truncate: null,
  5667. /**
  5668. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5669. * @type {string}
  5670. */
  5671. blend: null,
  5672. /**
  5673. * @param {CanvasRenderingContext2D} ctx
  5674. */
  5675. bind: function (ctx, el, prevEl) {
  5676. var style = this;
  5677. var prevStyle = prevEl && prevEl.style;
  5678. var firstDraw = !prevStyle;
  5679. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5680. var prop = STYLE_COMMON_PROPS[i];
  5681. var styleName = prop[0];
  5682. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5683. // FIXME Invalid property value will cause style leak from previous element.
  5684. ctx[styleName] =
  5685. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5686. }
  5687. }
  5688. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5689. ctx.fillStyle = style.fill;
  5690. }
  5691. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5692. ctx.strokeStyle = style.stroke;
  5693. }
  5694. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5695. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5696. }
  5697. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5698. ctx.globalCompositeOperation = style.blend || 'source-over';
  5699. }
  5700. if (this.hasStroke()) {
  5701. var lineWidth = style.lineWidth;
  5702. ctx.lineWidth = lineWidth / (
  5703. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5704. );
  5705. }
  5706. },
  5707. hasFill: function () {
  5708. var fill = this.fill;
  5709. return fill != null && fill !== 'none';
  5710. },
  5711. hasStroke: function () {
  5712. var stroke = this.stroke;
  5713. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5714. },
  5715. /**
  5716. * Extend from other style
  5717. * @param {zrender/graphic/Style} otherStyle
  5718. * @param {boolean} overwrite true: overwrirte any way.
  5719. * false: overwrite only when !target.hasOwnProperty
  5720. * others: overwrite when property is not null/undefined.
  5721. */
  5722. extendFrom: function (otherStyle, overwrite) {
  5723. if (otherStyle) {
  5724. for (var name in otherStyle) {
  5725. if (otherStyle.hasOwnProperty(name)
  5726. && (overwrite === true
  5727. || (
  5728. overwrite === false
  5729. ? !this.hasOwnProperty(name)
  5730. : otherStyle[name] != null
  5731. )
  5732. )
  5733. ) {
  5734. this[name] = otherStyle[name];
  5735. }
  5736. }
  5737. }
  5738. },
  5739. /**
  5740. * Batch setting style with a given object
  5741. * @param {Object|string} obj
  5742. * @param {*} [obj]
  5743. */
  5744. set: function (obj, value) {
  5745. if (typeof obj === 'string') {
  5746. this[obj] = value;
  5747. }
  5748. else {
  5749. this.extendFrom(obj, true);
  5750. }
  5751. },
  5752. /**
  5753. * Clone
  5754. * @return {zrender/graphic/Style} [description]
  5755. */
  5756. clone: function () {
  5757. var newStyle = new this.constructor();
  5758. newStyle.extendFrom(this, true);
  5759. return newStyle;
  5760. },
  5761. getGradient: function (ctx, obj, rect) {
  5762. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5763. var canvasGradient = method(ctx, obj, rect);
  5764. var colorStops = obj.colorStops;
  5765. for (var i = 0; i < colorStops.length; i++) {
  5766. canvasGradient.addColorStop(
  5767. colorStops[i].offset, colorStops[i].color
  5768. );
  5769. }
  5770. return canvasGradient;
  5771. }
  5772. };
  5773. var styleProto = Style.prototype;
  5774. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5775. var prop = STYLE_COMMON_PROPS[i];
  5776. if (!(prop[0] in styleProto)) {
  5777. styleProto[prop[0]] = prop[1];
  5778. }
  5779. }
  5780. // Provide for others
  5781. Style.getGradient = styleProto.getGradient;
  5782. var Pattern = function (image, repeat) {
  5783. // Should do nothing more in this constructor. Because gradient can be
  5784. // declard by `color: {image: ...}`, where this constructor will not be called.
  5785. this.image = image;
  5786. this.repeat = repeat;
  5787. // Can be cloned
  5788. this.type = 'pattern';
  5789. };
  5790. Pattern.prototype.getCanvasPattern = function (ctx) {
  5791. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5792. };
  5793. /**
  5794. * @module zrender/Layer
  5795. * @author pissang(https://www.github.com/pissang)
  5796. */
  5797. function returnFalse() {
  5798. return false;
  5799. }
  5800. /**
  5801. * 创建dom
  5802. *
  5803. * @inner
  5804. * @param {string} id dom id 待用
  5805. * @param {Painter} painter painter instance
  5806. * @param {number} number
  5807. */
  5808. function createDom(id, painter, dpr) {
  5809. var newDom = createCanvas();
  5810. var width = painter.getWidth();
  5811. var height = painter.getHeight();
  5812. var newDomStyle = newDom.style;
  5813. if (newDomStyle) { // In node or some other non-browser environment
  5814. newDomStyle.position = 'absolute';
  5815. newDomStyle.left = 0;
  5816. newDomStyle.top = 0;
  5817. newDomStyle.width = width + 'px';
  5818. newDomStyle.height = height + 'px';
  5819. newDom.setAttribute('data-zr-dom-id', id);
  5820. }
  5821. newDom.width = width * dpr;
  5822. newDom.height = height * dpr;
  5823. return newDom;
  5824. }
  5825. /**
  5826. * @alias module:zrender/Layer
  5827. * @constructor
  5828. * @extends module:zrender/mixin/Transformable
  5829. * @param {string} id
  5830. * @param {module:zrender/Painter} painter
  5831. * @param {number} [dpr]
  5832. */
  5833. var Layer = function(id, painter, dpr) {
  5834. var dom;
  5835. dpr = dpr || devicePixelRatio;
  5836. if (typeof id === 'string') {
  5837. dom = createDom(id, painter, dpr);
  5838. }
  5839. // Not using isDom because in node it will return false
  5840. else if (isObject$1(id)) {
  5841. dom = id;
  5842. id = dom.id;
  5843. }
  5844. this.id = id;
  5845. this.dom = dom;
  5846. var domStyle = dom.style;
  5847. if (domStyle) { // Not in node
  5848. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5849. domStyle['-webkit-user-select'] = 'none';
  5850. domStyle['user-select'] = 'none';
  5851. domStyle['-webkit-touch-callout'] = 'none';
  5852. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5853. domStyle['padding'] = 0;
  5854. domStyle['margin'] = 0;
  5855. domStyle['border-width'] = 0;
  5856. }
  5857. this.domBack = null;
  5858. this.ctxBack = null;
  5859. this.painter = painter;
  5860. this.config = null;
  5861. // Configs
  5862. /**
  5863. * 每次清空画布的颜色
  5864. * @type {string}
  5865. * @default 0
  5866. */
  5867. this.clearColor = 0;
  5868. /**
  5869. * 是否开启动态模糊
  5870. * @type {boolean}
  5871. * @default false
  5872. */
  5873. this.motionBlur = false;
  5874. /**
  5875. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5876. * @type {number}
  5877. * @default 0.7
  5878. */
  5879. this.lastFrameAlpha = 0.7;
  5880. /**
  5881. * Layer dpr
  5882. * @type {number}
  5883. */
  5884. this.dpr = dpr;
  5885. };
  5886. Layer.prototype = {
  5887. constructor: Layer,
  5888. __dirty: true,
  5889. __used: false,
  5890. __drawIndex: 0,
  5891. __startIndex: 0,
  5892. __endIndex: 0,
  5893. incremental: false,
  5894. getElementCount: function () {
  5895. return this.__endIndex - this.__startIndex;
  5896. },
  5897. initContext: function () {
  5898. this.ctx = this.dom.getContext('2d');
  5899. this.ctx.dpr = this.dpr;
  5900. },
  5901. createBackBuffer: function () {
  5902. var dpr = this.dpr;
  5903. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5904. this.ctxBack = this.domBack.getContext('2d');
  5905. if (dpr != 1) {
  5906. this.ctxBack.scale(dpr, dpr);
  5907. }
  5908. },
  5909. /**
  5910. * @param {number} width
  5911. * @param {number} height
  5912. */
  5913. resize: function (width, height) {
  5914. var dpr = this.dpr;
  5915. var dom = this.dom;
  5916. var domStyle = dom.style;
  5917. var domBack = this.domBack;
  5918. if (domStyle) {
  5919. domStyle.width = width + 'px';
  5920. domStyle.height = height + 'px';
  5921. }
  5922. dom.width = width * dpr;
  5923. dom.height = height * dpr;
  5924. if (domBack) {
  5925. domBack.width = width * dpr;
  5926. domBack.height = height * dpr;
  5927. if (dpr != 1) {
  5928. this.ctxBack.scale(dpr, dpr);
  5929. }
  5930. }
  5931. },
  5932. /**
  5933. * 清空该层画布
  5934. * @param {boolean} [clearAll]=false Clear all with out motion blur
  5935. * @param {Color} [clearColor]
  5936. */
  5937. clear: function (clearAll, clearColor) {
  5938. var dom = this.dom;
  5939. var ctx = this.ctx;
  5940. var width = dom.width;
  5941. var height = dom.height;
  5942. var clearColor = clearColor || this.clearColor;
  5943. var haveMotionBLur = this.motionBlur && !clearAll;
  5944. var lastFrameAlpha = this.lastFrameAlpha;
  5945. var dpr = this.dpr;
  5946. if (haveMotionBLur) {
  5947. if (!this.domBack) {
  5948. this.createBackBuffer();
  5949. }
  5950. this.ctxBack.globalCompositeOperation = 'copy';
  5951. this.ctxBack.drawImage(
  5952. dom, 0, 0,
  5953. width / dpr,
  5954. height / dpr
  5955. );
  5956. }
  5957. ctx.clearRect(0, 0, width, height);
  5958. if (clearColor && clearColor !== 'transparent') {
  5959. var clearColorGradientOrPattern;
  5960. // Gradient
  5961. if (clearColor.colorStops) {
  5962. // Cache canvas gradient
  5963. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5964. x: 0,
  5965. y: 0,
  5966. width: width,
  5967. height: height
  5968. });
  5969. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5970. }
  5971. // Pattern
  5972. else if (clearColor.image) {
  5973. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5974. }
  5975. ctx.save();
  5976. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5977. ctx.fillRect(0, 0, width, height);
  5978. ctx.restore();
  5979. }
  5980. if (haveMotionBLur) {
  5981. var domBack = this.domBack;
  5982. ctx.save();
  5983. ctx.globalAlpha = lastFrameAlpha;
  5984. ctx.drawImage(domBack, 0, 0, width, height);
  5985. ctx.restore();
  5986. }
  5987. }
  5988. };
  5989. var requestAnimationFrame = (
  5990. typeof window !== 'undefined'
  5991. && (
  5992. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5993. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  5994. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5995. || window.mozRequestAnimationFrame
  5996. || window.webkitRequestAnimationFrame
  5997. )
  5998. ) || function (func) {
  5999. setTimeout(func, 16);
  6000. };
  6001. var globalImageCache = new LRU(50);
  6002. /**
  6003. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6004. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6005. */
  6006. function findExistImage(newImageOrSrc) {
  6007. if (typeof newImageOrSrc === 'string') {
  6008. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6009. return cachedImgObj && cachedImgObj.image;
  6010. }
  6011. else {
  6012. return newImageOrSrc;
  6013. }
  6014. }
  6015. /**
  6016. * Caution: User should cache loaded images, but not just count on LRU.
  6017. * Consider if required images more than LRU size, will dead loop occur?
  6018. *
  6019. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6020. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6021. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6022. * @param {Function} [cb] params: (image, cbPayload)
  6023. * @param {Object} [cbPayload] Payload on cb calling.
  6024. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6025. */
  6026. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6027. if (!newImageOrSrc) {
  6028. return image;
  6029. }
  6030. else if (typeof newImageOrSrc === 'string') {
  6031. // Image should not be loaded repeatly.
  6032. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6033. return image;
  6034. }
  6035. // Only when there is no existent image or existent image src
  6036. // is different, this method is responsible for load.
  6037. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6038. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6039. if (cachedImgObj) {
  6040. image = cachedImgObj.image;
  6041. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6042. }
  6043. else {
  6044. !image && (image = new Image());
  6045. image.onload = imageOnLoad;
  6046. globalImageCache.put(
  6047. newImageOrSrc,
  6048. image.__cachedImgObj = {
  6049. image: image,
  6050. pending: [pendingWrap]
  6051. }
  6052. );
  6053. image.src = image.__zrImageSrc = newImageOrSrc;
  6054. }
  6055. return image;
  6056. }
  6057. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6058. else {
  6059. return newImageOrSrc;
  6060. }
  6061. }
  6062. function imageOnLoad() {
  6063. var cachedImgObj = this.__cachedImgObj;
  6064. this.onload = this.__cachedImgObj = null;
  6065. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6066. var pendingWrap = cachedImgObj.pending[i];
  6067. var cb = pendingWrap.cb;
  6068. cb && cb(this, pendingWrap.cbPayload);
  6069. pendingWrap.hostEl.dirty();
  6070. }
  6071. cachedImgObj.pending.length = 0;
  6072. }
  6073. function isImageReady(image) {
  6074. return image && image.width && image.height;
  6075. }
  6076. var textWidthCache = {};
  6077. var textWidthCacheCounter = 0;
  6078. var TEXT_CACHE_MAX = 5000;
  6079. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6080. var DEFAULT_FONT = '12px sans-serif';
  6081. // Avoid assign to an exported variable, for transforming to cjs.
  6082. var methods$1 = {};
  6083. function $override$1(name, fn) {
  6084. methods$1[name] = fn;
  6085. }
  6086. /**
  6087. * @public
  6088. * @param {string} text
  6089. * @param {string} font
  6090. * @return {number} width
  6091. */
  6092. function getWidth(text, font) {
  6093. font = font || DEFAULT_FONT;
  6094. var key = text + ':' + font;
  6095. if (textWidthCache[key]) {
  6096. return textWidthCache[key];
  6097. }
  6098. var textLines = (text + '').split('\n');
  6099. var width = 0;
  6100. for (var i = 0, l = textLines.length; i < l; i++) {
  6101. // textContain.measureText may be overrided in SVG or VML
  6102. width = Math.max(measureText(textLines[i], font).width, width);
  6103. }
  6104. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6105. textWidthCacheCounter = 0;
  6106. textWidthCache = {};
  6107. }
  6108. textWidthCacheCounter++;
  6109. textWidthCache[key] = width;
  6110. return width;
  6111. }
  6112. /**
  6113. * @public
  6114. * @param {string} text
  6115. * @param {string} font
  6116. * @param {string} [textAlign='left']
  6117. * @param {string} [textVerticalAlign='top']
  6118. * @param {Array.<number>} [textPadding]
  6119. * @param {Object} [rich]
  6120. * @param {Object} [truncate]
  6121. * @return {Object} {x, y, width, height, lineHeight}
  6122. */
  6123. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6124. return rich
  6125. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  6126. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  6127. }
  6128. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  6129. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  6130. var outerWidth = getWidth(text, font);
  6131. if (textPadding) {
  6132. outerWidth += textPadding[1] + textPadding[3];
  6133. }
  6134. var outerHeight = contentBlock.outerHeight;
  6135. var x = adjustTextX(0, outerWidth, textAlign);
  6136. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6137. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6138. rect.lineHeight = contentBlock.lineHeight;
  6139. return rect;
  6140. }
  6141. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6142. var contentBlock = parseRichText(text, {
  6143. rich: rich,
  6144. truncate: truncate,
  6145. font: font,
  6146. textAlign: textAlign,
  6147. textPadding: textPadding
  6148. });
  6149. var outerWidth = contentBlock.outerWidth;
  6150. var outerHeight = contentBlock.outerHeight;
  6151. var x = adjustTextX(0, outerWidth, textAlign);
  6152. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6153. return new BoundingRect(x, y, outerWidth, outerHeight);
  6154. }
  6155. /**
  6156. * @public
  6157. * @param {number} x
  6158. * @param {number} width
  6159. * @param {string} [textAlign='left']
  6160. * @return {number} Adjusted x.
  6161. */
  6162. function adjustTextX(x, width, textAlign) {
  6163. // FIXME Right to left language
  6164. if (textAlign === 'right') {
  6165. x -= width;
  6166. }
  6167. else if (textAlign === 'center') {
  6168. x -= width / 2;
  6169. }
  6170. return x;
  6171. }
  6172. /**
  6173. * @public
  6174. * @param {number} y
  6175. * @param {number} height
  6176. * @param {string} [textVerticalAlign='top']
  6177. * @return {number} Adjusted y.
  6178. */
  6179. function adjustTextY(y, height, textVerticalAlign) {
  6180. if (textVerticalAlign === 'middle') {
  6181. y -= height / 2;
  6182. }
  6183. else if (textVerticalAlign === 'bottom') {
  6184. y -= height;
  6185. }
  6186. return y;
  6187. }
  6188. /**
  6189. * @public
  6190. * @param {stirng} textPosition
  6191. * @param {Object} rect {x, y, width, height}
  6192. * @param {number} distance
  6193. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6194. */
  6195. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6196. var x = rect.x;
  6197. var y = rect.y;
  6198. var height = rect.height;
  6199. var width = rect.width;
  6200. var halfHeight = height / 2;
  6201. var textAlign = 'left';
  6202. var textVerticalAlign = 'top';
  6203. switch (textPosition) {
  6204. case 'left':
  6205. x -= distance;
  6206. y += halfHeight;
  6207. textAlign = 'right';
  6208. textVerticalAlign = 'middle';
  6209. break;
  6210. case 'right':
  6211. x += distance + width;
  6212. y += halfHeight;
  6213. textVerticalAlign = 'middle';
  6214. break;
  6215. case 'top':
  6216. x += width / 2;
  6217. y -= distance;
  6218. textAlign = 'center';
  6219. textVerticalAlign = 'bottom';
  6220. break;
  6221. case 'bottom':
  6222. x += width / 2;
  6223. y += height + distance;
  6224. textAlign = 'center';
  6225. break;
  6226. case 'inside':
  6227. x += width / 2;
  6228. y += halfHeight;
  6229. textAlign = 'center';
  6230. textVerticalAlign = 'middle';
  6231. break;
  6232. case 'insideLeft':
  6233. x += distance;
  6234. y += halfHeight;
  6235. textVerticalAlign = 'middle';
  6236. break;
  6237. case 'insideRight':
  6238. x += width - distance;
  6239. y += halfHeight;
  6240. textAlign = 'right';
  6241. textVerticalAlign = 'middle';
  6242. break;
  6243. case 'insideTop':
  6244. x += width / 2;
  6245. y += distance;
  6246. textAlign = 'center';
  6247. break;
  6248. case 'insideBottom':
  6249. x += width / 2;
  6250. y += height - distance;
  6251. textAlign = 'center';
  6252. textVerticalAlign = 'bottom';
  6253. break;
  6254. case 'insideTopLeft':
  6255. x += distance;
  6256. y += distance;
  6257. break;
  6258. case 'insideTopRight':
  6259. x += width - distance;
  6260. y += distance;
  6261. textAlign = 'right';
  6262. break;
  6263. case 'insideBottomLeft':
  6264. x += distance;
  6265. y += height - distance;
  6266. textVerticalAlign = 'bottom';
  6267. break;
  6268. case 'insideBottomRight':
  6269. x += width - distance;
  6270. y += height - distance;
  6271. textAlign = 'right';
  6272. textVerticalAlign = 'bottom';
  6273. break;
  6274. }
  6275. return {
  6276. x: x,
  6277. y: y,
  6278. textAlign: textAlign,
  6279. textVerticalAlign: textVerticalAlign
  6280. };
  6281. }
  6282. /**
  6283. * Show ellipsis if overflow.
  6284. *
  6285. * @public
  6286. * @param {string} text
  6287. * @param {string} containerWidth
  6288. * @param {string} font
  6289. * @param {number} [ellipsis='...']
  6290. * @param {Object} [options]
  6291. * @param {number} [options.maxIterations=3]
  6292. * @param {number} [options.minChar=0] If truncate result are less
  6293. * then minChar, ellipsis will not show, which is
  6294. * better for user hint in some cases.
  6295. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6296. * @return {string}
  6297. */
  6298. function truncateText(text, containerWidth, font, ellipsis, options) {
  6299. if (!containerWidth) {
  6300. return '';
  6301. }
  6302. var textLines = (text + '').split('\n');
  6303. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6304. // FIXME
  6305. // It is not appropriate that every line has '...' when truncate multiple lines.
  6306. for (var i = 0, len = textLines.length; i < len; i++) {
  6307. textLines[i] = truncateSingleLine(textLines[i], options);
  6308. }
  6309. return textLines.join('\n');
  6310. }
  6311. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6312. options = extend({}, options);
  6313. options.font = font;
  6314. var ellipsis = retrieve2(ellipsis, '...');
  6315. options.maxIterations = retrieve2(options.maxIterations, 2);
  6316. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6317. // FIXME
  6318. // Other languages?
  6319. options.cnCharWidth = getWidth('国', font);
  6320. // FIXME
  6321. // Consider proportional font?
  6322. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6323. options.placeholder = retrieve2(options.placeholder, '');
  6324. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6325. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6326. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6327. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6328. contentWidth -= ascCharWidth;
  6329. }
  6330. var ellipsisWidth = getWidth(ellipsis);
  6331. if (ellipsisWidth > contentWidth) {
  6332. ellipsis = '';
  6333. ellipsisWidth = 0;
  6334. }
  6335. contentWidth = containerWidth - ellipsisWidth;
  6336. options.ellipsis = ellipsis;
  6337. options.ellipsisWidth = ellipsisWidth;
  6338. options.contentWidth = contentWidth;
  6339. options.containerWidth = containerWidth;
  6340. return options;
  6341. }
  6342. function truncateSingleLine(textLine, options) {
  6343. var containerWidth = options.containerWidth;
  6344. var font = options.font;
  6345. var contentWidth = options.contentWidth;
  6346. if (!containerWidth) {
  6347. return '';
  6348. }
  6349. var lineWidth = getWidth(textLine, font);
  6350. if (lineWidth <= containerWidth) {
  6351. return textLine;
  6352. }
  6353. for (var j = 0;; j++) {
  6354. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6355. textLine += options.ellipsis;
  6356. break;
  6357. }
  6358. var subLength = j === 0
  6359. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6360. : lineWidth > 0
  6361. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6362. : 0;
  6363. textLine = textLine.substr(0, subLength);
  6364. lineWidth = getWidth(textLine, font);
  6365. }
  6366. if (textLine === '') {
  6367. textLine = options.placeholder;
  6368. }
  6369. return textLine;
  6370. }
  6371. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6372. var width = 0;
  6373. var i = 0;
  6374. for (var len = text.length; i < len && width < contentWidth; i++) {
  6375. var charCode = text.charCodeAt(i);
  6376. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6377. }
  6378. return i;
  6379. }
  6380. /**
  6381. * @public
  6382. * @param {string} font
  6383. * @return {number} line height
  6384. */
  6385. function getLineHeight(font) {
  6386. // FIXME A rough approach.
  6387. return getWidth('国', font);
  6388. }
  6389. /**
  6390. * @public
  6391. * @param {string} text
  6392. * @param {string} font
  6393. * @return {Object} width
  6394. */
  6395. function measureText(text, font) {
  6396. return methods$1.measureText(text, font);
  6397. }
  6398. // Avoid assign to an exported variable, for transforming to cjs.
  6399. methods$1.measureText = function (text, font) {
  6400. var ctx = getContext();
  6401. ctx.font = font || DEFAULT_FONT;
  6402. return ctx.measureText(text);
  6403. };
  6404. /**
  6405. * @public
  6406. * @param {string} text
  6407. * @param {string} font
  6408. * @param {Object} [truncate]
  6409. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6410. * Notice: for performance, do not calculate outerWidth util needed.
  6411. */
  6412. function parsePlainText(text, font, padding, truncate) {
  6413. text != null && (text += '');
  6414. var lineHeight = getLineHeight(font);
  6415. var lines = text ? text.split('\n') : [];
  6416. var height = lines.length * lineHeight;
  6417. var outerHeight = height;
  6418. if (padding) {
  6419. outerHeight += padding[0] + padding[2];
  6420. }
  6421. if (text && truncate) {
  6422. var truncOuterHeight = truncate.outerHeight;
  6423. var truncOuterWidth = truncate.outerWidth;
  6424. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6425. text = '';
  6426. lines = [];
  6427. }
  6428. else if (truncOuterWidth != null) {
  6429. var options = prepareTruncateOptions(
  6430. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6431. font,
  6432. truncate.ellipsis,
  6433. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6434. );
  6435. // FIXME
  6436. // It is not appropriate that every line has '...' when truncate multiple lines.
  6437. for (var i = 0, len = lines.length; i < len; i++) {
  6438. lines[i] = truncateSingleLine(lines[i], options);
  6439. }
  6440. }
  6441. }
  6442. return {
  6443. lines: lines,
  6444. height: height,
  6445. outerHeight: outerHeight,
  6446. lineHeight: lineHeight
  6447. };
  6448. }
  6449. /**
  6450. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6451. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6452. *
  6453. * @public
  6454. * @param {string} text
  6455. * @param {Object} style
  6456. * @return {Object} block
  6457. * {
  6458. * width,
  6459. * height,
  6460. * lines: [{
  6461. * lineHeight,
  6462. * width,
  6463. * tokens: [[{
  6464. * styleName,
  6465. * text,
  6466. * width, // include textPadding
  6467. * height, // include textPadding
  6468. * textWidth, // pure text width
  6469. * textHeight, // pure text height
  6470. * lineHeihgt,
  6471. * font,
  6472. * textAlign,
  6473. * textVerticalAlign
  6474. * }], [...], ...]
  6475. * }, ...]
  6476. * }
  6477. * If styleName is undefined, it is plain text.
  6478. */
  6479. function parseRichText(text, style) {
  6480. var contentBlock = {lines: [], width: 0, height: 0};
  6481. text != null && (text += '');
  6482. if (!text) {
  6483. return contentBlock;
  6484. }
  6485. var lastIndex = STYLE_REG.lastIndex = 0;
  6486. var result;
  6487. while ((result = STYLE_REG.exec(text)) != null) {
  6488. var matchedIndex = result.index;
  6489. if (matchedIndex > lastIndex) {
  6490. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6491. }
  6492. pushTokens(contentBlock, result[2], result[1]);
  6493. lastIndex = STYLE_REG.lastIndex;
  6494. }
  6495. if (lastIndex < text.length) {
  6496. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6497. }
  6498. var lines = contentBlock.lines;
  6499. var contentHeight = 0;
  6500. var contentWidth = 0;
  6501. // For `textWidth: 100%`
  6502. var pendingList = [];
  6503. var stlPadding = style.textPadding;
  6504. var truncate = style.truncate;
  6505. var truncateWidth = truncate && truncate.outerWidth;
  6506. var truncateHeight = truncate && truncate.outerHeight;
  6507. if (stlPadding) {
  6508. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6509. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6510. }
  6511. // Calculate layout info of tokens.
  6512. for (var i = 0; i < lines.length; i++) {
  6513. var line = lines[i];
  6514. var lineHeight = 0;
  6515. var lineWidth = 0;
  6516. for (var j = 0; j < line.tokens.length; j++) {
  6517. var token = line.tokens[j];
  6518. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6519. // textPadding should not inherit from style.
  6520. var textPadding = token.textPadding = tokenStyle.textPadding;
  6521. // textFont has been asigned to font by `normalizeStyle`.
  6522. var font = token.font = tokenStyle.font || style.font;
  6523. // textHeight can be used when textVerticalAlign is specified in token.
  6524. var tokenHeight = token.textHeight = retrieve2(
  6525. // textHeight should not be inherited, consider it can be specified
  6526. // as box height of the block.
  6527. tokenStyle.textHeight, getLineHeight(font)
  6528. );
  6529. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6530. token.height = tokenHeight;
  6531. token.lineHeight = retrieve3(
  6532. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6533. );
  6534. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6535. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6536. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6537. return {lines: [], width: 0, height: 0};
  6538. }
  6539. token.textWidth = getWidth(token.text, font);
  6540. var tokenWidth = tokenStyle.textWidth;
  6541. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6542. // Percent width, can be `100%`, can be used in drawing separate
  6543. // line when box width is needed to be auto.
  6544. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6545. token.percentWidth = tokenWidth;
  6546. pendingList.push(token);
  6547. tokenWidth = 0;
  6548. // Do not truncate in this case, because there is no user case
  6549. // and it is too complicated.
  6550. }
  6551. else {
  6552. if (tokenWidthNotSpecified) {
  6553. tokenWidth = token.textWidth;
  6554. // FIXME: If image is not loaded and textWidth is not specified, calling
  6555. // `getBoundingRect()` will not get correct result.
  6556. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6557. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6558. // Use cases:
  6559. // (1) If image is not loaded, it will be loaded at render phase and call
  6560. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6561. // image, and then the right size will be calculated here at the next tick.
  6562. // See `graphic/helper/text.js`.
  6563. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6564. // use `imageHelper.findExistImage` to find cached image.
  6565. // `imageHelper.findExistImage` will always be called here before
  6566. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6567. // which ensures that image will not be rendered before correct size calcualted.
  6568. if (bgImg) {
  6569. bgImg = findExistImage(bgImg);
  6570. if (isImageReady(bgImg)) {
  6571. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6572. }
  6573. }
  6574. }
  6575. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6576. tokenWidth += paddingW;
  6577. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6578. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6579. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6580. token.text = '';
  6581. token.textWidth = tokenWidth = 0;
  6582. }
  6583. else {
  6584. token.text = truncateText(
  6585. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6586. {minChar: truncate.minChar}
  6587. );
  6588. token.textWidth = getWidth(token.text, font);
  6589. tokenWidth = token.textWidth + paddingW;
  6590. }
  6591. }
  6592. }
  6593. lineWidth += (token.width = tokenWidth);
  6594. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6595. }
  6596. line.width = lineWidth;
  6597. line.lineHeight = lineHeight;
  6598. contentHeight += lineHeight;
  6599. contentWidth = Math.max(contentWidth, lineWidth);
  6600. }
  6601. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6602. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6603. if (stlPadding) {
  6604. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6605. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6606. }
  6607. for (var i = 0; i < pendingList.length; i++) {
  6608. var token = pendingList[i];
  6609. var percentWidth = token.percentWidth;
  6610. // Should not base on outerWidth, because token can not be placed out of padding.
  6611. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6612. }
  6613. return contentBlock;
  6614. }
  6615. function pushTokens(block, str, styleName) {
  6616. var isEmptyStr = str === '';
  6617. var strs = str.split('\n');
  6618. var lines = block.lines;
  6619. for (var i = 0; i < strs.length; i++) {
  6620. var text = strs[i];
  6621. var token = {
  6622. styleName: styleName,
  6623. text: text,
  6624. isLineHolder: !text && !isEmptyStr
  6625. };
  6626. // The first token should be appended to the last line.
  6627. if (!i) {
  6628. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6629. // Consider cases:
  6630. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6631. // (which is a placeholder) should be replaced by new token.
  6632. // (2) A image backage, where token likes {a|}.
  6633. // (3) A redundant '' will affect textAlign in line.
  6634. // (4) tokens with the same tplName should not be merged, because
  6635. // they should be displayed in different box (with border and padding).
  6636. var tokensLen = tokens.length;
  6637. (tokensLen === 1 && tokens[0].isLineHolder)
  6638. ? (tokens[0] = token)
  6639. // Consider text is '', only insert when it is the "lineHolder" or
  6640. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6641. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6642. }
  6643. // Other tokens always start a new line.
  6644. else {
  6645. // If there is '', insert it as a placeholder.
  6646. lines.push({tokens: [token]});
  6647. }
  6648. }
  6649. }
  6650. function makeFont(style) {
  6651. // FIXME in node-canvas fontWeight is before fontStyle
  6652. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6653. var font = (style.fontSize || style.fontFamily) && [
  6654. style.fontStyle,
  6655. style.fontWeight,
  6656. (style.fontSize || 12) + 'px',
  6657. // If font properties are defined, `fontFamily` should not be ignored.
  6658. style.fontFamily || 'sans-serif'
  6659. ].join(' ');
  6660. return font && trim(font) || style.textFont || style.font;
  6661. }
  6662. function buildPath(ctx, shape) {
  6663. var x = shape.x;
  6664. var y = shape.y;
  6665. var width = shape.width;
  6666. var height = shape.height;
  6667. var r = shape.r;
  6668. var r1;
  6669. var r2;
  6670. var r3;
  6671. var r4;
  6672. // Convert width and height to positive for better borderRadius
  6673. if (width < 0) {
  6674. x = x + width;
  6675. width = -width;
  6676. }
  6677. if (height < 0) {
  6678. y = y + height;
  6679. height = -height;
  6680. }
  6681. if (typeof r === 'number') {
  6682. r1 = r2 = r3 = r4 = r;
  6683. }
  6684. else if (r instanceof Array) {
  6685. if (r.length === 1) {
  6686. r1 = r2 = r3 = r4 = r[0];
  6687. }
  6688. else if (r.length === 2) {
  6689. r1 = r3 = r[0];
  6690. r2 = r4 = r[1];
  6691. }
  6692. else if (r.length === 3) {
  6693. r1 = r[0];
  6694. r2 = r4 = r[1];
  6695. r3 = r[2];
  6696. }
  6697. else {
  6698. r1 = r[0];
  6699. r2 = r[1];
  6700. r3 = r[2];
  6701. r4 = r[3];
  6702. }
  6703. }
  6704. else {
  6705. r1 = r2 = r3 = r4 = 0;
  6706. }
  6707. var total;
  6708. if (r1 + r2 > width) {
  6709. total = r1 + r2;
  6710. r1 *= width / total;
  6711. r2 *= width / total;
  6712. }
  6713. if (r3 + r4 > width) {
  6714. total = r3 + r4;
  6715. r3 *= width / total;
  6716. r4 *= width / total;
  6717. }
  6718. if (r2 + r3 > height) {
  6719. total = r2 + r3;
  6720. r2 *= height / total;
  6721. r3 *= height / total;
  6722. }
  6723. if (r1 + r4 > height) {
  6724. total = r1 + r4;
  6725. r1 *= height / total;
  6726. r4 *= height / total;
  6727. }
  6728. ctx.moveTo(x + r1, y);
  6729. ctx.lineTo(x + width - r2, y);
  6730. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  6731. ctx.lineTo(x + width, y + height - r3);
  6732. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  6733. ctx.lineTo(x + r4, y + height);
  6734. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  6735. ctx.lineTo(x, y + r1);
  6736. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  6737. }
  6738. // TODO: Have not support 'start', 'end' yet.
  6739. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6740. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6741. /**
  6742. * @param {module:zrender/graphic/Style} style
  6743. * @return {module:zrender/graphic/Style} The input style.
  6744. */
  6745. function normalizeTextStyle(style) {
  6746. normalizeStyle(style);
  6747. each$1(style.rich, normalizeStyle);
  6748. return style;
  6749. }
  6750. function normalizeStyle(style) {
  6751. if (style) {
  6752. style.font = makeFont(style);
  6753. var textAlign = style.textAlign;
  6754. textAlign === 'middle' && (textAlign = 'center');
  6755. style.textAlign = (
  6756. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6757. ) ? textAlign : 'left';
  6758. // Compatible with textBaseline.
  6759. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6760. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6761. style.textVerticalAlign = (
  6762. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6763. ) ? textVerticalAlign : 'top';
  6764. var textPadding = style.textPadding;
  6765. if (textPadding) {
  6766. style.textPadding = normalizeCssArray(style.textPadding);
  6767. }
  6768. }
  6769. }
  6770. /**
  6771. * @param {CanvasRenderingContext2D} ctx
  6772. * @param {string} text
  6773. * @param {module:zrender/graphic/Style} style
  6774. * @param {Object|boolean} [rect] {x, y, width, height}
  6775. * If set false, rect text is not used.
  6776. */
  6777. function renderText(hostEl, ctx, text, style, rect) {
  6778. style.rich
  6779. ? renderRichText(hostEl, ctx, text, style, rect)
  6780. : renderPlainText(hostEl, ctx, text, style, rect);
  6781. }
  6782. function renderPlainText(hostEl, ctx, text, style, rect) {
  6783. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6784. var textPadding = style.textPadding;
  6785. var contentBlock = hostEl.__textCotentBlock;
  6786. if (!contentBlock || hostEl.__dirty) {
  6787. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6788. text, font, textPadding, style.truncate
  6789. );
  6790. }
  6791. var outerHeight = contentBlock.outerHeight;
  6792. var textLines = contentBlock.lines;
  6793. var lineHeight = contentBlock.lineHeight;
  6794. var boxPos = getBoxPosition(outerHeight, style, rect);
  6795. var baseX = boxPos.baseX;
  6796. var baseY = boxPos.baseY;
  6797. var textAlign = boxPos.textAlign;
  6798. var textVerticalAlign = boxPos.textVerticalAlign;
  6799. // Origin of textRotation should be the base point of text drawing.
  6800. applyTextRotation(ctx, style, rect, baseX, baseY);
  6801. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6802. var textX = baseX;
  6803. var textY = boxY;
  6804. var needDrawBg = needDrawBackground(style);
  6805. if (needDrawBg || textPadding) {
  6806. // Consider performance, do not call getTextWidth util necessary.
  6807. var textWidth = getWidth(text, font);
  6808. var outerWidth = textWidth;
  6809. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6810. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6811. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6812. if (textPadding) {
  6813. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6814. textY += textPadding[0];
  6815. }
  6816. }
  6817. setCtx(ctx, 'textAlign', textAlign || 'left');
  6818. // Force baseline to be "middle". Otherwise, if using "top", the
  6819. // text will offset downward a little bit in font "Microsoft YaHei".
  6820. setCtx(ctx, 'textBaseline', 'middle');
  6821. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6822. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6823. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6824. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6825. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6826. // `textBaseline` is set as 'middle'.
  6827. textY += lineHeight / 2;
  6828. var textStrokeWidth = style.textStrokeWidth;
  6829. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6830. var textFill = getFill(style.textFill);
  6831. if (textStroke) {
  6832. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6833. setCtx(ctx, 'strokeStyle', textStroke);
  6834. }
  6835. if (textFill) {
  6836. setCtx(ctx, 'fillStyle', textFill);
  6837. }
  6838. for (var i = 0; i < textLines.length; i++) {
  6839. // Fill after stroke so the outline will not cover the main part.
  6840. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6841. textFill && ctx.fillText(textLines[i], textX, textY);
  6842. textY += lineHeight;
  6843. }
  6844. }
  6845. function renderRichText(hostEl, ctx, text, style, rect) {
  6846. var contentBlock = hostEl.__textCotentBlock;
  6847. if (!contentBlock || hostEl.__dirty) {
  6848. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6849. }
  6850. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6851. }
  6852. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6853. var contentWidth = contentBlock.width;
  6854. var outerWidth = contentBlock.outerWidth;
  6855. var outerHeight = contentBlock.outerHeight;
  6856. var textPadding = style.textPadding;
  6857. var boxPos = getBoxPosition(outerHeight, style, rect);
  6858. var baseX = boxPos.baseX;
  6859. var baseY = boxPos.baseY;
  6860. var textAlign = boxPos.textAlign;
  6861. var textVerticalAlign = boxPos.textVerticalAlign;
  6862. // Origin of textRotation should be the base point of text drawing.
  6863. applyTextRotation(ctx, style, rect, baseX, baseY);
  6864. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6865. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6866. var xLeft = boxX;
  6867. var lineTop = boxY;
  6868. if (textPadding) {
  6869. xLeft += textPadding[3];
  6870. lineTop += textPadding[0];
  6871. }
  6872. var xRight = xLeft + contentWidth;
  6873. needDrawBackground(style) && drawBackground(
  6874. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6875. );
  6876. for (var i = 0; i < contentBlock.lines.length; i++) {
  6877. var line = contentBlock.lines[i];
  6878. var tokens = line.tokens;
  6879. var tokenCount = tokens.length;
  6880. var lineHeight = line.lineHeight;
  6881. var usedWidth = line.width;
  6882. var leftIndex = 0;
  6883. var lineXLeft = xLeft;
  6884. var lineXRight = xRight;
  6885. var rightIndex = tokenCount - 1;
  6886. var token;
  6887. while (
  6888. leftIndex < tokenCount
  6889. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6890. ) {
  6891. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6892. usedWidth -= token.width;
  6893. lineXLeft += token.width;
  6894. leftIndex++;
  6895. }
  6896. while (
  6897. rightIndex >= 0
  6898. && (token = tokens[rightIndex], token.textAlign === 'right')
  6899. ) {
  6900. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6901. usedWidth -= token.width;
  6902. lineXRight -= token.width;
  6903. rightIndex--;
  6904. }
  6905. // The other tokens are placed as textAlign 'center' if there is enough space.
  6906. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6907. while (leftIndex <= rightIndex) {
  6908. token = tokens[leftIndex];
  6909. // Consider width specified by user, use 'center' rather than 'left'.
  6910. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6911. lineXLeft += token.width;
  6912. leftIndex++;
  6913. }
  6914. lineTop += lineHeight;
  6915. }
  6916. }
  6917. function applyTextRotation(ctx, style, rect, x, y) {
  6918. // textRotation only apply in RectText.
  6919. if (rect && style.textRotation) {
  6920. var origin = style.textOrigin;
  6921. if (origin === 'center') {
  6922. x = rect.width / 2 + rect.x;
  6923. y = rect.height / 2 + rect.y;
  6924. }
  6925. else if (origin) {
  6926. x = origin[0] + rect.x;
  6927. y = origin[1] + rect.y;
  6928. }
  6929. ctx.translate(x, y);
  6930. // Positive: anticlockwise
  6931. ctx.rotate(-style.textRotation);
  6932. ctx.translate(-x, -y);
  6933. }
  6934. }
  6935. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6936. var tokenStyle = style.rich[token.styleName] || {};
  6937. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6938. // the bias of "Microsoft YaHei".
  6939. var textVerticalAlign = token.textVerticalAlign;
  6940. var y = lineTop + lineHeight / 2;
  6941. if (textVerticalAlign === 'top') {
  6942. y = lineTop + token.height / 2;
  6943. }
  6944. else if (textVerticalAlign === 'bottom') {
  6945. y = lineTop + lineHeight - token.height / 2;
  6946. }
  6947. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6948. hostEl,
  6949. ctx,
  6950. tokenStyle,
  6951. textAlign === 'right'
  6952. ? x - token.width
  6953. : textAlign === 'center'
  6954. ? x - token.width / 2
  6955. : x,
  6956. y - token.height / 2,
  6957. token.width,
  6958. token.height
  6959. );
  6960. var textPadding = token.textPadding;
  6961. if (textPadding) {
  6962. x = getTextXForPadding(x, textAlign, textPadding);
  6963. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6964. }
  6965. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6966. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6967. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6968. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6969. setCtx(ctx, 'textAlign', textAlign);
  6970. // Force baseline to be "middle". Otherwise, if using "top", the
  6971. // text will offset downward a little bit in font "Microsoft YaHei".
  6972. setCtx(ctx, 'textBaseline', 'middle');
  6973. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6974. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6975. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6976. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6977. // Fill after stroke so the outline will not cover the main part.
  6978. if (textStroke) {
  6979. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6980. setCtx(ctx, 'strokeStyle', textStroke);
  6981. ctx.strokeText(token.text, x, y);
  6982. }
  6983. if (textFill) {
  6984. setCtx(ctx, 'fillStyle', textFill);
  6985. ctx.fillText(token.text, x, y);
  6986. }
  6987. }
  6988. function needDrawBackground(style) {
  6989. return style.textBackgroundColor
  6990. || (style.textBorderWidth && style.textBorderColor);
  6991. }
  6992. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6993. // shape: {x, y, width, height}
  6994. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  6995. var textBackgroundColor = style.textBackgroundColor;
  6996. var textBorderWidth = style.textBorderWidth;
  6997. var textBorderColor = style.textBorderColor;
  6998. var isPlainBg = isString(textBackgroundColor);
  6999. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7000. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7001. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7002. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7003. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7004. ctx.beginPath();
  7005. var textBorderRadius = style.textBorderRadius;
  7006. if (!textBorderRadius) {
  7007. ctx.rect(x, y, width, height);
  7008. }
  7009. else {
  7010. buildPath(ctx, {
  7011. x: x, y: y, width: width, height: height, r: textBorderRadius
  7012. });
  7013. }
  7014. ctx.closePath();
  7015. }
  7016. if (isPlainBg) {
  7017. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7018. ctx.fill();
  7019. }
  7020. else if (isObject$1(textBackgroundColor)) {
  7021. var image = textBackgroundColor.image;
  7022. image = createOrUpdateImage(
  7023. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7024. );
  7025. if (image && isImageReady(image)) {
  7026. ctx.drawImage(image, x, y, width, height);
  7027. }
  7028. }
  7029. if (textBorderWidth && textBorderColor) {
  7030. setCtx(ctx, 'lineWidth', textBorderWidth);
  7031. setCtx(ctx, 'strokeStyle', textBorderColor);
  7032. ctx.stroke();
  7033. }
  7034. }
  7035. function onBgImageLoaded(image, textBackgroundColor) {
  7036. // Replace image, so that `contain/text.js#parseRichText`
  7037. // will get correct result in next tick.
  7038. textBackgroundColor.image = image;
  7039. }
  7040. function getBoxPosition(blockHeiht, style, rect) {
  7041. var baseX = style.x || 0;
  7042. var baseY = style.y || 0;
  7043. var textAlign = style.textAlign;
  7044. var textVerticalAlign = style.textVerticalAlign;
  7045. // Text position represented by coord
  7046. if (rect) {
  7047. var textPosition = style.textPosition;
  7048. if (textPosition instanceof Array) {
  7049. // Percent
  7050. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7051. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7052. }
  7053. else {
  7054. var res = adjustTextPositionOnRect(
  7055. textPosition, rect, style.textDistance
  7056. );
  7057. baseX = res.x;
  7058. baseY = res.y;
  7059. // Default align and baseline when has textPosition
  7060. textAlign = textAlign || res.textAlign;
  7061. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7062. }
  7063. // textOffset is only support in RectText, otherwise
  7064. // we have to adjust boundingRect for textOffset.
  7065. var textOffset = style.textOffset;
  7066. if (textOffset) {
  7067. baseX += textOffset[0];
  7068. baseY += textOffset[1];
  7069. }
  7070. }
  7071. return {
  7072. baseX: baseX,
  7073. baseY: baseY,
  7074. textAlign: textAlign,
  7075. textVerticalAlign: textVerticalAlign
  7076. };
  7077. }
  7078. function setCtx(ctx, prop, value) {
  7079. ctx[prop] = fixShadow(ctx, prop, value);
  7080. return ctx[prop];
  7081. }
  7082. /**
  7083. * @param {string} [stroke] If specified, do not check style.textStroke.
  7084. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7085. * @param {number} style
  7086. */
  7087. function getStroke(stroke, lineWidth) {
  7088. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7089. ? null
  7090. // TODO pattern and gradient?
  7091. : (stroke.image || stroke.colorStops)
  7092. ? '#000'
  7093. : stroke;
  7094. }
  7095. function getFill(fill) {
  7096. return (fill == null || fill === 'none')
  7097. ? null
  7098. // TODO pattern and gradient?
  7099. : (fill.image || fill.colorStops)
  7100. ? '#000'
  7101. : fill;
  7102. }
  7103. function parsePercent(value, maxValue) {
  7104. if (typeof value === 'string') {
  7105. if (value.lastIndexOf('%') >= 0) {
  7106. return parseFloat(value) / 100 * maxValue;
  7107. }
  7108. return parseFloat(value);
  7109. }
  7110. return value;
  7111. }
  7112. function getTextXForPadding(x, textAlign, textPadding) {
  7113. return textAlign === 'right'
  7114. ? (x - textPadding[1])
  7115. : textAlign === 'center'
  7116. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7117. : (x + textPadding[3]);
  7118. }
  7119. /**
  7120. * @param {string} text
  7121. * @param {module:zrender/Style} style
  7122. * @return {boolean}
  7123. */
  7124. function needDrawText(text, style) {
  7125. return text != null
  7126. && (text
  7127. || style.textBackgroundColor
  7128. || (style.textBorderWidth && style.textBorderColor)
  7129. || style.textPadding
  7130. );
  7131. }
  7132. /**
  7133. * Mixin for drawing text in a element bounding rect
  7134. * @module zrender/mixin/RectText
  7135. */
  7136. var tmpRect$1 = new BoundingRect();
  7137. var RectText = function () {};
  7138. RectText.prototype = {
  7139. constructor: RectText,
  7140. /**
  7141. * Draw text in a rect with specified position.
  7142. * @param {CanvasRenderingContext2D} ctx
  7143. * @param {Object} rect Displayable rect
  7144. */
  7145. drawRectText: function (ctx, rect) {
  7146. var style = this.style;
  7147. rect = style.textRect || rect;
  7148. // Optimize, avoid normalize every time.
  7149. this.__dirty && normalizeTextStyle(style, true);
  7150. var text = style.text;
  7151. // Convert to string
  7152. text != null && (text += '');
  7153. if (!needDrawText(text, style)) {
  7154. return;
  7155. }
  7156. // FIXME
  7157. ctx.save();
  7158. // Transform rect to view space
  7159. var transform = this.transform;
  7160. if (!style.transformText) {
  7161. if (transform) {
  7162. tmpRect$1.copy(rect);
  7163. tmpRect$1.applyTransform(transform);
  7164. rect = tmpRect$1;
  7165. }
  7166. }
  7167. else {
  7168. this.setTransform(ctx);
  7169. }
  7170. // transformText and textRotation can not be used at the same time.
  7171. renderText(this, ctx, text, style, rect);
  7172. ctx.restore();
  7173. }
  7174. };
  7175. /**
  7176. * 可绘制的图形基类
  7177. * Base class of all displayable graphic objects
  7178. * @module zrender/graphic/Displayable
  7179. */
  7180. /**
  7181. * @alias module:zrender/graphic/Displayable
  7182. * @extends module:zrender/Element
  7183. * @extends module:zrender/graphic/mixin/RectText
  7184. */
  7185. function Displayable(opts) {
  7186. opts = opts || {};
  7187. Element.call(this, opts);
  7188. // Extend properties
  7189. for (var name in opts) {
  7190. if (
  7191. opts.hasOwnProperty(name) &&
  7192. name !== 'style'
  7193. ) {
  7194. this[name] = opts[name];
  7195. }
  7196. }
  7197. /**
  7198. * @type {module:zrender/graphic/Style}
  7199. */
  7200. this.style = new Style(opts.style, this);
  7201. this._rect = null;
  7202. // Shapes for cascade clipping.
  7203. this.__clipPaths = [];
  7204. // FIXME Stateful must be mixined after style is setted
  7205. // Stateful.call(this, opts);
  7206. }
  7207. Displayable.prototype = {
  7208. constructor: Displayable,
  7209. type: 'displayable',
  7210. /**
  7211. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7212. * Dirty flag. From which painter will determine if this displayable object needs brush
  7213. * @name module:zrender/graphic/Displayable#__dirty
  7214. * @type {boolean}
  7215. */
  7216. __dirty: true,
  7217. /**
  7218. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7219. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7220. * @name module:/zrender/graphic/Displayable#invisible
  7221. * @type {boolean}
  7222. * @default false
  7223. */
  7224. invisible: false,
  7225. /**
  7226. * @name module:/zrender/graphic/Displayable#z
  7227. * @type {number}
  7228. * @default 0
  7229. */
  7230. z: 0,
  7231. /**
  7232. * @name module:/zrender/graphic/Displayable#z
  7233. * @type {number}
  7234. * @default 0
  7235. */
  7236. z2: 0,
  7237. /**
  7238. * z层level,决定绘画在哪层canvas中
  7239. * @name module:/zrender/graphic/Displayable#zlevel
  7240. * @type {number}
  7241. * @default 0
  7242. */
  7243. zlevel: 0,
  7244. /**
  7245. * 是否可拖拽
  7246. * @name module:/zrender/graphic/Displayable#draggable
  7247. * @type {boolean}
  7248. * @default false
  7249. */
  7250. draggable: false,
  7251. /**
  7252. * 是否正在拖拽
  7253. * @name module:/zrender/graphic/Displayable#draggable
  7254. * @type {boolean}
  7255. * @default false
  7256. */
  7257. dragging: false,
  7258. /**
  7259. * 是否相应鼠标事件
  7260. * @name module:/zrender/graphic/Displayable#silent
  7261. * @type {boolean}
  7262. * @default false
  7263. */
  7264. silent: false,
  7265. /**
  7266. * If enable culling
  7267. * @type {boolean}
  7268. * @default false
  7269. */
  7270. culling: false,
  7271. /**
  7272. * Mouse cursor when hovered
  7273. * @name module:/zrender/graphic/Displayable#cursor
  7274. * @type {string}
  7275. */
  7276. cursor: 'pointer',
  7277. /**
  7278. * If hover area is bounding rect
  7279. * @name module:/zrender/graphic/Displayable#rectHover
  7280. * @type {string}
  7281. */
  7282. rectHover: false,
  7283. /**
  7284. * Render the element progressively when the value >= 0,
  7285. * usefull for large data.
  7286. * @type {boolean}
  7287. */
  7288. progressive: false,
  7289. /**
  7290. * @type {boolean}
  7291. */
  7292. incremental: false,
  7293. // inplace is used with incremental
  7294. inplace: false,
  7295. beforeBrush: function (ctx) {},
  7296. afterBrush: function (ctx) {},
  7297. /**
  7298. * 图形绘制方法
  7299. * @param {CanvasRenderingContext2D} ctx
  7300. */
  7301. // Interface
  7302. brush: function (ctx, prevEl) {},
  7303. /**
  7304. * 获取最小包围盒
  7305. * @return {module:zrender/core/BoundingRect}
  7306. */
  7307. // Interface
  7308. getBoundingRect: function () {},
  7309. /**
  7310. * 判断坐标 x, y 是否在图形上
  7311. * If displayable element contain coord x, y
  7312. * @param {number} x
  7313. * @param {number} y
  7314. * @return {boolean}
  7315. */
  7316. contain: function (x, y) {
  7317. return this.rectContain(x, y);
  7318. },
  7319. /**
  7320. * @param {Function} cb
  7321. * @param {} context
  7322. */
  7323. traverse: function (cb, context) {
  7324. cb.call(context, this);
  7325. },
  7326. /**
  7327. * 判断坐标 x, y 是否在图形的包围盒上
  7328. * If bounding rect of element contain coord x, y
  7329. * @param {number} x
  7330. * @param {number} y
  7331. * @return {boolean}
  7332. */
  7333. rectContain: function (x, y) {
  7334. var coord = this.transformCoordToLocal(x, y);
  7335. var rect = this.getBoundingRect();
  7336. return rect.contain(coord[0], coord[1]);
  7337. },
  7338. /**
  7339. * 标记图形元素为脏,并且在下一帧重绘
  7340. * Mark displayable element dirty and refresh next frame
  7341. */
  7342. dirty: function () {
  7343. this.__dirty = true;
  7344. this._rect = null;
  7345. this.__zr && this.__zr.refresh();
  7346. },
  7347. /**
  7348. * 图形是否会触发事件
  7349. * If displayable object binded any event
  7350. * @return {boolean}
  7351. */
  7352. // TODO, 通过 bind 绑定的事件
  7353. // isSilent: function () {
  7354. // return !(
  7355. // this.hoverable || this.draggable
  7356. // || this.onmousemove || this.onmouseover || this.onmouseout
  7357. // || this.onmousedown || this.onmouseup || this.onclick
  7358. // || this.ondragenter || this.ondragover || this.ondragleave
  7359. // || this.ondrop
  7360. // );
  7361. // },
  7362. /**
  7363. * Alias for animate('style')
  7364. * @param {boolean} loop
  7365. */
  7366. animateStyle: function (loop) {
  7367. return this.animate('style', loop);
  7368. },
  7369. attrKV: function (key, value) {
  7370. if (key !== 'style') {
  7371. Element.prototype.attrKV.call(this, key, value);
  7372. }
  7373. else {
  7374. this.style.set(value);
  7375. }
  7376. },
  7377. /**
  7378. * @param {Object|string} key
  7379. * @param {*} value
  7380. */
  7381. setStyle: function (key, value) {
  7382. this.style.set(key, value);
  7383. this.dirty(false);
  7384. return this;
  7385. },
  7386. /**
  7387. * Use given style object
  7388. * @param {Object} obj
  7389. */
  7390. useStyle: function (obj) {
  7391. this.style = new Style(obj, this);
  7392. this.dirty(false);
  7393. return this;
  7394. }
  7395. };
  7396. inherits(Displayable, Element);
  7397. mixin(Displayable, RectText);
  7398. /**
  7399. * @alias zrender/graphic/Image
  7400. * @extends module:zrender/graphic/Displayable
  7401. * @constructor
  7402. * @param {Object} opts
  7403. */
  7404. function ZImage(opts) {
  7405. Displayable.call(this, opts);
  7406. }
  7407. ZImage.prototype = {
  7408. constructor: ZImage,
  7409. type: 'image',
  7410. brush: function (ctx, prevEl) {
  7411. var style = this.style;
  7412. var src = style.image;
  7413. // Must bind each time
  7414. style.bind(ctx, this, prevEl);
  7415. var image = this._image = createOrUpdateImage(
  7416. src,
  7417. this._image,
  7418. this,
  7419. this.onload
  7420. );
  7421. if (!image || !isImageReady(image)) {
  7422. return;
  7423. }
  7424. // 图片已经加载完成
  7425. // if (image.nodeName.toUpperCase() == 'IMG') {
  7426. // if (!image.complete) {
  7427. // return;
  7428. // }
  7429. // }
  7430. // Else is canvas
  7431. var x = style.x || 0;
  7432. var y = style.y || 0;
  7433. var width = style.width;
  7434. var height = style.height;
  7435. var aspect = image.width / image.height;
  7436. if (width == null && height != null) {
  7437. // Keep image/height ratio
  7438. width = height * aspect;
  7439. }
  7440. else if (height == null && width != null) {
  7441. height = width / aspect;
  7442. }
  7443. else if (width == null && height == null) {
  7444. width = image.width;
  7445. height = image.height;
  7446. }
  7447. // 设置transform
  7448. this.setTransform(ctx);
  7449. if (style.sWidth && style.sHeight) {
  7450. var sx = style.sx || 0;
  7451. var sy = style.sy || 0;
  7452. ctx.drawImage(
  7453. image,
  7454. sx, sy, style.sWidth, style.sHeight,
  7455. x, y, width, height
  7456. );
  7457. }
  7458. else if (style.sx && style.sy) {
  7459. var sx = style.sx;
  7460. var sy = style.sy;
  7461. var sWidth = width - sx;
  7462. var sHeight = height - sy;
  7463. ctx.drawImage(
  7464. image,
  7465. sx, sy, sWidth, sHeight,
  7466. x, y, width, height
  7467. );
  7468. }
  7469. else {
  7470. ctx.drawImage(image, x, y, width, height);
  7471. }
  7472. // Draw rect text
  7473. if (style.text != null) {
  7474. // Only restore transform when needs draw text.
  7475. this.restoreTransform(ctx);
  7476. this.drawRectText(ctx, this.getBoundingRect());
  7477. }
  7478. },
  7479. getBoundingRect: function () {
  7480. var style = this.style;
  7481. if (! this._rect) {
  7482. this._rect = new BoundingRect(
  7483. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7484. );
  7485. }
  7486. return this._rect;
  7487. }
  7488. };
  7489. inherits(ZImage, Displayable);
  7490. var HOVER_LAYER_ZLEVEL = 1e5;
  7491. var CANVAS_ZLEVEL = 314159;
  7492. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7493. var INCREMENTAL_INC = 0.001;
  7494. function parseInt10(val) {
  7495. return parseInt(val, 10);
  7496. }
  7497. function isLayerValid(layer) {
  7498. if (!layer) {
  7499. return false;
  7500. }
  7501. if (layer.__builtin__) {
  7502. return true;
  7503. }
  7504. if (typeof(layer.resize) !== 'function'
  7505. || typeof(layer.refresh) !== 'function'
  7506. ) {
  7507. return false;
  7508. }
  7509. return true;
  7510. }
  7511. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7512. var viewRect = new BoundingRect(0, 0, 0, 0);
  7513. function isDisplayableCulled(el, width, height) {
  7514. tmpRect.copy(el.getBoundingRect());
  7515. if (el.transform) {
  7516. tmpRect.applyTransform(el.transform);
  7517. }
  7518. viewRect.width = width;
  7519. viewRect.height = height;
  7520. return !tmpRect.intersect(viewRect);
  7521. }
  7522. function isClipPathChanged(clipPaths, prevClipPaths) {
  7523. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7524. return false;
  7525. }
  7526. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7527. return true;
  7528. }
  7529. for (var i = 0; i < clipPaths.length; i++) {
  7530. if (clipPaths[i] !== prevClipPaths[i]) {
  7531. return true;
  7532. }
  7533. }
  7534. }
  7535. function doClip(clipPaths, ctx) {
  7536. for (var i = 0; i < clipPaths.length; i++) {
  7537. var clipPath = clipPaths[i];
  7538. clipPath.setTransform(ctx);
  7539. ctx.beginPath();
  7540. clipPath.buildPath(ctx, clipPath.shape);
  7541. ctx.clip();
  7542. // Transform back
  7543. clipPath.restoreTransform(ctx);
  7544. }
  7545. }
  7546. function createRoot(width, height) {
  7547. var domRoot = document.createElement('div');
  7548. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7549. domRoot.style.cssText = [
  7550. 'position:relative',
  7551. 'overflow:hidden',
  7552. 'width:' + width + 'px',
  7553. 'height:' + height + 'px',
  7554. 'padding:0',
  7555. 'margin:0',
  7556. 'border-width:0'
  7557. ].join(';') + ';';
  7558. return domRoot;
  7559. }
  7560. /**
  7561. * @alias module:zrender/Painter
  7562. * @constructor
  7563. * @param {HTMLElement} root 绘图容器
  7564. * @param {module:zrender/Storage} storage
  7565. * @param {Object} opts
  7566. */
  7567. var Painter = function (root, storage, opts) {
  7568. this.type = 'canvas';
  7569. // In node environment using node-canvas
  7570. var singleCanvas = !root.nodeName // In node ?
  7571. || root.nodeName.toUpperCase() === 'CANVAS';
  7572. this._opts = opts = extend({}, opts || {});
  7573. /**
  7574. * @type {number}
  7575. */
  7576. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7577. /**
  7578. * @type {boolean}
  7579. * @private
  7580. */
  7581. this._singleCanvas = singleCanvas;
  7582. /**
  7583. * 绘图容器
  7584. * @type {HTMLElement}
  7585. */
  7586. this.root = root;
  7587. var rootStyle = root.style;
  7588. if (rootStyle) {
  7589. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7590. rootStyle['-webkit-user-select'] =
  7591. rootStyle['user-select'] =
  7592. rootStyle['-webkit-touch-callout'] = 'none';
  7593. root.innerHTML = '';
  7594. }
  7595. /**
  7596. * @type {module:zrender/Storage}
  7597. */
  7598. this.storage = storage;
  7599. /**
  7600. * @type {Array.<number>}
  7601. * @private
  7602. */
  7603. var zlevelList = this._zlevelList = [];
  7604. /**
  7605. * @type {Object.<string, module:zrender/Layer>}
  7606. * @private
  7607. */
  7608. var layers = this._layers = {};
  7609. /**
  7610. * @type {Object.<string, Object>}
  7611. * @private
  7612. */
  7613. this._layerConfig = {};
  7614. /**
  7615. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7616. */
  7617. this._needsManuallyCompositing = false;
  7618. if (!singleCanvas) {
  7619. this._width = this._getSize(0);
  7620. this._height = this._getSize(1);
  7621. var domRoot = this._domRoot = createRoot(
  7622. this._width, this._height
  7623. );
  7624. root.appendChild(domRoot);
  7625. }
  7626. else {
  7627. var width = root.width;
  7628. var height = root.height;
  7629. if (opts.width != null) {
  7630. width = opts.width;
  7631. }
  7632. if (opts.height != null) {
  7633. height = opts.height;
  7634. }
  7635. this.dpr = opts.devicePixelRatio || 1;
  7636. // Use canvas width and height directly
  7637. root.width = width * this.dpr;
  7638. root.height = height * this.dpr;
  7639. this._width = width;
  7640. this._height = height;
  7641. // Create layer if only one given canvas
  7642. // Device can be specified to create a high dpi image.
  7643. var mainLayer = new Layer(root, this, this.dpr);
  7644. mainLayer.__builtin__ = true;
  7645. mainLayer.initContext();
  7646. // FIXME Use canvas width and height
  7647. // mainLayer.resize(width, height);
  7648. layers[CANVAS_ZLEVEL] = mainLayer;
  7649. mainLayer.zlevel = CANVAS_ZLEVEL;
  7650. // Not use common zlevel.
  7651. zlevelList.push(CANVAS_ZLEVEL);
  7652. this._domRoot = root;
  7653. }
  7654. /**
  7655. * @type {module:zrender/Layer}
  7656. * @private
  7657. */
  7658. this._hoverlayer = null;
  7659. this._hoverElements = [];
  7660. };
  7661. Painter.prototype = {
  7662. constructor: Painter,
  7663. getType: function () {
  7664. return 'canvas';
  7665. },
  7666. /**
  7667. * If painter use a single canvas
  7668. * @return {boolean}
  7669. */
  7670. isSingleCanvas: function () {
  7671. return this._singleCanvas;
  7672. },
  7673. /**
  7674. * @return {HTMLDivElement}
  7675. */
  7676. getViewportRoot: function () {
  7677. return this._domRoot;
  7678. },
  7679. getViewportRootOffset: function () {
  7680. var viewportRoot = this.getViewportRoot();
  7681. if (viewportRoot) {
  7682. return {
  7683. offsetLeft: viewportRoot.offsetLeft || 0,
  7684. offsetTop: viewportRoot.offsetTop || 0
  7685. };
  7686. }
  7687. },
  7688. /**
  7689. * 刷新
  7690. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7691. */
  7692. refresh: function (paintAll) {
  7693. var list = this.storage.getDisplayList(true);
  7694. var zlevelList = this._zlevelList;
  7695. this._redrawId = Math.random();
  7696. this._paintList(list, paintAll, this._redrawId);
  7697. // Paint custum layers
  7698. for (var i = 0; i < zlevelList.length; i++) {
  7699. var z = zlevelList[i];
  7700. var layer = this._layers[z];
  7701. if (!layer.__builtin__ && layer.refresh) {
  7702. var clearColor = i === 0 ? this._backgroundColor : null;
  7703. layer.refresh(clearColor);
  7704. }
  7705. }
  7706. this.refreshHover();
  7707. return this;
  7708. },
  7709. addHover: function (el, hoverStyle) {
  7710. if (el.__hoverMir) {
  7711. return;
  7712. }
  7713. var elMirror = new el.constructor({
  7714. style: el.style,
  7715. shape: el.shape
  7716. });
  7717. elMirror.__from = el;
  7718. el.__hoverMir = elMirror;
  7719. elMirror.setStyle(hoverStyle);
  7720. this._hoverElements.push(elMirror);
  7721. },
  7722. removeHover: function (el) {
  7723. var elMirror = el.__hoverMir;
  7724. var hoverElements = this._hoverElements;
  7725. var idx = indexOf(hoverElements, elMirror);
  7726. if (idx >= 0) {
  7727. hoverElements.splice(idx, 1);
  7728. }
  7729. el.__hoverMir = null;
  7730. },
  7731. clearHover: function (el) {
  7732. var hoverElements = this._hoverElements;
  7733. for (var i = 0; i < hoverElements.length; i++) {
  7734. var from = hoverElements[i].__from;
  7735. if (from) {
  7736. from.__hoverMir = null;
  7737. }
  7738. }
  7739. hoverElements.length = 0;
  7740. },
  7741. refreshHover: function () {
  7742. var hoverElements = this._hoverElements;
  7743. var len = hoverElements.length;
  7744. var hoverLayer = this._hoverlayer;
  7745. hoverLayer && hoverLayer.clear();
  7746. if (!len) {
  7747. return;
  7748. }
  7749. sort(hoverElements, this.storage.displayableSortFunc);
  7750. // Use a extream large zlevel
  7751. // FIXME?
  7752. if (!hoverLayer) {
  7753. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  7754. }
  7755. var scope = {};
  7756. hoverLayer.ctx.save();
  7757. for (var i = 0; i < len;) {
  7758. var el = hoverElements[i];
  7759. var originalEl = el.__from;
  7760. // Original el is removed
  7761. // PENDING
  7762. if (!(originalEl && originalEl.__zr)) {
  7763. hoverElements.splice(i, 1);
  7764. originalEl.__hoverMir = null;
  7765. len--;
  7766. continue;
  7767. }
  7768. i++;
  7769. // Use transform
  7770. // FIXME style and shape ?
  7771. if (!originalEl.invisible) {
  7772. el.transform = originalEl.transform;
  7773. el.invTransform = originalEl.invTransform;
  7774. el.__clipPaths = originalEl.__clipPaths;
  7775. // el.
  7776. this._doPaintEl(el, hoverLayer, true, scope);
  7777. }
  7778. }
  7779. hoverLayer.ctx.restore();
  7780. },
  7781. getHoverLayer: function () {
  7782. return this.getLayer(HOVER_LAYER_ZLEVEL);
  7783. },
  7784. _paintList: function (list, paintAll, redrawId) {
  7785. if (this._redrawId !== redrawId) {
  7786. return;
  7787. }
  7788. paintAll = paintAll || false;
  7789. this._updateLayerStatus(list);
  7790. var finished = this._doPaintList(list, paintAll);
  7791. if (this._needsManuallyCompositing) {
  7792. this._compositeManually();
  7793. }
  7794. if (!finished) {
  7795. var self = this;
  7796. requestAnimationFrame(function () {
  7797. self._paintList(list, paintAll, redrawId);
  7798. });
  7799. }
  7800. },
  7801. _compositeManually: function () {
  7802. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  7803. var width = this._domRoot.width;
  7804. var height = this._domRoot.height;
  7805. ctx.clearRect(0, 0, width, height);
  7806. // PENDING, If only builtin layer?
  7807. this.eachBuiltinLayer(function (layer) {
  7808. if (layer.virtual) {
  7809. ctx.drawImage(layer.dom, 0, 0, width, height);
  7810. }
  7811. });
  7812. },
  7813. _doPaintList: function (list, paintAll) {
  7814. var layerList = [];
  7815. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  7816. var zlevel = this._zlevelList[zi];
  7817. var layer = this._layers[zlevel];
  7818. if (layer.__builtin__
  7819. && layer !== this._hoverlayer
  7820. && (layer.__dirty || paintAll)
  7821. ) {
  7822. layerList.push(layer);
  7823. }
  7824. }
  7825. var finished = true;
  7826. for (var k = 0; k < layerList.length; k++) {
  7827. var layer = layerList[k];
  7828. var ctx = layer.ctx;
  7829. var scope = {};
  7830. ctx.save();
  7831. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  7832. var useTimer = !paintAll && layer.incremental && Date.now;
  7833. var startTime = useTimer && Date.now();
  7834. var clearColor = layer.zlevel === this._zlevelList[0]
  7835. ? this._backgroundColor : null;
  7836. // All elements in this layer are cleared.
  7837. if (layer.__startIndex === layer.__endIndex) {
  7838. layer.clear(false, clearColor);
  7839. }
  7840. else if (start === layer.__startIndex) {
  7841. var firstEl = list[start];
  7842. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  7843. layer.clear(false, clearColor);
  7844. }
  7845. }
  7846. if (start === -1) {
  7847. console.error('For some unknown reason. drawIndex is -1');
  7848. start = layer.__startIndex;
  7849. }
  7850. for (var i = start; i < layer.__endIndex; i++) {
  7851. var el = list[i];
  7852. this._doPaintEl(el, layer, paintAll, scope);
  7853. el.__dirty = false;
  7854. if (useTimer) {
  7855. // Date.now can be executed in 13,025,305 ops/second.
  7856. var dTime = Date.now() - startTime;
  7857. // Give 15 millisecond to draw.
  7858. // The rest elements will be drawn in the next frame.
  7859. if (dTime > 15) {
  7860. break;
  7861. }
  7862. }
  7863. }
  7864. layer.__drawIndex = i;
  7865. if (layer.__drawIndex < layer.__endIndex) {
  7866. finished = false;
  7867. }
  7868. if (scope.prevElClipPaths) {
  7869. // Needs restore the state. If last drawn element is in the clipping area.
  7870. ctx.restore();
  7871. }
  7872. ctx.restore();
  7873. }
  7874. if (env$1.wxa) {
  7875. // Flush for weixin application
  7876. each$1(this._layers, function (layer) {
  7877. if (layer && layer.ctx && layer.ctx.draw) {
  7878. layer.ctx.draw();
  7879. }
  7880. });
  7881. }
  7882. return finished;
  7883. },
  7884. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7885. var ctx = currentLayer.ctx;
  7886. var m = el.transform;
  7887. if (
  7888. (currentLayer.__dirty || forcePaint)
  7889. // Ignore invisible element
  7890. && !el.invisible
  7891. // Ignore transparent element
  7892. && el.style.opacity !== 0
  7893. // Ignore scale 0 element, in some environment like node-canvas
  7894. // Draw a scale 0 element can cause all following draw wrong
  7895. // And setTransform with scale 0 will cause set back transform failed.
  7896. && !(m && !m[0] && !m[3])
  7897. // Ignore culled element
  7898. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7899. ) {
  7900. var clipPaths = el.__clipPaths;
  7901. // Optimize when clipping on group with several elements
  7902. if (!scope.prevElClipPaths
  7903. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7904. ) {
  7905. // If has previous clipping state, restore from it
  7906. if (scope.prevElClipPaths) {
  7907. currentLayer.ctx.restore();
  7908. scope.prevElClipPaths = null;
  7909. // Reset prevEl since context has been restored
  7910. scope.prevEl = null;
  7911. }
  7912. // New clipping state
  7913. if (clipPaths) {
  7914. ctx.save();
  7915. doClip(clipPaths, ctx);
  7916. scope.prevElClipPaths = clipPaths;
  7917. }
  7918. }
  7919. el.beforeBrush && el.beforeBrush(ctx);
  7920. el.brush(ctx, scope.prevEl || null);
  7921. scope.prevEl = el;
  7922. el.afterBrush && el.afterBrush(ctx);
  7923. }
  7924. },
  7925. /**
  7926. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7927. * @param {number} zlevel
  7928. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  7929. * @return {module:zrender/Layer}
  7930. */
  7931. getLayer: function (zlevel, virtual) {
  7932. if (this._singleCanvas && !this._needsManuallyCompositing) {
  7933. zlevel = CANVAS_ZLEVEL;
  7934. }
  7935. var layer = this._layers[zlevel];
  7936. if (!layer) {
  7937. // Create a new layer
  7938. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7939. layer.zlevel = zlevel;
  7940. layer.__builtin__ = true;
  7941. if (this._layerConfig[zlevel]) {
  7942. merge(layer, this._layerConfig[zlevel], true);
  7943. }
  7944. if (virtual) {
  7945. layer.virtual = virtual;
  7946. }
  7947. this.insertLayer(zlevel, layer);
  7948. // Context is created after dom inserted to document
  7949. // Or excanvas will get 0px clientWidth and clientHeight
  7950. layer.initContext();
  7951. }
  7952. return layer;
  7953. },
  7954. insertLayer: function (zlevel, layer) {
  7955. var layersMap = this._layers;
  7956. var zlevelList = this._zlevelList;
  7957. var len = zlevelList.length;
  7958. var prevLayer = null;
  7959. var i = -1;
  7960. var domRoot = this._domRoot;
  7961. if (layersMap[zlevel]) {
  7962. zrLog('ZLevel ' + zlevel + ' has been used already');
  7963. return;
  7964. }
  7965. // Check if is a valid layer
  7966. if (!isLayerValid(layer)) {
  7967. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  7968. return;
  7969. }
  7970. if (len > 0 && zlevel > zlevelList[0]) {
  7971. for (i = 0; i < len - 1; i++) {
  7972. if (
  7973. zlevelList[i] < zlevel
  7974. && zlevelList[i + 1] > zlevel
  7975. ) {
  7976. break;
  7977. }
  7978. }
  7979. prevLayer = layersMap[zlevelList[i]];
  7980. }
  7981. zlevelList.splice(i + 1, 0, zlevel);
  7982. layersMap[zlevel] = layer;
  7983. // Vitual layer will not directly show on the screen.
  7984. // (It can be a WebGL layer and assigned to a ZImage element)
  7985. // But it still under management of zrender.
  7986. if (!layer.virtual) {
  7987. if (prevLayer) {
  7988. var prevDom = prevLayer.dom;
  7989. if (prevDom.nextSibling) {
  7990. domRoot.insertBefore(
  7991. layer.dom,
  7992. prevDom.nextSibling
  7993. );
  7994. }
  7995. else {
  7996. domRoot.appendChild(layer.dom);
  7997. }
  7998. }
  7999. else {
  8000. if (domRoot.firstChild) {
  8001. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8002. }
  8003. else {
  8004. domRoot.appendChild(layer.dom);
  8005. }
  8006. }
  8007. }
  8008. },
  8009. // Iterate each layer
  8010. eachLayer: function (cb, context) {
  8011. var zlevelList = this._zlevelList;
  8012. var z;
  8013. var i;
  8014. for (i = 0; i < zlevelList.length; i++) {
  8015. z = zlevelList[i];
  8016. cb.call(context, this._layers[z], z);
  8017. }
  8018. },
  8019. // Iterate each buildin layer
  8020. eachBuiltinLayer: function (cb, context) {
  8021. var zlevelList = this._zlevelList;
  8022. var layer;
  8023. var z;
  8024. var i;
  8025. for (i = 0; i < zlevelList.length; i++) {
  8026. z = zlevelList[i];
  8027. layer = this._layers[z];
  8028. if (layer.__builtin__) {
  8029. cb.call(context, layer, z);
  8030. }
  8031. }
  8032. },
  8033. // Iterate each other layer except buildin layer
  8034. eachOtherLayer: function (cb, context) {
  8035. var zlevelList = this._zlevelList;
  8036. var layer;
  8037. var z;
  8038. var i;
  8039. for (i = 0; i < zlevelList.length; i++) {
  8040. z = zlevelList[i];
  8041. layer = this._layers[z];
  8042. if (!layer.__builtin__) {
  8043. cb.call(context, layer, z);
  8044. }
  8045. }
  8046. },
  8047. /**
  8048. * 获取所有已创建的层
  8049. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8050. */
  8051. getLayers: function () {
  8052. return this._layers;
  8053. },
  8054. _updateLayerStatus: function (list) {
  8055. this.eachBuiltinLayer(function (layer, z) {
  8056. layer.__dirty = layer.__used = false;
  8057. });
  8058. function updatePrevLayer(idx) {
  8059. if (prevLayer) {
  8060. if (prevLayer.__endIndex !== idx) {
  8061. prevLayer.__dirty = true;
  8062. }
  8063. prevLayer.__endIndex = idx;
  8064. }
  8065. }
  8066. if (this._singleCanvas) {
  8067. for (var i = 1; i < list.length; i++) {
  8068. var el = list[i];
  8069. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8070. this._needsManuallyCompositing = true;
  8071. break;
  8072. }
  8073. }
  8074. }
  8075. var prevLayer = null;
  8076. var incrementalLayerCount = 0;
  8077. for (var i = 0; i < list.length; i++) {
  8078. var el = list[i];
  8079. var zlevel = el.zlevel;
  8080. var layer;
  8081. // PENDING If change one incremental element style ?
  8082. // TODO Where there are non-incremental elements between incremental elements.
  8083. if (el.incremental) {
  8084. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8085. layer.incremental = true;
  8086. incrementalLayerCount = 1;
  8087. }
  8088. else {
  8089. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8090. }
  8091. if (!layer.__builtin__) {
  8092. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8093. }
  8094. if (layer !== prevLayer) {
  8095. layer.__used = true;
  8096. if (layer.__startIndex !== i) {
  8097. layer.__dirty = true;
  8098. }
  8099. layer.__startIndex = i;
  8100. if (!layer.incremental) {
  8101. layer.__drawIndex = i;
  8102. }
  8103. else {
  8104. // Mark layer draw index needs to update.
  8105. layer.__drawIndex = -1;
  8106. }
  8107. updatePrevLayer(i);
  8108. prevLayer = layer;
  8109. }
  8110. if (el.__dirty) {
  8111. layer.__dirty = true;
  8112. if (layer.incremental && layer.__drawIndex < 0) {
  8113. // Start draw from the first dirty element.
  8114. layer.__drawIndex = i;
  8115. }
  8116. }
  8117. }
  8118. updatePrevLayer(i);
  8119. this.eachBuiltinLayer(function (layer, z) {
  8120. // Used in last frame but not in this frame. Needs clear
  8121. if (!layer.__used && layer.getElementCount() > 0) {
  8122. layer.__dirty = true;
  8123. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8124. }
  8125. // For incremental layer. In case start index changed and no elements are dirty.
  8126. if (layer.__dirty && layer.__drawIndex < 0) {
  8127. layer.__drawIndex = layer.__startIndex;
  8128. }
  8129. });
  8130. },
  8131. /**
  8132. * 清除hover层外所有内容
  8133. */
  8134. clear: function () {
  8135. this.eachBuiltinLayer(this._clearLayer);
  8136. return this;
  8137. },
  8138. _clearLayer: function (layer) {
  8139. layer.clear();
  8140. },
  8141. setBackgroundColor: function (backgroundColor) {
  8142. this._backgroundColor = backgroundColor;
  8143. },
  8144. /**
  8145. * 修改指定zlevel的绘制参数
  8146. *
  8147. * @param {string} zlevel
  8148. * @param {Object} config 配置对象
  8149. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8150. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8151. * @param {number} [config.lastFrameAlpha=0.7]
  8152. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8153. */
  8154. configLayer: function (zlevel, config) {
  8155. if (config) {
  8156. var layerConfig = this._layerConfig;
  8157. if (!layerConfig[zlevel]) {
  8158. layerConfig[zlevel] = config;
  8159. }
  8160. else {
  8161. merge(layerConfig[zlevel], config, true);
  8162. }
  8163. for (var i = 0; i < this._zlevelList.length; i++) {
  8164. var _zlevel = this._zlevelList[i];
  8165. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8166. var layer = this._layers[_zlevel];
  8167. merge(layer, layerConfig[zlevel], true);
  8168. }
  8169. }
  8170. }
  8171. },
  8172. /**
  8173. * 删除指定层
  8174. * @param {number} zlevel 层所在的zlevel
  8175. */
  8176. delLayer: function (zlevel) {
  8177. var layers = this._layers;
  8178. var zlevelList = this._zlevelList;
  8179. var layer = layers[zlevel];
  8180. if (!layer) {
  8181. return;
  8182. }
  8183. layer.dom.parentNode.removeChild(layer.dom);
  8184. delete layers[zlevel];
  8185. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8186. },
  8187. /**
  8188. * 区域大小变化后重绘
  8189. */
  8190. resize: function (width, height) {
  8191. if (!this._domRoot.style) { // Maybe in node or worker
  8192. if (width == null || height == null) {
  8193. return;
  8194. }
  8195. this._width = width;
  8196. this._height = height;
  8197. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8198. }
  8199. else {
  8200. var domRoot = this._domRoot;
  8201. // FIXME Why ?
  8202. domRoot.style.display = 'none';
  8203. // Save input w/h
  8204. var opts = this._opts;
  8205. width != null && (opts.width = width);
  8206. height != null && (opts.height = height);
  8207. width = this._getSize(0);
  8208. height = this._getSize(1);
  8209. domRoot.style.display = '';
  8210. // 优化没有实际改变的resize
  8211. if (this._width != width || height != this._height) {
  8212. domRoot.style.width = width + 'px';
  8213. domRoot.style.height = height + 'px';
  8214. for (var id in this._layers) {
  8215. if (this._layers.hasOwnProperty(id)) {
  8216. this._layers[id].resize(width, height);
  8217. }
  8218. }
  8219. each$1(this._progressiveLayers, function (layer) {
  8220. layer.resize(width, height);
  8221. });
  8222. this.refresh(true);
  8223. }
  8224. this._width = width;
  8225. this._height = height;
  8226. }
  8227. return this;
  8228. },
  8229. /**
  8230. * 清除单独的一个层
  8231. * @param {number} zlevel
  8232. */
  8233. clearLayer: function (zlevel) {
  8234. var layer = this._layers[zlevel];
  8235. if (layer) {
  8236. layer.clear();
  8237. }
  8238. },
  8239. /**
  8240. * 释放
  8241. */
  8242. dispose: function () {
  8243. this.root.innerHTML = '';
  8244. this.root =
  8245. this.storage =
  8246. this._domRoot =
  8247. this._layers = null;
  8248. },
  8249. /**
  8250. * Get canvas which has all thing rendered
  8251. * @param {Object} opts
  8252. * @param {string} [opts.backgroundColor]
  8253. * @param {number} [opts.pixelRatio]
  8254. */
  8255. getRenderedCanvas: function (opts) {
  8256. opts = opts || {};
  8257. if (this._singleCanvas && !this._compositeManually) {
  8258. return this._layers[CANVAS_ZLEVEL].dom;
  8259. }
  8260. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8261. imageLayer.initContext();
  8262. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8263. if (opts.pixelRatio <= this.dpr) {
  8264. this.refresh();
  8265. var width = imageLayer.dom.width;
  8266. var height = imageLayer.dom.height;
  8267. var ctx = imageLayer.ctx;
  8268. this.eachLayer(function (layer) {
  8269. if (layer.__builtin__) {
  8270. ctx.drawImage(layer.dom, 0, 0, width, height);
  8271. }
  8272. else if (layer.renderToCanvas) {
  8273. imageLayer.ctx.save();
  8274. layer.renderToCanvas(imageLayer.ctx);
  8275. imageLayer.ctx.restore();
  8276. }
  8277. });
  8278. }
  8279. else {
  8280. // PENDING, echarts-gl and incremental rendering.
  8281. var scope = {};
  8282. var displayList = this.storage.getDisplayList(true);
  8283. for (var i = 0; i < displayList.length; i++) {
  8284. var el = displayList[i];
  8285. this._doPaintEl(el, imageLayer, true, scope);
  8286. }
  8287. }
  8288. return imageLayer.dom;
  8289. },
  8290. /**
  8291. * 获取绘图区域宽度
  8292. */
  8293. getWidth: function () {
  8294. return this._width;
  8295. },
  8296. /**
  8297. * 获取绘图区域高度
  8298. */
  8299. getHeight: function () {
  8300. return this._height;
  8301. },
  8302. _getSize: function (whIdx) {
  8303. var opts = this._opts;
  8304. var wh = ['width', 'height'][whIdx];
  8305. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8306. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8307. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8308. if (opts[wh] != null && opts[wh] !== 'auto') {
  8309. return parseFloat(opts[wh]);
  8310. }
  8311. var root = this.root;
  8312. // IE8 does not support getComputedStyle, but it use VML.
  8313. var stl = document.defaultView.getComputedStyle(root);
  8314. return (
  8315. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8316. - (parseInt10(stl[plt]) || 0)
  8317. - (parseInt10(stl[prb]) || 0)
  8318. ) | 0;
  8319. },
  8320. pathToImage: function (path, dpr) {
  8321. dpr = dpr || this.dpr;
  8322. var canvas = document.createElement('canvas');
  8323. var ctx = canvas.getContext('2d');
  8324. var rect = path.getBoundingRect();
  8325. var style = path.style;
  8326. var shadowBlurSize = style.shadowBlur * dpr;
  8327. var shadowOffsetX = style.shadowOffsetX * dpr;
  8328. var shadowOffsetY = style.shadowOffsetY * dpr;
  8329. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8330. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8331. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8332. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8333. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8334. var width = rect.width + leftMargin + rightMargin;
  8335. var height = rect.height + topMargin + bottomMargin;
  8336. canvas.width = width * dpr;
  8337. canvas.height = height * dpr;
  8338. ctx.scale(dpr, dpr);
  8339. ctx.clearRect(0, 0, width, height);
  8340. ctx.dpr = dpr;
  8341. var pathTransform = {
  8342. position: path.position,
  8343. rotation: path.rotation,
  8344. scale: path.scale
  8345. };
  8346. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8347. path.rotation = 0;
  8348. path.scale = [1, 1];
  8349. path.updateTransform();
  8350. if (path) {
  8351. path.brush(ctx);
  8352. }
  8353. var ImageShape = ZImage;
  8354. var imgShape = new ImageShape({
  8355. style: {
  8356. x: 0,
  8357. y: 0,
  8358. image: canvas
  8359. }
  8360. });
  8361. if (pathTransform.position != null) {
  8362. imgShape.position = path.position = pathTransform.position;
  8363. }
  8364. if (pathTransform.rotation != null) {
  8365. imgShape.rotation = path.rotation = pathTransform.rotation;
  8366. }
  8367. if (pathTransform.scale != null) {
  8368. imgShape.scale = path.scale = pathTransform.scale;
  8369. }
  8370. return imgShape;
  8371. }
  8372. };
  8373. /**
  8374. * 事件辅助类
  8375. * @module zrender/core/event
  8376. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8377. */
  8378. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8379. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8380. function getBoundingClientRect(el) {
  8381. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8382. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8383. }
  8384. // `calculate` is optional, default false
  8385. function clientToLocal(el, e, out, calculate) {
  8386. out = out || {};
  8387. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8388. // to the padding edge of the target element. The only browser using this convention
  8389. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8390. // not support the properties.
  8391. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8392. // In zr painter.dom, padding edge equals to border edge.
  8393. // FIXME
  8394. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8395. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8396. // is too complex. So css-transfrom dont support in this case temporarily.
  8397. if (calculate || !env$1.canvasSupported) {
  8398. defaultGetZrXY(el, e, out);
  8399. }
  8400. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8401. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8402. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8403. // zoom-factor, overflow / opacity layers, transforms ...)
  8404. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8405. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8406. // BTW3, In ff, offsetX/offsetY is always 0.
  8407. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8408. out.zrX = e.layerX;
  8409. out.zrY = e.layerY;
  8410. }
  8411. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8412. else if (e.offsetX != null) {
  8413. out.zrX = e.offsetX;
  8414. out.zrY = e.offsetY;
  8415. }
  8416. // For some other device, e.g., IOS safari.
  8417. else {
  8418. defaultGetZrXY(el, e, out);
  8419. }
  8420. return out;
  8421. }
  8422. function defaultGetZrXY(el, e, out) {
  8423. // This well-known method below does not support css transform.
  8424. var box = getBoundingClientRect(el);
  8425. out.zrX = e.clientX - box.left;
  8426. out.zrY = e.clientY - box.top;
  8427. }
  8428. /**
  8429. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8430. * `calculate` is optional, default false.
  8431. */
  8432. function normalizeEvent(el, e, calculate) {
  8433. e = e || window.event;
  8434. if (e.zrX != null) {
  8435. return e;
  8436. }
  8437. var eventType = e.type;
  8438. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8439. if (!isTouch) {
  8440. clientToLocal(el, e, e, calculate);
  8441. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8442. }
  8443. else {
  8444. var touch = eventType != 'touchend'
  8445. ? e.targetTouches[0]
  8446. : e.changedTouches[0];
  8447. touch && clientToLocal(el, touch, e, calculate);
  8448. }
  8449. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8450. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8451. // If e.which has been defined, if may be readonly,
  8452. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8453. var button = e.button;
  8454. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8455. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8456. }
  8457. return e;
  8458. }
  8459. /**
  8460. * @param {HTMLElement} el
  8461. * @param {string} name
  8462. * @param {Function} handler
  8463. */
  8464. function addEventListener(el, name, handler) {
  8465. if (isDomLevel2) {
  8466. // Reproduct the console warning:
  8467. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  8468. // Consider marking event handler as 'passive' to make the page more responsive.
  8469. // Just set console log level: verbose in chrome dev tool.
  8470. // then the warning log will be printed when addEventListener called.
  8471. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  8472. // We have not yet found a neat way to using passive. Because in zrender the dom event
  8473. // listener delegate all of the upper events of element. Some of those events need
  8474. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  8475. // Before passive can be adopted, these issues should be considered:
  8476. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  8477. // passive or not.
  8478. // (2) How to tread that some zrender event listener is passive, and some is not. If
  8479. // we use other way but not preventDefault of mousewheel and touchmove, browser
  8480. // compatibility should be handled.
  8481. // var opts = (env.passiveSupported && name === 'mousewheel')
  8482. // ? {passive: true}
  8483. // // By default, the third param of el.addEventListener is `capture: false`.
  8484. // : void 0;
  8485. // el.addEventListener(name, handler /* , opts */);
  8486. el.addEventListener(name, handler);
  8487. }
  8488. else {
  8489. el.attachEvent('on' + name, handler);
  8490. }
  8491. }
  8492. function removeEventListener(el, name, handler) {
  8493. if (isDomLevel2) {
  8494. el.removeEventListener(name, handler);
  8495. }
  8496. else {
  8497. el.detachEvent('on' + name, handler);
  8498. }
  8499. }
  8500. /**
  8501. * preventDefault and stopPropagation.
  8502. * Notice: do not do that in zrender. Upper application
  8503. * do that if necessary.
  8504. *
  8505. * @memberOf module:zrender/core/event
  8506. * @method
  8507. * @param {Event} e : event对象
  8508. */
  8509. var stop = isDomLevel2
  8510. ? function (e) {
  8511. e.preventDefault();
  8512. e.stopPropagation();
  8513. e.cancelBubble = true;
  8514. }
  8515. : function (e) {
  8516. e.returnValue = false;
  8517. e.cancelBubble = true;
  8518. };
  8519. function notLeftMouse(e) {
  8520. // If e.which is undefined, considered as left mouse event.
  8521. return e.which > 1;
  8522. }
  8523. /**
  8524. * 动画主类, 调度和管理所有动画控制器
  8525. *
  8526. * @module zrender/animation/Animation
  8527. * @author pissang(https://github.com/pissang)
  8528. */
  8529. // TODO Additive animation
  8530. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8531. // https://developer.apple.com/videos/wwdc2014/#236
  8532. /**
  8533. * @typedef {Object} IZRenderStage
  8534. * @property {Function} update
  8535. */
  8536. /**
  8537. * @alias module:zrender/animation/Animation
  8538. * @constructor
  8539. * @param {Object} [options]
  8540. * @param {Function} [options.onframe]
  8541. * @param {IZRenderStage} [options.stage]
  8542. * @example
  8543. * var animation = new Animation();
  8544. * var obj = {
  8545. * x: 100,
  8546. * y: 100
  8547. * };
  8548. * animation.animate(node.position)
  8549. * .when(1000, {
  8550. * x: 500,
  8551. * y: 500
  8552. * })
  8553. * .when(2000, {
  8554. * x: 100,
  8555. * y: 100
  8556. * })
  8557. * .start('spline');
  8558. */
  8559. var Animation = function (options) {
  8560. options = options || {};
  8561. this.stage = options.stage || {};
  8562. this.onframe = options.onframe || function() {};
  8563. // private properties
  8564. this._clips = [];
  8565. this._running = false;
  8566. this._time;
  8567. this._pausedTime;
  8568. this._pauseStart;
  8569. this._paused = false;
  8570. Eventful.call(this);
  8571. };
  8572. Animation.prototype = {
  8573. constructor: Animation,
  8574. /**
  8575. * 添加 clip
  8576. * @param {module:zrender/animation/Clip} clip
  8577. */
  8578. addClip: function (clip) {
  8579. this._clips.push(clip);
  8580. },
  8581. /**
  8582. * 添加 animator
  8583. * @param {module:zrender/animation/Animator} animator
  8584. */
  8585. addAnimator: function (animator) {
  8586. animator.animation = this;
  8587. var clips = animator.getClips();
  8588. for (var i = 0; i < clips.length; i++) {
  8589. this.addClip(clips[i]);
  8590. }
  8591. },
  8592. /**
  8593. * 删除动画片段
  8594. * @param {module:zrender/animation/Clip} clip
  8595. */
  8596. removeClip: function(clip) {
  8597. var idx = indexOf(this._clips, clip);
  8598. if (idx >= 0) {
  8599. this._clips.splice(idx, 1);
  8600. }
  8601. },
  8602. /**
  8603. * 删除动画片段
  8604. * @param {module:zrender/animation/Animator} animator
  8605. */
  8606. removeAnimator: function (animator) {
  8607. var clips = animator.getClips();
  8608. for (var i = 0; i < clips.length; i++) {
  8609. this.removeClip(clips[i]);
  8610. }
  8611. animator.animation = null;
  8612. },
  8613. _update: function() {
  8614. var time = new Date().getTime() - this._pausedTime;
  8615. var delta = time - this._time;
  8616. var clips = this._clips;
  8617. var len = clips.length;
  8618. var deferredEvents = [];
  8619. var deferredClips = [];
  8620. for (var i = 0; i < len; i++) {
  8621. var clip = clips[i];
  8622. var e = clip.step(time, delta);
  8623. // Throw out the events need to be called after
  8624. // stage.update, like destroy
  8625. if (e) {
  8626. deferredEvents.push(e);
  8627. deferredClips.push(clip);
  8628. }
  8629. }
  8630. // Remove the finished clip
  8631. for (var i = 0; i < len;) {
  8632. if (clips[i]._needsRemove) {
  8633. clips[i] = clips[len - 1];
  8634. clips.pop();
  8635. len--;
  8636. }
  8637. else {
  8638. i++;
  8639. }
  8640. }
  8641. len = deferredEvents.length;
  8642. for (var i = 0; i < len; i++) {
  8643. deferredClips[i].fire(deferredEvents[i]);
  8644. }
  8645. this._time = time;
  8646. this.onframe(delta);
  8647. // 'frame' should be triggered before stage, because upper application
  8648. // depends on the sequence (e.g., echarts-stream and finish
  8649. // event judge)
  8650. this.trigger('frame', delta);
  8651. if (this.stage.update) {
  8652. this.stage.update();
  8653. }
  8654. },
  8655. _startLoop: function () {
  8656. var self = this;
  8657. this._running = true;
  8658. function step() {
  8659. if (self._running) {
  8660. requestAnimationFrame(step);
  8661. !self._paused && self._update();
  8662. }
  8663. }
  8664. requestAnimationFrame(step);
  8665. },
  8666. /**
  8667. * Start animation.
  8668. */
  8669. start: function () {
  8670. this._time = new Date().getTime();
  8671. this._pausedTime = 0;
  8672. this._startLoop();
  8673. },
  8674. /**
  8675. * Stop animation.
  8676. */
  8677. stop: function () {
  8678. this._running = false;
  8679. },
  8680. /**
  8681. * Pause animation.
  8682. */
  8683. pause: function () {
  8684. if (!this._paused) {
  8685. this._pauseStart = new Date().getTime();
  8686. this._paused = true;
  8687. }
  8688. },
  8689. /**
  8690. * Resume animation.
  8691. */
  8692. resume: function () {
  8693. if (this._paused) {
  8694. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8695. this._paused = false;
  8696. }
  8697. },
  8698. /**
  8699. * Clear animation.
  8700. */
  8701. clear: function () {
  8702. this._clips = [];
  8703. },
  8704. /**
  8705. * Whether animation finished.
  8706. */
  8707. isFinished: function () {
  8708. return !this._clips.length;
  8709. },
  8710. /**
  8711. * Creat animator for a target, whose props can be animated.
  8712. *
  8713. * @param {Object} target
  8714. * @param {Object} options
  8715. * @param {boolean} [options.loop=false] Whether loop animation.
  8716. * @param {Function} [options.getter=null] Get value from target.
  8717. * @param {Function} [options.setter=null] Set value to target.
  8718. * @return {module:zrender/animation/Animation~Animator}
  8719. */
  8720. // TODO Gap
  8721. animate: function (target, options) {
  8722. options = options || {};
  8723. var animator = new Animator(
  8724. target,
  8725. options.loop,
  8726. options.getter,
  8727. options.setter
  8728. );
  8729. this.addAnimator(animator);
  8730. return animator;
  8731. }
  8732. };
  8733. mixin(Animation, Eventful);
  8734. /**
  8735. * Only implements needed gestures for mobile.
  8736. */
  8737. var GestureMgr = function () {
  8738. /**
  8739. * @private
  8740. * @type {Array.<Object>}
  8741. */
  8742. this._track = [];
  8743. };
  8744. GestureMgr.prototype = {
  8745. constructor: GestureMgr,
  8746. recognize: function (event, target, root) {
  8747. this._doTrack(event, target, root);
  8748. return this._recognize(event);
  8749. },
  8750. clear: function () {
  8751. this._track.length = 0;
  8752. return this;
  8753. },
  8754. _doTrack: function (event, target, root) {
  8755. var touches = event.touches;
  8756. if (!touches) {
  8757. return;
  8758. }
  8759. var trackItem = {
  8760. points: [],
  8761. touches: [],
  8762. target: target,
  8763. event: event
  8764. };
  8765. for (var i = 0, len = touches.length; i < len; i++) {
  8766. var touch = touches[i];
  8767. var pos = clientToLocal(root, touch, {});
  8768. trackItem.points.push([pos.zrX, pos.zrY]);
  8769. trackItem.touches.push(touch);
  8770. }
  8771. this._track.push(trackItem);
  8772. },
  8773. _recognize: function (event) {
  8774. for (var eventName in recognizers) {
  8775. if (recognizers.hasOwnProperty(eventName)) {
  8776. var gestureInfo = recognizers[eventName](this._track, event);
  8777. if (gestureInfo) {
  8778. return gestureInfo;
  8779. }
  8780. }
  8781. }
  8782. }
  8783. };
  8784. function dist$1(pointPair) {
  8785. var dx = pointPair[1][0] - pointPair[0][0];
  8786. var dy = pointPair[1][1] - pointPair[0][1];
  8787. return Math.sqrt(dx * dx + dy * dy);
  8788. }
  8789. function center(pointPair) {
  8790. return [
  8791. (pointPair[0][0] + pointPair[1][0]) / 2,
  8792. (pointPair[0][1] + pointPair[1][1]) / 2
  8793. ];
  8794. }
  8795. var recognizers = {
  8796. pinch: function (track, event) {
  8797. var trackLen = track.length;
  8798. if (!trackLen) {
  8799. return;
  8800. }
  8801. var pinchEnd = (track[trackLen - 1] || {}).points;
  8802. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8803. if (pinchPre
  8804. && pinchPre.length > 1
  8805. && pinchEnd
  8806. && pinchEnd.length > 1
  8807. ) {
  8808. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8809. !isFinite(pinchScale) && (pinchScale = 1);
  8810. event.pinchScale = pinchScale;
  8811. var pinchCenter = center(pinchEnd);
  8812. event.pinchX = pinchCenter[0];
  8813. event.pinchY = pinchCenter[1];
  8814. return {
  8815. type: 'pinch',
  8816. target: track[0].target,
  8817. event: event
  8818. };
  8819. }
  8820. }
  8821. // Only pinch currently.
  8822. };
  8823. var TOUCH_CLICK_DELAY = 300;
  8824. var mouseHandlerNames = [
  8825. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8826. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8827. ];
  8828. var touchHandlerNames = [
  8829. 'touchstart', 'touchend', 'touchmove'
  8830. ];
  8831. var pointerEventNames = {
  8832. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8833. };
  8834. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8835. var nm = name.replace('mouse', 'pointer');
  8836. return pointerEventNames[nm] ? nm : name;
  8837. });
  8838. function eventNameFix(name) {
  8839. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8840. }
  8841. function processGesture(proxy, event, stage) {
  8842. var gestureMgr = proxy._gestureMgr;
  8843. stage === 'start' && gestureMgr.clear();
  8844. var gestureInfo = gestureMgr.recognize(
  8845. event,
  8846. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8847. proxy.dom
  8848. );
  8849. stage === 'end' && gestureMgr.clear();
  8850. // Do not do any preventDefault here. Upper application do that if necessary.
  8851. if (gestureInfo) {
  8852. var type = gestureInfo.type;
  8853. event.gestureEvent = type;
  8854. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8855. }
  8856. }
  8857. // function onMSGestureChange(proxy, event) {
  8858. // if (event.translationX || event.translationY) {
  8859. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8860. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8861. // }
  8862. // if (event.scale !== 1) {
  8863. // event.pinchX = event.offsetX;
  8864. // event.pinchY = event.offsetY;
  8865. // event.pinchScale = event.scale;
  8866. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8867. // }
  8868. // }
  8869. /**
  8870. * Prevent mouse event from being dispatched after Touch Events action
  8871. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8872. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8873. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8874. * Result: Blocking Mouse Events for 700ms.
  8875. */
  8876. function setTouchTimer(instance) {
  8877. instance._touching = true;
  8878. clearTimeout(instance._touchTimer);
  8879. instance._touchTimer = setTimeout(function () {
  8880. instance._touching = false;
  8881. }, 700);
  8882. }
  8883. var domHandlers = {
  8884. /**
  8885. * Mouse move handler
  8886. * @inner
  8887. * @param {Event} event
  8888. */
  8889. mousemove: function (event) {
  8890. event = normalizeEvent(this.dom, event);
  8891. this.trigger('mousemove', event);
  8892. },
  8893. /**
  8894. * Mouse out handler
  8895. * @inner
  8896. * @param {Event} event
  8897. */
  8898. mouseout: function (event) {
  8899. event = normalizeEvent(this.dom, event);
  8900. var element = event.toElement || event.relatedTarget;
  8901. if (element != this.dom) {
  8902. while (element && element.nodeType != 9) {
  8903. // 忽略包含在root中的dom引起的mouseOut
  8904. if (element === this.dom) {
  8905. return;
  8906. }
  8907. element = element.parentNode;
  8908. }
  8909. }
  8910. this.trigger('mouseout', event);
  8911. },
  8912. /**
  8913. * Touch开始响应函数
  8914. * @inner
  8915. * @param {Event} event
  8916. */
  8917. touchstart: function (event) {
  8918. // Default mouse behaviour should not be disabled here.
  8919. // For example, page may needs to be slided.
  8920. event = normalizeEvent(this.dom, event);
  8921. // Mark touch, which is useful in distinguish touch and
  8922. // mouse event in upper applicatoin.
  8923. event.zrByTouch = true;
  8924. this._lastTouchMoment = new Date();
  8925. processGesture(this, event, 'start');
  8926. // In touch device, trigger `mousemove`(`mouseover`) should
  8927. // be triggered, and must before `mousedown` triggered.
  8928. domHandlers.mousemove.call(this, event);
  8929. domHandlers.mousedown.call(this, event);
  8930. setTouchTimer(this);
  8931. },
  8932. /**
  8933. * Touch移动响应函数
  8934. * @inner
  8935. * @param {Event} event
  8936. */
  8937. touchmove: function (event) {
  8938. event = normalizeEvent(this.dom, event);
  8939. // Mark touch, which is useful in distinguish touch and
  8940. // mouse event in upper applicatoin.
  8941. event.zrByTouch = true;
  8942. processGesture(this, event, 'change');
  8943. // Mouse move should always be triggered no matter whether
  8944. // there is gestrue event, because mouse move and pinch may
  8945. // be used at the same time.
  8946. domHandlers.mousemove.call(this, event);
  8947. setTouchTimer(this);
  8948. },
  8949. /**
  8950. * Touch结束响应函数
  8951. * @inner
  8952. * @param {Event} event
  8953. */
  8954. touchend: function (event) {
  8955. event = normalizeEvent(this.dom, event);
  8956. // Mark touch, which is useful in distinguish touch and
  8957. // mouse event in upper applicatoin.
  8958. event.zrByTouch = true;
  8959. processGesture(this, event, 'end');
  8960. domHandlers.mouseup.call(this, event);
  8961. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8962. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8963. // we can conveniently implement "hover style" in both PC and touch device just
  8964. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8965. // to remove "hover style" on an element, without any additional code for
  8966. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8967. // style" will remain for user view)
  8968. // click event should always be triggered no matter whether
  8969. // there is gestrue event. System click can not be prevented.
  8970. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8971. domHandlers.click.call(this, event);
  8972. }
  8973. setTouchTimer(this);
  8974. },
  8975. pointerdown: function (event) {
  8976. domHandlers.mousedown.call(this, event);
  8977. // if (useMSGuesture(this, event)) {
  8978. // this._msGesture.addPointer(event.pointerId);
  8979. // }
  8980. },
  8981. pointermove: function (event) {
  8982. // FIXME
  8983. // pointermove is so sensitive that it always triggered when
  8984. // tap(click) on touch screen, which affect some judgement in
  8985. // upper application. So, we dont support mousemove on MS touch
  8986. // device yet.
  8987. if (!isPointerFromTouch(event)) {
  8988. domHandlers.mousemove.call(this, event);
  8989. }
  8990. },
  8991. pointerup: function (event) {
  8992. domHandlers.mouseup.call(this, event);
  8993. },
  8994. pointerout: function (event) {
  8995. // pointerout will be triggered when tap on touch screen
  8996. // (IE11+/Edge on MS Surface) after click event triggered,
  8997. // which is inconsistent with the mousout behavior we defined
  8998. // in touchend. So we unify them.
  8999. // (check domHandlers.touchend for detailed explanation)
  9000. if (!isPointerFromTouch(event)) {
  9001. domHandlers.mouseout.call(this, event);
  9002. }
  9003. }
  9004. };
  9005. function isPointerFromTouch(event) {
  9006. var pointerType = event.pointerType;
  9007. return pointerType === 'pen' || pointerType === 'touch';
  9008. }
  9009. // function useMSGuesture(handlerProxy, event) {
  9010. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9011. // }
  9012. // Common handlers
  9013. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9014. domHandlers[name] = function (event) {
  9015. event = normalizeEvent(this.dom, event);
  9016. this.trigger(name, event);
  9017. };
  9018. });
  9019. /**
  9020. * 为控制类实例初始化dom 事件处理函数
  9021. *
  9022. * @inner
  9023. * @param {module:zrender/Handler} instance 控制类实例
  9024. */
  9025. function initDomHandler(instance) {
  9026. each$1(touchHandlerNames, function (name) {
  9027. instance._handlers[name] = bind(domHandlers[name], instance);
  9028. });
  9029. each$1(pointerHandlerNames, function (name) {
  9030. instance._handlers[name] = bind(domHandlers[name], instance);
  9031. });
  9032. each$1(mouseHandlerNames, function (name) {
  9033. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  9034. });
  9035. function makeMouseHandler(fn, instance) {
  9036. return function () {
  9037. if (instance._touching) {
  9038. return;
  9039. }
  9040. return fn.apply(instance, arguments);
  9041. };
  9042. }
  9043. }
  9044. function HandlerDomProxy(dom) {
  9045. Eventful.call(this);
  9046. this.dom = dom;
  9047. /**
  9048. * @private
  9049. * @type {boolean}
  9050. */
  9051. this._touching = false;
  9052. /**
  9053. * @private
  9054. * @type {number}
  9055. */
  9056. this._touchTimer;
  9057. /**
  9058. * @private
  9059. * @type {module:zrender/core/GestureMgr}
  9060. */
  9061. this._gestureMgr = new GestureMgr();
  9062. this._handlers = {};
  9063. initDomHandler(this);
  9064. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9065. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9066. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9067. // at the same time.
  9068. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9069. // screen, which do not occurs in pointer event.
  9070. // So we use pointer event to both detect touch gesture and mouse behavior.
  9071. mountHandlers(pointerHandlerNames, this);
  9072. // FIXME
  9073. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9074. // which does not prevent defuault behavior occasionally (which may cause view port
  9075. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9076. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9077. // touch screen. And we only support click behavior on MS touch screen now.
  9078. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9079. // We dont support touch on IE on win7.
  9080. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9081. // if (typeof MSGesture === 'function') {
  9082. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9083. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9084. // }
  9085. }
  9086. else {
  9087. if (env$1.touchEventsSupported) {
  9088. mountHandlers(touchHandlerNames, this);
  9089. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9090. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9091. }
  9092. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9093. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9094. // mouse event can not be handle in those devices.
  9095. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9096. // mouseevent after touch event triggered, see `setTouchTimer`.
  9097. mountHandlers(mouseHandlerNames, this);
  9098. }
  9099. function mountHandlers(handlerNames, instance) {
  9100. each$1(handlerNames, function (name) {
  9101. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9102. }, instance);
  9103. }
  9104. }
  9105. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9106. handlerDomProxyProto.dispose = function () {
  9107. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9108. for (var i = 0; i < handlerNames.length; i++) {
  9109. var name = handlerNames[i];
  9110. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9111. }
  9112. };
  9113. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9114. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9115. };
  9116. mixin(HandlerDomProxy, Eventful);
  9117. /*!
  9118. * ZRender, a high performance 2d drawing library.
  9119. *
  9120. * Copyright (c) 2013, Baidu Inc.
  9121. * All rights reserved.
  9122. *
  9123. * LICENSE
  9124. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9125. */
  9126. var useVML = !env$1.canvasSupported;
  9127. var painterCtors = {
  9128. canvas: Painter
  9129. };
  9130. var instances$1 = {}; // ZRender实例map索引
  9131. /**
  9132. * @type {string}
  9133. */
  9134. var version$1 = '4.0.4';
  9135. /**
  9136. * Initializing a zrender instance
  9137. * @param {HTMLElement} dom
  9138. * @param {Object} opts
  9139. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9140. * @param {number} [opts.devicePixelRatio]
  9141. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9142. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9143. * @return {module:zrender/ZRender}
  9144. */
  9145. function init$1(dom, opts) {
  9146. var zr = new ZRender(guid(), dom, opts);
  9147. instances$1[zr.id] = zr;
  9148. return zr;
  9149. }
  9150. /**
  9151. * Dispose zrender instance
  9152. * @param {module:zrender/ZRender} zr
  9153. */
  9154. function dispose$1(zr) {
  9155. if (zr) {
  9156. zr.dispose();
  9157. }
  9158. else {
  9159. for (var key in instances$1) {
  9160. if (instances$1.hasOwnProperty(key)) {
  9161. instances$1[key].dispose();
  9162. }
  9163. }
  9164. instances$1 = {};
  9165. }
  9166. return this;
  9167. }
  9168. /**
  9169. * Get zrender instance by id
  9170. * @param {string} id zrender instance id
  9171. * @return {module:zrender/ZRender}
  9172. */
  9173. function getInstance(id) {
  9174. return instances$1[id];
  9175. }
  9176. function registerPainter(name, Ctor) {
  9177. painterCtors[name] = Ctor;
  9178. }
  9179. function delInstance(id) {
  9180. delete instances$1[id];
  9181. }
  9182. /**
  9183. * @module zrender/ZRender
  9184. */
  9185. /**
  9186. * @constructor
  9187. * @alias module:zrender/ZRender
  9188. * @param {string} id
  9189. * @param {HTMLElement} dom
  9190. * @param {Object} opts
  9191. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9192. * @param {number} [opts.devicePixelRatio]
  9193. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9194. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9195. */
  9196. var ZRender = function (id, dom, opts) {
  9197. opts = opts || {};
  9198. /**
  9199. * @type {HTMLDomElement}
  9200. */
  9201. this.dom = dom;
  9202. /**
  9203. * @type {string}
  9204. */
  9205. this.id = id;
  9206. var self = this;
  9207. var storage = new Storage();
  9208. var rendererType = opts.renderer;
  9209. // TODO WebGL
  9210. if (useVML) {
  9211. if (!painterCtors.vml) {
  9212. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9213. }
  9214. rendererType = 'vml';
  9215. }
  9216. else if (!rendererType || !painterCtors[rendererType]) {
  9217. rendererType = 'canvas';
  9218. }
  9219. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9220. this.storage = storage;
  9221. this.painter = painter;
  9222. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9223. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9224. /**
  9225. * @type {module:zrender/animation/Animation}
  9226. */
  9227. this.animation = new Animation({
  9228. stage: {
  9229. update: bind(this.flush, this)
  9230. }
  9231. });
  9232. this.animation.start();
  9233. /**
  9234. * @type {boolean}
  9235. * @private
  9236. */
  9237. this._needsRefresh;
  9238. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9239. // FIXME 有点ugly
  9240. var oldDelFromStorage = storage.delFromStorage;
  9241. var oldAddToStorage = storage.addToStorage;
  9242. storage.delFromStorage = function (el) {
  9243. oldDelFromStorage.call(storage, el);
  9244. el && el.removeSelfFromZr(self);
  9245. };
  9246. storage.addToStorage = function (el) {
  9247. oldAddToStorage.call(storage, el);
  9248. el.addSelfToZr(self);
  9249. };
  9250. };
  9251. ZRender.prototype = {
  9252. constructor: ZRender,
  9253. /**
  9254. * 获取实例唯一标识
  9255. * @return {string}
  9256. */
  9257. getId: function () {
  9258. return this.id;
  9259. },
  9260. /**
  9261. * 添加元素
  9262. * @param {module:zrender/Element} el
  9263. */
  9264. add: function (el) {
  9265. this.storage.addRoot(el);
  9266. this._needsRefresh = true;
  9267. },
  9268. /**
  9269. * 删除元素
  9270. * @param {module:zrender/Element} el
  9271. */
  9272. remove: function (el) {
  9273. this.storage.delRoot(el);
  9274. this._needsRefresh = true;
  9275. },
  9276. /**
  9277. * Change configuration of layer
  9278. * @param {string} zLevel
  9279. * @param {Object} config
  9280. * @param {string} [config.clearColor=0] Clear color
  9281. * @param {string} [config.motionBlur=false] If enable motion blur
  9282. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9283. */
  9284. configLayer: function (zLevel, config) {
  9285. if (this.painter.configLayer) {
  9286. this.painter.configLayer(zLevel, config);
  9287. }
  9288. this._needsRefresh = true;
  9289. },
  9290. /**
  9291. * Set background color
  9292. * @param {string} backgroundColor
  9293. */
  9294. setBackgroundColor: function (backgroundColor) {
  9295. if (this.painter.setBackgroundColor) {
  9296. this.painter.setBackgroundColor(backgroundColor);
  9297. }
  9298. this._needsRefresh = true;
  9299. },
  9300. /**
  9301. * Repaint the canvas immediately
  9302. */
  9303. refreshImmediately: function () {
  9304. // var start = new Date();
  9305. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9306. // Or it will cause zrender refreshes again and again.
  9307. this._needsRefresh = false;
  9308. this.painter.refresh();
  9309. /**
  9310. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9311. */
  9312. this._needsRefresh = false;
  9313. // var end = new Date();
  9314. // var log = document.getElementById('log');
  9315. // if (log) {
  9316. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9317. // }
  9318. },
  9319. /**
  9320. * Mark and repaint the canvas in the next frame of browser
  9321. */
  9322. refresh: function() {
  9323. this._needsRefresh = true;
  9324. },
  9325. /**
  9326. * Perform all refresh
  9327. */
  9328. flush: function () {
  9329. var triggerRendered;
  9330. if (this._needsRefresh) {
  9331. triggerRendered = true;
  9332. this.refreshImmediately();
  9333. }
  9334. if (this._needsRefreshHover) {
  9335. triggerRendered = true;
  9336. this.refreshHoverImmediately();
  9337. }
  9338. triggerRendered && this.trigger('rendered');
  9339. },
  9340. /**
  9341. * Add element to hover layer
  9342. * @param {module:zrender/Element} el
  9343. * @param {Object} style
  9344. */
  9345. addHover: function (el, style) {
  9346. if (this.painter.addHover) {
  9347. this.painter.addHover(el, style);
  9348. this.refreshHover();
  9349. }
  9350. },
  9351. /**
  9352. * Add element from hover layer
  9353. * @param {module:zrender/Element} el
  9354. */
  9355. removeHover: function (el) {
  9356. if (this.painter.removeHover) {
  9357. this.painter.removeHover(el);
  9358. this.refreshHover();
  9359. }
  9360. },
  9361. /**
  9362. * Clear all hover elements in hover layer
  9363. * @param {module:zrender/Element} el
  9364. */
  9365. clearHover: function () {
  9366. if (this.painter.clearHover) {
  9367. this.painter.clearHover();
  9368. this.refreshHover();
  9369. }
  9370. },
  9371. /**
  9372. * Refresh hover in next frame
  9373. */
  9374. refreshHover: function () {
  9375. this._needsRefreshHover = true;
  9376. },
  9377. /**
  9378. * Refresh hover immediately
  9379. */
  9380. refreshHoverImmediately: function () {
  9381. this._needsRefreshHover = false;
  9382. this.painter.refreshHover && this.painter.refreshHover();
  9383. },
  9384. /**
  9385. * Resize the canvas.
  9386. * Should be invoked when container size is changed
  9387. * @param {Object} [opts]
  9388. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9389. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9390. */
  9391. resize: function(opts) {
  9392. opts = opts || {};
  9393. this.painter.resize(opts.width, opts.height);
  9394. this.handler.resize();
  9395. },
  9396. /**
  9397. * Stop and clear all animation immediately
  9398. */
  9399. clearAnimation: function () {
  9400. this.animation.clear();
  9401. },
  9402. /**
  9403. * Get container width
  9404. */
  9405. getWidth: function() {
  9406. return this.painter.getWidth();
  9407. },
  9408. /**
  9409. * Get container height
  9410. */
  9411. getHeight: function() {
  9412. return this.painter.getHeight();
  9413. },
  9414. /**
  9415. * Export the canvas as Base64 URL
  9416. * @param {string} type
  9417. * @param {string} [backgroundColor='#fff']
  9418. * @return {string} Base64 URL
  9419. */
  9420. // toDataURL: function(type, backgroundColor) {
  9421. // return this.painter.getRenderedCanvas({
  9422. // backgroundColor: backgroundColor
  9423. // }).toDataURL(type);
  9424. // },
  9425. /**
  9426. * Converting a path to image.
  9427. * It has much better performance of drawing image rather than drawing a vector path.
  9428. * @param {module:zrender/graphic/Path} e
  9429. * @param {number} width
  9430. * @param {number} height
  9431. */
  9432. pathToImage: function(e, dpr) {
  9433. return this.painter.pathToImage(e, dpr);
  9434. },
  9435. /**
  9436. * Set default cursor
  9437. * @param {string} [cursorStyle='default'] 例如 crosshair
  9438. */
  9439. setCursorStyle: function (cursorStyle) {
  9440. this.handler.setCursorStyle(cursorStyle);
  9441. },
  9442. /**
  9443. * Find hovered element
  9444. * @param {number} x
  9445. * @param {number} y
  9446. * @return {Object} {target, topTarget}
  9447. */
  9448. findHover: function (x, y) {
  9449. return this.handler.findHover(x, y);
  9450. },
  9451. /**
  9452. * Bind event
  9453. *
  9454. * @param {string} eventName Event name
  9455. * @param {Function} eventHandler Handler function
  9456. * @param {Object} [context] Context object
  9457. */
  9458. on: function(eventName, eventHandler, context) {
  9459. this.handler.on(eventName, eventHandler, context);
  9460. },
  9461. /**
  9462. * Unbind event
  9463. * @param {string} eventName Event name
  9464. * @param {Function} [eventHandler] Handler function
  9465. */
  9466. off: function(eventName, eventHandler) {
  9467. this.handler.off(eventName, eventHandler);
  9468. },
  9469. /**
  9470. * Trigger event manually
  9471. *
  9472. * @param {string} eventName Event name
  9473. * @param {event=} event Event object
  9474. */
  9475. trigger: function (eventName, event) {
  9476. this.handler.trigger(eventName, event);
  9477. },
  9478. /**
  9479. * Clear all objects and the canvas.
  9480. */
  9481. clear: function () {
  9482. this.storage.delRoot();
  9483. this.painter.clear();
  9484. },
  9485. /**
  9486. * Dispose self.
  9487. */
  9488. dispose: function () {
  9489. this.animation.stop();
  9490. this.clear();
  9491. this.storage.dispose();
  9492. this.painter.dispose();
  9493. this.handler.dispose();
  9494. this.animation =
  9495. this.storage =
  9496. this.painter =
  9497. this.handler = null;
  9498. delInstance(this.id);
  9499. }
  9500. };
  9501. var zrender = (Object.freeze || Object)({
  9502. version: version$1,
  9503. init: init$1,
  9504. dispose: dispose$1,
  9505. getInstance: getInstance,
  9506. registerPainter: registerPainter
  9507. });
  9508. /*
  9509. * Licensed to the Apache Software Foundation (ASF) under one
  9510. * or more contributor license agreements. See the NOTICE file
  9511. * distributed with this work for additional information
  9512. * regarding copyright ownership. The ASF licenses this file
  9513. * to you under the Apache License, Version 2.0 (the
  9514. * "License"); you may not use this file except in compliance
  9515. * with the License. You may obtain a copy of the License at
  9516. *
  9517. * http://www.apache.org/licenses/LICENSE-2.0
  9518. *
  9519. * Unless required by applicable law or agreed to in writing,
  9520. * software distributed under the License is distributed on an
  9521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9522. * KIND, either express or implied. See the License for the
  9523. * specific language governing permissions and limitations
  9524. * under the License.
  9525. */
  9526. var each$2 = each$1;
  9527. var isObject$2 = isObject$1;
  9528. var isArray$1 = isArray;
  9529. /**
  9530. * Make the name displayable. But we should
  9531. * make sure it is not duplicated with user
  9532. * specified name, so use '\0';
  9533. */
  9534. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9535. /**
  9536. * If value is not array, then translate it to array.
  9537. * @param {*} value
  9538. * @return {Array} [value] or value
  9539. */
  9540. function normalizeToArray(value) {
  9541. return value instanceof Array
  9542. ? value
  9543. : value == null
  9544. ? []
  9545. : [value];
  9546. }
  9547. /**
  9548. * Sync default option between normal and emphasis like `position` and `show`
  9549. * In case some one will write code like
  9550. * label: {
  9551. * show: false,
  9552. * position: 'outside',
  9553. * fontSize: 18
  9554. * },
  9555. * emphasis: {
  9556. * label: { show: true }
  9557. * }
  9558. * @param {Object} opt
  9559. * @param {string} key
  9560. * @param {Array.<string>} subOpts
  9561. */
  9562. function defaultEmphasis(opt, key, subOpts) {
  9563. // Caution: performance sensitive.
  9564. if (opt) {
  9565. opt[key] = opt[key] || {};
  9566. opt.emphasis = opt.emphasis || {};
  9567. opt.emphasis[key] = opt.emphasis[key] || {};
  9568. // Default emphasis option from normal
  9569. for (var i = 0, len = subOpts.length; i < len; i++) {
  9570. var subOptName = subOpts[i];
  9571. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9572. && opt[key].hasOwnProperty(subOptName)
  9573. ) {
  9574. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9575. }
  9576. }
  9577. }
  9578. }
  9579. var TEXT_STYLE_OPTIONS = [
  9580. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9581. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9582. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9583. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9584. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9585. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9586. ];
  9587. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9588. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9589. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9590. // // FIXME: deprecated, check and remove it.
  9591. // 'textStyle'
  9592. // ]);
  9593. /**
  9594. * The method do not ensure performance.
  9595. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9596. * This helper method retieves value from data.
  9597. * @param {string|number|Date|Array|Object} dataItem
  9598. * @return {number|string|Date|Array.<number|string|Date>}
  9599. */
  9600. function getDataItemValue(dataItem) {
  9601. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9602. ? dataItem.value : dataItem;
  9603. }
  9604. /**
  9605. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9606. * This helper method determine if dataItem has extra option besides value
  9607. * @param {string|number|Date|Array|Object} dataItem
  9608. */
  9609. function isDataItemOption(dataItem) {
  9610. return isObject$2(dataItem)
  9611. && !(dataItem instanceof Array);
  9612. // // markLine data can be array
  9613. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9614. }
  9615. /**
  9616. * Mapping to exists for merge.
  9617. *
  9618. * @public
  9619. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9620. * @param {Object|Array.<Object>} newCptOptions
  9621. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9622. * index of which is the same as exists.
  9623. */
  9624. function mappingToExists(exists, newCptOptions) {
  9625. // Mapping by the order by original option (but not order of
  9626. // new option) in merge mode. Because we should ensure
  9627. // some specified index (like xAxisIndex) is consistent with
  9628. // original option, which is easy to understand, espatially in
  9629. // media query. And in most case, merge option is used to
  9630. // update partial option but not be expected to change order.
  9631. newCptOptions = (newCptOptions || []).slice();
  9632. var result = map(exists || [], function (obj, index) {
  9633. return {exist: obj};
  9634. });
  9635. // Mapping by id or name if specified.
  9636. each$2(newCptOptions, function (cptOption, index) {
  9637. if (!isObject$2(cptOption)) {
  9638. return;
  9639. }
  9640. // id has highest priority.
  9641. for (var i = 0; i < result.length; i++) {
  9642. if (!result[i].option // Consider name: two map to one.
  9643. && cptOption.id != null
  9644. && result[i].exist.id === cptOption.id + ''
  9645. ) {
  9646. result[i].option = cptOption;
  9647. newCptOptions[index] = null;
  9648. return;
  9649. }
  9650. }
  9651. for (var i = 0; i < result.length; i++) {
  9652. var exist = result[i].exist;
  9653. if (!result[i].option // Consider name: two map to one.
  9654. // Can not match when both ids exist but different.
  9655. && (exist.id == null || cptOption.id == null)
  9656. && cptOption.name != null
  9657. && !isIdInner(cptOption)
  9658. && !isIdInner(exist)
  9659. && exist.name === cptOption.name + ''
  9660. ) {
  9661. result[i].option = cptOption;
  9662. newCptOptions[index] = null;
  9663. return;
  9664. }
  9665. }
  9666. });
  9667. // Otherwise mapping by index.
  9668. each$2(newCptOptions, function (cptOption, index) {
  9669. if (!isObject$2(cptOption)) {
  9670. return;
  9671. }
  9672. var i = 0;
  9673. for (; i < result.length; i++) {
  9674. var exist = result[i].exist;
  9675. if (!result[i].option
  9676. // Existing model that already has id should be able to
  9677. // mapped to (because after mapping performed model may
  9678. // be assigned with a id, whish should not affect next
  9679. // mapping), except those has inner id.
  9680. && !isIdInner(exist)
  9681. // Caution:
  9682. // Do not overwrite id. But name can be overwritten,
  9683. // because axis use name as 'show label text'.
  9684. // 'exist' always has id and name and we dont
  9685. // need to check it.
  9686. && cptOption.id == null
  9687. ) {
  9688. result[i].option = cptOption;
  9689. break;
  9690. }
  9691. }
  9692. if (i >= result.length) {
  9693. result.push({option: cptOption});
  9694. }
  9695. });
  9696. return result;
  9697. }
  9698. /**
  9699. * Make id and name for mapping result (result of mappingToExists)
  9700. * into `keyInfo` field.
  9701. *
  9702. * @public
  9703. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9704. * which order is the same as exists.
  9705. * @return {Array.<Object>} The input.
  9706. */
  9707. function makeIdAndName(mapResult) {
  9708. // We use this id to hash component models and view instances
  9709. // in echarts. id can be specified by user, or auto generated.
  9710. // The id generation rule ensures new view instance are able
  9711. // to mapped to old instance when setOption are called in
  9712. // no-merge mode. So we generate model id by name and plus
  9713. // type in view id.
  9714. // name can be duplicated among components, which is convenient
  9715. // to specify multi components (like series) by one name.
  9716. // Ensure that each id is distinct.
  9717. var idMap = createHashMap();
  9718. each$2(mapResult, function (item, index) {
  9719. var existCpt = item.exist;
  9720. existCpt && idMap.set(existCpt.id, item);
  9721. });
  9722. each$2(mapResult, function (item, index) {
  9723. var opt = item.option;
  9724. assert$1(
  9725. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9726. 'id duplicates: ' + (opt && opt.id)
  9727. );
  9728. opt && opt.id != null && idMap.set(opt.id, item);
  9729. !item.keyInfo && (item.keyInfo = {});
  9730. });
  9731. // Make name and id.
  9732. each$2(mapResult, function (item, index) {
  9733. var existCpt = item.exist;
  9734. var opt = item.option;
  9735. var keyInfo = item.keyInfo;
  9736. if (!isObject$2(opt)) {
  9737. return;
  9738. }
  9739. // name can be overwitten. Consider case: axis.name = '20km'.
  9740. // But id generated by name will not be changed, which affect
  9741. // only in that case: setOption with 'not merge mode' and view
  9742. // instance will be recreated, which can be accepted.
  9743. keyInfo.name = opt.name != null
  9744. ? opt.name + ''
  9745. : existCpt
  9746. ? existCpt.name
  9747. // Avoid diffferent series has the same name,
  9748. // because name may be used like in color pallet.
  9749. : DUMMY_COMPONENT_NAME_PREFIX + index;
  9750. if (existCpt) {
  9751. keyInfo.id = existCpt.id;
  9752. }
  9753. else if (opt.id != null) {
  9754. keyInfo.id = opt.id + '';
  9755. }
  9756. else {
  9757. // Consider this situatoin:
  9758. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9759. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9760. // Series with the same name between optionA and optionB
  9761. // should be mapped.
  9762. var idNum = 0;
  9763. do {
  9764. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9765. }
  9766. while (idMap.get(keyInfo.id));
  9767. }
  9768. idMap.set(keyInfo.id, item);
  9769. });
  9770. }
  9771. function isNameSpecified(componentModel) {
  9772. var name = componentModel.name;
  9773. // Is specified when `indexOf` get -1 or > 0.
  9774. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  9775. }
  9776. /**
  9777. * @public
  9778. * @param {Object} cptOption
  9779. * @return {boolean}
  9780. */
  9781. function isIdInner(cptOption) {
  9782. return isObject$2(cptOption)
  9783. && cptOption.id
  9784. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  9785. }
  9786. /**
  9787. * A helper for removing duplicate items between batchA and batchB,
  9788. * and in themselves, and categorize by series.
  9789. *
  9790. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9791. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9792. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  9793. */
  9794. function compressBatches(batchA, batchB) {
  9795. var mapA = {};
  9796. var mapB = {};
  9797. makeMap(batchA || [], mapA);
  9798. makeMap(batchB || [], mapB, mapA);
  9799. return [mapToArray(mapA), mapToArray(mapB)];
  9800. function makeMap(sourceBatch, map$$1, otherMap) {
  9801. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  9802. var seriesId = sourceBatch[i].seriesId;
  9803. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  9804. var otherDataIndices = otherMap && otherMap[seriesId];
  9805. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  9806. var dataIndex = dataIndices[j];
  9807. if (otherDataIndices && otherDataIndices[dataIndex]) {
  9808. otherDataIndices[dataIndex] = null;
  9809. }
  9810. else {
  9811. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  9812. }
  9813. }
  9814. }
  9815. }
  9816. function mapToArray(map$$1, isData) {
  9817. var result = [];
  9818. for (var i in map$$1) {
  9819. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  9820. if (isData) {
  9821. result.push(+i);
  9822. }
  9823. else {
  9824. var dataIndices = mapToArray(map$$1[i], true);
  9825. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  9826. }
  9827. }
  9828. }
  9829. return result;
  9830. }
  9831. }
  9832. /**
  9833. * @param {module:echarts/data/List} data
  9834. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9835. * each of which can be Array or primary type.
  9836. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9837. */
  9838. function queryDataIndex(data, payload) {
  9839. if (payload.dataIndexInside != null) {
  9840. return payload.dataIndexInside;
  9841. }
  9842. else if (payload.dataIndex != null) {
  9843. return isArray(payload.dataIndex)
  9844. ? map(payload.dataIndex, function (value) {
  9845. return data.indexOfRawIndex(value);
  9846. })
  9847. : data.indexOfRawIndex(payload.dataIndex);
  9848. }
  9849. else if (payload.name != null) {
  9850. return isArray(payload.name)
  9851. ? map(payload.name, function (value) {
  9852. return data.indexOfName(value);
  9853. })
  9854. : data.indexOfName(payload.name);
  9855. }
  9856. }
  9857. /**
  9858. * Enable property storage to any host object.
  9859. * Notice: Serialization is not supported.
  9860. *
  9861. * For example:
  9862. * var inner = zrUitl.makeInner();
  9863. *
  9864. * function some1(hostObj) {
  9865. * inner(hostObj).someProperty = 1212;
  9866. * ...
  9867. * }
  9868. * function some2() {
  9869. * var fields = inner(this);
  9870. * fields.someProperty1 = 1212;
  9871. * fields.someProperty2 = 'xx';
  9872. * ...
  9873. * }
  9874. *
  9875. * @return {Function}
  9876. */
  9877. function makeInner() {
  9878. // Consider different scope by es module import.
  9879. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9880. return function (hostObj) {
  9881. return hostObj[key] || (hostObj[key] = {});
  9882. };
  9883. }
  9884. var innerUniqueIndex = 0;
  9885. /**
  9886. * @param {module:echarts/model/Global} ecModel
  9887. * @param {string|Object} finder
  9888. * If string, e.g., 'geo', means {geoIndex: 0}.
  9889. * If Object, could contain some of these properties below:
  9890. * {
  9891. * seriesIndex, seriesId, seriesName,
  9892. * geoIndex, geoId, geoName,
  9893. * bmapIndex, bmapId, bmapName,
  9894. * xAxisIndex, xAxisId, xAxisName,
  9895. * yAxisIndex, yAxisId, yAxisName,
  9896. * gridIndex, gridId, gridName,
  9897. * ... (can be extended)
  9898. * }
  9899. * Each properties can be number|string|Array.<number>|Array.<string>
  9900. * For example, a finder could be
  9901. * {
  9902. * seriesIndex: 3,
  9903. * geoId: ['aa', 'cc'],
  9904. * gridName: ['xx', 'rr']
  9905. * }
  9906. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9907. * If nothing or null/undefined specified, return nothing.
  9908. * @param {Object} [opt]
  9909. * @param {string} [opt.defaultMainType]
  9910. * @param {Array.<string>} [opt.includeMainTypes]
  9911. * @return {Object} result like:
  9912. * {
  9913. * seriesModels: [seriesModel1, seriesModel2],
  9914. * seriesModel: seriesModel1, // The first model
  9915. * geoModels: [geoModel1, geoModel2],
  9916. * geoModel: geoModel1, // The first model
  9917. * ...
  9918. * }
  9919. */
  9920. function parseFinder(ecModel, finder, opt) {
  9921. if (isString(finder)) {
  9922. var obj = {};
  9923. obj[finder + 'Index'] = 0;
  9924. finder = obj;
  9925. }
  9926. var defaultMainType = opt && opt.defaultMainType;
  9927. if (defaultMainType
  9928. && !has(finder, defaultMainType + 'Index')
  9929. && !has(finder, defaultMainType + 'Id')
  9930. && !has(finder, defaultMainType + 'Name')
  9931. ) {
  9932. finder[defaultMainType + 'Index'] = 0;
  9933. }
  9934. var result = {};
  9935. each$2(finder, function (value, key) {
  9936. var value = finder[key];
  9937. // Exclude 'dataIndex' and other illgal keys.
  9938. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9939. result[key] = value;
  9940. return;
  9941. }
  9942. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9943. var mainType = parsedKey[1];
  9944. var queryType = (parsedKey[2] || '').toLowerCase();
  9945. if (!mainType
  9946. || !queryType
  9947. || value == null
  9948. || (queryType === 'index' && value === 'none')
  9949. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9950. ) {
  9951. return;
  9952. }
  9953. var queryParam = {mainType: mainType};
  9954. if (queryType !== 'index' || value !== 'all') {
  9955. queryParam[queryType] = value;
  9956. }
  9957. var models = ecModel.queryComponents(queryParam);
  9958. result[mainType + 'Models'] = models;
  9959. result[mainType + 'Model'] = models[0];
  9960. });
  9961. return result;
  9962. }
  9963. function has(obj, prop) {
  9964. return obj && obj.hasOwnProperty(prop);
  9965. }
  9966. function setAttribute(dom, key, value) {
  9967. dom.setAttribute
  9968. ? dom.setAttribute(key, value)
  9969. : (dom[key] = value);
  9970. }
  9971. function getAttribute(dom, key) {
  9972. return dom.getAttribute
  9973. ? dom.getAttribute(key)
  9974. : dom[key];
  9975. }
  9976. /*
  9977. * Licensed to the Apache Software Foundation (ASF) under one
  9978. * or more contributor license agreements. See the NOTICE file
  9979. * distributed with this work for additional information
  9980. * regarding copyright ownership. The ASF licenses this file
  9981. * to you under the Apache License, Version 2.0 (the
  9982. * "License"); you may not use this file except in compliance
  9983. * with the License. You may obtain a copy of the License at
  9984. *
  9985. * http://www.apache.org/licenses/LICENSE-2.0
  9986. *
  9987. * Unless required by applicable law or agreed to in writing,
  9988. * software distributed under the License is distributed on an
  9989. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9990. * KIND, either express or implied. See the License for the
  9991. * specific language governing permissions and limitations
  9992. * under the License.
  9993. */
  9994. var TYPE_DELIMITER = '.';
  9995. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9996. /**
  9997. * Notice, parseClassType('') should returns {main: '', sub: ''}
  9998. * @public
  9999. */
  10000. function parseClassType$1(componentType) {
  10001. var ret = {main: '', sub: ''};
  10002. if (componentType) {
  10003. componentType = componentType.split(TYPE_DELIMITER);
  10004. ret.main = componentType[0] || '';
  10005. ret.sub = componentType[1] || '';
  10006. }
  10007. return ret;
  10008. }
  10009. /**
  10010. * @public
  10011. */
  10012. function checkClassType(componentType) {
  10013. assert$1(
  10014. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10015. 'componentType "' + componentType + '" illegal'
  10016. );
  10017. }
  10018. /**
  10019. * @public
  10020. */
  10021. function enableClassExtend(RootClass, mandatoryMethods) {
  10022. RootClass.$constructor = RootClass;
  10023. RootClass.extend = function (proto) {
  10024. if (__DEV__) {
  10025. each$1(mandatoryMethods, function (method) {
  10026. if (!proto[method]) {
  10027. console.warn(
  10028. 'Method `' + method + '` should be implemented'
  10029. + (proto.type ? ' in ' + proto.type : '') + '.'
  10030. );
  10031. }
  10032. });
  10033. }
  10034. var superClass = this;
  10035. var ExtendedClass = function () {
  10036. if (!proto.$constructor) {
  10037. superClass.apply(this, arguments);
  10038. }
  10039. else {
  10040. proto.$constructor.apply(this, arguments);
  10041. }
  10042. };
  10043. extend(ExtendedClass.prototype, proto);
  10044. ExtendedClass.extend = this.extend;
  10045. ExtendedClass.superCall = superCall;
  10046. ExtendedClass.superApply = superApply;
  10047. inherits(ExtendedClass, this);
  10048. ExtendedClass.superClass = superClass;
  10049. return ExtendedClass;
  10050. };
  10051. }
  10052. var classBase = 0;
  10053. /**
  10054. * Can not use instanceof, consider different scope by
  10055. * cross domain or es module import in ec extensions.
  10056. * Mount a method "isInstance()" to Clz.
  10057. */
  10058. function enableClassCheck(Clz) {
  10059. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10060. Clz.prototype[classAttr] = true;
  10061. if (__DEV__) {
  10062. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10063. }
  10064. Clz.isInstance = function (obj) {
  10065. return !!(obj && obj[classAttr]);
  10066. };
  10067. }
  10068. // superCall should have class info, which can not be fetch from 'this'.
  10069. // Consider this case:
  10070. // class A has method f,
  10071. // class B inherits class A, overrides method f, f call superApply('f'),
  10072. // class C inherits class B, do not overrides method f,
  10073. // then when method of class C is called, dead loop occured.
  10074. function superCall(context, methodName) {
  10075. var args = slice(arguments, 2);
  10076. return this.superClass.prototype[methodName].apply(context, args);
  10077. }
  10078. function superApply(context, methodName, args) {
  10079. return this.superClass.prototype[methodName].apply(context, args);
  10080. }
  10081. /**
  10082. * @param {Object} entity
  10083. * @param {Object} options
  10084. * @param {boolean} [options.registerWhenExtend]
  10085. * @public
  10086. */
  10087. function enableClassManagement(entity, options) {
  10088. options = options || {};
  10089. /**
  10090. * Component model classes
  10091. * key: componentType,
  10092. * value:
  10093. * componentClass, when componentType is 'xxx'
  10094. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10095. * @type {Object}
  10096. */
  10097. var storage = {};
  10098. entity.registerClass = function (Clazz, componentType) {
  10099. if (componentType) {
  10100. checkClassType(componentType);
  10101. componentType = parseClassType$1(componentType);
  10102. if (!componentType.sub) {
  10103. if (__DEV__) {
  10104. if (storage[componentType.main]) {
  10105. console.warn(componentType.main + ' exists.');
  10106. }
  10107. }
  10108. storage[componentType.main] = Clazz;
  10109. }
  10110. else if (componentType.sub !== IS_CONTAINER) {
  10111. var container = makeContainer(componentType);
  10112. container[componentType.sub] = Clazz;
  10113. }
  10114. }
  10115. return Clazz;
  10116. };
  10117. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10118. var Clazz = storage[componentMainType];
  10119. if (Clazz && Clazz[IS_CONTAINER]) {
  10120. Clazz = subType ? Clazz[subType] : null;
  10121. }
  10122. if (throwWhenNotFound && !Clazz) {
  10123. throw new Error(
  10124. !subType
  10125. ? componentMainType + '.' + 'type should be specified.'
  10126. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10127. );
  10128. }
  10129. return Clazz;
  10130. };
  10131. entity.getClassesByMainType = function (componentType) {
  10132. componentType = parseClassType$1(componentType);
  10133. var result = [];
  10134. var obj = storage[componentType.main];
  10135. if (obj && obj[IS_CONTAINER]) {
  10136. each$1(obj, function (o, type) {
  10137. type !== IS_CONTAINER && result.push(o);
  10138. });
  10139. }
  10140. else {
  10141. result.push(obj);
  10142. }
  10143. return result;
  10144. };
  10145. entity.hasClass = function (componentType) {
  10146. // Just consider componentType.main.
  10147. componentType = parseClassType$1(componentType);
  10148. return !!storage[componentType.main];
  10149. };
  10150. /**
  10151. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10152. */
  10153. entity.getAllClassMainTypes = function () {
  10154. var types = [];
  10155. each$1(storage, function (obj, type) {
  10156. types.push(type);
  10157. });
  10158. return types;
  10159. };
  10160. /**
  10161. * If a main type is container and has sub types
  10162. * @param {string} mainType
  10163. * @return {boolean}
  10164. */
  10165. entity.hasSubTypes = function (componentType) {
  10166. componentType = parseClassType$1(componentType);
  10167. var obj = storage[componentType.main];
  10168. return obj && obj[IS_CONTAINER];
  10169. };
  10170. entity.parseClassType = parseClassType$1;
  10171. function makeContainer(componentType) {
  10172. var container = storage[componentType.main];
  10173. if (!container || !container[IS_CONTAINER]) {
  10174. container = storage[componentType.main] = {};
  10175. container[IS_CONTAINER] = true;
  10176. }
  10177. return container;
  10178. }
  10179. if (options.registerWhenExtend) {
  10180. var originalExtend = entity.extend;
  10181. if (originalExtend) {
  10182. entity.extend = function (proto) {
  10183. var ExtendedClass = originalExtend.call(this, proto);
  10184. return entity.registerClass(ExtendedClass, proto.type);
  10185. };
  10186. }
  10187. }
  10188. return entity;
  10189. }
  10190. /**
  10191. * @param {string|Array.<string>} properties
  10192. */
  10193. /*
  10194. * Licensed to the Apache Software Foundation (ASF) under one
  10195. * or more contributor license agreements. See the NOTICE file
  10196. * distributed with this work for additional information
  10197. * regarding copyright ownership. The ASF licenses this file
  10198. * to you under the Apache License, Version 2.0 (the
  10199. * "License"); you may not use this file except in compliance
  10200. * with the License. You may obtain a copy of the License at
  10201. *
  10202. * http://www.apache.org/licenses/LICENSE-2.0
  10203. *
  10204. * Unless required by applicable law or agreed to in writing,
  10205. * software distributed under the License is distributed on an
  10206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10207. * KIND, either express or implied. See the License for the
  10208. * specific language governing permissions and limitations
  10209. * under the License.
  10210. */
  10211. // TODO Parse shadow style
  10212. // TODO Only shallow path support
  10213. var makeStyleMapper = function (properties) {
  10214. // Normalize
  10215. for (var i = 0; i < properties.length; i++) {
  10216. if (!properties[i][1]) {
  10217. properties[i][1] = properties[i][0];
  10218. }
  10219. }
  10220. return function (model, excludes, includes) {
  10221. var style = {};
  10222. for (var i = 0; i < properties.length; i++) {
  10223. var propName = properties[i][1];
  10224. if ((excludes && indexOf(excludes, propName) >= 0)
  10225. || (includes && indexOf(includes, propName) < 0)
  10226. ) {
  10227. continue;
  10228. }
  10229. var val = model.getShallow(propName);
  10230. if (val != null) {
  10231. style[properties[i][0]] = val;
  10232. }
  10233. }
  10234. return style;
  10235. };
  10236. };
  10237. /*
  10238. * Licensed to the Apache Software Foundation (ASF) under one
  10239. * or more contributor license agreements. See the NOTICE file
  10240. * distributed with this work for additional information
  10241. * regarding copyright ownership. The ASF licenses this file
  10242. * to you under the Apache License, Version 2.0 (the
  10243. * "License"); you may not use this file except in compliance
  10244. * with the License. You may obtain a copy of the License at
  10245. *
  10246. * http://www.apache.org/licenses/LICENSE-2.0
  10247. *
  10248. * Unless required by applicable law or agreed to in writing,
  10249. * software distributed under the License is distributed on an
  10250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10251. * KIND, either express or implied. See the License for the
  10252. * specific language governing permissions and limitations
  10253. * under the License.
  10254. */
  10255. var getLineStyle = makeStyleMapper(
  10256. [
  10257. ['lineWidth', 'width'],
  10258. ['stroke', 'color'],
  10259. ['opacity'],
  10260. ['shadowBlur'],
  10261. ['shadowOffsetX'],
  10262. ['shadowOffsetY'],
  10263. ['shadowColor']
  10264. ]
  10265. );
  10266. var lineStyleMixin = {
  10267. getLineStyle: function (excludes) {
  10268. var style = getLineStyle(this, excludes);
  10269. var lineDash = this.getLineDash(style.lineWidth);
  10270. lineDash && (style.lineDash = lineDash);
  10271. return style;
  10272. },
  10273. getLineDash: function (lineWidth) {
  10274. if (lineWidth == null) {
  10275. lineWidth = 1;
  10276. }
  10277. var lineType = this.get('type');
  10278. var dotSize = Math.max(lineWidth, 2);
  10279. var dashSize = lineWidth * 4;
  10280. return (lineType === 'solid' || lineType == null) ? null
  10281. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10282. }
  10283. };
  10284. /*
  10285. * Licensed to the Apache Software Foundation (ASF) under one
  10286. * or more contributor license agreements. See the NOTICE file
  10287. * distributed with this work for additional information
  10288. * regarding copyright ownership. The ASF licenses this file
  10289. * to you under the Apache License, Version 2.0 (the
  10290. * "License"); you may not use this file except in compliance
  10291. * with the License. You may obtain a copy of the License at
  10292. *
  10293. * http://www.apache.org/licenses/LICENSE-2.0
  10294. *
  10295. * Unless required by applicable law or agreed to in writing,
  10296. * software distributed under the License is distributed on an
  10297. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10298. * KIND, either express or implied. See the License for the
  10299. * specific language governing permissions and limitations
  10300. * under the License.
  10301. */
  10302. var getAreaStyle = makeStyleMapper(
  10303. [
  10304. ['fill', 'color'],
  10305. ['shadowBlur'],
  10306. ['shadowOffsetX'],
  10307. ['shadowOffsetY'],
  10308. ['opacity'],
  10309. ['shadowColor']
  10310. ]
  10311. );
  10312. var areaStyleMixin = {
  10313. getAreaStyle: function (excludes, includes) {
  10314. return getAreaStyle(this, excludes, includes);
  10315. }
  10316. };
  10317. /**
  10318. * 曲线辅助模块
  10319. * @module zrender/core/curve
  10320. * @author pissang(https://www.github.com/pissang)
  10321. */
  10322. var mathPow = Math.pow;
  10323. var mathSqrt$2 = Math.sqrt;
  10324. var EPSILON$1 = 1e-8;
  10325. var EPSILON_NUMERIC = 1e-4;
  10326. var THREE_SQRT = mathSqrt$2(3);
  10327. var ONE_THIRD = 1 / 3;
  10328. // 临时变量
  10329. var _v0 = create();
  10330. var _v1 = create();
  10331. var _v2 = create();
  10332. function isAroundZero(val) {
  10333. return val > -EPSILON$1 && val < EPSILON$1;
  10334. }
  10335. function isNotAroundZero$1(val) {
  10336. return val > EPSILON$1 || val < -EPSILON$1;
  10337. }
  10338. /**
  10339. * 计算三次贝塞尔值
  10340. * @memberOf module:zrender/core/curve
  10341. * @param {number} p0
  10342. * @param {number} p1
  10343. * @param {number} p2
  10344. * @param {number} p3
  10345. * @param {number} t
  10346. * @return {number}
  10347. */
  10348. function cubicAt(p0, p1, p2, p3, t) {
  10349. var onet = 1 - t;
  10350. return onet * onet * (onet * p0 + 3 * t * p1)
  10351. + t * t * (t * p3 + 3 * onet * p2);
  10352. }
  10353. /**
  10354. * 计算三次贝塞尔导数值
  10355. * @memberOf module:zrender/core/curve
  10356. * @param {number} p0
  10357. * @param {number} p1
  10358. * @param {number} p2
  10359. * @param {number} p3
  10360. * @param {number} t
  10361. * @return {number}
  10362. */
  10363. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10364. var onet = 1 - t;
  10365. return 3 * (
  10366. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10367. + (p3 - p2) * t * t
  10368. );
  10369. }
  10370. /**
  10371. * 计算三次贝塞尔方程根,使用盛金公式
  10372. * @memberOf module:zrender/core/curve
  10373. * @param {number} p0
  10374. * @param {number} p1
  10375. * @param {number} p2
  10376. * @param {number} p3
  10377. * @param {number} val
  10378. * @param {Array.<number>} roots
  10379. * @return {number} 有效根数目
  10380. */
  10381. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10382. // Evaluate roots of cubic functions
  10383. var a = p3 + 3 * (p1 - p2) - p0;
  10384. var b = 3 * (p2 - p1 * 2 + p0);
  10385. var c = 3 * (p1 - p0);
  10386. var d = p0 - val;
  10387. var A = b * b - 3 * a * c;
  10388. var B = b * c - 9 * a * d;
  10389. var C = c * c - 3 * b * d;
  10390. var n = 0;
  10391. if (isAroundZero(A) && isAroundZero(B)) {
  10392. if (isAroundZero(b)) {
  10393. roots[0] = 0;
  10394. }
  10395. else {
  10396. var t1 = -c / b; //t1, t2, t3, b is not zero
  10397. if (t1 >= 0 && t1 <= 1) {
  10398. roots[n++] = t1;
  10399. }
  10400. }
  10401. }
  10402. else {
  10403. var disc = B * B - 4 * A * C;
  10404. if (isAroundZero(disc)) {
  10405. var K = B / A;
  10406. var t1 = -b / a + K; // t1, a is not zero
  10407. var t2 = -K / 2; // t2, t3
  10408. if (t1 >= 0 && t1 <= 1) {
  10409. roots[n++] = t1;
  10410. }
  10411. if (t2 >= 0 && t2 <= 1) {
  10412. roots[n++] = t2;
  10413. }
  10414. }
  10415. else if (disc > 0) {
  10416. var discSqrt = mathSqrt$2(disc);
  10417. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10418. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10419. if (Y1 < 0) {
  10420. Y1 = -mathPow(-Y1, ONE_THIRD);
  10421. }
  10422. else {
  10423. Y1 = mathPow(Y1, ONE_THIRD);
  10424. }
  10425. if (Y2 < 0) {
  10426. Y2 = -mathPow(-Y2, ONE_THIRD);
  10427. }
  10428. else {
  10429. Y2 = mathPow(Y2, ONE_THIRD);
  10430. }
  10431. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10432. if (t1 >= 0 && t1 <= 1) {
  10433. roots[n++] = t1;
  10434. }
  10435. }
  10436. else {
  10437. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10438. var theta = Math.acos(T) / 3;
  10439. var ASqrt = mathSqrt$2(A);
  10440. var tmp = Math.cos(theta);
  10441. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10442. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10443. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10444. if (t1 >= 0 && t1 <= 1) {
  10445. roots[n++] = t1;
  10446. }
  10447. if (t2 >= 0 && t2 <= 1) {
  10448. roots[n++] = t2;
  10449. }
  10450. if (t3 >= 0 && t3 <= 1) {
  10451. roots[n++] = t3;
  10452. }
  10453. }
  10454. }
  10455. return n;
  10456. }
  10457. /**
  10458. * 计算三次贝塞尔方程极限值的位置
  10459. * @memberOf module:zrender/core/curve
  10460. * @param {number} p0
  10461. * @param {number} p1
  10462. * @param {number} p2
  10463. * @param {number} p3
  10464. * @param {Array.<number>} extrema
  10465. * @return {number} 有效数目
  10466. */
  10467. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10468. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10469. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10470. var c = 3 * p1 - 3 * p0;
  10471. var n = 0;
  10472. if (isAroundZero(a)) {
  10473. if (isNotAroundZero$1(b)) {
  10474. var t1 = -c / b;
  10475. if (t1 >= 0 && t1 <=1) {
  10476. extrema[n++] = t1;
  10477. }
  10478. }
  10479. }
  10480. else {
  10481. var disc = b * b - 4 * a * c;
  10482. if (isAroundZero(disc)) {
  10483. extrema[0] = -b / (2 * a);
  10484. }
  10485. else if (disc > 0) {
  10486. var discSqrt = mathSqrt$2(disc);
  10487. var t1 = (-b + discSqrt) / (2 * a);
  10488. var t2 = (-b - discSqrt) / (2 * a);
  10489. if (t1 >= 0 && t1 <= 1) {
  10490. extrema[n++] = t1;
  10491. }
  10492. if (t2 >= 0 && t2 <= 1) {
  10493. extrema[n++] = t2;
  10494. }
  10495. }
  10496. }
  10497. return n;
  10498. }
  10499. /**
  10500. * 细分三次贝塞尔曲线
  10501. * @memberOf module:zrender/core/curve
  10502. * @param {number} p0
  10503. * @param {number} p1
  10504. * @param {number} p2
  10505. * @param {number} p3
  10506. * @param {number} t
  10507. * @param {Array.<number>} out
  10508. */
  10509. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10510. var p01 = (p1 - p0) * t + p0;
  10511. var p12 = (p2 - p1) * t + p1;
  10512. var p23 = (p3 - p2) * t + p2;
  10513. var p012 = (p12 - p01) * t + p01;
  10514. var p123 = (p23 - p12) * t + p12;
  10515. var p0123 = (p123 - p012) * t + p012;
  10516. // Seg0
  10517. out[0] = p0;
  10518. out[1] = p01;
  10519. out[2] = p012;
  10520. out[3] = p0123;
  10521. // Seg1
  10522. out[4] = p0123;
  10523. out[5] = p123;
  10524. out[6] = p23;
  10525. out[7] = p3;
  10526. }
  10527. /**
  10528. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10529. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10530. * @param {number} x0
  10531. * @param {number} y0
  10532. * @param {number} x1
  10533. * @param {number} y1
  10534. * @param {number} x2
  10535. * @param {number} y2
  10536. * @param {number} x3
  10537. * @param {number} y3
  10538. * @param {number} x
  10539. * @param {number} y
  10540. * @param {Array.<number>} [out] 投射点
  10541. * @return {number}
  10542. */
  10543. function cubicProjectPoint(
  10544. x0, y0, x1, y1, x2, y2, x3, y3,
  10545. x, y, out
  10546. ) {
  10547. // http://pomax.github.io/bezierinfo/#projections
  10548. var t;
  10549. var interval = 0.005;
  10550. var d = Infinity;
  10551. var prev;
  10552. var next;
  10553. var d1;
  10554. var d2;
  10555. _v0[0] = x;
  10556. _v0[1] = y;
  10557. // 先粗略估计一下可能的最小距离的 t 值
  10558. // PENDING
  10559. for (var _t = 0; _t < 1; _t += 0.05) {
  10560. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10561. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10562. d1 = distSquare(_v0, _v1);
  10563. if (d1 < d) {
  10564. t = _t;
  10565. d = d1;
  10566. }
  10567. }
  10568. d = Infinity;
  10569. // At most 32 iteration
  10570. for (var i = 0; i < 32; i++) {
  10571. if (interval < EPSILON_NUMERIC) {
  10572. break;
  10573. }
  10574. prev = t - interval;
  10575. next = t + interval;
  10576. // t - interval
  10577. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10578. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10579. d1 = distSquare(_v1, _v0);
  10580. if (prev >= 0 && d1 < d) {
  10581. t = prev;
  10582. d = d1;
  10583. }
  10584. else {
  10585. // t + interval
  10586. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10587. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10588. d2 = distSquare(_v2, _v0);
  10589. if (next <= 1 && d2 < d) {
  10590. t = next;
  10591. d = d2;
  10592. }
  10593. else {
  10594. interval *= 0.5;
  10595. }
  10596. }
  10597. }
  10598. // t
  10599. if (out) {
  10600. out[0] = cubicAt(x0, x1, x2, x3, t);
  10601. out[1] = cubicAt(y0, y1, y2, y3, t);
  10602. }
  10603. // console.log(interval, i);
  10604. return mathSqrt$2(d);
  10605. }
  10606. /**
  10607. * 计算二次方贝塞尔值
  10608. * @param {number} p0
  10609. * @param {number} p1
  10610. * @param {number} p2
  10611. * @param {number} t
  10612. * @return {number}
  10613. */
  10614. function quadraticAt(p0, p1, p2, t) {
  10615. var onet = 1 - t;
  10616. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10617. }
  10618. /**
  10619. * 计算二次方贝塞尔导数值
  10620. * @param {number} p0
  10621. * @param {number} p1
  10622. * @param {number} p2
  10623. * @param {number} t
  10624. * @return {number}
  10625. */
  10626. function quadraticDerivativeAt(p0, p1, p2, t) {
  10627. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10628. }
  10629. /**
  10630. * 计算二次方贝塞尔方程根
  10631. * @param {number} p0
  10632. * @param {number} p1
  10633. * @param {number} p2
  10634. * @param {number} t
  10635. * @param {Array.<number>} roots
  10636. * @return {number} 有效根数目
  10637. */
  10638. function quadraticRootAt(p0, p1, p2, val, roots) {
  10639. var a = p0 - 2 * p1 + p2;
  10640. var b = 2 * (p1 - p0);
  10641. var c = p0 - val;
  10642. var n = 0;
  10643. if (isAroundZero(a)) {
  10644. if (isNotAroundZero$1(b)) {
  10645. var t1 = -c / b;
  10646. if (t1 >= 0 && t1 <= 1) {
  10647. roots[n++] = t1;
  10648. }
  10649. }
  10650. }
  10651. else {
  10652. var disc = b * b - 4 * a * c;
  10653. if (isAroundZero(disc)) {
  10654. var t1 = -b / (2 * a);
  10655. if (t1 >= 0 && t1 <= 1) {
  10656. roots[n++] = t1;
  10657. }
  10658. }
  10659. else if (disc > 0) {
  10660. var discSqrt = mathSqrt$2(disc);
  10661. var t1 = (-b + discSqrt) / (2 * a);
  10662. var t2 = (-b - discSqrt) / (2 * a);
  10663. if (t1 >= 0 && t1 <= 1) {
  10664. roots[n++] = t1;
  10665. }
  10666. if (t2 >= 0 && t2 <= 1) {
  10667. roots[n++] = t2;
  10668. }
  10669. }
  10670. }
  10671. return n;
  10672. }
  10673. /**
  10674. * 计算二次贝塞尔方程极限值
  10675. * @memberOf module:zrender/core/curve
  10676. * @param {number} p0
  10677. * @param {number} p1
  10678. * @param {number} p2
  10679. * @return {number}
  10680. */
  10681. function quadraticExtremum(p0, p1, p2) {
  10682. var divider = p0 + p2 - 2 * p1;
  10683. if (divider === 0) {
  10684. // p1 is center of p0 and p2
  10685. return 0.5;
  10686. }
  10687. else {
  10688. return (p0 - p1) / divider;
  10689. }
  10690. }
  10691. /**
  10692. * 细分二次贝塞尔曲线
  10693. * @memberOf module:zrender/core/curve
  10694. * @param {number} p0
  10695. * @param {number} p1
  10696. * @param {number} p2
  10697. * @param {number} t
  10698. * @param {Array.<number>} out
  10699. */
  10700. function quadraticSubdivide(p0, p1, p2, t, out) {
  10701. var p01 = (p1 - p0) * t + p0;
  10702. var p12 = (p2 - p1) * t + p1;
  10703. var p012 = (p12 - p01) * t + p01;
  10704. // Seg0
  10705. out[0] = p0;
  10706. out[1] = p01;
  10707. out[2] = p012;
  10708. // Seg1
  10709. out[3] = p012;
  10710. out[4] = p12;
  10711. out[5] = p2;
  10712. }
  10713. /**
  10714. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10715. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10716. * @param {number} x0
  10717. * @param {number} y0
  10718. * @param {number} x1
  10719. * @param {number} y1
  10720. * @param {number} x2
  10721. * @param {number} y2
  10722. * @param {number} x
  10723. * @param {number} y
  10724. * @param {Array.<number>} out 投射点
  10725. * @return {number}
  10726. */
  10727. function quadraticProjectPoint(
  10728. x0, y0, x1, y1, x2, y2,
  10729. x, y, out
  10730. ) {
  10731. // http://pomax.github.io/bezierinfo/#projections
  10732. var t;
  10733. var interval = 0.005;
  10734. var d = Infinity;
  10735. _v0[0] = x;
  10736. _v0[1] = y;
  10737. // 先粗略估计一下可能的最小距离的 t 值
  10738. // PENDING
  10739. for (var _t = 0; _t < 1; _t += 0.05) {
  10740. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10741. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10742. var d1 = distSquare(_v0, _v1);
  10743. if (d1 < d) {
  10744. t = _t;
  10745. d = d1;
  10746. }
  10747. }
  10748. d = Infinity;
  10749. // At most 32 iteration
  10750. for (var i = 0; i < 32; i++) {
  10751. if (interval < EPSILON_NUMERIC) {
  10752. break;
  10753. }
  10754. var prev = t - interval;
  10755. var next = t + interval;
  10756. // t - interval
  10757. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10758. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10759. var d1 = distSquare(_v1, _v0);
  10760. if (prev >= 0 && d1 < d) {
  10761. t = prev;
  10762. d = d1;
  10763. }
  10764. else {
  10765. // t + interval
  10766. _v2[0] = quadraticAt(x0, x1, x2, next);
  10767. _v2[1] = quadraticAt(y0, y1, y2, next);
  10768. var d2 = distSquare(_v2, _v0);
  10769. if (next <= 1 && d2 < d) {
  10770. t = next;
  10771. d = d2;
  10772. }
  10773. else {
  10774. interval *= 0.5;
  10775. }
  10776. }
  10777. }
  10778. // t
  10779. if (out) {
  10780. out[0] = quadraticAt(x0, x1, x2, t);
  10781. out[1] = quadraticAt(y0, y1, y2, t);
  10782. }
  10783. // console.log(interval, i);
  10784. return mathSqrt$2(d);
  10785. }
  10786. /**
  10787. * @author Yi Shen(https://github.com/pissang)
  10788. */
  10789. var mathMin$3 = Math.min;
  10790. var mathMax$3 = Math.max;
  10791. var mathSin$2 = Math.sin;
  10792. var mathCos$2 = Math.cos;
  10793. var PI2 = Math.PI * 2;
  10794. var start = create();
  10795. var end = create();
  10796. var extremity = create();
  10797. /**
  10798. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10799. * @module zrender/core/bbox
  10800. * @param {Array<Object>} points 顶点数组
  10801. * @param {number} min
  10802. * @param {number} max
  10803. */
  10804. function fromPoints(points, min$$1, max$$1) {
  10805. if (points.length === 0) {
  10806. return;
  10807. }
  10808. var p = points[0];
  10809. var left = p[0];
  10810. var right = p[0];
  10811. var top = p[1];
  10812. var bottom = p[1];
  10813. var i;
  10814. for (i = 1; i < points.length; i++) {
  10815. p = points[i];
  10816. left = mathMin$3(left, p[0]);
  10817. right = mathMax$3(right, p[0]);
  10818. top = mathMin$3(top, p[1]);
  10819. bottom = mathMax$3(bottom, p[1]);
  10820. }
  10821. min$$1[0] = left;
  10822. min$$1[1] = top;
  10823. max$$1[0] = right;
  10824. max$$1[1] = bottom;
  10825. }
  10826. /**
  10827. * @memberOf module:zrender/core/bbox
  10828. * @param {number} x0
  10829. * @param {number} y0
  10830. * @param {number} x1
  10831. * @param {number} y1
  10832. * @param {Array.<number>} min
  10833. * @param {Array.<number>} max
  10834. */
  10835. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10836. min$$1[0] = mathMin$3(x0, x1);
  10837. min$$1[1] = mathMin$3(y0, y1);
  10838. max$$1[0] = mathMax$3(x0, x1);
  10839. max$$1[1] = mathMax$3(y0, y1);
  10840. }
  10841. var xDim = [];
  10842. var yDim = [];
  10843. /**
  10844. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10845. * @memberOf module:zrender/core/bbox
  10846. * @param {number} x0
  10847. * @param {number} y0
  10848. * @param {number} x1
  10849. * @param {number} y1
  10850. * @param {number} x2
  10851. * @param {number} y2
  10852. * @param {number} x3
  10853. * @param {number} y3
  10854. * @param {Array.<number>} min
  10855. * @param {Array.<number>} max
  10856. */
  10857. function fromCubic(
  10858. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10859. ) {
  10860. var cubicExtrema$$1 = cubicExtrema;
  10861. var cubicAt$$1 = cubicAt;
  10862. var i;
  10863. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10864. min$$1[0] = Infinity;
  10865. min$$1[1] = Infinity;
  10866. max$$1[0] = -Infinity;
  10867. max$$1[1] = -Infinity;
  10868. for (i = 0; i < n; i++) {
  10869. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10870. min$$1[0] = mathMin$3(x, min$$1[0]);
  10871. max$$1[0] = mathMax$3(x, max$$1[0]);
  10872. }
  10873. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10874. for (i = 0; i < n; i++) {
  10875. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10876. min$$1[1] = mathMin$3(y, min$$1[1]);
  10877. max$$1[1] = mathMax$3(y, max$$1[1]);
  10878. }
  10879. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10880. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10881. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10882. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10883. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10884. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10885. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10886. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10887. }
  10888. /**
  10889. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10890. * @memberOf module:zrender/core/bbox
  10891. * @param {number} x0
  10892. * @param {number} y0
  10893. * @param {number} x1
  10894. * @param {number} y1
  10895. * @param {number} x2
  10896. * @param {number} y2
  10897. * @param {Array.<number>} min
  10898. * @param {Array.<number>} max
  10899. */
  10900. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10901. var quadraticExtremum$$1 = quadraticExtremum;
  10902. var quadraticAt$$1 = quadraticAt;
  10903. // Find extremities, where derivative in x dim or y dim is zero
  10904. var tx =
  10905. mathMax$3(
  10906. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10907. );
  10908. var ty =
  10909. mathMax$3(
  10910. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10911. );
  10912. var x = quadraticAt$$1(x0, x1, x2, tx);
  10913. var y = quadraticAt$$1(y0, y1, y2, ty);
  10914. min$$1[0] = mathMin$3(x0, x2, x);
  10915. min$$1[1] = mathMin$3(y0, y2, y);
  10916. max$$1[0] = mathMax$3(x0, x2, x);
  10917. max$$1[1] = mathMax$3(y0, y2, y);
  10918. }
  10919. /**
  10920. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10921. * @method
  10922. * @memberOf module:zrender/core/bbox
  10923. * @param {number} x
  10924. * @param {number} y
  10925. * @param {number} rx
  10926. * @param {number} ry
  10927. * @param {number} startAngle
  10928. * @param {number} endAngle
  10929. * @param {number} anticlockwise
  10930. * @param {Array.<number>} min
  10931. * @param {Array.<number>} max
  10932. */
  10933. function fromArc(
  10934. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10935. ) {
  10936. var vec2Min = min;
  10937. var vec2Max = max;
  10938. var diff = Math.abs(startAngle - endAngle);
  10939. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10940. // Is a circle
  10941. min$$1[0] = x - rx;
  10942. min$$1[1] = y - ry;
  10943. max$$1[0] = x + rx;
  10944. max$$1[1] = y + ry;
  10945. return;
  10946. }
  10947. start[0] = mathCos$2(startAngle) * rx + x;
  10948. start[1] = mathSin$2(startAngle) * ry + y;
  10949. end[0] = mathCos$2(endAngle) * rx + x;
  10950. end[1] = mathSin$2(endAngle) * ry + y;
  10951. vec2Min(min$$1, start, end);
  10952. vec2Max(max$$1, start, end);
  10953. // Thresh to [0, Math.PI * 2]
  10954. startAngle = startAngle % (PI2);
  10955. if (startAngle < 0) {
  10956. startAngle = startAngle + PI2;
  10957. }
  10958. endAngle = endAngle % (PI2);
  10959. if (endAngle < 0) {
  10960. endAngle = endAngle + PI2;
  10961. }
  10962. if (startAngle > endAngle && !anticlockwise) {
  10963. endAngle += PI2;
  10964. }
  10965. else if (startAngle < endAngle && anticlockwise) {
  10966. startAngle += PI2;
  10967. }
  10968. if (anticlockwise) {
  10969. var tmp = endAngle;
  10970. endAngle = startAngle;
  10971. startAngle = tmp;
  10972. }
  10973. // var number = 0;
  10974. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10975. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10976. if (angle > startAngle) {
  10977. extremity[0] = mathCos$2(angle) * rx + x;
  10978. extremity[1] = mathSin$2(angle) * ry + y;
  10979. vec2Min(min$$1, extremity, min$$1);
  10980. vec2Max(max$$1, extremity, max$$1);
  10981. }
  10982. }
  10983. }
  10984. /**
  10985. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10986. * 可以用于 isInsidePath 判断以及获取boundingRect
  10987. *
  10988. * @module zrender/core/PathProxy
  10989. * @author Yi Shen (http://www.github.com/pissang)
  10990. */
  10991. // TODO getTotalLength, getPointAtLength
  10992. var CMD = {
  10993. M: 1,
  10994. L: 2,
  10995. C: 3,
  10996. Q: 4,
  10997. A: 5,
  10998. Z: 6,
  10999. // Rect
  11000. R: 7
  11001. };
  11002. // var CMD_MEM_SIZE = {
  11003. // M: 3,
  11004. // L: 3,
  11005. // C: 7,
  11006. // Q: 5,
  11007. // A: 9,
  11008. // R: 5,
  11009. // Z: 1
  11010. // };
  11011. var min$1 = [];
  11012. var max$1 = [];
  11013. var min2 = [];
  11014. var max2 = [];
  11015. var mathMin$2 = Math.min;
  11016. var mathMax$2 = Math.max;
  11017. var mathCos$1 = Math.cos;
  11018. var mathSin$1 = Math.sin;
  11019. var mathSqrt$1 = Math.sqrt;
  11020. var mathAbs = Math.abs;
  11021. var hasTypedArray = typeof Float32Array != 'undefined';
  11022. /**
  11023. * @alias module:zrender/core/PathProxy
  11024. * @constructor
  11025. */
  11026. var PathProxy = function (notSaveData) {
  11027. this._saveData = !(notSaveData || false);
  11028. if (this._saveData) {
  11029. /**
  11030. * Path data. Stored as flat array
  11031. * @type {Array.<Object>}
  11032. */
  11033. this.data = [];
  11034. }
  11035. this._ctx = null;
  11036. };
  11037. /**
  11038. * 快速计算Path包围盒(并不是最小包围盒)
  11039. * @return {Object}
  11040. */
  11041. PathProxy.prototype = {
  11042. constructor: PathProxy,
  11043. _xi: 0,
  11044. _yi: 0,
  11045. _x0: 0,
  11046. _y0: 0,
  11047. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11048. _ux: 0,
  11049. _uy: 0,
  11050. _len: 0,
  11051. _lineDash: null,
  11052. _dashOffset: 0,
  11053. _dashIdx: 0,
  11054. _dashSum: 0,
  11055. /**
  11056. * @readOnly
  11057. */
  11058. setScale: function (sx, sy) {
  11059. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  11060. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  11061. },
  11062. getContext: function () {
  11063. return this._ctx;
  11064. },
  11065. /**
  11066. * @param {CanvasRenderingContext2D} ctx
  11067. * @return {module:zrender/core/PathProxy}
  11068. */
  11069. beginPath: function (ctx) {
  11070. this._ctx = ctx;
  11071. ctx && ctx.beginPath();
  11072. ctx && (this.dpr = ctx.dpr);
  11073. // Reset
  11074. if (this._saveData) {
  11075. this._len = 0;
  11076. }
  11077. if (this._lineDash) {
  11078. this._lineDash = null;
  11079. this._dashOffset = 0;
  11080. }
  11081. return this;
  11082. },
  11083. /**
  11084. * @param {number} x
  11085. * @param {number} y
  11086. * @return {module:zrender/core/PathProxy}
  11087. */
  11088. moveTo: function (x, y) {
  11089. this.addData(CMD.M, x, y);
  11090. this._ctx && this._ctx.moveTo(x, y);
  11091. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11092. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11093. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11094. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11095. this._x0 = x;
  11096. this._y0 = y;
  11097. this._xi = x;
  11098. this._yi = y;
  11099. return this;
  11100. },
  11101. /**
  11102. * @param {number} x
  11103. * @param {number} y
  11104. * @return {module:zrender/core/PathProxy}
  11105. */
  11106. lineTo: function (x, y) {
  11107. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11108. || mathAbs(y - this._yi) > this._uy
  11109. // Force draw the first segment
  11110. || this._len < 5;
  11111. this.addData(CMD.L, x, y);
  11112. if (this._ctx && exceedUnit) {
  11113. this._needsDash() ? this._dashedLineTo(x, y)
  11114. : this._ctx.lineTo(x, y);
  11115. }
  11116. if (exceedUnit) {
  11117. this._xi = x;
  11118. this._yi = y;
  11119. }
  11120. return this;
  11121. },
  11122. /**
  11123. * @param {number} x1
  11124. * @param {number} y1
  11125. * @param {number} x2
  11126. * @param {number} y2
  11127. * @param {number} x3
  11128. * @param {number} y3
  11129. * @return {module:zrender/core/PathProxy}
  11130. */
  11131. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11132. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11133. if (this._ctx) {
  11134. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11135. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11136. }
  11137. this._xi = x3;
  11138. this._yi = y3;
  11139. return this;
  11140. },
  11141. /**
  11142. * @param {number} x1
  11143. * @param {number} y1
  11144. * @param {number} x2
  11145. * @param {number} y2
  11146. * @return {module:zrender/core/PathProxy}
  11147. */
  11148. quadraticCurveTo: function (x1, y1, x2, y2) {
  11149. this.addData(CMD.Q, x1, y1, x2, y2);
  11150. if (this._ctx) {
  11151. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11152. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11153. }
  11154. this._xi = x2;
  11155. this._yi = y2;
  11156. return this;
  11157. },
  11158. /**
  11159. * @param {number} cx
  11160. * @param {number} cy
  11161. * @param {number} r
  11162. * @param {number} startAngle
  11163. * @param {number} endAngle
  11164. * @param {boolean} anticlockwise
  11165. * @return {module:zrender/core/PathProxy}
  11166. */
  11167. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11168. this.addData(
  11169. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11170. );
  11171. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11172. this._xi = mathCos$1(endAngle) * r + cx;
  11173. this._yi = mathSin$1(endAngle) * r + cx;
  11174. return this;
  11175. },
  11176. // TODO
  11177. arcTo: function (x1, y1, x2, y2, radius) {
  11178. if (this._ctx) {
  11179. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11180. }
  11181. return this;
  11182. },
  11183. // TODO
  11184. rect: function (x, y, w, h) {
  11185. this._ctx && this._ctx.rect(x, y, w, h);
  11186. this.addData(CMD.R, x, y, w, h);
  11187. return this;
  11188. },
  11189. /**
  11190. * @return {module:zrender/core/PathProxy}
  11191. */
  11192. closePath: function () {
  11193. this.addData(CMD.Z);
  11194. var ctx = this._ctx;
  11195. var x0 = this._x0;
  11196. var y0 = this._y0;
  11197. if (ctx) {
  11198. this._needsDash() && this._dashedLineTo(x0, y0);
  11199. ctx.closePath();
  11200. }
  11201. this._xi = x0;
  11202. this._yi = y0;
  11203. return this;
  11204. },
  11205. /**
  11206. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11207. * stroke 同样
  11208. * @param {CanvasRenderingContext2D} ctx
  11209. * @return {module:zrender/core/PathProxy}
  11210. */
  11211. fill: function (ctx) {
  11212. ctx && ctx.fill();
  11213. this.toStatic();
  11214. },
  11215. /**
  11216. * @param {CanvasRenderingContext2D} ctx
  11217. * @return {module:zrender/core/PathProxy}
  11218. */
  11219. stroke: function (ctx) {
  11220. ctx && ctx.stroke();
  11221. this.toStatic();
  11222. },
  11223. /**
  11224. * 必须在其它绘制命令前调用
  11225. * Must be invoked before all other path drawing methods
  11226. * @return {module:zrender/core/PathProxy}
  11227. */
  11228. setLineDash: function (lineDash) {
  11229. if (lineDash instanceof Array) {
  11230. this._lineDash = lineDash;
  11231. this._dashIdx = 0;
  11232. var lineDashSum = 0;
  11233. for (var i = 0; i < lineDash.length; i++) {
  11234. lineDashSum += lineDash[i];
  11235. }
  11236. this._dashSum = lineDashSum;
  11237. }
  11238. return this;
  11239. },
  11240. /**
  11241. * 必须在其它绘制命令前调用
  11242. * Must be invoked before all other path drawing methods
  11243. * @return {module:zrender/core/PathProxy}
  11244. */
  11245. setLineDashOffset: function (offset) {
  11246. this._dashOffset = offset;
  11247. return this;
  11248. },
  11249. /**
  11250. *
  11251. * @return {boolean}
  11252. */
  11253. len: function () {
  11254. return this._len;
  11255. },
  11256. /**
  11257. * 直接设置 Path 数据
  11258. */
  11259. setData: function (data) {
  11260. var len$$1 = data.length;
  11261. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11262. this.data = new Float32Array(len$$1);
  11263. }
  11264. for (var i = 0; i < len$$1; i++) {
  11265. this.data[i] = data[i];
  11266. }
  11267. this._len = len$$1;
  11268. },
  11269. /**
  11270. * 添加子路径
  11271. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11272. */
  11273. appendPath: function (path) {
  11274. if (!(path instanceof Array)) {
  11275. path = [path];
  11276. }
  11277. var len$$1 = path.length;
  11278. var appendSize = 0;
  11279. var offset = this._len;
  11280. for (var i = 0; i < len$$1; i++) {
  11281. appendSize += path[i].len();
  11282. }
  11283. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11284. this.data = new Float32Array(offset + appendSize);
  11285. }
  11286. for (var i = 0; i < len$$1; i++) {
  11287. var appendPathData = path[i].data;
  11288. for (var k = 0; k < appendPathData.length; k++) {
  11289. this.data[offset++] = appendPathData[k];
  11290. }
  11291. }
  11292. this._len = offset;
  11293. },
  11294. /**
  11295. * 填充 Path 数据。
  11296. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11297. */
  11298. addData: function (cmd) {
  11299. if (!this._saveData) {
  11300. return;
  11301. }
  11302. var data = this.data;
  11303. if (this._len + arguments.length > data.length) {
  11304. // 因为之前的数组已经转换成静态的 Float32Array
  11305. // 所以不够用时需要扩展一个新的动态数组
  11306. this._expandData();
  11307. data = this.data;
  11308. }
  11309. for (var i = 0; i < arguments.length; i++) {
  11310. data[this._len++] = arguments[i];
  11311. }
  11312. this._prevCmd = cmd;
  11313. },
  11314. _expandData: function () {
  11315. // Only if data is Float32Array
  11316. if (!(this.data instanceof Array)) {
  11317. var newData = [];
  11318. for (var i = 0; i < this._len; i++) {
  11319. newData[i] = this.data[i];
  11320. }
  11321. this.data = newData;
  11322. }
  11323. },
  11324. /**
  11325. * If needs js implemented dashed line
  11326. * @return {boolean}
  11327. * @private
  11328. */
  11329. _needsDash: function () {
  11330. return this._lineDash;
  11331. },
  11332. _dashedLineTo: function (x1, y1) {
  11333. var dashSum = this._dashSum;
  11334. var offset = this._dashOffset;
  11335. var lineDash = this._lineDash;
  11336. var ctx = this._ctx;
  11337. var x0 = this._xi;
  11338. var y0 = this._yi;
  11339. var dx = x1 - x0;
  11340. var dy = y1 - y0;
  11341. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11342. var x = x0;
  11343. var y = y0;
  11344. var dash;
  11345. var nDash = lineDash.length;
  11346. var idx;
  11347. dx /= dist$$1;
  11348. dy /= dist$$1;
  11349. if (offset < 0) {
  11350. // Convert to positive offset
  11351. offset = dashSum + offset;
  11352. }
  11353. offset %= dashSum;
  11354. x -= offset * dx;
  11355. y -= offset * dy;
  11356. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11357. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11358. idx = this._dashIdx;
  11359. dash = lineDash[idx];
  11360. x += dx * dash;
  11361. y += dy * dash;
  11362. this._dashIdx = (idx + 1) % nDash;
  11363. // Skip positive offset
  11364. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11365. continue;
  11366. }
  11367. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11368. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11369. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11370. );
  11371. }
  11372. // Offset for next lineTo
  11373. dx = x - x1;
  11374. dy = y - y1;
  11375. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11376. },
  11377. // Not accurate dashed line to
  11378. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11379. var dashSum = this._dashSum;
  11380. var offset = this._dashOffset;
  11381. var lineDash = this._lineDash;
  11382. var ctx = this._ctx;
  11383. var x0 = this._xi;
  11384. var y0 = this._yi;
  11385. var t;
  11386. var dx;
  11387. var dy;
  11388. var cubicAt$$1 = cubicAt;
  11389. var bezierLen = 0;
  11390. var idx = this._dashIdx;
  11391. var nDash = lineDash.length;
  11392. var x;
  11393. var y;
  11394. var tmpLen = 0;
  11395. if (offset < 0) {
  11396. // Convert to positive offset
  11397. offset = dashSum + offset;
  11398. }
  11399. offset %= dashSum;
  11400. // Bezier approx length
  11401. for (t = 0; t < 1; t += 0.1) {
  11402. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11403. - cubicAt$$1(x0, x1, x2, x3, t);
  11404. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11405. - cubicAt$$1(y0, y1, y2, y3, t);
  11406. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11407. }
  11408. // Find idx after add offset
  11409. for (; idx < nDash; idx++) {
  11410. tmpLen += lineDash[idx];
  11411. if (tmpLen > offset) {
  11412. break;
  11413. }
  11414. }
  11415. t = (tmpLen - offset) / bezierLen;
  11416. while (t <= 1) {
  11417. x = cubicAt$$1(x0, x1, x2, x3, t);
  11418. y = cubicAt$$1(y0, y1, y2, y3, t);
  11419. // Use line to approximate dashed bezier
  11420. // Bad result if dash is long
  11421. idx % 2 ? ctx.moveTo(x, y)
  11422. : ctx.lineTo(x, y);
  11423. t += lineDash[idx] / bezierLen;
  11424. idx = (idx + 1) % nDash;
  11425. }
  11426. // Finish the last segment and calculate the new offset
  11427. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11428. dx = x3 - x;
  11429. dy = y3 - y;
  11430. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11431. },
  11432. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11433. // Convert quadratic to cubic using degree elevation
  11434. var x3 = x2;
  11435. var y3 = y2;
  11436. x2 = (x2 + 2 * x1) / 3;
  11437. y2 = (y2 + 2 * y1) / 3;
  11438. x1 = (this._xi + 2 * x1) / 3;
  11439. y1 = (this._yi + 2 * y1) / 3;
  11440. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11441. },
  11442. /**
  11443. * 转成静态的 Float32Array 减少堆内存占用
  11444. * Convert dynamic array to static Float32Array
  11445. */
  11446. toStatic: function () {
  11447. var data = this.data;
  11448. if (data instanceof Array) {
  11449. data.length = this._len;
  11450. if (hasTypedArray) {
  11451. this.data = new Float32Array(data);
  11452. }
  11453. }
  11454. },
  11455. /**
  11456. * @return {module:zrender/core/BoundingRect}
  11457. */
  11458. getBoundingRect: function () {
  11459. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11460. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11461. var data = this.data;
  11462. var xi = 0;
  11463. var yi = 0;
  11464. var x0 = 0;
  11465. var y0 = 0;
  11466. for (var i = 0; i < data.length;) {
  11467. var cmd = data[i++];
  11468. if (i == 1) {
  11469. // 如果第一个命令是 L, C, Q
  11470. // 则 previous point 同绘制命令的第一个 point
  11471. //
  11472. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11473. xi = data[i];
  11474. yi = data[i + 1];
  11475. x0 = xi;
  11476. y0 = yi;
  11477. }
  11478. switch (cmd) {
  11479. case CMD.M:
  11480. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11481. // 在 closePath 的时候使用
  11482. x0 = data[i++];
  11483. y0 = data[i++];
  11484. xi = x0;
  11485. yi = y0;
  11486. min2[0] = x0;
  11487. min2[1] = y0;
  11488. max2[0] = x0;
  11489. max2[1] = y0;
  11490. break;
  11491. case CMD.L:
  11492. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11493. xi = data[i++];
  11494. yi = data[i++];
  11495. break;
  11496. case CMD.C:
  11497. fromCubic(
  11498. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11499. min2, max2
  11500. );
  11501. xi = data[i++];
  11502. yi = data[i++];
  11503. break;
  11504. case CMD.Q:
  11505. fromQuadratic(
  11506. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11507. min2, max2
  11508. );
  11509. xi = data[i++];
  11510. yi = data[i++];
  11511. break;
  11512. case CMD.A:
  11513. // TODO Arc 判断的开销比较大
  11514. var cx = data[i++];
  11515. var cy = data[i++];
  11516. var rx = data[i++];
  11517. var ry = data[i++];
  11518. var startAngle = data[i++];
  11519. var endAngle = data[i++] + startAngle;
  11520. // TODO Arc 旋转
  11521. var psi = data[i++];
  11522. var anticlockwise = 1 - data[i++];
  11523. if (i == 1) {
  11524. // 直接使用 arc 命令
  11525. // 第一个命令起点还未定义
  11526. x0 = mathCos$1(startAngle) * rx + cx;
  11527. y0 = mathSin$1(startAngle) * ry + cy;
  11528. }
  11529. fromArc(
  11530. cx, cy, rx, ry, startAngle, endAngle,
  11531. anticlockwise, min2, max2
  11532. );
  11533. xi = mathCos$1(endAngle) * rx + cx;
  11534. yi = mathSin$1(endAngle) * ry + cy;
  11535. break;
  11536. case CMD.R:
  11537. x0 = xi = data[i++];
  11538. y0 = yi = data[i++];
  11539. var width = data[i++];
  11540. var height = data[i++];
  11541. // Use fromLine
  11542. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11543. break;
  11544. case CMD.Z:
  11545. xi = x0;
  11546. yi = y0;
  11547. break;
  11548. }
  11549. // Union
  11550. min(min$1, min$1, min2);
  11551. max(max$1, max$1, max2);
  11552. }
  11553. // No data
  11554. if (i === 0) {
  11555. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11556. }
  11557. return new BoundingRect(
  11558. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11559. );
  11560. },
  11561. /**
  11562. * Rebuild path from current data
  11563. * Rebuild path will not consider javascript implemented line dash.
  11564. * @param {CanvasRenderingContext2D} ctx
  11565. */
  11566. rebuildPath: function (ctx) {
  11567. var d = this.data;
  11568. var x0, y0;
  11569. var xi, yi;
  11570. var x, y;
  11571. var ux = this._ux;
  11572. var uy = this._uy;
  11573. var len$$1 = this._len;
  11574. for (var i = 0; i < len$$1;) {
  11575. var cmd = d[i++];
  11576. if (i == 1) {
  11577. // 如果第一个命令是 L, C, Q
  11578. // 则 previous point 同绘制命令的第一个 point
  11579. //
  11580. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11581. xi = d[i];
  11582. yi = d[i + 1];
  11583. x0 = xi;
  11584. y0 = yi;
  11585. }
  11586. switch (cmd) {
  11587. case CMD.M:
  11588. x0 = xi = d[i++];
  11589. y0 = yi = d[i++];
  11590. ctx.moveTo(xi, yi);
  11591. break;
  11592. case CMD.L:
  11593. x = d[i++];
  11594. y = d[i++];
  11595. // Not draw too small seg between
  11596. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11597. ctx.lineTo(x, y);
  11598. xi = x;
  11599. yi = y;
  11600. }
  11601. break;
  11602. case CMD.C:
  11603. ctx.bezierCurveTo(
  11604. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11605. );
  11606. xi = d[i - 2];
  11607. yi = d[i - 1];
  11608. break;
  11609. case CMD.Q:
  11610. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11611. xi = d[i - 2];
  11612. yi = d[i - 1];
  11613. break;
  11614. case CMD.A:
  11615. var cx = d[i++];
  11616. var cy = d[i++];
  11617. var rx = d[i++];
  11618. var ry = d[i++];
  11619. var theta = d[i++];
  11620. var dTheta = d[i++];
  11621. var psi = d[i++];
  11622. var fs = d[i++];
  11623. var r = (rx > ry) ? rx : ry;
  11624. var scaleX = (rx > ry) ? 1 : rx / ry;
  11625. var scaleY = (rx > ry) ? ry / rx : 1;
  11626. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11627. var endAngle = theta + dTheta;
  11628. if (isEllipse) {
  11629. ctx.translate(cx, cy);
  11630. ctx.rotate(psi);
  11631. ctx.scale(scaleX, scaleY);
  11632. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11633. ctx.scale(1 / scaleX, 1 / scaleY);
  11634. ctx.rotate(-psi);
  11635. ctx.translate(-cx, -cy);
  11636. }
  11637. else {
  11638. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11639. }
  11640. if (i == 1) {
  11641. // 直接使用 arc 命令
  11642. // 第一个命令起点还未定义
  11643. x0 = mathCos$1(theta) * rx + cx;
  11644. y0 = mathSin$1(theta) * ry + cy;
  11645. }
  11646. xi = mathCos$1(endAngle) * rx + cx;
  11647. yi = mathSin$1(endAngle) * ry + cy;
  11648. break;
  11649. case CMD.R:
  11650. x0 = xi = d[i];
  11651. y0 = yi = d[i + 1];
  11652. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11653. break;
  11654. case CMD.Z:
  11655. ctx.closePath();
  11656. xi = x0;
  11657. yi = y0;
  11658. }
  11659. }
  11660. }
  11661. };
  11662. PathProxy.CMD = CMD;
  11663. /**
  11664. * 线段包含判断
  11665. * @param {number} x0
  11666. * @param {number} y0
  11667. * @param {number} x1
  11668. * @param {number} y1
  11669. * @param {number} lineWidth
  11670. * @param {number} x
  11671. * @param {number} y
  11672. * @return {boolean}
  11673. */
  11674. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11675. if (lineWidth === 0) {
  11676. return false;
  11677. }
  11678. var _l = lineWidth;
  11679. var _a = 0;
  11680. var _b = x0;
  11681. // Quick reject
  11682. if (
  11683. (y > y0 + _l && y > y1 + _l)
  11684. || (y < y0 - _l && y < y1 - _l)
  11685. || (x > x0 + _l && x > x1 + _l)
  11686. || (x < x0 - _l && x < x1 - _l)
  11687. ) {
  11688. return false;
  11689. }
  11690. if (x0 !== x1) {
  11691. _a = (y0 - y1) / (x0 - x1);
  11692. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11693. }
  11694. else {
  11695. return Math.abs(x - x0) <= _l / 2;
  11696. }
  11697. var tmp = _a * x - y + _b;
  11698. var _s = tmp * tmp / (_a * _a + 1);
  11699. return _s <= _l / 2 * _l / 2;
  11700. }
  11701. /**
  11702. * 三次贝塞尔曲线描边包含判断
  11703. * @param {number} x0
  11704. * @param {number} y0
  11705. * @param {number} x1
  11706. * @param {number} y1
  11707. * @param {number} x2
  11708. * @param {number} y2
  11709. * @param {number} x3
  11710. * @param {number} y3
  11711. * @param {number} lineWidth
  11712. * @param {number} x
  11713. * @param {number} y
  11714. * @return {boolean}
  11715. */
  11716. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11717. if (lineWidth === 0) {
  11718. return false;
  11719. }
  11720. var _l = lineWidth;
  11721. // Quick reject
  11722. if (
  11723. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11724. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11725. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11726. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11727. ) {
  11728. return false;
  11729. }
  11730. var d = cubicProjectPoint(
  11731. x0, y0, x1, y1, x2, y2, x3, y3,
  11732. x, y, null
  11733. );
  11734. return d <= _l / 2;
  11735. }
  11736. /**
  11737. * 二次贝塞尔曲线描边包含判断
  11738. * @param {number} x0
  11739. * @param {number} y0
  11740. * @param {number} x1
  11741. * @param {number} y1
  11742. * @param {number} x2
  11743. * @param {number} y2
  11744. * @param {number} lineWidth
  11745. * @param {number} x
  11746. * @param {number} y
  11747. * @return {boolean}
  11748. */
  11749. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11750. if (lineWidth === 0) {
  11751. return false;
  11752. }
  11753. var _l = lineWidth;
  11754. // Quick reject
  11755. if (
  11756. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11757. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11758. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11759. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11760. ) {
  11761. return false;
  11762. }
  11763. var d = quadraticProjectPoint(
  11764. x0, y0, x1, y1, x2, y2,
  11765. x, y, null
  11766. );
  11767. return d <= _l / 2;
  11768. }
  11769. var PI2$3 = Math.PI * 2;
  11770. function normalizeRadian(angle) {
  11771. angle %= PI2$3;
  11772. if (angle < 0) {
  11773. angle += PI2$3;
  11774. }
  11775. return angle;
  11776. }
  11777. var PI2$2 = Math.PI * 2;
  11778. /**
  11779. * 圆弧描边包含判断
  11780. * @param {number} cx
  11781. * @param {number} cy
  11782. * @param {number} r
  11783. * @param {number} startAngle
  11784. * @param {number} endAngle
  11785. * @param {boolean} anticlockwise
  11786. * @param {number} lineWidth
  11787. * @param {number} x
  11788. * @param {number} y
  11789. * @return {Boolean}
  11790. */
  11791. function containStroke$4(
  11792. cx, cy, r, startAngle, endAngle, anticlockwise,
  11793. lineWidth, x, y
  11794. ) {
  11795. if (lineWidth === 0) {
  11796. return false;
  11797. }
  11798. var _l = lineWidth;
  11799. x -= cx;
  11800. y -= cy;
  11801. var d = Math.sqrt(x * x + y * y);
  11802. if ((d - _l > r) || (d + _l < r)) {
  11803. return false;
  11804. }
  11805. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11806. // Is a circle
  11807. return true;
  11808. }
  11809. if (anticlockwise) {
  11810. var tmp = startAngle;
  11811. startAngle = normalizeRadian(endAngle);
  11812. endAngle = normalizeRadian(tmp);
  11813. } else {
  11814. startAngle = normalizeRadian(startAngle);
  11815. endAngle = normalizeRadian(endAngle);
  11816. }
  11817. if (startAngle > endAngle) {
  11818. endAngle += PI2$2;
  11819. }
  11820. var angle = Math.atan2(y, x);
  11821. if (angle < 0) {
  11822. angle += PI2$2;
  11823. }
  11824. return (angle >= startAngle && angle <= endAngle)
  11825. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11826. }
  11827. function windingLine(x0, y0, x1, y1, x, y) {
  11828. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11829. return 0;
  11830. }
  11831. // Ignore horizontal line
  11832. if (y1 === y0) {
  11833. return 0;
  11834. }
  11835. var dir = y1 < y0 ? 1 : -1;
  11836. var t = (y - y0) / (y1 - y0);
  11837. // Avoid winding error when intersection point is the connect point of two line of polygon
  11838. if (t === 1 || t === 0) {
  11839. dir = y1 < y0 ? 0.5 : -0.5;
  11840. }
  11841. var x_ = t * (x1 - x0) + x0;
  11842. // If (x, y) on the line, considered as "contain".
  11843. return x_ === x ? Infinity : x_ > x ? dir : 0;
  11844. }
  11845. var CMD$1 = PathProxy.CMD;
  11846. var PI2$1 = Math.PI * 2;
  11847. var EPSILON$2 = 1e-4;
  11848. function isAroundEqual(a, b) {
  11849. return Math.abs(a - b) < EPSILON$2;
  11850. }
  11851. // 临时数组
  11852. var roots = [-1, -1, -1];
  11853. var extrema = [-1, -1];
  11854. function swapExtrema() {
  11855. var tmp = extrema[0];
  11856. extrema[0] = extrema[1];
  11857. extrema[1] = tmp;
  11858. }
  11859. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11860. // Quick reject
  11861. if (
  11862. (y > y0 && y > y1 && y > y2 && y > y3)
  11863. || (y < y0 && y < y1 && y < y2 && y < y3)
  11864. ) {
  11865. return 0;
  11866. }
  11867. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11868. if (nRoots === 0) {
  11869. return 0;
  11870. }
  11871. else {
  11872. var w = 0;
  11873. var nExtrema = -1;
  11874. var y0_, y1_;
  11875. for (var i = 0; i < nRoots; i++) {
  11876. var t = roots[i];
  11877. // Avoid winding error when intersection point is the connect point of two line of polygon
  11878. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11879. var x_ = cubicAt(x0, x1, x2, x3, t);
  11880. if (x_ < x) { // Quick reject
  11881. continue;
  11882. }
  11883. if (nExtrema < 0) {
  11884. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11885. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11886. swapExtrema();
  11887. }
  11888. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11889. if (nExtrema > 1) {
  11890. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11891. }
  11892. }
  11893. if (nExtrema == 2) {
  11894. // 分成三段单调函数
  11895. if (t < extrema[0]) {
  11896. w += y0_ < y0 ? unit : -unit;
  11897. }
  11898. else if (t < extrema[1]) {
  11899. w += y1_ < y0_ ? unit : -unit;
  11900. }
  11901. else {
  11902. w += y3 < y1_ ? unit : -unit;
  11903. }
  11904. }
  11905. else {
  11906. // 分成两段单调函数
  11907. if (t < extrema[0]) {
  11908. w += y0_ < y0 ? unit : -unit;
  11909. }
  11910. else {
  11911. w += y3 < y0_ ? unit : -unit;
  11912. }
  11913. }
  11914. }
  11915. return w;
  11916. }
  11917. }
  11918. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11919. // Quick reject
  11920. if (
  11921. (y > y0 && y > y1 && y > y2)
  11922. || (y < y0 && y < y1 && y < y2)
  11923. ) {
  11924. return 0;
  11925. }
  11926. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11927. if (nRoots === 0) {
  11928. return 0;
  11929. }
  11930. else {
  11931. var t = quadraticExtremum(y0, y1, y2);
  11932. if (t >= 0 && t <= 1) {
  11933. var w = 0;
  11934. var y_ = quadraticAt(y0, y1, y2, t);
  11935. for (var i = 0; i < nRoots; i++) {
  11936. // Remove one endpoint.
  11937. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11938. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11939. if (x_ < x) { // Quick reject
  11940. continue;
  11941. }
  11942. if (roots[i] < t) {
  11943. w += y_ < y0 ? unit : -unit;
  11944. }
  11945. else {
  11946. w += y2 < y_ ? unit : -unit;
  11947. }
  11948. }
  11949. return w;
  11950. }
  11951. else {
  11952. // Remove one endpoint.
  11953. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11954. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11955. if (x_ < x) { // Quick reject
  11956. return 0;
  11957. }
  11958. return y2 < y0 ? unit : -unit;
  11959. }
  11960. }
  11961. }
  11962. // TODO
  11963. // Arc 旋转
  11964. function windingArc(
  11965. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11966. ) {
  11967. y -= cy;
  11968. if (y > r || y < -r) {
  11969. return 0;
  11970. }
  11971. var tmp = Math.sqrt(r * r - y * y);
  11972. roots[0] = -tmp;
  11973. roots[1] = tmp;
  11974. var diff = Math.abs(startAngle - endAngle);
  11975. if (diff < 1e-4) {
  11976. return 0;
  11977. }
  11978. if (diff % PI2$1 < 1e-4) {
  11979. // Is a circle
  11980. startAngle = 0;
  11981. endAngle = PI2$1;
  11982. var dir = anticlockwise ? 1 : -1;
  11983. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11984. return dir;
  11985. } else {
  11986. return 0;
  11987. }
  11988. }
  11989. if (anticlockwise) {
  11990. var tmp = startAngle;
  11991. startAngle = normalizeRadian(endAngle);
  11992. endAngle = normalizeRadian(tmp);
  11993. }
  11994. else {
  11995. startAngle = normalizeRadian(startAngle);
  11996. endAngle = normalizeRadian(endAngle);
  11997. }
  11998. if (startAngle > endAngle) {
  11999. endAngle += PI2$1;
  12000. }
  12001. var w = 0;
  12002. for (var i = 0; i < 2; i++) {
  12003. var x_ = roots[i];
  12004. if (x_ + cx > x) {
  12005. var angle = Math.atan2(y, x_);
  12006. var dir = anticlockwise ? 1 : -1;
  12007. if (angle < 0) {
  12008. angle = PI2$1 + angle;
  12009. }
  12010. if (
  12011. (angle >= startAngle && angle <= endAngle)
  12012. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12013. ) {
  12014. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12015. dir = -dir;
  12016. }
  12017. w += dir;
  12018. }
  12019. }
  12020. }
  12021. return w;
  12022. }
  12023. function containPath(data, lineWidth, isStroke, x, y) {
  12024. var w = 0;
  12025. var xi = 0;
  12026. var yi = 0;
  12027. var x0 = 0;
  12028. var y0 = 0;
  12029. for (var i = 0; i < data.length;) {
  12030. var cmd = data[i++];
  12031. // Begin a new subpath
  12032. if (cmd === CMD$1.M && i > 1) {
  12033. // Close previous subpath
  12034. if (!isStroke) {
  12035. w += windingLine(xi, yi, x0, y0, x, y);
  12036. }
  12037. // 如果被任何一个 subpath 包含
  12038. // if (w !== 0) {
  12039. // return true;
  12040. // }
  12041. }
  12042. if (i == 1) {
  12043. // 如果第一个命令是 L, C, Q
  12044. // 则 previous point 同绘制命令的第一个 point
  12045. //
  12046. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12047. xi = data[i];
  12048. yi = data[i + 1];
  12049. x0 = xi;
  12050. y0 = yi;
  12051. }
  12052. switch (cmd) {
  12053. case CMD$1.M:
  12054. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12055. // 在 closePath 的时候使用
  12056. x0 = data[i++];
  12057. y0 = data[i++];
  12058. xi = x0;
  12059. yi = y0;
  12060. break;
  12061. case CMD$1.L:
  12062. if (isStroke) {
  12063. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12064. return true;
  12065. }
  12066. }
  12067. else {
  12068. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12069. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12070. }
  12071. xi = data[i++];
  12072. yi = data[i++];
  12073. break;
  12074. case CMD$1.C:
  12075. if (isStroke) {
  12076. if (containStroke$2(xi, yi,
  12077. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12078. lineWidth, x, y
  12079. )) {
  12080. return true;
  12081. }
  12082. }
  12083. else {
  12084. w += windingCubic(
  12085. xi, yi,
  12086. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12087. x, y
  12088. ) || 0;
  12089. }
  12090. xi = data[i++];
  12091. yi = data[i++];
  12092. break;
  12093. case CMD$1.Q:
  12094. if (isStroke) {
  12095. if (containStroke$3(xi, yi,
  12096. data[i++], data[i++], data[i], data[i + 1],
  12097. lineWidth, x, y
  12098. )) {
  12099. return true;
  12100. }
  12101. }
  12102. else {
  12103. w += windingQuadratic(
  12104. xi, yi,
  12105. data[i++], data[i++], data[i], data[i + 1],
  12106. x, y
  12107. ) || 0;
  12108. }
  12109. xi = data[i++];
  12110. yi = data[i++];
  12111. break;
  12112. case CMD$1.A:
  12113. // TODO Arc 判断的开销比较大
  12114. var cx = data[i++];
  12115. var cy = data[i++];
  12116. var rx = data[i++];
  12117. var ry = data[i++];
  12118. var theta = data[i++];
  12119. var dTheta = data[i++];
  12120. // TODO Arc 旋转
  12121. var psi = data[i++];
  12122. var anticlockwise = 1 - data[i++];
  12123. var x1 = Math.cos(theta) * rx + cx;
  12124. var y1 = Math.sin(theta) * ry + cy;
  12125. // 不是直接使用 arc 命令
  12126. if (i > 1) {
  12127. w += windingLine(xi, yi, x1, y1, x, y);
  12128. }
  12129. else {
  12130. // 第一个命令起点还未定义
  12131. x0 = x1;
  12132. y0 = y1;
  12133. }
  12134. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12135. var _x = (x - cx) * ry / rx + cx;
  12136. if (isStroke) {
  12137. if (containStroke$4(
  12138. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12139. lineWidth, _x, y
  12140. )) {
  12141. return true;
  12142. }
  12143. }
  12144. else {
  12145. w += windingArc(
  12146. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12147. _x, y
  12148. );
  12149. }
  12150. xi = Math.cos(theta + dTheta) * rx + cx;
  12151. yi = Math.sin(theta + dTheta) * ry + cy;
  12152. break;
  12153. case CMD$1.R:
  12154. x0 = xi = data[i++];
  12155. y0 = yi = data[i++];
  12156. var width = data[i++];
  12157. var height = data[i++];
  12158. var x1 = x0 + width;
  12159. var y1 = y0 + height;
  12160. if (isStroke) {
  12161. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12162. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12163. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12164. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12165. ) {
  12166. return true;
  12167. }
  12168. }
  12169. else {
  12170. // FIXME Clockwise ?
  12171. w += windingLine(x1, y0, x1, y1, x, y);
  12172. w += windingLine(x0, y1, x0, y0, x, y);
  12173. }
  12174. break;
  12175. case CMD$1.Z:
  12176. if (isStroke) {
  12177. if (containStroke$1(
  12178. xi, yi, x0, y0, lineWidth, x, y
  12179. )) {
  12180. return true;
  12181. }
  12182. }
  12183. else {
  12184. // Close a subpath
  12185. w += windingLine(xi, yi, x0, y0, x, y);
  12186. // 如果被任何一个 subpath 包含
  12187. // FIXME subpaths may overlap
  12188. // if (w !== 0) {
  12189. // return true;
  12190. // }
  12191. }
  12192. xi = x0;
  12193. yi = y0;
  12194. break;
  12195. }
  12196. }
  12197. if (!isStroke && !isAroundEqual(yi, y0)) {
  12198. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12199. }
  12200. return w !== 0;
  12201. }
  12202. function contain(pathData, x, y) {
  12203. return containPath(pathData, 0, false, x, y);
  12204. }
  12205. function containStroke(pathData, lineWidth, x, y) {
  12206. return containPath(pathData, lineWidth, true, x, y);
  12207. }
  12208. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12209. var abs = Math.abs;
  12210. var pathProxyForDraw = new PathProxy(true);
  12211. /**
  12212. * @alias module:zrender/graphic/Path
  12213. * @extends module:zrender/graphic/Displayable
  12214. * @constructor
  12215. * @param {Object} opts
  12216. */
  12217. function Path(opts) {
  12218. Displayable.call(this, opts);
  12219. /**
  12220. * @type {module:zrender/core/PathProxy}
  12221. * @readOnly
  12222. */
  12223. this.path = null;
  12224. }
  12225. Path.prototype = {
  12226. constructor: Path,
  12227. type: 'path',
  12228. __dirtyPath: true,
  12229. strokeContainThreshold: 5,
  12230. brush: function (ctx, prevEl) {
  12231. var style = this.style;
  12232. var path = this.path || pathProxyForDraw;
  12233. var hasStroke = style.hasStroke();
  12234. var hasFill = style.hasFill();
  12235. var fill = style.fill;
  12236. var stroke = style.stroke;
  12237. var hasFillGradient = hasFill && !!(fill.colorStops);
  12238. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12239. var hasFillPattern = hasFill && !!(fill.image);
  12240. var hasStrokePattern = hasStroke && !!(stroke.image);
  12241. style.bind(ctx, this, prevEl);
  12242. this.setTransform(ctx);
  12243. if (this.__dirty) {
  12244. var rect;
  12245. // Update gradient because bounding rect may changed
  12246. if (hasFillGradient) {
  12247. rect = rect || this.getBoundingRect();
  12248. this._fillGradient = style.getGradient(ctx, fill, rect);
  12249. }
  12250. if (hasStrokeGradient) {
  12251. rect = rect || this.getBoundingRect();
  12252. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12253. }
  12254. }
  12255. // Use the gradient or pattern
  12256. if (hasFillGradient) {
  12257. // PENDING If may have affect the state
  12258. ctx.fillStyle = this._fillGradient;
  12259. }
  12260. else if (hasFillPattern) {
  12261. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12262. }
  12263. if (hasStrokeGradient) {
  12264. ctx.strokeStyle = this._strokeGradient;
  12265. }
  12266. else if (hasStrokePattern) {
  12267. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12268. }
  12269. var lineDash = style.lineDash;
  12270. var lineDashOffset = style.lineDashOffset;
  12271. var ctxLineDash = !!ctx.setLineDash;
  12272. // Update path sx, sy
  12273. var scale = this.getGlobalScale();
  12274. path.setScale(scale[0], scale[1]);
  12275. // Proxy context
  12276. // Rebuild path in following 2 cases
  12277. // 1. Path is dirty
  12278. // 2. Path needs javascript implemented lineDash stroking.
  12279. // In this case, lineDash information will not be saved in PathProxy
  12280. if (this.__dirtyPath
  12281. || (lineDash && !ctxLineDash && hasStroke)
  12282. ) {
  12283. path.beginPath(ctx);
  12284. // Setting line dash before build path
  12285. if (lineDash && !ctxLineDash) {
  12286. path.setLineDash(lineDash);
  12287. path.setLineDashOffset(lineDashOffset);
  12288. }
  12289. this.buildPath(path, this.shape, false);
  12290. // Clear path dirty flag
  12291. if (this.path) {
  12292. this.__dirtyPath = false;
  12293. }
  12294. }
  12295. else {
  12296. // Replay path building
  12297. ctx.beginPath();
  12298. this.path.rebuildPath(ctx);
  12299. }
  12300. hasFill && path.fill(ctx);
  12301. if (lineDash && ctxLineDash) {
  12302. ctx.setLineDash(lineDash);
  12303. ctx.lineDashOffset = lineDashOffset;
  12304. }
  12305. hasStroke && path.stroke(ctx);
  12306. if (lineDash && ctxLineDash) {
  12307. // PENDING
  12308. // Remove lineDash
  12309. ctx.setLineDash([]);
  12310. }
  12311. // Draw rect text
  12312. if (style.text != null) {
  12313. // Only restore transform when needs draw text.
  12314. this.restoreTransform(ctx);
  12315. this.drawRectText(ctx, this.getBoundingRect());
  12316. }
  12317. },
  12318. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12319. // Like in circle
  12320. buildPath: function (ctx, shapeCfg, inBundle) {},
  12321. createPathProxy: function () {
  12322. this.path = new PathProxy();
  12323. },
  12324. getBoundingRect: function () {
  12325. var rect = this._rect;
  12326. var style = this.style;
  12327. var needsUpdateRect = !rect;
  12328. if (needsUpdateRect) {
  12329. var path = this.path;
  12330. if (!path) {
  12331. // Create path on demand.
  12332. path = this.path = new PathProxy();
  12333. }
  12334. if (this.__dirtyPath) {
  12335. path.beginPath();
  12336. this.buildPath(path, this.shape, false);
  12337. }
  12338. rect = path.getBoundingRect();
  12339. }
  12340. this._rect = rect;
  12341. if (style.hasStroke()) {
  12342. // Needs update rect with stroke lineWidth when
  12343. // 1. Element changes scale or lineWidth
  12344. // 2. Shape is changed
  12345. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12346. if (this.__dirty || needsUpdateRect) {
  12347. rectWithStroke.copy(rect);
  12348. // FIXME Must after updateTransform
  12349. var w = style.lineWidth;
  12350. // PENDING, Min line width is needed when line is horizontal or vertical
  12351. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12352. // Only add extra hover lineWidth when there are no fill
  12353. if (!style.hasFill()) {
  12354. w = Math.max(w, this.strokeContainThreshold || 4);
  12355. }
  12356. // Consider line width
  12357. // Line scale can't be 0;
  12358. if (lineScale > 1e-10) {
  12359. rectWithStroke.width += w / lineScale;
  12360. rectWithStroke.height += w / lineScale;
  12361. rectWithStroke.x -= w / lineScale / 2;
  12362. rectWithStroke.y -= w / lineScale / 2;
  12363. }
  12364. }
  12365. // Return rect with stroke
  12366. return rectWithStroke;
  12367. }
  12368. return rect;
  12369. },
  12370. contain: function (x, y) {
  12371. var localPos = this.transformCoordToLocal(x, y);
  12372. var rect = this.getBoundingRect();
  12373. var style = this.style;
  12374. x = localPos[0];
  12375. y = localPos[1];
  12376. if (rect.contain(x, y)) {
  12377. var pathData = this.path.data;
  12378. if (style.hasStroke()) {
  12379. var lineWidth = style.lineWidth;
  12380. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12381. // Line scale can't be 0;
  12382. if (lineScale > 1e-10) {
  12383. // Only add extra hover lineWidth when there are no fill
  12384. if (!style.hasFill()) {
  12385. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12386. }
  12387. if (containStroke(
  12388. pathData, lineWidth / lineScale, x, y
  12389. )) {
  12390. return true;
  12391. }
  12392. }
  12393. }
  12394. if (style.hasFill()) {
  12395. return contain(pathData, x, y);
  12396. }
  12397. }
  12398. return false;
  12399. },
  12400. /**
  12401. * @param {boolean} dirtyPath
  12402. */
  12403. dirty: function (dirtyPath) {
  12404. if (dirtyPath == null) {
  12405. dirtyPath = true;
  12406. }
  12407. // Only mark dirty, not mark clean
  12408. if (dirtyPath) {
  12409. this.__dirtyPath = dirtyPath;
  12410. this._rect = null;
  12411. }
  12412. this.__dirty = true;
  12413. this.__zr && this.__zr.refresh();
  12414. // Used as a clipping path
  12415. if (this.__clipTarget) {
  12416. this.__clipTarget.dirty();
  12417. }
  12418. },
  12419. /**
  12420. * Alias for animate('shape')
  12421. * @param {boolean} loop
  12422. */
  12423. animateShape: function (loop) {
  12424. return this.animate('shape', loop);
  12425. },
  12426. // Overwrite attrKV
  12427. attrKV: function (key, value) {
  12428. // FIXME
  12429. if (key === 'shape') {
  12430. this.setShape(value);
  12431. this.__dirtyPath = true;
  12432. this._rect = null;
  12433. }
  12434. else {
  12435. Displayable.prototype.attrKV.call(this, key, value);
  12436. }
  12437. },
  12438. /**
  12439. * @param {Object|string} key
  12440. * @param {*} value
  12441. */
  12442. setShape: function (key, value) {
  12443. var shape = this.shape;
  12444. // Path from string may not have shape
  12445. if (shape) {
  12446. if (isObject$1(key)) {
  12447. for (var name in key) {
  12448. if (key.hasOwnProperty(name)) {
  12449. shape[name] = key[name];
  12450. }
  12451. }
  12452. }
  12453. else {
  12454. shape[key] = value;
  12455. }
  12456. this.dirty(true);
  12457. }
  12458. return this;
  12459. },
  12460. getLineScale: function () {
  12461. var m = this.transform;
  12462. // Get the line scale.
  12463. // Determinant of `m` means how much the area is enlarged by the
  12464. // transformation. So its square root can be used as a scale factor
  12465. // for width.
  12466. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12467. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12468. : 1;
  12469. }
  12470. };
  12471. /**
  12472. * 扩展一个 Path element, 比如星形,圆等。
  12473. * Extend a path element
  12474. * @param {Object} props
  12475. * @param {string} props.type Path type
  12476. * @param {Function} props.init Initialize
  12477. * @param {Function} props.buildPath Overwrite buildPath method
  12478. * @param {Object} [props.style] Extended default style config
  12479. * @param {Object} [props.shape] Extended default shape config
  12480. */
  12481. Path.extend = function (defaults$$1) {
  12482. var Sub = function (opts) {
  12483. Path.call(this, opts);
  12484. if (defaults$$1.style) {
  12485. // Extend default style
  12486. this.style.extendFrom(defaults$$1.style, false);
  12487. }
  12488. // Extend default shape
  12489. var defaultShape = defaults$$1.shape;
  12490. if (defaultShape) {
  12491. this.shape = this.shape || {};
  12492. var thisShape = this.shape;
  12493. for (var name in defaultShape) {
  12494. if (
  12495. ! thisShape.hasOwnProperty(name)
  12496. && defaultShape.hasOwnProperty(name)
  12497. ) {
  12498. thisShape[name] = defaultShape[name];
  12499. }
  12500. }
  12501. }
  12502. defaults$$1.init && defaults$$1.init.call(this, opts);
  12503. };
  12504. inherits(Sub, Path);
  12505. // FIXME 不能 extend position, rotation 等引用对象
  12506. for (var name in defaults$$1) {
  12507. // Extending prototype values and methods
  12508. if (name !== 'style' && name !== 'shape') {
  12509. Sub.prototype[name] = defaults$$1[name];
  12510. }
  12511. }
  12512. return Sub;
  12513. };
  12514. inherits(Path, Displayable);
  12515. var CMD$2 = PathProxy.CMD;
  12516. var points = [[], [], []];
  12517. var mathSqrt$3 = Math.sqrt;
  12518. var mathAtan2 = Math.atan2;
  12519. var transformPath = function (path, m) {
  12520. var data = path.data;
  12521. var cmd;
  12522. var nPoint;
  12523. var i;
  12524. var j;
  12525. var k;
  12526. var p;
  12527. var M = CMD$2.M;
  12528. var C = CMD$2.C;
  12529. var L = CMD$2.L;
  12530. var R = CMD$2.R;
  12531. var A = CMD$2.A;
  12532. var Q = CMD$2.Q;
  12533. for (i = 0, j = 0; i < data.length;) {
  12534. cmd = data[i++];
  12535. j = i;
  12536. nPoint = 0;
  12537. switch (cmd) {
  12538. case M:
  12539. nPoint = 1;
  12540. break;
  12541. case L:
  12542. nPoint = 1;
  12543. break;
  12544. case C:
  12545. nPoint = 3;
  12546. break;
  12547. case Q:
  12548. nPoint = 2;
  12549. break;
  12550. case A:
  12551. var x = m[4];
  12552. var y = m[5];
  12553. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12554. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12555. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12556. // cx
  12557. data[i] *= sx;
  12558. data[i++] += x;
  12559. // cy
  12560. data[i] *= sy;
  12561. data[i++] += y;
  12562. // Scale rx and ry
  12563. // FIXME Assume psi is 0 here
  12564. data[i++] *= sx;
  12565. data[i++] *= sy;
  12566. // Start angle
  12567. data[i++] += angle;
  12568. // end angle
  12569. data[i++] += angle;
  12570. // FIXME psi
  12571. i += 2;
  12572. j = i;
  12573. break;
  12574. case R:
  12575. // x0, y0
  12576. p[0] = data[i++];
  12577. p[1] = data[i++];
  12578. applyTransform(p, p, m);
  12579. data[j++] = p[0];
  12580. data[j++] = p[1];
  12581. // x1, y1
  12582. p[0] += data[i++];
  12583. p[1] += data[i++];
  12584. applyTransform(p, p, m);
  12585. data[j++] = p[0];
  12586. data[j++] = p[1];
  12587. }
  12588. for (k = 0; k < nPoint; k++) {
  12589. var p = points[k];
  12590. p[0] = data[i++];
  12591. p[1] = data[i++];
  12592. applyTransform(p, p, m);
  12593. // Write back
  12594. data[j++] = p[0];
  12595. data[j++] = p[1];
  12596. }
  12597. }
  12598. };
  12599. // command chars
  12600. var cc = [
  12601. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12602. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12603. ];
  12604. var mathSqrt = Math.sqrt;
  12605. var mathSin = Math.sin;
  12606. var mathCos = Math.cos;
  12607. var PI = Math.PI;
  12608. var vMag = function(v) {
  12609. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12610. };
  12611. var vRatio = function(u, v) {
  12612. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12613. };
  12614. var vAngle = function(u, v) {
  12615. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12616. * Math.acos(vRatio(u, v));
  12617. };
  12618. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12619. var psi = psiDeg * (PI / 180.0);
  12620. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12621. + mathSin(psi) * (y1 - y2) / 2.0;
  12622. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12623. + mathCos(psi) * (y1 - y2) / 2.0;
  12624. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12625. if (lambda > 1) {
  12626. rx *= mathSqrt(lambda);
  12627. ry *= mathSqrt(lambda);
  12628. }
  12629. var f = (fa === fs ? -1 : 1)
  12630. * mathSqrt((((rx * rx) * (ry * ry))
  12631. - ((rx * rx) * (yp * yp))
  12632. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12633. + (ry * ry) * (xp * xp))
  12634. ) || 0;
  12635. var cxp = f * rx * yp / ry;
  12636. var cyp = f * -ry * xp / rx;
  12637. var cx = (x1 + x2) / 2.0
  12638. + mathCos(psi) * cxp
  12639. - mathSin(psi) * cyp;
  12640. var cy = (y1 + y2) / 2.0
  12641. + mathSin(psi) * cxp
  12642. + mathCos(psi) * cyp;
  12643. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12644. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12645. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12646. var dTheta = vAngle(u, v);
  12647. if (vRatio(u, v) <= -1) {
  12648. dTheta = PI;
  12649. }
  12650. if (vRatio(u, v) >= 1) {
  12651. dTheta = 0;
  12652. }
  12653. if (fs === 0 && dTheta > 0) {
  12654. dTheta = dTheta - 2 * PI;
  12655. }
  12656. if (fs === 1 && dTheta < 0) {
  12657. dTheta = dTheta + 2 * PI;
  12658. }
  12659. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12660. }
  12661. function createPathProxyFromString(data) {
  12662. if (!data) {
  12663. return [];
  12664. }
  12665. // command string
  12666. var cs = data.replace(/-/g, ' -')
  12667. .replace(/ /g, ' ')
  12668. .replace(/ /g, ',')
  12669. .replace(/,,/g, ',');
  12670. var n;
  12671. // create pipes so that we can split the data
  12672. for (n = 0; n < cc.length; n++) {
  12673. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12674. }
  12675. // create array
  12676. var arr = cs.split('|');
  12677. // init context point
  12678. var cpx = 0;
  12679. var cpy = 0;
  12680. var path = new PathProxy();
  12681. var CMD = PathProxy.CMD;
  12682. var prevCmd;
  12683. for (n = 1; n < arr.length; n++) {
  12684. var str = arr[n];
  12685. var c = str.charAt(0);
  12686. var off = 0;
  12687. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12688. var cmd;
  12689. if (p.length > 0 && p[0] === '') {
  12690. p.shift();
  12691. }
  12692. for (var i = 0; i < p.length; i++) {
  12693. p[i] = parseFloat(p[i]);
  12694. }
  12695. while (off < p.length && !isNaN(p[off])) {
  12696. if (isNaN(p[0])) {
  12697. break;
  12698. }
  12699. var ctlPtx;
  12700. var ctlPty;
  12701. var rx;
  12702. var ry;
  12703. var psi;
  12704. var fa;
  12705. var fs;
  12706. var x1 = cpx;
  12707. var y1 = cpy;
  12708. // convert l, H, h, V, and v to L
  12709. switch (c) {
  12710. case 'l':
  12711. cpx += p[off++];
  12712. cpy += p[off++];
  12713. cmd = CMD.L;
  12714. path.addData(cmd, cpx, cpy);
  12715. break;
  12716. case 'L':
  12717. cpx = p[off++];
  12718. cpy = p[off++];
  12719. cmd = CMD.L;
  12720. path.addData(cmd, cpx, cpy);
  12721. break;
  12722. case 'm':
  12723. cpx += p[off++];
  12724. cpy += p[off++];
  12725. cmd = CMD.M;
  12726. path.addData(cmd, cpx, cpy);
  12727. c = 'l';
  12728. break;
  12729. case 'M':
  12730. cpx = p[off++];
  12731. cpy = p[off++];
  12732. cmd = CMD.M;
  12733. path.addData(cmd, cpx, cpy);
  12734. c = 'L';
  12735. break;
  12736. case 'h':
  12737. cpx += p[off++];
  12738. cmd = CMD.L;
  12739. path.addData(cmd, cpx, cpy);
  12740. break;
  12741. case 'H':
  12742. cpx = p[off++];
  12743. cmd = CMD.L;
  12744. path.addData(cmd, cpx, cpy);
  12745. break;
  12746. case 'v':
  12747. cpy += p[off++];
  12748. cmd = CMD.L;
  12749. path.addData(cmd, cpx, cpy);
  12750. break;
  12751. case 'V':
  12752. cpy = p[off++];
  12753. cmd = CMD.L;
  12754. path.addData(cmd, cpx, cpy);
  12755. break;
  12756. case 'C':
  12757. cmd = CMD.C;
  12758. path.addData(
  12759. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12760. );
  12761. cpx = p[off - 2];
  12762. cpy = p[off - 1];
  12763. break;
  12764. case 'c':
  12765. cmd = CMD.C;
  12766. path.addData(
  12767. cmd,
  12768. p[off++] + cpx, p[off++] + cpy,
  12769. p[off++] + cpx, p[off++] + cpy,
  12770. p[off++] + cpx, p[off++] + cpy
  12771. );
  12772. cpx += p[off - 2];
  12773. cpy += p[off - 1];
  12774. break;
  12775. case 'S':
  12776. ctlPtx = cpx;
  12777. ctlPty = cpy;
  12778. var len = path.len();
  12779. var pathData = path.data;
  12780. if (prevCmd === CMD.C) {
  12781. ctlPtx += cpx - pathData[len - 4];
  12782. ctlPty += cpy - pathData[len - 3];
  12783. }
  12784. cmd = CMD.C;
  12785. x1 = p[off++];
  12786. y1 = p[off++];
  12787. cpx = p[off++];
  12788. cpy = p[off++];
  12789. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12790. break;
  12791. case 's':
  12792. ctlPtx = cpx;
  12793. ctlPty = cpy;
  12794. var len = path.len();
  12795. var pathData = path.data;
  12796. if (prevCmd === CMD.C) {
  12797. ctlPtx += cpx - pathData[len - 4];
  12798. ctlPty += cpy - pathData[len - 3];
  12799. }
  12800. cmd = CMD.C;
  12801. x1 = cpx + p[off++];
  12802. y1 = cpy + p[off++];
  12803. cpx += p[off++];
  12804. cpy += p[off++];
  12805. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12806. break;
  12807. case 'Q':
  12808. x1 = p[off++];
  12809. y1 = p[off++];
  12810. cpx = p[off++];
  12811. cpy = p[off++];
  12812. cmd = CMD.Q;
  12813. path.addData(cmd, x1, y1, cpx, cpy);
  12814. break;
  12815. case 'q':
  12816. x1 = p[off++] + cpx;
  12817. y1 = p[off++] + cpy;
  12818. cpx += p[off++];
  12819. cpy += p[off++];
  12820. cmd = CMD.Q;
  12821. path.addData(cmd, x1, y1, cpx, cpy);
  12822. break;
  12823. case 'T':
  12824. ctlPtx = cpx;
  12825. ctlPty = cpy;
  12826. var len = path.len();
  12827. var pathData = path.data;
  12828. if (prevCmd === CMD.Q) {
  12829. ctlPtx += cpx - pathData[len - 4];
  12830. ctlPty += cpy - pathData[len - 3];
  12831. }
  12832. cpx = p[off++];
  12833. cpy = p[off++];
  12834. cmd = CMD.Q;
  12835. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12836. break;
  12837. case 't':
  12838. ctlPtx = cpx;
  12839. ctlPty = cpy;
  12840. var len = path.len();
  12841. var pathData = path.data;
  12842. if (prevCmd === CMD.Q) {
  12843. ctlPtx += cpx - pathData[len - 4];
  12844. ctlPty += cpy - pathData[len - 3];
  12845. }
  12846. cpx += p[off++];
  12847. cpy += p[off++];
  12848. cmd = CMD.Q;
  12849. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12850. break;
  12851. case 'A':
  12852. rx = p[off++];
  12853. ry = p[off++];
  12854. psi = p[off++];
  12855. fa = p[off++];
  12856. fs = p[off++];
  12857. x1 = cpx, y1 = cpy;
  12858. cpx = p[off++];
  12859. cpy = p[off++];
  12860. cmd = CMD.A;
  12861. processArc(
  12862. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12863. );
  12864. break;
  12865. case 'a':
  12866. rx = p[off++];
  12867. ry = p[off++];
  12868. psi = p[off++];
  12869. fa = p[off++];
  12870. fs = p[off++];
  12871. x1 = cpx, y1 = cpy;
  12872. cpx += p[off++];
  12873. cpy += p[off++];
  12874. cmd = CMD.A;
  12875. processArc(
  12876. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12877. );
  12878. break;
  12879. }
  12880. }
  12881. if (c === 'z' || c === 'Z') {
  12882. cmd = CMD.Z;
  12883. path.addData(cmd);
  12884. }
  12885. prevCmd = cmd;
  12886. }
  12887. path.toStatic();
  12888. return path;
  12889. }
  12890. // TODO Optimize double memory cost problem
  12891. function createPathOptions(str, opts) {
  12892. var pathProxy = createPathProxyFromString(str);
  12893. opts = opts || {};
  12894. opts.buildPath = function (path) {
  12895. if (path.setData) {
  12896. path.setData(pathProxy.data);
  12897. // Svg and vml renderer don't have context
  12898. var ctx = path.getContext();
  12899. if (ctx) {
  12900. path.rebuildPath(ctx);
  12901. }
  12902. }
  12903. else {
  12904. var ctx = path;
  12905. pathProxy.rebuildPath(ctx);
  12906. }
  12907. };
  12908. opts.applyTransform = function (m) {
  12909. transformPath(pathProxy, m);
  12910. this.dirty(true);
  12911. };
  12912. return opts;
  12913. }
  12914. /**
  12915. * Create a Path object from path string data
  12916. * http://www.w3.org/TR/SVG/paths.html#PathData
  12917. * @param {Object} opts Other options
  12918. */
  12919. function createFromString(str, opts) {
  12920. return new Path(createPathOptions(str, opts));
  12921. }
  12922. /**
  12923. * Create a Path class from path string data
  12924. * @param {string} str
  12925. * @param {Object} opts Other options
  12926. */
  12927. function extendFromString(str, opts) {
  12928. return Path.extend(createPathOptions(str, opts));
  12929. }
  12930. /**
  12931. * Merge multiple paths
  12932. */
  12933. // TODO Apply transform
  12934. // TODO stroke dash
  12935. // TODO Optimize double memory cost problem
  12936. function mergePath$1(pathEls, opts) {
  12937. var pathList = [];
  12938. var len = pathEls.length;
  12939. for (var i = 0; i < len; i++) {
  12940. var pathEl = pathEls[i];
  12941. if (!pathEl.path) {
  12942. pathEl.createPathProxy();
  12943. }
  12944. if (pathEl.__dirtyPath) {
  12945. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12946. }
  12947. pathList.push(pathEl.path);
  12948. }
  12949. var pathBundle = new Path(opts);
  12950. // Need path proxy.
  12951. pathBundle.createPathProxy();
  12952. pathBundle.buildPath = function (path) {
  12953. path.appendPath(pathList);
  12954. // Svg and vml renderer don't have context
  12955. var ctx = path.getContext();
  12956. if (ctx) {
  12957. path.rebuildPath(ctx);
  12958. }
  12959. };
  12960. return pathBundle;
  12961. }
  12962. /**
  12963. * @alias zrender/graphic/Text
  12964. * @extends module:zrender/graphic/Displayable
  12965. * @constructor
  12966. * @param {Object} opts
  12967. */
  12968. var Text = function (opts) { // jshint ignore:line
  12969. Displayable.call(this, opts);
  12970. };
  12971. Text.prototype = {
  12972. constructor: Text,
  12973. type: 'text',
  12974. brush: function (ctx, prevEl) {
  12975. var style = this.style;
  12976. // Optimize, avoid normalize every time.
  12977. this.__dirty && normalizeTextStyle(style, true);
  12978. // Use props with prefix 'text'.
  12979. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12980. style.shadowOffsetX = style.shadowOffsetY = null;
  12981. var text = style.text;
  12982. // Convert to string
  12983. text != null && (text += '');
  12984. // Always bind style
  12985. style.bind(ctx, this, prevEl);
  12986. if (!needDrawText(text, style)) {
  12987. return;
  12988. }
  12989. this.setTransform(ctx);
  12990. renderText(this, ctx, text, style);
  12991. this.restoreTransform(ctx);
  12992. },
  12993. getBoundingRect: function () {
  12994. var style = this.style;
  12995. // Optimize, avoid normalize every time.
  12996. this.__dirty && normalizeTextStyle(style, true);
  12997. if (!this._rect) {
  12998. var text = style.text;
  12999. text != null ? (text += '') : (text = '');
  13000. var rect = getBoundingRect(
  13001. style.text + '',
  13002. style.font,
  13003. style.textAlign,
  13004. style.textVerticalAlign,
  13005. style.textPadding,
  13006. style.rich
  13007. );
  13008. rect.x += style.x || 0;
  13009. rect.y += style.y || 0;
  13010. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13011. var w = style.textStrokeWidth;
  13012. rect.x -= w / 2;
  13013. rect.y -= w / 2;
  13014. rect.width += w;
  13015. rect.height += w;
  13016. }
  13017. this._rect = rect;
  13018. }
  13019. return this._rect;
  13020. }
  13021. };
  13022. inherits(Text, Displayable);
  13023. /**
  13024. * 圆形
  13025. * @module zrender/shape/Circle
  13026. */
  13027. var Circle = Path.extend({
  13028. type: 'circle',
  13029. shape: {
  13030. cx: 0,
  13031. cy: 0,
  13032. r: 0
  13033. },
  13034. buildPath : function (ctx, shape, inBundle) {
  13035. // Better stroking in ShapeBundle
  13036. // Always do it may have performence issue ( fill may be 2x more cost)
  13037. if (inBundle) {
  13038. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13039. }
  13040. // else {
  13041. // if (ctx.allocate && !ctx.data.length) {
  13042. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13043. // }
  13044. // }
  13045. // Better stroking in ShapeBundle
  13046. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13047. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13048. }
  13049. });
  13050. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13051. // where exception "unexpected call to method or property access"
  13052. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13053. // whose area size is zero is drawn and ctx.clip() is called and
  13054. // shadowBlur is set. See #4572, #3112, #5777.
  13055. // (e.g.,
  13056. // ctx.moveTo(10, 10);
  13057. // ctx.lineTo(20, 10);
  13058. // ctx.closePath();
  13059. // ctx.clip();
  13060. // ctx.shadowBlur = 10;
  13061. // ...
  13062. // ctx.fill();
  13063. // )
  13064. var shadowTemp = [
  13065. ['shadowBlur', 0],
  13066. ['shadowColor', '#000'],
  13067. ['shadowOffsetX', 0],
  13068. ['shadowOffsetY', 0]
  13069. ];
  13070. var fixClipWithShadow = function (orignalBrush) {
  13071. // version string can be: '11.0'
  13072. return (env$1.browser.ie && env$1.browser.version >= 11)
  13073. ? function () {
  13074. var clipPaths = this.__clipPaths;
  13075. var style = this.style;
  13076. var modified;
  13077. if (clipPaths) {
  13078. for (var i = 0; i < clipPaths.length; i++) {
  13079. var clipPath = clipPaths[i];
  13080. var shape = clipPath && clipPath.shape;
  13081. var type = clipPath && clipPath.type;
  13082. if (shape && (
  13083. (type === 'sector' && shape.startAngle === shape.endAngle)
  13084. || (type === 'rect' && (!shape.width || !shape.height))
  13085. )) {
  13086. for (var j = 0; j < shadowTemp.length; j++) {
  13087. // It is save to put shadowTemp static, because shadowTemp
  13088. // will be all modified each item brush called.
  13089. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13090. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13091. }
  13092. modified = true;
  13093. break;
  13094. }
  13095. }
  13096. }
  13097. orignalBrush.apply(this, arguments);
  13098. if (modified) {
  13099. for (var j = 0; j < shadowTemp.length; j++) {
  13100. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13101. }
  13102. }
  13103. }
  13104. : orignalBrush;
  13105. };
  13106. /**
  13107. * 扇形
  13108. * @module zrender/graphic/shape/Sector
  13109. */
  13110. var Sector = Path.extend({
  13111. type: 'sector',
  13112. shape: {
  13113. cx: 0,
  13114. cy: 0,
  13115. r0: 0,
  13116. r: 0,
  13117. startAngle: 0,
  13118. endAngle: Math.PI * 2,
  13119. clockwise: true
  13120. },
  13121. brush: fixClipWithShadow(Path.prototype.brush),
  13122. buildPath: function (ctx, shape) {
  13123. var x = shape.cx;
  13124. var y = shape.cy;
  13125. var r0 = Math.max(shape.r0 || 0, 0);
  13126. var r = Math.max(shape.r, 0);
  13127. var startAngle = shape.startAngle;
  13128. var endAngle = shape.endAngle;
  13129. var clockwise = shape.clockwise;
  13130. var unitX = Math.cos(startAngle);
  13131. var unitY = Math.sin(startAngle);
  13132. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13133. ctx.lineTo(unitX * r + x, unitY * r + y);
  13134. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13135. ctx.lineTo(
  13136. Math.cos(endAngle) * r0 + x,
  13137. Math.sin(endAngle) * r0 + y
  13138. );
  13139. if (r0 !== 0) {
  13140. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13141. }
  13142. ctx.closePath();
  13143. }
  13144. });
  13145. /**
  13146. * 圆环
  13147. * @module zrender/graphic/shape/Ring
  13148. */
  13149. var Ring = Path.extend({
  13150. type: 'ring',
  13151. shape: {
  13152. cx: 0,
  13153. cy: 0,
  13154. r: 0,
  13155. r0: 0
  13156. },
  13157. buildPath: function (ctx, shape) {
  13158. var x = shape.cx;
  13159. var y = shape.cy;
  13160. var PI2 = Math.PI * 2;
  13161. ctx.moveTo(x + shape.r, y);
  13162. ctx.arc(x, y, shape.r, 0, PI2, false);
  13163. ctx.moveTo(x + shape.r0, y);
  13164. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13165. }
  13166. });
  13167. /**
  13168. * Catmull-Rom spline 插值折线
  13169. * @module zrender/shape/util/smoothSpline
  13170. * @author pissang (https://www.github.com/pissang)
  13171. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13172. * errorrik (errorrik@gmail.com)
  13173. */
  13174. /**
  13175. * @inner
  13176. */
  13177. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13178. var v0 = (p2 - p0) * 0.5;
  13179. var v1 = (p3 - p1) * 0.5;
  13180. return (2 * (p1 - p2) + v0 + v1) * t3
  13181. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13182. + v0 * t + p1;
  13183. }
  13184. /**
  13185. * @alias module:zrender/shape/util/smoothSpline
  13186. * @param {Array} points 线段顶点数组
  13187. * @param {boolean} isLoop
  13188. * @return {Array}
  13189. */
  13190. var smoothSpline = function (points, isLoop) {
  13191. var len$$1 = points.length;
  13192. var ret = [];
  13193. var distance$$1 = 0;
  13194. for (var i = 1; i < len$$1; i++) {
  13195. distance$$1 += distance(points[i - 1], points[i]);
  13196. }
  13197. var segs = distance$$1 / 2;
  13198. segs = segs < len$$1 ? len$$1 : segs;
  13199. for (var i = 0; i < segs; i++) {
  13200. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13201. var idx = Math.floor(pos);
  13202. var w = pos - idx;
  13203. var p0;
  13204. var p1 = points[idx % len$$1];
  13205. var p2;
  13206. var p3;
  13207. if (!isLoop) {
  13208. p0 = points[idx === 0 ? idx : idx - 1];
  13209. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13210. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13211. }
  13212. else {
  13213. p0 = points[(idx - 1 + len$$1) % len$$1];
  13214. p2 = points[(idx + 1) % len$$1];
  13215. p3 = points[(idx + 2) % len$$1];
  13216. }
  13217. var w2 = w * w;
  13218. var w3 = w * w2;
  13219. ret.push([
  13220. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13221. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13222. ]);
  13223. }
  13224. return ret;
  13225. };
  13226. /**
  13227. * 贝塞尔平滑曲线
  13228. * @module zrender/shape/util/smoothBezier
  13229. * @author pissang (https://www.github.com/pissang)
  13230. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13231. * errorrik (errorrik@gmail.com)
  13232. */
  13233. /**
  13234. * 贝塞尔平滑曲线
  13235. * @alias module:zrender/shape/util/smoothBezier
  13236. * @param {Array} points 线段顶点数组
  13237. * @param {number} smooth 平滑等级, 0-1
  13238. * @param {boolean} isLoop
  13239. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13240. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13241. * 整个折线的包围盒做一个并集用来约束控制点。
  13242. * @param {Array} 计算出来的控制点数组
  13243. */
  13244. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13245. var cps = [];
  13246. var v = [];
  13247. var v1 = [];
  13248. var v2 = [];
  13249. var prevPoint;
  13250. var nextPoint;
  13251. var min$$1, max$$1;
  13252. if (constraint) {
  13253. min$$1 = [Infinity, Infinity];
  13254. max$$1 = [-Infinity, -Infinity];
  13255. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13256. min(min$$1, min$$1, points[i]);
  13257. max(max$$1, max$$1, points[i]);
  13258. }
  13259. // 与指定的包围盒做并集
  13260. min(min$$1, min$$1, constraint[0]);
  13261. max(max$$1, max$$1, constraint[1]);
  13262. }
  13263. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13264. var point = points[i];
  13265. if (isLoop) {
  13266. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13267. nextPoint = points[(i + 1) % len$$1];
  13268. }
  13269. else {
  13270. if (i === 0 || i === len$$1 - 1) {
  13271. cps.push(clone$1(points[i]));
  13272. continue;
  13273. }
  13274. else {
  13275. prevPoint = points[i - 1];
  13276. nextPoint = points[i + 1];
  13277. }
  13278. }
  13279. sub(v, nextPoint, prevPoint);
  13280. // use degree to scale the handle length
  13281. scale(v, v, smooth);
  13282. var d0 = distance(point, prevPoint);
  13283. var d1 = distance(point, nextPoint);
  13284. var sum = d0 + d1;
  13285. if (sum !== 0) {
  13286. d0 /= sum;
  13287. d1 /= sum;
  13288. }
  13289. scale(v1, v, -d0);
  13290. scale(v2, v, d1);
  13291. var cp0 = add([], point, v1);
  13292. var cp1 = add([], point, v2);
  13293. if (constraint) {
  13294. max(cp0, cp0, min$$1);
  13295. min(cp0, cp0, max$$1);
  13296. max(cp1, cp1, min$$1);
  13297. min(cp1, cp1, max$$1);
  13298. }
  13299. cps.push(cp0);
  13300. cps.push(cp1);
  13301. }
  13302. if (isLoop) {
  13303. cps.push(cps.shift());
  13304. }
  13305. return cps;
  13306. };
  13307. function buildPath$1(ctx, shape, closePath) {
  13308. var points = shape.points;
  13309. var smooth = shape.smooth;
  13310. if (points && points.length >= 2) {
  13311. if (smooth && smooth !== 'spline') {
  13312. var controlPoints = smoothBezier(
  13313. points, smooth, closePath, shape.smoothConstraint
  13314. );
  13315. ctx.moveTo(points[0][0], points[0][1]);
  13316. var len = points.length;
  13317. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13318. var cp1 = controlPoints[i * 2];
  13319. var cp2 = controlPoints[i * 2 + 1];
  13320. var p = points[(i + 1) % len];
  13321. ctx.bezierCurveTo(
  13322. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13323. );
  13324. }
  13325. }
  13326. else {
  13327. if (smooth === 'spline') {
  13328. points = smoothSpline(points, closePath);
  13329. }
  13330. ctx.moveTo(points[0][0], points[0][1]);
  13331. for (var i = 1, l = points.length; i < l; i++) {
  13332. ctx.lineTo(points[i][0], points[i][1]);
  13333. }
  13334. }
  13335. closePath && ctx.closePath();
  13336. }
  13337. }
  13338. /**
  13339. * 多边形
  13340. * @module zrender/shape/Polygon
  13341. */
  13342. var Polygon = Path.extend({
  13343. type: 'polygon',
  13344. shape: {
  13345. points: null,
  13346. smooth: false,
  13347. smoothConstraint: null
  13348. },
  13349. buildPath: function (ctx, shape) {
  13350. buildPath$1(ctx, shape, true);
  13351. }
  13352. });
  13353. /**
  13354. * @module zrender/graphic/shape/Polyline
  13355. */
  13356. var Polyline = Path.extend({
  13357. type: 'polyline',
  13358. shape: {
  13359. points: null,
  13360. smooth: false,
  13361. smoothConstraint: null
  13362. },
  13363. style: {
  13364. stroke: '#000',
  13365. fill: null
  13366. },
  13367. buildPath: function (ctx, shape) {
  13368. buildPath$1(ctx, shape, false);
  13369. }
  13370. });
  13371. /**
  13372. * 矩形
  13373. * @module zrender/graphic/shape/Rect
  13374. */
  13375. var Rect = Path.extend({
  13376. type: 'rect',
  13377. shape: {
  13378. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13379. // r缩写为1 相当于 [1, 1, 1, 1]
  13380. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13381. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13382. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13383. r: 0,
  13384. x: 0,
  13385. y: 0,
  13386. width: 0,
  13387. height: 0
  13388. },
  13389. buildPath: function (ctx, shape) {
  13390. var x = shape.x;
  13391. var y = shape.y;
  13392. var width = shape.width;
  13393. var height = shape.height;
  13394. if (!shape.r) {
  13395. ctx.rect(x, y, width, height);
  13396. }
  13397. else {
  13398. buildPath(ctx, shape);
  13399. }
  13400. ctx.closePath();
  13401. return;
  13402. }
  13403. });
  13404. /**
  13405. * 直线
  13406. * @module zrender/graphic/shape/Line
  13407. */
  13408. var Line = Path.extend({
  13409. type: 'line',
  13410. shape: {
  13411. // Start point
  13412. x1: 0,
  13413. y1: 0,
  13414. // End point
  13415. x2: 0,
  13416. y2: 0,
  13417. percent: 1
  13418. },
  13419. style: {
  13420. stroke: '#000',
  13421. fill: null
  13422. },
  13423. buildPath: function (ctx, shape) {
  13424. var x1 = shape.x1;
  13425. var y1 = shape.y1;
  13426. var x2 = shape.x2;
  13427. var y2 = shape.y2;
  13428. var percent = shape.percent;
  13429. if (percent === 0) {
  13430. return;
  13431. }
  13432. ctx.moveTo(x1, y1);
  13433. if (percent < 1) {
  13434. x2 = x1 * (1 - percent) + x2 * percent;
  13435. y2 = y1 * (1 - percent) + y2 * percent;
  13436. }
  13437. ctx.lineTo(x2, y2);
  13438. },
  13439. /**
  13440. * Get point at percent
  13441. * @param {number} percent
  13442. * @return {Array.<number>}
  13443. */
  13444. pointAt: function (p) {
  13445. var shape = this.shape;
  13446. return [
  13447. shape.x1 * (1 - p) + shape.x2 * p,
  13448. shape.y1 * (1 - p) + shape.y2 * p
  13449. ];
  13450. }
  13451. });
  13452. /**
  13453. * 贝塞尔曲线
  13454. * @module zrender/shape/BezierCurve
  13455. */
  13456. var out = [];
  13457. function someVectorAt(shape, t, isTangent) {
  13458. var cpx2 = shape.cpx2;
  13459. var cpy2 = shape.cpy2;
  13460. if (cpx2 === null || cpy2 === null) {
  13461. return [
  13462. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13463. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13464. ];
  13465. }
  13466. else {
  13467. return [
  13468. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13469. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13470. ];
  13471. }
  13472. }
  13473. var BezierCurve = Path.extend({
  13474. type: 'bezier-curve',
  13475. shape: {
  13476. x1: 0,
  13477. y1: 0,
  13478. x2: 0,
  13479. y2: 0,
  13480. cpx1: 0,
  13481. cpy1: 0,
  13482. // cpx2: 0,
  13483. // cpy2: 0
  13484. // Curve show percent, for animating
  13485. percent: 1
  13486. },
  13487. style: {
  13488. stroke: '#000',
  13489. fill: null
  13490. },
  13491. buildPath: function (ctx, shape) {
  13492. var x1 = shape.x1;
  13493. var y1 = shape.y1;
  13494. var x2 = shape.x2;
  13495. var y2 = shape.y2;
  13496. var cpx1 = shape.cpx1;
  13497. var cpy1 = shape.cpy1;
  13498. var cpx2 = shape.cpx2;
  13499. var cpy2 = shape.cpy2;
  13500. var percent = shape.percent;
  13501. if (percent === 0) {
  13502. return;
  13503. }
  13504. ctx.moveTo(x1, y1);
  13505. if (cpx2 == null || cpy2 == null) {
  13506. if (percent < 1) {
  13507. quadraticSubdivide(
  13508. x1, cpx1, x2, percent, out
  13509. );
  13510. cpx1 = out[1];
  13511. x2 = out[2];
  13512. quadraticSubdivide(
  13513. y1, cpy1, y2, percent, out
  13514. );
  13515. cpy1 = out[1];
  13516. y2 = out[2];
  13517. }
  13518. ctx.quadraticCurveTo(
  13519. cpx1, cpy1,
  13520. x2, y2
  13521. );
  13522. }
  13523. else {
  13524. if (percent < 1) {
  13525. cubicSubdivide(
  13526. x1, cpx1, cpx2, x2, percent, out
  13527. );
  13528. cpx1 = out[1];
  13529. cpx2 = out[2];
  13530. x2 = out[3];
  13531. cubicSubdivide(
  13532. y1, cpy1, cpy2, y2, percent, out
  13533. );
  13534. cpy1 = out[1];
  13535. cpy2 = out[2];
  13536. y2 = out[3];
  13537. }
  13538. ctx.bezierCurveTo(
  13539. cpx1, cpy1,
  13540. cpx2, cpy2,
  13541. x2, y2
  13542. );
  13543. }
  13544. },
  13545. /**
  13546. * Get point at percent
  13547. * @param {number} t
  13548. * @return {Array.<number>}
  13549. */
  13550. pointAt: function (t) {
  13551. return someVectorAt(this.shape, t, false);
  13552. },
  13553. /**
  13554. * Get tangent at percent
  13555. * @param {number} t
  13556. * @return {Array.<number>}
  13557. */
  13558. tangentAt: function (t) {
  13559. var p = someVectorAt(this.shape, t, true);
  13560. return normalize(p, p);
  13561. }
  13562. });
  13563. /**
  13564. * 圆弧
  13565. * @module zrender/graphic/shape/Arc
  13566. */
  13567. var Arc = Path.extend({
  13568. type: 'arc',
  13569. shape: {
  13570. cx: 0,
  13571. cy: 0,
  13572. r: 0,
  13573. startAngle: 0,
  13574. endAngle: Math.PI * 2,
  13575. clockwise: true
  13576. },
  13577. style: {
  13578. stroke: '#000',
  13579. fill: null
  13580. },
  13581. buildPath: function (ctx, shape) {
  13582. var x = shape.cx;
  13583. var y = shape.cy;
  13584. var r = Math.max(shape.r, 0);
  13585. var startAngle = shape.startAngle;
  13586. var endAngle = shape.endAngle;
  13587. var clockwise = shape.clockwise;
  13588. var unitX = Math.cos(startAngle);
  13589. var unitY = Math.sin(startAngle);
  13590. ctx.moveTo(unitX * r + x, unitY * r + y);
  13591. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13592. }
  13593. });
  13594. // CompoundPath to improve performance
  13595. var CompoundPath = Path.extend({
  13596. type: 'compound',
  13597. shape: {
  13598. paths: null
  13599. },
  13600. _updatePathDirty: function () {
  13601. var dirtyPath = this.__dirtyPath;
  13602. var paths = this.shape.paths;
  13603. for (var i = 0; i < paths.length; i++) {
  13604. // Mark as dirty if any subpath is dirty
  13605. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13606. }
  13607. this.__dirtyPath = dirtyPath;
  13608. this.__dirty = this.__dirty || dirtyPath;
  13609. },
  13610. beforeBrush: function () {
  13611. this._updatePathDirty();
  13612. var paths = this.shape.paths || [];
  13613. var scale = this.getGlobalScale();
  13614. // Update path scale
  13615. for (var i = 0; i < paths.length; i++) {
  13616. if (!paths[i].path) {
  13617. paths[i].createPathProxy();
  13618. }
  13619. paths[i].path.setScale(scale[0], scale[1]);
  13620. }
  13621. },
  13622. buildPath: function (ctx, shape) {
  13623. var paths = shape.paths || [];
  13624. for (var i = 0; i < paths.length; i++) {
  13625. paths[i].buildPath(ctx, paths[i].shape, true);
  13626. }
  13627. },
  13628. afterBrush: function () {
  13629. var paths = this.shape.paths || [];
  13630. for (var i = 0; i < paths.length; i++) {
  13631. paths[i].__dirtyPath = false;
  13632. }
  13633. },
  13634. getBoundingRect: function () {
  13635. this._updatePathDirty();
  13636. return Path.prototype.getBoundingRect.call(this);
  13637. }
  13638. });
  13639. /**
  13640. * @param {Array.<Object>} colorStops
  13641. */
  13642. var Gradient = function (colorStops) {
  13643. this.colorStops = colorStops || [];
  13644. };
  13645. Gradient.prototype = {
  13646. constructor: Gradient,
  13647. addColorStop: function (offset, color) {
  13648. this.colorStops.push({
  13649. offset: offset,
  13650. color: color
  13651. });
  13652. }
  13653. };
  13654. /**
  13655. * x, y, x2, y2 are all percent from 0 to 1
  13656. * @param {number} [x=0]
  13657. * @param {number} [y=0]
  13658. * @param {number} [x2=1]
  13659. * @param {number} [y2=0]
  13660. * @param {Array.<Object>} colorStops
  13661. * @param {boolean} [globalCoord=false]
  13662. */
  13663. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13664. // Should do nothing more in this constructor. Because gradient can be
  13665. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13666. // this constructor will not be called.
  13667. this.x = x == null ? 0 : x;
  13668. this.y = y == null ? 0 : y;
  13669. this.x2 = x2 == null ? 1 : x2;
  13670. this.y2 = y2 == null ? 0 : y2;
  13671. // Can be cloned
  13672. this.type = 'linear';
  13673. // If use global coord
  13674. this.global = globalCoord || false;
  13675. Gradient.call(this, colorStops);
  13676. };
  13677. LinearGradient.prototype = {
  13678. constructor: LinearGradient
  13679. };
  13680. inherits(LinearGradient, Gradient);
  13681. /**
  13682. * x, y, r are all percent from 0 to 1
  13683. * @param {number} [x=0.5]
  13684. * @param {number} [y=0.5]
  13685. * @param {number} [r=0.5]
  13686. * @param {Array.<Object>} [colorStops]
  13687. * @param {boolean} [globalCoord=false]
  13688. */
  13689. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13690. // Should do nothing more in this constructor. Because gradient can be
  13691. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13692. // this constructor will not be called.
  13693. this.x = x == null ? 0.5 : x;
  13694. this.y = y == null ? 0.5 : y;
  13695. this.r = r == null ? 0.5 : r;
  13696. // Can be cloned
  13697. this.type = 'radial';
  13698. // If use global coord
  13699. this.global = globalCoord || false;
  13700. Gradient.call(this, colorStops);
  13701. };
  13702. RadialGradient.prototype = {
  13703. constructor: RadialGradient
  13704. };
  13705. inherits(RadialGradient, Gradient);
  13706. /**
  13707. * Displayable for incremental rendering. It will be rendered in a separate layer
  13708. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13709. * addDisplayables will render the added displayables incremetally.
  13710. *
  13711. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13712. */
  13713. // TODO Style override ?
  13714. function IncrementalDisplayble(opts) {
  13715. Displayable.call(this, opts);
  13716. this._displayables = [];
  13717. this._temporaryDisplayables = [];
  13718. this._cursor = 0;
  13719. this.notClear = true;
  13720. }
  13721. IncrementalDisplayble.prototype.incremental = true;
  13722. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13723. this._displayables = [];
  13724. this._temporaryDisplayables = [];
  13725. this._cursor = 0;
  13726. this.dirty();
  13727. this.notClear = false;
  13728. };
  13729. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13730. if (notPersistent) {
  13731. this._temporaryDisplayables.push(displayable);
  13732. }
  13733. else {
  13734. this._displayables.push(displayable);
  13735. }
  13736. this.dirty();
  13737. };
  13738. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13739. notPersistent = notPersistent || false;
  13740. for (var i = 0; i < displayables.length; i++) {
  13741. this.addDisplayable(displayables[i], notPersistent);
  13742. }
  13743. };
  13744. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13745. for (var i = this._cursor; i < this._displayables.length; i++) {
  13746. cb && cb(this._displayables[i]);
  13747. }
  13748. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13749. cb && cb(this._temporaryDisplayables[i]);
  13750. }
  13751. };
  13752. IncrementalDisplayble.prototype.update = function () {
  13753. this.updateTransform();
  13754. for (var i = this._cursor; i < this._displayables.length; i++) {
  13755. var displayable = this._displayables[i];
  13756. // PENDING
  13757. displayable.parent = this;
  13758. displayable.update();
  13759. displayable.parent = null;
  13760. }
  13761. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13762. var displayable = this._temporaryDisplayables[i];
  13763. // PENDING
  13764. displayable.parent = this;
  13765. displayable.update();
  13766. displayable.parent = null;
  13767. }
  13768. };
  13769. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13770. // Render persistant displayables.
  13771. for (var i = this._cursor; i < this._displayables.length; i++) {
  13772. var displayable = this._displayables[i];
  13773. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13774. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13775. displayable.afterBrush && displayable.afterBrush(ctx);
  13776. }
  13777. this._cursor = i;
  13778. // Render temporary displayables.
  13779. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13780. var displayable = this._temporaryDisplayables[i];
  13781. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13782. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13783. displayable.afterBrush && displayable.afterBrush(ctx);
  13784. }
  13785. this._temporaryDisplayables = [];
  13786. this.notClear = true;
  13787. };
  13788. var m = [];
  13789. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13790. if (!this._rect) {
  13791. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13792. for (var i = 0; i < this._displayables.length; i++) {
  13793. var displayable = this._displayables[i];
  13794. var childRect = displayable.getBoundingRect().clone();
  13795. if (displayable.needLocalTransform()) {
  13796. childRect.applyTransform(displayable.getLocalTransform(m));
  13797. }
  13798. rect.union(childRect);
  13799. }
  13800. this._rect = rect;
  13801. }
  13802. return this._rect;
  13803. };
  13804. IncrementalDisplayble.prototype.contain = function (x, y) {
  13805. var localPos = this.transformCoordToLocal(x, y);
  13806. var rect = this.getBoundingRect();
  13807. if (rect.contain(localPos[0], localPos[1])) {
  13808. for (var i = 0; i < this._displayables.length; i++) {
  13809. var displayable = this._displayables[i];
  13810. if (displayable.contain(x, y)) {
  13811. return true;
  13812. }
  13813. }
  13814. }
  13815. return false;
  13816. };
  13817. inherits(IncrementalDisplayble, Displayable);
  13818. /*
  13819. * Licensed to the Apache Software Foundation (ASF) under one
  13820. * or more contributor license agreements. See the NOTICE file
  13821. * distributed with this work for additional information
  13822. * regarding copyright ownership. The ASF licenses this file
  13823. * to you under the Apache License, Version 2.0 (the
  13824. * "License"); you may not use this file except in compliance
  13825. * with the License. You may obtain a copy of the License at
  13826. *
  13827. * http://www.apache.org/licenses/LICENSE-2.0
  13828. *
  13829. * Unless required by applicable law or agreed to in writing,
  13830. * software distributed under the License is distributed on an
  13831. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13832. * KIND, either express or implied. See the License for the
  13833. * specific language governing permissions and limitations
  13834. * under the License.
  13835. */
  13836. var round = Math.round;
  13837. var mathMax$1 = Math.max;
  13838. var mathMin$1 = Math.min;
  13839. var EMPTY_OBJ = {};
  13840. /**
  13841. * Extend shape with parameters
  13842. */
  13843. function extendShape(opts) {
  13844. return Path.extend(opts);
  13845. }
  13846. /**
  13847. * Extend path
  13848. */
  13849. function extendPath(pathData, opts) {
  13850. return extendFromString(pathData, opts);
  13851. }
  13852. /**
  13853. * Create a path element from path data string
  13854. * @param {string} pathData
  13855. * @param {Object} opts
  13856. * @param {module:zrender/core/BoundingRect} rect
  13857. * @param {string} [layout=cover] 'center' or 'cover'
  13858. */
  13859. function makePath(pathData, opts, rect, layout) {
  13860. var path = createFromString(pathData, opts);
  13861. var boundingRect = path.getBoundingRect();
  13862. if (rect) {
  13863. if (layout === 'center') {
  13864. rect = centerGraphic(rect, boundingRect);
  13865. }
  13866. resizePath(path, rect);
  13867. }
  13868. return path;
  13869. }
  13870. /**
  13871. * Create a image element from image url
  13872. * @param {string} imageUrl image url
  13873. * @param {Object} opts options
  13874. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13875. * @param {string} [layout=cover] 'center' or 'cover'
  13876. */
  13877. function makeImage(imageUrl, rect, layout) {
  13878. var path = new ZImage({
  13879. style: {
  13880. image: imageUrl,
  13881. x: rect.x,
  13882. y: rect.y,
  13883. width: rect.width,
  13884. height: rect.height
  13885. },
  13886. onload: function (img) {
  13887. if (layout === 'center') {
  13888. var boundingRect = {
  13889. width: img.width,
  13890. height: img.height
  13891. };
  13892. path.setStyle(centerGraphic(rect, boundingRect));
  13893. }
  13894. }
  13895. });
  13896. return path;
  13897. }
  13898. /**
  13899. * Get position of centered element in bounding box.
  13900. *
  13901. * @param {Object} rect element local bounding box
  13902. * @param {Object} boundingRect constraint bounding box
  13903. * @return {Object} element position containing x, y, width, and height
  13904. */
  13905. function centerGraphic(rect, boundingRect) {
  13906. // Set rect to center, keep width / height ratio.
  13907. var aspect = boundingRect.width / boundingRect.height;
  13908. var width = rect.height * aspect;
  13909. var height;
  13910. if (width <= rect.width) {
  13911. height = rect.height;
  13912. }
  13913. else {
  13914. width = rect.width;
  13915. height = width / aspect;
  13916. }
  13917. var cx = rect.x + rect.width / 2;
  13918. var cy = rect.y + rect.height / 2;
  13919. return {
  13920. x: cx - width / 2,
  13921. y: cy - height / 2,
  13922. width: width,
  13923. height: height
  13924. };
  13925. }
  13926. var mergePath = mergePath$1;
  13927. /**
  13928. * Resize a path to fit the rect
  13929. * @param {module:zrender/graphic/Path} path
  13930. * @param {Object} rect
  13931. */
  13932. function resizePath(path, rect) {
  13933. if (!path.applyTransform) {
  13934. return;
  13935. }
  13936. var pathRect = path.getBoundingRect();
  13937. var m = pathRect.calculateTransform(rect);
  13938. path.applyTransform(m);
  13939. }
  13940. /**
  13941. * Sub pixel optimize line for canvas
  13942. *
  13943. * @param {Object} param
  13944. * @param {Object} [param.shape]
  13945. * @param {number} [param.shape.x1]
  13946. * @param {number} [param.shape.y1]
  13947. * @param {number} [param.shape.x2]
  13948. * @param {number} [param.shape.y2]
  13949. * @param {Object} [param.style]
  13950. * @param {number} [param.style.lineWidth]
  13951. * @return {Object} Modified param
  13952. */
  13953. function subPixelOptimizeLine(param) {
  13954. var shape = param.shape;
  13955. var lineWidth = param.style.lineWidth;
  13956. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  13957. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13958. }
  13959. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  13960. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13961. }
  13962. return param;
  13963. }
  13964. /**
  13965. * Sub pixel optimize rect for canvas
  13966. *
  13967. * @param {Object} param
  13968. * @param {Object} [param.shape]
  13969. * @param {number} [param.shape.x]
  13970. * @param {number} [param.shape.y]
  13971. * @param {number} [param.shape.width]
  13972. * @param {number} [param.shape.height]
  13973. * @param {Object} [param.style]
  13974. * @param {number} [param.style.lineWidth]
  13975. * @return {Object} Modified param
  13976. */
  13977. function subPixelOptimizeRect(param) {
  13978. var shape = param.shape;
  13979. var lineWidth = param.style.lineWidth;
  13980. var originX = shape.x;
  13981. var originY = shape.y;
  13982. var originWidth = shape.width;
  13983. var originHeight = shape.height;
  13984. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13985. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13986. shape.width = Math.max(
  13987. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13988. originWidth === 0 ? 0 : 1
  13989. );
  13990. shape.height = Math.max(
  13991. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13992. originHeight === 0 ? 0 : 1
  13993. );
  13994. return param;
  13995. }
  13996. /**
  13997. * Sub pixel optimize for canvas
  13998. *
  13999. * @param {number} position Coordinate, such as x, y
  14000. * @param {number} lineWidth Should be nonnegative integer.
  14001. * @param {boolean=} positiveOrNegative Default false (negative).
  14002. * @return {number} Optimized position.
  14003. */
  14004. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  14005. // Assure that (position + lineWidth / 2) is near integer edge,
  14006. // otherwise line will be fuzzy in canvas.
  14007. var doubledPosition = round(position * 2);
  14008. return (doubledPosition + round(lineWidth)) % 2 === 0
  14009. ? doubledPosition / 2
  14010. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14011. }
  14012. function hasFillOrStroke(fillOrStroke) {
  14013. return fillOrStroke != null && fillOrStroke != 'none';
  14014. }
  14015. function liftColor(color) {
  14016. return typeof color === 'string' ? lift(color, -0.1) : color;
  14017. }
  14018. /**
  14019. * @private
  14020. */
  14021. function cacheElementStl(el) {
  14022. if (el.__hoverStlDirty) {
  14023. var stroke = el.style.stroke;
  14024. var fill = el.style.fill;
  14025. // Create hoverStyle on mouseover
  14026. var hoverStyle = el.__hoverStl;
  14027. hoverStyle.fill = hoverStyle.fill
  14028. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  14029. hoverStyle.stroke = hoverStyle.stroke
  14030. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  14031. var normalStyle = {};
  14032. for (var name in hoverStyle) {
  14033. // See comment in `doSingleEnterHover`.
  14034. if (hoverStyle[name] != null) {
  14035. normalStyle[name] = el.style[name];
  14036. }
  14037. }
  14038. el.__normalStl = normalStyle;
  14039. el.__hoverStlDirty = false;
  14040. }
  14041. }
  14042. /**
  14043. * @private
  14044. */
  14045. function doSingleEnterHover(el) {
  14046. if (el.__isHover) {
  14047. return;
  14048. }
  14049. cacheElementStl(el);
  14050. if (el.useHoverLayer) {
  14051. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  14052. }
  14053. else {
  14054. var style = el.style;
  14055. var insideRollbackOpt = style.insideRollbackOpt;
  14056. // Consider case: only `position: 'top'` is set on emphasis, then text
  14057. // color should be returned to `autoColor`, rather than remain '#fff'.
  14058. // So we should rollback then apply again after style merging.
  14059. insideRollbackOpt && rollbackInsideStyle(style);
  14060. // styles can be:
  14061. // {
  14062. // label: {
  14063. // show: false,
  14064. // position: 'outside',
  14065. // fontSize: 18
  14066. // },
  14067. // emphasis: {
  14068. // label: {
  14069. // show: true
  14070. // }
  14071. // }
  14072. // },
  14073. // where properties of `emphasis` may not appear in `normal`. We previously use
  14074. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14075. // But consider rich text and setOption in merge mode, it is impossible to cover
  14076. // all properties in merge. So we use merge mode when setting style here, where
  14077. // only properties that is not `null/undefined` can be set. The disadventage:
  14078. // null/undefined can not be used to remove style any more in `emphasis`.
  14079. style.extendFrom(el.__hoverStl);
  14080. // Do not save `insideRollback`.
  14081. if (insideRollbackOpt) {
  14082. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  14083. // textFill may be rollbacked to null.
  14084. if (style.textFill == null) {
  14085. style.textFill = insideRollbackOpt.autoColor;
  14086. }
  14087. }
  14088. el.dirty(false);
  14089. el.z2 += 1;
  14090. }
  14091. el.__isHover = true;
  14092. }
  14093. /**
  14094. * @inner
  14095. */
  14096. function doSingleLeaveHover(el) {
  14097. if (!el.__isHover) {
  14098. return;
  14099. }
  14100. var normalStl = el.__normalStl;
  14101. if (el.useHoverLayer) {
  14102. el.__zr && el.__zr.removeHover(el);
  14103. }
  14104. else {
  14105. // Consider null/undefined value, should use
  14106. // `setStyle` but not `extendFrom(stl, true)`.
  14107. normalStl && el.setStyle(normalStl);
  14108. el.z2 -= 1;
  14109. }
  14110. el.__isHover = false;
  14111. }
  14112. /**
  14113. * @inner
  14114. */
  14115. function doEnterHover(el) {
  14116. el.type === 'group'
  14117. ? el.traverse(function (child) {
  14118. if (child.type !== 'group') {
  14119. doSingleEnterHover(child);
  14120. }
  14121. })
  14122. : doSingleEnterHover(el);
  14123. }
  14124. function doLeaveHover(el) {
  14125. el.type === 'group'
  14126. ? el.traverse(function (child) {
  14127. if (child.type !== 'group') {
  14128. doSingleLeaveHover(child);
  14129. }
  14130. })
  14131. : doSingleLeaveHover(el);
  14132. }
  14133. /**
  14134. * @inner
  14135. */
  14136. function setElementHoverStl(el, hoverStl) {
  14137. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14138. // Often used when item group has a label element and it's hoverStyle is different
  14139. el.__hoverStl = el.hoverStyle || hoverStl || {};
  14140. el.__hoverStlDirty = true;
  14141. if (el.__isHover) {
  14142. cacheElementStl(el);
  14143. }
  14144. }
  14145. /**
  14146. * @inner
  14147. */
  14148. function onElementMouseOver(e) {
  14149. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14150. return;
  14151. }
  14152. // Only if element is not in emphasis status
  14153. !this.__isEmphasis && doEnterHover(this);
  14154. }
  14155. /**
  14156. * @inner
  14157. */
  14158. function onElementMouseOut(e) {
  14159. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14160. return;
  14161. }
  14162. // Only if element is not in emphasis status
  14163. !this.__isEmphasis && doLeaveHover(this);
  14164. }
  14165. /**
  14166. * @inner
  14167. */
  14168. function enterEmphasis() {
  14169. this.__isEmphasis = true;
  14170. doEnterHover(this);
  14171. }
  14172. /**
  14173. * @inner
  14174. */
  14175. function leaveEmphasis() {
  14176. this.__isEmphasis = false;
  14177. doLeaveHover(this);
  14178. }
  14179. /**
  14180. * Set hover style of element.
  14181. * This method can be called repeatly without side-effects.
  14182. * @param {module:zrender/Element} el
  14183. * @param {Object} [hoverStyle]
  14184. * @param {Object} [opt]
  14185. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14186. * In touch device, mouseover event will be trigger on touchstart event
  14187. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14188. * conviniently use hoverStyle when tap on touch screen without additional
  14189. * code for compatibility.
  14190. * But if the chart/component has select feature, which usually also use
  14191. * hoverStyle, there might be conflict between 'select-highlight' and
  14192. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14193. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14194. * on touch device.
  14195. */
  14196. function setHoverStyle(el, hoverStyle, opt) {
  14197. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  14198. el.type === 'group'
  14199. ? el.traverse(function (child) {
  14200. if (child.type !== 'group') {
  14201. setElementHoverStl(child, hoverStyle);
  14202. }
  14203. })
  14204. : setElementHoverStl(el, hoverStyle);
  14205. // Duplicated function will be auto-ignored, see Eventful.js.
  14206. el.on('mouseover', onElementMouseOver)
  14207. .on('mouseout', onElementMouseOut);
  14208. // Emphasis, normal can be triggered manually
  14209. el.on('emphasis', enterEmphasis)
  14210. .on('normal', leaveEmphasis);
  14211. }
  14212. /**
  14213. * @param {Object|module:zrender/graphic/Style} normalStyle
  14214. * @param {Object} emphasisStyle
  14215. * @param {module:echarts/model/Model} normalModel
  14216. * @param {module:echarts/model/Model} emphasisModel
  14217. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14218. * @param {string|Function} [opt.defaultText]
  14219. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14220. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14221. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14222. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14223. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14224. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14225. * @param {Object} [normalSpecified]
  14226. * @param {Object} [emphasisSpecified]
  14227. */
  14228. function setLabelStyle(
  14229. normalStyle, emphasisStyle,
  14230. normalModel, emphasisModel,
  14231. opt,
  14232. normalSpecified, emphasisSpecified
  14233. ) {
  14234. opt = opt || EMPTY_OBJ;
  14235. var labelFetcher = opt.labelFetcher;
  14236. var labelDataIndex = opt.labelDataIndex;
  14237. var labelDimIndex = opt.labelDimIndex;
  14238. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14239. // is not supported util someone requests.
  14240. var showNormal = normalModel.getShallow('show');
  14241. var showEmphasis = emphasisModel.getShallow('show');
  14242. // Consider performance, only fetch label when necessary.
  14243. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14244. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14245. var baseText;
  14246. if (showNormal || showEmphasis) {
  14247. if (labelFetcher) {
  14248. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14249. }
  14250. if (baseText == null) {
  14251. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14252. }
  14253. }
  14254. var normalStyleText = showNormal ? baseText : null;
  14255. var emphasisStyleText = showEmphasis
  14256. ? retrieve2(
  14257. labelFetcher
  14258. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14259. : null,
  14260. baseText
  14261. )
  14262. : null;
  14263. // Optimize: If style.text is null, text will not be drawn.
  14264. if (normalStyleText != null || emphasisStyleText != null) {
  14265. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14266. // values have to be set on `normalStyle`.
  14267. // If we set default values on `emphasisStyle`, consider case:
  14268. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14269. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14270. // Then the 'red' will not work on emphasis.
  14271. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14272. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14273. }
  14274. normalStyle.text = normalStyleText;
  14275. emphasisStyle.text = emphasisStyleText;
  14276. }
  14277. /**
  14278. * Set basic textStyle properties.
  14279. * @param {Object|module:zrender/graphic/Style} textStyle
  14280. * @param {module:echarts/model/Model} model
  14281. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14282. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14283. * @param {boolean} [isEmphasis]
  14284. */
  14285. function setTextStyle(
  14286. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14287. ) {
  14288. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14289. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14290. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14291. return textStyle;
  14292. }
  14293. /**
  14294. * Set text option in the style.
  14295. * @deprecated
  14296. * @param {Object} textStyle
  14297. * @param {module:echarts/model/Model} labelModel
  14298. * @param {string|boolean} defaultColor Default text color.
  14299. * If set as false, it will be processed as a emphasis style.
  14300. */
  14301. function setText(textStyle, labelModel, defaultColor) {
  14302. var opt = {isRectText: true};
  14303. var isEmphasis;
  14304. if (defaultColor === false) {
  14305. isEmphasis = true;
  14306. }
  14307. else {
  14308. // Support setting color as 'auto' to get visual color.
  14309. opt.autoColor = defaultColor;
  14310. }
  14311. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14312. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14313. }
  14314. /**
  14315. * {
  14316. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14317. * isRectText: boolean,
  14318. * autoColor: string, specify a color when color is 'auto',
  14319. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14320. * If autoColor specified, it is used as default textFill.
  14321. * useInsideStyle:
  14322. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14323. * if `textFill` is not specified.
  14324. * `false`: Do not use inside style.
  14325. * `null/undefined`: use inside style if `isRectText` is true and
  14326. * `textFill` is not specified and textPosition contains `'inside'`.
  14327. * forceRich: boolean
  14328. * }
  14329. */
  14330. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14331. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14332. opt = opt || EMPTY_OBJ;
  14333. if (opt.isRectText) {
  14334. var textPosition = textStyleModel.getShallow('position')
  14335. || (isEmphasis ? null : 'inside');
  14336. // 'outside' is not a valid zr textPostion value, but used
  14337. // in bar series, and magric type should be considered.
  14338. textPosition === 'outside' && (textPosition = 'top');
  14339. textStyle.textPosition = textPosition;
  14340. textStyle.textOffset = textStyleModel.getShallow('offset');
  14341. var labelRotate = textStyleModel.getShallow('rotate');
  14342. labelRotate != null && (labelRotate *= Math.PI / 180);
  14343. textStyle.textRotation = labelRotate;
  14344. textStyle.textDistance = retrieve2(
  14345. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14346. );
  14347. }
  14348. var ecModel = textStyleModel.ecModel;
  14349. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14350. // Consider case:
  14351. // {
  14352. // data: [{
  14353. // value: 12,
  14354. // label: {
  14355. // rich: {
  14356. // // no 'a' here but using parent 'a'.
  14357. // }
  14358. // }
  14359. // }],
  14360. // rich: {
  14361. // a: { ... }
  14362. // }
  14363. // }
  14364. var richItemNames = getRichItemNames(textStyleModel);
  14365. var richResult;
  14366. if (richItemNames) {
  14367. richResult = {};
  14368. for (var name in richItemNames) {
  14369. if (richItemNames.hasOwnProperty(name)) {
  14370. // Cascade is supported in rich.
  14371. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14372. // In rich, never `disableBox`.
  14373. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14374. }
  14375. }
  14376. }
  14377. textStyle.rich = richResult;
  14378. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14379. if (opt.forceRich && !opt.textStyle) {
  14380. opt.textStyle = {};
  14381. }
  14382. return textStyle;
  14383. }
  14384. // Consider case:
  14385. // {
  14386. // data: [{
  14387. // value: 12,
  14388. // label: {
  14389. // rich: {
  14390. // // no 'a' here but using parent 'a'.
  14391. // }
  14392. // }
  14393. // }],
  14394. // rich: {
  14395. // a: { ... }
  14396. // }
  14397. // }
  14398. function getRichItemNames(textStyleModel) {
  14399. // Use object to remove duplicated names.
  14400. var richItemNameMap;
  14401. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14402. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14403. if (rich) {
  14404. richItemNameMap = richItemNameMap || {};
  14405. for (var name in rich) {
  14406. if (rich.hasOwnProperty(name)) {
  14407. richItemNameMap[name] = 1;
  14408. }
  14409. }
  14410. }
  14411. textStyleModel = textStyleModel.parentModel;
  14412. }
  14413. return richItemNameMap;
  14414. }
  14415. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14416. // In merge mode, default value should not be given.
  14417. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14418. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14419. || globalTextStyle.color;
  14420. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14421. || globalTextStyle.textBorderColor;
  14422. textStyle.textStrokeWidth = retrieve2(
  14423. textStyleModel.getShallow('textBorderWidth'),
  14424. globalTextStyle.textBorderWidth
  14425. );
  14426. if (!isEmphasis) {
  14427. if (isBlock) {
  14428. // Always set `insideRollback`, for clearing previous.
  14429. var originalTextPosition = textStyle.textPosition;
  14430. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14431. // Save original textPosition, because style.textPosition will be repalced by
  14432. // real location (like [10, 30]) in zrender.
  14433. textStyle.insideOriginalTextPosition = originalTextPosition;
  14434. textStyle.insideRollbackOpt = opt;
  14435. }
  14436. // Set default finally.
  14437. if (textStyle.textFill == null) {
  14438. textStyle.textFill = opt.autoColor;
  14439. }
  14440. }
  14441. // Do not use `getFont` here, because merge should be supported, where
  14442. // part of these properties may be changed in emphasis style, and the
  14443. // others should remain their original value got from normal style.
  14444. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14445. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14446. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14447. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14448. textStyle.textAlign = textStyleModel.getShallow('align');
  14449. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14450. || textStyleModel.getShallow('baseline');
  14451. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14452. textStyle.textWidth = textStyleModel.getShallow('width');
  14453. textStyle.textHeight = textStyleModel.getShallow('height');
  14454. textStyle.textTag = textStyleModel.getShallow('tag');
  14455. if (!isBlock || !opt.disableBox) {
  14456. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14457. textStyle.textPadding = textStyleModel.getShallow('padding');
  14458. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14459. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14460. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14461. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14462. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14463. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14464. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14465. }
  14466. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14467. || globalTextStyle.textShadowColor;
  14468. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14469. || globalTextStyle.textShadowBlur;
  14470. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14471. || globalTextStyle.textShadowOffsetX;
  14472. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14473. || globalTextStyle.textShadowOffsetY;
  14474. }
  14475. function getAutoColor(color, opt) {
  14476. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14477. }
  14478. function applyInsideStyle(textStyle, textPosition, opt) {
  14479. var useInsideStyle = opt.useInsideStyle;
  14480. var insideRollback;
  14481. if (textStyle.textFill == null
  14482. && useInsideStyle !== false
  14483. && (useInsideStyle === true
  14484. || (opt.isRectText
  14485. && textPosition
  14486. // textPosition can be [10, 30]
  14487. && typeof textPosition === 'string'
  14488. && textPosition.indexOf('inside') >= 0
  14489. )
  14490. )
  14491. ) {
  14492. insideRollback = {
  14493. textFill: null,
  14494. textStroke: textStyle.textStroke,
  14495. textStrokeWidth: textStyle.textStrokeWidth
  14496. };
  14497. textStyle.textFill = '#fff';
  14498. // Consider text with #fff overflow its container.
  14499. if (textStyle.textStroke == null) {
  14500. textStyle.textStroke = opt.autoColor;
  14501. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14502. }
  14503. }
  14504. return insideRollback;
  14505. }
  14506. function rollbackInsideStyle(style) {
  14507. var insideRollback = style.insideRollback;
  14508. if (insideRollback) {
  14509. style.textFill = insideRollback.textFill;
  14510. style.textStroke = insideRollback.textStroke;
  14511. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14512. }
  14513. }
  14514. function getFont(opt, ecModel) {
  14515. // ecModel or default text style model.
  14516. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14517. return trim([
  14518. // FIXME in node-canvas fontWeight is before fontStyle
  14519. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14520. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14521. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14522. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14523. ].join(' '));
  14524. }
  14525. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14526. if (typeof dataIndex === 'function') {
  14527. cb = dataIndex;
  14528. dataIndex = null;
  14529. }
  14530. // Do not check 'animation' property directly here. Consider this case:
  14531. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14532. // but its parent model (`seriesModel`) does.
  14533. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14534. if (animationEnabled) {
  14535. var postfix = isUpdate ? 'Update' : '';
  14536. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14537. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14538. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14539. if (typeof animationDelay === 'function') {
  14540. animationDelay = animationDelay(
  14541. dataIndex,
  14542. animatableModel.getAnimationDelayParams
  14543. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14544. : null
  14545. );
  14546. }
  14547. if (typeof duration === 'function') {
  14548. duration = duration(dataIndex);
  14549. }
  14550. duration > 0
  14551. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14552. : (el.stopAnimation(), el.attr(props), cb && cb());
  14553. }
  14554. else {
  14555. el.stopAnimation();
  14556. el.attr(props);
  14557. cb && cb();
  14558. }
  14559. }
  14560. /**
  14561. * Update graphic element properties with or without animation according to the
  14562. * configuration in series.
  14563. *
  14564. * Caution: this method will stop previous animation.
  14565. * So if do not use this method to one element twice before
  14566. * animation starts, unless you know what you are doing.
  14567. *
  14568. * @param {module:zrender/Element} el
  14569. * @param {Object} props
  14570. * @param {module:echarts/model/Model} [animatableModel]
  14571. * @param {number} [dataIndex]
  14572. * @param {Function} [cb]
  14573. * @example
  14574. * graphic.updateProps(el, {
  14575. * position: [100, 100]
  14576. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14577. * // Or
  14578. * graphic.updateProps(el, {
  14579. * position: [100, 100]
  14580. * }, seriesModel, function () { console.log('Animation done!'); });
  14581. */
  14582. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14583. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14584. }
  14585. /**
  14586. * Init graphic element properties with or without animation according to the
  14587. * configuration in series.
  14588. *
  14589. * Caution: this method will stop previous animation.
  14590. * So if do not use this method to one element twice before
  14591. * animation starts, unless you know what you are doing.
  14592. *
  14593. * @param {module:zrender/Element} el
  14594. * @param {Object} props
  14595. * @param {module:echarts/model/Model} [animatableModel]
  14596. * @param {number} [dataIndex]
  14597. * @param {Function} cb
  14598. */
  14599. function initProps(el, props, animatableModel, dataIndex, cb) {
  14600. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14601. }
  14602. /**
  14603. * Get transform matrix of target (param target),
  14604. * in coordinate of its ancestor (param ancestor)
  14605. *
  14606. * @param {module:zrender/mixin/Transformable} target
  14607. * @param {module:zrender/mixin/Transformable} [ancestor]
  14608. */
  14609. function getTransform(target, ancestor) {
  14610. var mat = identity([]);
  14611. while (target && target !== ancestor) {
  14612. mul$1(mat, target.getLocalTransform(), mat);
  14613. target = target.parent;
  14614. }
  14615. return mat;
  14616. }
  14617. /**
  14618. * Apply transform to an vertex.
  14619. * @param {Array.<number>} target [x, y]
  14620. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14621. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14622. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14623. * @param {boolean=} invert Whether use invert matrix.
  14624. * @return {Array.<number>} [x, y]
  14625. */
  14626. function applyTransform$1(target, transform, invert$$1) {
  14627. if (transform && !isArrayLike(transform)) {
  14628. transform = Transformable.getLocalTransform(transform);
  14629. }
  14630. if (invert$$1) {
  14631. transform = invert([], transform);
  14632. }
  14633. return applyTransform([], target, transform);
  14634. }
  14635. /**
  14636. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14637. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14638. * @param {boolean=} invert Whether use invert matrix.
  14639. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14640. */
  14641. function transformDirection(direction, transform, invert$$1) {
  14642. // Pick a base, ensure that transform result will not be (0, 0).
  14643. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14644. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14645. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14646. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14647. var vertex = [
  14648. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14649. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14650. ];
  14651. vertex = applyTransform$1(vertex, transform, invert$$1);
  14652. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14653. ? (vertex[0] > 0 ? 'right' : 'left')
  14654. : (vertex[1] > 0 ? 'bottom' : 'top');
  14655. }
  14656. /**
  14657. * Apply group transition animation from g1 to g2.
  14658. * If no animatableModel, no animation.
  14659. */
  14660. function groupTransition(g1, g2, animatableModel, cb) {
  14661. if (!g1 || !g2) {
  14662. return;
  14663. }
  14664. function getElMap(g) {
  14665. var elMap = {};
  14666. g.traverse(function (el) {
  14667. if (!el.isGroup && el.anid) {
  14668. elMap[el.anid] = el;
  14669. }
  14670. });
  14671. return elMap;
  14672. }
  14673. function getAnimatableProps(el) {
  14674. var obj = {
  14675. position: clone$1(el.position),
  14676. rotation: el.rotation
  14677. };
  14678. if (el.shape) {
  14679. obj.shape = extend({}, el.shape);
  14680. }
  14681. return obj;
  14682. }
  14683. var elMap1 = getElMap(g1);
  14684. g2.traverse(function (el) {
  14685. if (!el.isGroup && el.anid) {
  14686. var oldEl = elMap1[el.anid];
  14687. if (oldEl) {
  14688. var newProp = getAnimatableProps(el);
  14689. el.attr(getAnimatableProps(oldEl));
  14690. updateProps(el, newProp, animatableModel, el.dataIndex);
  14691. }
  14692. // else {
  14693. // if (el.previousProps) {
  14694. // graphic.updateProps
  14695. // }
  14696. // }
  14697. }
  14698. });
  14699. }
  14700. /**
  14701. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14702. * @param {Object} rect {x, y, width, height}
  14703. * @return {Array.<Array.<number>>} A new clipped points.
  14704. */
  14705. function clipPointsByRect(points, rect) {
  14706. return map(points, function (point) {
  14707. var x = point[0];
  14708. x = mathMax$1(x, rect.x);
  14709. x = mathMin$1(x, rect.x + rect.width);
  14710. var y = point[1];
  14711. y = mathMax$1(y, rect.y);
  14712. y = mathMin$1(y, rect.y + rect.height);
  14713. return [x, y];
  14714. });
  14715. }
  14716. /**
  14717. * @param {Object} targetRect {x, y, width, height}
  14718. * @param {Object} rect {x, y, width, height}
  14719. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14720. */
  14721. function clipRectByRect(targetRect, rect) {
  14722. var x = mathMax$1(targetRect.x, rect.x);
  14723. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14724. var y = mathMax$1(targetRect.y, rect.y);
  14725. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14726. if (x2 >= x && y2 >= y) {
  14727. return {
  14728. x: x,
  14729. y: y,
  14730. width: x2 - x,
  14731. height: y2 - y
  14732. };
  14733. }
  14734. }
  14735. /**
  14736. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14737. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14738. * @param {Object} [rect] {x, y, width, height}
  14739. * @return {module:zrender/Element} Icon path or image element.
  14740. */
  14741. function createIcon(iconStr, opt, rect) {
  14742. opt = extend({rectHover: true}, opt);
  14743. var style = opt.style = {strokeNoScale: true};
  14744. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14745. if (iconStr) {
  14746. return iconStr.indexOf('image://') === 0
  14747. ? (
  14748. style.image = iconStr.slice(8),
  14749. defaults(style, rect),
  14750. new ZImage(opt)
  14751. )
  14752. : (
  14753. makePath(
  14754. iconStr.replace('path://', ''),
  14755. opt,
  14756. rect,
  14757. 'center'
  14758. )
  14759. );
  14760. }
  14761. }
  14762. var graphic = (Object.freeze || Object)({
  14763. extendShape: extendShape,
  14764. extendPath: extendPath,
  14765. makePath: makePath,
  14766. makeImage: makeImage,
  14767. mergePath: mergePath,
  14768. resizePath: resizePath,
  14769. subPixelOptimizeLine: subPixelOptimizeLine,
  14770. subPixelOptimizeRect: subPixelOptimizeRect,
  14771. subPixelOptimize: subPixelOptimize,
  14772. setHoverStyle: setHoverStyle,
  14773. setLabelStyle: setLabelStyle,
  14774. setTextStyle: setTextStyle,
  14775. setText: setText,
  14776. getFont: getFont,
  14777. updateProps: updateProps,
  14778. initProps: initProps,
  14779. getTransform: getTransform,
  14780. applyTransform: applyTransform$1,
  14781. transformDirection: transformDirection,
  14782. groupTransition: groupTransition,
  14783. clipPointsByRect: clipPointsByRect,
  14784. clipRectByRect: clipRectByRect,
  14785. createIcon: createIcon,
  14786. Group: Group,
  14787. Image: ZImage,
  14788. Text: Text,
  14789. Circle: Circle,
  14790. Sector: Sector,
  14791. Ring: Ring,
  14792. Polygon: Polygon,
  14793. Polyline: Polyline,
  14794. Rect: Rect,
  14795. Line: Line,
  14796. BezierCurve: BezierCurve,
  14797. Arc: Arc,
  14798. IncrementalDisplayable: IncrementalDisplayble,
  14799. CompoundPath: CompoundPath,
  14800. LinearGradient: LinearGradient,
  14801. RadialGradient: RadialGradient,
  14802. BoundingRect: BoundingRect
  14803. });
  14804. /*
  14805. * Licensed to the Apache Software Foundation (ASF) under one
  14806. * or more contributor license agreements. See the NOTICE file
  14807. * distributed with this work for additional information
  14808. * regarding copyright ownership. The ASF licenses this file
  14809. * to you under the Apache License, Version 2.0 (the
  14810. * "License"); you may not use this file except in compliance
  14811. * with the License. You may obtain a copy of the License at
  14812. *
  14813. * http://www.apache.org/licenses/LICENSE-2.0
  14814. *
  14815. * Unless required by applicable law or agreed to in writing,
  14816. * software distributed under the License is distributed on an
  14817. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14818. * KIND, either express or implied. See the License for the
  14819. * specific language governing permissions and limitations
  14820. * under the License.
  14821. */
  14822. var PATH_COLOR = ['textStyle', 'color'];
  14823. var textStyleMixin = {
  14824. /**
  14825. * Get color property or get color from option.textStyle.color
  14826. * @param {boolean} [isEmphasis]
  14827. * @return {string}
  14828. */
  14829. getTextColor: function (isEmphasis) {
  14830. var ecModel = this.ecModel;
  14831. return this.getShallow('color')
  14832. || (
  14833. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14834. );
  14835. },
  14836. /**
  14837. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14838. * @return {string}
  14839. */
  14840. getFont: function () {
  14841. return getFont({
  14842. fontStyle: this.getShallow('fontStyle'),
  14843. fontWeight: this.getShallow('fontWeight'),
  14844. fontSize: this.getShallow('fontSize'),
  14845. fontFamily: this.getShallow('fontFamily')
  14846. }, this.ecModel);
  14847. },
  14848. getTextRect: function (text) {
  14849. return getBoundingRect(
  14850. text,
  14851. this.getFont(),
  14852. this.getShallow('align'),
  14853. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14854. this.getShallow('padding'),
  14855. this.getShallow('rich'),
  14856. this.getShallow('truncateText')
  14857. );
  14858. }
  14859. };
  14860. /*
  14861. * Licensed to the Apache Software Foundation (ASF) under one
  14862. * or more contributor license agreements. See the NOTICE file
  14863. * distributed with this work for additional information
  14864. * regarding copyright ownership. The ASF licenses this file
  14865. * to you under the Apache License, Version 2.0 (the
  14866. * "License"); you may not use this file except in compliance
  14867. * with the License. You may obtain a copy of the License at
  14868. *
  14869. * http://www.apache.org/licenses/LICENSE-2.0
  14870. *
  14871. * Unless required by applicable law or agreed to in writing,
  14872. * software distributed under the License is distributed on an
  14873. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14874. * KIND, either express or implied. See the License for the
  14875. * specific language governing permissions and limitations
  14876. * under the License.
  14877. */
  14878. var getItemStyle = makeStyleMapper(
  14879. [
  14880. ['fill', 'color'],
  14881. ['stroke', 'borderColor'],
  14882. ['lineWidth', 'borderWidth'],
  14883. ['opacity'],
  14884. ['shadowBlur'],
  14885. ['shadowOffsetX'],
  14886. ['shadowOffsetY'],
  14887. ['shadowColor'],
  14888. ['textPosition'],
  14889. ['textAlign']
  14890. ]
  14891. );
  14892. var itemStyleMixin = {
  14893. getItemStyle: function (excludes, includes) {
  14894. var style = getItemStyle(this, excludes, includes);
  14895. var lineDash = this.getBorderLineDash();
  14896. lineDash && (style.lineDash = lineDash);
  14897. return style;
  14898. },
  14899. getBorderLineDash: function () {
  14900. var lineType = this.get('borderType');
  14901. return (lineType === 'solid' || lineType == null) ? null
  14902. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14903. }
  14904. };
  14905. /*
  14906. * Licensed to the Apache Software Foundation (ASF) under one
  14907. * or more contributor license agreements. See the NOTICE file
  14908. * distributed with this work for additional information
  14909. * regarding copyright ownership. The ASF licenses this file
  14910. * to you under the Apache License, Version 2.0 (the
  14911. * "License"); you may not use this file except in compliance
  14912. * with the License. You may obtain a copy of the License at
  14913. *
  14914. * http://www.apache.org/licenses/LICENSE-2.0
  14915. *
  14916. * Unless required by applicable law or agreed to in writing,
  14917. * software distributed under the License is distributed on an
  14918. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14919. * KIND, either express or implied. See the License for the
  14920. * specific language governing permissions and limitations
  14921. * under the License.
  14922. */
  14923. /**
  14924. * @module echarts/model/Model
  14925. */
  14926. var mixin$1 = mixin;
  14927. var inner = makeInner();
  14928. /**
  14929. * @alias module:echarts/model/Model
  14930. * @constructor
  14931. * @param {Object} option
  14932. * @param {module:echarts/model/Model} [parentModel]
  14933. * @param {module:echarts/model/Global} [ecModel]
  14934. */
  14935. function Model(option, parentModel, ecModel) {
  14936. /**
  14937. * @type {module:echarts/model/Model}
  14938. * @readOnly
  14939. */
  14940. this.parentModel = parentModel;
  14941. /**
  14942. * @type {module:echarts/model/Global}
  14943. * @readOnly
  14944. */
  14945. this.ecModel = ecModel;
  14946. /**
  14947. * @type {Object}
  14948. * @protected
  14949. */
  14950. this.option = option;
  14951. // Simple optimization
  14952. // if (this.init) {
  14953. // if (arguments.length <= 4) {
  14954. // this.init(option, parentModel, ecModel, extraOpt);
  14955. // }
  14956. // else {
  14957. // this.init.apply(this, arguments);
  14958. // }
  14959. // }
  14960. }
  14961. Model.prototype = {
  14962. constructor: Model,
  14963. /**
  14964. * Model 的初始化函数
  14965. * @param {Object} option
  14966. */
  14967. init: null,
  14968. /**
  14969. * 从新的 Option merge
  14970. */
  14971. mergeOption: function (option) {
  14972. merge(this.option, option, true);
  14973. },
  14974. /**
  14975. * @param {string|Array.<string>} path
  14976. * @param {boolean} [ignoreParent=false]
  14977. * @return {*}
  14978. */
  14979. get: function (path, ignoreParent) {
  14980. if (path == null) {
  14981. return this.option;
  14982. }
  14983. return doGet(
  14984. this.option,
  14985. this.parsePath(path),
  14986. !ignoreParent && getParent(this, path)
  14987. );
  14988. },
  14989. /**
  14990. * @param {string} key
  14991. * @param {boolean} [ignoreParent=false]
  14992. * @return {*}
  14993. */
  14994. getShallow: function (key, ignoreParent) {
  14995. var option = this.option;
  14996. var val = option == null ? option : option[key];
  14997. var parentModel = !ignoreParent && getParent(this, key);
  14998. if (val == null && parentModel) {
  14999. val = parentModel.getShallow(key);
  15000. }
  15001. return val;
  15002. },
  15003. /**
  15004. * @param {string|Array.<string>} [path]
  15005. * @param {module:echarts/model/Model} [parentModel]
  15006. * @return {module:echarts/model/Model}
  15007. */
  15008. getModel: function (path, parentModel) {
  15009. var obj = path == null
  15010. ? this.option
  15011. : doGet(this.option, path = this.parsePath(path));
  15012. var thisParentModel;
  15013. parentModel = parentModel || (
  15014. (thisParentModel = getParent(this, path))
  15015. && thisParentModel.getModel(path)
  15016. );
  15017. return new Model(obj, parentModel, this.ecModel);
  15018. },
  15019. /**
  15020. * If model has option
  15021. */
  15022. isEmpty: function () {
  15023. return this.option == null;
  15024. },
  15025. restoreData: function () {},
  15026. // Pending
  15027. clone: function () {
  15028. var Ctor = this.constructor;
  15029. return new Ctor(clone(this.option));
  15030. },
  15031. setReadOnly: function (properties) {
  15032. // clazzUtil.setReadOnly(this, properties);
  15033. },
  15034. // If path is null/undefined, return null/undefined.
  15035. parsePath: function(path) {
  15036. if (typeof path === 'string') {
  15037. path = path.split('.');
  15038. }
  15039. return path;
  15040. },
  15041. /**
  15042. * @param {Function} getParentMethod
  15043. * param {Array.<string>|string} path
  15044. * return {module:echarts/model/Model}
  15045. */
  15046. customizeGetParent: function (getParentMethod) {
  15047. inner(this).getParent = getParentMethod;
  15048. },
  15049. isAnimationEnabled: function () {
  15050. if (!env$1.node) {
  15051. if (this.option.animation != null) {
  15052. return !!this.option.animation;
  15053. }
  15054. else if (this.parentModel) {
  15055. return this.parentModel.isAnimationEnabled();
  15056. }
  15057. }
  15058. }
  15059. };
  15060. function doGet(obj, pathArr, parentModel) {
  15061. for (var i = 0; i < pathArr.length; i++) {
  15062. // Ignore empty
  15063. if (!pathArr[i]) {
  15064. continue;
  15065. }
  15066. // obj could be number/string/... (like 0)
  15067. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  15068. if (obj == null) {
  15069. break;
  15070. }
  15071. }
  15072. if (obj == null && parentModel) {
  15073. obj = parentModel.get(pathArr);
  15074. }
  15075. return obj;
  15076. }
  15077. // `path` can be null/undefined
  15078. function getParent(model, path) {
  15079. var getParentMethod = inner(model).getParent;
  15080. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15081. }
  15082. // Enable Model.extend.
  15083. enableClassExtend(Model);
  15084. enableClassCheck(Model);
  15085. mixin$1(Model, lineStyleMixin);
  15086. mixin$1(Model, areaStyleMixin);
  15087. mixin$1(Model, textStyleMixin);
  15088. mixin$1(Model, itemStyleMixin);
  15089. /*
  15090. * Licensed to the Apache Software Foundation (ASF) under one
  15091. * or more contributor license agreements. See the NOTICE file
  15092. * distributed with this work for additional information
  15093. * regarding copyright ownership. The ASF licenses this file
  15094. * to you under the Apache License, Version 2.0 (the
  15095. * "License"); you may not use this file except in compliance
  15096. * with the License. You may obtain a copy of the License at
  15097. *
  15098. * http://www.apache.org/licenses/LICENSE-2.0
  15099. *
  15100. * Unless required by applicable law or agreed to in writing,
  15101. * software distributed under the License is distributed on an
  15102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15103. * KIND, either express or implied. See the License for the
  15104. * specific language governing permissions and limitations
  15105. * under the License.
  15106. */
  15107. var base = 0;
  15108. /**
  15109. * @public
  15110. * @param {string} type
  15111. * @return {string}
  15112. */
  15113. function getUID(type) {
  15114. // Considering the case of crossing js context,
  15115. // use Math.random to make id as unique as possible.
  15116. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  15117. }
  15118. /**
  15119. * @inner
  15120. */
  15121. function enableSubTypeDefaulter(entity) {
  15122. var subTypeDefaulters = {};
  15123. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15124. componentType = parseClassType$1(componentType);
  15125. subTypeDefaulters[componentType.main] = defaulter;
  15126. };
  15127. entity.determineSubType = function (componentType, option) {
  15128. var type = option.type;
  15129. if (!type) {
  15130. var componentTypeMain = parseClassType$1(componentType).main;
  15131. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15132. type = subTypeDefaulters[componentTypeMain](option);
  15133. }
  15134. }
  15135. return type;
  15136. };
  15137. return entity;
  15138. }
  15139. /**
  15140. * Topological travel on Activity Network (Activity On Vertices).
  15141. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15142. *
  15143. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15144. *
  15145. * If there is circle dependencey, Error will be thrown.
  15146. *
  15147. */
  15148. function enableTopologicalTravel(entity, dependencyGetter) {
  15149. /**
  15150. * @public
  15151. * @param {Array.<string>} targetNameList Target Component type list.
  15152. * Can be ['aa', 'bb', 'aa.xx']
  15153. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15154. * @param {Function} callback Params: componentType, dependencies.
  15155. * @param {Object} context Scope of callback.
  15156. */
  15157. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15158. if (!targetNameList.length) {
  15159. return;
  15160. }
  15161. var result = makeDepndencyGraph(fullNameList);
  15162. var graph = result.graph;
  15163. var stack = result.noEntryList;
  15164. var targetNameSet = {};
  15165. each$1(targetNameList, function (name) {
  15166. targetNameSet[name] = true;
  15167. });
  15168. while (stack.length) {
  15169. var currComponentType = stack.pop();
  15170. var currVertex = graph[currComponentType];
  15171. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15172. if (isInTargetNameSet) {
  15173. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15174. delete targetNameSet[currComponentType];
  15175. }
  15176. each$1(
  15177. currVertex.successor,
  15178. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15179. );
  15180. }
  15181. each$1(targetNameSet, function () {
  15182. throw new Error('Circle dependency may exists');
  15183. });
  15184. function removeEdge(succComponentType) {
  15185. graph[succComponentType].entryCount--;
  15186. if (graph[succComponentType].entryCount === 0) {
  15187. stack.push(succComponentType);
  15188. }
  15189. }
  15190. // Consider this case: legend depends on series, and we call
  15191. // chart.setOption({series: [...]}), where only series is in option.
  15192. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15193. // not be called, but only sereis.mergeOption is called. Thus legend
  15194. // have no chance to update its local record about series (like which
  15195. // name of series is available in legend).
  15196. function removeEdgeAndAdd(succComponentType) {
  15197. targetNameSet[succComponentType] = true;
  15198. removeEdge(succComponentType);
  15199. }
  15200. };
  15201. /**
  15202. * DepndencyGraph: {Object}
  15203. * key: conponentType,
  15204. * value: {
  15205. * successor: [conponentTypes...],
  15206. * originalDeps: [conponentTypes...],
  15207. * entryCount: {number}
  15208. * }
  15209. */
  15210. function makeDepndencyGraph(fullNameList) {
  15211. var graph = {};
  15212. var noEntryList = [];
  15213. each$1(fullNameList, function (name) {
  15214. var thisItem = createDependencyGraphItem(graph, name);
  15215. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15216. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15217. thisItem.entryCount = availableDeps.length;
  15218. if (thisItem.entryCount === 0) {
  15219. noEntryList.push(name);
  15220. }
  15221. each$1(availableDeps, function (dependentName) {
  15222. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15223. thisItem.predecessor.push(dependentName);
  15224. }
  15225. var thatItem = createDependencyGraphItem(graph, dependentName);
  15226. if (indexOf(thatItem.successor, dependentName) < 0) {
  15227. thatItem.successor.push(name);
  15228. }
  15229. });
  15230. });
  15231. return {graph: graph, noEntryList: noEntryList};
  15232. }
  15233. function createDependencyGraphItem(graph, name) {
  15234. if (!graph[name]) {
  15235. graph[name] = {predecessor: [], successor: []};
  15236. }
  15237. return graph[name];
  15238. }
  15239. function getAvailableDependencies(originalDeps, fullNameList) {
  15240. var availableDeps = [];
  15241. each$1(originalDeps, function (dep) {
  15242. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15243. });
  15244. return availableDeps;
  15245. }
  15246. }
  15247. /*
  15248. * Licensed to the Apache Software Foundation (ASF) under one
  15249. * or more contributor license agreements. See the NOTICE file
  15250. * distributed with this work for additional information
  15251. * regarding copyright ownership. The ASF licenses this file
  15252. * to you under the Apache License, Version 2.0 (the
  15253. * "License"); you may not use this file except in compliance
  15254. * with the License. You may obtain a copy of the License at
  15255. *
  15256. * http://www.apache.org/licenses/LICENSE-2.0
  15257. *
  15258. * Unless required by applicable law or agreed to in writing,
  15259. * software distributed under the License is distributed on an
  15260. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15261. * KIND, either express or implied. See the License for the
  15262. * specific language governing permissions and limitations
  15263. * under the License.
  15264. */
  15265. var RADIAN_EPSILON = 1e-4;
  15266. function _trim(str) {
  15267. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15268. }
  15269. /**
  15270. * Linear mapping a value from domain to range
  15271. * @memberOf module:echarts/util/number
  15272. * @param {(number|Array.<number>)} val
  15273. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15274. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15275. * @param {boolean} clamp
  15276. * @return {(number|Array.<number>}
  15277. */
  15278. function linearMap(val, domain, range, clamp) {
  15279. var subDomain = domain[1] - domain[0];
  15280. var subRange = range[1] - range[0];
  15281. if (subDomain === 0) {
  15282. return subRange === 0
  15283. ? range[0]
  15284. : (range[0] + range[1]) / 2;
  15285. }
  15286. // Avoid accuracy problem in edge, such as
  15287. // 146.39 - 62.83 === 83.55999999999999.
  15288. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15289. // It is a little verbose for efficiency considering this method
  15290. // is a hotspot.
  15291. if (clamp) {
  15292. if (subDomain > 0) {
  15293. if (val <= domain[0]) {
  15294. return range[0];
  15295. }
  15296. else if (val >= domain[1]) {
  15297. return range[1];
  15298. }
  15299. }
  15300. else {
  15301. if (val >= domain[0]) {
  15302. return range[0];
  15303. }
  15304. else if (val <= domain[1]) {
  15305. return range[1];
  15306. }
  15307. }
  15308. }
  15309. else {
  15310. if (val === domain[0]) {
  15311. return range[0];
  15312. }
  15313. if (val === domain[1]) {
  15314. return range[1];
  15315. }
  15316. }
  15317. return (val - domain[0]) / subDomain * subRange + range[0];
  15318. }
  15319. /**
  15320. * Convert a percent string to absolute number.
  15321. * Returns NaN if percent is not a valid string or number
  15322. * @memberOf module:echarts/util/number
  15323. * @param {string|number} percent
  15324. * @param {number} all
  15325. * @return {number}
  15326. */
  15327. function parsePercent$1(percent, all) {
  15328. switch (percent) {
  15329. case 'center':
  15330. case 'middle':
  15331. percent = '50%';
  15332. break;
  15333. case 'left':
  15334. case 'top':
  15335. percent = '0%';
  15336. break;
  15337. case 'right':
  15338. case 'bottom':
  15339. percent = '100%';
  15340. break;
  15341. }
  15342. if (typeof percent === 'string') {
  15343. if (_trim(percent).match(/%$/)) {
  15344. return parseFloat(percent) / 100 * all;
  15345. }
  15346. return parseFloat(percent);
  15347. }
  15348. return percent == null ? NaN : +percent;
  15349. }
  15350. /**
  15351. * (1) Fix rounding error of float numbers.
  15352. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15353. *
  15354. * @param {number} x
  15355. * @param {number} [precision]
  15356. * @param {boolean} [returnStr]
  15357. * @return {number|string}
  15358. */
  15359. function round$1(x, precision, returnStr) {
  15360. if (precision == null) {
  15361. precision = 10;
  15362. }
  15363. // Avoid range error
  15364. precision = Math.min(Math.max(0, precision), 20);
  15365. x = (+x).toFixed(precision);
  15366. return returnStr ? x : +x;
  15367. }
  15368. function asc(arr) {
  15369. arr.sort(function (a, b) {
  15370. return a - b;
  15371. });
  15372. return arr;
  15373. }
  15374. /**
  15375. * Get precision
  15376. * @param {number} val
  15377. */
  15378. function getPrecision(val) {
  15379. val = +val;
  15380. if (isNaN(val)) {
  15381. return 0;
  15382. }
  15383. // It is much faster than methods converting number to string as follows
  15384. // var tmp = val.toString();
  15385. // return tmp.length - 1 - tmp.indexOf('.');
  15386. // especially when precision is low
  15387. var e = 1;
  15388. var count = 0;
  15389. while (Math.round(val * e) / e !== val) {
  15390. e *= 10;
  15391. count++;
  15392. }
  15393. return count;
  15394. }
  15395. /**
  15396. * @param {string|number} val
  15397. * @return {number}
  15398. */
  15399. function getPrecisionSafe(val) {
  15400. var str = val.toString();
  15401. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15402. var eIndex = str.indexOf('e');
  15403. if (eIndex > 0) {
  15404. var precision = +str.slice(eIndex + 1);
  15405. return precision < 0 ? -precision : 0;
  15406. }
  15407. else {
  15408. var dotIndex = str.indexOf('.');
  15409. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15410. }
  15411. }
  15412. /**
  15413. * Minimal dicernible data precisioin according to a single pixel.
  15414. *
  15415. * @param {Array.<number>} dataExtent
  15416. * @param {Array.<number>} pixelExtent
  15417. * @return {number} precision
  15418. */
  15419. function getPixelPrecision(dataExtent, pixelExtent) {
  15420. var log = Math.log;
  15421. var LN10 = Math.LN10;
  15422. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15423. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15424. // toFixed() digits argument must be between 0 and 20.
  15425. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15426. return !isFinite(precision) ? 20 : precision;
  15427. }
  15428. /**
  15429. * Get a data of given precision, assuring the sum of percentages
  15430. * in valueList is 1.
  15431. * The largest remainer method is used.
  15432. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15433. *
  15434. * @param {Array.<number>} valueList a list of all data
  15435. * @param {number} idx index of the data to be processed in valueList
  15436. * @param {number} precision integer number showing digits of precision
  15437. * @return {number} percent ranging from 0 to 100
  15438. */
  15439. function getPercentWithPrecision(valueList, idx, precision) {
  15440. if (!valueList[idx]) {
  15441. return 0;
  15442. }
  15443. var sum = reduce(valueList, function (acc, val) {
  15444. return acc + (isNaN(val) ? 0 : val);
  15445. }, 0);
  15446. if (sum === 0) {
  15447. return 0;
  15448. }
  15449. var digits = Math.pow(10, precision);
  15450. var votesPerQuota = map(valueList, function (val) {
  15451. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15452. });
  15453. var targetSeats = digits * 100;
  15454. var seats = map(votesPerQuota, function (votes) {
  15455. // Assign automatic seats.
  15456. return Math.floor(votes);
  15457. });
  15458. var currentSum = reduce(seats, function (acc, val) {
  15459. return acc + val;
  15460. }, 0);
  15461. var remainder = map(votesPerQuota, function (votes, idx) {
  15462. return votes - seats[idx];
  15463. });
  15464. // Has remainding votes.
  15465. while (currentSum < targetSeats) {
  15466. // Find next largest remainder.
  15467. var max = Number.NEGATIVE_INFINITY;
  15468. var maxId = null;
  15469. for (var i = 0, len = remainder.length; i < len; ++i) {
  15470. if (remainder[i] > max) {
  15471. max = remainder[i];
  15472. maxId = i;
  15473. }
  15474. }
  15475. // Add a vote to max remainder.
  15476. ++seats[maxId];
  15477. remainder[maxId] = 0;
  15478. ++currentSum;
  15479. }
  15480. return seats[idx] / digits;
  15481. }
  15482. // Number.MAX_SAFE_INTEGER, ie do not support.
  15483. var MAX_SAFE_INTEGER = 9007199254740991;
  15484. /**
  15485. * To 0 - 2 * PI, considering negative radian.
  15486. * @param {number} radian
  15487. * @return {number}
  15488. */
  15489. function remRadian(radian) {
  15490. var pi2 = Math.PI * 2;
  15491. return (radian % pi2 + pi2) % pi2;
  15492. }
  15493. /**
  15494. * @param {type} radian
  15495. * @return {boolean}
  15496. */
  15497. function isRadianAroundZero(val) {
  15498. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15499. }
  15500. 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
  15501. /**
  15502. * @param {string|Date|number} value These values can be accepted:
  15503. * + An instance of Date, represent a time in its own time zone.
  15504. * + Or string in a subset of ISO 8601, only including:
  15505. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15506. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15507. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15508. * all of which will be treated as local time if time zone is not specified
  15509. * (see <https://momentjs.com/>).
  15510. * + Or other string format, including (all of which will be treated as loacal time):
  15511. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15512. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15513. * + a timestamp, which represent a time in UTC.
  15514. * @return {Date} date
  15515. */
  15516. function parseDate(value) {
  15517. if (value instanceof Date) {
  15518. return value;
  15519. }
  15520. else if (typeof value === 'string') {
  15521. // Different browsers parse date in different way, so we parse it manually.
  15522. // Some other issues:
  15523. // new Date('1970-01-01') is UTC,
  15524. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15525. // See issue #3623
  15526. var match = TIME_REG.exec(value);
  15527. if (!match) {
  15528. // return Invalid Date.
  15529. return new Date(NaN);
  15530. }
  15531. // Use local time when no timezone offset specifed.
  15532. if (!match[8]) {
  15533. // match[n] can only be string or undefined.
  15534. // But take care of '12' + 1 => '121'.
  15535. return new Date(
  15536. +match[1],
  15537. +(match[2] || 1) - 1,
  15538. +match[3] || 1,
  15539. +match[4] || 0,
  15540. +(match[5] || 0),
  15541. +match[6] || 0,
  15542. +match[7] || 0
  15543. );
  15544. }
  15545. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15546. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15547. // For example, system timezone is set as "Time Zone: America/Toronto",
  15548. // then these code will get different result:
  15549. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15550. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15551. // So we should not use `new Date`, but use `Date.UTC`.
  15552. else {
  15553. var hour = +match[4] || 0;
  15554. if (match[8].toUpperCase() !== 'Z') {
  15555. hour -= match[8].slice(0, 3);
  15556. }
  15557. return new Date(Date.UTC(
  15558. +match[1],
  15559. +(match[2] || 1) - 1,
  15560. +match[3] || 1,
  15561. hour,
  15562. +(match[5] || 0),
  15563. +match[6] || 0,
  15564. +match[7] || 0
  15565. ));
  15566. }
  15567. }
  15568. else if (value == null) {
  15569. return new Date(NaN);
  15570. }
  15571. return new Date(Math.round(value));
  15572. }
  15573. /**
  15574. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15575. *
  15576. * @param {number} val
  15577. * @return {number}
  15578. */
  15579. function quantity(val) {
  15580. return Math.pow(10, quantityExponent(val));
  15581. }
  15582. function quantityExponent(val) {
  15583. return Math.floor(Math.log(val) / Math.LN10);
  15584. }
  15585. /**
  15586. * find a “nice” number approximately equal to x. Round the number if round = true,
  15587. * take ceiling if round = false. The primary observation is that the “nicest”
  15588. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15589. *
  15590. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15591. *
  15592. * @param {number} val Non-negative value.
  15593. * @param {boolean} round
  15594. * @return {number}
  15595. */
  15596. function nice(val, round) {
  15597. var exponent = quantityExponent(val);
  15598. var exp10 = Math.pow(10, exponent);
  15599. var f = val / exp10; // 1 <= f < 10
  15600. var nf;
  15601. if (round) {
  15602. if (f < 1.5) { nf = 1; }
  15603. else if (f < 2.5) { nf = 2; }
  15604. else if (f < 4) { nf = 3; }
  15605. else if (f < 7) { nf = 5; }
  15606. else { nf = 10; }
  15607. }
  15608. else {
  15609. if (f < 1) { nf = 1; }
  15610. else if (f < 2) { nf = 2; }
  15611. else if (f < 3) { nf = 3; }
  15612. else if (f < 5) { nf = 5; }
  15613. else { nf = 10; }
  15614. }
  15615. val = nf * exp10;
  15616. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15617. // 20 is the uppper bound of toFixed.
  15618. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15619. }
  15620. /**
  15621. * Order intervals asc, and split them when overlap.
  15622. * expect(numberUtil.reformIntervals([
  15623. * {interval: [18, 62], close: [1, 1]},
  15624. * {interval: [-Infinity, -70], close: [0, 0]},
  15625. * {interval: [-70, -26], close: [1, 1]},
  15626. * {interval: [-26, 18], close: [1, 1]},
  15627. * {interval: [62, 150], close: [1, 1]},
  15628. * {interval: [106, 150], close: [1, 1]},
  15629. * {interval: [150, Infinity], close: [0, 0]}
  15630. * ])).toEqual([
  15631. * {interval: [-Infinity, -70], close: [0, 0]},
  15632. * {interval: [-70, -26], close: [1, 1]},
  15633. * {interval: [-26, 18], close: [0, 1]},
  15634. * {interval: [18, 62], close: [0, 1]},
  15635. * {interval: [62, 150], close: [0, 1]},
  15636. * {interval: [150, Infinity], close: [0, 0]}
  15637. * ]);
  15638. * @param {Array.<Object>} list, where `close` mean open or close
  15639. * of the interval, and Infinity can be used.
  15640. * @return {Array.<Object>} The origin list, which has been reformed.
  15641. */
  15642. function reformIntervals(list) {
  15643. list.sort(function (a, b) {
  15644. return littleThan(a, b, 0) ? -1 : 1;
  15645. });
  15646. var curr = -Infinity;
  15647. var currClose = 1;
  15648. for (var i = 0; i < list.length;) {
  15649. var interval = list[i].interval;
  15650. var close = list[i].close;
  15651. for (var lg = 0; lg < 2; lg++) {
  15652. if (interval[lg] <= curr) {
  15653. interval[lg] = curr;
  15654. close[lg] = !lg ? 1 - currClose : 1;
  15655. }
  15656. curr = interval[lg];
  15657. currClose = close[lg];
  15658. }
  15659. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15660. list.splice(i, 1);
  15661. }
  15662. else {
  15663. i++;
  15664. }
  15665. }
  15666. return list;
  15667. function littleThan(a, b, lg) {
  15668. return a.interval[lg] < b.interval[lg]
  15669. || (
  15670. a.interval[lg] === b.interval[lg]
  15671. && (
  15672. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  15673. || (!lg && littleThan(a, b, 1))
  15674. )
  15675. );
  15676. }
  15677. }
  15678. /**
  15679. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15680. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15681. * subtraction forces infinities to NaN
  15682. *
  15683. * @param {*} v
  15684. * @return {boolean}
  15685. */
  15686. function isNumeric(v) {
  15687. return v - parseFloat(v) >= 0;
  15688. }
  15689. var number = (Object.freeze || Object)({
  15690. linearMap: linearMap,
  15691. parsePercent: parsePercent$1,
  15692. round: round$1,
  15693. asc: asc,
  15694. getPrecision: getPrecision,
  15695. getPrecisionSafe: getPrecisionSafe,
  15696. getPixelPrecision: getPixelPrecision,
  15697. getPercentWithPrecision: getPercentWithPrecision,
  15698. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15699. remRadian: remRadian,
  15700. isRadianAroundZero: isRadianAroundZero,
  15701. parseDate: parseDate,
  15702. quantity: quantity,
  15703. nice: nice,
  15704. reformIntervals: reformIntervals,
  15705. isNumeric: isNumeric
  15706. });
  15707. /*
  15708. * Licensed to the Apache Software Foundation (ASF) under one
  15709. * or more contributor license agreements. See the NOTICE file
  15710. * distributed with this work for additional information
  15711. * regarding copyright ownership. The ASF licenses this file
  15712. * to you under the Apache License, Version 2.0 (the
  15713. * "License"); you may not use this file except in compliance
  15714. * with the License. You may obtain a copy of the License at
  15715. *
  15716. * http://www.apache.org/licenses/LICENSE-2.0
  15717. *
  15718. * Unless required by applicable law or agreed to in writing,
  15719. * software distributed under the License is distributed on an
  15720. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15721. * KIND, either express or implied. See the License for the
  15722. * specific language governing permissions and limitations
  15723. * under the License.
  15724. */
  15725. /**
  15726. * 每三位默认加,格式化
  15727. * @param {string|number} x
  15728. * @return {string}
  15729. */
  15730. function addCommas(x) {
  15731. if (isNaN(x)) {
  15732. return '-';
  15733. }
  15734. x = (x + '').split('.');
  15735. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  15736. + (x.length > 1 ? ('.' + x[1]) : '');
  15737. }
  15738. /**
  15739. * @param {string} str
  15740. * @param {boolean} [upperCaseFirst=false]
  15741. * @return {string} str
  15742. */
  15743. function toCamelCase(str, upperCaseFirst) {
  15744. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  15745. return group1.toUpperCase();
  15746. });
  15747. if (upperCaseFirst && str) {
  15748. str = str.charAt(0).toUpperCase() + str.slice(1);
  15749. }
  15750. return str;
  15751. }
  15752. var normalizeCssArray$1 = normalizeCssArray;
  15753. var replaceReg = /([&<>"'])/g;
  15754. var replaceMap = {
  15755. '&': '&amp;',
  15756. '<': '&lt;',
  15757. '>': '&gt;',
  15758. '"': '&quot;',
  15759. '\'': '&#39;'
  15760. };
  15761. function encodeHTML(source) {
  15762. return source == null
  15763. ? ''
  15764. : (source + '').replace(replaceReg, function (str, c) {
  15765. return replaceMap[c];
  15766. });
  15767. }
  15768. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15769. var wrapVar = function (varName, seriesIdx) {
  15770. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15771. };
  15772. /**
  15773. * Template formatter
  15774. * @param {string} tpl
  15775. * @param {Array.<Object>|Object} paramsList
  15776. * @param {boolean} [encode=false]
  15777. * @return {string}
  15778. */
  15779. function formatTpl(tpl, paramsList, encode) {
  15780. if (!isArray(paramsList)) {
  15781. paramsList = [paramsList];
  15782. }
  15783. var seriesLen = paramsList.length;
  15784. if (!seriesLen) {
  15785. return '';
  15786. }
  15787. var $vars = paramsList[0].$vars || [];
  15788. for (var i = 0; i < $vars.length; i++) {
  15789. var alias = TPL_VAR_ALIAS[i];
  15790. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15791. }
  15792. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15793. for (var k = 0; k < $vars.length; k++) {
  15794. var val = paramsList[seriesIdx][$vars[k]];
  15795. tpl = tpl.replace(
  15796. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  15797. encode ? encodeHTML(val) : val
  15798. );
  15799. }
  15800. }
  15801. return tpl;
  15802. }
  15803. /**
  15804. * simple Template formatter
  15805. *
  15806. * @param {string} tpl
  15807. * @param {Object} param
  15808. * @param {boolean} [encode=false]
  15809. * @return {string}
  15810. */
  15811. function formatTplSimple(tpl, param, encode) {
  15812. each$1(param, function (value, key) {
  15813. tpl = tpl.replace(
  15814. '{' + key + '}',
  15815. encode ? encodeHTML(value) : value
  15816. );
  15817. });
  15818. return tpl;
  15819. }
  15820. /**
  15821. * @param {Object|string} [opt] If string, means color.
  15822. * @param {string} [opt.color]
  15823. * @param {string} [opt.extraCssText]
  15824. * @param {string} [opt.type='item'] 'item' or 'subItem'
  15825. * @return {string}
  15826. */
  15827. function getTooltipMarker(opt, extraCssText) {
  15828. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  15829. var color = opt.color;
  15830. var type = opt.type;
  15831. var extraCssText = opt.extraCssText;
  15832. if (!color) {
  15833. return '';
  15834. }
  15835. return type === 'subItem'
  15836. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  15837. + 'border-radius:4px;width:4px;height:4px;background-color:'
  15838. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  15839. : '<span style="display:inline-block;margin-right:5px;'
  15840. + 'border-radius:10px;width:10px;height:10px;background-color:'
  15841. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  15842. }
  15843. function pad(str, len) {
  15844. str += '';
  15845. return '0000'.substr(0, len - str.length) + str;
  15846. }
  15847. /**
  15848. * ISO Date format
  15849. * @param {string} tpl
  15850. * @param {number} value
  15851. * @param {boolean} [isUTC=false] Default in local time.
  15852. * see `module:echarts/scale/Time`
  15853. * and `module:echarts/util/number#parseDate`.
  15854. * @inner
  15855. */
  15856. function formatTime(tpl, value, isUTC) {
  15857. if (tpl === 'week'
  15858. || tpl === 'month'
  15859. || tpl === 'quarter'
  15860. || tpl === 'half-year'
  15861. || tpl === 'year'
  15862. ) {
  15863. tpl = 'MM-dd\nyyyy';
  15864. }
  15865. var date = parseDate(value);
  15866. var utc = isUTC ? 'UTC' : '';
  15867. var y = date['get' + utc + 'FullYear']();
  15868. var M = date['get' + utc + 'Month']() + 1;
  15869. var d = date['get' + utc + 'Date']();
  15870. var h = date['get' + utc + 'Hours']();
  15871. var m = date['get' + utc + 'Minutes']();
  15872. var s = date['get' + utc + 'Seconds']();
  15873. var S = date['get' + utc + 'Milliseconds']();
  15874. tpl = tpl.replace('MM', pad(M, 2))
  15875. .replace('M', M)
  15876. .replace('yyyy', y)
  15877. .replace('yy', y % 100)
  15878. .replace('dd', pad(d, 2))
  15879. .replace('d', d)
  15880. .replace('hh', pad(h, 2))
  15881. .replace('h', h)
  15882. .replace('mm', pad(m, 2))
  15883. .replace('m', m)
  15884. .replace('ss', pad(s, 2))
  15885. .replace('s', s)
  15886. .replace('SSS', pad(S, 3));
  15887. return tpl;
  15888. }
  15889. /**
  15890. * Capital first
  15891. * @param {string} str
  15892. * @return {string}
  15893. */
  15894. function capitalFirst(str) {
  15895. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15896. }
  15897. var truncateText$1 = truncateText;
  15898. var getTextRect = getBoundingRect;
  15899. var format = (Object.freeze || Object)({
  15900. addCommas: addCommas,
  15901. toCamelCase: toCamelCase,
  15902. normalizeCssArray: normalizeCssArray$1,
  15903. encodeHTML: encodeHTML,
  15904. formatTpl: formatTpl,
  15905. formatTplSimple: formatTplSimple,
  15906. getTooltipMarker: getTooltipMarker,
  15907. formatTime: formatTime,
  15908. capitalFirst: capitalFirst,
  15909. truncateText: truncateText$1,
  15910. getTextRect: getTextRect
  15911. });
  15912. /*
  15913. * Licensed to the Apache Software Foundation (ASF) under one
  15914. * or more contributor license agreements. See the NOTICE file
  15915. * distributed with this work for additional information
  15916. * regarding copyright ownership. The ASF licenses this file
  15917. * to you under the Apache License, Version 2.0 (the
  15918. * "License"); you may not use this file except in compliance
  15919. * with the License. You may obtain a copy of the License at
  15920. *
  15921. * http://www.apache.org/licenses/LICENSE-2.0
  15922. *
  15923. * Unless required by applicable law or agreed to in writing,
  15924. * software distributed under the License is distributed on an
  15925. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15926. * KIND, either express or implied. See the License for the
  15927. * specific language governing permissions and limitations
  15928. * under the License.
  15929. */
  15930. // Layout helpers for each component positioning
  15931. var each$3 = each$1;
  15932. /**
  15933. * @public
  15934. */
  15935. var LOCATION_PARAMS = [
  15936. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15937. ];
  15938. /**
  15939. * @public
  15940. */
  15941. var HV_NAMES = [
  15942. ['width', 'left', 'right'],
  15943. ['height', 'top', 'bottom']
  15944. ];
  15945. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15946. var x = 0;
  15947. var y = 0;
  15948. if (maxWidth == null) {
  15949. maxWidth = Infinity;
  15950. }
  15951. if (maxHeight == null) {
  15952. maxHeight = Infinity;
  15953. }
  15954. var currentLineMaxSize = 0;
  15955. group.eachChild(function (child, idx) {
  15956. var position = child.position;
  15957. var rect = child.getBoundingRect();
  15958. var nextChild = group.childAt(idx + 1);
  15959. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15960. var nextX;
  15961. var nextY;
  15962. if (orient === 'horizontal') {
  15963. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15964. nextX = x + moveX;
  15965. // Wrap when width exceeds maxWidth or meet a `newline` group
  15966. // FIXME compare before adding gap?
  15967. if (nextX > maxWidth || child.newline) {
  15968. x = 0;
  15969. nextX = moveX;
  15970. y += currentLineMaxSize + gap;
  15971. currentLineMaxSize = rect.height;
  15972. }
  15973. else {
  15974. // FIXME: consider rect.y is not `0`?
  15975. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15976. }
  15977. }
  15978. else {
  15979. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15980. nextY = y + moveY;
  15981. // Wrap when width exceeds maxHeight or meet a `newline` group
  15982. if (nextY > maxHeight || child.newline) {
  15983. x += currentLineMaxSize + gap;
  15984. y = 0;
  15985. nextY = moveY;
  15986. currentLineMaxSize = rect.width;
  15987. }
  15988. else {
  15989. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15990. }
  15991. }
  15992. if (child.newline) {
  15993. return;
  15994. }
  15995. position[0] = x;
  15996. position[1] = y;
  15997. orient === 'horizontal'
  15998. ? (x = nextX + gap)
  15999. : (y = nextY + gap);
  16000. });
  16001. }
  16002. /**
  16003. * VBox or HBox layouting
  16004. * @param {string} orient
  16005. * @param {module:zrender/container/Group} group
  16006. * @param {number} gap
  16007. * @param {number} [width=Infinity]
  16008. * @param {number} [height=Infinity]
  16009. */
  16010. var box = boxLayout;
  16011. /**
  16012. * VBox layouting
  16013. * @param {module:zrender/container/Group} group
  16014. * @param {number} gap
  16015. * @param {number} [width=Infinity]
  16016. * @param {number} [height=Infinity]
  16017. */
  16018. var vbox = curry(boxLayout, 'vertical');
  16019. /**
  16020. * HBox layouting
  16021. * @param {module:zrender/container/Group} group
  16022. * @param {number} gap
  16023. * @param {number} [width=Infinity]
  16024. * @param {number} [height=Infinity]
  16025. */
  16026. var hbox = curry(boxLayout, 'horizontal');
  16027. /**
  16028. * If x or x2 is not specified or 'center' 'left' 'right',
  16029. * the width would be as long as possible.
  16030. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16031. * the height would be as long as possible.
  16032. *
  16033. * @param {Object} positionInfo
  16034. * @param {number|string} [positionInfo.x]
  16035. * @param {number|string} [positionInfo.y]
  16036. * @param {number|string} [positionInfo.x2]
  16037. * @param {number|string} [positionInfo.y2]
  16038. * @param {Object} containerRect {width, height}
  16039. * @param {string|number} margin
  16040. * @return {Object} {width, height}
  16041. */
  16042. function getAvailableSize(positionInfo, containerRect, margin) {
  16043. var containerWidth = containerRect.width;
  16044. var containerHeight = containerRect.height;
  16045. var x = parsePercent$1(positionInfo.x, containerWidth);
  16046. var y = parsePercent$1(positionInfo.y, containerHeight);
  16047. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  16048. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  16049. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  16050. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  16051. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  16052. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  16053. margin = normalizeCssArray$1(margin || 0);
  16054. return {
  16055. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16056. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16057. };
  16058. }
  16059. /**
  16060. * Parse position info.
  16061. *
  16062. * @param {Object} positionInfo
  16063. * @param {number|string} [positionInfo.left]
  16064. * @param {number|string} [positionInfo.top]
  16065. * @param {number|string} [positionInfo.right]
  16066. * @param {number|string} [positionInfo.bottom]
  16067. * @param {number|string} [positionInfo.width]
  16068. * @param {number|string} [positionInfo.height]
  16069. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16070. * @param {Object} containerRect
  16071. * @param {string|number} [margin]
  16072. *
  16073. * @return {module:zrender/core/BoundingRect}
  16074. */
  16075. function getLayoutRect(
  16076. positionInfo, containerRect, margin
  16077. ) {
  16078. margin = normalizeCssArray$1(margin || 0);
  16079. var containerWidth = containerRect.width;
  16080. var containerHeight = containerRect.height;
  16081. var left = parsePercent$1(positionInfo.left, containerWidth);
  16082. var top = parsePercent$1(positionInfo.top, containerHeight);
  16083. var right = parsePercent$1(positionInfo.right, containerWidth);
  16084. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16085. var width = parsePercent$1(positionInfo.width, containerWidth);
  16086. var height = parsePercent$1(positionInfo.height, containerHeight);
  16087. var verticalMargin = margin[2] + margin[0];
  16088. var horizontalMargin = margin[1] + margin[3];
  16089. var aspect = positionInfo.aspect;
  16090. // If width is not specified, calculate width from left and right
  16091. if (isNaN(width)) {
  16092. width = containerWidth - right - horizontalMargin - left;
  16093. }
  16094. if (isNaN(height)) {
  16095. height = containerHeight - bottom - verticalMargin - top;
  16096. }
  16097. if (aspect != null) {
  16098. // If width and height are not given
  16099. // 1. Graph should not exceeds the container
  16100. // 2. Aspect must be keeped
  16101. // 3. Graph should take the space as more as possible
  16102. // FIXME
  16103. // Margin is not considered, because there is no case that both
  16104. // using margin and aspect so far.
  16105. if (isNaN(width) && isNaN(height)) {
  16106. if (aspect > containerWidth / containerHeight) {
  16107. width = containerWidth * 0.8;
  16108. }
  16109. else {
  16110. height = containerHeight * 0.8;
  16111. }
  16112. }
  16113. // Calculate width or height with given aspect
  16114. if (isNaN(width)) {
  16115. width = aspect * height;
  16116. }
  16117. if (isNaN(height)) {
  16118. height = width / aspect;
  16119. }
  16120. }
  16121. // If left is not specified, calculate left from right and width
  16122. if (isNaN(left)) {
  16123. left = containerWidth - right - width - horizontalMargin;
  16124. }
  16125. if (isNaN(top)) {
  16126. top = containerHeight - bottom - height - verticalMargin;
  16127. }
  16128. // Align left and top
  16129. switch (positionInfo.left || positionInfo.right) {
  16130. case 'center':
  16131. left = containerWidth / 2 - width / 2 - margin[3];
  16132. break;
  16133. case 'right':
  16134. left = containerWidth - width - horizontalMargin;
  16135. break;
  16136. }
  16137. switch (positionInfo.top || positionInfo.bottom) {
  16138. case 'middle':
  16139. case 'center':
  16140. top = containerHeight / 2 - height / 2 - margin[0];
  16141. break;
  16142. case 'bottom':
  16143. top = containerHeight - height - verticalMargin;
  16144. break;
  16145. }
  16146. // If something is wrong and left, top, width, height are calculated as NaN
  16147. left = left || 0;
  16148. top = top || 0;
  16149. if (isNaN(width)) {
  16150. // Width may be NaN if only one value is given except width
  16151. width = containerWidth - horizontalMargin - left - (right || 0);
  16152. }
  16153. if (isNaN(height)) {
  16154. // Height may be NaN if only one value is given except height
  16155. height = containerHeight - verticalMargin - top - (bottom || 0);
  16156. }
  16157. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16158. rect.margin = margin;
  16159. return rect;
  16160. }
  16161. /**
  16162. * Position a zr element in viewport
  16163. * Group position is specified by either
  16164. * {left, top}, {right, bottom}
  16165. * If all properties exists, right and bottom will be igonred.
  16166. *
  16167. * Logic:
  16168. * 1. Scale (against origin point in parent coord)
  16169. * 2. Rotate (against origin point in parent coord)
  16170. * 3. Traslate (with el.position by this method)
  16171. * So this method only fixes the last step 'Traslate', which does not affect
  16172. * scaling and rotating.
  16173. *
  16174. * If be called repeatly with the same input el, the same result will be gotten.
  16175. *
  16176. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16177. * @param {Object} positionInfo
  16178. * @param {number|string} [positionInfo.left]
  16179. * @param {number|string} [positionInfo.top]
  16180. * @param {number|string} [positionInfo.right]
  16181. * @param {number|string} [positionInfo.bottom]
  16182. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16183. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16184. * @param {Object} containerRect
  16185. * @param {string|number} margin
  16186. * @param {Object} [opt]
  16187. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16188. * @param {Array.<number>} [opt.boundingMode='all']
  16189. * Specify how to calculate boundingRect when locating.
  16190. * 'all': Position the boundingRect that is transformed and uioned
  16191. * both itself and its descendants.
  16192. * This mode simplies confine the elements in the bounding
  16193. * of their container (e.g., using 'right: 0').
  16194. * 'raw': Position the boundingRect that is not transformed and only itself.
  16195. * This mode is useful when you want a element can overflow its
  16196. * container. (Consider a rotated circle needs to be located in a corner.)
  16197. * In this mode positionInfo.width/height can only be number.
  16198. */
  16199. function positionElement(el, positionInfo, containerRect, margin, opt) {
  16200. var h = !opt || !opt.hv || opt.hv[0];
  16201. var v = !opt || !opt.hv || opt.hv[1];
  16202. var boundingMode = opt && opt.boundingMode || 'all';
  16203. if (!h && !v) {
  16204. return;
  16205. }
  16206. var rect;
  16207. if (boundingMode === 'raw') {
  16208. rect = el.type === 'group'
  16209. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  16210. : el.getBoundingRect();
  16211. }
  16212. else {
  16213. rect = el.getBoundingRect();
  16214. if (el.needLocalTransform()) {
  16215. var transform = el.getLocalTransform();
  16216. // Notice: raw rect may be inner object of el,
  16217. // which should not be modified.
  16218. rect = rect.clone();
  16219. rect.applyTransform(transform);
  16220. }
  16221. }
  16222. // The real width and height can not be specified but calculated by the given el.
  16223. positionInfo = getLayoutRect(
  16224. defaults(
  16225. {width: rect.width, height: rect.height},
  16226. positionInfo
  16227. ),
  16228. containerRect,
  16229. margin
  16230. );
  16231. // Because 'tranlate' is the last step in transform
  16232. // (see zrender/core/Transformable#getLocalTransform),
  16233. // we can just only modify el.position to get final result.
  16234. var elPos = el.position;
  16235. var dx = h ? positionInfo.x - rect.x : 0;
  16236. var dy = v ? positionInfo.y - rect.y : 0;
  16237. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  16238. }
  16239. /**
  16240. * @param {Object} option Contains some of the properties in HV_NAMES.
  16241. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16242. */
  16243. function sizeCalculable(option, hvIdx) {
  16244. return option[HV_NAMES[hvIdx][0]] != null
  16245. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  16246. }
  16247. /**
  16248. * Consider Case:
  16249. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16250. * through setOption or media query, using normal zrUtil.merge will cause
  16251. * {right: 0} does not take effect.
  16252. *
  16253. * @example
  16254. * ComponentModel.extend({
  16255. * init: function () {
  16256. * ...
  16257. * var inputPositionParams = layout.getLayoutParams(option);
  16258. * this.mergeOption(inputPositionParams);
  16259. * },
  16260. * mergeOption: function (newOption) {
  16261. * newOption && zrUtil.merge(thisOption, newOption, true);
  16262. * layout.mergeLayoutParam(thisOption, newOption);
  16263. * }
  16264. * });
  16265. *
  16266. * @param {Object} targetOption
  16267. * @param {Object} newOption
  16268. * @param {Object|string} [opt]
  16269. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16270. * that width (or height) should not be calculated by left and right (or top and bottom).
  16271. */
  16272. function mergeLayoutParam(targetOption, newOption, opt) {
  16273. !isObject$1(opt) && (opt = {});
  16274. var ignoreSize = opt.ignoreSize;
  16275. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16276. var hResult = merge$$1(HV_NAMES[0], 0);
  16277. var vResult = merge$$1(HV_NAMES[1], 1);
  16278. copy(HV_NAMES[0], targetOption, hResult);
  16279. copy(HV_NAMES[1], targetOption, vResult);
  16280. function merge$$1(names, hvIdx) {
  16281. var newParams = {};
  16282. var newValueCount = 0;
  16283. var merged = {};
  16284. var mergedValueCount = 0;
  16285. var enoughParamNumber = 2;
  16286. each$3(names, function (name) {
  16287. merged[name] = targetOption[name];
  16288. });
  16289. each$3(names, function (name) {
  16290. // Consider case: newOption.width is null, which is
  16291. // set by user for removing width setting.
  16292. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16293. hasValue(newParams, name) && newValueCount++;
  16294. hasValue(merged, name) && mergedValueCount++;
  16295. });
  16296. if (ignoreSize[hvIdx]) {
  16297. // Only one of left/right is premitted to exist.
  16298. if (hasValue(newOption, names[1])) {
  16299. merged[names[2]] = null;
  16300. }
  16301. else if (hasValue(newOption, names[2])) {
  16302. merged[names[1]] = null;
  16303. }
  16304. return merged;
  16305. }
  16306. // Case: newOption: {width: ..., right: ...},
  16307. // or targetOption: {right: ...} and newOption: {width: ...},
  16308. // There is no conflict when merged only has params count
  16309. // little than enoughParamNumber.
  16310. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16311. return merged;
  16312. }
  16313. // Case: newOption: {width: ..., right: ...},
  16314. // Than we can make sure user only want those two, and ignore
  16315. // all origin params in targetOption.
  16316. else if (newValueCount >= enoughParamNumber) {
  16317. return newParams;
  16318. }
  16319. else {
  16320. // Chose another param from targetOption by priority.
  16321. for (var i = 0; i < names.length; i++) {
  16322. var name = names[i];
  16323. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16324. newParams[name] = targetOption[name];
  16325. break;
  16326. }
  16327. }
  16328. return newParams;
  16329. }
  16330. }
  16331. function hasProp(obj, name) {
  16332. return obj.hasOwnProperty(name);
  16333. }
  16334. function hasValue(obj, name) {
  16335. return obj[name] != null && obj[name] !== 'auto';
  16336. }
  16337. function copy(names, target, source) {
  16338. each$3(names, function (name) {
  16339. target[name] = source[name];
  16340. });
  16341. }
  16342. }
  16343. /**
  16344. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16345. * @param {Object} source
  16346. * @return {Object} Result contains those props.
  16347. */
  16348. function getLayoutParams(source) {
  16349. return copyLayoutParams({}, source);
  16350. }
  16351. /**
  16352. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16353. * @param {Object} source
  16354. * @return {Object} Result contains those props.
  16355. */
  16356. function copyLayoutParams(target, source) {
  16357. source && target && each$3(LOCATION_PARAMS, function (name) {
  16358. source.hasOwnProperty(name) && (target[name] = source[name]);
  16359. });
  16360. return target;
  16361. }
  16362. /*
  16363. * Licensed to the Apache Software Foundation (ASF) under one
  16364. * or more contributor license agreements. See the NOTICE file
  16365. * distributed with this work for additional information
  16366. * regarding copyright ownership. The ASF licenses this file
  16367. * to you under the Apache License, Version 2.0 (the
  16368. * "License"); you may not use this file except in compliance
  16369. * with the License. You may obtain a copy of the License at
  16370. *
  16371. * http://www.apache.org/licenses/LICENSE-2.0
  16372. *
  16373. * Unless required by applicable law or agreed to in writing,
  16374. * software distributed under the License is distributed on an
  16375. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16376. * KIND, either express or implied. See the License for the
  16377. * specific language governing permissions and limitations
  16378. * under the License.
  16379. */
  16380. var boxLayoutMixin = {
  16381. getBoxLayoutParams: function () {
  16382. return {
  16383. left: this.get('left'),
  16384. top: this.get('top'),
  16385. right: this.get('right'),
  16386. bottom: this.get('bottom'),
  16387. width: this.get('width'),
  16388. height: this.get('height')
  16389. };
  16390. }
  16391. };
  16392. /*
  16393. * Licensed to the Apache Software Foundation (ASF) under one
  16394. * or more contributor license agreements. See the NOTICE file
  16395. * distributed with this work for additional information
  16396. * regarding copyright ownership. The ASF licenses this file
  16397. * to you under the Apache License, Version 2.0 (the
  16398. * "License"); you may not use this file except in compliance
  16399. * with the License. You may obtain a copy of the License at
  16400. *
  16401. * http://www.apache.org/licenses/LICENSE-2.0
  16402. *
  16403. * Unless required by applicable law or agreed to in writing,
  16404. * software distributed under the License is distributed on an
  16405. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16406. * KIND, either express or implied. See the License for the
  16407. * specific language governing permissions and limitations
  16408. * under the License.
  16409. */
  16410. /**
  16411. * Component model
  16412. *
  16413. * @module echarts/model/Component
  16414. */
  16415. var inner$1 = makeInner();
  16416. /**
  16417. * @alias module:echarts/model/Component
  16418. * @constructor
  16419. * @param {Object} option
  16420. * @param {module:echarts/model/Model} parentModel
  16421. * @param {module:echarts/model/Model} ecModel
  16422. */
  16423. var ComponentModel = Model.extend({
  16424. type: 'component',
  16425. /**
  16426. * @readOnly
  16427. * @type {string}
  16428. */
  16429. id: '',
  16430. /**
  16431. * Because simplified concept is probably better, series.name (or component.name)
  16432. * has been having too many resposibilities:
  16433. * (1) Generating id (which requires name in option should not be modified).
  16434. * (2) As an index to mapping series when merging option or calling API (a name
  16435. * can refer to more then one components, which is convinient is some case).
  16436. * (3) Display.
  16437. * @readOnly
  16438. */
  16439. name: '',
  16440. /**
  16441. * @readOnly
  16442. * @type {string}
  16443. */
  16444. mainType: '',
  16445. /**
  16446. * @readOnly
  16447. * @type {string}
  16448. */
  16449. subType: '',
  16450. /**
  16451. * @readOnly
  16452. * @type {number}
  16453. */
  16454. componentIndex: 0,
  16455. /**
  16456. * @type {Object}
  16457. * @protected
  16458. */
  16459. defaultOption: null,
  16460. /**
  16461. * @type {module:echarts/model/Global}
  16462. * @readOnly
  16463. */
  16464. ecModel: null,
  16465. /**
  16466. * key: componentType
  16467. * value: Component model list, can not be null.
  16468. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16469. * @readOnly
  16470. */
  16471. dependentModels: [],
  16472. /**
  16473. * @type {string}
  16474. * @readOnly
  16475. */
  16476. uid: null,
  16477. /**
  16478. * Support merge layout params.
  16479. * Only support 'box' now (left/right/top/bottom/width/height).
  16480. * @type {string|Object} Object can be {ignoreSize: true}
  16481. * @readOnly
  16482. */
  16483. layoutMode: null,
  16484. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16485. Model.call(this, option, parentModel, ecModel, extraOpt);
  16486. this.uid = getUID('ec_cpt_model');
  16487. },
  16488. init: function (option, parentModel, ecModel, extraOpt) {
  16489. this.mergeDefaultAndTheme(option, ecModel);
  16490. },
  16491. mergeDefaultAndTheme: function (option, ecModel) {
  16492. var layoutMode = this.layoutMode;
  16493. var inputPositionParams = layoutMode
  16494. ? getLayoutParams(option) : {};
  16495. var themeModel = ecModel.getTheme();
  16496. merge(option, themeModel.get(this.mainType));
  16497. merge(option, this.getDefaultOption());
  16498. if (layoutMode) {
  16499. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16500. }
  16501. },
  16502. mergeOption: function (option, extraOpt) {
  16503. merge(this.option, option, true);
  16504. var layoutMode = this.layoutMode;
  16505. if (layoutMode) {
  16506. mergeLayoutParam(this.option, option, layoutMode);
  16507. }
  16508. },
  16509. // Hooker after init or mergeOption
  16510. optionUpdated: function (newCptOption, isInit) {},
  16511. getDefaultOption: function () {
  16512. var fields = inner$1(this);
  16513. if (!fields.defaultOption) {
  16514. var optList = [];
  16515. var Class = this.constructor;
  16516. while (Class) {
  16517. var opt = Class.prototype.defaultOption;
  16518. opt && optList.push(opt);
  16519. Class = Class.superClass;
  16520. }
  16521. var defaultOption = {};
  16522. for (var i = optList.length - 1; i >= 0; i--) {
  16523. defaultOption = merge(defaultOption, optList[i], true);
  16524. }
  16525. fields.defaultOption = defaultOption;
  16526. }
  16527. return fields.defaultOption;
  16528. },
  16529. getReferringComponents: function (mainType) {
  16530. return this.ecModel.queryComponents({
  16531. mainType: mainType,
  16532. index: this.get(mainType + 'Index', true),
  16533. id: this.get(mainType + 'Id', true)
  16534. });
  16535. }
  16536. });
  16537. // Reset ComponentModel.extend, add preConstruct.
  16538. // clazzUtil.enableClassExtend(
  16539. // ComponentModel,
  16540. // function (option, parentModel, ecModel, extraOpt) {
  16541. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16542. // zrUtil.extend(this, extraOpt);
  16543. // this.uid = componentUtil.getUID('componentModel');
  16544. // // this.setReadOnly([
  16545. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16546. // // 'dependentModels', 'componentIndex'
  16547. // // ]);
  16548. // }
  16549. // );
  16550. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16551. enableClassManagement(
  16552. ComponentModel, {registerWhenExtend: true}
  16553. );
  16554. enableSubTypeDefaulter(ComponentModel);
  16555. // Add capability of ComponentModel.topologicalTravel.
  16556. enableTopologicalTravel(ComponentModel, getDependencies);
  16557. function getDependencies(componentType) {
  16558. var deps = [];
  16559. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16560. deps = deps.concat(Clazz.prototype.dependencies || []);
  16561. });
  16562. // Ensure main type.
  16563. deps = map(deps, function (type) {
  16564. return parseClassType$1(type).main;
  16565. });
  16566. // Hack dataset for convenience.
  16567. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16568. deps.unshift('dataset');
  16569. }
  16570. return deps;
  16571. }
  16572. mixin(ComponentModel, boxLayoutMixin);
  16573. /*
  16574. * Licensed to the Apache Software Foundation (ASF) under one
  16575. * or more contributor license agreements. See the NOTICE file
  16576. * distributed with this work for additional information
  16577. * regarding copyright ownership. The ASF licenses this file
  16578. * to you under the Apache License, Version 2.0 (the
  16579. * "License"); you may not use this file except in compliance
  16580. * with the License. You may obtain a copy of the License at
  16581. *
  16582. * http://www.apache.org/licenses/LICENSE-2.0
  16583. *
  16584. * Unless required by applicable law or agreed to in writing,
  16585. * software distributed under the License is distributed on an
  16586. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16587. * KIND, either express or implied. See the License for the
  16588. * specific language governing permissions and limitations
  16589. * under the License.
  16590. */
  16591. var platform = '';
  16592. // Navigator not exists in node
  16593. if (typeof navigator !== 'undefined') {
  16594. platform = navigator.platform || '';
  16595. }
  16596. var globalDefault = {
  16597. // backgroundColor: 'rgba(0,0,0,0)',
  16598. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16599. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16600. // Light colors:
  16601. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16602. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16603. // Dark colors:
  16604. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16605. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16606. // If xAxis and yAxis declared, grid is created by default.
  16607. // grid: {},
  16608. textStyle: {
  16609. // color: '#000',
  16610. // decoration: 'none',
  16611. // PENDING
  16612. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16613. // fontFamily: 'Arial, Verdana, sans-serif',
  16614. fontSize: 12,
  16615. fontStyle: 'normal',
  16616. fontWeight: 'normal'
  16617. },
  16618. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16619. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16620. // Default is source-over
  16621. blendMode: null,
  16622. animation: 'auto',
  16623. animationDuration: 1000,
  16624. animationDurationUpdate: 300,
  16625. animationEasing: 'exponentialOut',
  16626. animationEasingUpdate: 'cubicOut',
  16627. animationThreshold: 2000,
  16628. // Configuration for progressive/incremental rendering
  16629. progressiveThreshold: 3000,
  16630. progressive: 400,
  16631. // Threshold of if use single hover layer to optimize.
  16632. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16633. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16634. // which is unexpected.
  16635. // see example <echarts/test/heatmap-large.html>.
  16636. hoverLayerThreshold: 3000,
  16637. // See: module:echarts/scale/Time
  16638. useUTC: false
  16639. };
  16640. /*
  16641. * Licensed to the Apache Software Foundation (ASF) under one
  16642. * or more contributor license agreements. See the NOTICE file
  16643. * distributed with this work for additional information
  16644. * regarding copyright ownership. The ASF licenses this file
  16645. * to you under the Apache License, Version 2.0 (the
  16646. * "License"); you may not use this file except in compliance
  16647. * with the License. You may obtain a copy of the License at
  16648. *
  16649. * http://www.apache.org/licenses/LICENSE-2.0
  16650. *
  16651. * Unless required by applicable law or agreed to in writing,
  16652. * software distributed under the License is distributed on an
  16653. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16654. * KIND, either express or implied. See the License for the
  16655. * specific language governing permissions and limitations
  16656. * under the License.
  16657. */
  16658. var inner$2 = makeInner();
  16659. function getNearestColorPalette(colors, requestColorNum) {
  16660. var paletteNum = colors.length;
  16661. // TODO colors must be in order
  16662. for (var i = 0; i < paletteNum; i++) {
  16663. if (colors[i].length > requestColorNum) {
  16664. return colors[i];
  16665. }
  16666. }
  16667. return colors[paletteNum - 1];
  16668. }
  16669. var colorPaletteMixin = {
  16670. clearColorPalette: function () {
  16671. inner$2(this).colorIdx = 0;
  16672. inner$2(this).colorNameMap = {};
  16673. },
  16674. /**
  16675. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  16676. * twise with the same parameters will get different result.
  16677. * @param {Object} [scope=this]
  16678. * @param {Object} [requestColorNum]
  16679. * @return {string} color string.
  16680. */
  16681. getColorFromPalette: function (name, scope, requestColorNum) {
  16682. scope = scope || this;
  16683. var scopeFields = inner$2(scope);
  16684. var colorIdx = scopeFields.colorIdx || 0;
  16685. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  16686. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16687. if (colorNameMap.hasOwnProperty(name)) {
  16688. return colorNameMap[name];
  16689. }
  16690. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16691. var layeredColorPalette = this.get('colorLayer', true);
  16692. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  16693. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  16694. // In case can't find in layered color palette.
  16695. colorPalette = colorPalette || defaultColorPalette;
  16696. if (!colorPalette || !colorPalette.length) {
  16697. return;
  16698. }
  16699. var color = colorPalette[colorIdx];
  16700. if (name) {
  16701. colorNameMap[name] = color;
  16702. }
  16703. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16704. return color;
  16705. }
  16706. };
  16707. /*
  16708. * Licensed to the Apache Software Foundation (ASF) under one
  16709. * or more contributor license agreements. See the NOTICE file
  16710. * distributed with this work for additional information
  16711. * regarding copyright ownership. The ASF licenses this file
  16712. * to you under the Apache License, Version 2.0 (the
  16713. * "License"); you may not use this file except in compliance
  16714. * with the License. You may obtain a copy of the License at
  16715. *
  16716. * http://www.apache.org/licenses/LICENSE-2.0
  16717. *
  16718. * Unless required by applicable law or agreed to in writing,
  16719. * software distributed under the License is distributed on an
  16720. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16721. * KIND, either express or implied. See the License for the
  16722. * specific language governing permissions and limitations
  16723. * under the License.
  16724. */
  16725. /**
  16726. * Helper for model references.
  16727. * There are many manners to refer axis/coordSys.
  16728. */
  16729. // TODO
  16730. // merge relevant logic to this file?
  16731. // check: "modelHelper" of tooltip and "BrushTargetManager".
  16732. /**
  16733. * @return {Object} For example:
  16734. * {
  16735. * coordSysName: 'cartesian2d',
  16736. * coordSysDims: ['x', 'y', ...],
  16737. * axisMap: HashMap({
  16738. * x: xAxisModel,
  16739. * y: yAxisModel
  16740. * }),
  16741. * categoryAxisMap: HashMap({
  16742. * x: xAxisModel,
  16743. * y: undefined
  16744. * }),
  16745. * // It also indicate that whether there is category axis.
  16746. * firstCategoryDimIndex: 1,
  16747. * // To replace user specified encode.
  16748. * }
  16749. */
  16750. function getCoordSysDefineBySeries(seriesModel) {
  16751. var coordSysName = seriesModel.get('coordinateSystem');
  16752. var result = {
  16753. coordSysName: coordSysName,
  16754. coordSysDims: [],
  16755. axisMap: createHashMap(),
  16756. categoryAxisMap: createHashMap()
  16757. };
  16758. var fetch = fetchers[coordSysName];
  16759. if (fetch) {
  16760. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  16761. return result;
  16762. }
  16763. }
  16764. var fetchers = {
  16765. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  16766. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  16767. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  16768. if (__DEV__) {
  16769. if (!xAxisModel) {
  16770. throw new Error('xAxis "' + retrieve(
  16771. seriesModel.get('xAxisIndex'),
  16772. seriesModel.get('xAxisId'),
  16773. 0
  16774. ) + '" not found');
  16775. }
  16776. if (!yAxisModel) {
  16777. throw new Error('yAxis "' + retrieve(
  16778. seriesModel.get('xAxisIndex'),
  16779. seriesModel.get('yAxisId'),
  16780. 0
  16781. ) + '" not found');
  16782. }
  16783. }
  16784. result.coordSysDims = ['x', 'y'];
  16785. axisMap.set('x', xAxisModel);
  16786. axisMap.set('y', yAxisModel);
  16787. if (isCategory(xAxisModel)) {
  16788. categoryAxisMap.set('x', xAxisModel);
  16789. result.firstCategoryDimIndex = 0;
  16790. }
  16791. if (isCategory(yAxisModel)) {
  16792. categoryAxisMap.set('y', yAxisModel);
  16793. result.firstCategoryDimIndex = 1;
  16794. }
  16795. },
  16796. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  16797. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  16798. if (__DEV__) {
  16799. if (!singleAxisModel) {
  16800. throw new Error('singleAxis should be specified.');
  16801. }
  16802. }
  16803. result.coordSysDims = ['single'];
  16804. axisMap.set('single', singleAxisModel);
  16805. if (isCategory(singleAxisModel)) {
  16806. categoryAxisMap.set('single', singleAxisModel);
  16807. result.firstCategoryDimIndex = 0;
  16808. }
  16809. },
  16810. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  16811. var polarModel = seriesModel.getReferringComponents('polar')[0];
  16812. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  16813. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  16814. if (__DEV__) {
  16815. if (!angleAxisModel) {
  16816. throw new Error('angleAxis option not found');
  16817. }
  16818. if (!radiusAxisModel) {
  16819. throw new Error('radiusAxis option not found');
  16820. }
  16821. }
  16822. result.coordSysDims = ['radius', 'angle'];
  16823. axisMap.set('radius', radiusAxisModel);
  16824. axisMap.set('angle', angleAxisModel);
  16825. if (isCategory(radiusAxisModel)) {
  16826. categoryAxisMap.set('radius', radiusAxisModel);
  16827. result.firstCategoryDimIndex = 0;
  16828. }
  16829. if (isCategory(angleAxisModel)) {
  16830. categoryAxisMap.set('angle', angleAxisModel);
  16831. result.firstCategoryDimIndex = 1;
  16832. }
  16833. },
  16834. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  16835. result.coordSysDims = ['lng', 'lat'];
  16836. },
  16837. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  16838. var ecModel = seriesModel.ecModel;
  16839. var parallelModel = ecModel.getComponent(
  16840. 'parallel', seriesModel.get('parallelIndex')
  16841. );
  16842. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  16843. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  16844. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  16845. var axisDim = coordSysDims[index];
  16846. axisMap.set(axisDim, axisModel);
  16847. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  16848. categoryAxisMap.set(axisDim, axisModel);
  16849. result.firstCategoryDimIndex = index;
  16850. }
  16851. });
  16852. }
  16853. };
  16854. function isCategory(axisModel) {
  16855. return axisModel.get('type') === 'category';
  16856. }
  16857. /*
  16858. * Licensed to the Apache Software Foundation (ASF) under one
  16859. * or more contributor license agreements. See the NOTICE file
  16860. * distributed with this work for additional information
  16861. * regarding copyright ownership. The ASF licenses this file
  16862. * to you under the Apache License, Version 2.0 (the
  16863. * "License"); you may not use this file except in compliance
  16864. * with the License. You may obtain a copy of the License at
  16865. *
  16866. * http://www.apache.org/licenses/LICENSE-2.0
  16867. *
  16868. * Unless required by applicable law or agreed to in writing,
  16869. * software distributed under the License is distributed on an
  16870. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16871. * KIND, either express or implied. See the License for the
  16872. * specific language governing permissions and limitations
  16873. * under the License.
  16874. */
  16875. // Avoid typo.
  16876. var SOURCE_FORMAT_ORIGINAL = 'original';
  16877. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16878. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16879. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16880. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16881. // ??? CHANGE A NAME
  16882. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16883. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16884. var SERIES_LAYOUT_BY_ROW = 'row';
  16885. /*
  16886. * Licensed to the Apache Software Foundation (ASF) under one
  16887. * or more contributor license agreements. See the NOTICE file
  16888. * distributed with this work for additional information
  16889. * regarding copyright ownership. The ASF licenses this file
  16890. * to you under the Apache License, Version 2.0 (the
  16891. * "License"); you may not use this file except in compliance
  16892. * with the License. You may obtain a copy of the License at
  16893. *
  16894. * http://www.apache.org/licenses/LICENSE-2.0
  16895. *
  16896. * Unless required by applicable law or agreed to in writing,
  16897. * software distributed under the License is distributed on an
  16898. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16899. * KIND, either express or implied. See the License for the
  16900. * specific language governing permissions and limitations
  16901. * under the License.
  16902. */
  16903. /**
  16904. * [sourceFormat]
  16905. *
  16906. * + "original":
  16907. * This format is only used in series.data, where
  16908. * itemStyle can be specified in data item.
  16909. *
  16910. * + "arrayRows":
  16911. * [
  16912. * ['product', 'score', 'amount'],
  16913. * ['Matcha Latte', 89.3, 95.8],
  16914. * ['Milk Tea', 92.1, 89.4],
  16915. * ['Cheese Cocoa', 94.4, 91.2],
  16916. * ['Walnut Brownie', 85.4, 76.9]
  16917. * ]
  16918. *
  16919. * + "objectRows":
  16920. * [
  16921. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  16922. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  16923. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  16924. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  16925. * ]
  16926. *
  16927. * + "keyedColumns":
  16928. * {
  16929. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  16930. * 'count': [823, 235, 1042, 988],
  16931. * 'score': [95.8, 81.4, 91.2, 76.9]
  16932. * }
  16933. *
  16934. * + "typedArray"
  16935. *
  16936. * + "unknown"
  16937. */
  16938. /**
  16939. * @constructor
  16940. * @param {Object} fields
  16941. * @param {string} fields.sourceFormat
  16942. * @param {Array|Object} fields.fromDataset
  16943. * @param {Array|Object} [fields.data]
  16944. * @param {string} [seriesLayoutBy='column']
  16945. * @param {Array.<Object|string>} [dimensionsDefine]
  16946. * @param {Objet|HashMap} [encodeDefine]
  16947. * @param {number} [startIndex=0]
  16948. * @param {number} [dimensionsDetectCount]
  16949. */
  16950. function Source(fields) {
  16951. /**
  16952. * @type {boolean}
  16953. */
  16954. this.fromDataset = fields.fromDataset;
  16955. /**
  16956. * Not null/undefined.
  16957. * @type {Array|Object}
  16958. */
  16959. this.data = fields.data || (
  16960. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  16961. );
  16962. /**
  16963. * See also "detectSourceFormat".
  16964. * Not null/undefined.
  16965. * @type {string}
  16966. */
  16967. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  16968. /**
  16969. * 'row' or 'column'
  16970. * Not null/undefined.
  16971. * @type {string} seriesLayoutBy
  16972. */
  16973. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  16974. /**
  16975. * dimensions definition in option.
  16976. * can be null/undefined.
  16977. * @type {Array.<Object|string>}
  16978. */
  16979. this.dimensionsDefine = fields.dimensionsDefine;
  16980. /**
  16981. * encode definition in option.
  16982. * can be null/undefined.
  16983. * @type {Objet|HashMap}
  16984. */
  16985. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  16986. /**
  16987. * Not null/undefined, uint.
  16988. * @type {number}
  16989. */
  16990. this.startIndex = fields.startIndex || 0;
  16991. /**
  16992. * Can be null/undefined (when unknown), uint.
  16993. * @type {number}
  16994. */
  16995. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  16996. }
  16997. /**
  16998. * Wrap original series data for some compatibility cases.
  16999. */
  17000. Source.seriesDataToSource = function (data) {
  17001. return new Source({
  17002. data: data,
  17003. sourceFormat: isTypedArray(data)
  17004. ? SOURCE_FORMAT_TYPED_ARRAY
  17005. : SOURCE_FORMAT_ORIGINAL,
  17006. fromDataset: false
  17007. });
  17008. };
  17009. enableClassCheck(Source);
  17010. /*
  17011. * Licensed to the Apache Software Foundation (ASF) under one
  17012. * or more contributor license agreements. See the NOTICE file
  17013. * distributed with this work for additional information
  17014. * regarding copyright ownership. The ASF licenses this file
  17015. * to you under the Apache License, Version 2.0 (the
  17016. * "License"); you may not use this file except in compliance
  17017. * with the License. You may obtain a copy of the License at
  17018. *
  17019. * http://www.apache.org/licenses/LICENSE-2.0
  17020. *
  17021. * Unless required by applicable law or agreed to in writing,
  17022. * software distributed under the License is distributed on an
  17023. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17024. * KIND, either express or implied. See the License for the
  17025. * specific language governing permissions and limitations
  17026. * under the License.
  17027. */
  17028. var inner$3 = makeInner();
  17029. /**
  17030. * @see {module:echarts/data/Source}
  17031. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17032. * @return {string} sourceFormat
  17033. */
  17034. function detectSourceFormat(datasetModel) {
  17035. var data = datasetModel.option.source;
  17036. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17037. if (isTypedArray(data)) {
  17038. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17039. }
  17040. else if (isArray(data)) {
  17041. // FIXME Whether tolerate null in top level array?
  17042. for (var i = 0, len = data.length; i < len; i++) {
  17043. var item = data[i];
  17044. if (item == null) {
  17045. continue;
  17046. }
  17047. else if (isArray(item)) {
  17048. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17049. break;
  17050. }
  17051. else if (isObject$1(item)) {
  17052. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17053. break;
  17054. }
  17055. }
  17056. }
  17057. else if (isObject$1(data)) {
  17058. for (var key in data) {
  17059. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17060. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17061. break;
  17062. }
  17063. }
  17064. }
  17065. else if (data != null) {
  17066. throw new Error('Invalid data');
  17067. }
  17068. inner$3(datasetModel).sourceFormat = sourceFormat;
  17069. }
  17070. /**
  17071. * [Scenarios]:
  17072. * (1) Provide source data directly:
  17073. * series: {
  17074. * encode: {...},
  17075. * dimensions: [...]
  17076. * seriesLayoutBy: 'row',
  17077. * data: [[...]]
  17078. * }
  17079. * (2) Refer to datasetModel.
  17080. * series: [{
  17081. * encode: {...}
  17082. * // Ignore datasetIndex means `datasetIndex: 0`
  17083. * // and the dimensions defination in dataset is used
  17084. * }, {
  17085. * encode: {...},
  17086. * seriesLayoutBy: 'column',
  17087. * datasetIndex: 1
  17088. * }]
  17089. *
  17090. * Get data from series itself or datset.
  17091. * @return {module:echarts/data/Source} source
  17092. */
  17093. function getSource(seriesModel) {
  17094. return inner$3(seriesModel).source;
  17095. }
  17096. /**
  17097. * MUST be called before mergeOption of all series.
  17098. * @param {module:echarts/model/Global} ecModel
  17099. */
  17100. function resetSourceDefaulter(ecModel) {
  17101. // `datasetMap` is used to make default encode.
  17102. inner$3(ecModel).datasetMap = createHashMap();
  17103. }
  17104. /**
  17105. * [Caution]:
  17106. * MUST be called after series option merged and
  17107. * before "series.getInitailData()" called.
  17108. *
  17109. * [The rule of making default encode]:
  17110. * Category axis (if exists) alway map to the first dimension.
  17111. * Each other axis occupies a subsequent dimension.
  17112. *
  17113. * [Why make default encode]:
  17114. * Simplify the typing of encode in option, avoiding the case like that:
  17115. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17116. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17117. *
  17118. * @param {module:echarts/model/Series} seriesModel
  17119. */
  17120. function prepareSource(seriesModel) {
  17121. var seriesOption = seriesModel.option;
  17122. var data = seriesOption.data;
  17123. var sourceFormat = isTypedArray(data)
  17124. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17125. var fromDataset = false;
  17126. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17127. var sourceHeader = seriesOption.sourceHeader;
  17128. var dimensionsDefine = seriesOption.dimensions;
  17129. var datasetModel = getDatasetModel(seriesModel);
  17130. if (datasetModel) {
  17131. var datasetOption = datasetModel.option;
  17132. data = datasetOption.source;
  17133. sourceFormat = inner$3(datasetModel).sourceFormat;
  17134. fromDataset = true;
  17135. // These settings from series has higher priority.
  17136. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17137. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17138. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17139. }
  17140. var completeResult = completeBySourceData(
  17141. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17142. );
  17143. // Note: dataset option does not have `encode`.
  17144. var encodeDefine = seriesOption.encode;
  17145. if (!encodeDefine && datasetModel) {
  17146. encodeDefine = makeDefaultEncode(
  17147. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17148. );
  17149. }
  17150. inner$3(seriesModel).source = new Source({
  17151. data: data,
  17152. fromDataset: fromDataset,
  17153. seriesLayoutBy: seriesLayoutBy,
  17154. sourceFormat: sourceFormat,
  17155. dimensionsDefine: completeResult.dimensionsDefine,
  17156. startIndex: completeResult.startIndex,
  17157. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17158. encodeDefine: encodeDefine
  17159. });
  17160. }
  17161. // return {startIndex, dimensionsDefine, dimensionsCount}
  17162. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17163. if (!data) {
  17164. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17165. }
  17166. var dimensionsDetectCount;
  17167. var startIndex;
  17168. var findPotentialName;
  17169. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17170. // Rule: Most of the first line are string: it is header.
  17171. // Caution: consider a line with 5 string and 1 number,
  17172. // it still can not be sure it is a head, because the
  17173. // 5 string may be 5 values of category columns.
  17174. if (sourceHeader === 'auto' || sourceHeader == null) {
  17175. arrayRowsTravelFirst(function (val) {
  17176. // '-' is regarded as null/undefined.
  17177. if (val != null && val !== '-') {
  17178. if (isString(val)) {
  17179. startIndex == null && (startIndex = 1);
  17180. }
  17181. else {
  17182. startIndex = 0;
  17183. }
  17184. }
  17185. // 10 is an experience number, avoid long loop.
  17186. }, seriesLayoutBy, data, 10);
  17187. }
  17188. else {
  17189. startIndex = sourceHeader ? 1 : 0;
  17190. }
  17191. if (!dimensionsDefine && startIndex === 1) {
  17192. dimensionsDefine = [];
  17193. arrayRowsTravelFirst(function (val, index) {
  17194. dimensionsDefine[index] = val != null ? val : '';
  17195. }, seriesLayoutBy, data);
  17196. }
  17197. dimensionsDetectCount = dimensionsDefine
  17198. ? dimensionsDefine.length
  17199. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17200. ? data.length
  17201. : data[0]
  17202. ? data[0].length
  17203. : null;
  17204. }
  17205. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17206. if (!dimensionsDefine) {
  17207. dimensionsDefine = objectRowsCollectDimensions(data);
  17208. findPotentialName = true;
  17209. }
  17210. }
  17211. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17212. if (!dimensionsDefine) {
  17213. dimensionsDefine = [];
  17214. findPotentialName = true;
  17215. each$1(data, function (colArr, key) {
  17216. dimensionsDefine.push(key);
  17217. });
  17218. }
  17219. }
  17220. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17221. var value0 = getDataItemValue(data[0]);
  17222. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17223. }
  17224. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17225. if (__DEV__) {
  17226. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  17227. }
  17228. }
  17229. var potentialNameDimIndex;
  17230. if (findPotentialName) {
  17231. each$1(dimensionsDefine, function (dim, idx) {
  17232. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17233. potentialNameDimIndex = idx;
  17234. }
  17235. });
  17236. }
  17237. return {
  17238. startIndex: startIndex,
  17239. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17240. dimensionsDetectCount: dimensionsDetectCount,
  17241. potentialNameDimIndex: potentialNameDimIndex
  17242. // TODO: potentialIdDimIdx
  17243. };
  17244. }
  17245. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17246. // which is reasonable. But dimension name is duplicated.
  17247. // Returns undefined or an array contains only object without null/undefiend or string.
  17248. function normalizeDimensionsDefine(dimensionsDefine) {
  17249. if (!dimensionsDefine) {
  17250. // The meaning of null/undefined is different from empty array.
  17251. return;
  17252. }
  17253. var nameMap = createHashMap();
  17254. return map(dimensionsDefine, function (item, index) {
  17255. item = extend({}, isObject$1(item) ? item : {name: item});
  17256. // User can set null in dimensions.
  17257. // We dont auto specify name, othewise a given name may
  17258. // cause it be refered unexpectedly.
  17259. if (item.name == null) {
  17260. return item;
  17261. }
  17262. // Also consider number form like 2012.
  17263. item.name += '';
  17264. // User may also specify displayName.
  17265. // displayName will always exists except user not
  17266. // specified or dim name is not specified or detected.
  17267. // (A auto generated dim name will not be used as
  17268. // displayName).
  17269. if (item.displayName == null) {
  17270. item.displayName = item.name;
  17271. }
  17272. var exist = nameMap.get(item.name);
  17273. if (!exist) {
  17274. nameMap.set(item.name, {count: 1});
  17275. }
  17276. else {
  17277. item.name += '-' + exist.count++;
  17278. }
  17279. return item;
  17280. });
  17281. }
  17282. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  17283. maxLoop == null && (maxLoop = Infinity);
  17284. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17285. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17286. cb(data[i] ? data[i][0] : null, i);
  17287. }
  17288. }
  17289. else {
  17290. var value0 = data[0] || [];
  17291. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  17292. cb(value0[i], i);
  17293. }
  17294. }
  17295. }
  17296. function objectRowsCollectDimensions(data) {
  17297. var firstIndex = 0;
  17298. var obj;
  17299. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  17300. if (obj) {
  17301. var dimensions = [];
  17302. each$1(obj, function (value, key) {
  17303. dimensions.push(key);
  17304. });
  17305. return dimensions;
  17306. }
  17307. }
  17308. // ??? TODO merge to completedimensions, where also has
  17309. // default encode making logic. And the default rule
  17310. // should depends on series? consider 'map'.
  17311. function makeDefaultEncode(
  17312. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17313. ) {
  17314. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  17315. var encode = {};
  17316. // var encodeTooltip = [];
  17317. // var encodeLabel = [];
  17318. var encodeItemName = [];
  17319. var encodeSeriesName = [];
  17320. var seriesType = seriesModel.subType;
  17321. // ??? TODO refactor: provide by series itself.
  17322. // Consider the case: 'map' series is based on geo coordSys,
  17323. // 'graph', 'heatmap' can be based on cartesian. But can not
  17324. // give default rule simply here.
  17325. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  17326. var cSeriesMap = createHashMap([
  17327. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  17328. ]);
  17329. // Usually in this case series will use the first data
  17330. // dimension as the "value" dimension, or other default
  17331. // processes respectively.
  17332. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  17333. var ecModel = seriesModel.ecModel;
  17334. var datasetMap = inner$3(ecModel).datasetMap;
  17335. var key = datasetModel.uid + '_' + seriesLayoutBy;
  17336. var datasetRecord = datasetMap.get(key)
  17337. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  17338. // TODO
  17339. // Auto detect first time axis and do arrangement.
  17340. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  17341. // In value way.
  17342. if (coordSysDefine.firstCategoryDimIndex == null) {
  17343. var dataDim = datasetRecord.valueWayDim++;
  17344. encode[coordDim] = dataDim;
  17345. // ??? TODO give a better default series name rule?
  17346. // especially when encode x y specified.
  17347. // consider: when mutiple series share one dimension
  17348. // category axis, series name should better use
  17349. // the other dimsion name. On the other hand, use
  17350. // both dimensions name.
  17351. encodeSeriesName.push(dataDim);
  17352. // encodeTooltip.push(dataDim);
  17353. // encodeLabel.push(dataDim);
  17354. }
  17355. // In category way, category axis.
  17356. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  17357. encode[coordDim] = 0;
  17358. encodeItemName.push(0);
  17359. }
  17360. // In category way, non-category axis.
  17361. else {
  17362. var dataDim = datasetRecord.categoryWayDim++;
  17363. encode[coordDim] = dataDim;
  17364. // encodeTooltip.push(dataDim);
  17365. // encodeLabel.push(dataDim);
  17366. encodeSeriesName.push(dataDim);
  17367. }
  17368. });
  17369. }
  17370. // Do not make a complex rule! Hard to code maintain and not necessary.
  17371. // ??? TODO refactor: provide by series itself.
  17372. // [{name: ..., value: ...}, ...] like:
  17373. else if (nSeriesMap.get(seriesType) != null) {
  17374. // Find the first not ordinal. (5 is an experience value)
  17375. var firstNotOrdinal;
  17376. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  17377. if (!doGuessOrdinal(
  17378. data, sourceFormat, seriesLayoutBy,
  17379. completeResult.dimensionsDefine, completeResult.startIndex, i
  17380. )) {
  17381. firstNotOrdinal = i;
  17382. }
  17383. }
  17384. if (firstNotOrdinal != null) {
  17385. encode.value = firstNotOrdinal;
  17386. var nameDimIndex = completeResult.potentialNameDimIndex
  17387. || Math.max(firstNotOrdinal - 1, 0);
  17388. // By default, label use itemName in charts.
  17389. // So we dont set encodeLabel here.
  17390. encodeSeriesName.push(nameDimIndex);
  17391. encodeItemName.push(nameDimIndex);
  17392. // encodeTooltip.push(firstNotOrdinal);
  17393. }
  17394. }
  17395. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  17396. // encodeLabel.length && (encode.label = encodeLabel);
  17397. encodeItemName.length && (encode.itemName = encodeItemName);
  17398. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17399. return encode;
  17400. }
  17401. /**
  17402. * If return null/undefined, indicate that should not use datasetModel.
  17403. */
  17404. function getDatasetModel(seriesModel) {
  17405. var option = seriesModel.option;
  17406. // Caution: consider the scenario:
  17407. // A dataset is declared and a series is not expected to use the dataset,
  17408. // and at the beginning `setOption({series: { noData })` (just prepare other
  17409. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17410. // the user should set an empty array to avoid that dataset is used by default.
  17411. var thisData = option.data;
  17412. if (!thisData) {
  17413. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  17414. }
  17415. }
  17416. /**
  17417. * The rule should not be complex, otherwise user might not
  17418. * be able to known where the data is wrong.
  17419. * The code is ugly, but how to make it neat?
  17420. *
  17421. * @param {module:echars/data/Source} source
  17422. * @param {number} dimIndex
  17423. * @return {boolean} Whether ordinal.
  17424. */
  17425. function guessOrdinal(source, dimIndex) {
  17426. return doGuessOrdinal(
  17427. source.data,
  17428. source.sourceFormat,
  17429. source.seriesLayoutBy,
  17430. source.dimensionsDefine,
  17431. source.startIndex,
  17432. dimIndex
  17433. );
  17434. }
  17435. // dimIndex may be overflow source data.
  17436. function doGuessOrdinal(
  17437. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  17438. ) {
  17439. var result;
  17440. // Experience value.
  17441. var maxLoop = 5;
  17442. if (isTypedArray(data)) {
  17443. return false;
  17444. }
  17445. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17446. // always exists in source.
  17447. var dimName;
  17448. if (dimensionsDefine) {
  17449. dimName = dimensionsDefine[dimIndex];
  17450. dimName = isObject$1(dimName) ? dimName.name : dimName;
  17451. }
  17452. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17453. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17454. var sample = data[dimIndex];
  17455. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17456. if ((result = detectValue(sample[startIndex + i])) != null) {
  17457. return result;
  17458. }
  17459. }
  17460. }
  17461. else {
  17462. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17463. var row = data[startIndex + i];
  17464. if (row && (result = detectValue(row[dimIndex])) != null) {
  17465. return result;
  17466. }
  17467. }
  17468. }
  17469. }
  17470. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17471. if (!dimName) {
  17472. return;
  17473. }
  17474. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17475. var item = data[i];
  17476. if (item && (result = detectValue(item[dimName])) != null) {
  17477. return result;
  17478. }
  17479. }
  17480. }
  17481. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17482. if (!dimName) {
  17483. return;
  17484. }
  17485. var sample = data[dimName];
  17486. if (!sample || isTypedArray(sample)) {
  17487. return false;
  17488. }
  17489. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17490. if ((result = detectValue(sample[i])) != null) {
  17491. return result;
  17492. }
  17493. }
  17494. }
  17495. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17496. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17497. var item = data[i];
  17498. var val = getDataItemValue(item);
  17499. if (!isArray(val)) {
  17500. return false;
  17501. }
  17502. if ((result = detectValue(val[dimIndex])) != null) {
  17503. return result;
  17504. }
  17505. }
  17506. }
  17507. function detectValue(val) {
  17508. // Consider usage convenience, '1', '2' will be treated as "number".
  17509. // `isFinit('')` get `true`.
  17510. if (val != null && isFinite(val) && val !== '') {
  17511. return false;
  17512. }
  17513. else if (isString(val) && val !== '-') {
  17514. return true;
  17515. }
  17516. }
  17517. return false;
  17518. }
  17519. /*
  17520. * Licensed to the Apache Software Foundation (ASF) under one
  17521. * or more contributor license agreements. See the NOTICE file
  17522. * distributed with this work for additional information
  17523. * regarding copyright ownership. The ASF licenses this file
  17524. * to you under the Apache License, Version 2.0 (the
  17525. * "License"); you may not use this file except in compliance
  17526. * with the License. You may obtain a copy of the License at
  17527. *
  17528. * http://www.apache.org/licenses/LICENSE-2.0
  17529. *
  17530. * Unless required by applicable law or agreed to in writing,
  17531. * software distributed under the License is distributed on an
  17532. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17533. * KIND, either express or implied. See the License for the
  17534. * specific language governing permissions and limitations
  17535. * under the License.
  17536. */
  17537. /**
  17538. * ECharts global model
  17539. *
  17540. * @module {echarts/model/Global}
  17541. */
  17542. /**
  17543. * Caution: If the mechanism should be changed some day, these cases
  17544. * should be considered:
  17545. *
  17546. * (1) In `merge option` mode, if using the same option to call `setOption`
  17547. * many times, the result should be the same (try our best to ensure that).
  17548. * (2) In `merge option` mode, if a component has no id/name specified, it
  17549. * will be merged by index, and the result sequence of the components is
  17550. * consistent to the original sequence.
  17551. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17552. * `mergeOption` in module:echarts/model/OptionManager.
  17553. */
  17554. var OPTION_INNER_KEY = '\0_ec_inner';
  17555. /**
  17556. * @alias module:echarts/model/Global
  17557. *
  17558. * @param {Object} option
  17559. * @param {module:echarts/model/Model} parentModel
  17560. * @param {Object} theme
  17561. */
  17562. var GlobalModel = Model.extend({
  17563. init: function (option, parentModel, theme, optionManager) {
  17564. theme = theme || {};
  17565. this.option = null; // Mark as not initialized.
  17566. /**
  17567. * @type {module:echarts/model/Model}
  17568. * @private
  17569. */
  17570. this._theme = new Model(theme);
  17571. /**
  17572. * @type {module:echarts/model/OptionManager}
  17573. */
  17574. this._optionManager = optionManager;
  17575. },
  17576. setOption: function (option, optionPreprocessorFuncs) {
  17577. assert$1(
  17578. !(OPTION_INNER_KEY in option),
  17579. 'please use chart.getOption()'
  17580. );
  17581. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17582. this.resetOption(null);
  17583. },
  17584. /**
  17585. * @param {string} type null/undefined: reset all.
  17586. * 'recreate': force recreate all.
  17587. * 'timeline': only reset timeline option
  17588. * 'media': only reset media query option
  17589. * @return {boolean} Whether option changed.
  17590. */
  17591. resetOption: function (type) {
  17592. var optionChanged = false;
  17593. var optionManager = this._optionManager;
  17594. if (!type || type === 'recreate') {
  17595. var baseOption = optionManager.mountOption(type === 'recreate');
  17596. if (!this.option || type === 'recreate') {
  17597. initBase.call(this, baseOption);
  17598. }
  17599. else {
  17600. this.restoreData();
  17601. this.mergeOption(baseOption);
  17602. }
  17603. optionChanged = true;
  17604. }
  17605. if (type === 'timeline' || type === 'media') {
  17606. this.restoreData();
  17607. }
  17608. if (!type || type === 'recreate' || type === 'timeline') {
  17609. var timelineOption = optionManager.getTimelineOption(this);
  17610. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17611. }
  17612. if (!type || type === 'recreate' || type === 'media') {
  17613. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17614. if (mediaOptions.length) {
  17615. each$1(mediaOptions, function (mediaOption) {
  17616. this.mergeOption(mediaOption, optionChanged = true);
  17617. }, this);
  17618. }
  17619. }
  17620. return optionChanged;
  17621. },
  17622. /**
  17623. * @protected
  17624. */
  17625. mergeOption: function (newOption) {
  17626. var option = this.option;
  17627. var componentsMap = this._componentsMap;
  17628. var newCptTypes = [];
  17629. resetSourceDefaulter(this);
  17630. // If no component class, merge directly.
  17631. // For example: color, animaiton options, etc.
  17632. each$1(newOption, function (componentOption, mainType) {
  17633. if (componentOption == null) {
  17634. return;
  17635. }
  17636. if (!ComponentModel.hasClass(mainType)) {
  17637. // globalSettingTask.dirty();
  17638. option[mainType] = option[mainType] == null
  17639. ? clone(componentOption)
  17640. : merge(option[mainType], componentOption, true);
  17641. }
  17642. else if (mainType) {
  17643. newCptTypes.push(mainType);
  17644. }
  17645. });
  17646. ComponentModel.topologicalTravel(
  17647. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  17648. );
  17649. function visitComponent(mainType, dependencies) {
  17650. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17651. var mapResult = mappingToExists(
  17652. componentsMap.get(mainType), newCptOptionList
  17653. );
  17654. makeIdAndName(mapResult);
  17655. // Set mainType and complete subType.
  17656. each$1(mapResult, function (item, index) {
  17657. var opt = item.option;
  17658. if (isObject$1(opt)) {
  17659. item.keyInfo.mainType = mainType;
  17660. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17661. }
  17662. });
  17663. var dependentModels = getComponentsByTypes(
  17664. componentsMap, dependencies
  17665. );
  17666. option[mainType] = [];
  17667. componentsMap.set(mainType, []);
  17668. each$1(mapResult, function (resultItem, index) {
  17669. var componentModel = resultItem.exist;
  17670. var newCptOption = resultItem.option;
  17671. assert$1(
  17672. isObject$1(newCptOption) || componentModel,
  17673. 'Empty component definition'
  17674. );
  17675. // Consider where is no new option and should be merged using {},
  17676. // see removeEdgeAndAdd in topologicalTravel and
  17677. // ComponentModel.getAllClassMainTypes.
  17678. if (!newCptOption) {
  17679. componentModel.mergeOption({}, this);
  17680. componentModel.optionUpdated({}, false);
  17681. }
  17682. else {
  17683. var ComponentModelClass = ComponentModel.getClass(
  17684. mainType, resultItem.keyInfo.subType, true
  17685. );
  17686. if (componentModel && componentModel instanceof ComponentModelClass) {
  17687. componentModel.name = resultItem.keyInfo.name;
  17688. // componentModel.settingTask && componentModel.settingTask.dirty();
  17689. componentModel.mergeOption(newCptOption, this);
  17690. componentModel.optionUpdated(newCptOption, false);
  17691. }
  17692. else {
  17693. // PENDING Global as parent ?
  17694. var extraOpt = extend(
  17695. {
  17696. dependentModels: dependentModels,
  17697. componentIndex: index
  17698. },
  17699. resultItem.keyInfo
  17700. );
  17701. componentModel = new ComponentModelClass(
  17702. newCptOption, this, this, extraOpt
  17703. );
  17704. extend(componentModel, extraOpt);
  17705. componentModel.init(newCptOption, this, this, extraOpt);
  17706. // Call optionUpdated after init.
  17707. // newCptOption has been used as componentModel.option
  17708. // and may be merged with theme and default, so pass null
  17709. // to avoid confusion.
  17710. componentModel.optionUpdated(null, true);
  17711. }
  17712. }
  17713. componentsMap.get(mainType)[index] = componentModel;
  17714. option[mainType][index] = componentModel.option;
  17715. }, this);
  17716. // Backup series for filtering.
  17717. if (mainType === 'series') {
  17718. createSeriesIndices(this, componentsMap.get('series'));
  17719. }
  17720. }
  17721. this._seriesIndicesMap = createHashMap(
  17722. this._seriesIndices = this._seriesIndices || []
  17723. );
  17724. },
  17725. /**
  17726. * Get option for output (cloned option and inner info removed)
  17727. * @public
  17728. * @return {Object}
  17729. */
  17730. getOption: function () {
  17731. var option = clone(this.option);
  17732. each$1(option, function (opts, mainType) {
  17733. if (ComponentModel.hasClass(mainType)) {
  17734. var opts = normalizeToArray(opts);
  17735. for (var i = opts.length - 1; i >= 0; i--) {
  17736. // Remove options with inner id.
  17737. if (isIdInner(opts[i])) {
  17738. opts.splice(i, 1);
  17739. }
  17740. }
  17741. option[mainType] = opts;
  17742. }
  17743. });
  17744. delete option[OPTION_INNER_KEY];
  17745. return option;
  17746. },
  17747. /**
  17748. * @return {module:echarts/model/Model}
  17749. */
  17750. getTheme: function () {
  17751. return this._theme;
  17752. },
  17753. /**
  17754. * @param {string} mainType
  17755. * @param {number} [idx=0]
  17756. * @return {module:echarts/model/Component}
  17757. */
  17758. getComponent: function (mainType, idx) {
  17759. var list = this._componentsMap.get(mainType);
  17760. if (list) {
  17761. return list[idx || 0];
  17762. }
  17763. },
  17764. /**
  17765. * If none of index and id and name used, return all components with mainType.
  17766. * @param {Object} condition
  17767. * @param {string} condition.mainType
  17768. * @param {string} [condition.subType] If ignore, only query by mainType
  17769. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17770. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17771. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17772. * @return {Array.<module:echarts/model/Component>}
  17773. */
  17774. queryComponents: function (condition) {
  17775. var mainType = condition.mainType;
  17776. if (!mainType) {
  17777. return [];
  17778. }
  17779. var index = condition.index;
  17780. var id = condition.id;
  17781. var name = condition.name;
  17782. var cpts = this._componentsMap.get(mainType);
  17783. if (!cpts || !cpts.length) {
  17784. return [];
  17785. }
  17786. var result;
  17787. if (index != null) {
  17788. if (!isArray(index)) {
  17789. index = [index];
  17790. }
  17791. result = filter(map(index, function (idx) {
  17792. return cpts[idx];
  17793. }), function (val) {
  17794. return !!val;
  17795. });
  17796. }
  17797. else if (id != null) {
  17798. var isIdArray = isArray(id);
  17799. result = filter(cpts, function (cpt) {
  17800. return (isIdArray && indexOf(id, cpt.id) >= 0)
  17801. || (!isIdArray && cpt.id === id);
  17802. });
  17803. }
  17804. else if (name != null) {
  17805. var isNameArray = isArray(name);
  17806. result = filter(cpts, function (cpt) {
  17807. return (isNameArray && indexOf(name, cpt.name) >= 0)
  17808. || (!isNameArray && cpt.name === name);
  17809. });
  17810. }
  17811. else {
  17812. // Return all components with mainType
  17813. result = cpts.slice();
  17814. }
  17815. return filterBySubType(result, condition);
  17816. },
  17817. /**
  17818. * The interface is different from queryComponents,
  17819. * which is convenient for inner usage.
  17820. *
  17821. * @usage
  17822. * var result = findComponents(
  17823. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17824. * );
  17825. * var result = findComponents(
  17826. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17827. * );
  17828. * var result = findComponents(
  17829. * {mainType: 'series'},
  17830. * function (model, index) {...}
  17831. * );
  17832. * // result like [component0, componnet1, ...]
  17833. *
  17834. * @param {Object} condition
  17835. * @param {string} condition.mainType Mandatory.
  17836. * @param {string} [condition.subType] Optional.
  17837. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17838. * where xxx is mainType.
  17839. * If query attribute is null/undefined or has no index/id/name,
  17840. * do not filtering by query conditions, which is convenient for
  17841. * no-payload situations or when target of action is global.
  17842. * @param {Function} [condition.filter] parameter: component, return boolean.
  17843. * @return {Array.<module:echarts/model/Component>}
  17844. */
  17845. findComponents: function (condition) {
  17846. var query = condition.query;
  17847. var mainType = condition.mainType;
  17848. var queryCond = getQueryCond(query);
  17849. var result = queryCond
  17850. ? this.queryComponents(queryCond)
  17851. : this._componentsMap.get(mainType);
  17852. return doFilter(filterBySubType(result, condition));
  17853. function getQueryCond(q) {
  17854. var indexAttr = mainType + 'Index';
  17855. var idAttr = mainType + 'Id';
  17856. var nameAttr = mainType + 'Name';
  17857. return q && (
  17858. q[indexAttr] != null
  17859. || q[idAttr] != null
  17860. || q[nameAttr] != null
  17861. )
  17862. ? {
  17863. mainType: mainType,
  17864. // subType will be filtered finally.
  17865. index: q[indexAttr],
  17866. id: q[idAttr],
  17867. name: q[nameAttr]
  17868. }
  17869. : null;
  17870. }
  17871. function doFilter(res) {
  17872. return condition.filter
  17873. ? filter(res, condition.filter)
  17874. : res;
  17875. }
  17876. },
  17877. /**
  17878. * @usage
  17879. * eachComponent('legend', function (legendModel, index) {
  17880. * ...
  17881. * });
  17882. * eachComponent(function (componentType, model, index) {
  17883. * // componentType does not include subType
  17884. * // (componentType is 'xxx' but not 'xxx.aa')
  17885. * });
  17886. * eachComponent(
  17887. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17888. * function (model, index) {...}
  17889. * );
  17890. * eachComponent(
  17891. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17892. * function (model, index) {...}
  17893. * );
  17894. *
  17895. * @param {string|Object=} mainType When mainType is object, the definition
  17896. * is the same as the method 'findComponents'.
  17897. * @param {Function} cb
  17898. * @param {*} context
  17899. */
  17900. eachComponent: function (mainType, cb, context) {
  17901. var componentsMap = this._componentsMap;
  17902. if (typeof mainType === 'function') {
  17903. context = cb;
  17904. cb = mainType;
  17905. componentsMap.each(function (components, componentType) {
  17906. each$1(components, function (component, index) {
  17907. cb.call(context, componentType, component, index);
  17908. });
  17909. });
  17910. }
  17911. else if (isString(mainType)) {
  17912. each$1(componentsMap.get(mainType), cb, context);
  17913. }
  17914. else if (isObject$1(mainType)) {
  17915. var queryResult = this.findComponents(mainType);
  17916. each$1(queryResult, cb, context);
  17917. }
  17918. },
  17919. /**
  17920. * @param {string} name
  17921. * @return {Array.<module:echarts/model/Series>}
  17922. */
  17923. getSeriesByName: function (name) {
  17924. var series = this._componentsMap.get('series');
  17925. return filter(series, function (oneSeries) {
  17926. return oneSeries.name === name;
  17927. });
  17928. },
  17929. /**
  17930. * @param {number} seriesIndex
  17931. * @return {module:echarts/model/Series}
  17932. */
  17933. getSeriesByIndex: function (seriesIndex) {
  17934. return this._componentsMap.get('series')[seriesIndex];
  17935. },
  17936. /**
  17937. * Get series list before filtered by type.
  17938. * FIXME: rename to getRawSeriesByType?
  17939. *
  17940. * @param {string} subType
  17941. * @return {Array.<module:echarts/model/Series>}
  17942. */
  17943. getSeriesByType: function (subType) {
  17944. var series = this._componentsMap.get('series');
  17945. return filter(series, function (oneSeries) {
  17946. return oneSeries.subType === subType;
  17947. });
  17948. },
  17949. /**
  17950. * @return {Array.<module:echarts/model/Series>}
  17951. */
  17952. getSeries: function () {
  17953. return this._componentsMap.get('series').slice();
  17954. },
  17955. /**
  17956. * @return {number}
  17957. */
  17958. getSeriesCount: function () {
  17959. return this._componentsMap.get('series').length;
  17960. },
  17961. /**
  17962. * After filtering, series may be different
  17963. * frome raw series.
  17964. *
  17965. * @param {Function} cb
  17966. * @param {*} context
  17967. */
  17968. eachSeries: function (cb, context) {
  17969. assertSeriesInitialized(this);
  17970. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17971. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17972. cb.call(context, series, rawSeriesIndex);
  17973. }, this);
  17974. },
  17975. /**
  17976. * Iterate raw series before filtered.
  17977. *
  17978. * @param {Function} cb
  17979. * @param {*} context
  17980. */
  17981. eachRawSeries: function (cb, context) {
  17982. each$1(this._componentsMap.get('series'), cb, context);
  17983. },
  17984. /**
  17985. * After filtering, series may be different.
  17986. * frome raw series.
  17987. *
  17988. * @parma {string} subType
  17989. * @param {Function} cb
  17990. * @param {*} context
  17991. */
  17992. eachSeriesByType: function (subType, cb, context) {
  17993. assertSeriesInitialized(this);
  17994. each$1(this._seriesIndices, function (rawSeriesIndex) {
  17995. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17996. if (series.subType === subType) {
  17997. cb.call(context, series, rawSeriesIndex);
  17998. }
  17999. }, this);
  18000. },
  18001. /**
  18002. * Iterate raw series before filtered of given type.
  18003. *
  18004. * @parma {string} subType
  18005. * @param {Function} cb
  18006. * @param {*} context
  18007. */
  18008. eachRawSeriesByType: function (subType, cb, context) {
  18009. return each$1(this.getSeriesByType(subType), cb, context);
  18010. },
  18011. /**
  18012. * @param {module:echarts/model/Series} seriesModel
  18013. */
  18014. isSeriesFiltered: function (seriesModel) {
  18015. assertSeriesInitialized(this);
  18016. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18017. },
  18018. /**
  18019. * @return {Array.<number>}
  18020. */
  18021. getCurrentSeriesIndices: function () {
  18022. return (this._seriesIndices || []).slice();
  18023. },
  18024. /**
  18025. * @param {Function} cb
  18026. * @param {*} context
  18027. */
  18028. filterSeries: function (cb, context) {
  18029. assertSeriesInitialized(this);
  18030. var filteredSeries = filter(
  18031. this._componentsMap.get('series'), cb, context
  18032. );
  18033. createSeriesIndices(this, filteredSeries);
  18034. },
  18035. restoreData: function (payload) {
  18036. var componentsMap = this._componentsMap;
  18037. createSeriesIndices(this, componentsMap.get('series'));
  18038. var componentTypes = [];
  18039. componentsMap.each(function (components, componentType) {
  18040. componentTypes.push(componentType);
  18041. });
  18042. ComponentModel.topologicalTravel(
  18043. componentTypes,
  18044. ComponentModel.getAllClassMainTypes(),
  18045. function (componentType, dependencies) {
  18046. each$1(componentsMap.get(componentType), function (component) {
  18047. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18048. && component.restoreData();
  18049. });
  18050. }
  18051. );
  18052. }
  18053. });
  18054. function isNotTargetSeries(seriesModel, payload) {
  18055. if (payload) {
  18056. var index = payload.seiresIndex;
  18057. var id = payload.seriesId;
  18058. var name = payload.seriesName;
  18059. return (index != null && seriesModel.componentIndex !== index)
  18060. || (id != null && seriesModel.id !== id)
  18061. || (name != null && seriesModel.name !== name);
  18062. }
  18063. }
  18064. /**
  18065. * @inner
  18066. */
  18067. function mergeTheme(option, theme) {
  18068. // PENDING
  18069. // NOT use `colorLayer` in theme if option has `color`
  18070. var notMergeColorLayer = option.color && !option.colorLayer;
  18071. each$1(theme, function (themeItem, name) {
  18072. if (name === 'colorLayer' && notMergeColorLayer) {
  18073. return;
  18074. }
  18075. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18076. if (!ComponentModel.hasClass(name)) {
  18077. if (typeof themeItem === 'object') {
  18078. option[name] = !option[name]
  18079. ? clone(themeItem)
  18080. : merge(option[name], themeItem, false);
  18081. }
  18082. else {
  18083. if (option[name] == null) {
  18084. option[name] = themeItem;
  18085. }
  18086. }
  18087. }
  18088. });
  18089. }
  18090. function initBase(baseOption) {
  18091. baseOption = baseOption;
  18092. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18093. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18094. this.option = {};
  18095. this.option[OPTION_INNER_KEY] = 1;
  18096. /**
  18097. * Init with series: [], in case of calling findSeries method
  18098. * before series initialized.
  18099. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18100. * @private
  18101. */
  18102. this._componentsMap = createHashMap({series: []});
  18103. /**
  18104. * Mapping between filtered series list and raw series list.
  18105. * key: filtered series indices, value: raw series indices.
  18106. * @type {Array.<nubmer>}
  18107. * @private
  18108. */
  18109. this._seriesIndices;
  18110. this._seriesIndicesMap;
  18111. mergeTheme(baseOption, this._theme.option);
  18112. // TODO Needs clone when merging to the unexisted property
  18113. merge(baseOption, globalDefault, false);
  18114. this.mergeOption(baseOption);
  18115. }
  18116. /**
  18117. * @inner
  18118. * @param {Array.<string>|string} types model types
  18119. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18120. */
  18121. function getComponentsByTypes(componentsMap, types) {
  18122. if (!isArray(types)) {
  18123. types = types ? [types] : [];
  18124. }
  18125. var ret = {};
  18126. each$1(types, function (type) {
  18127. ret[type] = (componentsMap.get(type) || []).slice();
  18128. });
  18129. return ret;
  18130. }
  18131. /**
  18132. * @inner
  18133. */
  18134. function determineSubType(mainType, newCptOption, existComponent) {
  18135. var subType = newCptOption.type
  18136. ? newCptOption.type
  18137. : existComponent
  18138. ? existComponent.subType
  18139. // Use determineSubType only when there is no existComponent.
  18140. : ComponentModel.determineSubType(mainType, newCptOption);
  18141. // tooltip, markline, markpoint may always has no subType
  18142. return subType;
  18143. }
  18144. /**
  18145. * @inner
  18146. */
  18147. function createSeriesIndices(ecModel, seriesModels) {
  18148. ecModel._seriesIndicesMap = createHashMap(
  18149. ecModel._seriesIndices = map(seriesModels, function (series) {
  18150. return series.componentIndex;
  18151. }) || []
  18152. );
  18153. }
  18154. /**
  18155. * @inner
  18156. */
  18157. function filterBySubType(components, condition) {
  18158. // Using hasOwnProperty for restrict. Consider
  18159. // subType is undefined in user payload.
  18160. return condition.hasOwnProperty('subType')
  18161. ? filter(components, function (cpt) {
  18162. return cpt.subType === condition.subType;
  18163. })
  18164. : components;
  18165. }
  18166. /**
  18167. * @inner
  18168. */
  18169. function assertSeriesInitialized(ecModel) {
  18170. // Components that use _seriesIndices should depends on series component,
  18171. // which make sure that their initialization is after series.
  18172. if (__DEV__) {
  18173. if (!ecModel._seriesIndices) {
  18174. throw new Error('Option should contains series.');
  18175. }
  18176. }
  18177. }
  18178. mixin(GlobalModel, colorPaletteMixin);
  18179. /*
  18180. * Licensed to the Apache Software Foundation (ASF) under one
  18181. * or more contributor license agreements. See the NOTICE file
  18182. * distributed with this work for additional information
  18183. * regarding copyright ownership. The ASF licenses this file
  18184. * to you under the Apache License, Version 2.0 (the
  18185. * "License"); you may not use this file except in compliance
  18186. * with the License. You may obtain a copy of the License at
  18187. *
  18188. * http://www.apache.org/licenses/LICENSE-2.0
  18189. *
  18190. * Unless required by applicable law or agreed to in writing,
  18191. * software distributed under the License is distributed on an
  18192. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18193. * KIND, either express or implied. See the License for the
  18194. * specific language governing permissions and limitations
  18195. * under the License.
  18196. */
  18197. var echartsAPIList = [
  18198. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  18199. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  18200. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  18201. ];
  18202. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18203. function ExtensionAPI(chartInstance) {
  18204. each$1(echartsAPIList, function (name) {
  18205. this[name] = bind(chartInstance[name], chartInstance);
  18206. }, this);
  18207. }
  18208. /*
  18209. * Licensed to the Apache Software Foundation (ASF) under one
  18210. * or more contributor license agreements. See the NOTICE file
  18211. * distributed with this work for additional information
  18212. * regarding copyright ownership. The ASF licenses this file
  18213. * to you under the Apache License, Version 2.0 (the
  18214. * "License"); you may not use this file except in compliance
  18215. * with the License. You may obtain a copy of the License at
  18216. *
  18217. * http://www.apache.org/licenses/LICENSE-2.0
  18218. *
  18219. * Unless required by applicable law or agreed to in writing,
  18220. * software distributed under the License is distributed on an
  18221. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18222. * KIND, either express or implied. See the License for the
  18223. * specific language governing permissions and limitations
  18224. * under the License.
  18225. */
  18226. var coordinateSystemCreators = {};
  18227. function CoordinateSystemManager() {
  18228. this._coordinateSystems = [];
  18229. }
  18230. CoordinateSystemManager.prototype = {
  18231. constructor: CoordinateSystemManager,
  18232. create: function (ecModel, api) {
  18233. var coordinateSystems = [];
  18234. each$1(coordinateSystemCreators, function (creater, type) {
  18235. var list = creater.create(ecModel, api);
  18236. coordinateSystems = coordinateSystems.concat(list || []);
  18237. });
  18238. this._coordinateSystems = coordinateSystems;
  18239. },
  18240. update: function (ecModel, api) {
  18241. each$1(this._coordinateSystems, function (coordSys) {
  18242. coordSys.update && coordSys.update(ecModel, api);
  18243. });
  18244. },
  18245. getCoordinateSystems: function () {
  18246. return this._coordinateSystems.slice();
  18247. }
  18248. };
  18249. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18250. coordinateSystemCreators[type] = coordinateSystemCreator;
  18251. };
  18252. CoordinateSystemManager.get = function (type) {
  18253. return coordinateSystemCreators[type];
  18254. };
  18255. /*
  18256. * Licensed to the Apache Software Foundation (ASF) under one
  18257. * or more contributor license agreements. See the NOTICE file
  18258. * distributed with this work for additional information
  18259. * regarding copyright ownership. The ASF licenses this file
  18260. * to you under the Apache License, Version 2.0 (the
  18261. * "License"); you may not use this file except in compliance
  18262. * with the License. You may obtain a copy of the License at
  18263. *
  18264. * http://www.apache.org/licenses/LICENSE-2.0
  18265. *
  18266. * Unless required by applicable law or agreed to in writing,
  18267. * software distributed under the License is distributed on an
  18268. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18269. * KIND, either express or implied. See the License for the
  18270. * specific language governing permissions and limitations
  18271. * under the License.
  18272. */
  18273. /**
  18274. * ECharts option manager
  18275. *
  18276. * @module {echarts/model/OptionManager}
  18277. */
  18278. var each$4 = each$1;
  18279. var clone$3 = clone;
  18280. var map$1 = map;
  18281. var merge$1 = merge;
  18282. var QUERY_REG = /^(min|max)?(.+)$/;
  18283. /**
  18284. * TERM EXPLANATIONS:
  18285. *
  18286. * [option]:
  18287. *
  18288. * An object that contains definitions of components. For example:
  18289. * var option = {
  18290. * title: {...},
  18291. * legend: {...},
  18292. * visualMap: {...},
  18293. * series: [
  18294. * {data: [...]},
  18295. * {data: [...]},
  18296. * ...
  18297. * ]
  18298. * };
  18299. *
  18300. * [rawOption]:
  18301. *
  18302. * An object input to echarts.setOption. 'rawOption' may be an
  18303. * 'option', or may be an object contains multi-options. For example:
  18304. * var option = {
  18305. * baseOption: {
  18306. * title: {...},
  18307. * legend: {...},
  18308. * series: [
  18309. * {data: [...]},
  18310. * {data: [...]},
  18311. * ...
  18312. * ]
  18313. * },
  18314. * timeline: {...},
  18315. * options: [
  18316. * {title: {...}, series: {data: [...]}},
  18317. * {title: {...}, series: {data: [...]}},
  18318. * ...
  18319. * ],
  18320. * media: [
  18321. * {
  18322. * query: {maxWidth: 320},
  18323. * option: {series: {x: 20}, visualMap: {show: false}}
  18324. * },
  18325. * {
  18326. * query: {minWidth: 320, maxWidth: 720},
  18327. * option: {series: {x: 500}, visualMap: {show: true}}
  18328. * },
  18329. * {
  18330. * option: {series: {x: 1200}, visualMap: {show: true}}
  18331. * }
  18332. * ]
  18333. * };
  18334. *
  18335. * @alias module:echarts/model/OptionManager
  18336. * @param {module:echarts/ExtensionAPI} api
  18337. */
  18338. function OptionManager(api) {
  18339. /**
  18340. * @private
  18341. * @type {module:echarts/ExtensionAPI}
  18342. */
  18343. this._api = api;
  18344. /**
  18345. * @private
  18346. * @type {Array.<number>}
  18347. */
  18348. this._timelineOptions = [];
  18349. /**
  18350. * @private
  18351. * @type {Array.<Object>}
  18352. */
  18353. this._mediaList = [];
  18354. /**
  18355. * @private
  18356. * @type {Object}
  18357. */
  18358. this._mediaDefault;
  18359. /**
  18360. * -1, means default.
  18361. * empty means no media.
  18362. * @private
  18363. * @type {Array.<number>}
  18364. */
  18365. this._currentMediaIndices = [];
  18366. /**
  18367. * @private
  18368. * @type {Object}
  18369. */
  18370. this._optionBackup;
  18371. /**
  18372. * @private
  18373. * @type {Object}
  18374. */
  18375. this._newBaseOption;
  18376. }
  18377. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18378. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18379. // rawOption cloned and backuped when timeline changed, which does no
  18380. // good to performance. What's more, that both timeline and setOption
  18381. // method supply 'notMerge' brings complex and some problems.
  18382. // Consider this case:
  18383. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18384. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18385. OptionManager.prototype = {
  18386. constructor: OptionManager,
  18387. /**
  18388. * @public
  18389. * @param {Object} rawOption Raw option.
  18390. * @param {module:echarts/model/Global} ecModel
  18391. * @param {Array.<Function>} optionPreprocessorFuncs
  18392. * @return {Object} Init option
  18393. */
  18394. setOption: function (rawOption, optionPreprocessorFuncs) {
  18395. if (rawOption) {
  18396. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18397. each$1(normalizeToArray(rawOption.series), function (series) {
  18398. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18399. });
  18400. }
  18401. // Caution: some series modify option data, if do not clone,
  18402. // it should ensure that the repeat modify correctly
  18403. // (create a new object when modify itself).
  18404. rawOption = clone$3(rawOption, true);
  18405. // FIXME
  18406. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  18407. var oldOptionBackup = this._optionBackup;
  18408. var newParsedOption = parseRawOption.call(
  18409. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  18410. );
  18411. this._newBaseOption = newParsedOption.baseOption;
  18412. // For setOption at second time (using merge mode);
  18413. if (oldOptionBackup) {
  18414. // Only baseOption can be merged.
  18415. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  18416. // For simplicity, timeline options and media options do not support merge,
  18417. // that is, if you `setOption` twice and both has timeline options, the latter
  18418. // timeline opitons will not be merged to the formers, but just substitude them.
  18419. if (newParsedOption.timelineOptions.length) {
  18420. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  18421. }
  18422. if (newParsedOption.mediaList.length) {
  18423. oldOptionBackup.mediaList = newParsedOption.mediaList;
  18424. }
  18425. if (newParsedOption.mediaDefault) {
  18426. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  18427. }
  18428. }
  18429. else {
  18430. this._optionBackup = newParsedOption;
  18431. }
  18432. },
  18433. /**
  18434. * @param {boolean} isRecreate
  18435. * @return {Object}
  18436. */
  18437. mountOption: function (isRecreate) {
  18438. var optionBackup = this._optionBackup;
  18439. // TODO
  18440. // 如果没有reset功能则不clone。
  18441. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  18442. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  18443. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  18444. this._currentMediaIndices = [];
  18445. return clone$3(isRecreate
  18446. // this._optionBackup.baseOption, which is created at the first `setOption`
  18447. // called, and is merged into every new option by inner method `mergeOption`
  18448. // each time `setOption` called, can be only used in `isRecreate`, because
  18449. // its reliability is under suspicion. In other cases option merge is
  18450. // performed by `model.mergeOption`.
  18451. ? optionBackup.baseOption : this._newBaseOption
  18452. );
  18453. },
  18454. /**
  18455. * @param {module:echarts/model/Global} ecModel
  18456. * @return {Object}
  18457. */
  18458. getTimelineOption: function (ecModel) {
  18459. var option;
  18460. var timelineOptions = this._timelineOptions;
  18461. if (timelineOptions.length) {
  18462. // getTimelineOption can only be called after ecModel inited,
  18463. // so we can get currentIndex from timelineModel.
  18464. var timelineModel = ecModel.getComponent('timeline');
  18465. if (timelineModel) {
  18466. option = clone$3(
  18467. timelineOptions[timelineModel.getCurrentIndex()],
  18468. true
  18469. );
  18470. }
  18471. }
  18472. return option;
  18473. },
  18474. /**
  18475. * @param {module:echarts/model/Global} ecModel
  18476. * @return {Array.<Object>}
  18477. */
  18478. getMediaOption: function (ecModel) {
  18479. var ecWidth = this._api.getWidth();
  18480. var ecHeight = this._api.getHeight();
  18481. var mediaList = this._mediaList;
  18482. var mediaDefault = this._mediaDefault;
  18483. var indices = [];
  18484. var result = [];
  18485. // No media defined.
  18486. if (!mediaList.length && !mediaDefault) {
  18487. return result;
  18488. }
  18489. // Multi media may be applied, the latter defined media has higher priority.
  18490. for (var i = 0, len = mediaList.length; i < len; i++) {
  18491. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18492. indices.push(i);
  18493. }
  18494. }
  18495. // FIXME
  18496. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  18497. if (!indices.length && mediaDefault) {
  18498. indices = [-1];
  18499. }
  18500. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18501. result = map$1(indices, function (index) {
  18502. return clone$3(
  18503. index === -1 ? mediaDefault.option : mediaList[index].option
  18504. );
  18505. });
  18506. }
  18507. // Otherwise return nothing.
  18508. this._currentMediaIndices = indices;
  18509. return result;
  18510. }
  18511. };
  18512. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  18513. var timelineOptions = [];
  18514. var mediaList = [];
  18515. var mediaDefault;
  18516. var baseOption;
  18517. // Compatible with ec2.
  18518. var timelineOpt = rawOption.timeline;
  18519. if (rawOption.baseOption) {
  18520. baseOption = rawOption.baseOption;
  18521. }
  18522. // For timeline
  18523. if (timelineOpt || rawOption.options) {
  18524. baseOption = baseOption || {};
  18525. timelineOptions = (rawOption.options || []).slice();
  18526. }
  18527. // For media query
  18528. if (rawOption.media) {
  18529. baseOption = baseOption || {};
  18530. var media = rawOption.media;
  18531. each$4(media, function (singleMedia) {
  18532. if (singleMedia && singleMedia.option) {
  18533. if (singleMedia.query) {
  18534. mediaList.push(singleMedia);
  18535. }
  18536. else if (!mediaDefault) {
  18537. // Use the first media default.
  18538. mediaDefault = singleMedia;
  18539. }
  18540. }
  18541. });
  18542. }
  18543. // For normal option
  18544. if (!baseOption) {
  18545. baseOption = rawOption;
  18546. }
  18547. // Set timelineOpt to baseOption in ec3,
  18548. // which is convenient for merge option.
  18549. if (!baseOption.timeline) {
  18550. baseOption.timeline = timelineOpt;
  18551. }
  18552. // Preprocess.
  18553. each$4([baseOption].concat(timelineOptions)
  18554. .concat(map(mediaList, function (media) {
  18555. return media.option;
  18556. })),
  18557. function (option) {
  18558. each$4(optionPreprocessorFuncs, function (preProcess) {
  18559. preProcess(option, isNew);
  18560. });
  18561. }
  18562. );
  18563. return {
  18564. baseOption: baseOption,
  18565. timelineOptions: timelineOptions,
  18566. mediaDefault: mediaDefault,
  18567. mediaList: mediaList
  18568. };
  18569. }
  18570. /**
  18571. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18572. * Support: width, height, aspectRatio
  18573. * Can use max or min as prefix.
  18574. */
  18575. function applyMediaQuery(query, ecWidth, ecHeight) {
  18576. var realMap = {
  18577. width: ecWidth,
  18578. height: ecHeight,
  18579. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18580. };
  18581. var applicatable = true;
  18582. each$1(query, function (value, attr) {
  18583. var matched = attr.match(QUERY_REG);
  18584. if (!matched || !matched[1] || !matched[2]) {
  18585. return;
  18586. }
  18587. var operator = matched[1];
  18588. var realAttr = matched[2].toLowerCase();
  18589. if (!compare(realMap[realAttr], value, operator)) {
  18590. applicatable = false;
  18591. }
  18592. });
  18593. return applicatable;
  18594. }
  18595. function compare(real, expect, operator) {
  18596. if (operator === 'min') {
  18597. return real >= expect;
  18598. }
  18599. else if (operator === 'max') {
  18600. return real <= expect;
  18601. }
  18602. else { // Equals
  18603. return real === expect;
  18604. }
  18605. }
  18606. function indicesEquals(indices1, indices2) {
  18607. // indices is always order by asc and has only finite number.
  18608. return indices1.join(',') === indices2.join(',');
  18609. }
  18610. /**
  18611. * Consider case:
  18612. * `chart.setOption(opt1);`
  18613. * Then user do some interaction like dataZoom, dataView changing.
  18614. * `chart.setOption(opt2);`
  18615. * Then user press 'reset button' in toolbox.
  18616. *
  18617. * After doing that all of the interaction effects should be reset, the
  18618. * chart should be the same as the result of invoke
  18619. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18620. *
  18621. * Although it is not able ensure that
  18622. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18623. * `chart.setOption(merge(opt1, opt2));` exactly,
  18624. * this might be the only simple way to implement that feature.
  18625. *
  18626. * MEMO: We've considered some other approaches:
  18627. * 1. Each model handle its self restoration but not uniform treatment.
  18628. * (Too complex in logic and error-prone)
  18629. * 2. Use a shadow ecModel. (Performace expensive)
  18630. */
  18631. function mergeOption(oldOption, newOption) {
  18632. newOption = newOption || {};
  18633. each$4(newOption, function (newCptOpt, mainType) {
  18634. if (newCptOpt == null) {
  18635. return;
  18636. }
  18637. var oldCptOpt = oldOption[mainType];
  18638. if (!ComponentModel.hasClass(mainType)) {
  18639. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18640. }
  18641. else {
  18642. newCptOpt = normalizeToArray(newCptOpt);
  18643. oldCptOpt = normalizeToArray(oldCptOpt);
  18644. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18645. oldOption[mainType] = map$1(mapResult, function (item) {
  18646. return (item.option && item.exist)
  18647. ? merge$1(item.exist, item.option, true)
  18648. : (item.exist || item.option);
  18649. });
  18650. }
  18651. });
  18652. }
  18653. /*
  18654. * Licensed to the Apache Software Foundation (ASF) under one
  18655. * or more contributor license agreements. See the NOTICE file
  18656. * distributed with this work for additional information
  18657. * regarding copyright ownership. The ASF licenses this file
  18658. * to you under the Apache License, Version 2.0 (the
  18659. * "License"); you may not use this file except in compliance
  18660. * with the License. You may obtain a copy of the License at
  18661. *
  18662. * http://www.apache.org/licenses/LICENSE-2.0
  18663. *
  18664. * Unless required by applicable law or agreed to in writing,
  18665. * software distributed under the License is distributed on an
  18666. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18667. * KIND, either express or implied. See the License for the
  18668. * specific language governing permissions and limitations
  18669. * under the License.
  18670. */
  18671. var each$5 = each$1;
  18672. var isObject$3 = isObject$1;
  18673. var POSSIBLE_STYLES = [
  18674. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  18675. 'chordStyle', 'label', 'labelLine'
  18676. ];
  18677. function compatEC2ItemStyle(opt) {
  18678. var itemStyleOpt = opt && opt.itemStyle;
  18679. if (!itemStyleOpt) {
  18680. return;
  18681. }
  18682. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18683. var styleName = POSSIBLE_STYLES[i];
  18684. var normalItemStyleOpt = itemStyleOpt.normal;
  18685. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18686. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18687. opt[styleName] = opt[styleName] || {};
  18688. if (!opt[styleName].normal) {
  18689. opt[styleName].normal = normalItemStyleOpt[styleName];
  18690. }
  18691. else {
  18692. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18693. }
  18694. normalItemStyleOpt[styleName] = null;
  18695. }
  18696. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18697. opt[styleName] = opt[styleName] || {};
  18698. if (!opt[styleName].emphasis) {
  18699. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18700. }
  18701. else {
  18702. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18703. }
  18704. emphasisItemStyleOpt[styleName] = null;
  18705. }
  18706. }
  18707. }
  18708. function convertNormalEmphasis(opt, optType, useExtend) {
  18709. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18710. var normalOpt = opt[optType].normal;
  18711. var emphasisOpt = opt[optType].emphasis;
  18712. if (normalOpt) {
  18713. // Timeline controlStyle has other properties besides normal and emphasis
  18714. if (useExtend) {
  18715. opt[optType].normal = opt[optType].emphasis = null;
  18716. defaults(opt[optType], normalOpt);
  18717. }
  18718. else {
  18719. opt[optType] = normalOpt;
  18720. }
  18721. }
  18722. if (emphasisOpt) {
  18723. opt.emphasis = opt.emphasis || {};
  18724. opt.emphasis[optType] = emphasisOpt;
  18725. }
  18726. }
  18727. }
  18728. function removeEC3NormalStatus(opt) {
  18729. convertNormalEmphasis(opt, 'itemStyle');
  18730. convertNormalEmphasis(opt, 'lineStyle');
  18731. convertNormalEmphasis(opt, 'areaStyle');
  18732. convertNormalEmphasis(opt, 'label');
  18733. convertNormalEmphasis(opt, 'labelLine');
  18734. // treemap
  18735. convertNormalEmphasis(opt, 'upperLabel');
  18736. // graph
  18737. convertNormalEmphasis(opt, 'edgeLabel');
  18738. }
  18739. function compatTextStyle(opt, propName) {
  18740. // Check whether is not object (string\null\undefined ...)
  18741. var labelOptSingle = isObject$3(opt) && opt[propName];
  18742. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  18743. if (textStyle) {
  18744. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18745. var propName = TEXT_STYLE_OPTIONS[i];
  18746. if (textStyle.hasOwnProperty(propName)) {
  18747. labelOptSingle[propName] = textStyle[propName];
  18748. }
  18749. }
  18750. }
  18751. }
  18752. function compatEC3CommonStyles(opt) {
  18753. if (opt) {
  18754. removeEC3NormalStatus(opt);
  18755. compatTextStyle(opt, 'label');
  18756. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18757. }
  18758. }
  18759. function processSeries(seriesOpt) {
  18760. if (!isObject$3(seriesOpt)) {
  18761. return;
  18762. }
  18763. compatEC2ItemStyle(seriesOpt);
  18764. removeEC3NormalStatus(seriesOpt);
  18765. compatTextStyle(seriesOpt, 'label');
  18766. // treemap
  18767. compatTextStyle(seriesOpt, 'upperLabel');
  18768. // graph
  18769. compatTextStyle(seriesOpt, 'edgeLabel');
  18770. if (seriesOpt.emphasis) {
  18771. compatTextStyle(seriesOpt.emphasis, 'label');
  18772. // treemap
  18773. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18774. // graph
  18775. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18776. }
  18777. var markPoint = seriesOpt.markPoint;
  18778. if (markPoint) {
  18779. compatEC2ItemStyle(markPoint);
  18780. compatEC3CommonStyles(markPoint);
  18781. }
  18782. var markLine = seriesOpt.markLine;
  18783. if (markLine) {
  18784. compatEC2ItemStyle(markLine);
  18785. compatEC3CommonStyles(markLine);
  18786. }
  18787. var markArea = seriesOpt.markArea;
  18788. if (markArea) {
  18789. compatEC3CommonStyles(markArea);
  18790. }
  18791. var data = seriesOpt.data;
  18792. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18793. // then the backward compat based on option type will not be performed.
  18794. if (seriesOpt.type === 'graph') {
  18795. data = data || seriesOpt.nodes;
  18796. var edgeData = seriesOpt.links || seriesOpt.edges;
  18797. if (edgeData && !isTypedArray(edgeData)) {
  18798. for (var i = 0; i < edgeData.length; i++) {
  18799. compatEC3CommonStyles(edgeData[i]);
  18800. }
  18801. }
  18802. each$1(seriesOpt.categories, function (opt) {
  18803. removeEC3NormalStatus(opt);
  18804. });
  18805. }
  18806. if (data && !isTypedArray(data)) {
  18807. for (var i = 0; i < data.length; i++) {
  18808. compatEC3CommonStyles(data[i]);
  18809. }
  18810. }
  18811. // mark point data
  18812. var markPoint = seriesOpt.markPoint;
  18813. if (markPoint && markPoint.data) {
  18814. var mpData = markPoint.data;
  18815. for (var i = 0; i < mpData.length; i++) {
  18816. compatEC3CommonStyles(mpData[i]);
  18817. }
  18818. }
  18819. // mark line data
  18820. var markLine = seriesOpt.markLine;
  18821. if (markLine && markLine.data) {
  18822. var mlData = markLine.data;
  18823. for (var i = 0; i < mlData.length; i++) {
  18824. if (isArray(mlData[i])) {
  18825. compatEC3CommonStyles(mlData[i][0]);
  18826. compatEC3CommonStyles(mlData[i][1]);
  18827. }
  18828. else {
  18829. compatEC3CommonStyles(mlData[i]);
  18830. }
  18831. }
  18832. }
  18833. // Series
  18834. if (seriesOpt.type === 'gauge') {
  18835. compatTextStyle(seriesOpt, 'axisLabel');
  18836. compatTextStyle(seriesOpt, 'title');
  18837. compatTextStyle(seriesOpt, 'detail');
  18838. }
  18839. else if (seriesOpt.type === 'treemap') {
  18840. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18841. each$1(seriesOpt.levels, function (opt) {
  18842. removeEC3NormalStatus(opt);
  18843. });
  18844. }
  18845. else if (seriesOpt.type === 'tree') {
  18846. removeEC3NormalStatus(seriesOpt.leaves);
  18847. }
  18848. // sunburst starts from ec4, so it does not need to compat levels.
  18849. }
  18850. function toArr(o) {
  18851. return isArray(o) ? o : o ? [o] : [];
  18852. }
  18853. function toObj(o) {
  18854. return (isArray(o) ? o[0] : o) || {};
  18855. }
  18856. var compatStyle = function (option, isTheme) {
  18857. each$5(toArr(option.series), function (seriesOpt) {
  18858. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18859. });
  18860. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18861. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18862. each$5(
  18863. axes,
  18864. function (axisName) {
  18865. each$5(toArr(option[axisName]), function (axisOpt) {
  18866. if (axisOpt) {
  18867. compatTextStyle(axisOpt, 'axisLabel');
  18868. compatTextStyle(axisOpt.axisPointer, 'label');
  18869. }
  18870. });
  18871. }
  18872. );
  18873. each$5(toArr(option.parallel), function (parallelOpt) {
  18874. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18875. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18876. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18877. });
  18878. each$5(toArr(option.calendar), function (calendarOpt) {
  18879. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18880. compatTextStyle(calendarOpt, 'dayLabel');
  18881. compatTextStyle(calendarOpt, 'monthLabel');
  18882. compatTextStyle(calendarOpt, 'yearLabel');
  18883. });
  18884. // radar.name.textStyle
  18885. each$5(toArr(option.radar), function (radarOpt) {
  18886. compatTextStyle(radarOpt, 'name');
  18887. });
  18888. each$5(toArr(option.geo), function (geoOpt) {
  18889. if (isObject$3(geoOpt)) {
  18890. compatEC3CommonStyles(geoOpt);
  18891. each$5(toArr(geoOpt.regions), function (regionObj) {
  18892. compatEC3CommonStyles(regionObj);
  18893. });
  18894. }
  18895. });
  18896. each$5(toArr(option.timeline), function (timelineOpt) {
  18897. compatEC3CommonStyles(timelineOpt);
  18898. convertNormalEmphasis(timelineOpt, 'label');
  18899. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18900. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18901. var data = timelineOpt.data;
  18902. isArray(data) && each$1(data, function (item) {
  18903. if (isObject$1(item)) {
  18904. convertNormalEmphasis(item, 'label');
  18905. convertNormalEmphasis(item, 'itemStyle');
  18906. }
  18907. });
  18908. });
  18909. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18910. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18911. each$5(toolboxOpt.feature, function (featureOpt) {
  18912. convertNormalEmphasis(featureOpt, 'iconStyle');
  18913. });
  18914. });
  18915. compatTextStyle(toObj(option.axisPointer), 'label');
  18916. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18917. };
  18918. /*
  18919. * Licensed to the Apache Software Foundation (ASF) under one
  18920. * or more contributor license agreements. See the NOTICE file
  18921. * distributed with this work for additional information
  18922. * regarding copyright ownership. The ASF licenses this file
  18923. * to you under the Apache License, Version 2.0 (the
  18924. * "License"); you may not use this file except in compliance
  18925. * with the License. You may obtain a copy of the License at
  18926. *
  18927. * http://www.apache.org/licenses/LICENSE-2.0
  18928. *
  18929. * Unless required by applicable law or agreed to in writing,
  18930. * software distributed under the License is distributed on an
  18931. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18932. * KIND, either express or implied. See the License for the
  18933. * specific language governing permissions and limitations
  18934. * under the License.
  18935. */
  18936. // Compatitable with 2.0
  18937. function get(opt, path) {
  18938. path = path.split(',');
  18939. var obj = opt;
  18940. for (var i = 0; i < path.length; i++) {
  18941. obj = obj && obj[path[i]];
  18942. if (obj == null) {
  18943. break;
  18944. }
  18945. }
  18946. return obj;
  18947. }
  18948. function set$1(opt, path, val, overwrite) {
  18949. path = path.split(',');
  18950. var obj = opt;
  18951. var key;
  18952. for (var i = 0; i < path.length - 1; i++) {
  18953. key = path[i];
  18954. if (obj[key] == null) {
  18955. obj[key] = {};
  18956. }
  18957. obj = obj[key];
  18958. }
  18959. if (overwrite || obj[path[i]] == null) {
  18960. obj[path[i]] = val;
  18961. }
  18962. }
  18963. function compatLayoutProperties(option) {
  18964. each$1(LAYOUT_PROPERTIES, function (prop) {
  18965. if (prop[0] in option && !(prop[1] in option)) {
  18966. option[prop[1]] = option[prop[0]];
  18967. }
  18968. });
  18969. }
  18970. var LAYOUT_PROPERTIES = [
  18971. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  18972. ];
  18973. var COMPATITABLE_COMPONENTS = [
  18974. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  18975. ];
  18976. var backwardCompat = function (option, isTheme) {
  18977. compatStyle(option, isTheme);
  18978. // Make sure series array for model initialization.
  18979. option.series = normalizeToArray(option.series);
  18980. each$1(option.series, function (seriesOpt) {
  18981. if (!isObject$1(seriesOpt)) {
  18982. return;
  18983. }
  18984. var seriesType = seriesOpt.type;
  18985. if (seriesType === 'pie' || seriesType === 'gauge') {
  18986. if (seriesOpt.clockWise != null) {
  18987. seriesOpt.clockwise = seriesOpt.clockWise;
  18988. }
  18989. }
  18990. if (seriesType === 'gauge') {
  18991. var pointerColor = get(seriesOpt, 'pointer.color');
  18992. pointerColor != null
  18993. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  18994. }
  18995. compatLayoutProperties(seriesOpt);
  18996. });
  18997. // dataRange has changed to visualMap
  18998. if (option.dataRange) {
  18999. option.visualMap = option.dataRange;
  19000. }
  19001. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19002. var options = option[componentName];
  19003. if (options) {
  19004. if (!isArray(options)) {
  19005. options = [options];
  19006. }
  19007. each$1(options, function (option) {
  19008. compatLayoutProperties(option);
  19009. });
  19010. }
  19011. });
  19012. };
  19013. /*
  19014. * Licensed to the Apache Software Foundation (ASF) under one
  19015. * or more contributor license agreements. See the NOTICE file
  19016. * distributed with this work for additional information
  19017. * regarding copyright ownership. The ASF licenses this file
  19018. * to you under the Apache License, Version 2.0 (the
  19019. * "License"); you may not use this file except in compliance
  19020. * with the License. You may obtain a copy of the License at
  19021. *
  19022. * http://www.apache.org/licenses/LICENSE-2.0
  19023. *
  19024. * Unless required by applicable law or agreed to in writing,
  19025. * software distributed under the License is distributed on an
  19026. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19027. * KIND, either express or implied. See the License for the
  19028. * specific language governing permissions and limitations
  19029. * under the License.
  19030. */
  19031. // (1) [Caution]: the logic is correct based on the premises:
  19032. // data processing stage is blocked in stream.
  19033. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19034. // (2) Only register once when import repeatly.
  19035. // Should be executed before after series filtered and before stack calculation.
  19036. var dataStack = function (ecModel) {
  19037. var stackInfoMap = createHashMap();
  19038. ecModel.eachSeries(function (seriesModel) {
  19039. var stack = seriesModel.get('stack');
  19040. // Compatibal: when `stack` is set as '', do not stack.
  19041. if (stack) {
  19042. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19043. var data = seriesModel.getData();
  19044. var stackInfo = {
  19045. // Used for calculate axis extent automatically.
  19046. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19047. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19048. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19049. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19050. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19051. data: data,
  19052. seriesModel: seriesModel
  19053. };
  19054. // If stacked on axis that do not support data stack.
  19055. if (!stackInfo.stackedDimension
  19056. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19057. ) {
  19058. return;
  19059. }
  19060. stackInfoList.length && data.setCalculationInfo(
  19061. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19062. );
  19063. stackInfoList.push(stackInfo);
  19064. }
  19065. });
  19066. stackInfoMap.each(calculateStack);
  19067. };
  19068. function calculateStack(stackInfoList) {
  19069. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19070. var resultVal = [];
  19071. var resultNaN = [NaN, NaN];
  19072. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19073. var targetData = targetStackInfo.data;
  19074. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19075. // Should not write on raw data, because stack series model list changes
  19076. // depending on legend selection.
  19077. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19078. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19079. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19080. // should also be NaN, to draw a appropriate belt area.
  19081. if (isNaN(sum)) {
  19082. return resultNaN;
  19083. }
  19084. var byValue;
  19085. var stackedDataRawIndex;
  19086. if (isStackedByIndex) {
  19087. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19088. }
  19089. else {
  19090. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19091. }
  19092. // If stackOver is NaN, chart view will render point on value start.
  19093. var stackedOver = NaN;
  19094. for (var j = idxInStack - 1; j >= 0; j--) {
  19095. var stackInfo = stackInfoList[j];
  19096. // Has been optimized by inverted indices on `stackedByDimension`.
  19097. if (!isStackedByIndex) {
  19098. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19099. }
  19100. if (stackedDataRawIndex >= 0) {
  19101. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19102. // Considering positive stack, negative stack and empty data
  19103. if ((sum >= 0 && val > 0) // Positive stack
  19104. || (sum <= 0 && val < 0) // Negative stack
  19105. ) {
  19106. sum += val;
  19107. stackedOver = val;
  19108. break;
  19109. }
  19110. }
  19111. }
  19112. resultVal[0] = sum;
  19113. resultVal[1] = stackedOver;
  19114. return resultVal;
  19115. });
  19116. targetData.hostModel.setData(newData);
  19117. // Update for consequent calculation
  19118. targetStackInfo.data = newData;
  19119. });
  19120. }
  19121. /*
  19122. * Licensed to the Apache Software Foundation (ASF) under one
  19123. * or more contributor license agreements. See the NOTICE file
  19124. * distributed with this work for additional information
  19125. * regarding copyright ownership. The ASF licenses this file
  19126. * to you under the Apache License, Version 2.0 (the
  19127. * "License"); you may not use this file except in compliance
  19128. * with the License. You may obtain a copy of the License at
  19129. *
  19130. * http://www.apache.org/licenses/LICENSE-2.0
  19131. *
  19132. * Unless required by applicable law or agreed to in writing,
  19133. * software distributed under the License is distributed on an
  19134. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19135. * KIND, either express or implied. See the License for the
  19136. * specific language governing permissions and limitations
  19137. * under the License.
  19138. */
  19139. // TODO
  19140. // ??? refactor? check the outer usage of data provider.
  19141. // merge with defaultDimValueGetter?
  19142. /**
  19143. * If normal array used, mutable chunk size is supported.
  19144. * If typed array used, chunk size must be fixed.
  19145. */
  19146. function DefaultDataProvider(source, dimSize) {
  19147. if (!Source.isInstance(source)) {
  19148. source = Source.seriesDataToSource(source);
  19149. }
  19150. this._source = source;
  19151. var data = this._data = source.data;
  19152. var sourceFormat = source.sourceFormat;
  19153. // Typed array. TODO IE10+?
  19154. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19155. if (__DEV__) {
  19156. if (dimSize == null) {
  19157. throw new Error('Typed array data must specify dimension size');
  19158. }
  19159. }
  19160. this._offset = 0;
  19161. this._dimSize = dimSize;
  19162. this._data = data;
  19163. }
  19164. var methods = providerMethods[
  19165. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  19166. ? sourceFormat + '_' + source.seriesLayoutBy
  19167. : sourceFormat
  19168. ];
  19169. if (__DEV__) {
  19170. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19171. }
  19172. extend(this, methods);
  19173. }
  19174. var providerProto = DefaultDataProvider.prototype;
  19175. // If data is pure without style configuration
  19176. providerProto.pure = false;
  19177. // If data is persistent and will not be released after use.
  19178. providerProto.persistent = true;
  19179. // ???! FIXME legacy data provider do not has method getSource
  19180. providerProto.getSource = function () {
  19181. return this._source;
  19182. };
  19183. var providerMethods = {
  19184. 'arrayRows_column': {
  19185. pure: true,
  19186. count: function () {
  19187. return Math.max(0, this._data.length - this._source.startIndex);
  19188. },
  19189. getItem: function (idx) {
  19190. return this._data[idx + this._source.startIndex];
  19191. },
  19192. appendData: appendDataSimply
  19193. },
  19194. 'arrayRows_row': {
  19195. pure: true,
  19196. count: function () {
  19197. var row = this._data[0];
  19198. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19199. },
  19200. getItem: function (idx) {
  19201. idx += this._source.startIndex;
  19202. var item = [];
  19203. var data = this._data;
  19204. for (var i = 0; i < data.length; i++) {
  19205. var row = data[i];
  19206. item.push(row ? row[idx] : null);
  19207. }
  19208. return item;
  19209. },
  19210. appendData: function () {
  19211. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19212. }
  19213. },
  19214. 'objectRows': {
  19215. pure: true,
  19216. count: countSimply,
  19217. getItem: getItemSimply,
  19218. appendData: appendDataSimply
  19219. },
  19220. 'keyedColumns': {
  19221. pure: true,
  19222. count: function () {
  19223. var dimName = this._source.dimensionsDefine[0].name;
  19224. var col = this._data[dimName];
  19225. return col ? col.length : 0;
  19226. },
  19227. getItem: function (idx) {
  19228. var item = [];
  19229. var dims = this._source.dimensionsDefine;
  19230. for (var i = 0; i < dims.length; i++) {
  19231. var col = this._data[dims[i].name];
  19232. item.push(col ? col[idx] : null);
  19233. }
  19234. return item;
  19235. },
  19236. appendData: function (newData) {
  19237. var data = this._data;
  19238. each$1(newData, function (newCol, key) {
  19239. var oldCol = data[key] || (data[key] = []);
  19240. for (var i = 0; i < (newCol || []).length; i++) {
  19241. oldCol.push(newCol[i]);
  19242. }
  19243. });
  19244. }
  19245. },
  19246. 'original': {
  19247. count: countSimply,
  19248. getItem: getItemSimply,
  19249. appendData: appendDataSimply
  19250. },
  19251. 'typedArray': {
  19252. persistent: false,
  19253. pure: true,
  19254. count: function () {
  19255. return this._data ? (this._data.length / this._dimSize) : 0;
  19256. },
  19257. getItem: function (idx, out) {
  19258. idx = idx - this._offset;
  19259. out = out || [];
  19260. var offset = this._dimSize * idx;
  19261. for (var i = 0; i < this._dimSize; i++) {
  19262. out[i] = this._data[offset + i];
  19263. }
  19264. return out;
  19265. },
  19266. appendData: function (newData) {
  19267. if (__DEV__) {
  19268. assert$1(
  19269. isTypedArray(newData),
  19270. 'Added data must be TypedArray if data in initialization is TypedArray'
  19271. );
  19272. }
  19273. this._data = newData;
  19274. },
  19275. // Clean self if data is already used.
  19276. clean: function () {
  19277. // PENDING
  19278. this._offset += this.count();
  19279. this._data = null;
  19280. }
  19281. }
  19282. };
  19283. function countSimply() {
  19284. return this._data.length;
  19285. }
  19286. function getItemSimply(idx) {
  19287. return this._data[idx];
  19288. }
  19289. function appendDataSimply(newData) {
  19290. for (var i = 0; i < newData.length; i++) {
  19291. this._data.push(newData[i]);
  19292. }
  19293. }
  19294. var rawValueGetters = {
  19295. arrayRows: getRawValueSimply,
  19296. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  19297. return dimIndex != null ? dataItem[dimName] : dataItem;
  19298. },
  19299. keyedColumns: getRawValueSimply,
  19300. original: function (dataItem, dataIndex, dimIndex, dimName) {
  19301. // FIXME
  19302. // In some case (markpoint in geo (geo-map.html)), dataItem
  19303. // is {coord: [...]}
  19304. var value = getDataItemValue(dataItem);
  19305. return (dimIndex == null || !(value instanceof Array))
  19306. ? value
  19307. : value[dimIndex];
  19308. },
  19309. typedArray: getRawValueSimply
  19310. };
  19311. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  19312. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  19313. }
  19314. var defaultDimValueGetters = {
  19315. arrayRows: getDimValueSimply,
  19316. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  19317. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  19318. },
  19319. keyedColumns: getDimValueSimply,
  19320. original: function (dataItem, dimName, dataIndex, dimIndex) {
  19321. // Performance sensitive, do not use modelUtil.getDataItemValue.
  19322. // If dataItem is an plain object with no value field, the var `value`
  19323. // will be assigned with the object, but it will be tread correctly
  19324. // in the `convertDataValue`.
  19325. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  19326. // If any dataItem is like { value: 10 }
  19327. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  19328. this.hasItemOption = true;
  19329. }
  19330. return converDataValue(
  19331. (value instanceof Array)
  19332. ? value[dimIndex]
  19333. // If value is a single number or something else not array.
  19334. : value,
  19335. this._dimensionInfos[dimName]
  19336. );
  19337. },
  19338. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  19339. return dataItem[dimIndex];
  19340. }
  19341. };
  19342. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  19343. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  19344. }
  19345. /**
  19346. * This helper method convert value in data.
  19347. * @param {string|number|Date} value
  19348. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  19349. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  19350. */
  19351. function converDataValue(value, dimInfo) {
  19352. // Performance sensitive.
  19353. var dimType = dimInfo && dimInfo.type;
  19354. if (dimType === 'ordinal') {
  19355. // If given value is a category string
  19356. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  19357. return ordinalMeta
  19358. ? ordinalMeta.parseAndCollect(value)
  19359. : value;
  19360. }
  19361. if (dimType === 'time'
  19362. // spead up when using timestamp
  19363. && typeof value !== 'number'
  19364. && value != null
  19365. && value !== '-'
  19366. ) {
  19367. value = +parseDate(value);
  19368. }
  19369. // dimType defaults 'number'.
  19370. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19371. // parse to NaN.
  19372. return (value == null || value === '')
  19373. ? NaN
  19374. // If string (like '-'), using '+' parse to NaN
  19375. // If object, also parse to NaN
  19376. : +value;
  19377. }
  19378. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19379. // Consider persistent.
  19380. // Caution: why use raw value to display on label or tooltip?
  19381. // A reason is to avoid format. For example time value we do not know
  19382. // how to format is expected. More over, if stack is used, calculated
  19383. // value may be 0.91000000001, which have brings trouble to display.
  19384. // TODO: consider how to treat null/undefined/NaN when display?
  19385. /**
  19386. * @param {module:echarts/data/List} data
  19387. * @param {number} dataIndex
  19388. * @param {string|number} [dim] dimName or dimIndex
  19389. * @return {Array.<number>|string|number} can be null/undefined.
  19390. */
  19391. function retrieveRawValue(data, dataIndex, dim) {
  19392. if (!data) {
  19393. return;
  19394. }
  19395. // Consider data may be not persistent.
  19396. var dataItem = data.getRawDataItem(dataIndex);
  19397. if (dataItem == null) {
  19398. return;
  19399. }
  19400. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19401. var dimName;
  19402. var dimIndex;
  19403. var dimInfo = data.getDimensionInfo(dim);
  19404. if (dimInfo) {
  19405. dimName = dimInfo.name;
  19406. dimIndex = dimInfo.index;
  19407. }
  19408. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  19409. }
  19410. /**
  19411. * Compatible with some cases (in pie, map) like:
  19412. * data: [{name: 'xx', value: 5, selected: true}, ...]
  19413. * where only sourceFormat is 'original' and 'objectRows' supported.
  19414. *
  19415. * ??? TODO
  19416. * Supported detail options in data item when using 'arrayRows'.
  19417. *
  19418. * @param {module:echarts/data/List} data
  19419. * @param {number} dataIndex
  19420. * @param {string} attr like 'selected'
  19421. */
  19422. function retrieveRawAttr(data, dataIndex, attr) {
  19423. if (!data) {
  19424. return;
  19425. }
  19426. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19427. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  19428. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  19429. ) {
  19430. return;
  19431. }
  19432. var dataItem = data.getRawDataItem(dataIndex);
  19433. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  19434. dataItem = null;
  19435. }
  19436. if (dataItem) {
  19437. return dataItem[attr];
  19438. }
  19439. }
  19440. /*
  19441. * Licensed to the Apache Software Foundation (ASF) under one
  19442. * or more contributor license agreements. See the NOTICE file
  19443. * distributed with this work for additional information
  19444. * regarding copyright ownership. The ASF licenses this file
  19445. * to you under the Apache License, Version 2.0 (the
  19446. * "License"); you may not use this file except in compliance
  19447. * with the License. You may obtain a copy of the License at
  19448. *
  19449. * http://www.apache.org/licenses/LICENSE-2.0
  19450. *
  19451. * Unless required by applicable law or agreed to in writing,
  19452. * software distributed under the License is distributed on an
  19453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19454. * KIND, either express or implied. See the License for the
  19455. * specific language governing permissions and limitations
  19456. * under the License.
  19457. */
  19458. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19459. // PENDING A little ugly
  19460. var dataFormatMixin = {
  19461. /**
  19462. * Get params for formatter
  19463. * @param {number} dataIndex
  19464. * @param {string} [dataType]
  19465. * @return {Object}
  19466. */
  19467. getDataParams: function (dataIndex, dataType) {
  19468. var data = this.getData(dataType);
  19469. var rawValue = this.getRawValue(dataIndex, dataType);
  19470. var rawDataIndex = data.getRawIndex(dataIndex);
  19471. var name = data.getName(dataIndex);
  19472. var itemOpt = data.getRawDataItem(dataIndex);
  19473. var color = data.getItemVisual(dataIndex, 'color');
  19474. return {
  19475. componentType: this.mainType,
  19476. componentSubType: this.subType,
  19477. seriesType: this.mainType === 'series' ? this.subType : null,
  19478. seriesIndex: this.seriesIndex,
  19479. seriesId: this.id,
  19480. seriesName: this.name,
  19481. name: name,
  19482. dataIndex: rawDataIndex,
  19483. data: itemOpt,
  19484. dataType: dataType,
  19485. value: rawValue,
  19486. color: color,
  19487. marker: getTooltipMarker(color),
  19488. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19489. $vars: ['seriesName', 'name', 'value']
  19490. };
  19491. },
  19492. /**
  19493. * Format label
  19494. * @param {number} dataIndex
  19495. * @param {string} [status='normal'] 'normal' or 'emphasis'
  19496. * @param {string} [dataType]
  19497. * @param {number} [dimIndex]
  19498. * @param {string} [labelProp='label']
  19499. * @return {string} If not formatter, return null/undefined
  19500. */
  19501. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  19502. status = status || 'normal';
  19503. var data = this.getData(dataType);
  19504. var itemModel = data.getItemModel(dataIndex);
  19505. var params = this.getDataParams(dataIndex, dataType);
  19506. if (dimIndex != null && (params.value instanceof Array)) {
  19507. params.value = params.value[dimIndex];
  19508. }
  19509. var formatter = itemModel.get(
  19510. status === 'normal'
  19511. ? [labelProp || 'label', 'formatter']
  19512. : [status, labelProp || 'label', 'formatter']
  19513. );
  19514. if (typeof formatter === 'function') {
  19515. params.status = status;
  19516. return formatter(params);
  19517. }
  19518. else if (typeof formatter === 'string') {
  19519. var str = formatTpl(formatter, params);
  19520. // Support 'aaa{@[3]}bbb{@product}ccc'.
  19521. // Do not support '}' in dim name util have to.
  19522. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  19523. var len = dim.length;
  19524. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  19525. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  19526. }
  19527. return retrieveRawValue(data, dataIndex, dim);
  19528. });
  19529. }
  19530. },
  19531. /**
  19532. * Get raw value in option
  19533. * @param {number} idx
  19534. * @param {string} [dataType]
  19535. * @return {Array|number|string}
  19536. */
  19537. getRawValue: function (idx, dataType) {
  19538. return retrieveRawValue(this.getData(dataType), idx);
  19539. },
  19540. /**
  19541. * Should be implemented.
  19542. * @param {number} dataIndex
  19543. * @param {boolean} [multipleSeries=false]
  19544. * @param {number} [dataType]
  19545. * @return {string} tooltip string
  19546. */
  19547. formatTooltip: function () {
  19548. // Empty function
  19549. }
  19550. };
  19551. /*
  19552. * Licensed to the Apache Software Foundation (ASF) under one
  19553. * or more contributor license agreements. See the NOTICE file
  19554. * distributed with this work for additional information
  19555. * regarding copyright ownership. The ASF licenses this file
  19556. * to you under the Apache License, Version 2.0 (the
  19557. * "License"); you may not use this file except in compliance
  19558. * with the License. You may obtain a copy of the License at
  19559. *
  19560. * http://www.apache.org/licenses/LICENSE-2.0
  19561. *
  19562. * Unless required by applicable law or agreed to in writing,
  19563. * software distributed under the License is distributed on an
  19564. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19565. * KIND, either express or implied. See the License for the
  19566. * specific language governing permissions and limitations
  19567. * under the License.
  19568. */
  19569. /**
  19570. * @param {Object} define
  19571. * @return See the return of `createTask`.
  19572. */
  19573. function createTask(define) {
  19574. return new Task(define);
  19575. }
  19576. /**
  19577. * @constructor
  19578. * @param {Object} define
  19579. * @param {Function} define.reset Custom reset
  19580. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  19581. * @param {Function} [define.count] count is used to determin data task.
  19582. * @param {Function} [define.onDirty] count is used to determin data task.
  19583. */
  19584. function Task(define) {
  19585. define = define || {};
  19586. this._reset = define.reset;
  19587. this._plan = define.plan;
  19588. this._count = define.count;
  19589. this._onDirty = define.onDirty;
  19590. this._dirty = true;
  19591. // Context must be specified implicitly, to
  19592. // avoid miss update context when model changed.
  19593. this.context;
  19594. }
  19595. var taskProto = Task.prototype;
  19596. /**
  19597. * @param {Object} performArgs
  19598. * @param {number} [performArgs.step] Specified step.
  19599. * @param {number} [performArgs.skip] Skip customer perform call.
  19600. * @param {number} [performArgs.modBy] Sampling window size.
  19601. * @param {number} [performArgs.modDataCount] Sampling count.
  19602. */
  19603. taskProto.perform = function (performArgs) {
  19604. var upTask = this._upstream;
  19605. var skip = performArgs && performArgs.skip;
  19606. // TODO some refactor.
  19607. // Pull data. Must pull data each time, because context.data
  19608. // may be updated by Series.setData.
  19609. if (this._dirty && upTask) {
  19610. var context = this.context;
  19611. context.data = context.outputData = upTask.context.outputData;
  19612. }
  19613. if (this.__pipeline) {
  19614. this.__pipeline.currentTask = this;
  19615. }
  19616. var planResult;
  19617. if (this._plan && !skip) {
  19618. planResult = this._plan(this.context);
  19619. }
  19620. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19621. // elements uniformed distributed when progress, especially when moving or zooming.
  19622. var lastModBy = normalizeModBy(this._modBy);
  19623. var lastModDataCount = this._modDataCount || 0;
  19624. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19625. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19626. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19627. planResult = 'reset';
  19628. }
  19629. function normalizeModBy(val) {
  19630. !(val >= 1) && (val = 1); // jshint ignore:line
  19631. return val;
  19632. }
  19633. var forceFirstProgress;
  19634. if (this._dirty || planResult === 'reset') {
  19635. this._dirty = false;
  19636. forceFirstProgress = reset(this, skip);
  19637. }
  19638. this._modBy = modBy;
  19639. this._modDataCount = modDataCount;
  19640. var step = performArgs && performArgs.step;
  19641. if (upTask) {
  19642. if (__DEV__) {
  19643. assert$1(upTask._outputDueEnd != null);
  19644. }
  19645. this._dueEnd = upTask._outputDueEnd;
  19646. }
  19647. // DataTask or overallTask
  19648. else {
  19649. if (__DEV__) {
  19650. assert$1(!this._progress || this._count);
  19651. }
  19652. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19653. }
  19654. // Note: Stubs, that its host overall task let it has progress, has progress.
  19655. // If no progress, pass index from upstream to downstream each time plan called.
  19656. if (this._progress) {
  19657. var start = this._dueIndex;
  19658. var end = Math.min(
  19659. step != null ? this._dueIndex + step : Infinity,
  19660. this._dueEnd
  19661. );
  19662. if (!skip && (forceFirstProgress || start < end)) {
  19663. var progress = this._progress;
  19664. if (isArray(progress)) {
  19665. for (var i = 0; i < progress.length; i++) {
  19666. doProgress(this, progress[i], start, end, modBy, modDataCount);
  19667. }
  19668. }
  19669. else {
  19670. doProgress(this, progress, start, end, modBy, modDataCount);
  19671. }
  19672. }
  19673. this._dueIndex = end;
  19674. // If no `outputDueEnd`, assume that output data and
  19675. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19676. var outputDueEnd = this._settedOutputEnd != null
  19677. ? this._settedOutputEnd : end;
  19678. if (__DEV__) {
  19679. // ??? Can not rollback.
  19680. assert$1(outputDueEnd >= this._outputDueEnd);
  19681. }
  19682. this._outputDueEnd = outputDueEnd;
  19683. }
  19684. else {
  19685. // (1) Some overall task has no progress.
  19686. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19687. // This should always be performed so it can be passed to downstream.
  19688. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  19689. ? this._settedOutputEnd : this._dueEnd;
  19690. }
  19691. return this.unfinished();
  19692. };
  19693. var iterator = (function () {
  19694. var end;
  19695. var current;
  19696. var modBy;
  19697. var modDataCount;
  19698. var winCount;
  19699. var it = {
  19700. reset: function (s, e, sStep, sCount) {
  19701. current = s;
  19702. end = e;
  19703. modBy = sStep;
  19704. modDataCount = sCount;
  19705. winCount = Math.ceil(modDataCount / modBy);
  19706. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  19707. }
  19708. };
  19709. return it;
  19710. function sequentialNext() {
  19711. return current < end ? current++ : null;
  19712. }
  19713. function modNext() {
  19714. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  19715. var result = current >= end
  19716. ? null
  19717. : dataIndex < modDataCount
  19718. ? dataIndex
  19719. // If modDataCount is smaller than data.count() (consider `appendData` case),
  19720. // Use normal linear rendering mode.
  19721. : current;
  19722. current++;
  19723. return result;
  19724. }
  19725. })();
  19726. taskProto.dirty = function () {
  19727. this._dirty = true;
  19728. this._onDirty && this._onDirty(this.context);
  19729. };
  19730. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  19731. iterator.reset(start, end, modBy, modDataCount);
  19732. taskIns._callingProgress = progress;
  19733. taskIns._callingProgress({
  19734. start: start, end: end, count: end - start, next: iterator.next
  19735. }, taskIns.context);
  19736. }
  19737. function reset(taskIns, skip) {
  19738. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  19739. taskIns._settedOutputEnd = null;
  19740. var progress;
  19741. var forceFirstProgress;
  19742. if (!skip && taskIns._reset) {
  19743. progress = taskIns._reset(taskIns.context);
  19744. if (progress && progress.progress) {
  19745. forceFirstProgress = progress.forceFirstProgress;
  19746. progress = progress.progress;
  19747. }
  19748. // To simplify no progress checking, array must has item.
  19749. if (isArray(progress) && !progress.length) {
  19750. progress = null;
  19751. }
  19752. }
  19753. taskIns._progress = progress;
  19754. taskIns._modBy = taskIns._modDataCount = null;
  19755. var downstream = taskIns._downstream;
  19756. downstream && downstream.dirty();
  19757. return forceFirstProgress;
  19758. }
  19759. /**
  19760. * @return {boolean}
  19761. */
  19762. taskProto.unfinished = function () {
  19763. return this._progress && this._dueIndex < this._dueEnd;
  19764. };
  19765. /**
  19766. * @param {Object} downTask The downstream task.
  19767. * @return {Object} The downstream task.
  19768. */
  19769. taskProto.pipe = function (downTask) {
  19770. if (__DEV__) {
  19771. assert$1(downTask && !downTask._disposed && downTask !== this);
  19772. }
  19773. // If already downstream, do not dirty downTask.
  19774. if (this._downstream !== downTask || this._dirty) {
  19775. this._downstream = downTask;
  19776. downTask._upstream = this;
  19777. downTask.dirty();
  19778. }
  19779. };
  19780. taskProto.dispose = function () {
  19781. if (this._disposed) {
  19782. return;
  19783. }
  19784. this._upstream && (this._upstream._downstream = null);
  19785. this._downstream && (this._downstream._upstream = null);
  19786. this._dirty = false;
  19787. this._disposed = true;
  19788. };
  19789. taskProto.getUpstream = function () {
  19790. return this._upstream;
  19791. };
  19792. taskProto.getDownstream = function () {
  19793. return this._downstream;
  19794. };
  19795. taskProto.setOutputEnd = function (end) {
  19796. // This only happend in dataTask, dataZoom, map, currently.
  19797. // where dataZoom do not set end each time, but only set
  19798. // when reset. So we should record the setted end, in case
  19799. // that the stub of dataZoom perform again and earse the
  19800. // setted end by upstream.
  19801. this._outputDueEnd = this._settedOutputEnd = end;
  19802. };
  19803. ///////////////////////////////////////////////////////////
  19804. // For stream debug (Should be commented out after used!)
  19805. // Usage: printTask(this, 'begin');
  19806. // Usage: printTask(this, null, {someExtraProp});
  19807. // function printTask(task, prefix, extra) {
  19808. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19809. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19810. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19811. // var props = [];
  19812. // if (task.__pipeline) {
  19813. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19814. // props.push({text: 'idx', value: val});
  19815. // } else {
  19816. // var stubCount = 0;
  19817. // task.agentStubMap.each(() => stubCount++);
  19818. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19819. // }
  19820. // props.push({text: 'uid', value: task.uidDebug});
  19821. // if (task.__pipeline) {
  19822. // props.push({text: 'pid', value: task.__pipeline.id});
  19823. // task.agent && props.push(
  19824. // {text: 'stubFor', value: task.agent.uidDebug}
  19825. // );
  19826. // }
  19827. // props.push(
  19828. // {text: 'dirty', value: task._dirty},
  19829. // {text: 'dueIndex', value: task._dueIndex},
  19830. // {text: 'dueEnd', value: task._dueEnd},
  19831. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19832. // );
  19833. // if (extra) {
  19834. // Object.keys(extra).forEach(key => {
  19835. // props.push({text: key, value: extra[key]});
  19836. // });
  19837. // }
  19838. // var args = ['color: blue'];
  19839. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19840. // args.push('color: black', 'color: red'),
  19841. // `${item.text}: %c${item.value}`
  19842. // )).join('%c, ');
  19843. // console.log.apply(console, [msg].concat(args));
  19844. // // console.log(this);
  19845. // }
  19846. /*
  19847. * Licensed to the Apache Software Foundation (ASF) under one
  19848. * or more contributor license agreements. See the NOTICE file
  19849. * distributed with this work for additional information
  19850. * regarding copyright ownership. The ASF licenses this file
  19851. * to you under the Apache License, Version 2.0 (the
  19852. * "License"); you may not use this file except in compliance
  19853. * with the License. You may obtain a copy of the License at
  19854. *
  19855. * http://www.apache.org/licenses/LICENSE-2.0
  19856. *
  19857. * Unless required by applicable law or agreed to in writing,
  19858. * software distributed under the License is distributed on an
  19859. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19860. * KIND, either express or implied. See the License for the
  19861. * specific language governing permissions and limitations
  19862. * under the License.
  19863. */
  19864. var inner$4 = makeInner();
  19865. var SeriesModel = ComponentModel.extend({
  19866. type: 'series.__base__',
  19867. /**
  19868. * @readOnly
  19869. */
  19870. seriesIndex: 0,
  19871. // coodinateSystem will be injected in the echarts/CoordinateSystem
  19872. coordinateSystem: null,
  19873. /**
  19874. * @type {Object}
  19875. * @protected
  19876. */
  19877. defaultOption: null,
  19878. /**
  19879. * Data provided for legend
  19880. * @type {Function}
  19881. */
  19882. // PENDING
  19883. legendDataProvider: null,
  19884. /**
  19885. * Access path of color for visual
  19886. */
  19887. visualColorAccessPath: 'itemStyle.color',
  19888. /**
  19889. * Support merge layout params.
  19890. * Only support 'box' now (left/right/top/bottom/width/height).
  19891. * @type {string|Object} Object can be {ignoreSize: true}
  19892. * @readOnly
  19893. */
  19894. layoutMode: null,
  19895. init: function (option, parentModel, ecModel, extraOpt) {
  19896. /**
  19897. * @type {number}
  19898. * @readOnly
  19899. */
  19900. this.seriesIndex = this.componentIndex;
  19901. this.dataTask = createTask({
  19902. count: dataTaskCount,
  19903. reset: dataTaskReset
  19904. });
  19905. this.dataTask.context = {model: this};
  19906. this.mergeDefaultAndTheme(option, ecModel);
  19907. prepareSource(this);
  19908. var data = this.getInitialData(option, ecModel);
  19909. wrapData(data, this);
  19910. this.dataTask.context.data = data;
  19911. if (__DEV__) {
  19912. assert$1(data, 'getInitialData returned invalid data.');
  19913. }
  19914. /**
  19915. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  19916. * @private
  19917. */
  19918. inner$4(this).dataBeforeProcessed = data;
  19919. // If we reverse the order (make data firstly, and then make
  19920. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19921. // cause data.graph.data !== data when using
  19922. // module:echarts/data/Graph or module:echarts/data/Tree.
  19923. // See module:echarts/data/helper/linkList
  19924. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19925. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19926. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19927. // Call `seriesModel.getRawData()` instead.
  19928. // this.restoreData();
  19929. autoSeriesName(this);
  19930. },
  19931. /**
  19932. * Util for merge default and theme to option
  19933. * @param {Object} option
  19934. * @param {module:echarts/model/Global} ecModel
  19935. */
  19936. mergeDefaultAndTheme: function (option, ecModel) {
  19937. var layoutMode = this.layoutMode;
  19938. var inputPositionParams = layoutMode
  19939. ? getLayoutParams(option) : {};
  19940. // Backward compat: using subType on theme.
  19941. // But if name duplicate between series subType
  19942. // (for example: parallel) add component mainType,
  19943. // add suffix 'Series'.
  19944. var themeSubType = this.subType;
  19945. if (ComponentModel.hasClass(themeSubType)) {
  19946. themeSubType += 'Series';
  19947. }
  19948. merge(
  19949. option,
  19950. ecModel.getTheme().get(this.subType)
  19951. );
  19952. merge(option, this.getDefaultOption());
  19953. // Default label emphasis `show`
  19954. defaultEmphasis(option, 'label', ['show']);
  19955. this.fillDataTextStyle(option.data);
  19956. if (layoutMode) {
  19957. mergeLayoutParam(option, inputPositionParams, layoutMode);
  19958. }
  19959. },
  19960. mergeOption: function (newSeriesOption, ecModel) {
  19961. // this.settingTask.dirty();
  19962. newSeriesOption = merge(this.option, newSeriesOption, true);
  19963. this.fillDataTextStyle(newSeriesOption.data);
  19964. var layoutMode = this.layoutMode;
  19965. if (layoutMode) {
  19966. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  19967. }
  19968. prepareSource(this);
  19969. var data = this.getInitialData(newSeriesOption, ecModel);
  19970. wrapData(data, this);
  19971. this.dataTask.dirty();
  19972. this.dataTask.context.data = data;
  19973. inner$4(this).dataBeforeProcessed = data;
  19974. autoSeriesName(this);
  19975. },
  19976. fillDataTextStyle: function (data) {
  19977. // Default data label emphasis `show`
  19978. // FIXME Tree structure data ?
  19979. // FIXME Performance ?
  19980. if (data && !isTypedArray(data)) {
  19981. var props = ['show'];
  19982. for (var i = 0; i < data.length; i++) {
  19983. if (data[i] && data[i].label) {
  19984. defaultEmphasis(data[i], 'label', props);
  19985. }
  19986. }
  19987. }
  19988. },
  19989. /**
  19990. * Init a data structure from data related option in series
  19991. * Must be overwritten
  19992. */
  19993. getInitialData: function () {},
  19994. /**
  19995. * Append data to list
  19996. * @param {Object} params
  19997. * @param {Array|TypedArray} params.data
  19998. */
  19999. appendData: function (params) {
  20000. // FIXME ???
  20001. // (1) If data from dataset, forbidden append.
  20002. // (2) support append data of dataset.
  20003. var data = this.getRawData();
  20004. data.appendData(params.data);
  20005. },
  20006. /**
  20007. * Consider some method like `filter`, `map` need make new data,
  20008. * We should make sure that `seriesModel.getData()` get correct
  20009. * data in the stream procedure. So we fetch data from upstream
  20010. * each time `task.perform` called.
  20011. * @param {string} [dataType]
  20012. * @return {module:echarts/data/List}
  20013. */
  20014. getData: function (dataType) {
  20015. var task = getCurrentTask(this);
  20016. if (task) {
  20017. var data = task.context.data;
  20018. return dataType == null ? data : data.getLinkedData(dataType);
  20019. }
  20020. else {
  20021. // When series is not alive (that may happen when click toolbox
  20022. // restore or setOption with not merge mode), series data may
  20023. // be still need to judge animation or something when graphic
  20024. // elements want to know whether fade out.
  20025. return inner$4(this).data;
  20026. }
  20027. },
  20028. /**
  20029. * @param {module:echarts/data/List} data
  20030. */
  20031. setData: function (data) {
  20032. var task = getCurrentTask(this);
  20033. if (task) {
  20034. var context = task.context;
  20035. // Consider case: filter, data sample.
  20036. if (context.data !== data && task.modifyOutputEnd) {
  20037. task.setOutputEnd(data.count());
  20038. }
  20039. context.outputData = data;
  20040. // Caution: setData should update context.data,
  20041. // Because getData may be called multiply in a
  20042. // single stage and expect to get the data just
  20043. // set. (For example, AxisProxy, x y both call
  20044. // getData and setDate sequentially).
  20045. // So the context.data should be fetched from
  20046. // upstream each time when a stage starts to be
  20047. // performed.
  20048. if (task !== this.dataTask) {
  20049. context.data = data;
  20050. }
  20051. }
  20052. inner$4(this).data = data;
  20053. },
  20054. /**
  20055. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20056. * @return {module:echarts/data/Source} source
  20057. */
  20058. getSource: function () {
  20059. return getSource(this);
  20060. },
  20061. /**
  20062. * Get data before processed
  20063. * @return {module:echarts/data/List}
  20064. */
  20065. getRawData: function () {
  20066. return inner$4(this).dataBeforeProcessed;
  20067. },
  20068. /**
  20069. * Get base axis if has coordinate system and has axis.
  20070. * By default use coordSys.getBaseAxis();
  20071. * Can be overrided for some chart.
  20072. * @return {type} description
  20073. */
  20074. getBaseAxis: function () {
  20075. var coordSys = this.coordinateSystem;
  20076. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20077. },
  20078. // FIXME
  20079. /**
  20080. * Default tooltip formatter
  20081. *
  20082. * @param {number} dataIndex
  20083. * @param {boolean} [multipleSeries=false]
  20084. * @param {number} [dataType]
  20085. */
  20086. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  20087. function formatArrayValue(value) {
  20088. // ??? TODO refactor these logic.
  20089. // check: category-no-encode-has-axis-data in dataset.html
  20090. var vertially = reduce(value, function (vertially, val, idx) {
  20091. var dimItem = data.getDimensionInfo(idx);
  20092. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20093. }, 0);
  20094. var result = [];
  20095. tooltipDims.length
  20096. ? each$1(tooltipDims, function (dim) {
  20097. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20098. })
  20099. // By default, all dims is used on tooltip.
  20100. : each$1(value, setEachItem);
  20101. function setEachItem(val, dim) {
  20102. var dimInfo = data.getDimensionInfo(dim);
  20103. // If `dimInfo.tooltip` is not set, show tooltip.
  20104. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20105. return;
  20106. }
  20107. var dimType = dimInfo.type;
  20108. var dimHead = getTooltipMarker({color: color, type: 'subItem'});
  20109. var valStr = (vertially
  20110. ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': '
  20111. : ''
  20112. )
  20113. // FIXME should not format time for raw data?
  20114. + encodeHTML(dimType === 'ordinal'
  20115. ? val + ''
  20116. : dimType === 'time'
  20117. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  20118. : addCommas(val)
  20119. );
  20120. valStr && result.push(valStr);
  20121. }
  20122. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  20123. }
  20124. function formatSingleValue(val) {
  20125. return encodeHTML(addCommas(val));
  20126. }
  20127. var data = this.getData();
  20128. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  20129. var tooltipDimLen = tooltipDims.length;
  20130. var value = this.getRawValue(dataIndex);
  20131. var isValueArr = isArray(value);
  20132. var color = data.getItemVisual(dataIndex, 'color');
  20133. if (isObject$1(color) && color.colorStops) {
  20134. color = (color.colorStops[0] || {}).color;
  20135. }
  20136. color = color || 'transparent';
  20137. // Complicated rule for pretty tooltip.
  20138. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  20139. ? formatArrayValue(value)
  20140. : tooltipDimLen
  20141. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  20142. : formatSingleValue(isValueArr ? value[0] : value);
  20143. var colorEl = getTooltipMarker(color);
  20144. var name = data.getName(dataIndex);
  20145. var seriesName = this.name;
  20146. if (!isNameSpecified(this)) {
  20147. seriesName = '';
  20148. }
  20149. seriesName = seriesName
  20150. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  20151. : '';
  20152. return !multipleSeries
  20153. ? seriesName + colorEl
  20154. + (name
  20155. ? encodeHTML(name) + ': ' + formattedValue
  20156. : formattedValue
  20157. )
  20158. : colorEl + seriesName + formattedValue;
  20159. },
  20160. /**
  20161. * @return {boolean}
  20162. */
  20163. isAnimationEnabled: function () {
  20164. if (env$1.node) {
  20165. return false;
  20166. }
  20167. var animationEnabled = this.getShallow('animation');
  20168. if (animationEnabled) {
  20169. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20170. animationEnabled = false;
  20171. }
  20172. }
  20173. return animationEnabled;
  20174. },
  20175. restoreData: function () {
  20176. this.dataTask.dirty();
  20177. },
  20178. getColorFromPalette: function (name, scope, requestColorNum) {
  20179. var ecModel = this.ecModel;
  20180. // PENDING
  20181. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  20182. if (!color) {
  20183. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20184. }
  20185. return color;
  20186. },
  20187. /**
  20188. * Use `data.mapDimension(coordDim, true)` instead.
  20189. * @deprecated
  20190. */
  20191. coordDimToDataDim: function (coordDim) {
  20192. return this.getRawData().mapDimension(coordDim, true);
  20193. },
  20194. /**
  20195. * Get progressive rendering count each step
  20196. * @return {number}
  20197. */
  20198. getProgressive: function () {
  20199. return this.get('progressive');
  20200. },
  20201. /**
  20202. * Get progressive rendering count each step
  20203. * @return {number}
  20204. */
  20205. getProgressiveThreshold: function () {
  20206. return this.get('progressiveThreshold');
  20207. },
  20208. /**
  20209. * Get data indices for show tooltip content. See tooltip.
  20210. * @abstract
  20211. * @param {Array.<string>|string} dim
  20212. * @param {Array.<number>} value
  20213. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  20214. * @return {Object} {dataIndices, nestestValue}.
  20215. */
  20216. getAxisTooltipData: null,
  20217. /**
  20218. * See tooltip.
  20219. * @abstract
  20220. * @param {number} dataIndex
  20221. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  20222. */
  20223. getTooltipPosition: null,
  20224. /**
  20225. * @see {module:echarts/stream/Scheduler}
  20226. */
  20227. pipeTask: null,
  20228. /**
  20229. * Convinient for override in extended class.
  20230. * @protected
  20231. * @type {Function}
  20232. */
  20233. preventIncremental: null,
  20234. /**
  20235. * @public
  20236. * @readOnly
  20237. * @type {Object}
  20238. */
  20239. pipelineContext: null
  20240. });
  20241. mixin(SeriesModel, dataFormatMixin);
  20242. mixin(SeriesModel, colorPaletteMixin);
  20243. /**
  20244. * MUST be called after `prepareSource` called
  20245. * Here we need to make auto series, especially for auto legend. But we
  20246. * do not modify series.name in option to avoid side effects.
  20247. */
  20248. function autoSeriesName(seriesModel) {
  20249. // User specified name has higher priority, otherwise it may cause
  20250. // series can not be queried unexpectedly.
  20251. var name = seriesModel.name;
  20252. if (!isNameSpecified(seriesModel)) {
  20253. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20254. }
  20255. }
  20256. function getSeriesAutoName(seriesModel) {
  20257. var data = seriesModel.getRawData();
  20258. var dataDims = data.mapDimension('seriesName', true);
  20259. var nameArr = [];
  20260. each$1(dataDims, function (dataDim) {
  20261. var dimInfo = data.getDimensionInfo(dataDim);
  20262. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20263. });
  20264. return nameArr.join(' ');
  20265. }
  20266. function dataTaskCount(context) {
  20267. return context.model.getRawData().count();
  20268. }
  20269. function dataTaskReset(context) {
  20270. var seriesModel = context.model;
  20271. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  20272. return dataTaskProgress;
  20273. }
  20274. function dataTaskProgress(param, context) {
  20275. // Avoid repead cloneShallow when data just created in reset.
  20276. if (param.end > context.outputData.count()) {
  20277. context.model.getRawData().cloneShallow(context.outputData);
  20278. }
  20279. }
  20280. // TODO refactor
  20281. function wrapData(data, seriesModel) {
  20282. each$1(data.CHANGABLE_METHODS, function (methodName) {
  20283. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  20284. });
  20285. }
  20286. function onDataSelfChange(seriesModel) {
  20287. var task = getCurrentTask(seriesModel);
  20288. if (task) {
  20289. // Consider case: filter, selectRange
  20290. task.setOutputEnd(this.count());
  20291. }
  20292. }
  20293. function getCurrentTask(seriesModel) {
  20294. var scheduler = (seriesModel.ecModel || {}).scheduler;
  20295. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  20296. if (pipeline) {
  20297. // When pipline finished, the currrentTask keep the last
  20298. // task (renderTask).
  20299. var task = pipeline.currentTask;
  20300. if (task) {
  20301. var agentStubMap = task.agentStubMap;
  20302. if (agentStubMap) {
  20303. task = agentStubMap.get(seriesModel.uid);
  20304. }
  20305. }
  20306. return task;
  20307. }
  20308. }
  20309. /*
  20310. * Licensed to the Apache Software Foundation (ASF) under one
  20311. * or more contributor license agreements. See the NOTICE file
  20312. * distributed with this work for additional information
  20313. * regarding copyright ownership. The ASF licenses this file
  20314. * to you under the Apache License, Version 2.0 (the
  20315. * "License"); you may not use this file except in compliance
  20316. * with the License. You may obtain a copy of the License at
  20317. *
  20318. * http://www.apache.org/licenses/LICENSE-2.0
  20319. *
  20320. * Unless required by applicable law or agreed to in writing,
  20321. * software distributed under the License is distributed on an
  20322. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20323. * KIND, either express or implied. See the License for the
  20324. * specific language governing permissions and limitations
  20325. * under the License.
  20326. */
  20327. var Component = function () {
  20328. /**
  20329. * @type {module:zrender/container/Group}
  20330. * @readOnly
  20331. */
  20332. this.group = new Group();
  20333. /**
  20334. * @type {string}
  20335. * @readOnly
  20336. */
  20337. this.uid = getUID('viewComponent');
  20338. };
  20339. Component.prototype = {
  20340. constructor: Component,
  20341. init: function (ecModel, api) {},
  20342. render: function (componentModel, ecModel, api, payload) {},
  20343. dispose: function () {}
  20344. };
  20345. var componentProto = Component.prototype;
  20346. componentProto.updateView
  20347. = componentProto.updateLayout
  20348. = componentProto.updateVisual
  20349. = function (seriesModel, ecModel, api, payload) {
  20350. // Do nothing;
  20351. };
  20352. // Enable Component.extend.
  20353. enableClassExtend(Component);
  20354. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20355. enableClassManagement(Component, {registerWhenExtend: true});
  20356. /*
  20357. * Licensed to the Apache Software Foundation (ASF) under one
  20358. * or more contributor license agreements. See the NOTICE file
  20359. * distributed with this work for additional information
  20360. * regarding copyright ownership. The ASF licenses this file
  20361. * to you under the Apache License, Version 2.0 (the
  20362. * "License"); you may not use this file except in compliance
  20363. * with the License. You may obtain a copy of the License at
  20364. *
  20365. * http://www.apache.org/licenses/LICENSE-2.0
  20366. *
  20367. * Unless required by applicable law or agreed to in writing,
  20368. * software distributed under the License is distributed on an
  20369. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20370. * KIND, either express or implied. See the License for the
  20371. * specific language governing permissions and limitations
  20372. * under the License.
  20373. */
  20374. /**
  20375. * @return {string} If large mode changed, return string 'reset';
  20376. */
  20377. var createRenderPlanner = function () {
  20378. var inner = makeInner();
  20379. return function (seriesModel) {
  20380. var fields = inner(seriesModel);
  20381. var pipelineContext = seriesModel.pipelineContext;
  20382. var originalLarge = fields.large;
  20383. var originalProgressive = fields.progressiveRender;
  20384. var large = fields.large = pipelineContext.large;
  20385. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  20386. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  20387. };
  20388. };
  20389. /*
  20390. * Licensed to the Apache Software Foundation (ASF) under one
  20391. * or more contributor license agreements. See the NOTICE file
  20392. * distributed with this work for additional information
  20393. * regarding copyright ownership. The ASF licenses this file
  20394. * to you under the Apache License, Version 2.0 (the
  20395. * "License"); you may not use this file except in compliance
  20396. * with the License. You may obtain a copy of the License at
  20397. *
  20398. * http://www.apache.org/licenses/LICENSE-2.0
  20399. *
  20400. * Unless required by applicable law or agreed to in writing,
  20401. * software distributed under the License is distributed on an
  20402. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20403. * KIND, either express or implied. See the License for the
  20404. * specific language governing permissions and limitations
  20405. * under the License.
  20406. */
  20407. var inner$5 = makeInner();
  20408. var renderPlanner = createRenderPlanner();
  20409. function Chart() {
  20410. /**
  20411. * @type {module:zrender/container/Group}
  20412. * @readOnly
  20413. */
  20414. this.group = new Group();
  20415. /**
  20416. * @type {string}
  20417. * @readOnly
  20418. */
  20419. this.uid = getUID('viewChart');
  20420. this.renderTask = createTask({
  20421. plan: renderTaskPlan,
  20422. reset: renderTaskReset
  20423. });
  20424. this.renderTask.context = {view: this};
  20425. }
  20426. Chart.prototype = {
  20427. type: 'chart',
  20428. /**
  20429. * Init the chart.
  20430. * @param {module:echarts/model/Global} ecModel
  20431. * @param {module:echarts/ExtensionAPI} api
  20432. */
  20433. init: function (ecModel, api) {},
  20434. /**
  20435. * Render the chart.
  20436. * @param {module:echarts/model/Series} seriesModel
  20437. * @param {module:echarts/model/Global} ecModel
  20438. * @param {module:echarts/ExtensionAPI} api
  20439. * @param {Object} payload
  20440. */
  20441. render: function (seriesModel, ecModel, api, payload) {},
  20442. /**
  20443. * Highlight series or specified data item.
  20444. * @param {module:echarts/model/Series} seriesModel
  20445. * @param {module:echarts/model/Global} ecModel
  20446. * @param {module:echarts/ExtensionAPI} api
  20447. * @param {Object} payload
  20448. */
  20449. highlight: function (seriesModel, ecModel, api, payload) {
  20450. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20451. },
  20452. /**
  20453. * Downplay series or specified data item.
  20454. * @param {module:echarts/model/Series} seriesModel
  20455. * @param {module:echarts/model/Global} ecModel
  20456. * @param {module:echarts/ExtensionAPI} api
  20457. * @param {Object} payload
  20458. */
  20459. downplay: function (seriesModel, ecModel, api, payload) {
  20460. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20461. },
  20462. /**
  20463. * Remove self.
  20464. * @param {module:echarts/model/Global} ecModel
  20465. * @param {module:echarts/ExtensionAPI} api
  20466. */
  20467. remove: function (ecModel, api) {
  20468. this.group.removeAll();
  20469. },
  20470. /**
  20471. * Dispose self.
  20472. * @param {module:echarts/model/Global} ecModel
  20473. * @param {module:echarts/ExtensionAPI} api
  20474. */
  20475. dispose: function () {},
  20476. /**
  20477. * Rendering preparation in progressive mode.
  20478. * @param {module:echarts/model/Series} seriesModel
  20479. * @param {module:echarts/model/Global} ecModel
  20480. * @param {module:echarts/ExtensionAPI} api
  20481. * @param {Object} payload
  20482. */
  20483. incrementalPrepareRender: null,
  20484. /**
  20485. * Render in progressive mode.
  20486. * @param {module:echarts/model/Series} seriesModel
  20487. * @param {module:echarts/model/Global} ecModel
  20488. * @param {module:echarts/ExtensionAPI} api
  20489. * @param {Object} payload
  20490. */
  20491. incrementalRender: null,
  20492. /**
  20493. * Update transform directly.
  20494. * @param {module:echarts/model/Series} seriesModel
  20495. * @param {module:echarts/model/Global} ecModel
  20496. * @param {module:echarts/ExtensionAPI} api
  20497. * @param {Object} payload
  20498. * @return {Object} {update: true}
  20499. */
  20500. updateTransform: null
  20501. /**
  20502. * The view contains the given point.
  20503. * @interface
  20504. * @param {Array.<number>} point
  20505. * @return {boolean}
  20506. */
  20507. // containPoint: function () {}
  20508. };
  20509. var chartProto = Chart.prototype;
  20510. chartProto.updateView
  20511. = chartProto.updateLayout
  20512. = chartProto.updateVisual
  20513. = function (seriesModel, ecModel, api, payload) {
  20514. this.render(seriesModel, ecModel, api, payload);
  20515. };
  20516. /**
  20517. * Set state of single element
  20518. * @param {module:zrender/Element} el
  20519. * @param {string} state
  20520. */
  20521. function elSetState(el, state) {
  20522. if (el) {
  20523. el.trigger(state);
  20524. if (el.type === 'group') {
  20525. for (var i = 0; i < el.childCount(); i++) {
  20526. elSetState(el.childAt(i), state);
  20527. }
  20528. }
  20529. }
  20530. }
  20531. /**
  20532. * @param {module:echarts/data/List} data
  20533. * @param {Object} payload
  20534. * @param {string} state 'normal'|'emphasis'
  20535. */
  20536. function toggleHighlight(data, payload, state) {
  20537. var dataIndex = queryDataIndex(data, payload);
  20538. if (dataIndex != null) {
  20539. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  20540. elSetState(data.getItemGraphicEl(dataIdx), state);
  20541. });
  20542. }
  20543. else {
  20544. data.eachItemGraphicEl(function (el) {
  20545. elSetState(el, state);
  20546. });
  20547. }
  20548. }
  20549. // Enable Chart.extend.
  20550. enableClassExtend(Chart, ['dispose']);
  20551. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20552. enableClassManagement(Chart, {registerWhenExtend: true});
  20553. Chart.markUpdateMethod = function (payload, methodName) {
  20554. inner$5(payload).updateMethod = methodName;
  20555. };
  20556. function renderTaskPlan(context) {
  20557. return renderPlanner(context.model);
  20558. }
  20559. function renderTaskReset(context) {
  20560. var seriesModel = context.model;
  20561. var ecModel = context.ecModel;
  20562. var api = context.api;
  20563. var payload = context.payload;
  20564. // ???! remove updateView updateVisual
  20565. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  20566. var view = context.view;
  20567. var updateMethod = payload && inner$5(payload).updateMethod;
  20568. var methodName = progressiveRender
  20569. ? 'incrementalPrepareRender'
  20570. : (updateMethod && view[updateMethod])
  20571. ? updateMethod
  20572. // `appendData` is also supported when data amount
  20573. // is less than progressive threshold.
  20574. : 'render';
  20575. if (methodName !== 'render') {
  20576. view[methodName](seriesModel, ecModel, api, payload);
  20577. }
  20578. return progressMethodMap[methodName];
  20579. }
  20580. var progressMethodMap = {
  20581. incrementalPrepareRender: {
  20582. progress: function (params, context) {
  20583. context.view.incrementalRender(
  20584. params, context.model, context.ecModel, context.api, context.payload
  20585. );
  20586. }
  20587. },
  20588. render: {
  20589. // Put view.render in `progress` to support appendData. But in this case
  20590. // view.render should not be called in reset, otherwise it will be called
  20591. // twise. Use `forceFirstProgress` to make sure that view.render is called
  20592. // in any cases.
  20593. forceFirstProgress: true,
  20594. progress: function (params, context) {
  20595. context.view.render(
  20596. context.model, context.ecModel, context.api, context.payload
  20597. );
  20598. }
  20599. }
  20600. };
  20601. /*
  20602. * Licensed to the Apache Software Foundation (ASF) under one
  20603. * or more contributor license agreements. See the NOTICE file
  20604. * distributed with this work for additional information
  20605. * regarding copyright ownership. The ASF licenses this file
  20606. * to you under the Apache License, Version 2.0 (the
  20607. * "License"); you may not use this file except in compliance
  20608. * with the License. You may obtain a copy of the License at
  20609. *
  20610. * http://www.apache.org/licenses/LICENSE-2.0
  20611. *
  20612. * Unless required by applicable law or agreed to in writing,
  20613. * software distributed under the License is distributed on an
  20614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20615. * KIND, either express or implied. See the License for the
  20616. * specific language governing permissions and limitations
  20617. * under the License.
  20618. */
  20619. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  20620. var RATE = '\0__throttleRate';
  20621. var THROTTLE_TYPE = '\0__throttleType';
  20622. /**
  20623. * @public
  20624. * @param {(Function)} fn
  20625. * @param {number} [delay=0] Unit: ms.
  20626. * @param {boolean} [debounce=false]
  20627. * true: If call interval less than `delay`, only the last call works.
  20628. * false: If call interval less than `delay, call works on fixed rate.
  20629. * @return {(Function)} throttled fn.
  20630. */
  20631. function throttle(fn, delay, debounce) {
  20632. var currCall;
  20633. var lastCall = 0;
  20634. var lastExec = 0;
  20635. var timer = null;
  20636. var diff;
  20637. var scope;
  20638. var args;
  20639. var debounceNextCall;
  20640. delay = delay || 0;
  20641. function exec() {
  20642. lastExec = (new Date()).getTime();
  20643. timer = null;
  20644. fn.apply(scope, args || []);
  20645. }
  20646. var cb = function () {
  20647. currCall = (new Date()).getTime();
  20648. scope = this;
  20649. args = arguments;
  20650. var thisDelay = debounceNextCall || delay;
  20651. var thisDebounce = debounceNextCall || debounce;
  20652. debounceNextCall = null;
  20653. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  20654. clearTimeout(timer);
  20655. // Here we should make sure that: the `exec` SHOULD NOT be called later
  20656. // than a new call of `cb`, that is, preserving the command order. Consider
  20657. // calculating "scale rate" when roaming as an example. When a call of `cb`
  20658. // happens, either the `exec` is called dierectly, or the call is delayed.
  20659. // But the delayed call should never be later than next call of `cb`. Under
  20660. // this assurance, we can simply update view state each time `dispatchAction`
  20661. // triggered by user roaming, but not need to add extra code to avoid the
  20662. // state being "rolled-back".
  20663. if (thisDebounce) {
  20664. timer = setTimeout(exec, thisDelay);
  20665. }
  20666. else {
  20667. if (diff >= 0) {
  20668. exec();
  20669. }
  20670. else {
  20671. timer = setTimeout(exec, -diff);
  20672. }
  20673. }
  20674. lastCall = currCall;
  20675. };
  20676. /**
  20677. * Clear throttle.
  20678. * @public
  20679. */
  20680. cb.clear = function () {
  20681. if (timer) {
  20682. clearTimeout(timer);
  20683. timer = null;
  20684. }
  20685. };
  20686. /**
  20687. * Enable debounce once.
  20688. */
  20689. cb.debounceNextCall = function (debounceDelay) {
  20690. debounceNextCall = debounceDelay;
  20691. };
  20692. return cb;
  20693. }
  20694. /**
  20695. * Create throttle method or update throttle rate.
  20696. *
  20697. * @example
  20698. * ComponentView.prototype.render = function () {
  20699. * ...
  20700. * throttle.createOrUpdate(
  20701. * this,
  20702. * '_dispatchAction',
  20703. * this.model.get('throttle'),
  20704. * 'fixRate'
  20705. * );
  20706. * };
  20707. * ComponentView.prototype.remove = function () {
  20708. * throttle.clear(this, '_dispatchAction');
  20709. * };
  20710. * ComponentView.prototype.dispose = function () {
  20711. * throttle.clear(this, '_dispatchAction');
  20712. * };
  20713. *
  20714. * @public
  20715. * @param {Object} obj
  20716. * @param {string} fnAttr
  20717. * @param {number} [rate]
  20718. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  20719. * @return {Function} throttled function.
  20720. */
  20721. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  20722. var fn = obj[fnAttr];
  20723. if (!fn) {
  20724. return;
  20725. }
  20726. var originFn = fn[ORIGIN_METHOD] || fn;
  20727. var lastThrottleType = fn[THROTTLE_TYPE];
  20728. var lastRate = fn[RATE];
  20729. if (lastRate !== rate || lastThrottleType !== throttleType) {
  20730. if (rate == null || !throttleType) {
  20731. return (obj[fnAttr] = originFn);
  20732. }
  20733. fn = obj[fnAttr] = throttle(
  20734. originFn, rate, throttleType === 'debounce'
  20735. );
  20736. fn[ORIGIN_METHOD] = originFn;
  20737. fn[THROTTLE_TYPE] = throttleType;
  20738. fn[RATE] = rate;
  20739. }
  20740. return fn;
  20741. }
  20742. /**
  20743. * Clear throttle. Example see throttle.createOrUpdate.
  20744. *
  20745. * @public
  20746. * @param {Object} obj
  20747. * @param {string} fnAttr
  20748. */
  20749. function clear(obj, fnAttr) {
  20750. var fn = obj[fnAttr];
  20751. if (fn && fn[ORIGIN_METHOD]) {
  20752. obj[fnAttr] = fn[ORIGIN_METHOD];
  20753. }
  20754. }
  20755. /*
  20756. * Licensed to the Apache Software Foundation (ASF) under one
  20757. * or more contributor license agreements. See the NOTICE file
  20758. * distributed with this work for additional information
  20759. * regarding copyright ownership. The ASF licenses this file
  20760. * to you under the Apache License, Version 2.0 (the
  20761. * "License"); you may not use this file except in compliance
  20762. * with the License. You may obtain a copy of the License at
  20763. *
  20764. * http://www.apache.org/licenses/LICENSE-2.0
  20765. *
  20766. * Unless required by applicable law or agreed to in writing,
  20767. * software distributed under the License is distributed on an
  20768. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20769. * KIND, either express or implied. See the License for the
  20770. * specific language governing permissions and limitations
  20771. * under the License.
  20772. */
  20773. var seriesColor = {
  20774. createOnAllSeries: true,
  20775. performRawSeries: true,
  20776. reset: function (seriesModel, ecModel) {
  20777. var data = seriesModel.getData();
  20778. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  20779. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  20780. || seriesModel.getColorFromPalette(
  20781. // TODO series count changed.
  20782. seriesModel.name, null, ecModel.getSeriesCount()
  20783. ); // Default color
  20784. // FIXME Set color function or use the platte color
  20785. data.setVisual('color', color);
  20786. // Only visible series has each data be visual encoded
  20787. if (!ecModel.isSeriesFiltered(seriesModel)) {
  20788. if (typeof color === 'function' && !(color instanceof Gradient)) {
  20789. data.each(function (idx) {
  20790. data.setItemVisual(
  20791. idx, 'color', color(seriesModel.getDataParams(idx))
  20792. );
  20793. });
  20794. }
  20795. // itemStyle in each data item
  20796. var dataEach = function (data, idx) {
  20797. var itemModel = data.getItemModel(idx);
  20798. var color = itemModel.get(colorAccessPath, true);
  20799. if (color != null) {
  20800. data.setItemVisual(idx, 'color', color);
  20801. }
  20802. };
  20803. return { dataEach: data.hasItemOption ? dataEach : null };
  20804. }
  20805. }
  20806. };
  20807. /*
  20808. * Licensed to the Apache Software Foundation (ASF) under one
  20809. * or more contributor license agreements. See the NOTICE file
  20810. * distributed with this work for additional information
  20811. * regarding copyright ownership. The ASF licenses this file
  20812. * to you under the Apache License, Version 2.0 (the
  20813. * "License"); you may not use this file except in compliance
  20814. * with the License. You may obtain a copy of the License at
  20815. *
  20816. * http://www.apache.org/licenses/LICENSE-2.0
  20817. *
  20818. * Unless required by applicable law or agreed to in writing,
  20819. * software distributed under the License is distributed on an
  20820. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20821. * KIND, either express or implied. See the License for the
  20822. * specific language governing permissions and limitations
  20823. * under the License.
  20824. */
  20825. var lang = {
  20826. toolbox: {
  20827. brush: {
  20828. title: {
  20829. rect: '矩形选择',
  20830. polygon: '圈选',
  20831. lineX: '横向选择',
  20832. lineY: '纵向选择',
  20833. keep: '保持选择',
  20834. clear: '清除选择'
  20835. }
  20836. },
  20837. dataView: {
  20838. title: '数据视图',
  20839. lang: ['数据视图', '关闭', '刷新']
  20840. },
  20841. dataZoom: {
  20842. title: {
  20843. zoom: '区域缩放',
  20844. back: '区域缩放还原'
  20845. }
  20846. },
  20847. magicType: {
  20848. title: {
  20849. line: '切换为折线图',
  20850. bar: '切换为柱状图',
  20851. stack: '切换为堆叠',
  20852. tiled: '切换为平铺'
  20853. }
  20854. },
  20855. restore: {
  20856. title: '还原'
  20857. },
  20858. saveAsImage: {
  20859. title: '保存为图片',
  20860. lang: ['右键另存为图片']
  20861. }
  20862. },
  20863. series: {
  20864. typeNames: {
  20865. pie: '饼图',
  20866. bar: '柱状图',
  20867. line: '折线图',
  20868. scatter: '散点图',
  20869. effectScatter: '涟漪散点图',
  20870. radar: '雷达图',
  20871. tree: '树图',
  20872. treemap: '矩形树图',
  20873. boxplot: '箱型图',
  20874. candlestick: 'K线图',
  20875. k: 'K线图',
  20876. heatmap: '热力图',
  20877. map: '地图',
  20878. parallel: '平行坐标图',
  20879. lines: '线图',
  20880. graph: '关系图',
  20881. sankey: '桑基图',
  20882. funnel: '漏斗图',
  20883. gauge: '仪表盘图',
  20884. pictorialBar: '象形柱图',
  20885. themeRiver: '主题河流图',
  20886. sunburst: '旭日图'
  20887. }
  20888. },
  20889. aria: {
  20890. general: {
  20891. withTitle: '这是一个关于“{title}”的图表。',
  20892. withoutTitle: '这是一个图表,'
  20893. },
  20894. series: {
  20895. single: {
  20896. prefix: '',
  20897. withName: '图表类型是{seriesType},表示{seriesName}。',
  20898. withoutName: '图表类型是{seriesType}。'
  20899. },
  20900. multiple: {
  20901. prefix: '它由{seriesCount}个图表系列组成。',
  20902. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  20903. withoutName: '第{seriesId}个系列是一个{seriesType},',
  20904. separator: {
  20905. middle: ';',
  20906. end: '。'
  20907. }
  20908. }
  20909. },
  20910. data: {
  20911. allData: '其数据是——',
  20912. partialData: '其中,前{displayCnt}项是——',
  20913. withName: '{name}的数据是{value}',
  20914. withoutName: '{value}',
  20915. separator: {
  20916. middle: ',',
  20917. end: ''
  20918. }
  20919. }
  20920. }
  20921. };
  20922. /*
  20923. * Licensed to the Apache Software Foundation (ASF) under one
  20924. * or more contributor license agreements. See the NOTICE file
  20925. * distributed with this work for additional information
  20926. * regarding copyright ownership. The ASF licenses this file
  20927. * to you under the Apache License, Version 2.0 (the
  20928. * "License"); you may not use this file except in compliance
  20929. * with the License. You may obtain a copy of the License at
  20930. *
  20931. * http://www.apache.org/licenses/LICENSE-2.0
  20932. *
  20933. * Unless required by applicable law or agreed to in writing,
  20934. * software distributed under the License is distributed on an
  20935. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20936. * KIND, either express or implied. See the License for the
  20937. * specific language governing permissions and limitations
  20938. * under the License.
  20939. */
  20940. var aria = function (dom, ecModel) {
  20941. var ariaModel = ecModel.getModel('aria');
  20942. if (!ariaModel.get('show')) {
  20943. return;
  20944. }
  20945. else if (ariaModel.get('description')) {
  20946. dom.setAttribute('aria-label', ariaModel.get('description'));
  20947. return;
  20948. }
  20949. var seriesCnt = 0;
  20950. ecModel.eachSeries(function (seriesModel, idx) {
  20951. ++seriesCnt;
  20952. }, this);
  20953. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  20954. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  20955. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  20956. var ariaLabel;
  20957. if (seriesCnt < 1) {
  20958. // No series, no aria label
  20959. return;
  20960. }
  20961. else {
  20962. var title = getTitle();
  20963. if (title) {
  20964. ariaLabel = replace(getConfig('general.withTitle'), {
  20965. title: title
  20966. });
  20967. }
  20968. else {
  20969. ariaLabel = getConfig('general.withoutTitle');
  20970. }
  20971. var seriesLabels = [];
  20972. var prefix = seriesCnt > 1
  20973. ? 'series.multiple.prefix'
  20974. : 'series.single.prefix';
  20975. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  20976. ecModel.eachSeries(function (seriesModel, idx) {
  20977. if (idx < displaySeriesCnt) {
  20978. var seriesLabel;
  20979. var seriesName = seriesModel.get('name');
  20980. var seriesTpl = 'series.'
  20981. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  20982. seriesLabel = getConfig(seriesName
  20983. ? seriesTpl + 'withName'
  20984. : seriesTpl + 'withoutName');
  20985. seriesLabel = replace(seriesLabel, {
  20986. seriesId: seriesModel.seriesIndex,
  20987. seriesName: seriesModel.get('name'),
  20988. seriesType: getSeriesTypeName(seriesModel.subType)
  20989. });
  20990. var data = seriesModel.getData();
  20991. window.data = data;
  20992. if (data.count() > maxDataCnt) {
  20993. // Show part of data
  20994. seriesLabel += replace(getConfig('data.partialData'), {
  20995. displayCnt: maxDataCnt
  20996. });
  20997. }
  20998. else {
  20999. seriesLabel += getConfig('data.allData');
  21000. }
  21001. var dataLabels = [];
  21002. for (var i = 0; i < data.count(); i++) {
  21003. if (i < maxDataCnt) {
  21004. var name = data.getName(i);
  21005. var value = retrieveRawValue(data, i);
  21006. dataLabels.push(
  21007. replace(
  21008. name
  21009. ? getConfig('data.withName')
  21010. : getConfig('data.withoutName'),
  21011. {
  21012. name: name,
  21013. value: value
  21014. }
  21015. )
  21016. );
  21017. }
  21018. }
  21019. seriesLabel += dataLabels
  21020. .join(getConfig('data.separator.middle'))
  21021. + getConfig('data.separator.end');
  21022. seriesLabels.push(seriesLabel);
  21023. }
  21024. });
  21025. ariaLabel += seriesLabels
  21026. .join(getConfig('series.multiple.separator.middle'))
  21027. + getConfig('series.multiple.separator.end');
  21028. dom.setAttribute('aria-label', ariaLabel);
  21029. }
  21030. function replace(str, keyValues) {
  21031. if (typeof str !== 'string') {
  21032. return str;
  21033. }
  21034. var result = str;
  21035. each$1(keyValues, function (value, key) {
  21036. result = result.replace(
  21037. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21038. value
  21039. );
  21040. });
  21041. return result;
  21042. }
  21043. function getConfig(path) {
  21044. var userConfig = ariaModel.get(path);
  21045. if (userConfig == null) {
  21046. var pathArr = path.split('.');
  21047. var result = lang.aria;
  21048. for (var i = 0; i < pathArr.length; ++i) {
  21049. result = result[pathArr[i]];
  21050. }
  21051. return result;
  21052. }
  21053. else {
  21054. return userConfig;
  21055. }
  21056. }
  21057. function getTitle() {
  21058. var title = ecModel.getModel('title').option;
  21059. if (title && title.length) {
  21060. title = title[0];
  21061. }
  21062. return title && title.text;
  21063. }
  21064. function getSeriesTypeName(type) {
  21065. return lang.series.typeNames[type] || '自定义图';
  21066. }
  21067. };
  21068. /*
  21069. * Licensed to the Apache Software Foundation (ASF) under one
  21070. * or more contributor license agreements. See the NOTICE file
  21071. * distributed with this work for additional information
  21072. * regarding copyright ownership. The ASF licenses this file
  21073. * to you under the Apache License, Version 2.0 (the
  21074. * "License"); you may not use this file except in compliance
  21075. * with the License. You may obtain a copy of the License at
  21076. *
  21077. * http://www.apache.org/licenses/LICENSE-2.0
  21078. *
  21079. * Unless required by applicable law or agreed to in writing,
  21080. * software distributed under the License is distributed on an
  21081. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21082. * KIND, either express or implied. See the License for the
  21083. * specific language governing permissions and limitations
  21084. * under the License.
  21085. */
  21086. var PI$1 = Math.PI;
  21087. /**
  21088. * @param {module:echarts/ExtensionAPI} api
  21089. * @param {Object} [opts]
  21090. * @param {string} [opts.text]
  21091. * @param {string} [opts.color]
  21092. * @param {string} [opts.textColor]
  21093. * @return {module:zrender/Element}
  21094. */
  21095. var loadingDefault = function (api, opts) {
  21096. opts = opts || {};
  21097. defaults(opts, {
  21098. text: 'loading',
  21099. color: '#c23531',
  21100. textColor: '#000',
  21101. maskColor: 'rgba(255, 255, 255, 0.8)',
  21102. zlevel: 0
  21103. });
  21104. var mask = new Rect({
  21105. style: {
  21106. fill: opts.maskColor
  21107. },
  21108. zlevel: opts.zlevel,
  21109. z: 10000
  21110. });
  21111. var arc = new Arc({
  21112. shape: {
  21113. startAngle: -PI$1 / 2,
  21114. endAngle: -PI$1 / 2 + 0.1,
  21115. r: 10
  21116. },
  21117. style: {
  21118. stroke: opts.color,
  21119. lineCap: 'round',
  21120. lineWidth: 5
  21121. },
  21122. zlevel: opts.zlevel,
  21123. z: 10001
  21124. });
  21125. var labelRect = new Rect({
  21126. style: {
  21127. fill: 'none',
  21128. text: opts.text,
  21129. textPosition: 'right',
  21130. textDistance: 10,
  21131. textFill: opts.textColor
  21132. },
  21133. zlevel: opts.zlevel,
  21134. z: 10001
  21135. });
  21136. arc.animateShape(true)
  21137. .when(1000, {
  21138. endAngle: PI$1 * 3 / 2
  21139. })
  21140. .start('circularInOut');
  21141. arc.animateShape(true)
  21142. .when(1000, {
  21143. startAngle: PI$1 * 3 / 2
  21144. })
  21145. .delay(300)
  21146. .start('circularInOut');
  21147. var group = new Group();
  21148. group.add(arc);
  21149. group.add(labelRect);
  21150. group.add(mask);
  21151. // Inject resize
  21152. group.resize = function () {
  21153. var cx = api.getWidth() / 2;
  21154. var cy = api.getHeight() / 2;
  21155. arc.setShape({
  21156. cx: cx,
  21157. cy: cy
  21158. });
  21159. var r = arc.shape.r;
  21160. labelRect.setShape({
  21161. x: cx - r,
  21162. y: cy - r,
  21163. width: r * 2,
  21164. height: r * 2
  21165. });
  21166. mask.setShape({
  21167. x: 0,
  21168. y: 0,
  21169. width: api.getWidth(),
  21170. height: api.getHeight()
  21171. });
  21172. };
  21173. group.resize();
  21174. return group;
  21175. };
  21176. /*
  21177. * Licensed to the Apache Software Foundation (ASF) under one
  21178. * or more contributor license agreements. See the NOTICE file
  21179. * distributed with this work for additional information
  21180. * regarding copyright ownership. The ASF licenses this file
  21181. * to you under the Apache License, Version 2.0 (the
  21182. * "License"); you may not use this file except in compliance
  21183. * with the License. You may obtain a copy of the License at
  21184. *
  21185. * http://www.apache.org/licenses/LICENSE-2.0
  21186. *
  21187. * Unless required by applicable law or agreed to in writing,
  21188. * software distributed under the License is distributed on an
  21189. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21190. * KIND, either express or implied. See the License for the
  21191. * specific language governing permissions and limitations
  21192. * under the License.
  21193. */
  21194. /**
  21195. * @module echarts/stream/Scheduler
  21196. */
  21197. /**
  21198. * @constructor
  21199. */
  21200. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21201. this.ecInstance = ecInstance;
  21202. this.api = api;
  21203. this.unfinished;
  21204. // Fix current processors in case that in some rear cases that
  21205. // processors might be registered after echarts instance created.
  21206. // Register processors incrementally for a echarts instance is
  21207. // not supported by this stream architecture.
  21208. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21209. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21210. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21211. /**
  21212. * @private
  21213. * @type {
  21214. * [handlerUID: string]: {
  21215. * seriesTaskMap?: {
  21216. * [seriesUID: string]: Task
  21217. * },
  21218. * overallTask?: Task
  21219. * }
  21220. * }
  21221. */
  21222. this._stageTaskMap = createHashMap();
  21223. }
  21224. var proto = Scheduler.prototype;
  21225. /**
  21226. * @param {module:echarts/model/Global} ecModel
  21227. * @param {Object} payload
  21228. */
  21229. proto.restoreData = function (ecModel, payload) {
  21230. // TODO: Only restroe needed series and components, but not all components.
  21231. // Currently `restoreData` of all of the series and component will be called.
  21232. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21233. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21234. // and some components like coordinate system, axes, dataZoom, visualMap only
  21235. // need their target series refresh.
  21236. // (1) If we are implementing this feature some day, we should consider these cases:
  21237. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21238. // on the settings of `dataZoom`), it should be re-performed if the component
  21239. // is modified by `setOption`.
  21240. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21241. // it should be re-performed when the result array of `getTargetSeries` changed.
  21242. // We use `dependencies` to cover these issues.
  21243. // (3) How to update target series when coordinate system related components modified.
  21244. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21245. // and this case all of the tasks will be set as dirty.
  21246. ecModel.restoreData(payload);
  21247. // Theoretically an overall task not only depends on each of its target series, but also
  21248. // depends on all of the series.
  21249. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21250. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21251. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21252. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21253. // probably cause state chaos (consider `dataZoomProcessor`).
  21254. this._stageTaskMap.each(function (taskRecord) {
  21255. var overallTask = taskRecord.overallTask;
  21256. overallTask && overallTask.dirty();
  21257. });
  21258. };
  21259. // If seriesModel provided, incremental threshold is check by series data.
  21260. proto.getPerformArgs = function (task, isBlock) {
  21261. // For overall task
  21262. if (!task.__pipeline) {
  21263. return;
  21264. }
  21265. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21266. var pCtx = pipeline.context;
  21267. var incremental = !isBlock
  21268. && pipeline.progressiveEnabled
  21269. && (!pCtx || pCtx.progressiveRender)
  21270. && task.__idxInPipeline > pipeline.blockIndex;
  21271. var step = incremental ? pipeline.step : null;
  21272. var modDataCount = pCtx && pCtx.modDataCount;
  21273. var modBy = modDataCount != null ? Math.ceil(modDataCount / step): null;
  21274. return {step: step, modBy: modBy, modDataCount: modDataCount};
  21275. };
  21276. proto.getPipeline = function (pipelineId) {
  21277. return this._pipelineMap.get(pipelineId);
  21278. };
  21279. /**
  21280. * Current, progressive rendering starts from visual and layout.
  21281. * Always detect render mode in the same stage, avoiding that incorrect
  21282. * detection caused by data filtering.
  21283. * Caution:
  21284. * `updateStreamModes` use `seriesModel.getData()`.
  21285. */
  21286. proto.updateStreamModes = function (seriesModel, view) {
  21287. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21288. var data = seriesModel.getData();
  21289. var dataLen = data.count();
  21290. // `progressiveRender` means that can render progressively in each
  21291. // animation frame. Note that some types of series do not provide
  21292. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21293. // use the term `incremental` but not `progressive` to describe the
  21294. // case that `chart.appendData`.
  21295. var progressiveRender = pipeline.progressiveEnabled
  21296. && view.incrementalPrepareRender
  21297. && dataLen >= pipeline.threshold;
  21298. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  21299. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21300. // see `test/candlestick-large3.html`
  21301. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21302. seriesModel.pipelineContext = pipeline.context = {
  21303. progressiveRender: progressiveRender,
  21304. modDataCount: modDataCount,
  21305. large: large
  21306. };
  21307. };
  21308. proto.restorePipelines = function (ecModel) {
  21309. var scheduler = this;
  21310. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21311. ecModel.eachSeries(function (seriesModel) {
  21312. var progressive = seriesModel.getProgressive();
  21313. var pipelineId = seriesModel.uid;
  21314. pipelineMap.set(pipelineId, {
  21315. id: pipelineId,
  21316. head: null,
  21317. tail: null,
  21318. threshold: seriesModel.getProgressiveThreshold(),
  21319. progressiveEnabled: progressive
  21320. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21321. blockIndex: -1,
  21322. step: Math.round(progressive || 700),
  21323. count: 0
  21324. });
  21325. pipe(scheduler, seriesModel, seriesModel.dataTask);
  21326. });
  21327. };
  21328. proto.prepareStageTasks = function () {
  21329. var stageTaskMap = this._stageTaskMap;
  21330. var ecModel = this.ecInstance.getModel();
  21331. var api = this.api;
  21332. each$1(this._allHandlers, function (handler) {
  21333. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  21334. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  21335. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  21336. }, this);
  21337. };
  21338. proto.prepareView = function (view, model, ecModel, api) {
  21339. var renderTask = view.renderTask;
  21340. var context = renderTask.context;
  21341. context.model = model;
  21342. context.ecModel = ecModel;
  21343. context.api = api;
  21344. renderTask.__block = !view.incrementalPrepareRender;
  21345. pipe(this, model, renderTask);
  21346. };
  21347. proto.performDataProcessorTasks = function (ecModel, payload) {
  21348. // If we do not use `block` here, it should be considered when to update modes.
  21349. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  21350. };
  21351. // opt
  21352. // opt.visualType: 'visual' or 'layout'
  21353. // opt.setDirty
  21354. proto.performVisualTasks = function (ecModel, payload, opt) {
  21355. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  21356. };
  21357. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  21358. opt = opt || {};
  21359. var unfinished;
  21360. each$1(stageHandlers, function (stageHandler, idx) {
  21361. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21362. return;
  21363. }
  21364. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21365. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21366. var overallTask = stageHandlerRecord.overallTask;
  21367. if (overallTask) {
  21368. var overallNeedDirty;
  21369. var agentStubMap = overallTask.agentStubMap;
  21370. agentStubMap.each(function (stub) {
  21371. if (needSetDirty(opt, stub)) {
  21372. stub.dirty();
  21373. overallNeedDirty = true;
  21374. }
  21375. });
  21376. overallNeedDirty && overallTask.dirty();
  21377. updatePayload(overallTask, payload);
  21378. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  21379. // Execute stubs firstly, which may set the overall task dirty,
  21380. // then execute the overall task. And stub will call seriesModel.setData,
  21381. // which ensures that in the overallTask seriesModel.getData() will not
  21382. // return incorrect data.
  21383. agentStubMap.each(function (stub) {
  21384. stub.perform(performArgs);
  21385. });
  21386. unfinished |= overallTask.perform(performArgs);
  21387. }
  21388. else if (seriesTaskMap) {
  21389. seriesTaskMap.each(function (task, pipelineId) {
  21390. if (needSetDirty(opt, task)) {
  21391. task.dirty();
  21392. }
  21393. var performArgs = scheduler.getPerformArgs(task, opt.block);
  21394. performArgs.skip = !stageHandler.performRawSeries
  21395. && ecModel.isSeriesFiltered(task.context.model);
  21396. updatePayload(task, payload);
  21397. unfinished |= task.perform(performArgs);
  21398. });
  21399. }
  21400. });
  21401. function needSetDirty(opt, task) {
  21402. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21403. }
  21404. scheduler.unfinished |= unfinished;
  21405. }
  21406. proto.performSeriesTasks = function (ecModel) {
  21407. var unfinished;
  21408. ecModel.eachSeries(function (seriesModel) {
  21409. // Progress to the end for dataInit and dataRestore.
  21410. unfinished |= seriesModel.dataTask.perform();
  21411. });
  21412. this.unfinished |= unfinished;
  21413. };
  21414. proto.plan = function () {
  21415. // Travel pipelines, check block.
  21416. this._pipelineMap.each(function (pipeline) {
  21417. var task = pipeline.tail;
  21418. do {
  21419. if (task.__block) {
  21420. pipeline.blockIndex = task.__idxInPipeline;
  21421. break;
  21422. }
  21423. task = task.getUpstream();
  21424. }
  21425. while (task);
  21426. });
  21427. };
  21428. var updatePayload = proto.updatePayload = function (task, payload) {
  21429. payload !== 'remain' && (task.context.payload = payload);
  21430. };
  21431. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21432. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  21433. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  21434. var seriesType = stageHandler.seriesType;
  21435. var getTargetSeries = stageHandler.getTargetSeries;
  21436. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21437. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21438. // it works but it may cause other irrelevant charts blocked.
  21439. if (stageHandler.createOnAllSeries) {
  21440. ecModel.eachRawSeries(create);
  21441. }
  21442. else if (seriesType) {
  21443. ecModel.eachRawSeriesByType(seriesType, create);
  21444. }
  21445. else if (getTargetSeries) {
  21446. getTargetSeries(ecModel, api).each(create);
  21447. }
  21448. function create(seriesModel) {
  21449. var pipelineId = seriesModel.uid;
  21450. // Init tasks for each seriesModel only once.
  21451. // Reuse original task instance.
  21452. var task = seriesTaskMap.get(pipelineId)
  21453. || seriesTaskMap.set(pipelineId, createTask({
  21454. plan: seriesTaskPlan,
  21455. reset: seriesTaskReset,
  21456. count: seriesTaskCount
  21457. }));
  21458. task.context = {
  21459. model: seriesModel,
  21460. ecModel: ecModel,
  21461. api: api,
  21462. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21463. plan: stageHandler.plan,
  21464. reset: stageHandler.reset,
  21465. scheduler: scheduler
  21466. };
  21467. pipe(scheduler, seriesModel, task);
  21468. }
  21469. // Clear unused series tasks.
  21470. var pipelineMap = scheduler._pipelineMap;
  21471. seriesTaskMap.each(function (task, pipelineId) {
  21472. if (!pipelineMap.get(pipelineId)) {
  21473. task.dispose();
  21474. seriesTaskMap.removeKey(pipelineId);
  21475. }
  21476. });
  21477. }
  21478. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21479. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  21480. // For overall task, the function only be called on reset stage.
  21481. || createTask({reset: overallTaskReset});
  21482. overallTask.context = {
  21483. ecModel: ecModel,
  21484. api: api,
  21485. overallReset: stageHandler.overallReset,
  21486. scheduler: scheduler
  21487. };
  21488. // Reuse orignal stubs.
  21489. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  21490. var seriesType = stageHandler.seriesType;
  21491. var getTargetSeries = stageHandler.getTargetSeries;
  21492. var overallProgress = true;
  21493. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  21494. // An overall task with seriesType detected or has `getTargetSeries`, we add
  21495. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21496. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21497. // we set the pipeline block.
  21498. if (seriesType) {
  21499. ecModel.eachRawSeriesByType(seriesType, createStub);
  21500. }
  21501. else if (getTargetSeries) {
  21502. getTargetSeries(ecModel, api).each(createStub);
  21503. }
  21504. // Otherwise, (usually it is legancy case), the overall task will only be
  21505. // executed when upstream dirty. Otherwise the progressive rendering of all
  21506. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  21507. // dirty info from upsteam.
  21508. else {
  21509. overallProgress = false;
  21510. each$1(ecModel.getSeries(), createStub);
  21511. }
  21512. function createStub(seriesModel) {
  21513. var pipelineId = seriesModel.uid;
  21514. var stub = agentStubMap.get(pipelineId);
  21515. if (!stub) {
  21516. stub = agentStubMap.set(pipelineId, createTask(
  21517. {reset: stubReset, onDirty: stubOnDirty}
  21518. ));
  21519. // When the result of `getTargetSeries` changed, the overallTask
  21520. // should be set as dirty and re-performed.
  21521. overallTask.dirty();
  21522. }
  21523. stub.context = {
  21524. model: seriesModel,
  21525. overallProgress: overallProgress,
  21526. modifyOutputEnd: modifyOutputEnd
  21527. };
  21528. stub.agent = overallTask;
  21529. stub.__block = overallProgress;
  21530. pipe(scheduler, seriesModel, stub);
  21531. }
  21532. // Clear unused stubs.
  21533. var pipelineMap = scheduler._pipelineMap;
  21534. agentStubMap.each(function (stub, pipelineId) {
  21535. if (!pipelineMap.get(pipelineId)) {
  21536. stub.dispose();
  21537. // When the result of `getTargetSeries` changed, the overallTask
  21538. // should be set as dirty and re-performed.
  21539. overallTask.dirty();
  21540. agentStubMap.removeKey(pipelineId);
  21541. }
  21542. });
  21543. }
  21544. function overallTaskReset(context) {
  21545. context.overallReset(
  21546. context.ecModel, context.api, context.payload
  21547. );
  21548. }
  21549. function stubReset(context, upstreamContext) {
  21550. return context.overallProgress && stubProgress;
  21551. }
  21552. function stubProgress() {
  21553. this.agent.dirty();
  21554. this.getDownstream().dirty();
  21555. }
  21556. function stubOnDirty() {
  21557. this.agent && this.agent.dirty();
  21558. }
  21559. function seriesTaskPlan(context) {
  21560. return context.plan && context.plan(
  21561. context.model, context.ecModel, context.api, context.payload
  21562. );
  21563. }
  21564. function seriesTaskReset(context) {
  21565. if (context.useClearVisual) {
  21566. context.data.clearAllVisual();
  21567. }
  21568. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  21569. context.model, context.ecModel, context.api, context.payload
  21570. ));
  21571. return resetDefines.length > 1
  21572. ? map(resetDefines, function (v, idx) {
  21573. return makeSeriesTaskProgress(idx);
  21574. })
  21575. : singleSeriesTaskProgress;
  21576. }
  21577. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  21578. function makeSeriesTaskProgress(resetDefineIdx) {
  21579. return function (params, context) {
  21580. var data = context.data;
  21581. var resetDefine = context.resetDefines[resetDefineIdx];
  21582. if (resetDefine && resetDefine.dataEach) {
  21583. for (var i = params.start; i < params.end; i++) {
  21584. resetDefine.dataEach(data, i);
  21585. }
  21586. }
  21587. else if (resetDefine && resetDefine.progress) {
  21588. resetDefine.progress(params, data);
  21589. }
  21590. };
  21591. }
  21592. function seriesTaskCount(context) {
  21593. return context.data.count();
  21594. }
  21595. function pipe(scheduler, seriesModel, task) {
  21596. var pipelineId = seriesModel.uid;
  21597. var pipeline = scheduler._pipelineMap.get(pipelineId);
  21598. !pipeline.head && (pipeline.head = task);
  21599. pipeline.tail && pipeline.tail.pipe(task);
  21600. pipeline.tail = task;
  21601. task.__idxInPipeline = pipeline.count++;
  21602. task.__pipeline = pipeline;
  21603. }
  21604. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  21605. if (isFunction$1(stageHandler)) {
  21606. stageHandler = {
  21607. overallReset: stageHandler,
  21608. seriesType: detectSeriseType(stageHandler)
  21609. };
  21610. }
  21611. stageHandler.uid = getUID('stageHandler');
  21612. visualType && (stageHandler.visualType = visualType);
  21613. return stageHandler;
  21614. };
  21615. /**
  21616. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  21617. * To ensure that they can work normally, they should work in block mode, that is,
  21618. * they should not be started util the previous tasks finished. So they cause the
  21619. * progressive rendering disabled. We try to detect the series type, to narrow down
  21620. * the block range to only the series type they concern, but not all series.
  21621. */
  21622. function detectSeriseType(legacyFunc) {
  21623. seriesType = null;
  21624. try {
  21625. // Assume there is no async when calling `eachSeriesByType`.
  21626. legacyFunc(ecModelMock, apiMock);
  21627. }
  21628. catch (e) {
  21629. }
  21630. return seriesType;
  21631. }
  21632. var ecModelMock = {};
  21633. var apiMock = {};
  21634. var seriesType;
  21635. mockMethods(ecModelMock, GlobalModel);
  21636. mockMethods(apiMock, ExtensionAPI);
  21637. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  21638. seriesType = type;
  21639. };
  21640. ecModelMock.eachComponent = function (cond) {
  21641. if (cond.mainType === 'series' && cond.subType) {
  21642. seriesType = cond.subType;
  21643. }
  21644. };
  21645. function mockMethods(target, Clz) {
  21646. for (var name in Clz.prototype) {
  21647. // Do not use hasOwnProperty
  21648. target[name] = noop;
  21649. }
  21650. }
  21651. /*
  21652. * Licensed to the Apache Software Foundation (ASF) under one
  21653. * or more contributor license agreements. See the NOTICE file
  21654. * distributed with this work for additional information
  21655. * regarding copyright ownership. The ASF licenses this file
  21656. * to you under the Apache License, Version 2.0 (the
  21657. * "License"); you may not use this file except in compliance
  21658. * with the License. You may obtain a copy of the License at
  21659. *
  21660. * http://www.apache.org/licenses/LICENSE-2.0
  21661. *
  21662. * Unless required by applicable law or agreed to in writing,
  21663. * software distributed under the License is distributed on an
  21664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21665. * KIND, either express or implied. See the License for the
  21666. * specific language governing permissions and limitations
  21667. * under the License.
  21668. */
  21669. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  21670. var lightTheme = {
  21671. color: colorAll,
  21672. colorLayer: [
  21673. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  21674. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  21675. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  21676. colorAll
  21677. ]
  21678. };
  21679. /*
  21680. * Licensed to the Apache Software Foundation (ASF) under one
  21681. * or more contributor license agreements. See the NOTICE file
  21682. * distributed with this work for additional information
  21683. * regarding copyright ownership. The ASF licenses this file
  21684. * to you under the Apache License, Version 2.0 (the
  21685. * "License"); you may not use this file except in compliance
  21686. * with the License. You may obtain a copy of the License at
  21687. *
  21688. * http://www.apache.org/licenses/LICENSE-2.0
  21689. *
  21690. * Unless required by applicable law or agreed to in writing,
  21691. * software distributed under the License is distributed on an
  21692. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21693. * KIND, either express or implied. See the License for the
  21694. * specific language governing permissions and limitations
  21695. * under the License.
  21696. */
  21697. var contrastColor = '#eee';
  21698. var axisCommon = function () {
  21699. return {
  21700. axisLine: {
  21701. lineStyle: {
  21702. color: contrastColor
  21703. }
  21704. },
  21705. axisTick: {
  21706. lineStyle: {
  21707. color: contrastColor
  21708. }
  21709. },
  21710. axisLabel: {
  21711. textStyle: {
  21712. color: contrastColor
  21713. }
  21714. },
  21715. splitLine: {
  21716. lineStyle: {
  21717. type: 'dashed',
  21718. color: '#aaa'
  21719. }
  21720. },
  21721. splitArea: {
  21722. areaStyle: {
  21723. color: contrastColor
  21724. }
  21725. }
  21726. };
  21727. };
  21728. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  21729. var theme = {
  21730. color: colorPalette,
  21731. backgroundColor: '#333',
  21732. tooltip: {
  21733. axisPointer: {
  21734. lineStyle: {
  21735. color: contrastColor
  21736. },
  21737. crossStyle: {
  21738. color: contrastColor
  21739. }
  21740. }
  21741. },
  21742. legend: {
  21743. textStyle: {
  21744. color: contrastColor
  21745. }
  21746. },
  21747. textStyle: {
  21748. color: contrastColor
  21749. },
  21750. title: {
  21751. textStyle: {
  21752. color: contrastColor
  21753. }
  21754. },
  21755. toolbox: {
  21756. iconStyle: {
  21757. normal: {
  21758. borderColor: contrastColor
  21759. }
  21760. }
  21761. },
  21762. dataZoom: {
  21763. textStyle: {
  21764. color: contrastColor
  21765. }
  21766. },
  21767. visualMap: {
  21768. textStyle: {
  21769. color: contrastColor
  21770. }
  21771. },
  21772. timeline: {
  21773. lineStyle: {
  21774. color: contrastColor
  21775. },
  21776. itemStyle: {
  21777. normal: {
  21778. color: colorPalette[1]
  21779. }
  21780. },
  21781. label: {
  21782. normal: {
  21783. textStyle: {
  21784. color: contrastColor
  21785. }
  21786. }
  21787. },
  21788. controlStyle: {
  21789. normal: {
  21790. color: contrastColor,
  21791. borderColor: contrastColor
  21792. }
  21793. }
  21794. },
  21795. timeAxis: axisCommon(),
  21796. logAxis: axisCommon(),
  21797. valueAxis: axisCommon(),
  21798. categoryAxis: axisCommon(),
  21799. line: {
  21800. symbol: 'circle'
  21801. },
  21802. graph: {
  21803. color: colorPalette
  21804. },
  21805. gauge: {
  21806. title: {
  21807. textStyle: {
  21808. color: contrastColor
  21809. }
  21810. }
  21811. },
  21812. candlestick: {
  21813. itemStyle: {
  21814. normal: {
  21815. color: '#FD1050',
  21816. color0: '#0CF49B',
  21817. borderColor: '#FD1050',
  21818. borderColor0: '#0CF49B'
  21819. }
  21820. }
  21821. }
  21822. };
  21823. theme.categoryAxis.splitLine.show = false;
  21824. /*
  21825. * Licensed to the Apache Software Foundation (ASF) under one
  21826. * or more contributor license agreements. See the NOTICE file
  21827. * distributed with this work for additional information
  21828. * regarding copyright ownership. The ASF licenses this file
  21829. * to you under the Apache License, Version 2.0 (the
  21830. * "License"); you may not use this file except in compliance
  21831. * with the License. You may obtain a copy of the License at
  21832. *
  21833. * http://www.apache.org/licenses/LICENSE-2.0
  21834. *
  21835. * Unless required by applicable law or agreed to in writing,
  21836. * software distributed under the License is distributed on an
  21837. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21838. * KIND, either express or implied. See the License for the
  21839. * specific language governing permissions and limitations
  21840. * under the License.
  21841. */
  21842. /**
  21843. * This module is imported by echarts directly.
  21844. *
  21845. * Notice:
  21846. * Always keep this file exists for backward compatibility.
  21847. * Because before 4.1.0, dataset is an optional component,
  21848. * some users may import this module manually.
  21849. */
  21850. ComponentModel.extend({
  21851. type: 'dataset',
  21852. /**
  21853. * @protected
  21854. */
  21855. defaultOption: {
  21856. // 'row', 'column'
  21857. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  21858. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  21859. sourceHeader: null,
  21860. dimensions: null,
  21861. source: null
  21862. },
  21863. optionUpdated: function () {
  21864. detectSourceFormat(this);
  21865. }
  21866. });
  21867. Component.extend({
  21868. type: 'dataset'
  21869. });
  21870. /*
  21871. * Licensed to the Apache Software Foundation (ASF) under one
  21872. * or more contributor license agreements. See the NOTICE file
  21873. * distributed with this work for additional information
  21874. * regarding copyright ownership. The ASF licenses this file
  21875. * to you under the Apache License, Version 2.0 (the
  21876. * "License"); you may not use this file except in compliance
  21877. * with the License. You may obtain a copy of the License at
  21878. *
  21879. * http://www.apache.org/licenses/LICENSE-2.0
  21880. *
  21881. * Unless required by applicable law or agreed to in writing,
  21882. * software distributed under the License is distributed on an
  21883. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21884. * KIND, either express or implied. See the License for the
  21885. * specific language governing permissions and limitations
  21886. * under the License.
  21887. */
  21888. var assert = assert$1;
  21889. var each = each$1;
  21890. var isFunction = isFunction$1;
  21891. var isObject = isObject$1;
  21892. var parseClassType = ComponentModel.parseClassType;
  21893. var version = '4.1.0';
  21894. var dependencies = {
  21895. zrender: '4.0.4'
  21896. };
  21897. var TEST_FRAME_REMAIN_TIME = 1;
  21898. var PRIORITY_PROCESSOR_FILTER = 1000;
  21899. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  21900. var PRIORITY_VISUAL_LAYOUT = 1000;
  21901. var PRIORITY_VISUAL_GLOBAL = 2000;
  21902. var PRIORITY_VISUAL_CHART = 3000;
  21903. var PRIORITY_VISUAL_COMPONENT = 4000;
  21904. // FIXME
  21905. // necessary?
  21906. var PRIORITY_VISUAL_BRUSH = 5000;
  21907. var PRIORITY = {
  21908. PROCESSOR: {
  21909. FILTER: PRIORITY_PROCESSOR_FILTER,
  21910. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  21911. },
  21912. VISUAL: {
  21913. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  21914. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  21915. CHART: PRIORITY_VISUAL_CHART,
  21916. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  21917. BRUSH: PRIORITY_VISUAL_BRUSH
  21918. }
  21919. };
  21920. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  21921. // where they must not be invoked nestedly, except the only case: invoke
  21922. // dispatchAction with updateMethod "none" in main process.
  21923. // This flag is used to carry out this rule.
  21924. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  21925. var IN_MAIN_PROCESS = '__flagInMainProcess';
  21926. var OPTION_UPDATED = '__optionUpdated';
  21927. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  21928. function createRegisterEventWithLowercaseName(method) {
  21929. return function (eventName, handler, context) {
  21930. // Event name is all lowercase
  21931. eventName = eventName && eventName.toLowerCase();
  21932. Eventful.prototype[method].call(this, eventName, handler, context);
  21933. };
  21934. }
  21935. /**
  21936. * @module echarts~MessageCenter
  21937. */
  21938. function MessageCenter() {
  21939. Eventful.call(this);
  21940. }
  21941. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  21942. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  21943. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  21944. mixin(MessageCenter, Eventful);
  21945. /**
  21946. * @module echarts~ECharts
  21947. */
  21948. function ECharts(dom, theme$$1, opts) {
  21949. opts = opts || {};
  21950. // Get theme by name
  21951. if (typeof theme$$1 === 'string') {
  21952. theme$$1 = themeStorage[theme$$1];
  21953. }
  21954. /**
  21955. * @type {string}
  21956. */
  21957. this.id;
  21958. /**
  21959. * Group id
  21960. * @type {string}
  21961. */
  21962. this.group;
  21963. /**
  21964. * @type {HTMLElement}
  21965. * @private
  21966. */
  21967. this._dom = dom;
  21968. var defaultRenderer = 'canvas';
  21969. if (__DEV__) {
  21970. defaultRenderer = (
  21971. typeof window === 'undefined' ? global : window
  21972. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  21973. }
  21974. /**
  21975. * @type {module:zrender/ZRender}
  21976. * @private
  21977. */
  21978. var zr = this._zr = init$1(dom, {
  21979. renderer: opts.renderer || defaultRenderer,
  21980. devicePixelRatio: opts.devicePixelRatio,
  21981. width: opts.width,
  21982. height: opts.height
  21983. });
  21984. /**
  21985. * Expect 60 pfs.
  21986. * @type {Function}
  21987. * @private
  21988. */
  21989. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  21990. var theme$$1 = clone(theme$$1);
  21991. theme$$1 && backwardCompat(theme$$1, true);
  21992. /**
  21993. * @type {Object}
  21994. * @private
  21995. */
  21996. this._theme = theme$$1;
  21997. /**
  21998. * @type {Array.<module:echarts/view/Chart>}
  21999. * @private
  22000. */
  22001. this._chartsViews = [];
  22002. /**
  22003. * @type {Object.<string, module:echarts/view/Chart>}
  22004. * @private
  22005. */
  22006. this._chartsMap = {};
  22007. /**
  22008. * @type {Array.<module:echarts/view/Component>}
  22009. * @private
  22010. */
  22011. this._componentsViews = [];
  22012. /**
  22013. * @type {Object.<string, module:echarts/view/Component>}
  22014. * @private
  22015. */
  22016. this._componentsMap = {};
  22017. /**
  22018. * @type {module:echarts/CoordinateSystem}
  22019. * @private
  22020. */
  22021. this._coordSysMgr = new CoordinateSystemManager();
  22022. /**
  22023. * @type {module:echarts/ExtensionAPI}
  22024. * @private
  22025. */
  22026. var api = this._api = createExtensionAPI(this);
  22027. // Sort on demand
  22028. function prioritySortFunc(a, b) {
  22029. return a.__prio - b.__prio;
  22030. }
  22031. sort(visualFuncs, prioritySortFunc);
  22032. sort(dataProcessorFuncs, prioritySortFunc);
  22033. /**
  22034. * @type {module:echarts/stream/Scheduler}
  22035. */
  22036. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  22037. Eventful.call(this);
  22038. /**
  22039. * @type {module:echarts~MessageCenter}
  22040. * @private
  22041. */
  22042. this._messageCenter = new MessageCenter();
  22043. // Init mouse events
  22044. this._initEvents();
  22045. // In case some people write `window.onresize = chart.resize`
  22046. this.resize = bind(this.resize, this);
  22047. // Can't dispatch action during rendering procedure
  22048. this._pendingActions = [];
  22049. zr.animation.on('frame', this._onframe, this);
  22050. bindRenderedEvent(zr, this);
  22051. // ECharts instance can be used as value.
  22052. setAsPrimitive(this);
  22053. }
  22054. var echartsProto = ECharts.prototype;
  22055. echartsProto._onframe = function () {
  22056. if (this._disposed) {
  22057. return;
  22058. }
  22059. var scheduler = this._scheduler;
  22060. // Lazy update
  22061. if (this[OPTION_UPDATED]) {
  22062. var silent = this[OPTION_UPDATED].silent;
  22063. this[IN_MAIN_PROCESS] = true;
  22064. prepare(this);
  22065. updateMethods.update.call(this);
  22066. this[IN_MAIN_PROCESS] = false;
  22067. this[OPTION_UPDATED] = false;
  22068. flushPendingActions.call(this, silent);
  22069. triggerUpdatedEvent.call(this, silent);
  22070. }
  22071. // Avoid do both lazy update and progress in one frame.
  22072. else if (scheduler.unfinished) {
  22073. // Stream progress.
  22074. var remainTime = TEST_FRAME_REMAIN_TIME;
  22075. var ecModel = this._model;
  22076. var api = this._api;
  22077. scheduler.unfinished = false;
  22078. do {
  22079. var startTime = +new Date();
  22080. scheduler.performSeriesTasks(ecModel);
  22081. // Currently dataProcessorFuncs do not check threshold.
  22082. scheduler.performDataProcessorTasks(ecModel);
  22083. updateStreamModes(this, ecModel);
  22084. // Do not update coordinate system here. Because that coord system update in
  22085. // each frame is not a good user experience. So we follow the rule that
  22086. // the extent of the coordinate system is determin in the first frame (the
  22087. // frame is executed immedietely after task reset.
  22088. // this._coordSysMgr.update(ecModel, api);
  22089. // console.log('--- ec frame visual ---', remainTime);
  22090. scheduler.performVisualTasks(ecModel);
  22091. renderSeries(this, this._model, api, 'remain');
  22092. remainTime -= (+new Date() - startTime);
  22093. }
  22094. while (remainTime > 0 && scheduler.unfinished);
  22095. // Call flush explicitly for trigger finished event.
  22096. if (!scheduler.unfinished) {
  22097. this._zr.flush();
  22098. }
  22099. // Else, zr flushing be ensue within the same frame,
  22100. // because zr flushing is after onframe event.
  22101. }
  22102. };
  22103. /**
  22104. * @return {HTMLElement}
  22105. */
  22106. echartsProto.getDom = function () {
  22107. return this._dom;
  22108. };
  22109. /**
  22110. * @return {module:zrender~ZRender}
  22111. */
  22112. echartsProto.getZr = function () {
  22113. return this._zr;
  22114. };
  22115. /**
  22116. * Usage:
  22117. * chart.setOption(option, notMerge, lazyUpdate);
  22118. * chart.setOption(option, {
  22119. * notMerge: ...,
  22120. * lazyUpdate: ...,
  22121. * silent: ...
  22122. * });
  22123. *
  22124. * @param {Object} option
  22125. * @param {Object|boolean} [opts] opts or notMerge.
  22126. * @param {boolean} [opts.notMerge=false]
  22127. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  22128. */
  22129. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  22130. if (__DEV__) {
  22131. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  22132. }
  22133. var silent;
  22134. if (isObject(notMerge)) {
  22135. lazyUpdate = notMerge.lazyUpdate;
  22136. silent = notMerge.silent;
  22137. notMerge = notMerge.notMerge;
  22138. }
  22139. this[IN_MAIN_PROCESS] = true;
  22140. if (!this._model || notMerge) {
  22141. var optionManager = new OptionManager(this._api);
  22142. var theme$$1 = this._theme;
  22143. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  22144. ecModel.scheduler = this._scheduler;
  22145. ecModel.init(null, null, theme$$1, optionManager);
  22146. }
  22147. this._model.setOption(option, optionPreprocessorFuncs);
  22148. if (lazyUpdate) {
  22149. this[OPTION_UPDATED] = {silent: silent};
  22150. this[IN_MAIN_PROCESS] = false;
  22151. }
  22152. else {
  22153. prepare(this);
  22154. updateMethods.update.call(this);
  22155. // Ensure zr refresh sychronously, and then pixel in canvas can be
  22156. // fetched after `setOption`.
  22157. this._zr.flush();
  22158. this[OPTION_UPDATED] = false;
  22159. this[IN_MAIN_PROCESS] = false;
  22160. flushPendingActions.call(this, silent);
  22161. triggerUpdatedEvent.call(this, silent);
  22162. }
  22163. };
  22164. /**
  22165. * @DEPRECATED
  22166. */
  22167. echartsProto.setTheme = function () {
  22168. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  22169. };
  22170. /**
  22171. * @return {module:echarts/model/Global}
  22172. */
  22173. echartsProto.getModel = function () {
  22174. return this._model;
  22175. };
  22176. /**
  22177. * @return {Object}
  22178. */
  22179. echartsProto.getOption = function () {
  22180. return this._model && this._model.getOption();
  22181. };
  22182. /**
  22183. * @return {number}
  22184. */
  22185. echartsProto.getWidth = function () {
  22186. return this._zr.getWidth();
  22187. };
  22188. /**
  22189. * @return {number}
  22190. */
  22191. echartsProto.getHeight = function () {
  22192. return this._zr.getHeight();
  22193. };
  22194. /**
  22195. * @return {number}
  22196. */
  22197. echartsProto.getDevicePixelRatio = function () {
  22198. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  22199. };
  22200. /**
  22201. * Get canvas which has all thing rendered
  22202. * @param {Object} opts
  22203. * @param {string} [opts.backgroundColor]
  22204. * @return {string}
  22205. */
  22206. echartsProto.getRenderedCanvas = function (opts) {
  22207. if (!env$1.canvasSupported) {
  22208. return;
  22209. }
  22210. opts = opts || {};
  22211. opts.pixelRatio = opts.pixelRatio || 1;
  22212. opts.backgroundColor = opts.backgroundColor
  22213. || this._model.get('backgroundColor');
  22214. var zr = this._zr;
  22215. // var list = zr.storage.getDisplayList();
  22216. // Stop animations
  22217. // Never works before in init animation, so remove it.
  22218. // zrUtil.each(list, function (el) {
  22219. // el.stopAnimation(true);
  22220. // });
  22221. return zr.painter.getRenderedCanvas(opts);
  22222. };
  22223. /**
  22224. * Get svg data url
  22225. * @return {string}
  22226. */
  22227. echartsProto.getSvgDataUrl = function () {
  22228. if (!env$1.svgSupported) {
  22229. return;
  22230. }
  22231. var zr = this._zr;
  22232. var list = zr.storage.getDisplayList();
  22233. // Stop animations
  22234. each$1(list, function (el) {
  22235. el.stopAnimation(true);
  22236. });
  22237. return zr.painter.pathToDataUrl();
  22238. };
  22239. /**
  22240. * @return {string}
  22241. * @param {Object} opts
  22242. * @param {string} [opts.type='png']
  22243. * @param {string} [opts.pixelRatio=1]
  22244. * @param {string} [opts.backgroundColor]
  22245. * @param {string} [opts.excludeComponents]
  22246. */
  22247. echartsProto.getDataURL = function (opts) {
  22248. opts = opts || {};
  22249. var excludeComponents = opts.excludeComponents;
  22250. var ecModel = this._model;
  22251. var excludesComponentViews = [];
  22252. var self = this;
  22253. each(excludeComponents, function (componentType) {
  22254. ecModel.eachComponent({
  22255. mainType: componentType
  22256. }, function (component) {
  22257. var view = self._componentsMap[component.__viewId];
  22258. if (!view.group.ignore) {
  22259. excludesComponentViews.push(view);
  22260. view.group.ignore = true;
  22261. }
  22262. });
  22263. });
  22264. var url = this._zr.painter.getType() === 'svg'
  22265. ? this.getSvgDataUrl()
  22266. : this.getRenderedCanvas(opts).toDataURL(
  22267. 'image/' + (opts && opts.type || 'png')
  22268. );
  22269. each(excludesComponentViews, function (view) {
  22270. view.group.ignore = false;
  22271. });
  22272. return url;
  22273. };
  22274. /**
  22275. * @return {string}
  22276. * @param {Object} opts
  22277. * @param {string} [opts.type='png']
  22278. * @param {string} [opts.pixelRatio=1]
  22279. * @param {string} [opts.backgroundColor]
  22280. */
  22281. echartsProto.getConnectedDataURL = function (opts) {
  22282. if (!env$1.canvasSupported) {
  22283. return;
  22284. }
  22285. var groupId = this.group;
  22286. var mathMin = Math.min;
  22287. var mathMax = Math.max;
  22288. var MAX_NUMBER = Infinity;
  22289. if (connectedGroups[groupId]) {
  22290. var left = MAX_NUMBER;
  22291. var top = MAX_NUMBER;
  22292. var right = -MAX_NUMBER;
  22293. var bottom = -MAX_NUMBER;
  22294. var canvasList = [];
  22295. var dpr = (opts && opts.pixelRatio) || 1;
  22296. each$1(instances, function (chart, id) {
  22297. if (chart.group === groupId) {
  22298. var canvas = chart.getRenderedCanvas(
  22299. clone(opts)
  22300. );
  22301. var boundingRect = chart.getDom().getBoundingClientRect();
  22302. left = mathMin(boundingRect.left, left);
  22303. top = mathMin(boundingRect.top, top);
  22304. right = mathMax(boundingRect.right, right);
  22305. bottom = mathMax(boundingRect.bottom, bottom);
  22306. canvasList.push({
  22307. dom: canvas,
  22308. left: boundingRect.left,
  22309. top: boundingRect.top
  22310. });
  22311. }
  22312. });
  22313. left *= dpr;
  22314. top *= dpr;
  22315. right *= dpr;
  22316. bottom *= dpr;
  22317. var width = right - left;
  22318. var height = bottom - top;
  22319. var targetCanvas = createCanvas();
  22320. targetCanvas.width = width;
  22321. targetCanvas.height = height;
  22322. var zr = init$1(targetCanvas);
  22323. each(canvasList, function (item) {
  22324. var img = new ZImage({
  22325. style: {
  22326. x: item.left * dpr - left,
  22327. y: item.top * dpr - top,
  22328. image: item.dom
  22329. }
  22330. });
  22331. zr.add(img);
  22332. });
  22333. zr.refreshImmediately();
  22334. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  22335. }
  22336. else {
  22337. return this.getDataURL(opts);
  22338. }
  22339. };
  22340. /**
  22341. * Convert from logical coordinate system to pixel coordinate system.
  22342. * See CoordinateSystem#convertToPixel.
  22343. * @param {string|Object} finder
  22344. * If string, e.g., 'geo', means {geoIndex: 0}.
  22345. * If Object, could contain some of these properties below:
  22346. * {
  22347. * seriesIndex / seriesId / seriesName,
  22348. * geoIndex / geoId, geoName,
  22349. * bmapIndex / bmapId / bmapName,
  22350. * xAxisIndex / xAxisId / xAxisName,
  22351. * yAxisIndex / yAxisId / yAxisName,
  22352. * gridIndex / gridId / gridName,
  22353. * ... (can be extended)
  22354. * }
  22355. * @param {Array|number} value
  22356. * @return {Array|number} result
  22357. */
  22358. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  22359. /**
  22360. * Convert from pixel coordinate system to logical coordinate system.
  22361. * See CoordinateSystem#convertFromPixel.
  22362. * @param {string|Object} finder
  22363. * If string, e.g., 'geo', means {geoIndex: 0}.
  22364. * If Object, could contain some of these properties below:
  22365. * {
  22366. * seriesIndex / seriesId / seriesName,
  22367. * geoIndex / geoId / geoName,
  22368. * bmapIndex / bmapId / bmapName,
  22369. * xAxisIndex / xAxisId / xAxisName,
  22370. * yAxisIndex / yAxisId / yAxisName
  22371. * gridIndex / gridId / gridName,
  22372. * ... (can be extended)
  22373. * }
  22374. * @param {Array|number} value
  22375. * @return {Array|number} result
  22376. */
  22377. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  22378. function doConvertPixel(methodName, finder, value) {
  22379. var ecModel = this._model;
  22380. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  22381. var result;
  22382. finder = parseFinder(ecModel, finder);
  22383. for (var i = 0; i < coordSysList.length; i++) {
  22384. var coordSys = coordSysList[i];
  22385. if (coordSys[methodName]
  22386. && (result = coordSys[methodName](ecModel, finder, value)) != null
  22387. ) {
  22388. return result;
  22389. }
  22390. }
  22391. if (__DEV__) {
  22392. console.warn(
  22393. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  22394. );
  22395. }
  22396. }
  22397. /**
  22398. * Is the specified coordinate systems or components contain the given pixel point.
  22399. * @param {string|Object} finder
  22400. * If string, e.g., 'geo', means {geoIndex: 0}.
  22401. * If Object, could contain some of these properties below:
  22402. * {
  22403. * seriesIndex / seriesId / seriesName,
  22404. * geoIndex / geoId / geoName,
  22405. * bmapIndex / bmapId / bmapName,
  22406. * xAxisIndex / xAxisId / xAxisName,
  22407. * yAxisIndex / yAxisId / yAxisName,
  22408. * gridIndex / gridId / gridName,
  22409. * ... (can be extended)
  22410. * }
  22411. * @param {Array|number} value
  22412. * @return {boolean} result
  22413. */
  22414. echartsProto.containPixel = function (finder, value) {
  22415. var ecModel = this._model;
  22416. var result;
  22417. finder = parseFinder(ecModel, finder);
  22418. each$1(finder, function (models, key) {
  22419. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  22420. var coordSys = model.coordinateSystem;
  22421. if (coordSys && coordSys.containPoint) {
  22422. result |= !!coordSys.containPoint(value);
  22423. }
  22424. else if (key === 'seriesModels') {
  22425. var view = this._chartsMap[model.__viewId];
  22426. if (view && view.containPoint) {
  22427. result |= view.containPoint(value, model);
  22428. }
  22429. else {
  22430. if (__DEV__) {
  22431. console.warn(key + ': ' + (view
  22432. ? 'The found component do not support containPoint.'
  22433. : 'No view mapping to the found component.'
  22434. ));
  22435. }
  22436. }
  22437. }
  22438. else {
  22439. if (__DEV__) {
  22440. console.warn(key + ': containPoint is not supported');
  22441. }
  22442. }
  22443. }, this);
  22444. }, this);
  22445. return !!result;
  22446. };
  22447. /**
  22448. * Get visual from series or data.
  22449. * @param {string|Object} finder
  22450. * If string, e.g., 'series', means {seriesIndex: 0}.
  22451. * If Object, could contain some of these properties below:
  22452. * {
  22453. * seriesIndex / seriesId / seriesName,
  22454. * dataIndex / dataIndexInside
  22455. * }
  22456. * If dataIndex is not specified, series visual will be fetched,
  22457. * but not data item visual.
  22458. * If all of seriesIndex, seriesId, seriesName are not specified,
  22459. * visual will be fetched from first series.
  22460. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  22461. */
  22462. echartsProto.getVisual = function (finder, visualType) {
  22463. var ecModel = this._model;
  22464. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  22465. var seriesModel = finder.seriesModel;
  22466. if (__DEV__) {
  22467. if (!seriesModel) {
  22468. console.warn('There is no specified seires model');
  22469. }
  22470. }
  22471. var data = seriesModel.getData();
  22472. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  22473. ? finder.dataIndexInside
  22474. : finder.hasOwnProperty('dataIndex')
  22475. ? data.indexOfRawIndex(finder.dataIndex)
  22476. : null;
  22477. return dataIndexInside != null
  22478. ? data.getItemVisual(dataIndexInside, visualType)
  22479. : data.getVisual(visualType);
  22480. };
  22481. /**
  22482. * Get view of corresponding component model
  22483. * @param {module:echarts/model/Component} componentModel
  22484. * @return {module:echarts/view/Component}
  22485. */
  22486. echartsProto.getViewOfComponentModel = function (componentModel) {
  22487. return this._componentsMap[componentModel.__viewId];
  22488. };
  22489. /**
  22490. * Get view of corresponding series model
  22491. * @param {module:echarts/model/Series} seriesModel
  22492. * @return {module:echarts/view/Chart}
  22493. */
  22494. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  22495. return this._chartsMap[seriesModel.__viewId];
  22496. };
  22497. var updateMethods = {
  22498. prepareAndUpdate: function (payload) {
  22499. prepare(this);
  22500. updateMethods.update.call(this, payload);
  22501. },
  22502. /**
  22503. * @param {Object} payload
  22504. * @private
  22505. */
  22506. update: function (payload) {
  22507. // console.profile && console.profile('update');
  22508. var ecModel = this._model;
  22509. var api = this._api;
  22510. var zr = this._zr;
  22511. var coordSysMgr = this._coordSysMgr;
  22512. var scheduler = this._scheduler;
  22513. // update before setOption
  22514. if (!ecModel) {
  22515. return;
  22516. }
  22517. scheduler.restoreData(ecModel, payload);
  22518. scheduler.performSeriesTasks(ecModel);
  22519. // TODO
  22520. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  22521. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  22522. // Create new coordinate system each update
  22523. // In LineView may save the old coordinate system and use it to get the orignal point
  22524. coordSysMgr.create(ecModel, api);
  22525. scheduler.performDataProcessorTasks(ecModel, payload);
  22526. // Current stream render is not supported in data process. So we can update
  22527. // stream modes after data processing, where the filtered data is used to
  22528. // deteming whether use progressive rendering.
  22529. updateStreamModes(this, ecModel);
  22530. // We update stream modes before coordinate system updated, then the modes info
  22531. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  22532. // the drawback is the full coord info can not be fetched. Fortunately this full
  22533. // coord is not requied in stream mode updater currently.
  22534. coordSysMgr.update(ecModel, api);
  22535. clearColorPalette(ecModel);
  22536. scheduler.performVisualTasks(ecModel, payload);
  22537. render(this, ecModel, api, payload);
  22538. // Set background
  22539. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  22540. // In IE8
  22541. if (!env$1.canvasSupported) {
  22542. var colorArr = parse(backgroundColor);
  22543. backgroundColor = stringify(colorArr, 'rgb');
  22544. if (colorArr[3] === 0) {
  22545. backgroundColor = 'transparent';
  22546. }
  22547. }
  22548. else {
  22549. zr.setBackgroundColor(backgroundColor);
  22550. }
  22551. performPostUpdateFuncs(ecModel, api);
  22552. // console.profile && console.profileEnd('update');
  22553. },
  22554. /**
  22555. * @param {Object} payload
  22556. * @private
  22557. */
  22558. updateTransform: function (payload) {
  22559. var ecModel = this._model;
  22560. var ecIns = this;
  22561. var api = this._api;
  22562. // update before setOption
  22563. if (!ecModel) {
  22564. return;
  22565. }
  22566. // ChartView.markUpdateMethod(payload, 'updateTransform');
  22567. var componentDirtyList = [];
  22568. ecModel.eachComponent(function (componentType, componentModel) {
  22569. var componentView = ecIns.getViewOfComponentModel(componentModel);
  22570. if (componentView && componentView.__alive) {
  22571. if (componentView.updateTransform) {
  22572. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  22573. result && result.update && componentDirtyList.push(componentView);
  22574. }
  22575. else {
  22576. componentDirtyList.push(componentView);
  22577. }
  22578. }
  22579. });
  22580. var seriesDirtyMap = createHashMap();
  22581. ecModel.eachSeries(function (seriesModel) {
  22582. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  22583. if (chartView.updateTransform) {
  22584. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  22585. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  22586. }
  22587. else {
  22588. seriesDirtyMap.set(seriesModel.uid, 1);
  22589. }
  22590. });
  22591. clearColorPalette(ecModel);
  22592. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22593. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  22594. this._scheduler.performVisualTasks(
  22595. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  22596. );
  22597. // Currently, not call render of components. Geo render cost a lot.
  22598. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  22599. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  22600. performPostUpdateFuncs(ecModel, this._api);
  22601. },
  22602. /**
  22603. * @param {Object} payload
  22604. * @private
  22605. */
  22606. updateView: function (payload) {
  22607. var ecModel = this._model;
  22608. // update before setOption
  22609. if (!ecModel) {
  22610. return;
  22611. }
  22612. Chart.markUpdateMethod(payload, 'updateView');
  22613. clearColorPalette(ecModel);
  22614. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22615. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  22616. render(this, this._model, this._api, payload);
  22617. performPostUpdateFuncs(ecModel, this._api);
  22618. },
  22619. /**
  22620. * @param {Object} payload
  22621. * @private
  22622. */
  22623. updateVisual: function (payload) {
  22624. updateMethods.update.call(this, payload);
  22625. // var ecModel = this._model;
  22626. // // update before setOption
  22627. // if (!ecModel) {
  22628. // return;
  22629. // }
  22630. // ChartView.markUpdateMethod(payload, 'updateVisual');
  22631. // clearColorPalette(ecModel);
  22632. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22633. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  22634. // render(this, this._model, this._api, payload);
  22635. // performPostUpdateFuncs(ecModel, this._api);
  22636. },
  22637. /**
  22638. * @param {Object} payload
  22639. * @private
  22640. */
  22641. updateLayout: function (payload) {
  22642. updateMethods.update.call(this, payload);
  22643. // var ecModel = this._model;
  22644. // // update before setOption
  22645. // if (!ecModel) {
  22646. // return;
  22647. // }
  22648. // ChartView.markUpdateMethod(payload, 'updateLayout');
  22649. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22650. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  22651. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  22652. // render(this, this._model, this._api, payload);
  22653. // performPostUpdateFuncs(ecModel, this._api);
  22654. }
  22655. };
  22656. function prepare(ecIns) {
  22657. var ecModel = ecIns._model;
  22658. var scheduler = ecIns._scheduler;
  22659. scheduler.restorePipelines(ecModel);
  22660. scheduler.prepareStageTasks();
  22661. prepareView(ecIns, 'component', ecModel, scheduler);
  22662. prepareView(ecIns, 'chart', ecModel, scheduler);
  22663. scheduler.plan();
  22664. }
  22665. /**
  22666. * @private
  22667. */
  22668. function updateDirectly(ecIns, method, payload, mainType, subType) {
  22669. var ecModel = ecIns._model;
  22670. // broadcast
  22671. if (!mainType) {
  22672. // FIXME
  22673. // Chart will not be update directly here, except set dirty.
  22674. // But there is no such scenario now.
  22675. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  22676. return;
  22677. }
  22678. var query = {};
  22679. query[mainType + 'Id'] = payload[mainType + 'Id'];
  22680. query[mainType + 'Index'] = payload[mainType + 'Index'];
  22681. query[mainType + 'Name'] = payload[mainType + 'Name'];
  22682. var condition = {mainType: mainType, query: query};
  22683. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  22684. var excludeSeriesId = payload.excludeSeriesId;
  22685. if (excludeSeriesId != null) {
  22686. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  22687. }
  22688. // If dispatchAction before setOption, do nothing.
  22689. ecModel && ecModel.eachComponent(condition, function (model) {
  22690. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  22691. callView(ecIns[
  22692. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  22693. ][model.__viewId]);
  22694. }
  22695. }, ecIns);
  22696. function callView(view) {
  22697. view && view.__alive && view[method] && view[method](
  22698. view.__model, ecModel, ecIns._api, payload
  22699. );
  22700. }
  22701. }
  22702. /**
  22703. * Resize the chart
  22704. * @param {Object} opts
  22705. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  22706. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  22707. * @param {boolean} [opts.silent=false]
  22708. */
  22709. echartsProto.resize = function (opts) {
  22710. if (__DEV__) {
  22711. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  22712. }
  22713. this._zr.resize(opts);
  22714. var ecModel = this._model;
  22715. // Resize loading effect
  22716. this._loadingFX && this._loadingFX.resize();
  22717. if (!ecModel) {
  22718. return;
  22719. }
  22720. var optionChanged = ecModel.resetOption('media');
  22721. var silent = opts && opts.silent;
  22722. this[IN_MAIN_PROCESS] = true;
  22723. optionChanged && prepare(this);
  22724. updateMethods.update.call(this);
  22725. this[IN_MAIN_PROCESS] = false;
  22726. flushPendingActions.call(this, silent);
  22727. triggerUpdatedEvent.call(this, silent);
  22728. };
  22729. function updateStreamModes(ecIns, ecModel) {
  22730. var chartsMap = ecIns._chartsMap;
  22731. var scheduler = ecIns._scheduler;
  22732. ecModel.eachSeries(function (seriesModel) {
  22733. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  22734. });
  22735. }
  22736. /**
  22737. * Show loading effect
  22738. * @param {string} [name='default']
  22739. * @param {Object} [cfg]
  22740. */
  22741. echartsProto.showLoading = function (name, cfg) {
  22742. if (isObject(name)) {
  22743. cfg = name;
  22744. name = '';
  22745. }
  22746. name = name || 'default';
  22747. this.hideLoading();
  22748. if (!loadingEffects[name]) {
  22749. if (__DEV__) {
  22750. console.warn('Loading effects ' + name + ' not exists.');
  22751. }
  22752. return;
  22753. }
  22754. var el = loadingEffects[name](this._api, cfg);
  22755. var zr = this._zr;
  22756. this._loadingFX = el;
  22757. zr.add(el);
  22758. };
  22759. /**
  22760. * Hide loading effect
  22761. */
  22762. echartsProto.hideLoading = function () {
  22763. this._loadingFX && this._zr.remove(this._loadingFX);
  22764. this._loadingFX = null;
  22765. };
  22766. /**
  22767. * @param {Object} eventObj
  22768. * @return {Object}
  22769. */
  22770. echartsProto.makeActionFromEvent = function (eventObj) {
  22771. var payload = extend({}, eventObj);
  22772. payload.type = eventActionMap[eventObj.type];
  22773. return payload;
  22774. };
  22775. /**
  22776. * @pubilc
  22777. * @param {Object} payload
  22778. * @param {string} [payload.type] Action type
  22779. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  22780. * @param {boolean} [opt.silent=false] Whether trigger events.
  22781. * @param {boolean} [opt.flush=undefined]
  22782. * true: Flush immediately, and then pixel in canvas can be fetched
  22783. * immediately. Caution: it might affect performance.
  22784. * false: Not not flush.
  22785. * undefined: Auto decide whether perform flush.
  22786. */
  22787. echartsProto.dispatchAction = function (payload, opt) {
  22788. if (!isObject(opt)) {
  22789. opt = {silent: !!opt};
  22790. }
  22791. if (!actions[payload.type]) {
  22792. return;
  22793. }
  22794. // Avoid dispatch action before setOption. Especially in `connect`.
  22795. if (!this._model) {
  22796. return;
  22797. }
  22798. // May dispatchAction in rendering procedure
  22799. if (this[IN_MAIN_PROCESS]) {
  22800. this._pendingActions.push(payload);
  22801. return;
  22802. }
  22803. doDispatchAction.call(this, payload, opt.silent);
  22804. if (opt.flush) {
  22805. this._zr.flush(true);
  22806. }
  22807. else if (opt.flush !== false && env$1.browser.weChat) {
  22808. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  22809. // hang when sliding page (on touch event), which cause that zr does not
  22810. // refresh util user interaction finished, which is not expected.
  22811. // But `dispatchAction` may be called too frequently when pan on touch
  22812. // screen, which impacts performance if do not throttle them.
  22813. this._throttledZrFlush();
  22814. }
  22815. flushPendingActions.call(this, opt.silent);
  22816. triggerUpdatedEvent.call(this, opt.silent);
  22817. };
  22818. function doDispatchAction(payload, silent) {
  22819. var payloadType = payload.type;
  22820. var escapeConnect = payload.escapeConnect;
  22821. var actionWrap = actions[payloadType];
  22822. var actionInfo = actionWrap.actionInfo;
  22823. var cptType = (actionInfo.update || 'update').split(':');
  22824. var updateMethod = cptType.pop();
  22825. cptType = cptType[0] != null && parseClassType(cptType[0]);
  22826. this[IN_MAIN_PROCESS] = true;
  22827. var payloads = [payload];
  22828. var batched = false;
  22829. // Batch action
  22830. if (payload.batch) {
  22831. batched = true;
  22832. payloads = map(payload.batch, function (item) {
  22833. item = defaults(extend({}, item), payload);
  22834. item.batch = null;
  22835. return item;
  22836. });
  22837. }
  22838. var eventObjBatch = [];
  22839. var eventObj;
  22840. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  22841. each(payloads, function (batchItem) {
  22842. // Action can specify the event by return it.
  22843. eventObj = actionWrap.action(batchItem, this._model, this._api);
  22844. // Emit event outside
  22845. eventObj = eventObj || extend({}, batchItem);
  22846. // Convert type to eventType
  22847. eventObj.type = actionInfo.event || eventObj.type;
  22848. eventObjBatch.push(eventObj);
  22849. // light update does not perform data process, layout and visual.
  22850. if (isHighDown) {
  22851. // method, payload, mainType, subType
  22852. updateDirectly(this, updateMethod, batchItem, 'series');
  22853. }
  22854. else if (cptType) {
  22855. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  22856. }
  22857. }, this);
  22858. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  22859. // Still dirty
  22860. if (this[OPTION_UPDATED]) {
  22861. // FIXME Pass payload ?
  22862. prepare(this);
  22863. updateMethods.update.call(this, payload);
  22864. this[OPTION_UPDATED] = false;
  22865. }
  22866. else {
  22867. updateMethods[updateMethod].call(this, payload);
  22868. }
  22869. }
  22870. // Follow the rule of action batch
  22871. if (batched) {
  22872. eventObj = {
  22873. type: actionInfo.event || payloadType,
  22874. escapeConnect: escapeConnect,
  22875. batch: eventObjBatch
  22876. };
  22877. }
  22878. else {
  22879. eventObj = eventObjBatch[0];
  22880. }
  22881. this[IN_MAIN_PROCESS] = false;
  22882. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  22883. }
  22884. function flushPendingActions(silent) {
  22885. var pendingActions = this._pendingActions;
  22886. while (pendingActions.length) {
  22887. var payload = pendingActions.shift();
  22888. doDispatchAction.call(this, payload, silent);
  22889. }
  22890. }
  22891. function triggerUpdatedEvent(silent) {
  22892. !silent && this.trigger('updated');
  22893. }
  22894. /**
  22895. * Event `rendered` is triggered when zr
  22896. * rendered. It is useful for realtime
  22897. * snapshot (reflect animation).
  22898. *
  22899. * Event `finished` is triggered when:
  22900. * (1) zrender rendering finished.
  22901. * (2) initial animation finished.
  22902. * (3) progressive rendering finished.
  22903. * (4) no pending action.
  22904. * (5) no delayed setOption needs to be processed.
  22905. */
  22906. function bindRenderedEvent(zr, ecIns) {
  22907. zr.on('rendered', function () {
  22908. ecIns.trigger('rendered');
  22909. // The `finished` event should not be triggered repeatly,
  22910. // so it should only be triggered when rendering indeed happend
  22911. // in zrender. (Consider the case that dipatchAction is keep
  22912. // triggering when mouse move).
  22913. if (
  22914. // Although zr is dirty if initial animation is not finished
  22915. // and this checking is called on frame, we also check
  22916. // animation finished for robustness.
  22917. zr.animation.isFinished()
  22918. && !ecIns[OPTION_UPDATED]
  22919. && !ecIns._scheduler.unfinished
  22920. && !ecIns._pendingActions.length
  22921. ) {
  22922. ecIns.trigger('finished');
  22923. }
  22924. });
  22925. }
  22926. /**
  22927. * @param {Object} params
  22928. * @param {number} params.seriesIndex
  22929. * @param {Array|TypedArray} params.data
  22930. */
  22931. echartsProto.appendData = function (params) {
  22932. var seriesIndex = params.seriesIndex;
  22933. var ecModel = this.getModel();
  22934. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  22935. if (__DEV__) {
  22936. assert(params.data && seriesModel);
  22937. }
  22938. seriesModel.appendData(params);
  22939. // Note: `appendData` does not support that update extent of coordinate
  22940. // system, util some scenario require that. In the expected usage of
  22941. // `appendData`, the initial extent of coordinate system should better
  22942. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  22943. // the extent changed while `appendData`, the location of the painted
  22944. // graphic elements have to be changed, which make the usage of
  22945. // `appendData` meaningless.
  22946. this._scheduler.unfinished = true;
  22947. };
  22948. /**
  22949. * Register event
  22950. * @method
  22951. */
  22952. echartsProto.on = createRegisterEventWithLowercaseName('on');
  22953. echartsProto.off = createRegisterEventWithLowercaseName('off');
  22954. echartsProto.one = createRegisterEventWithLowercaseName('one');
  22955. /**
  22956. * Prepare view instances of charts and components
  22957. * @param {module:echarts/model/Global} ecModel
  22958. * @private
  22959. */
  22960. function prepareView(ecIns, type, ecModel, scheduler) {
  22961. var isComponent = type === 'component';
  22962. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  22963. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  22964. var zr = ecIns._zr;
  22965. var api = ecIns._api;
  22966. for (var i = 0; i < viewList.length; i++) {
  22967. viewList[i].__alive = false;
  22968. }
  22969. isComponent
  22970. ? ecModel.eachComponent(function (componentType, model) {
  22971. componentType !== 'series' && doPrepare(model);
  22972. })
  22973. : ecModel.eachSeries(doPrepare);
  22974. function doPrepare(model) {
  22975. // Consider: id same and type changed.
  22976. var viewId = '_ec_' + model.id + '_' + model.type;
  22977. var view = viewMap[viewId];
  22978. if (!view) {
  22979. var classType = parseClassType(model.type);
  22980. var Clazz = isComponent
  22981. ? Component.getClass(classType.main, classType.sub)
  22982. : Chart.getClass(classType.sub);
  22983. if (__DEV__) {
  22984. assert(Clazz, classType.sub + ' does not exist.');
  22985. }
  22986. view = new Clazz();
  22987. view.init(ecModel, api);
  22988. viewMap[viewId] = view;
  22989. viewList.push(view);
  22990. zr.add(view.group);
  22991. }
  22992. model.__viewId = view.__id = viewId;
  22993. view.__alive = true;
  22994. view.__model = model;
  22995. view.group.__ecComponentInfo = {
  22996. mainType: model.mainType,
  22997. index: model.componentIndex
  22998. };
  22999. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  23000. }
  23001. for (var i = 0; i < viewList.length;) {
  23002. var view = viewList[i];
  23003. if (!view.__alive) {
  23004. !isComponent && view.renderTask.dispose();
  23005. zr.remove(view.group);
  23006. view.dispose(ecModel, api);
  23007. viewList.splice(i, 1);
  23008. delete viewMap[view.__id];
  23009. view.__id = view.group.__ecComponentInfo = null;
  23010. }
  23011. else {
  23012. i++;
  23013. }
  23014. }
  23015. }
  23016. // /**
  23017. // * Encode visual infomation from data after data processing
  23018. // *
  23019. // * @param {module:echarts/model/Global} ecModel
  23020. // * @param {object} layout
  23021. // * @param {boolean} [layoutFilter] `true`: only layout,
  23022. // * `false`: only not layout,
  23023. // * `null`/`undefined`: all.
  23024. // * @param {string} taskBaseTag
  23025. // * @private
  23026. // */
  23027. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  23028. // each(visualFuncs, function (visual, index) {
  23029. // var isLayout = visual.isLayout;
  23030. // if (layoutFilter == null
  23031. // || (layoutFilter === false && !isLayout)
  23032. // || (layoutFilter === true && isLayout)
  23033. // ) {
  23034. // visual.func(ecModel, api, payload);
  23035. // }
  23036. // });
  23037. // }
  23038. function clearColorPalette(ecModel) {
  23039. ecModel.clearColorPalette();
  23040. ecModel.eachSeries(function (seriesModel) {
  23041. seriesModel.clearColorPalette();
  23042. });
  23043. }
  23044. function render(ecIns, ecModel, api, payload) {
  23045. renderComponents(ecIns, ecModel, api, payload);
  23046. each(ecIns._chartsViews, function (chart) {
  23047. chart.__alive = false;
  23048. });
  23049. renderSeries(ecIns, ecModel, api, payload);
  23050. // Remove groups of unrendered charts
  23051. each(ecIns._chartsViews, function (chart) {
  23052. if (!chart.__alive) {
  23053. chart.remove(ecModel, api);
  23054. }
  23055. });
  23056. }
  23057. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  23058. each(dirtyList || ecIns._componentsViews, function (componentView) {
  23059. var componentModel = componentView.__model;
  23060. componentView.render(componentModel, ecModel, api, payload);
  23061. updateZ(componentModel, componentView);
  23062. });
  23063. }
  23064. /**
  23065. * Render each chart and component
  23066. * @private
  23067. */
  23068. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  23069. // Render all charts
  23070. var scheduler = ecIns._scheduler;
  23071. var unfinished;
  23072. ecModel.eachSeries(function (seriesModel) {
  23073. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23074. chartView.__alive = true;
  23075. var renderTask = chartView.renderTask;
  23076. scheduler.updatePayload(renderTask, payload);
  23077. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  23078. renderTask.dirty();
  23079. }
  23080. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  23081. chartView.group.silent = !!seriesModel.get('silent');
  23082. updateZ(seriesModel, chartView);
  23083. updateBlend(seriesModel, chartView);
  23084. });
  23085. scheduler.unfinished |= unfinished;
  23086. // If use hover layer
  23087. updateHoverLayerStatus(ecIns._zr, ecModel);
  23088. // Add aria
  23089. aria(ecIns._zr.dom, ecModel);
  23090. }
  23091. function performPostUpdateFuncs(ecModel, api) {
  23092. each(postUpdateFuncs, function (func) {
  23093. func(ecModel, api);
  23094. });
  23095. }
  23096. var MOUSE_EVENT_NAMES = [
  23097. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  23098. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  23099. ];
  23100. /**
  23101. * @private
  23102. */
  23103. echartsProto._initEvents = function () {
  23104. each(MOUSE_EVENT_NAMES, function (eveName) {
  23105. this._zr.on(eveName, function (e) {
  23106. var ecModel = this.getModel();
  23107. var el = e.target;
  23108. var params;
  23109. // no e.target when 'globalout'.
  23110. if (eveName === 'globalout') {
  23111. params = {};
  23112. }
  23113. else if (el && el.dataIndex != null) {
  23114. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  23115. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  23116. }
  23117. // If element has custom eventData of components
  23118. else if (el && el.eventData) {
  23119. params = extend({}, el.eventData);
  23120. }
  23121. if (params) {
  23122. params.event = e;
  23123. params.type = eveName;
  23124. this.trigger(eveName, params);
  23125. }
  23126. }, this);
  23127. }, this);
  23128. each(eventActionMap, function (actionType, eventType) {
  23129. this._messageCenter.on(eventType, function (event) {
  23130. this.trigger(eventType, event);
  23131. }, this);
  23132. }, this);
  23133. };
  23134. /**
  23135. * @return {boolean}
  23136. */
  23137. echartsProto.isDisposed = function () {
  23138. return this._disposed;
  23139. };
  23140. /**
  23141. * Clear
  23142. */
  23143. echartsProto.clear = function () {
  23144. this.setOption({ series: [] }, true);
  23145. };
  23146. /**
  23147. * Dispose instance
  23148. */
  23149. echartsProto.dispose = function () {
  23150. if (this._disposed) {
  23151. if (__DEV__) {
  23152. console.warn('Instance ' + this.id + ' has been disposed');
  23153. }
  23154. return;
  23155. }
  23156. this._disposed = true;
  23157. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  23158. var api = this._api;
  23159. var ecModel = this._model;
  23160. each(this._componentsViews, function (component) {
  23161. component.dispose(ecModel, api);
  23162. });
  23163. each(this._chartsViews, function (chart) {
  23164. chart.dispose(ecModel, api);
  23165. });
  23166. // Dispose after all views disposed
  23167. this._zr.dispose();
  23168. delete instances[this.id];
  23169. };
  23170. mixin(ECharts, Eventful);
  23171. function updateHoverLayerStatus(zr, ecModel) {
  23172. var storage = zr.storage;
  23173. var elCount = 0;
  23174. storage.traverse(function (el) {
  23175. if (!el.isGroup) {
  23176. elCount++;
  23177. }
  23178. });
  23179. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  23180. storage.traverse(function (el) {
  23181. if (!el.isGroup) {
  23182. // Don't switch back.
  23183. el.useHoverLayer = true;
  23184. }
  23185. });
  23186. }
  23187. }
  23188. /**
  23189. * Update chart progressive and blend.
  23190. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23191. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23192. */
  23193. function updateBlend(seriesModel, chartView) {
  23194. var blendMode = seriesModel.get('blendMode') || null;
  23195. if (__DEV__) {
  23196. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  23197. console.warn('Only canvas support blendMode');
  23198. }
  23199. }
  23200. chartView.group.traverse(function (el) {
  23201. // FIXME marker and other components
  23202. if (!el.isGroup) {
  23203. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  23204. if (el.style.blend !== blendMode) {
  23205. el.setStyle('blend', blendMode);
  23206. }
  23207. }
  23208. if (el.eachPendingDisplayable) {
  23209. el.eachPendingDisplayable(function (displayable) {
  23210. displayable.setStyle('blend', blendMode);
  23211. });
  23212. }
  23213. });
  23214. }
  23215. /**
  23216. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23217. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23218. */
  23219. function updateZ(model, view) {
  23220. var z = model.get('z');
  23221. var zlevel = model.get('zlevel');
  23222. // Set z and zlevel
  23223. view.group.traverse(function (el) {
  23224. if (el.type !== 'group') {
  23225. z != null && (el.z = z);
  23226. zlevel != null && (el.zlevel = zlevel);
  23227. }
  23228. });
  23229. }
  23230. function createExtensionAPI(ecInstance) {
  23231. var coordSysMgr = ecInstance._coordSysMgr;
  23232. return extend(new ExtensionAPI(ecInstance), {
  23233. // Inject methods
  23234. getCoordinateSystems: bind(
  23235. coordSysMgr.getCoordinateSystems, coordSysMgr
  23236. ),
  23237. getComponentByElement: function (el) {
  23238. while (el) {
  23239. var modelInfo = el.__ecComponentInfo;
  23240. if (modelInfo != null) {
  23241. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  23242. }
  23243. el = el.parent;
  23244. }
  23245. }
  23246. });
  23247. }
  23248. /**
  23249. * @type {Object} key: actionType.
  23250. * @inner
  23251. */
  23252. var actions = {};
  23253. /**
  23254. * Map eventType to actionType
  23255. * @type {Object}
  23256. */
  23257. var eventActionMap = {};
  23258. /**
  23259. * Data processor functions of each stage
  23260. * @type {Array.<Object.<string, Function>>}
  23261. * @inner
  23262. */
  23263. var dataProcessorFuncs = [];
  23264. /**
  23265. * @type {Array.<Function>}
  23266. * @inner
  23267. */
  23268. var optionPreprocessorFuncs = [];
  23269. /**
  23270. * @type {Array.<Function>}
  23271. * @inner
  23272. */
  23273. var postUpdateFuncs = [];
  23274. /**
  23275. * Visual encoding functions of each stage
  23276. * @type {Array.<Object.<string, Function>>}
  23277. */
  23278. var visualFuncs = [];
  23279. /**
  23280. * Theme storage
  23281. * @type {Object.<key, Object>}
  23282. */
  23283. var themeStorage = {};
  23284. /**
  23285. * Loading effects
  23286. */
  23287. var loadingEffects = {};
  23288. var instances = {};
  23289. var connectedGroups = {};
  23290. var idBase = new Date() - 0;
  23291. var groupIdBase = new Date() - 0;
  23292. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  23293. var mapDataStores = {};
  23294. function enableConnect(chart) {
  23295. var STATUS_PENDING = 0;
  23296. var STATUS_UPDATING = 1;
  23297. var STATUS_UPDATED = 2;
  23298. var STATUS_KEY = '__connectUpdateStatus';
  23299. function updateConnectedChartsStatus(charts, status) {
  23300. for (var i = 0; i < charts.length; i++) {
  23301. var otherChart = charts[i];
  23302. otherChart[STATUS_KEY] = status;
  23303. }
  23304. }
  23305. each(eventActionMap, function (actionType, eventType) {
  23306. chart._messageCenter.on(eventType, function (event) {
  23307. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  23308. if (event && event.escapeConnect) {
  23309. return;
  23310. }
  23311. var action = chart.makeActionFromEvent(event);
  23312. var otherCharts = [];
  23313. each(instances, function (otherChart) {
  23314. if (otherChart !== chart && otherChart.group === chart.group) {
  23315. otherCharts.push(otherChart);
  23316. }
  23317. });
  23318. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  23319. each(otherCharts, function (otherChart) {
  23320. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  23321. otherChart.dispatchAction(action);
  23322. }
  23323. });
  23324. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  23325. }
  23326. });
  23327. });
  23328. }
  23329. /**
  23330. * @param {HTMLElement} dom
  23331. * @param {Object} [theme]
  23332. * @param {Object} opts
  23333. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  23334. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  23335. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  23336. * Can be 'auto' (the same as null/undefined)
  23337. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  23338. * Can be 'auto' (the same as null/undefined)
  23339. */
  23340. function init(dom, theme$$1, opts) {
  23341. if (__DEV__) {
  23342. // Check version
  23343. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  23344. throw new Error(
  23345. 'zrender/src ' + version$1
  23346. + ' is too old for ECharts ' + version
  23347. + '. Current version need ZRender '
  23348. + dependencies.zrender + '+'
  23349. );
  23350. }
  23351. if (!dom) {
  23352. throw new Error('Initialize failed: invalid dom.');
  23353. }
  23354. }
  23355. var existInstance = getInstanceByDom(dom);
  23356. if (existInstance) {
  23357. if (__DEV__) {
  23358. console.warn('There is a chart instance already initialized on the dom.');
  23359. }
  23360. return existInstance;
  23361. }
  23362. if (__DEV__) {
  23363. if (isDom(dom)
  23364. && dom.nodeName.toUpperCase() !== 'CANVAS'
  23365. && (
  23366. (!dom.clientWidth && (!opts || opts.width == null))
  23367. || (!dom.clientHeight && (!opts || opts.height == null))
  23368. )
  23369. ) {
  23370. console.warn('Can\'t get dom width or height');
  23371. }
  23372. }
  23373. var chart = new ECharts(dom, theme$$1, opts);
  23374. chart.id = 'ec_' + idBase++;
  23375. instances[chart.id] = chart;
  23376. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  23377. enableConnect(chart);
  23378. return chart;
  23379. }
  23380. /**
  23381. * @return {string|Array.<module:echarts~ECharts>} groupId
  23382. */
  23383. function connect(groupId) {
  23384. // Is array of charts
  23385. if (isArray(groupId)) {
  23386. var charts = groupId;
  23387. groupId = null;
  23388. // If any chart has group
  23389. each(charts, function (chart) {
  23390. if (chart.group != null) {
  23391. groupId = chart.group;
  23392. }
  23393. });
  23394. groupId = groupId || ('g_' + groupIdBase++);
  23395. each(charts, function (chart) {
  23396. chart.group = groupId;
  23397. });
  23398. }
  23399. connectedGroups[groupId] = true;
  23400. return groupId;
  23401. }
  23402. /**
  23403. * @DEPRECATED
  23404. * @return {string} groupId
  23405. */
  23406. function disConnect(groupId) {
  23407. connectedGroups[groupId] = false;
  23408. }
  23409. /**
  23410. * @return {string} groupId
  23411. */
  23412. var disconnect = disConnect;
  23413. /**
  23414. * Dispose a chart instance
  23415. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  23416. */
  23417. function dispose(chart) {
  23418. if (typeof chart === 'string') {
  23419. chart = instances[chart];
  23420. }
  23421. else if (!(chart instanceof ECharts)){
  23422. // Try to treat as dom
  23423. chart = getInstanceByDom(chart);
  23424. }
  23425. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  23426. chart.dispose();
  23427. }
  23428. }
  23429. /**
  23430. * @param {HTMLElement} dom
  23431. * @return {echarts~ECharts}
  23432. */
  23433. function getInstanceByDom(dom) {
  23434. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  23435. }
  23436. /**
  23437. * @param {string} key
  23438. * @return {echarts~ECharts}
  23439. */
  23440. function getInstanceById(key) {
  23441. return instances[key];
  23442. }
  23443. /**
  23444. * Register theme
  23445. */
  23446. function registerTheme(name, theme$$1) {
  23447. themeStorage[name] = theme$$1;
  23448. }
  23449. /**
  23450. * Register option preprocessor
  23451. * @param {Function} preprocessorFunc
  23452. */
  23453. function registerPreprocessor(preprocessorFunc) {
  23454. optionPreprocessorFuncs.push(preprocessorFunc);
  23455. }
  23456. /**
  23457. * @param {number} [priority=1000]
  23458. * @param {Object|Function} processor
  23459. */
  23460. function registerProcessor(priority, processor) {
  23461. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  23462. }
  23463. /**
  23464. * Register postUpdater
  23465. * @param {Function} postUpdateFunc
  23466. */
  23467. function registerPostUpdate(postUpdateFunc) {
  23468. postUpdateFuncs.push(postUpdateFunc);
  23469. }
  23470. /**
  23471. * Usage:
  23472. * registerAction('someAction', 'someEvent', function () { ... });
  23473. * registerAction('someAction', function () { ... });
  23474. * registerAction(
  23475. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  23476. * function () { ... }
  23477. * );
  23478. *
  23479. * @param {(string|Object)} actionInfo
  23480. * @param {string} actionInfo.type
  23481. * @param {string} [actionInfo.event]
  23482. * @param {string} [actionInfo.update]
  23483. * @param {string} [eventName]
  23484. * @param {Function} action
  23485. */
  23486. function registerAction(actionInfo, eventName, action) {
  23487. if (typeof eventName === 'function') {
  23488. action = eventName;
  23489. eventName = '';
  23490. }
  23491. var actionType = isObject(actionInfo)
  23492. ? actionInfo.type
  23493. : ([actionInfo, actionInfo = {
  23494. event: eventName
  23495. }][0]);
  23496. // Event name is all lowercase
  23497. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  23498. eventName = actionInfo.event;
  23499. // Validate action type and event name.
  23500. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  23501. if (!actions[actionType]) {
  23502. actions[actionType] = {action: action, actionInfo: actionInfo};
  23503. }
  23504. eventActionMap[eventName] = actionType;
  23505. }
  23506. /**
  23507. * @param {string} type
  23508. * @param {*} CoordinateSystem
  23509. */
  23510. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  23511. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  23512. }
  23513. /**
  23514. * Get dimensions of specified coordinate system.
  23515. * @param {string} type
  23516. * @return {Array.<string|Object>}
  23517. */
  23518. function getCoordinateSystemDimensions(type) {
  23519. var coordSysCreator = CoordinateSystemManager.get(type);
  23520. if (coordSysCreator) {
  23521. return coordSysCreator.getDimensionsInfo
  23522. ? coordSysCreator.getDimensionsInfo()
  23523. : coordSysCreator.dimensions.slice();
  23524. }
  23525. }
  23526. /**
  23527. * Layout is a special stage of visual encoding
  23528. * Most visual encoding like color are common for different chart
  23529. * But each chart has it's own layout algorithm
  23530. *
  23531. * @param {number} [priority=1000]
  23532. * @param {Function} layoutTask
  23533. */
  23534. function registerLayout(priority, layoutTask) {
  23535. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  23536. }
  23537. /**
  23538. * @param {number} [priority=3000]
  23539. * @param {module:echarts/stream/Task} visualTask
  23540. */
  23541. function registerVisual(priority, visualTask) {
  23542. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  23543. }
  23544. /**
  23545. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  23546. */
  23547. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  23548. if (isFunction(priority) || isObject(priority)) {
  23549. fn = priority;
  23550. priority = defaultPriority;
  23551. }
  23552. if (__DEV__) {
  23553. if (isNaN(priority) || priority == null) {
  23554. throw new Error('Illegal priority');
  23555. }
  23556. // Check duplicate
  23557. each(targetList, function (wrap) {
  23558. assert(wrap.__raw !== fn);
  23559. });
  23560. }
  23561. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  23562. stageHandler.__prio = priority;
  23563. stageHandler.__raw = fn;
  23564. targetList.push(stageHandler);
  23565. return stageHandler;
  23566. }
  23567. /**
  23568. * @param {string} name
  23569. */
  23570. function registerLoading(name, loadingFx) {
  23571. loadingEffects[name] = loadingFx;
  23572. }
  23573. /**
  23574. * @param {Object} opts
  23575. * @param {string} [superClass]
  23576. */
  23577. function extendComponentModel(opts/*, superClass*/) {
  23578. // var Clazz = ComponentModel;
  23579. // if (superClass) {
  23580. // var classType = parseClassType(superClass);
  23581. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  23582. // }
  23583. return ComponentModel.extend(opts);
  23584. }
  23585. /**
  23586. * @param {Object} opts
  23587. * @param {string} [superClass]
  23588. */
  23589. function extendComponentView(opts/*, superClass*/) {
  23590. // var Clazz = ComponentView;
  23591. // if (superClass) {
  23592. // var classType = parseClassType(superClass);
  23593. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  23594. // }
  23595. return Component.extend(opts);
  23596. }
  23597. /**
  23598. * @param {Object} opts
  23599. * @param {string} [superClass]
  23600. */
  23601. function extendSeriesModel(opts/*, superClass*/) {
  23602. // var Clazz = SeriesModel;
  23603. // if (superClass) {
  23604. // superClass = 'series.' + superClass.replace('series.', '');
  23605. // var classType = parseClassType(superClass);
  23606. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  23607. // }
  23608. return SeriesModel.extend(opts);
  23609. }
  23610. /**
  23611. * @param {Object} opts
  23612. * @param {string} [superClass]
  23613. */
  23614. function extendChartView(opts/*, superClass*/) {
  23615. // var Clazz = ChartView;
  23616. // if (superClass) {
  23617. // superClass = superClass.replace('series.', '');
  23618. // var classType = parseClassType(superClass);
  23619. // Clazz = ChartView.getClass(classType.main, true);
  23620. // }
  23621. return Chart.extend(opts);
  23622. }
  23623. /**
  23624. * ZRender need a canvas context to do measureText.
  23625. * But in node environment canvas may be created by node-canvas.
  23626. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  23627. *
  23628. * Be careful of using it in the browser.
  23629. *
  23630. * @param {Function} creator
  23631. * @example
  23632. * var Canvas = require('canvas');
  23633. * var echarts = require('echarts');
  23634. * echarts.setCanvasCreator(function () {
  23635. * // Small size is enough.
  23636. * return new Canvas(32, 32);
  23637. * });
  23638. */
  23639. function setCanvasCreator(creator) {
  23640. $override('createCanvas', creator);
  23641. }
  23642. /**
  23643. * @param {string} mapName
  23644. * @param {Object|string} geoJson
  23645. * @param {Object} [specialAreas]
  23646. *
  23647. * @example
  23648. * $.get('USA.json', function (geoJson) {
  23649. * echarts.registerMap('USA', geoJson);
  23650. * // Or
  23651. * echarts.registerMap('USA', {
  23652. * geoJson: geoJson,
  23653. * specialAreas: {}
  23654. * })
  23655. * });
  23656. */
  23657. function registerMap(mapName, geoJson, specialAreas) {
  23658. if (geoJson.geoJson && !geoJson.features) {
  23659. specialAreas = geoJson.specialAreas;
  23660. geoJson = geoJson.geoJson;
  23661. }
  23662. if (typeof geoJson === 'string') {
  23663. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  23664. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  23665. }
  23666. mapDataStores[mapName] = {
  23667. geoJson: geoJson,
  23668. specialAreas: specialAreas
  23669. };
  23670. }
  23671. /**
  23672. * @param {string} mapName
  23673. * @return {Object}
  23674. */
  23675. function getMap(mapName) {
  23676. return mapDataStores[mapName];
  23677. }
  23678. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  23679. registerPreprocessor(backwardCompat);
  23680. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  23681. registerLoading('default', loadingDefault);
  23682. // Default actions
  23683. registerAction({
  23684. type: 'highlight',
  23685. event: 'highlight',
  23686. update: 'highlight'
  23687. }, noop);
  23688. registerAction({
  23689. type: 'downplay',
  23690. event: 'downplay',
  23691. update: 'downplay'
  23692. }, noop);
  23693. // Default theme
  23694. registerTheme('light', lightTheme);
  23695. registerTheme('dark', theme);
  23696. // For backward compatibility, where the namespace `dataTool` will
  23697. // be mounted on `echarts` is the extension `dataTool` is imported.
  23698. var dataTool = {};
  23699. /*
  23700. * Licensed to the Apache Software Foundation (ASF) under one
  23701. * or more contributor license agreements. See the NOTICE file
  23702. * distributed with this work for additional information
  23703. * regarding copyright ownership. The ASF licenses this file
  23704. * to you under the Apache License, Version 2.0 (the
  23705. * "License"); you may not use this file except in compliance
  23706. * with the License. You may obtain a copy of the License at
  23707. *
  23708. * http://www.apache.org/licenses/LICENSE-2.0
  23709. *
  23710. * Unless required by applicable law or agreed to in writing,
  23711. * software distributed under the License is distributed on an
  23712. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23713. * KIND, either express or implied. See the License for the
  23714. * specific language governing permissions and limitations
  23715. * under the License.
  23716. */
  23717. function defaultKeyGetter(item) {
  23718. return item;
  23719. }
  23720. /**
  23721. * @param {Array} oldArr
  23722. * @param {Array} newArr
  23723. * @param {Function} oldKeyGetter
  23724. * @param {Function} newKeyGetter
  23725. * @param {Object} [context] Can be visited by this.context in callback.
  23726. */
  23727. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  23728. this._old = oldArr;
  23729. this._new = newArr;
  23730. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  23731. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  23732. this.context = context;
  23733. }
  23734. DataDiffer.prototype = {
  23735. constructor: DataDiffer,
  23736. /**
  23737. * Callback function when add a data
  23738. */
  23739. add: function (func) {
  23740. this._add = func;
  23741. return this;
  23742. },
  23743. /**
  23744. * Callback function when update a data
  23745. */
  23746. update: function (func) {
  23747. this._update = func;
  23748. return this;
  23749. },
  23750. /**
  23751. * Callback function when remove a data
  23752. */
  23753. remove: function (func) {
  23754. this._remove = func;
  23755. return this;
  23756. },
  23757. execute: function () {
  23758. var oldArr = this._old;
  23759. var newArr = this._new;
  23760. var oldDataIndexMap = {};
  23761. var newDataIndexMap = {};
  23762. var oldDataKeyArr = [];
  23763. var newDataKeyArr = [];
  23764. var i;
  23765. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  23766. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  23767. // Travel by inverted order to make sure order consistency
  23768. // when duplicate keys exists (consider newDataIndex.pop() below).
  23769. // For performance consideration, these code below do not look neat.
  23770. for (i = 0; i < oldArr.length; i++) {
  23771. var key = oldDataKeyArr[i];
  23772. var idx = newDataIndexMap[key];
  23773. // idx can never be empty array here. see 'set null' logic below.
  23774. if (idx != null) {
  23775. // Consider there is duplicate key (for example, use dataItem.name as key).
  23776. // We should make sure every item in newArr and oldArr can be visited.
  23777. var len = idx.length;
  23778. if (len) {
  23779. len === 1 && (newDataIndexMap[key] = null);
  23780. idx = idx.unshift();
  23781. }
  23782. else {
  23783. newDataIndexMap[key] = null;
  23784. }
  23785. this._update && this._update(idx, i);
  23786. }
  23787. else {
  23788. this._remove && this._remove(i);
  23789. }
  23790. }
  23791. for (var i = 0; i < newDataKeyArr.length; i++) {
  23792. var key = newDataKeyArr[i];
  23793. if (newDataIndexMap.hasOwnProperty(key)) {
  23794. var idx = newDataIndexMap[key];
  23795. if (idx == null) {
  23796. continue;
  23797. }
  23798. // idx can never be empty array here. see 'set null' logic above.
  23799. if (!idx.length) {
  23800. this._add && this._add(idx);
  23801. }
  23802. else {
  23803. for (var j = 0, len = idx.length; j < len; j++) {
  23804. this._add && this._add(idx[j]);
  23805. }
  23806. }
  23807. }
  23808. }
  23809. }
  23810. };
  23811. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  23812. for (var i = 0; i < arr.length; i++) {
  23813. // Add prefix to avoid conflict with Object.prototype.
  23814. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  23815. var existence = map[key];
  23816. if (existence == null) {
  23817. keyArr.push(key);
  23818. map[key] = i;
  23819. }
  23820. else {
  23821. if (!existence.length) {
  23822. map[key] = existence = [existence];
  23823. }
  23824. existence.push(i);
  23825. }
  23826. }
  23827. }
  23828. /*
  23829. * Licensed to the Apache Software Foundation (ASF) under one
  23830. * or more contributor license agreements. See the NOTICE file
  23831. * distributed with this work for additional information
  23832. * regarding copyright ownership. The ASF licenses this file
  23833. * to you under the Apache License, Version 2.0 (the
  23834. * "License"); you may not use this file except in compliance
  23835. * with the License. You may obtain a copy of the License at
  23836. *
  23837. * http://www.apache.org/licenses/LICENSE-2.0
  23838. *
  23839. * Unless required by applicable law or agreed to in writing,
  23840. * software distributed under the License is distributed on an
  23841. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23842. * KIND, either express or implied. See the License for the
  23843. * specific language governing permissions and limitations
  23844. * under the License.
  23845. */
  23846. var OTHER_DIMENSIONS = createHashMap([
  23847. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  23848. ]);
  23849. function summarizeDimensions(data) {
  23850. var summary = {};
  23851. var encode = summary.encode = {};
  23852. var notExtraCoordDimMap = createHashMap();
  23853. var defaultedLabel = [];
  23854. var defaultedTooltip = [];
  23855. each$1(data.dimensions, function (dimName) {
  23856. var dimItem = data.getDimensionInfo(dimName);
  23857. var coordDim = dimItem.coordDim;
  23858. if (coordDim) {
  23859. if (__DEV__) {
  23860. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  23861. }
  23862. var coordDimArr = encode[coordDim];
  23863. if (!encode.hasOwnProperty(coordDim)) {
  23864. coordDimArr = encode[coordDim] = [];
  23865. }
  23866. coordDimArr[dimItem.coordDimIndex] = dimName;
  23867. if (!dimItem.isExtraCoord) {
  23868. notExtraCoordDimMap.set(coordDim, 1);
  23869. // Use the last coord dim (and label friendly) as default label,
  23870. // because when dataset is used, it is hard to guess which dimension
  23871. // can be value dimension. If both show x, y on label is not look good,
  23872. // and conventionally y axis is focused more.
  23873. if (mayLabelDimType(dimItem.type)) {
  23874. defaultedLabel[0] = dimName;
  23875. }
  23876. }
  23877. if (dimItem.defaultTooltip) {
  23878. defaultedTooltip.push(dimName);
  23879. }
  23880. }
  23881. OTHER_DIMENSIONS.each(function (v, otherDim) {
  23882. var otherDimArr = encode[otherDim];
  23883. if (!encode.hasOwnProperty(otherDim)) {
  23884. otherDimArr = encode[otherDim] = [];
  23885. }
  23886. var dimIndex = dimItem.otherDims[otherDim];
  23887. if (dimIndex != null && dimIndex !== false) {
  23888. otherDimArr[dimIndex] = dimItem.name;
  23889. }
  23890. });
  23891. });
  23892. var dataDimsOnCoord = [];
  23893. var encodeFirstDimNotExtra = {};
  23894. notExtraCoordDimMap.each(function (v, coordDim) {
  23895. var dimArr = encode[coordDim];
  23896. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  23897. // But should fix the case that radar axes: simplify the logic
  23898. // of `completeDimension`, remove `extraPrefix`.
  23899. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  23900. // Not necessary to remove duplicate, because a data
  23901. // dim canot on more than one coordDim.
  23902. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  23903. });
  23904. summary.dataDimsOnCoord = dataDimsOnCoord;
  23905. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  23906. var encodeLabel = encode.label;
  23907. // FIXME `encode.label` is not recommanded, because formatter can not be set
  23908. // in this way. Use label.formatter instead. May be remove this approach someday.
  23909. if (encodeLabel && encodeLabel.length) {
  23910. defaultedLabel = encodeLabel.slice();
  23911. }
  23912. var encodeTooltip = encode.tooltip;
  23913. if (encodeTooltip && encodeTooltip.length) {
  23914. defaultedTooltip = encodeTooltip.slice();
  23915. }
  23916. else if (!defaultedTooltip.length) {
  23917. defaultedTooltip = defaultedLabel.slice();
  23918. }
  23919. encode.defaultedLabel = defaultedLabel;
  23920. encode.defaultedTooltip = defaultedTooltip;
  23921. return summary;
  23922. }
  23923. function getDimensionTypeByAxis(axisType) {
  23924. return axisType === 'category'
  23925. ? 'ordinal'
  23926. : axisType === 'time'
  23927. ? 'time'
  23928. : 'float';
  23929. }
  23930. function mayLabelDimType(dimType) {
  23931. // In most cases, ordinal and time do not suitable for label.
  23932. // Ordinal info can be displayed on axis. Time is too long.
  23933. return !(dimType === 'ordinal' || dimType === 'time');
  23934. }
  23935. // function findTheLastDimMayLabel(data) {
  23936. // // Get last value dim
  23937. // var dimensions = data.dimensions.slice();
  23938. // var valueType;
  23939. // var valueDim;
  23940. // while (dimensions.length && (
  23941. // valueDim = dimensions.pop(),
  23942. // valueType = data.getDimensionInfo(valueDim).type,
  23943. // valueType === 'ordinal' || valueType === 'time'
  23944. // )) {} // jshint ignore:line
  23945. // return valueDim;
  23946. // }
  23947. /*
  23948. * Licensed to the Apache Software Foundation (ASF) under one
  23949. * or more contributor license agreements. See the NOTICE file
  23950. * distributed with this work for additional information
  23951. * regarding copyright ownership. The ASF licenses this file
  23952. * to you under the Apache License, Version 2.0 (the
  23953. * "License"); you may not use this file except in compliance
  23954. * with the License. You may obtain a copy of the License at
  23955. *
  23956. * http://www.apache.org/licenses/LICENSE-2.0
  23957. *
  23958. * Unless required by applicable law or agreed to in writing,
  23959. * software distributed under the License is distributed on an
  23960. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23961. * KIND, either express or implied. See the License for the
  23962. * specific language governing permissions and limitations
  23963. * under the License.
  23964. */
  23965. /**
  23966. * List for data storage
  23967. * @module echarts/data/List
  23968. */
  23969. var isObject$4 = isObject$1;
  23970. var UNDEFINED = 'undefined';
  23971. // Use prefix to avoid index to be the same as otherIdList[idx],
  23972. // which will cause weird udpate animation.
  23973. var ID_PREFIX = 'e\0\0';
  23974. var dataCtors = {
  23975. 'float': typeof Float64Array === UNDEFINED
  23976. ? Array : Float64Array,
  23977. 'int': typeof Int32Array === UNDEFINED
  23978. ? Array : Int32Array,
  23979. // Ordinal data type can be string or int
  23980. 'ordinal': Array,
  23981. 'number': Array,
  23982. 'time': Array
  23983. };
  23984. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  23985. // different from the Ctor of typed array.
  23986. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  23987. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  23988. function getIndicesCtor(list) {
  23989. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  23990. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  23991. }
  23992. function cloneChunk(originalChunk) {
  23993. var Ctor = originalChunk.constructor;
  23994. // Only shallow clone is enough when Array.
  23995. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  23996. }
  23997. var TRANSFERABLE_PROPERTIES = [
  23998. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  23999. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  24000. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  24001. ];
  24002. var CLONE_PROPERTIES = [
  24003. '_extent', '_approximateExtent', '_rawExtent'
  24004. ];
  24005. function transferProperties(target, source) {
  24006. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  24007. if (source.hasOwnProperty(propName)) {
  24008. target[propName] = source[propName];
  24009. }
  24010. });
  24011. target.__wrappedMethods = source.__wrappedMethods;
  24012. each$1(CLONE_PROPERTIES, function (propName) {
  24013. target[propName] = clone(source[propName]);
  24014. });
  24015. target._calculationInfo = extend(source._calculationInfo);
  24016. }
  24017. /**
  24018. * @constructor
  24019. * @alias module:echarts/data/List
  24020. *
  24021. * @param {Array.<string|Object>} dimensions
  24022. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  24023. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  24024. * Spetial fields: {
  24025. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  24026. * createInvertedIndices: <boolean>
  24027. * }
  24028. * @param {module:echarts/model/Model} hostModel
  24029. */
  24030. var List = function (dimensions, hostModel) {
  24031. dimensions = dimensions || ['x', 'y'];
  24032. var dimensionInfos = {};
  24033. var dimensionNames = [];
  24034. var invertedIndicesMap = {};
  24035. for (var i = 0; i < dimensions.length; i++) {
  24036. // Use the original dimensions[i], where other flag props may exists.
  24037. var dimensionInfo = dimensions[i];
  24038. if (isString(dimensionInfo)) {
  24039. dimensionInfo = {name: dimensionInfo};
  24040. }
  24041. var dimensionName = dimensionInfo.name;
  24042. dimensionInfo.type = dimensionInfo.type || 'float';
  24043. if (!dimensionInfo.coordDim) {
  24044. dimensionInfo.coordDim = dimensionName;
  24045. dimensionInfo.coordDimIndex = 0;
  24046. }
  24047. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  24048. dimensionNames.push(dimensionName);
  24049. dimensionInfos[dimensionName] = dimensionInfo;
  24050. dimensionInfo.index = i;
  24051. if (dimensionInfo.createInvertedIndices) {
  24052. invertedIndicesMap[dimensionName] = [];
  24053. }
  24054. }
  24055. /**
  24056. * @readOnly
  24057. * @type {Array.<string>}
  24058. */
  24059. this.dimensions = dimensionNames;
  24060. /**
  24061. * Infomation of each data dimension, like data type.
  24062. * @type {Object}
  24063. */
  24064. this._dimensionInfos = dimensionInfos;
  24065. /**
  24066. * @type {module:echarts/model/Model}
  24067. */
  24068. this.hostModel = hostModel;
  24069. /**
  24070. * @type {module:echarts/model/Model}
  24071. */
  24072. this.dataType;
  24073. /**
  24074. * Indices stores the indices of data subset after filtered.
  24075. * This data subset will be used in chart.
  24076. * @type {Array.<number>}
  24077. * @readOnly
  24078. */
  24079. this._indices = null;
  24080. this._count = 0;
  24081. this._rawCount = 0;
  24082. /**
  24083. * Data storage
  24084. * @type {Object.<key, Array.<TypedArray|Array>>}
  24085. * @private
  24086. */
  24087. this._storage = {};
  24088. /**
  24089. * @type {Array.<string>}
  24090. */
  24091. this._nameList = [];
  24092. /**
  24093. * @type {Array.<string>}
  24094. */
  24095. this._idList = [];
  24096. /**
  24097. * Models of data option is stored sparse for optimizing memory cost
  24098. * @type {Array.<module:echarts/model/Model>}
  24099. * @private
  24100. */
  24101. this._optionModels = [];
  24102. /**
  24103. * Global visual properties after visual coding
  24104. * @type {Object}
  24105. * @private
  24106. */
  24107. this._visual = {};
  24108. /**
  24109. * Globel layout properties.
  24110. * @type {Object}
  24111. * @private
  24112. */
  24113. this._layout = {};
  24114. /**
  24115. * Item visual properties after visual coding
  24116. * @type {Array.<Object>}
  24117. * @private
  24118. */
  24119. this._itemVisuals = [];
  24120. /**
  24121. * Key: visual type, Value: boolean
  24122. * @type {Object}
  24123. * @readOnly
  24124. */
  24125. this.hasItemVisual = {};
  24126. /**
  24127. * Item layout properties after layout
  24128. * @type {Array.<Object>}
  24129. * @private
  24130. */
  24131. this._itemLayouts = [];
  24132. /**
  24133. * Graphic elemnents
  24134. * @type {Array.<module:zrender/Element>}
  24135. * @private
  24136. */
  24137. this._graphicEls = [];
  24138. /**
  24139. * Max size of each chunk.
  24140. * @type {number}
  24141. * @private
  24142. */
  24143. this._chunkSize = 1e5;
  24144. /**
  24145. * @type {number}
  24146. * @private
  24147. */
  24148. this._chunkCount = 0;
  24149. /**
  24150. * @type {Array.<Array|Object>}
  24151. * @private
  24152. */
  24153. this._rawData;
  24154. /**
  24155. * Raw extent will not be cloned, but only transfered.
  24156. * It will not be calculated util needed.
  24157. * key: dim,
  24158. * value: {end: number, extent: Array.<number>}
  24159. * @type {Object}
  24160. * @private
  24161. */
  24162. this._rawExtent = {};
  24163. /**
  24164. * @type {Object}
  24165. * @private
  24166. */
  24167. this._extent = {};
  24168. /**
  24169. * key: dim
  24170. * value: extent
  24171. * @type {Object}
  24172. * @private
  24173. */
  24174. this._approximateExtent = {};
  24175. /**
  24176. * Cache summary info for fast visit. See "dimensionHelper".
  24177. * @type {Object}
  24178. * @private
  24179. */
  24180. this._dimensionsSummary = summarizeDimensions(this);
  24181. /**
  24182. * @type {Object.<Array|TypedArray>}
  24183. * @private
  24184. */
  24185. this._invertedIndicesMap = invertedIndicesMap;
  24186. /**
  24187. * @type {Object}
  24188. * @private
  24189. */
  24190. this._calculationInfo = {};
  24191. };
  24192. var listProto = List.prototype;
  24193. listProto.type = 'list';
  24194. /**
  24195. * If each data item has it's own option
  24196. * @type {boolean}
  24197. */
  24198. listProto.hasItemOption = true;
  24199. /**
  24200. * Get dimension name
  24201. * @param {string|number} dim
  24202. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  24203. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  24204. * @return {string} Concrete dim name.
  24205. */
  24206. listProto.getDimension = function (dim) {
  24207. if (!isNaN(dim)) {
  24208. dim = this.dimensions[dim] || dim;
  24209. }
  24210. return dim;
  24211. };
  24212. /**
  24213. * Get type and calculation info of particular dimension
  24214. * @param {string|number} dim
  24215. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  24216. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  24217. */
  24218. listProto.getDimensionInfo = function (dim) {
  24219. // Do not clone, because there may be categories in dimInfo.
  24220. return this._dimensionInfos[this.getDimension(dim)];
  24221. };
  24222. /**
  24223. * @return {Array.<string>} concrete dimension name list on coord.
  24224. */
  24225. listProto.getDimensionsOnCoord = function () {
  24226. return this._dimensionsSummary.dataDimsOnCoord.slice();
  24227. };
  24228. /**
  24229. * @param {string} coordDim
  24230. * @param {number} [idx] A coordDim may map to more than one data dim.
  24231. * If idx is `true`, return a array of all mapped dims.
  24232. * If idx is not specified, return the first dim not extra.
  24233. * @return {string|Array.<string>} concrete data dim.
  24234. * If idx is number, and not found, return null/undefined.
  24235. * If idx is `true`, and not found, return empty array (always return array).
  24236. */
  24237. listProto.mapDimension = function (coordDim, idx) {
  24238. var dimensionsSummary = this._dimensionsSummary;
  24239. if (idx == null) {
  24240. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  24241. }
  24242. var dims = dimensionsSummary.encode[coordDim];
  24243. return idx === true
  24244. // always return array if idx is `true`
  24245. ? (dims || []).slice()
  24246. : (dims && dims[idx]);
  24247. };
  24248. /**
  24249. * Initialize from data
  24250. * @param {Array.<Object|number|Array>} data source or data or data provider.
  24251. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  24252. * defualt label/tooltip.
  24253. * A name can be specified in encode.itemName,
  24254. * or dataItem.name (only for series option data),
  24255. * or provided in nameList from outside.
  24256. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  24257. */
  24258. listProto.initData = function (data, nameList, dimValueGetter) {
  24259. var notProvider = Source.isInstance(data) || isArrayLike(data);
  24260. if (notProvider) {
  24261. data = new DefaultDataProvider(data, this.dimensions.length);
  24262. }
  24263. if (__DEV__) {
  24264. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  24265. throw new Error('Inavlid data provider.');
  24266. }
  24267. }
  24268. this._rawData = data;
  24269. // Clear
  24270. this._storage = {};
  24271. this._indices = null;
  24272. this._nameList = nameList || [];
  24273. this._idList = [];
  24274. this._nameRepeatCount = {};
  24275. if (!dimValueGetter) {
  24276. this.hasItemOption = false;
  24277. }
  24278. /**
  24279. * @readOnly
  24280. */
  24281. this.defaultDimValueGetter = defaultDimValueGetters[
  24282. this._rawData.getSource().sourceFormat
  24283. ];
  24284. // Default dim value getter
  24285. this._dimValueGetter = dimValueGetter = dimValueGetter
  24286. || this.defaultDimValueGetter;
  24287. // Reset raw extent.
  24288. this._rawExtent = {};
  24289. this._initDataFromProvider(0, data.count());
  24290. // If data has no item option.
  24291. if (data.pure) {
  24292. this.hasItemOption = false;
  24293. }
  24294. };
  24295. listProto.getProvider = function () {
  24296. return this._rawData;
  24297. };
  24298. listProto.appendData = function (data) {
  24299. if (__DEV__) {
  24300. assert$1(!this._indices, 'appendData can only be called on raw data.');
  24301. }
  24302. var rawData = this._rawData;
  24303. var start = this.count();
  24304. rawData.appendData(data);
  24305. var end = rawData.count();
  24306. if (!rawData.persistent) {
  24307. end += start;
  24308. }
  24309. this._initDataFromProvider(start, end);
  24310. };
  24311. listProto._initDataFromProvider = function (start, end) {
  24312. // Optimize.
  24313. if (start >= end) {
  24314. return;
  24315. }
  24316. var chunkSize = this._chunkSize;
  24317. var rawData = this._rawData;
  24318. var storage = this._storage;
  24319. var dimensions = this.dimensions;
  24320. var dimLen = dimensions.length;
  24321. var dimensionInfoMap = this._dimensionInfos;
  24322. var nameList = this._nameList;
  24323. var idList = this._idList;
  24324. var rawExtent = this._rawExtent;
  24325. var nameRepeatCount = this._nameRepeatCount = {};
  24326. var nameDimIdx;
  24327. var chunkCount = this._chunkCount;
  24328. var lastChunkIndex = chunkCount - 1;
  24329. for (var i = 0; i < dimLen; i++) {
  24330. var dim = dimensions[i];
  24331. if (!rawExtent[dim]) {
  24332. rawExtent[dim] = getInitialExtent();
  24333. }
  24334. var dimInfo = dimensionInfoMap[dim];
  24335. if (dimInfo.otherDims.itemName === 0) {
  24336. nameDimIdx = this._nameDimIdx = i;
  24337. }
  24338. if (dimInfo.otherDims.itemId === 0) {
  24339. this._idDimIdx = i;
  24340. }
  24341. var DataCtor = dataCtors[dimInfo.type];
  24342. if (!storage[dim]) {
  24343. storage[dim] = [];
  24344. }
  24345. var resizeChunkArray = storage[dim][lastChunkIndex];
  24346. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  24347. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  24348. // The cost of the copy is probably inconsiderable
  24349. // within the initial chunkSize.
  24350. for (var j = 0; j < resizeChunkArray.length; j++) {
  24351. newStore[j] = resizeChunkArray[j];
  24352. }
  24353. storage[dim][lastChunkIndex] = newStore;
  24354. }
  24355. // Create new chunks.
  24356. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  24357. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  24358. }
  24359. this._chunkCount = storage[dim].length;
  24360. }
  24361. var dataItem = new Array(dimLen);
  24362. for (var idx = start; idx < end; idx++) {
  24363. // NOTICE: Try not to write things into dataItem
  24364. dataItem = rawData.getItem(idx, dataItem);
  24365. // Each data item is value
  24366. // [1, 2]
  24367. // 2
  24368. // Bar chart, line chart which uses category axis
  24369. // only gives the 'y' value. 'x' value is the indices of category
  24370. // Use a tempValue to normalize the value to be a (x, y) value
  24371. var chunkIndex = Math.floor(idx / chunkSize);
  24372. var chunkOffset = idx % chunkSize;
  24373. // Store the data by dimensions
  24374. for (var k = 0; k < dimLen; k++) {
  24375. var dim = dimensions[k];
  24376. var dimStorage = storage[dim][chunkIndex];
  24377. // PENDING NULL is empty or zero
  24378. var val = this._dimValueGetter(dataItem, dim, idx, k);
  24379. dimStorage[chunkOffset] = val;
  24380. var dimRawExtent = rawExtent[dim];
  24381. if (val < dimRawExtent[0]) {
  24382. dimRawExtent[0] = val;
  24383. }
  24384. if (val > dimRawExtent[1]) {
  24385. dimRawExtent[1] = val;
  24386. }
  24387. }
  24388. // ??? FIXME not check by pure but sourceFormat?
  24389. // TODO refactor these logic.
  24390. if (!rawData.pure) {
  24391. var name = nameList[idx];
  24392. if (dataItem && name == null) {
  24393. // If dataItem is {name: ...}, it has highest priority.
  24394. // That is appropriate for many common cases.
  24395. if (dataItem.name != null) {
  24396. // There is no other place to persistent dataItem.name,
  24397. // so save it to nameList.
  24398. nameList[idx] = name = dataItem.name;
  24399. }
  24400. else if (nameDimIdx != null) {
  24401. var nameDim = dimensions[nameDimIdx];
  24402. var nameDimChunk = storage[nameDim][chunkIndex];
  24403. if (nameDimChunk) {
  24404. name = nameDimChunk[chunkOffset];
  24405. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  24406. if (ordinalMeta && ordinalMeta.categories.length) {
  24407. name = ordinalMeta.categories[name];
  24408. }
  24409. }
  24410. }
  24411. }
  24412. // Try using the id in option
  24413. // id or name is used on dynamical data, mapping old and new items.
  24414. var id = dataItem == null ? null : dataItem.id;
  24415. if (id == null && name != null) {
  24416. // Use name as id and add counter to avoid same name
  24417. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  24418. id = name;
  24419. if (nameRepeatCount[name] > 0) {
  24420. id += '__ec__' + nameRepeatCount[name];
  24421. }
  24422. nameRepeatCount[name]++;
  24423. }
  24424. id != null && (idList[idx] = id);
  24425. }
  24426. }
  24427. if (!rawData.persistent && rawData.clean) {
  24428. // Clean unused data if data source is typed array.
  24429. rawData.clean();
  24430. }
  24431. this._rawCount = this._count = end;
  24432. // Reset data extent
  24433. this._extent = {};
  24434. prepareInvertedIndex(this);
  24435. };
  24436. function prepareInvertedIndex(list) {
  24437. var invertedIndicesMap = list._invertedIndicesMap;
  24438. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  24439. var dimInfo = list._dimensionInfos[dim];
  24440. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  24441. var ordinalMeta = dimInfo.ordinalMeta;
  24442. if (ordinalMeta) {
  24443. invertedIndices = invertedIndicesMap[dim] = new CtorUint32Array(
  24444. ordinalMeta.categories.length
  24445. );
  24446. // The default value of TypedArray is 0. To avoid miss
  24447. // mapping to 0, we should set it as NaN.
  24448. for (var i = 0; i < invertedIndices.length; i++) {
  24449. invertedIndices[i] = NaN;
  24450. }
  24451. for (var i = 0; i < list._count; i++) {
  24452. // Only support the case that all values are distinct.
  24453. invertedIndices[list.get(dim, i)] = i;
  24454. }
  24455. }
  24456. });
  24457. }
  24458. function getRawValueFromStore(list, dimIndex, rawIndex) {
  24459. var val;
  24460. if (dimIndex != null) {
  24461. var chunkSize = list._chunkSize;
  24462. var chunkIndex = Math.floor(rawIndex / chunkSize);
  24463. var chunkOffset = rawIndex % chunkSize;
  24464. var dim = list.dimensions[dimIndex];
  24465. var chunk = list._storage[dim][chunkIndex];
  24466. if (chunk) {
  24467. val = chunk[chunkOffset];
  24468. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  24469. if (ordinalMeta && ordinalMeta.categories.length) {
  24470. val = ordinalMeta.categories[val];
  24471. }
  24472. }
  24473. }
  24474. return val;
  24475. }
  24476. /**
  24477. * @return {number}
  24478. */
  24479. listProto.count = function () {
  24480. return this._count;
  24481. };
  24482. listProto.getIndices = function () {
  24483. var newIndices;
  24484. var indices = this._indices;
  24485. if (indices) {
  24486. var Ctor = indices.constructor;
  24487. var thisCount = this._count;
  24488. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  24489. if (Ctor === Array) {
  24490. newIndices = new Ctor(thisCount);
  24491. for (var i = 0; i < thisCount; i++) {
  24492. newIndices[i] = indices[i];
  24493. }
  24494. }
  24495. else {
  24496. newIndices = new Ctor(indices.buffer, 0, thisCount);
  24497. }
  24498. }
  24499. else {
  24500. var Ctor = getIndicesCtor(this);
  24501. var newIndices = new Ctor(this.count());
  24502. for (var i = 0; i < newIndices.length; i++) {
  24503. newIndices[i] = i;
  24504. }
  24505. }
  24506. return newIndices;
  24507. };
  24508. /**
  24509. * Get value. Return NaN if idx is out of range.
  24510. * @param {string} dim Dim must be concrete name.
  24511. * @param {number} idx
  24512. * @param {boolean} stack
  24513. * @return {number}
  24514. */
  24515. listProto.get = function (dim, idx /*, stack */) {
  24516. if (!(idx >= 0 && idx < this._count)) {
  24517. return NaN;
  24518. }
  24519. var storage = this._storage;
  24520. if (!storage[dim]) {
  24521. // TODO Warn ?
  24522. return NaN;
  24523. }
  24524. idx = this.getRawIndex(idx);
  24525. var chunkIndex = Math.floor(idx / this._chunkSize);
  24526. var chunkOffset = idx % this._chunkSize;
  24527. var chunkStore = storage[dim][chunkIndex];
  24528. var value = chunkStore[chunkOffset];
  24529. // FIXME ordinal data type is not stackable
  24530. // if (stack) {
  24531. // var dimensionInfo = this._dimensionInfos[dim];
  24532. // if (dimensionInfo && dimensionInfo.stackable) {
  24533. // var stackedOn = this.stackedOn;
  24534. // while (stackedOn) {
  24535. // // Get no stacked data of stacked on
  24536. // var stackedValue = stackedOn.get(dim, idx);
  24537. // // Considering positive stack, negative stack and empty data
  24538. // if ((value >= 0 && stackedValue > 0) // Positive stack
  24539. // || (value <= 0 && stackedValue < 0) // Negative stack
  24540. // ) {
  24541. // value += stackedValue;
  24542. // }
  24543. // stackedOn = stackedOn.stackedOn;
  24544. // }
  24545. // }
  24546. // }
  24547. return value;
  24548. };
  24549. /**
  24550. * @param {string} dim concrete dim
  24551. * @param {number} rawIndex
  24552. * @return {number|string}
  24553. */
  24554. listProto.getByRawIndex = function (dim, rawIdx) {
  24555. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  24556. return NaN;
  24557. }
  24558. var dimStore = this._storage[dim];
  24559. if (!dimStore) {
  24560. // TODO Warn ?
  24561. return NaN;
  24562. }
  24563. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  24564. var chunkOffset = rawIdx % this._chunkSize;
  24565. var chunkStore = dimStore[chunkIndex];
  24566. return chunkStore[chunkOffset];
  24567. };
  24568. /**
  24569. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  24570. * Hack a much simpler _getFast
  24571. * @private
  24572. */
  24573. listProto._getFast = function (dim, rawIdx) {
  24574. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  24575. var chunkOffset = rawIdx % this._chunkSize;
  24576. var chunkStore = this._storage[dim][chunkIndex];
  24577. return chunkStore[chunkOffset];
  24578. };
  24579. /**
  24580. * Get value for multi dimensions.
  24581. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  24582. * @param {number} idx
  24583. * @return {number}
  24584. */
  24585. listProto.getValues = function (dimensions, idx /*, stack */) {
  24586. var values = [];
  24587. if (!isArray(dimensions)) {
  24588. // stack = idx;
  24589. idx = dimensions;
  24590. dimensions = this.dimensions;
  24591. }
  24592. for (var i = 0, len = dimensions.length; i < len; i++) {
  24593. values.push(this.get(dimensions[i], idx /*, stack */));
  24594. }
  24595. return values;
  24596. };
  24597. /**
  24598. * If value is NaN. Inlcuding '-'
  24599. * Only check the coord dimensions.
  24600. * @param {string} dim
  24601. * @param {number} idx
  24602. * @return {number}
  24603. */
  24604. listProto.hasValue = function (idx) {
  24605. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  24606. var dimensionInfos = this._dimensionInfos;
  24607. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  24608. if (
  24609. // Ordinal type can be string or number
  24610. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  24611. // FIXME check ordinal when using index?
  24612. && isNaN(this.get(dataDimsOnCoord[i], idx))
  24613. ) {
  24614. return false;
  24615. }
  24616. }
  24617. return true;
  24618. };
  24619. /**
  24620. * Get extent of data in one dimension
  24621. * @param {string} dim
  24622. * @param {boolean} stack
  24623. */
  24624. listProto.getDataExtent = function (dim /*, stack */) {
  24625. // Make sure use concrete dim as cache name.
  24626. dim = this.getDimension(dim);
  24627. var dimData = this._storage[dim];
  24628. var initialExtent = getInitialExtent();
  24629. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  24630. if (!dimData) {
  24631. return initialExtent;
  24632. }
  24633. // Make more strict checkings to ensure hitting cache.
  24634. var currEnd = this.count();
  24635. // var cacheName = [dim, !!stack].join('_');
  24636. // var cacheName = dim;
  24637. // Consider the most cases when using data zoom, `getDataExtent`
  24638. // happened before filtering. We cache raw extent, which is not
  24639. // necessary to be cleared and recalculated when restore data.
  24640. var useRaw = !this._indices; // && !stack;
  24641. var dimExtent;
  24642. if (useRaw) {
  24643. return this._rawExtent[dim].slice();
  24644. }
  24645. dimExtent = this._extent[dim];
  24646. if (dimExtent) {
  24647. return dimExtent.slice();
  24648. }
  24649. dimExtent = initialExtent;
  24650. var min = dimExtent[0];
  24651. var max = dimExtent[1];
  24652. for (var i = 0; i < currEnd; i++) {
  24653. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  24654. var value = this._getFast(dim, this.getRawIndex(i));
  24655. value < min && (min = value);
  24656. value > max && (max = value);
  24657. }
  24658. dimExtent = [min, max];
  24659. this._extent[dim] = dimExtent;
  24660. return dimExtent;
  24661. };
  24662. /**
  24663. * Optimize for the scenario that data is filtered by a given extent.
  24664. * Consider that if data amount is more than hundreds of thousand,
  24665. * extent calculation will cost more than 10ms and the cache will
  24666. * be erased because of the filtering.
  24667. */
  24668. listProto.getApproximateExtent = function (dim /*, stack */) {
  24669. dim = this.getDimension(dim);
  24670. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  24671. };
  24672. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  24673. dim = this.getDimension(dim);
  24674. this._approximateExtent[dim] = extent.slice();
  24675. };
  24676. /**
  24677. * @param {string} key
  24678. * @return {*}
  24679. */
  24680. listProto.getCalculationInfo = function (key) {
  24681. return this._calculationInfo[key];
  24682. };
  24683. /**
  24684. * @param {string|Object} key or k-v object
  24685. * @param {*} [value]
  24686. */
  24687. listProto.setCalculationInfo = function (key, value) {
  24688. isObject$4(key)
  24689. ? extend(this._calculationInfo, key)
  24690. : (this._calculationInfo[key] = value);
  24691. };
  24692. /**
  24693. * Get sum of data in one dimension
  24694. * @param {string} dim
  24695. */
  24696. listProto.getSum = function (dim /*, stack */) {
  24697. var dimData = this._storage[dim];
  24698. var sum = 0;
  24699. if (dimData) {
  24700. for (var i = 0, len = this.count(); i < len; i++) {
  24701. var value = this.get(dim, i /*, stack */);
  24702. if (!isNaN(value)) {
  24703. sum += value;
  24704. }
  24705. }
  24706. }
  24707. return sum;
  24708. };
  24709. /**
  24710. * Get median of data in one dimension
  24711. * @param {string} dim
  24712. */
  24713. listProto.getMedian = function (dim /*, stack */) {
  24714. var dimDataArray = [];
  24715. // map all data of one dimension
  24716. this.each(dim, function (val, idx) {
  24717. if (!isNaN(val)) {
  24718. dimDataArray.push(val);
  24719. }
  24720. });
  24721. // TODO
  24722. // Use quick select?
  24723. // immutability & sort
  24724. var sortedDimDataArray = [].concat(dimDataArray).sort(function(a, b) {
  24725. return a - b;
  24726. });
  24727. var len = this.count();
  24728. // calculate median
  24729. return len === 0 ? 0 :
  24730. len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] :
  24731. (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  24732. };
  24733. // /**
  24734. // * Retreive the index with given value
  24735. // * @param {string} dim Concrete dimension.
  24736. // * @param {number} value
  24737. // * @return {number}
  24738. // */
  24739. // Currently incorrect: should return dataIndex but not rawIndex.
  24740. // Do not fix it until this method is to be used somewhere.
  24741. // FIXME Precision of float value
  24742. // listProto.indexOf = function (dim, value) {
  24743. // var storage = this._storage;
  24744. // var dimData = storage[dim];
  24745. // var chunkSize = this._chunkSize;
  24746. // if (dimData) {
  24747. // for (var i = 0, len = this.count(); i < len; i++) {
  24748. // var chunkIndex = Math.floor(i / chunkSize);
  24749. // var chunkOffset = i % chunkSize;
  24750. // if (dimData[chunkIndex][chunkOffset] === value) {
  24751. // return i;
  24752. // }
  24753. // }
  24754. // }
  24755. // return -1;
  24756. // };
  24757. /**
  24758. * Only support the dimension which inverted index created.
  24759. * Do not support other cases until required.
  24760. * @param {string} concrete dim
  24761. * @param {number|string} value
  24762. * @return {number} rawIndex
  24763. */
  24764. listProto.rawIndexOf = function (dim, value) {
  24765. var invertedIndices = dim && this._invertedIndicesMap[dim];
  24766. if (__DEV__) {
  24767. if (!invertedIndices) {
  24768. throw new Error('Do not supported yet');
  24769. }
  24770. }
  24771. var rawIndex = invertedIndices[value];
  24772. if (rawIndex == null || isNaN(rawIndex)) {
  24773. return -1;
  24774. }
  24775. return rawIndex;
  24776. };
  24777. /**
  24778. * Retreive the index with given name
  24779. * @param {number} idx
  24780. * @param {number} name
  24781. * @return {number}
  24782. */
  24783. listProto.indexOfName = function (name) {
  24784. for (var i = 0, len = this.count(); i < len; i++) {
  24785. if (this.getName(i) === name) {
  24786. return i;
  24787. }
  24788. }
  24789. return -1;
  24790. };
  24791. /**
  24792. * Retreive the index with given raw data index
  24793. * @param {number} idx
  24794. * @param {number} name
  24795. * @return {number}
  24796. */
  24797. listProto.indexOfRawIndex = function (rawIndex) {
  24798. if (!this._indices) {
  24799. return rawIndex;
  24800. }
  24801. if (rawIndex >= this._rawCount || rawIndex < 0) {
  24802. return -1;
  24803. }
  24804. // Indices are ascending
  24805. var indices = this._indices;
  24806. // If rawIndex === dataIndex
  24807. var rawDataIndex = indices[rawIndex];
  24808. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  24809. return rawIndex;
  24810. }
  24811. var left = 0;
  24812. var right = this._count - 1;
  24813. while (left <= right) {
  24814. var mid = (left + right) / 2 | 0;
  24815. if (indices[mid] < rawIndex) {
  24816. left = mid + 1;
  24817. }
  24818. else if (indices[mid] > rawIndex) {
  24819. right = mid - 1;
  24820. }
  24821. else {
  24822. return mid;
  24823. }
  24824. }
  24825. return -1;
  24826. };
  24827. /**
  24828. * Retreive the index of nearest value
  24829. * @param {string} dim
  24830. * @param {number} value
  24831. * @param {number} [maxDistance=Infinity]
  24832. * @return {Array.<number>} Considere multiple points has the same value.
  24833. */
  24834. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  24835. var storage = this._storage;
  24836. var dimData = storage[dim];
  24837. var nearestIndices = [];
  24838. if (!dimData) {
  24839. return nearestIndices;
  24840. }
  24841. if (maxDistance == null) {
  24842. maxDistance = Infinity;
  24843. }
  24844. var minDist = Number.MAX_VALUE;
  24845. var minDiff = -1;
  24846. for (var i = 0, len = this.count(); i < len; i++) {
  24847. var diff = value - this.get(dim, i /*, stack */);
  24848. var dist = Math.abs(diff);
  24849. if (diff <= maxDistance && dist <= minDist) {
  24850. // For the case of two data are same on xAxis, which has sequence data.
  24851. // Show the nearest index
  24852. // https://github.com/ecomfe/echarts/issues/2869
  24853. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  24854. minDist = dist;
  24855. minDiff = diff;
  24856. nearestIndices.length = 0;
  24857. }
  24858. nearestIndices.push(i);
  24859. }
  24860. }
  24861. return nearestIndices;
  24862. };
  24863. /**
  24864. * Get raw data index
  24865. * @param {number} idx
  24866. * @return {number}
  24867. */
  24868. listProto.getRawIndex = getRawIndexWithoutIndices;
  24869. function getRawIndexWithoutIndices(idx) {
  24870. return idx;
  24871. }
  24872. function getRawIndexWithIndices(idx) {
  24873. if (idx < this._count && idx >= 0) {
  24874. return this._indices[idx];
  24875. }
  24876. return -1;
  24877. }
  24878. /**
  24879. * Get raw data item
  24880. * @param {number} idx
  24881. * @return {number}
  24882. */
  24883. listProto.getRawDataItem = function (idx) {
  24884. if (!this._rawData.persistent) {
  24885. var val = [];
  24886. for (var i = 0; i < this.dimensions.length; i++) {
  24887. var dim = this.dimensions[i];
  24888. val.push(this.get(dim, idx));
  24889. }
  24890. return val;
  24891. }
  24892. else {
  24893. return this._rawData.getItem(this.getRawIndex(idx));
  24894. }
  24895. };
  24896. /**
  24897. * @param {number} idx
  24898. * @param {boolean} [notDefaultIdx=false]
  24899. * @return {string}
  24900. */
  24901. listProto.getName = function (idx) {
  24902. var rawIndex = this.getRawIndex(idx);
  24903. return this._nameList[rawIndex]
  24904. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  24905. || '';
  24906. };
  24907. /**
  24908. * @param {number} idx
  24909. * @param {boolean} [notDefaultIdx=false]
  24910. * @return {string}
  24911. */
  24912. listProto.getId = function (idx) {
  24913. return getId(this, this.getRawIndex(idx));
  24914. };
  24915. function getId(list, rawIndex) {
  24916. var id = list._idList[rawIndex];
  24917. if (id == null) {
  24918. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  24919. }
  24920. if (id == null) {
  24921. // FIXME Check the usage in graph, should not use prefix.
  24922. id = ID_PREFIX + rawIndex;
  24923. }
  24924. return id;
  24925. }
  24926. function normalizeDimensions(dimensions) {
  24927. if (!isArray(dimensions)) {
  24928. dimensions = [dimensions];
  24929. }
  24930. return dimensions;
  24931. }
  24932. function validateDimensions(list, dims) {
  24933. for (var i = 0; i < dims.length; i++) {
  24934. // stroage may be empty when no data, so use
  24935. // dimensionInfos to check.
  24936. if (!list._dimensionInfos[dims[i]]) {
  24937. console.error('Unkown dimension ' + dims[i]);
  24938. }
  24939. }
  24940. }
  24941. /**
  24942. * Data iteration
  24943. * @param {string|Array.<string>}
  24944. * @param {Function} cb
  24945. * @param {*} [context=this]
  24946. *
  24947. * @example
  24948. * list.each('x', function (x, idx) {});
  24949. * list.each(['x', 'y'], function (x, y, idx) {});
  24950. * list.each(function (idx) {})
  24951. */
  24952. listProto.each = function (dims, cb, context, contextCompat) {
  24953. 'use strict';
  24954. if (!this._count) {
  24955. return;
  24956. }
  24957. if (typeof dims === 'function') {
  24958. contextCompat = context;
  24959. context = cb;
  24960. cb = dims;
  24961. dims = [];
  24962. }
  24963. // contextCompat just for compat echarts3
  24964. context = context || contextCompat || this;
  24965. dims = map(normalizeDimensions(dims), this.getDimension, this);
  24966. if (__DEV__) {
  24967. validateDimensions(this, dims);
  24968. }
  24969. var dimSize = dims.length;
  24970. for (var i = 0; i < this.count(); i++) {
  24971. // Simple optimization
  24972. switch (dimSize) {
  24973. case 0:
  24974. cb.call(context, i);
  24975. break;
  24976. case 1:
  24977. cb.call(context, this.get(dims[0], i), i);
  24978. break;
  24979. case 2:
  24980. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  24981. break;
  24982. default:
  24983. var k = 0;
  24984. var value = [];
  24985. for (; k < dimSize; k++) {
  24986. value[k] = this.get(dims[k], i);
  24987. }
  24988. // Index
  24989. value[k] = i;
  24990. cb.apply(context, value);
  24991. }
  24992. }
  24993. };
  24994. /**
  24995. * Data filter
  24996. * @param {string|Array.<string>}
  24997. * @param {Function} cb
  24998. * @param {*} [context=this]
  24999. */
  25000. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  25001. 'use strict';
  25002. if (!this._count) {
  25003. return;
  25004. }
  25005. if (typeof dimensions === 'function') {
  25006. contextCompat = context;
  25007. context = cb;
  25008. cb = dimensions;
  25009. dimensions = [];
  25010. }
  25011. // contextCompat just for compat echarts3
  25012. context = context || contextCompat || this;
  25013. dimensions = map(
  25014. normalizeDimensions(dimensions), this.getDimension, this
  25015. );
  25016. if (__DEV__) {
  25017. validateDimensions(this, dimensions);
  25018. }
  25019. var count = this.count();
  25020. var Ctor = getIndicesCtor(this);
  25021. var newIndices = new Ctor(count);
  25022. var value = [];
  25023. var dimSize = dimensions.length;
  25024. var offset = 0;
  25025. var dim0 = dimensions[0];
  25026. for (var i = 0; i < count; i++) {
  25027. var keep;
  25028. var rawIdx = this.getRawIndex(i);
  25029. // Simple optimization
  25030. if (dimSize === 0) {
  25031. keep = cb.call(context, i);
  25032. }
  25033. else if (dimSize === 1) {
  25034. var val = this._getFast(dim0, rawIdx);
  25035. keep = cb.call(context, val, i);
  25036. }
  25037. else {
  25038. for (var k = 0; k < dimSize; k++) {
  25039. value[k] = this._getFast(dim0, rawIdx);
  25040. }
  25041. value[k] = i;
  25042. keep = cb.apply(context, value);
  25043. }
  25044. if (keep) {
  25045. newIndices[offset++] = rawIdx;
  25046. }
  25047. }
  25048. // Set indices after filtered.
  25049. if (offset < count) {
  25050. this._indices = newIndices;
  25051. }
  25052. this._count = offset;
  25053. // Reset data extent
  25054. this._extent = {};
  25055. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25056. return this;
  25057. };
  25058. /**
  25059. * Select data in range. (For optimization of filter)
  25060. * (Manually inline code, support 5 million data filtering in data zoom.)
  25061. */
  25062. listProto.selectRange = function (range) {
  25063. 'use strict';
  25064. if (!this._count) {
  25065. return;
  25066. }
  25067. var dimensions = [];
  25068. for (var dim in range) {
  25069. if (range.hasOwnProperty(dim)) {
  25070. dimensions.push(dim);
  25071. }
  25072. }
  25073. if (__DEV__) {
  25074. validateDimensions(this, dimensions);
  25075. }
  25076. var dimSize = dimensions.length;
  25077. if (!dimSize) {
  25078. return;
  25079. }
  25080. var originalCount = this.count();
  25081. var Ctor = getIndicesCtor(this);
  25082. var newIndices = new Ctor(originalCount);
  25083. var offset = 0;
  25084. var dim0 = dimensions[0];
  25085. var min = range[dim0][0];
  25086. var max = range[dim0][1];
  25087. var quickFinished = false;
  25088. if (!this._indices) {
  25089. // Extreme optimization for common case. About 2x faster in chrome.
  25090. var idx = 0;
  25091. if (dimSize === 1) {
  25092. var dimStorage = this._storage[dimensions[0]];
  25093. for (var k = 0; k < this._chunkCount; k++) {
  25094. var chunkStorage = dimStorage[k];
  25095. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25096. for (var i = 0; i < len; i++) {
  25097. var val = chunkStorage[i];
  25098. // NaN will not be filtered. Consider the case, in line chart, empty
  25099. // value indicates the line should be broken. But for the case like
  25100. // scatter plot, a data item with empty value will not be rendered,
  25101. // but the axis extent may be effected if some other dim of the data
  25102. // item has value. Fortunately it is not a significant negative effect.
  25103. if (
  25104. (val >= min && val <= max) || isNaN(val)
  25105. ) {
  25106. newIndices[offset++] = idx;
  25107. }
  25108. idx++;
  25109. }
  25110. }
  25111. quickFinished = true;
  25112. }
  25113. else if (dimSize === 2) {
  25114. var dimStorage = this._storage[dim0];
  25115. var dimStorage2 = this._storage[dimensions[1]];
  25116. var min2 = range[dimensions[1]][0];
  25117. var max2 = range[dimensions[1]][1];
  25118. for (var k = 0; k < this._chunkCount; k++) {
  25119. var chunkStorage = dimStorage[k];
  25120. var chunkStorage2= dimStorage2[k];
  25121. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25122. for (var i = 0; i < len; i++) {
  25123. var val = chunkStorage[i];
  25124. var val2 = chunkStorage2[i];
  25125. // Do not filter NaN, see comment above.
  25126. if ((
  25127. (val >= min && val <= max) || isNaN(val)
  25128. )
  25129. && (
  25130. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  25131. )
  25132. ) {
  25133. newIndices[offset++] = idx;
  25134. }
  25135. idx++;
  25136. }
  25137. }
  25138. quickFinished = true;
  25139. }
  25140. }
  25141. if (!quickFinished) {
  25142. if (dimSize === 1) {
  25143. for (var i = 0; i < originalCount; i++) {
  25144. var rawIndex = this.getRawIndex(i);
  25145. var val = this._getFast(dim0, rawIndex);
  25146. // Do not filter NaN, see comment above.
  25147. if (
  25148. (val >= min && val <= max) || isNaN(val)
  25149. ) {
  25150. newIndices[offset++] = rawIndex;
  25151. }
  25152. }
  25153. }
  25154. else {
  25155. for (var i = 0; i < originalCount; i++) {
  25156. var keep = true;
  25157. var rawIndex = this.getRawIndex(i);
  25158. for (var k = 0; k < dimSize; k++) {
  25159. var dimk = dimensions[k];
  25160. var val = this._getFast(dim, rawIndex);
  25161. // Do not filter NaN, see comment above.
  25162. if (val < range[dimk][0] || val > range[dimk][1]) {
  25163. keep = false;
  25164. }
  25165. }
  25166. if (keep) {
  25167. newIndices[offset++] = this.getRawIndex(i);
  25168. }
  25169. }
  25170. }
  25171. }
  25172. // Set indices after filtered.
  25173. if (offset < originalCount) {
  25174. this._indices = newIndices;
  25175. }
  25176. this._count = offset;
  25177. // Reset data extent
  25178. this._extent = {};
  25179. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25180. return this;
  25181. };
  25182. /**
  25183. * Data mapping to a plain array
  25184. * @param {string|Array.<string>} [dimensions]
  25185. * @param {Function} cb
  25186. * @param {*} [context=this]
  25187. * @return {Array}
  25188. */
  25189. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  25190. 'use strict';
  25191. if (typeof dimensions === 'function') {
  25192. contextCompat = context;
  25193. context = cb;
  25194. cb = dimensions;
  25195. dimensions = [];
  25196. }
  25197. // contextCompat just for compat echarts3
  25198. context = context || contextCompat || this;
  25199. var result = [];
  25200. this.each(dimensions, function () {
  25201. result.push(cb && cb.apply(this, arguments));
  25202. }, context);
  25203. return result;
  25204. };
  25205. // Data in excludeDimensions is copied, otherwise transfered.
  25206. function cloneListForMapAndSample(original, excludeDimensions) {
  25207. var allDimensions = original.dimensions;
  25208. var list = new List(
  25209. map(allDimensions, original.getDimensionInfo, original),
  25210. original.hostModel
  25211. );
  25212. // FIXME If needs stackedOn, value may already been stacked
  25213. transferProperties(list, original);
  25214. var storage = list._storage = {};
  25215. var originalStorage = original._storage;
  25216. // Init storage
  25217. for (var i = 0; i < allDimensions.length; i++) {
  25218. var dim = allDimensions[i];
  25219. if (originalStorage[dim]) {
  25220. // Notice that we do not reset invertedIndicesMap here, becuase
  25221. // there is no scenario of mapping or sampling ordinal dimension.
  25222. if (indexOf(excludeDimensions, dim) >= 0) {
  25223. storage[dim] = cloneDimStore(originalStorage[dim]);
  25224. list._rawExtent[dim] = getInitialExtent();
  25225. list._extent[dim] = null;
  25226. }
  25227. else {
  25228. // Direct reference for other dimensions
  25229. storage[dim] = originalStorage[dim];
  25230. }
  25231. }
  25232. }
  25233. return list;
  25234. }
  25235. function cloneDimStore(originalDimStore) {
  25236. var newDimStore = new Array(originalDimStore.length);
  25237. for (var j = 0; j < originalDimStore.length; j++) {
  25238. newDimStore[j] = cloneChunk(originalDimStore[j]);
  25239. }
  25240. return newDimStore;
  25241. }
  25242. function getInitialExtent() {
  25243. return [Infinity, -Infinity];
  25244. }
  25245. /**
  25246. * Data mapping to a new List with given dimensions
  25247. * @param {string|Array.<string>} dimensions
  25248. * @param {Function} cb
  25249. * @param {*} [context=this]
  25250. * @return {Array}
  25251. */
  25252. listProto.map = function (dimensions, cb, context, contextCompat) {
  25253. 'use strict';
  25254. // contextCompat just for compat echarts3
  25255. context = context || contextCompat || this;
  25256. dimensions = map(
  25257. normalizeDimensions(dimensions), this.getDimension, this
  25258. );
  25259. if (__DEV__) {
  25260. validateDimensions(this, dimensions);
  25261. }
  25262. var list = cloneListForMapAndSample(this, dimensions);
  25263. // Following properties are all immutable.
  25264. // So we can reference to the same value
  25265. list._indices = this._indices;
  25266. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25267. var storage = list._storage;
  25268. var tmpRetValue = [];
  25269. var chunkSize = this._chunkSize;
  25270. var dimSize = dimensions.length;
  25271. var dataCount = this.count();
  25272. var values = [];
  25273. var rawExtent = list._rawExtent;
  25274. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  25275. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  25276. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  25277. }
  25278. values[dimSize] = dataIndex;
  25279. var retValue = cb && cb.apply(context, values);
  25280. if (retValue != null) {
  25281. // a number or string (in oridinal dimension)?
  25282. if (typeof retValue !== 'object') {
  25283. tmpRetValue[0] = retValue;
  25284. retValue = tmpRetValue;
  25285. }
  25286. var rawIndex = this.getRawIndex(dataIndex);
  25287. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25288. var chunkOffset = rawIndex % chunkSize;
  25289. for (var i = 0; i < retValue.length; i++) {
  25290. var dim = dimensions[i];
  25291. var val = retValue[i];
  25292. var rawExtentOnDim = rawExtent[dim];
  25293. var dimStore = storage[dim];
  25294. if (dimStore) {
  25295. dimStore[chunkIndex][chunkOffset] = val;
  25296. }
  25297. if (val < rawExtentOnDim[0]) {
  25298. rawExtentOnDim[0] = val;
  25299. }
  25300. if (val > rawExtentOnDim[1]) {
  25301. rawExtentOnDim[1] = val;
  25302. }
  25303. }
  25304. }
  25305. }
  25306. return list;
  25307. };
  25308. /**
  25309. * Large data down sampling on given dimension
  25310. * @param {string} dimension
  25311. * @param {number} rate
  25312. * @param {Function} sampleValue
  25313. * @param {Function} sampleIndex Sample index for name and id
  25314. */
  25315. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  25316. var list = cloneListForMapAndSample(this, [dimension]);
  25317. var targetStorage = list._storage;
  25318. var frameValues = [];
  25319. var frameSize = Math.floor(1 / rate);
  25320. var dimStore = targetStorage[dimension];
  25321. var len = this.count();
  25322. var chunkSize = this._chunkSize;
  25323. var rawExtentOnDim = list._rawExtent[dimension];
  25324. var newIndices = new (getIndicesCtor(this))(len);
  25325. var offset = 0;
  25326. for (var i = 0; i < len; i += frameSize) {
  25327. // Last frame
  25328. if (frameSize > len - i) {
  25329. frameSize = len - i;
  25330. frameValues.length = frameSize;
  25331. }
  25332. for (var k = 0; k < frameSize; k++) {
  25333. var dataIdx = this.getRawIndex(i + k);
  25334. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  25335. var originalChunkOffset = dataIdx % chunkSize;
  25336. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  25337. }
  25338. var value = sampleValue(frameValues);
  25339. var sampleFrameIdx = this.getRawIndex(
  25340. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  25341. );
  25342. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  25343. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  25344. // Only write value on the filtered data
  25345. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  25346. if (value < rawExtentOnDim[0]) {
  25347. rawExtentOnDim[0] = value;
  25348. }
  25349. if (value > rawExtentOnDim[1]) {
  25350. rawExtentOnDim[1] = value;
  25351. }
  25352. newIndices[offset++] = sampleFrameIdx;
  25353. }
  25354. list._count = offset;
  25355. list._indices = newIndices;
  25356. list.getRawIndex = getRawIndexWithIndices;
  25357. return list;
  25358. };
  25359. /**
  25360. * Get model of one data item.
  25361. *
  25362. * @param {number} idx
  25363. */
  25364. // FIXME Model proxy ?
  25365. listProto.getItemModel = function (idx) {
  25366. var hostModel = this.hostModel;
  25367. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  25368. };
  25369. /**
  25370. * Create a data differ
  25371. * @param {module:echarts/data/List} otherList
  25372. * @return {module:echarts/data/DataDiffer}
  25373. */
  25374. listProto.diff = function (otherList) {
  25375. var thisList = this;
  25376. return new DataDiffer(
  25377. otherList ? otherList.getIndices() : [],
  25378. this.getIndices(),
  25379. function (idx) {
  25380. return getId(otherList, idx);
  25381. },
  25382. function (idx) {
  25383. return getId(thisList, idx);
  25384. }
  25385. );
  25386. };
  25387. /**
  25388. * Get visual property.
  25389. * @param {string} key
  25390. */
  25391. listProto.getVisual = function (key) {
  25392. var visual = this._visual;
  25393. return visual && visual[key];
  25394. };
  25395. /**
  25396. * Set visual property
  25397. * @param {string|Object} key
  25398. * @param {*} [value]
  25399. *
  25400. * @example
  25401. * setVisual('color', color);
  25402. * setVisual({
  25403. * 'color': color
  25404. * });
  25405. */
  25406. listProto.setVisual = function (key, val) {
  25407. if (isObject$4(key)) {
  25408. for (var name in key) {
  25409. if (key.hasOwnProperty(name)) {
  25410. this.setVisual(name, key[name]);
  25411. }
  25412. }
  25413. return;
  25414. }
  25415. this._visual = this._visual || {};
  25416. this._visual[key] = val;
  25417. };
  25418. /**
  25419. * Set layout property.
  25420. * @param {string|Object} key
  25421. * @param {*} [val]
  25422. */
  25423. listProto.setLayout = function (key, val) {
  25424. if (isObject$4(key)) {
  25425. for (var name in key) {
  25426. if (key.hasOwnProperty(name)) {
  25427. this.setLayout(name, key[name]);
  25428. }
  25429. }
  25430. return;
  25431. }
  25432. this._layout[key] = val;
  25433. };
  25434. /**
  25435. * Get layout property.
  25436. * @param {string} key.
  25437. * @return {*}
  25438. */
  25439. listProto.getLayout = function (key) {
  25440. return this._layout[key];
  25441. };
  25442. /**
  25443. * Get layout of single data item
  25444. * @param {number} idx
  25445. */
  25446. listProto.getItemLayout = function (idx) {
  25447. return this._itemLayouts[idx];
  25448. };
  25449. /**
  25450. * Set layout of single data item
  25451. * @param {number} idx
  25452. * @param {Object} layout
  25453. * @param {boolean=} [merge=false]
  25454. */
  25455. listProto.setItemLayout = function (idx, layout, merge$$1) {
  25456. this._itemLayouts[idx] = merge$$1
  25457. ? extend(this._itemLayouts[idx] || {}, layout)
  25458. : layout;
  25459. };
  25460. /**
  25461. * Clear all layout of single data item
  25462. */
  25463. listProto.clearItemLayouts = function () {
  25464. this._itemLayouts.length = 0;
  25465. };
  25466. /**
  25467. * Get visual property of single data item
  25468. * @param {number} idx
  25469. * @param {string} key
  25470. * @param {boolean} [ignoreParent=false]
  25471. */
  25472. listProto.getItemVisual = function (idx, key, ignoreParent) {
  25473. var itemVisual = this._itemVisuals[idx];
  25474. var val = itemVisual && itemVisual[key];
  25475. if (val == null && !ignoreParent) {
  25476. // Use global visual property
  25477. return this.getVisual(key);
  25478. }
  25479. return val;
  25480. };
  25481. /**
  25482. * Set visual property of single data item
  25483. *
  25484. * @param {number} idx
  25485. * @param {string|Object} key
  25486. * @param {*} [value]
  25487. *
  25488. * @example
  25489. * setItemVisual(0, 'color', color);
  25490. * setItemVisual(0, {
  25491. * 'color': color
  25492. * });
  25493. */
  25494. listProto.setItemVisual = function (idx, key, value) {
  25495. var itemVisual = this._itemVisuals[idx] || {};
  25496. var hasItemVisual = this.hasItemVisual;
  25497. this._itemVisuals[idx] = itemVisual;
  25498. if (isObject$4(key)) {
  25499. for (var name in key) {
  25500. if (key.hasOwnProperty(name)) {
  25501. itemVisual[name] = key[name];
  25502. hasItemVisual[name] = true;
  25503. }
  25504. }
  25505. return;
  25506. }
  25507. itemVisual[key] = value;
  25508. hasItemVisual[key] = true;
  25509. };
  25510. /**
  25511. * Clear itemVisuals and list visual.
  25512. */
  25513. listProto.clearAllVisual = function () {
  25514. this._visual = {};
  25515. this._itemVisuals = [];
  25516. this.hasItemVisual = {};
  25517. };
  25518. var setItemDataAndSeriesIndex = function (child) {
  25519. child.seriesIndex = this.seriesIndex;
  25520. child.dataIndex = this.dataIndex;
  25521. child.dataType = this.dataType;
  25522. };
  25523. /**
  25524. * Set graphic element relative to data. It can be set as null
  25525. * @param {number} idx
  25526. * @param {module:zrender/Element} [el]
  25527. */
  25528. listProto.setItemGraphicEl = function (idx, el) {
  25529. var hostModel = this.hostModel;
  25530. if (el) {
  25531. // Add data index and series index for indexing the data by element
  25532. // Useful in tooltip
  25533. el.dataIndex = idx;
  25534. el.dataType = this.dataType;
  25535. el.seriesIndex = hostModel && hostModel.seriesIndex;
  25536. if (el.type === 'group') {
  25537. el.traverse(setItemDataAndSeriesIndex, el);
  25538. }
  25539. }
  25540. this._graphicEls[idx] = el;
  25541. };
  25542. /**
  25543. * @param {number} idx
  25544. * @return {module:zrender/Element}
  25545. */
  25546. listProto.getItemGraphicEl = function (idx) {
  25547. return this._graphicEls[idx];
  25548. };
  25549. /**
  25550. * @param {Function} cb
  25551. * @param {*} context
  25552. */
  25553. listProto.eachItemGraphicEl = function (cb, context) {
  25554. each$1(this._graphicEls, function (el, idx) {
  25555. if (el) {
  25556. cb && cb.call(context, el, idx);
  25557. }
  25558. });
  25559. };
  25560. /**
  25561. * Shallow clone a new list except visual and layout properties, and graph elements.
  25562. * New list only change the indices.
  25563. */
  25564. listProto.cloneShallow = function (list) {
  25565. if (!list) {
  25566. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  25567. list = new List(dimensionInfoList, this.hostModel);
  25568. }
  25569. // FIXME
  25570. list._storage = this._storage;
  25571. transferProperties(list, this);
  25572. // Clone will not change the data extent and indices
  25573. if (this._indices) {
  25574. var Ctor = this._indices.constructor;
  25575. list._indices = new Ctor(this._indices);
  25576. }
  25577. else {
  25578. list._indices = null;
  25579. }
  25580. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25581. return list;
  25582. };
  25583. /**
  25584. * Wrap some method to add more feature
  25585. * @param {string} methodName
  25586. * @param {Function} injectFunction
  25587. */
  25588. listProto.wrapMethod = function (methodName, injectFunction) {
  25589. var originalMethod = this[methodName];
  25590. if (typeof originalMethod !== 'function') {
  25591. return;
  25592. }
  25593. this.__wrappedMethods = this.__wrappedMethods || [];
  25594. this.__wrappedMethods.push(methodName);
  25595. this[methodName] = function () {
  25596. var res = originalMethod.apply(this, arguments);
  25597. return injectFunction.apply(this, [res].concat(slice(arguments)));
  25598. };
  25599. };
  25600. // Methods that create a new list based on this list should be listed here.
  25601. // Notice that those method should `RETURN` the new list.
  25602. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  25603. // Methods that change indices of this list should be listed here.
  25604. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  25605. /*
  25606. * Licensed to the Apache Software Foundation (ASF) under one
  25607. * or more contributor license agreements. See the NOTICE file
  25608. * distributed with this work for additional information
  25609. * regarding copyright ownership. The ASF licenses this file
  25610. * to you under the Apache License, Version 2.0 (the
  25611. * "License"); you may not use this file except in compliance
  25612. * with the License. You may obtain a copy of the License at
  25613. *
  25614. * http://www.apache.org/licenses/LICENSE-2.0
  25615. *
  25616. * Unless required by applicable law or agreed to in writing,
  25617. * software distributed under the License is distributed on an
  25618. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25619. * KIND, either express or implied. See the License for the
  25620. * specific language governing permissions and limitations
  25621. * under the License.
  25622. */
  25623. /**
  25624. * @deprecated
  25625. * Use `echarts/data/helper/createDimensions` instead.
  25626. */
  25627. /**
  25628. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  25629. *
  25630. * Complete the dimensions array, by user defined `dimension` and `encode`,
  25631. * and guessing from the data structure.
  25632. * If no 'value' dimension specified, the first no-named dimension will be
  25633. * named as 'value'.
  25634. *
  25635. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  25636. * provides not only dim template, but also default order.
  25637. * properties: 'name', 'type', 'displayName'.
  25638. * `name` of each item provides default coord name.
  25639. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  25640. * provide dims count that the sysDim required.
  25641. * [{ordinalMeta}] can be specified.
  25642. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  25643. * @param {Object} [opt]
  25644. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  25645. * For example: ['asdf', {name, type}, ...].
  25646. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  25647. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  25648. * If not specified, extra dim names will be:
  25649. * 'value', 'value0', 'value1', ...
  25650. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  25651. * If `generateCoordCount` specified, the generated dim names will be:
  25652. * `generateCoord` + 0, `generateCoord` + 1, ...
  25653. * can be Infinity, indicate that use all of the remain columns.
  25654. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  25655. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  25656. * @return {Array.<Object>} [{
  25657. * name: string mandatory,
  25658. * displayName: string, the origin name in dimsDef, see source helper.
  25659. * If displayName given, the tooltip will displayed vertically.
  25660. * coordDim: string mandatory,
  25661. * coordDimIndex: number mandatory,
  25662. * type: string optional,
  25663. * otherDims: { never null/undefined
  25664. * tooltip: number optional,
  25665. * label: number optional,
  25666. * itemName: number optional,
  25667. * seriesName: number optional,
  25668. * },
  25669. * isExtraCoord: boolean true if coord is generated
  25670. * (not specified in encode and not series specified)
  25671. * other props ...
  25672. * }]
  25673. */
  25674. function completeDimensions(sysDims, source, opt) {
  25675. if (!Source.isInstance(source)) {
  25676. source = Source.seriesDataToSource(source);
  25677. }
  25678. opt = opt || {};
  25679. sysDims = (sysDims || []).slice();
  25680. var dimsDef = (opt.dimsDef || []).slice();
  25681. var encodeDef = createHashMap(opt.encodeDef);
  25682. var dataDimNameMap = createHashMap();
  25683. var coordDimNameMap = createHashMap();
  25684. // var valueCandidate;
  25685. var result = [];
  25686. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  25687. // Apply user defined dims (`name` and `type`) and init result.
  25688. for (var i = 0; i < dimCount; i++) {
  25689. var dimDefItem = dimsDef[i] = extend(
  25690. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  25691. );
  25692. var userDimName = dimDefItem.name;
  25693. var resultItem = result[i] = {otherDims: {}};
  25694. // Name will be applied later for avoiding duplication.
  25695. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  25696. // Only if `series.dimensions` is defined in option
  25697. // displayName, will be set, and dimension will be diplayed vertically in
  25698. // tooltip by default.
  25699. resultItem.name = resultItem.displayName = userDimName;
  25700. dataDimNameMap.set(userDimName, i);
  25701. }
  25702. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  25703. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  25704. }
  25705. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  25706. encodeDef.each(function (dataDims, coordDim) {
  25707. dataDims = normalizeToArray(dataDims).slice();
  25708. var validDataDims = encodeDef.set(coordDim, []);
  25709. each$1(dataDims, function (resultDimIdx, idx) {
  25710. // The input resultDimIdx can be dim name or index.
  25711. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  25712. if (resultDimIdx != null && resultDimIdx < dimCount) {
  25713. validDataDims[idx] = resultDimIdx;
  25714. applyDim(result[resultDimIdx], coordDim, idx);
  25715. }
  25716. });
  25717. });
  25718. // Apply templetes and default order from `sysDims`.
  25719. var availDimIdx = 0;
  25720. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  25721. var coordDim;
  25722. var sysDimItem;
  25723. var sysDimItemDimsDef;
  25724. var sysDimItemOtherDims;
  25725. if (isString(sysDimItem)) {
  25726. coordDim = sysDimItem;
  25727. sysDimItem = {};
  25728. }
  25729. else {
  25730. coordDim = sysDimItem.name;
  25731. var ordinalMeta = sysDimItem.ordinalMeta;
  25732. sysDimItem.ordinalMeta = null;
  25733. sysDimItem = clone(sysDimItem);
  25734. sysDimItem.ordinalMeta = ordinalMeta;
  25735. // `coordDimIndex` should not be set directly.
  25736. sysDimItemDimsDef = sysDimItem.dimsDef;
  25737. sysDimItemOtherDims = sysDimItem.otherDims;
  25738. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  25739. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  25740. }
  25741. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  25742. // dimensions provides default dim sequences.
  25743. if (!dataDims.length) {
  25744. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  25745. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  25746. availDimIdx++;
  25747. }
  25748. availDimIdx < result.length && dataDims.push(availDimIdx++);
  25749. }
  25750. }
  25751. // Apply templates.
  25752. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  25753. var resultItem = result[resultDimIdx];
  25754. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  25755. if (resultItem.name == null && sysDimItemDimsDef) {
  25756. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  25757. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  25758. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  25759. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  25760. }
  25761. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  25762. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  25763. });
  25764. });
  25765. function applyDim(resultItem, coordDim, coordDimIndex) {
  25766. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  25767. resultItem.otherDims[coordDim] = coordDimIndex;
  25768. }
  25769. else {
  25770. resultItem.coordDim = coordDim;
  25771. resultItem.coordDimIndex = coordDimIndex;
  25772. coordDimNameMap.set(coordDim, true);
  25773. }
  25774. }
  25775. // Make sure the first extra dim is 'value'.
  25776. var generateCoord = opt.generateCoord;
  25777. var generateCoordCount = opt.generateCoordCount;
  25778. var fromZero = generateCoordCount != null;
  25779. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  25780. var extra = generateCoord || 'value';
  25781. // Set dim `name` and other `coordDim` and other props.
  25782. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  25783. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  25784. var coordDim = resultItem.coordDim;
  25785. if (coordDim == null) {
  25786. resultItem.coordDim = genName(
  25787. extra, coordDimNameMap, fromZero
  25788. );
  25789. resultItem.coordDimIndex = 0;
  25790. if (!generateCoord || generateCoordCount <= 0) {
  25791. resultItem.isExtraCoord = true;
  25792. }
  25793. generateCoordCount--;
  25794. }
  25795. resultItem.name == null && (resultItem.name = genName(
  25796. resultItem.coordDim,
  25797. dataDimNameMap
  25798. ));
  25799. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  25800. resultItem.type = 'ordinal';
  25801. }
  25802. }
  25803. return result;
  25804. }
  25805. // ??? TODO
  25806. // Originally detect dimCount by data[0]. Should we
  25807. // optimize it to only by sysDims and dimensions and encode.
  25808. // So only necessary dims will be initialized.
  25809. // But
  25810. // (1) custom series should be considered. where other dims
  25811. // may be visited.
  25812. // (2) sometimes user need to calcualte bubble size or use visualMap
  25813. // on other dimensions besides coordSys needed.
  25814. // So, dims that is not used by system, should be shared in storage?
  25815. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  25816. // Note that the result dimCount should not small than columns count
  25817. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  25818. var dimCount = Math.max(
  25819. source.dimensionsDetectCount || 1,
  25820. sysDims.length,
  25821. dimsDef.length,
  25822. optDimCount || 0
  25823. );
  25824. each$1(sysDims, function (sysDimItem) {
  25825. var sysDimItemDimsDef = sysDimItem.dimsDef;
  25826. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  25827. });
  25828. return dimCount;
  25829. }
  25830. function genName(name, map$$1, fromZero) {
  25831. if (fromZero || map$$1.get(name) != null) {
  25832. var i = 0;
  25833. while (map$$1.get(name + i) != null) {
  25834. i++;
  25835. }
  25836. name += i;
  25837. }
  25838. map$$1.set(name, true);
  25839. return name;
  25840. }
  25841. /*
  25842. * Licensed to the Apache Software Foundation (ASF) under one
  25843. * or more contributor license agreements. See the NOTICE file
  25844. * distributed with this work for additional information
  25845. * regarding copyright ownership. The ASF licenses this file
  25846. * to you under the Apache License, Version 2.0 (the
  25847. * "License"); you may not use this file except in compliance
  25848. * with the License. You may obtain a copy of the License at
  25849. *
  25850. * http://www.apache.org/licenses/LICENSE-2.0
  25851. *
  25852. * Unless required by applicable law or agreed to in writing,
  25853. * software distributed under the License is distributed on an
  25854. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25855. * KIND, either express or implied. See the License for the
  25856. * specific language governing permissions and limitations
  25857. * under the License.
  25858. */
  25859. /**
  25860. * Substitute `completeDimensions`.
  25861. * `completeDimensions` is to be deprecated.
  25862. */
  25863. /**
  25864. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  25865. * @param {Object|Array} [opt]
  25866. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  25867. * @param {number} [opt.dimensionsCount]
  25868. * @param {string} [opt.generateCoord]
  25869. * @param {string} [opt.generateCoordCount]
  25870. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  25871. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  25872. * @return {Array.<Object>} dimensionsInfo
  25873. */
  25874. var createDimensions = function (source, opt) {
  25875. opt = opt || {};
  25876. return completeDimensions(opt.coordDimensions || [], source, {
  25877. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  25878. encodeDef: opt.encodeDefine || source.encodeDefine,
  25879. dimCount: opt.dimensionsCount,
  25880. generateCoord: opt.generateCoord,
  25881. generateCoordCount: opt.generateCoordCount
  25882. });
  25883. };
  25884. /*
  25885. * Licensed to the Apache Software Foundation (ASF) under one
  25886. * or more contributor license agreements. See the NOTICE file
  25887. * distributed with this work for additional information
  25888. * regarding copyright ownership. The ASF licenses this file
  25889. * to you under the Apache License, Version 2.0 (the
  25890. * "License"); you may not use this file except in compliance
  25891. * with the License. You may obtain a copy of the License at
  25892. *
  25893. * http://www.apache.org/licenses/LICENSE-2.0
  25894. *
  25895. * Unless required by applicable law or agreed to in writing,
  25896. * software distributed under the License is distributed on an
  25897. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25898. * KIND, either express or implied. See the License for the
  25899. * specific language governing permissions and limitations
  25900. * under the License.
  25901. */
  25902. /**
  25903. * Note that it is too complicated to support 3d stack by value
  25904. * (have to create two-dimension inverted index), so in 3d case
  25905. * we just support that stacked by index.
  25906. *
  25907. * @param {module:echarts/model/Series} seriesModel
  25908. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  25909. * The input dimensionInfoList will be modified.
  25910. * @param {Object} [opt]
  25911. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  25912. * @param {boolean} [opt.byIndex=false]
  25913. * @return {Object} calculationInfo
  25914. * {
  25915. * stackedDimension: string
  25916. * stackedByDimension: string
  25917. * isStackedByIndex: boolean
  25918. * stackedOverDimension: string
  25919. * stackResultDimension: string
  25920. * }
  25921. */
  25922. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  25923. opt = opt || {};
  25924. var byIndex = opt.byIndex;
  25925. var stackedCoordDimension = opt.stackedCoordDimension;
  25926. // Compatibal: when `stack` is set as '', do not stack.
  25927. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  25928. var stackedByDimInfo;
  25929. var stackedDimInfo;
  25930. var stackResultDimension;
  25931. var stackedOverDimension;
  25932. each$1(dimensionInfoList, function (dimensionInfo, index) {
  25933. if (isString(dimensionInfo)) {
  25934. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  25935. }
  25936. if (mayStack && !dimensionInfo.isExtraCoord) {
  25937. // Find the first ordinal dimension as the stackedByDimInfo.
  25938. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  25939. stackedByDimInfo = dimensionInfo;
  25940. }
  25941. // Find the first stackable dimension as the stackedDimInfo.
  25942. if (!stackedDimInfo
  25943. && dimensionInfo.type !== 'ordinal'
  25944. && dimensionInfo.type !== 'time'
  25945. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  25946. ) {
  25947. stackedDimInfo = dimensionInfo;
  25948. }
  25949. }
  25950. });
  25951. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  25952. // Compatible with previous design, value axis (time axis) only stack by index.
  25953. // It may make sense if the user provides elaborately constructed data.
  25954. byIndex = true;
  25955. }
  25956. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  25957. // That put stack logic in List is for using conveniently in echarts extensions, but it
  25958. // might not be a good way.
  25959. if (stackedDimInfo) {
  25960. // Use a weird name that not duplicated with other names.
  25961. stackResultDimension = '__\0ecstackresult';
  25962. stackedOverDimension = '__\0ecstackedover';
  25963. // Create inverted index to fast query index by value.
  25964. if (stackedByDimInfo) {
  25965. stackedByDimInfo.createInvertedIndices = true;
  25966. }
  25967. var stackedDimCoordDim = stackedDimInfo.coordDim;
  25968. var stackedDimType = stackedDimInfo.type;
  25969. var stackedDimCoordIndex = 0;
  25970. each$1(dimensionInfoList, function (dimensionInfo) {
  25971. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  25972. stackedDimCoordIndex++;
  25973. }
  25974. });
  25975. dimensionInfoList.push({
  25976. name: stackResultDimension,
  25977. coordDim: stackedDimCoordDim,
  25978. coordDimIndex: stackedDimCoordIndex,
  25979. type: stackedDimType,
  25980. isExtraCoord: true,
  25981. isCalculationCoord: true
  25982. });
  25983. stackedDimCoordIndex++;
  25984. dimensionInfoList.push({
  25985. name: stackedOverDimension,
  25986. // This dimension contains stack base (generally, 0), so do not set it as
  25987. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  25988. coordDim: stackedOverDimension,
  25989. coordDimIndex: stackedDimCoordIndex,
  25990. type: stackedDimType,
  25991. isExtraCoord: true,
  25992. isCalculationCoord: true
  25993. });
  25994. }
  25995. return {
  25996. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  25997. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  25998. isStackedByIndex: byIndex,
  25999. stackedOverDimension: stackedOverDimension,
  26000. stackResultDimension: stackResultDimension
  26001. };
  26002. }
  26003. /**
  26004. * @param {module:echarts/data/List} data
  26005. * @param {string} stackedDim
  26006. */
  26007. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  26008. // Each single series only maps to one pair of axis. So we do not need to
  26009. // check stackByDim, whatever stacked by a dimension or stacked by index.
  26010. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  26011. // && (
  26012. // stackedByDim != null
  26013. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  26014. // : data.getCalculationInfo('isStackedByIndex')
  26015. // );
  26016. }
  26017. /**
  26018. * @param {module:echarts/data/List} data
  26019. * @param {string} targetDim
  26020. * @param {string} [stackedByDim] If not input this parameter, check whether
  26021. * stacked by index.
  26022. * @return {string} dimension
  26023. */
  26024. function getStackedDimension(data, targetDim) {
  26025. return isDimensionStacked(data, targetDim)
  26026. ? data.getCalculationInfo('stackResultDimension')
  26027. : targetDim;
  26028. }
  26029. /*
  26030. * Licensed to the Apache Software Foundation (ASF) under one
  26031. * or more contributor license agreements. See the NOTICE file
  26032. * distributed with this work for additional information
  26033. * regarding copyright ownership. The ASF licenses this file
  26034. * to you under the Apache License, Version 2.0 (the
  26035. * "License"); you may not use this file except in compliance
  26036. * with the License. You may obtain a copy of the License at
  26037. *
  26038. * http://www.apache.org/licenses/LICENSE-2.0
  26039. *
  26040. * Unless required by applicable law or agreed to in writing,
  26041. * software distributed under the License is distributed on an
  26042. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26043. * KIND, either express or implied. See the License for the
  26044. * specific language governing permissions and limitations
  26045. * under the License.
  26046. */
  26047. /**
  26048. * @param {module:echarts/data/Source|Array} source Or raw data.
  26049. * @param {module:echarts/model/Series} seriesModel
  26050. * @param {Object} [opt]
  26051. * @param {string} [opt.generateCoord]
  26052. */
  26053. function createListFromArray(source, seriesModel, opt) {
  26054. opt = opt || {};
  26055. if (!Source.isInstance(source)) {
  26056. source = Source.seriesDataToSource(source);
  26057. }
  26058. var coordSysName = seriesModel.get('coordinateSystem');
  26059. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  26060. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  26061. var coordSysDimDefs;
  26062. if (coordSysDefine) {
  26063. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  26064. var dimInfo = {name: dim};
  26065. var axisModel = coordSysDefine.axisMap.get(dim);
  26066. if (axisModel) {
  26067. var axisType = axisModel.get('type');
  26068. dimInfo.type = getDimensionTypeByAxis(axisType);
  26069. // dimInfo.stackable = isStackable(axisType);
  26070. }
  26071. return dimInfo;
  26072. });
  26073. }
  26074. if (!coordSysDimDefs) {
  26075. // Get dimensions from registered coordinate system
  26076. coordSysDimDefs = (registeredCoordSys && (
  26077. registeredCoordSys.getDimensionsInfo
  26078. ? registeredCoordSys.getDimensionsInfo()
  26079. : registeredCoordSys.dimensions.slice()
  26080. )) || ['x', 'y'];
  26081. }
  26082. var dimInfoList = createDimensions(source, {
  26083. coordDimensions: coordSysDimDefs,
  26084. generateCoord: opt.generateCoord
  26085. });
  26086. var firstCategoryDimIndex;
  26087. var hasNameEncode;
  26088. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  26089. var coordDim = dimInfo.coordDim;
  26090. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  26091. if (categoryAxisModel) {
  26092. if (firstCategoryDimIndex == null) {
  26093. firstCategoryDimIndex = dimIndex;
  26094. }
  26095. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  26096. }
  26097. if (dimInfo.otherDims.itemName != null) {
  26098. hasNameEncode = true;
  26099. }
  26100. });
  26101. if (!hasNameEncode && firstCategoryDimIndex != null) {
  26102. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  26103. }
  26104. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  26105. var list = new List(dimInfoList, seriesModel);
  26106. list.setCalculationInfo(stackCalculationInfo);
  26107. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  26108. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  26109. // Use dataIndex as ordinal value in categoryAxis
  26110. return dimIndex === firstCategoryDimIndex
  26111. ? dataIndex
  26112. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  26113. }
  26114. : null;
  26115. list.hasItemOption = false;
  26116. list.initData(source, null, dimValueGetter);
  26117. return list;
  26118. }
  26119. function isNeedCompleteOrdinalData(source) {
  26120. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  26121. var sampleItem = firstDataNotNull(source.data || []);
  26122. return sampleItem != null
  26123. && !isArray(getDataItemValue(sampleItem));
  26124. }
  26125. }
  26126. function firstDataNotNull(data) {
  26127. var i = 0;
  26128. while (i < data.length && data[i] == null) {
  26129. i++;
  26130. }
  26131. return data[i];
  26132. }
  26133. /*
  26134. * Licensed to the Apache Software Foundation (ASF) under one
  26135. * or more contributor license agreements. See the NOTICE file
  26136. * distributed with this work for additional information
  26137. * regarding copyright ownership. The ASF licenses this file
  26138. * to you under the Apache License, Version 2.0 (the
  26139. * "License"); you may not use this file except in compliance
  26140. * with the License. You may obtain a copy of the License at
  26141. *
  26142. * http://www.apache.org/licenses/LICENSE-2.0
  26143. *
  26144. * Unless required by applicable law or agreed to in writing,
  26145. * software distributed under the License is distributed on an
  26146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26147. * KIND, either express or implied. See the License for the
  26148. * specific language governing permissions and limitations
  26149. * under the License.
  26150. */
  26151. /**
  26152. * // Scale class management
  26153. * @module echarts/scale/Scale
  26154. */
  26155. /**
  26156. * @param {Object} [setting]
  26157. */
  26158. function Scale(setting) {
  26159. this._setting = setting || {};
  26160. /**
  26161. * Extent
  26162. * @type {Array.<number>}
  26163. * @protected
  26164. */
  26165. this._extent = [Infinity, -Infinity];
  26166. /**
  26167. * Step is calculated in adjustExtent
  26168. * @type {Array.<number>}
  26169. * @protected
  26170. */
  26171. this._interval = 0;
  26172. this.init && this.init.apply(this, arguments);
  26173. }
  26174. /**
  26175. * Parse input val to valid inner number.
  26176. * @param {*} val
  26177. * @return {number}
  26178. */
  26179. Scale.prototype.parse = function (val) {
  26180. // Notice: This would be a trap here, If the implementation
  26181. // of this method depends on extent, and this method is used
  26182. // before extent set (like in dataZoom), it would be wrong.
  26183. // Nevertheless, parse does not depend on extent generally.
  26184. return val;
  26185. };
  26186. Scale.prototype.getSetting = function (name) {
  26187. return this._setting[name];
  26188. };
  26189. Scale.prototype.contain = function (val) {
  26190. var extent = this._extent;
  26191. return val >= extent[0] && val <= extent[1];
  26192. };
  26193. /**
  26194. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  26195. * @param {number} val
  26196. * @return {number}
  26197. */
  26198. Scale.prototype.normalize = function (val) {
  26199. var extent = this._extent;
  26200. if (extent[1] === extent[0]) {
  26201. return 0.5;
  26202. }
  26203. return (val - extent[0]) / (extent[1] - extent[0]);
  26204. };
  26205. /**
  26206. * Scale normalized value
  26207. * @param {number} val
  26208. * @return {number}
  26209. */
  26210. Scale.prototype.scale = function (val) {
  26211. var extent = this._extent;
  26212. return val * (extent[1] - extent[0]) + extent[0];
  26213. };
  26214. /**
  26215. * Set extent from data
  26216. * @param {Array.<number>} other
  26217. */
  26218. Scale.prototype.unionExtent = function (other) {
  26219. var extent = this._extent;
  26220. other[0] < extent[0] && (extent[0] = other[0]);
  26221. other[1] > extent[1] && (extent[1] = other[1]);
  26222. // not setExtent because in log axis it may transformed to power
  26223. // this.setExtent(extent[0], extent[1]);
  26224. };
  26225. /**
  26226. * Set extent from data
  26227. * @param {module:echarts/data/List} data
  26228. * @param {string} dim
  26229. */
  26230. Scale.prototype.unionExtentFromData = function (data, dim) {
  26231. this.unionExtent(data.getApproximateExtent(dim));
  26232. };
  26233. /**
  26234. * Get extent
  26235. * @return {Array.<number>}
  26236. */
  26237. Scale.prototype.getExtent = function () {
  26238. return this._extent.slice();
  26239. };
  26240. /**
  26241. * Set extent
  26242. * @param {number} start
  26243. * @param {number} end
  26244. */
  26245. Scale.prototype.setExtent = function (start, end) {
  26246. var thisExtent = this._extent;
  26247. if (!isNaN(start)) {
  26248. thisExtent[0] = start;
  26249. }
  26250. if (!isNaN(end)) {
  26251. thisExtent[1] = end;
  26252. }
  26253. };
  26254. /**
  26255. * When axis extent depends on data and no data exists,
  26256. * axis ticks should not be drawn, which is named 'blank'.
  26257. */
  26258. Scale.prototype.isBlank = function () {
  26259. return this._isBlank;
  26260. },
  26261. /**
  26262. * When axis extent depends on data and no data exists,
  26263. * axis ticks should not be drawn, which is named 'blank'.
  26264. */
  26265. Scale.prototype.setBlank = function (isBlank) {
  26266. this._isBlank = isBlank;
  26267. };
  26268. /**
  26269. * @abstract
  26270. * @param {*} tick
  26271. * @return {string} label of the tick.
  26272. */
  26273. Scale.prototype.getLabel = null;
  26274. enableClassExtend(Scale);
  26275. enableClassManagement(Scale, {
  26276. registerWhenExtend: true
  26277. });
  26278. /*
  26279. * Licensed to the Apache Software Foundation (ASF) under one
  26280. * or more contributor license agreements. See the NOTICE file
  26281. * distributed with this work for additional information
  26282. * regarding copyright ownership. The ASF licenses this file
  26283. * to you under the Apache License, Version 2.0 (the
  26284. * "License"); you may not use this file except in compliance
  26285. * with the License. You may obtain a copy of the License at
  26286. *
  26287. * http://www.apache.org/licenses/LICENSE-2.0
  26288. *
  26289. * Unless required by applicable law or agreed to in writing,
  26290. * software distributed under the License is distributed on an
  26291. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26292. * KIND, either express or implied. See the License for the
  26293. * specific language governing permissions and limitations
  26294. * under the License.
  26295. */
  26296. /**
  26297. * @constructor
  26298. * @param {Object} [opt]
  26299. * @param {Object} [opt.categories=[]]
  26300. * @param {Object} [opt.needCollect=false]
  26301. * @param {Object} [opt.deduplication=false]
  26302. */
  26303. function OrdinalMeta(opt) {
  26304. /**
  26305. * @readOnly
  26306. * @type {Array.<string>}
  26307. */
  26308. this.categories = opt.categories || [];
  26309. /**
  26310. * @private
  26311. * @type {boolean}
  26312. */
  26313. this._needCollect = opt.needCollect;
  26314. /**
  26315. * @private
  26316. * @type {boolean}
  26317. */
  26318. this._deduplication = opt.deduplication;
  26319. /**
  26320. * @private
  26321. * @type {boolean}
  26322. */
  26323. this._map;
  26324. }
  26325. /**
  26326. * @param {module:echarts/model/Model} axisModel
  26327. * @return {module:echarts/data/OrdinalMeta}
  26328. */
  26329. OrdinalMeta.createByAxisModel = function (axisModel) {
  26330. var option = axisModel.option;
  26331. var data = option.data;
  26332. var categories = data && map(data, getName);
  26333. return new OrdinalMeta({
  26334. categories: categories,
  26335. needCollect: !categories,
  26336. // deduplication is default in axis.
  26337. deduplication: option.dedplication !== false
  26338. });
  26339. };
  26340. var proto$1 = OrdinalMeta.prototype;
  26341. /**
  26342. * @param {string} category
  26343. * @return {number} ordinal
  26344. */
  26345. proto$1.getOrdinal = function (category) {
  26346. return getOrCreateMap(this).get(category);
  26347. };
  26348. /**
  26349. * @param {*} category
  26350. * @return {number} The ordinal. If not found, return NaN.
  26351. */
  26352. proto$1.parseAndCollect = function (category) {
  26353. var index;
  26354. var needCollect = this._needCollect;
  26355. // The value of category dim can be the index of the given category set.
  26356. // This feature is only supported when !needCollect, because we should
  26357. // consider a common case: a value is 2017, which is a number but is
  26358. // expected to be tread as a category. This case usually happen in dataset,
  26359. // where it happent to be no need of the index feature.
  26360. if (typeof category !== 'string' && !needCollect) {
  26361. return category;
  26362. }
  26363. // Optimize for the scenario:
  26364. // category is ['2012-01-01', '2012-01-02', ...], where the input
  26365. // data has been ensured not duplicate and is large data.
  26366. // Notice, if a dataset dimension provide categroies, usually echarts
  26367. // should remove duplication except user tell echarts dont do that
  26368. // (set axis.deduplication = false), because echarts do not know whether
  26369. // the values in the category dimension has duplication (consider the
  26370. // parallel-aqi example)
  26371. if (needCollect && !this._deduplication) {
  26372. index = this.categories.length;
  26373. this.categories[index] = category;
  26374. return index;
  26375. }
  26376. var map$$1 = getOrCreateMap(this);
  26377. index = map$$1.get(category);
  26378. if (index == null) {
  26379. if (needCollect) {
  26380. index = this.categories.length;
  26381. this.categories[index] = category;
  26382. map$$1.set(category, index);
  26383. }
  26384. else {
  26385. index = NaN;
  26386. }
  26387. }
  26388. return index;
  26389. };
  26390. // Consider big data, do not create map until needed.
  26391. function getOrCreateMap(ordinalMeta) {
  26392. return ordinalMeta._map || (
  26393. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  26394. );
  26395. }
  26396. function getName(obj) {
  26397. if (isObject$1(obj) && obj.value != null) {
  26398. return obj.value;
  26399. }
  26400. else {
  26401. return obj + '';
  26402. }
  26403. }
  26404. /*
  26405. * Licensed to the Apache Software Foundation (ASF) under one
  26406. * or more contributor license agreements. See the NOTICE file
  26407. * distributed with this work for additional information
  26408. * regarding copyright ownership. The ASF licenses this file
  26409. * to you under the Apache License, Version 2.0 (the
  26410. * "License"); you may not use this file except in compliance
  26411. * with the License. You may obtain a copy of the License at
  26412. *
  26413. * http://www.apache.org/licenses/LICENSE-2.0
  26414. *
  26415. * Unless required by applicable law or agreed to in writing,
  26416. * software distributed under the License is distributed on an
  26417. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26418. * KIND, either express or implied. See the License for the
  26419. * specific language governing permissions and limitations
  26420. * under the License.
  26421. */
  26422. /**
  26423. * Linear continuous scale
  26424. * @module echarts/coord/scale/Ordinal
  26425. *
  26426. * http://en.wikipedia.org/wiki/Level_of_measurement
  26427. */
  26428. // FIXME only one data
  26429. var scaleProto = Scale.prototype;
  26430. var OrdinalScale = Scale.extend({
  26431. type: 'ordinal',
  26432. /**
  26433. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  26434. */
  26435. init: function (ordinalMeta, extent) {
  26436. // Caution: Should not use instanceof, consider ec-extensions using
  26437. // import approach to get OrdinalMeta class.
  26438. if (!ordinalMeta || isArray(ordinalMeta)) {
  26439. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  26440. }
  26441. this._ordinalMeta = ordinalMeta;
  26442. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  26443. },
  26444. parse: function (val) {
  26445. return typeof val === 'string'
  26446. ? this._ordinalMeta.getOrdinal(val)
  26447. // val might be float.
  26448. : Math.round(val);
  26449. },
  26450. contain: function (rank) {
  26451. rank = this.parse(rank);
  26452. return scaleProto.contain.call(this, rank)
  26453. && this._ordinalMeta.categories[rank] != null;
  26454. },
  26455. /**
  26456. * Normalize given rank or name to linear [0, 1]
  26457. * @param {number|string} [val]
  26458. * @return {number}
  26459. */
  26460. normalize: function (val) {
  26461. return scaleProto.normalize.call(this, this.parse(val));
  26462. },
  26463. scale: function (val) {
  26464. return Math.round(scaleProto.scale.call(this, val));
  26465. },
  26466. /**
  26467. * @return {Array}
  26468. */
  26469. getTicks: function () {
  26470. var ticks = [];
  26471. var extent = this._extent;
  26472. var rank = extent[0];
  26473. while (rank <= extent[1]) {
  26474. ticks.push(rank);
  26475. rank++;
  26476. }
  26477. return ticks;
  26478. },
  26479. /**
  26480. * Get item on rank n
  26481. * @param {number} n
  26482. * @return {string}
  26483. */
  26484. getLabel: function (n) {
  26485. if (!this.isBlank()) {
  26486. // Note that if no data, ordinalMeta.categories is an empty array.
  26487. return this._ordinalMeta.categories[n];
  26488. }
  26489. },
  26490. /**
  26491. * @return {number}
  26492. */
  26493. count: function () {
  26494. return this._extent[1] - this._extent[0] + 1;
  26495. },
  26496. /**
  26497. * @override
  26498. */
  26499. unionExtentFromData: function (data, dim) {
  26500. this.unionExtent(data.getApproximateExtent(dim));
  26501. },
  26502. getOrdinalMeta: function () {
  26503. return this._ordinalMeta;
  26504. },
  26505. niceTicks: noop,
  26506. niceExtent: noop
  26507. });
  26508. /**
  26509. * @return {module:echarts/scale/Time}
  26510. */
  26511. OrdinalScale.create = function () {
  26512. return new OrdinalScale();
  26513. };
  26514. /*
  26515. * Licensed to the Apache Software Foundation (ASF) under one
  26516. * or more contributor license agreements. See the NOTICE file
  26517. * distributed with this work for additional information
  26518. * regarding copyright ownership. The ASF licenses this file
  26519. * to you under the Apache License, Version 2.0 (the
  26520. * "License"); you may not use this file except in compliance
  26521. * with the License. You may obtain a copy of the License at
  26522. *
  26523. * http://www.apache.org/licenses/LICENSE-2.0
  26524. *
  26525. * Unless required by applicable law or agreed to in writing,
  26526. * software distributed under the License is distributed on an
  26527. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26528. * KIND, either express or implied. See the License for the
  26529. * specific language governing permissions and limitations
  26530. * under the License.
  26531. */
  26532. /**
  26533. * For testable.
  26534. */
  26535. var roundNumber$1 = round$1;
  26536. /**
  26537. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  26538. * Should be extent[0] < extent[1].
  26539. * @param {number} splitNumber splitNumber should be >= 1.
  26540. * @param {number} [minInterval]
  26541. * @param {number} [maxInterval]
  26542. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  26543. */
  26544. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  26545. var result = {};
  26546. var span = extent[1] - extent[0];
  26547. var interval = result.interval = nice(span / splitNumber, true);
  26548. if (minInterval != null && interval < minInterval) {
  26549. interval = result.interval = minInterval;
  26550. }
  26551. if (maxInterval != null && interval > maxInterval) {
  26552. interval = result.interval = maxInterval;
  26553. }
  26554. // Tow more digital for tick.
  26555. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  26556. // Niced extent inside original extent
  26557. var niceTickExtent = result.niceTickExtent = [
  26558. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  26559. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  26560. ];
  26561. fixExtent(niceTickExtent, extent);
  26562. return result;
  26563. }
  26564. /**
  26565. * @param {number} interval
  26566. * @return {number} interval precision
  26567. */
  26568. function getIntervalPrecision(interval) {
  26569. // Tow more digital for tick.
  26570. return getPrecisionSafe(interval) + 2;
  26571. }
  26572. function clamp(niceTickExtent, idx, extent) {
  26573. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  26574. }
  26575. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  26576. function fixExtent(niceTickExtent, extent) {
  26577. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  26578. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  26579. clamp(niceTickExtent, 0, extent);
  26580. clamp(niceTickExtent, 1, extent);
  26581. if (niceTickExtent[0] > niceTickExtent[1]) {
  26582. niceTickExtent[0] = niceTickExtent[1];
  26583. }
  26584. }
  26585. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  26586. var ticks = [];
  26587. // If interval is 0, return [];
  26588. if (!interval) {
  26589. return ticks;
  26590. }
  26591. // Consider this case: using dataZoom toolbox, zoom and zoom.
  26592. var safeLimit = 10000;
  26593. if (extent[0] < niceTickExtent[0]) {
  26594. ticks.push(extent[0]);
  26595. }
  26596. var tick = niceTickExtent[0];
  26597. while (tick <= niceTickExtent[1]) {
  26598. ticks.push(tick);
  26599. // Avoid rounding error
  26600. tick = roundNumber$1(tick + interval, intervalPrecision);
  26601. if (tick === ticks[ticks.length - 1]) {
  26602. // Consider out of safe float point, e.g.,
  26603. // -3711126.9907707 + 2e-10 === -3711126.9907707
  26604. break;
  26605. }
  26606. if (ticks.length > safeLimit) {
  26607. return [];
  26608. }
  26609. }
  26610. // Consider this case: the last item of ticks is smaller
  26611. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  26612. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  26613. ticks.push(extent[1]);
  26614. }
  26615. return ticks;
  26616. }
  26617. /*
  26618. * Licensed to the Apache Software Foundation (ASF) under one
  26619. * or more contributor license agreements. See the NOTICE file
  26620. * distributed with this work for additional information
  26621. * regarding copyright ownership. The ASF licenses this file
  26622. * to you under the Apache License, Version 2.0 (the
  26623. * "License"); you may not use this file except in compliance
  26624. * with the License. You may obtain a copy of the License at
  26625. *
  26626. * http://www.apache.org/licenses/LICENSE-2.0
  26627. *
  26628. * Unless required by applicable law or agreed to in writing,
  26629. * software distributed under the License is distributed on an
  26630. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26631. * KIND, either express or implied. See the License for the
  26632. * specific language governing permissions and limitations
  26633. * under the License.
  26634. */
  26635. /**
  26636. * Interval scale
  26637. * @module echarts/scale/Interval
  26638. */
  26639. var roundNumber = round$1;
  26640. /**
  26641. * @alias module:echarts/coord/scale/Interval
  26642. * @constructor
  26643. */
  26644. var IntervalScale = Scale.extend({
  26645. type: 'interval',
  26646. _interval: 0,
  26647. _intervalPrecision: 2,
  26648. setExtent: function (start, end) {
  26649. var thisExtent = this._extent;
  26650. //start,end may be a Number like '25',so...
  26651. if (!isNaN(start)) {
  26652. thisExtent[0] = parseFloat(start);
  26653. }
  26654. if (!isNaN(end)) {
  26655. thisExtent[1] = parseFloat(end);
  26656. }
  26657. },
  26658. unionExtent: function (other) {
  26659. var extent = this._extent;
  26660. other[0] < extent[0] && (extent[0] = other[0]);
  26661. other[1] > extent[1] && (extent[1] = other[1]);
  26662. // unionExtent may called by it's sub classes
  26663. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  26664. },
  26665. /**
  26666. * Get interval
  26667. */
  26668. getInterval: function () {
  26669. return this._interval;
  26670. },
  26671. /**
  26672. * Set interval
  26673. */
  26674. setInterval: function (interval) {
  26675. this._interval = interval;
  26676. // Dropped auto calculated niceExtent and use user setted extent
  26677. // We assume user wan't to set both interval, min, max to get a better result
  26678. this._niceExtent = this._extent.slice();
  26679. this._intervalPrecision = getIntervalPrecision(interval);
  26680. },
  26681. /**
  26682. * @return {Array.<number>}
  26683. */
  26684. getTicks: function () {
  26685. return intervalScaleGetTicks(
  26686. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  26687. );
  26688. },
  26689. /**
  26690. * @param {number} data
  26691. * @param {Object} [opt]
  26692. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  26693. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  26694. * @return {string}
  26695. */
  26696. getLabel: function (data, opt) {
  26697. if (data == null) {
  26698. return '';
  26699. }
  26700. var precision = opt && opt.precision;
  26701. if (precision == null) {
  26702. precision = getPrecisionSafe(data) || 0;
  26703. }
  26704. else if (precision === 'auto') {
  26705. // Should be more precise then tick.
  26706. precision = this._intervalPrecision;
  26707. }
  26708. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  26709. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  26710. data = roundNumber(data, precision, true);
  26711. return addCommas(data);
  26712. },
  26713. /**
  26714. * Update interval and extent of intervals for nice ticks
  26715. *
  26716. * @param {number} [splitNumber = 5] Desired number of ticks
  26717. * @param {number} [minInterval]
  26718. * @param {number} [maxInterval]
  26719. */
  26720. niceTicks: function (splitNumber, minInterval, maxInterval) {
  26721. splitNumber = splitNumber || 5;
  26722. var extent = this._extent;
  26723. var span = extent[1] - extent[0];
  26724. if (!isFinite(span)) {
  26725. return;
  26726. }
  26727. // User may set axis min 0 and data are all negative
  26728. // FIXME If it needs to reverse ?
  26729. if (span < 0) {
  26730. span = -span;
  26731. extent.reverse();
  26732. }
  26733. var result = intervalScaleNiceTicks(
  26734. extent, splitNumber, minInterval, maxInterval
  26735. );
  26736. this._intervalPrecision = result.intervalPrecision;
  26737. this._interval = result.interval;
  26738. this._niceExtent = result.niceTickExtent;
  26739. },
  26740. /**
  26741. * Nice extent.
  26742. * @param {Object} opt
  26743. * @param {number} [opt.splitNumber = 5] Given approx tick number
  26744. * @param {boolean} [opt.fixMin=false]
  26745. * @param {boolean} [opt.fixMax=false]
  26746. * @param {boolean} [opt.minInterval]
  26747. * @param {boolean} [opt.maxInterval]
  26748. */
  26749. niceExtent: function (opt) {
  26750. var extent = this._extent;
  26751. // If extent start and end are same, expand them
  26752. if (extent[0] === extent[1]) {
  26753. if (extent[0] !== 0) {
  26754. // Expand extent
  26755. var expandSize = extent[0];
  26756. // In the fowllowing case
  26757. // Axis has been fixed max 100
  26758. // Plus data are all 100 and axis extent are [100, 100].
  26759. // Extend to the both side will cause expanded max is larger than fixed max.
  26760. // So only expand to the smaller side.
  26761. if (!opt.fixMax) {
  26762. extent[1] += expandSize / 2;
  26763. extent[0] -= expandSize / 2;
  26764. }
  26765. else {
  26766. extent[0] -= expandSize / 2;
  26767. }
  26768. }
  26769. else {
  26770. extent[1] = 1;
  26771. }
  26772. }
  26773. var span = extent[1] - extent[0];
  26774. // If there are no data and extent are [Infinity, -Infinity]
  26775. if (!isFinite(span)) {
  26776. extent[0] = 0;
  26777. extent[1] = 1;
  26778. }
  26779. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  26780. // var extent = this._extent;
  26781. var interval = this._interval;
  26782. if (!opt.fixMin) {
  26783. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  26784. }
  26785. if (!opt.fixMax) {
  26786. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  26787. }
  26788. }
  26789. });
  26790. /**
  26791. * @return {module:echarts/scale/Time}
  26792. */
  26793. IntervalScale.create = function () {
  26794. return new IntervalScale();
  26795. };
  26796. /*
  26797. * Licensed to the Apache Software Foundation (ASF) under one
  26798. * or more contributor license agreements. See the NOTICE file
  26799. * distributed with this work for additional information
  26800. * regarding copyright ownership. The ASF licenses this file
  26801. * to you under the Apache License, Version 2.0 (the
  26802. * "License"); you may not use this file except in compliance
  26803. * with the License. You may obtain a copy of the License at
  26804. *
  26805. * http://www.apache.org/licenses/LICENSE-2.0
  26806. *
  26807. * Unless required by applicable law or agreed to in writing,
  26808. * software distributed under the License is distributed on an
  26809. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26810. * KIND, either express or implied. See the License for the
  26811. * specific language governing permissions and limitations
  26812. * under the License.
  26813. */
  26814. var STACK_PREFIX = '__ec_stack_';
  26815. var LARGE_BAR_MIN_WIDTH = 0.5;
  26816. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  26817. function getSeriesStackId(seriesModel) {
  26818. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  26819. }
  26820. function getAxisKey(axis) {
  26821. return axis.dim + axis.index;
  26822. }
  26823. /**
  26824. * @param {Object} opt
  26825. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  26826. * @param {number} opt.count Positive interger.
  26827. * @param {number} [opt.barWidth]
  26828. * @param {number} [opt.barMaxWidth]
  26829. * @param {number} [opt.barGap]
  26830. * @param {number} [opt.barCategoryGap]
  26831. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  26832. */
  26833. function getLayoutOnAxis(opt) {
  26834. var params = [];
  26835. var baseAxis = opt.axis;
  26836. var axisKey = 'axis0';
  26837. if (baseAxis.type !== 'category') {
  26838. return;
  26839. }
  26840. var bandWidth = baseAxis.getBandWidth();
  26841. for (var i = 0; i < opt.count || 0; i++) {
  26842. params.push(defaults({
  26843. bandWidth: bandWidth,
  26844. axisKey: axisKey,
  26845. stackId: STACK_PREFIX + i
  26846. }, opt));
  26847. }
  26848. var widthAndOffsets = doCalBarWidthAndOffset(params);
  26849. var result = [];
  26850. for (var i = 0; i < opt.count; i++) {
  26851. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  26852. item.offsetCenter = item.offset + item.width / 2;
  26853. result.push(item);
  26854. }
  26855. return result;
  26856. }
  26857. function prepareLayoutBarSeries(seriesType, ecModel) {
  26858. var seriesModels = [];
  26859. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  26860. // Check series coordinate, do layout for cartesian2d only
  26861. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  26862. seriesModels.push(seriesModel);
  26863. }
  26864. });
  26865. return seriesModels;
  26866. }
  26867. function makeColumnLayout(barSeries) {
  26868. var seriesInfoList = [];
  26869. each$1(barSeries, function (seriesModel) {
  26870. var data = seriesModel.getData();
  26871. var cartesian = seriesModel.coordinateSystem;
  26872. var baseAxis = cartesian.getBaseAxis();
  26873. var axisExtent = baseAxis.getExtent();
  26874. var bandWidth = baseAxis.type === 'category'
  26875. ? baseAxis.getBandWidth()
  26876. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  26877. var barWidth = parsePercent$1(
  26878. seriesModel.get('barWidth'), bandWidth
  26879. );
  26880. var barMaxWidth = parsePercent$1(
  26881. seriesModel.get('barMaxWidth'), bandWidth
  26882. );
  26883. var barGap = seriesModel.get('barGap');
  26884. var barCategoryGap = seriesModel.get('barCategoryGap');
  26885. seriesInfoList.push({
  26886. bandWidth: bandWidth,
  26887. barWidth: barWidth,
  26888. barMaxWidth: barMaxWidth,
  26889. barGap: barGap,
  26890. barCategoryGap: barCategoryGap,
  26891. axisKey: getAxisKey(baseAxis),
  26892. stackId: getSeriesStackId(seriesModel)
  26893. });
  26894. });
  26895. return doCalBarWidthAndOffset(seriesInfoList);
  26896. }
  26897. function doCalBarWidthAndOffset(seriesInfoList) {
  26898. // Columns info on each category axis. Key is cartesian name
  26899. var columnsMap = {};
  26900. each$1(seriesInfoList, function (seriesInfo, idx) {
  26901. var axisKey = seriesInfo.axisKey;
  26902. var bandWidth = seriesInfo.bandWidth;
  26903. var columnsOnAxis = columnsMap[axisKey] || {
  26904. bandWidth: bandWidth,
  26905. remainedWidth: bandWidth,
  26906. autoWidthCount: 0,
  26907. categoryGap: '20%',
  26908. gap: '30%',
  26909. stacks: {}
  26910. };
  26911. var stacks = columnsOnAxis.stacks;
  26912. columnsMap[axisKey] = columnsOnAxis;
  26913. var stackId = seriesInfo.stackId;
  26914. if (!stacks[stackId]) {
  26915. columnsOnAxis.autoWidthCount++;
  26916. }
  26917. stacks[stackId] = stacks[stackId] || {
  26918. width: 0,
  26919. maxWidth: 0
  26920. };
  26921. // Caution: In a single coordinate system, these barGrid attributes
  26922. // will be shared by series. Consider that they have default values,
  26923. // only the attributes set on the last series will work.
  26924. // Do not change this fact unless there will be a break change.
  26925. // TODO
  26926. var barWidth = seriesInfo.barWidth;
  26927. if (barWidth && !stacks[stackId].width) {
  26928. // See #6312, do not restrict width.
  26929. stacks[stackId].width = barWidth;
  26930. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  26931. columnsOnAxis.remainedWidth -= barWidth;
  26932. }
  26933. var barMaxWidth = seriesInfo.barMaxWidth;
  26934. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  26935. var barGap = seriesInfo.barGap;
  26936. (barGap != null) && (columnsOnAxis.gap = barGap);
  26937. var barCategoryGap = seriesInfo.barCategoryGap;
  26938. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  26939. });
  26940. var result = {};
  26941. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  26942. result[coordSysName] = {};
  26943. var stacks = columnsOnAxis.stacks;
  26944. var bandWidth = columnsOnAxis.bandWidth;
  26945. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  26946. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  26947. var remainedWidth = columnsOnAxis.remainedWidth;
  26948. var autoWidthCount = columnsOnAxis.autoWidthCount;
  26949. var autoWidth = (remainedWidth - categoryGap)
  26950. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  26951. autoWidth = Math.max(autoWidth, 0);
  26952. // Find if any auto calculated bar exceeded maxBarWidth
  26953. each$1(stacks, function (column, stack) {
  26954. var maxWidth = column.maxWidth;
  26955. if (maxWidth && maxWidth < autoWidth) {
  26956. maxWidth = Math.min(maxWidth, remainedWidth);
  26957. if (column.width) {
  26958. maxWidth = Math.min(maxWidth, column.width);
  26959. }
  26960. remainedWidth -= maxWidth;
  26961. column.width = maxWidth;
  26962. autoWidthCount--;
  26963. }
  26964. });
  26965. // Recalculate width again
  26966. autoWidth = (remainedWidth - categoryGap)
  26967. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  26968. autoWidth = Math.max(autoWidth, 0);
  26969. var widthSum = 0;
  26970. var lastColumn;
  26971. each$1(stacks, function (column, idx) {
  26972. if (!column.width) {
  26973. column.width = autoWidth;
  26974. }
  26975. lastColumn = column;
  26976. widthSum += column.width * (1 + barGapPercent);
  26977. });
  26978. if (lastColumn) {
  26979. widthSum -= lastColumn.width * barGapPercent;
  26980. }
  26981. var offset = -widthSum / 2;
  26982. each$1(stacks, function (column, stackId) {
  26983. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  26984. offset: offset,
  26985. width: column.width
  26986. };
  26987. offset += column.width * (1 + barGapPercent);
  26988. });
  26989. });
  26990. return result;
  26991. }
  26992. /**
  26993. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  26994. * @param {module:echarts/coord/Axis} axis
  26995. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  26996. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  26997. */
  26998. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  26999. if (barWidthAndOffset && axis) {
  27000. var result = barWidthAndOffset[getAxisKey(axis)];
  27001. if (result != null && seriesModel != null) {
  27002. result = result[getSeriesStackId(seriesModel)];
  27003. }
  27004. return result;
  27005. }
  27006. }
  27007. /**
  27008. * @param {string} seriesType
  27009. * @param {module:echarts/model/Global} ecModel
  27010. */
  27011. function layout(seriesType, ecModel) {
  27012. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  27013. var barWidthAndOffset = makeColumnLayout(seriesModels);
  27014. var lastStackCoords = {};
  27015. each$1(seriesModels, function (seriesModel) {
  27016. var data = seriesModel.getData();
  27017. var cartesian = seriesModel.coordinateSystem;
  27018. var baseAxis = cartesian.getBaseAxis();
  27019. var stackId = getSeriesStackId(seriesModel);
  27020. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  27021. var columnOffset = columnLayoutInfo.offset;
  27022. var columnWidth = columnLayoutInfo.width;
  27023. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27024. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  27025. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  27026. data.setLayout({
  27027. offset: columnOffset,
  27028. size: columnWidth
  27029. });
  27030. var valueDim = data.mapDimension(valueAxis.dim);
  27031. var baseDim = data.mapDimension(baseAxis.dim);
  27032. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  27033. var isValueAxisH = valueAxis.isHorizontal();
  27034. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  27035. for (var idx = 0, len = data.count(); idx < len; idx++) {
  27036. var value = data.get(valueDim, idx);
  27037. var baseValue = data.get(baseDim, idx);
  27038. if (isNaN(value)) {
  27039. continue;
  27040. }
  27041. var sign = value >= 0 ? 'p' : 'n';
  27042. var baseCoord = valueAxisStart;
  27043. // Because of the barMinHeight, we can not use the value in
  27044. // stackResultDimension directly.
  27045. if (stacked) {
  27046. // Only ordinal axis can be stacked.
  27047. if (!lastStackCoords[stackId][baseValue]) {
  27048. lastStackCoords[stackId][baseValue] = {
  27049. p: valueAxisStart, // Positive stack
  27050. n: valueAxisStart // Negative stack
  27051. };
  27052. }
  27053. // Should also consider #4243
  27054. baseCoord = lastStackCoords[stackId][baseValue][sign];
  27055. }
  27056. var x;
  27057. var y;
  27058. var width;
  27059. var height;
  27060. if (isValueAxisH) {
  27061. var coord = cartesian.dataToPoint([value, baseValue]);
  27062. x = baseCoord;
  27063. y = coord[1] + columnOffset;
  27064. width = coord[0] - valueAxisStart;
  27065. height = columnWidth;
  27066. if (Math.abs(width) < barMinHeight) {
  27067. width = (width < 0 ? -1 : 1) * barMinHeight;
  27068. }
  27069. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  27070. }
  27071. else {
  27072. var coord = cartesian.dataToPoint([baseValue, value]);
  27073. x = coord[0] + columnOffset;
  27074. y = baseCoord;
  27075. width = columnWidth;
  27076. height = coord[1] - valueAxisStart;
  27077. if (Math.abs(height) < barMinHeight) {
  27078. // Include zero to has a positive bar
  27079. height = (height <= 0 ? -1 : 1) * barMinHeight;
  27080. }
  27081. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  27082. }
  27083. data.setItemLayout(idx, {
  27084. x: x,
  27085. y: y,
  27086. width: width,
  27087. height: height
  27088. });
  27089. }
  27090. }, this);
  27091. }
  27092. // TODO: Do not support stack in large mode yet.
  27093. var largeLayout = {
  27094. seriesType: 'bar',
  27095. plan: createRenderPlanner(),
  27096. reset: function (seriesModel) {
  27097. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  27098. return;
  27099. }
  27100. var data = seriesModel.getData();
  27101. var cartesian = seriesModel.coordinateSystem;
  27102. var baseAxis = cartesian.getBaseAxis();
  27103. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27104. var valueDim = data.mapDimension(valueAxis.dim);
  27105. var baseDim = data.mapDimension(baseAxis.dim);
  27106. var valueAxisHorizontal = valueAxis.isHorizontal();
  27107. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  27108. var barWidth = retrieveColumnLayout(
  27109. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  27110. ).width;
  27111. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  27112. barWidth = LARGE_BAR_MIN_WIDTH;
  27113. }
  27114. return {progress: progress};
  27115. function progress(params, data) {
  27116. var largePoints = new LargeArr(params.count * 2);
  27117. var dataIndex;
  27118. var coord = [];
  27119. var valuePair = [];
  27120. var offset = 0;
  27121. while ((dataIndex = params.next()) != null) {
  27122. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  27123. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  27124. coord = cartesian.dataToPoint(valuePair, null, coord);
  27125. largePoints[offset++] = coord[0];
  27126. largePoints[offset++] = coord[1];
  27127. }
  27128. data.setLayout({
  27129. largePoints: largePoints,
  27130. barWidth: barWidth,
  27131. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  27132. valueAxisHorizontal: valueAxisHorizontal
  27133. });
  27134. }
  27135. }
  27136. };
  27137. function isOnCartesian(seriesModel) {
  27138. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  27139. }
  27140. function isInLargeMode(seriesModel) {
  27141. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  27142. }
  27143. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  27144. return (
  27145. indexOf(baseAxis.getAxesOnZeroOf(), valueAxis) >= 0
  27146. || stacked
  27147. )
  27148. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  27149. : valueAxis.getGlobalExtent()[0];
  27150. }
  27151. /*
  27152. * Licensed to the Apache Software Foundation (ASF) under one
  27153. * or more contributor license agreements. See the NOTICE file
  27154. * distributed with this work for additional information
  27155. * regarding copyright ownership. The ASF licenses this file
  27156. * to you under the Apache License, Version 2.0 (the
  27157. * "License"); you may not use this file except in compliance
  27158. * with the License. You may obtain a copy of the License at
  27159. *
  27160. * http://www.apache.org/licenses/LICENSE-2.0
  27161. *
  27162. * Unless required by applicable law or agreed to in writing,
  27163. * software distributed under the License is distributed on an
  27164. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27165. * KIND, either express or implied. See the License for the
  27166. * specific language governing permissions and limitations
  27167. * under the License.
  27168. */
  27169. /*
  27170. * The `scaleLevels` references to d3.js. The use of the source
  27171. * code of this file is also subject to the terms and consitions
  27172. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  27173. */
  27174. // [About UTC and local time zone]:
  27175. // In most cases, `number.parseDate` will treat input data string as local time
  27176. // (except time zone is specified in time string). And `format.formateTime` returns
  27177. // local time by default. option.useUTC is false by default. This design have
  27178. // concidered these common case:
  27179. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  27180. // in local time by default.
  27181. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  27182. // as its original time, without any time difference.
  27183. var intervalScaleProto = IntervalScale.prototype;
  27184. var mathCeil = Math.ceil;
  27185. var mathFloor = Math.floor;
  27186. var ONE_SECOND = 1000;
  27187. var ONE_MINUTE = ONE_SECOND * 60;
  27188. var ONE_HOUR = ONE_MINUTE * 60;
  27189. var ONE_DAY = ONE_HOUR * 24;
  27190. // FIXME 公用?
  27191. var bisect = function (a, x, lo, hi) {
  27192. while (lo < hi) {
  27193. var mid = lo + hi >>> 1;
  27194. if (a[mid][1] < x) {
  27195. lo = mid + 1;
  27196. }
  27197. else {
  27198. hi = mid;
  27199. }
  27200. }
  27201. return lo;
  27202. };
  27203. /**
  27204. * @alias module:echarts/coord/scale/Time
  27205. * @constructor
  27206. */
  27207. var TimeScale = IntervalScale.extend({
  27208. type: 'time',
  27209. /**
  27210. * @override
  27211. */
  27212. getLabel: function (val) {
  27213. var stepLvl = this._stepLvl;
  27214. var date = new Date(val);
  27215. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  27216. },
  27217. /**
  27218. * @override
  27219. */
  27220. niceExtent: function (opt) {
  27221. var extent = this._extent;
  27222. // If extent start and end are same, expand them
  27223. if (extent[0] === extent[1]) {
  27224. // Expand extent
  27225. extent[0] -= ONE_DAY;
  27226. extent[1] += ONE_DAY;
  27227. }
  27228. // If there are no data and extent are [Infinity, -Infinity]
  27229. if (extent[1] === -Infinity && extent[0] === Infinity) {
  27230. var d = new Date();
  27231. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  27232. extent[0] = extent[1] - ONE_DAY;
  27233. }
  27234. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  27235. // var extent = this._extent;
  27236. var interval = this._interval;
  27237. if (!opt.fixMin) {
  27238. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  27239. }
  27240. if (!opt.fixMax) {
  27241. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  27242. }
  27243. },
  27244. /**
  27245. * @override
  27246. */
  27247. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  27248. approxTickNum = approxTickNum || 10;
  27249. var extent = this._extent;
  27250. var span = extent[1] - extent[0];
  27251. var approxInterval = span / approxTickNum;
  27252. if (minInterval != null && approxInterval < minInterval) {
  27253. approxInterval = minInterval;
  27254. }
  27255. if (maxInterval != null && approxInterval > maxInterval) {
  27256. approxInterval = maxInterval;
  27257. }
  27258. var scaleLevelsLen = scaleLevels.length;
  27259. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  27260. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  27261. var interval = level[1];
  27262. // Same with interval scale if span is much larger than 1 year
  27263. if (level[0] === 'year') {
  27264. var yearSpan = span / interval;
  27265. // From "Nice Numbers for Graph Labels" of Graphic Gems
  27266. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  27267. var yearStep = nice(yearSpan / approxTickNum, true);
  27268. interval *= yearStep;
  27269. }
  27270. var timezoneOffset = this.getSetting('useUTC')
  27271. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  27272. var niceExtent = [
  27273. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  27274. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  27275. ];
  27276. fixExtent(niceExtent, extent);
  27277. this._stepLvl = level;
  27278. // Interval will be used in getTicks
  27279. this._interval = interval;
  27280. this._niceExtent = niceExtent;
  27281. },
  27282. parse: function (val) {
  27283. // val might be float.
  27284. return +parseDate(val);
  27285. }
  27286. });
  27287. each$1(['contain', 'normalize'], function (methodName) {
  27288. TimeScale.prototype[methodName] = function (val) {
  27289. return intervalScaleProto[methodName].call(this, this.parse(val));
  27290. };
  27291. });
  27292. // Steps from d3, see the license statement at the top of this file.
  27293. var scaleLevels = [
  27294. // Format interval
  27295. ['hh:mm:ss', ONE_SECOND], // 1s
  27296. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  27297. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  27298. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  27299. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  27300. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  27301. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  27302. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  27303. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  27304. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  27305. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  27306. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  27307. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  27308. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  27309. ['MM-dd\nyyyy', ONE_DAY], // 1d
  27310. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  27311. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  27312. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  27313. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  27314. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  27315. ['week', ONE_DAY * 7], // 7d
  27316. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  27317. ['week', ONE_DAY * 14], // 2w
  27318. ['week', ONE_DAY * 21], // 3w
  27319. ['month', ONE_DAY * 31], // 1M
  27320. ['week', ONE_DAY * 42], // 6w
  27321. ['month', ONE_DAY * 62], // 2M
  27322. ['week', ONE_DAY * 42], // 10w
  27323. ['quarter', ONE_DAY * 380 / 4], // 3M
  27324. ['month', ONE_DAY * 31 * 4], // 4M
  27325. ['month', ONE_DAY * 31 * 5], // 5M
  27326. ['half-year', ONE_DAY * 380 / 2], // 6M
  27327. ['month', ONE_DAY * 31 * 8], // 8M
  27328. ['month', ONE_DAY * 31 * 10], // 10M
  27329. ['year', ONE_DAY * 380] // 1Y
  27330. ];
  27331. /**
  27332. * @param {module:echarts/model/Model}
  27333. * @return {module:echarts/scale/Time}
  27334. */
  27335. TimeScale.create = function (model) {
  27336. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  27337. };
  27338. /*
  27339. * Licensed to the Apache Software Foundation (ASF) under one
  27340. * or more contributor license agreements. See the NOTICE file
  27341. * distributed with this work for additional information
  27342. * regarding copyright ownership. The ASF licenses this file
  27343. * to you under the Apache License, Version 2.0 (the
  27344. * "License"); you may not use this file except in compliance
  27345. * with the License. You may obtain a copy of the License at
  27346. *
  27347. * http://www.apache.org/licenses/LICENSE-2.0
  27348. *
  27349. * Unless required by applicable law or agreed to in writing,
  27350. * software distributed under the License is distributed on an
  27351. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27352. * KIND, either express or implied. See the License for the
  27353. * specific language governing permissions and limitations
  27354. * under the License.
  27355. */
  27356. /**
  27357. * Log scale
  27358. * @module echarts/scale/Log
  27359. */
  27360. // Use some method of IntervalScale
  27361. var scaleProto$1 = Scale.prototype;
  27362. var intervalScaleProto$1 = IntervalScale.prototype;
  27363. var getPrecisionSafe$1 = getPrecisionSafe;
  27364. var roundingErrorFix = round$1;
  27365. var mathFloor$1 = Math.floor;
  27366. var mathCeil$1 = Math.ceil;
  27367. var mathPow$1 = Math.pow;
  27368. var mathLog = Math.log;
  27369. var LogScale = Scale.extend({
  27370. type: 'log',
  27371. base: 10,
  27372. $constructor: function () {
  27373. Scale.apply(this, arguments);
  27374. this._originalScale = new IntervalScale();
  27375. },
  27376. /**
  27377. * @return {Array.<number>}
  27378. */
  27379. getTicks: function () {
  27380. var originalScale = this._originalScale;
  27381. var extent = this._extent;
  27382. var originalExtent = originalScale.getExtent();
  27383. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  27384. var powVal = round$1(mathPow$1(this.base, val));
  27385. // Fix #4158
  27386. powVal = (val === extent[0] && originalScale.__fixMin)
  27387. ? fixRoundingError(powVal, originalExtent[0])
  27388. : powVal;
  27389. powVal = (val === extent[1] && originalScale.__fixMax)
  27390. ? fixRoundingError(powVal, originalExtent[1])
  27391. : powVal;
  27392. return powVal;
  27393. }, this);
  27394. },
  27395. /**
  27396. * @param {number} val
  27397. * @return {string}
  27398. */
  27399. getLabel: intervalScaleProto$1.getLabel,
  27400. /**
  27401. * @param {number} val
  27402. * @return {number}
  27403. */
  27404. scale: function (val) {
  27405. val = scaleProto$1.scale.call(this, val);
  27406. return mathPow$1(this.base, val);
  27407. },
  27408. /**
  27409. * @param {number} start
  27410. * @param {number} end
  27411. */
  27412. setExtent: function (start, end) {
  27413. var base = this.base;
  27414. start = mathLog(start) / mathLog(base);
  27415. end = mathLog(end) / mathLog(base);
  27416. intervalScaleProto$1.setExtent.call(this, start, end);
  27417. },
  27418. /**
  27419. * @return {number} end
  27420. */
  27421. getExtent: function () {
  27422. var base = this.base;
  27423. var extent = scaleProto$1.getExtent.call(this);
  27424. extent[0] = mathPow$1(base, extent[0]);
  27425. extent[1] = mathPow$1(base, extent[1]);
  27426. // Fix #4158
  27427. var originalScale = this._originalScale;
  27428. var originalExtent = originalScale.getExtent();
  27429. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  27430. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  27431. return extent;
  27432. },
  27433. /**
  27434. * @param {Array.<number>} extent
  27435. */
  27436. unionExtent: function (extent) {
  27437. this._originalScale.unionExtent(extent);
  27438. var base = this.base;
  27439. extent[0] = mathLog(extent[0]) / mathLog(base);
  27440. extent[1] = mathLog(extent[1]) / mathLog(base);
  27441. scaleProto$1.unionExtent.call(this, extent);
  27442. },
  27443. /**
  27444. * @override
  27445. */
  27446. unionExtentFromData: function (data, dim) {
  27447. // TODO
  27448. // filter value that <= 0
  27449. this.unionExtent(data.getApproximateExtent(dim));
  27450. },
  27451. /**
  27452. * Update interval and extent of intervals for nice ticks
  27453. * @param {number} [approxTickNum = 10] Given approx tick number
  27454. */
  27455. niceTicks: function (approxTickNum) {
  27456. approxTickNum = approxTickNum || 10;
  27457. var extent = this._extent;
  27458. var span = extent[1] - extent[0];
  27459. if (span === Infinity || span <= 0) {
  27460. return;
  27461. }
  27462. var interval = quantity(span);
  27463. var err = approxTickNum / span * interval;
  27464. // Filter ticks to get closer to the desired count.
  27465. if (err <= 0.5) {
  27466. interval *= 10;
  27467. }
  27468. // Interval should be integer
  27469. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  27470. interval *= 10;
  27471. }
  27472. var niceExtent = [
  27473. round$1(mathCeil$1(extent[0] / interval) * interval),
  27474. round$1(mathFloor$1(extent[1] / interval) * interval)
  27475. ];
  27476. this._interval = interval;
  27477. this._niceExtent = niceExtent;
  27478. },
  27479. /**
  27480. * Nice extent.
  27481. * @override
  27482. */
  27483. niceExtent: function (opt) {
  27484. intervalScaleProto$1.niceExtent.call(this, opt);
  27485. var originalScale = this._originalScale;
  27486. originalScale.__fixMin = opt.fixMin;
  27487. originalScale.__fixMax = opt.fixMax;
  27488. }
  27489. });
  27490. each$1(['contain', 'normalize'], function (methodName) {
  27491. LogScale.prototype[methodName] = function (val) {
  27492. val = mathLog(val) / mathLog(this.base);
  27493. return scaleProto$1[methodName].call(this, val);
  27494. };
  27495. });
  27496. LogScale.create = function () {
  27497. return new LogScale();
  27498. };
  27499. function fixRoundingError(val, originalVal) {
  27500. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  27501. }
  27502. /*
  27503. * Licensed to the Apache Software Foundation (ASF) under one
  27504. * or more contributor license agreements. See the NOTICE file
  27505. * distributed with this work for additional information
  27506. * regarding copyright ownership. The ASF licenses this file
  27507. * to you under the Apache License, Version 2.0 (the
  27508. * "License"); you may not use this file except in compliance
  27509. * with the License. You may obtain a copy of the License at
  27510. *
  27511. * http://www.apache.org/licenses/LICENSE-2.0
  27512. *
  27513. * Unless required by applicable law or agreed to in writing,
  27514. * software distributed under the License is distributed on an
  27515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27516. * KIND, either express or implied. See the License for the
  27517. * specific language governing permissions and limitations
  27518. * under the License.
  27519. */
  27520. /**
  27521. * Get axis scale extent before niced.
  27522. * Item of returned array can only be number (including Infinity and NaN).
  27523. */
  27524. function getScaleExtent(scale, model) {
  27525. var scaleType = scale.type;
  27526. var min = model.getMin();
  27527. var max = model.getMax();
  27528. var fixMin = min != null;
  27529. var fixMax = max != null;
  27530. var originalExtent = scale.getExtent();
  27531. var axisDataLen;
  27532. var boundaryGap;
  27533. var span;
  27534. if (scaleType === 'ordinal') {
  27535. axisDataLen = model.getCategories().length;
  27536. }
  27537. else {
  27538. boundaryGap = model.get('boundaryGap');
  27539. if (!isArray(boundaryGap)) {
  27540. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  27541. }
  27542. if (typeof boundaryGap[0] === 'boolean') {
  27543. if (__DEV__) {
  27544. console.warn('Boolean type for boundaryGap is only '
  27545. + 'allowed for ordinal axis. Please use string in '
  27546. + 'percentage instead, e.g., "20%". Currently, '
  27547. + 'boundaryGap is set to be 0.');
  27548. }
  27549. boundaryGap = [0, 0];
  27550. }
  27551. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  27552. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  27553. span = (originalExtent[1] - originalExtent[0])
  27554. || Math.abs(originalExtent[0]);
  27555. }
  27556. // Notice: When min/max is not set (that is, when there are null/undefined,
  27557. // which is the most common case), these cases should be ensured:
  27558. // (1) For 'ordinal', show all axis.data.
  27559. // (2) For others:
  27560. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  27561. // disabled).
  27562. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  27563. // be the result that originalExtent enlarged by boundaryGap.
  27564. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  27565. // FIXME
  27566. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  27567. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  27568. // that the results processed by boundaryGap are positive/negative?
  27569. if (min == null) {
  27570. min = scaleType === 'ordinal'
  27571. ? (axisDataLen ? 0 : NaN)
  27572. : originalExtent[0] - boundaryGap[0] * span;
  27573. }
  27574. if (max == null) {
  27575. max = scaleType === 'ordinal'
  27576. ? (axisDataLen ? axisDataLen - 1 : NaN)
  27577. : originalExtent[1] + boundaryGap[1] * span;
  27578. }
  27579. if (min === 'dataMin') {
  27580. min = originalExtent[0];
  27581. }
  27582. else if (typeof min === 'function') {
  27583. min = min({
  27584. min: originalExtent[0],
  27585. max: originalExtent[1]
  27586. });
  27587. }
  27588. if (max === 'dataMax') {
  27589. max = originalExtent[1];
  27590. }
  27591. else if (typeof max === 'function') {
  27592. max = max({
  27593. min: originalExtent[0],
  27594. max: originalExtent[1]
  27595. });
  27596. }
  27597. (min == null || !isFinite(min)) && (min = NaN);
  27598. (max == null || !isFinite(max)) && (max = NaN);
  27599. scale.setBlank(
  27600. eqNaN(min)
  27601. || eqNaN(max)
  27602. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  27603. );
  27604. // Evaluate if axis needs cross zero
  27605. if (model.getNeedCrossZero()) {
  27606. // Axis is over zero and min is not set
  27607. if (min > 0 && max > 0 && !fixMin) {
  27608. min = 0;
  27609. }
  27610. // Axis is under zero and max is not set
  27611. if (min < 0 && max < 0 && !fixMax) {
  27612. max = 0;
  27613. }
  27614. }
  27615. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  27616. // is base axis
  27617. // FIXME
  27618. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  27619. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  27620. // Should not depend on series type `bar`?
  27621. // (3) Fix that might overlap when using dataZoom.
  27622. // (4) Consider other chart types using `barGrid`?
  27623. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  27624. var ecModel = model.ecModel;
  27625. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  27626. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  27627. var isBaseAxisAndHasBarSeries;
  27628. each$1(barSeriesModels, function (seriesModel) {
  27629. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  27630. });
  27631. if (isBaseAxisAndHasBarSeries) {
  27632. // Calculate placement of bars on axis
  27633. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  27634. // Adjust axis min and max to account for overflow
  27635. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  27636. min = adjustedScale.min;
  27637. max = adjustedScale.max;
  27638. }
  27639. }
  27640. return [min, max];
  27641. }
  27642. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  27643. // Get Axis Length
  27644. var axisExtent = model.axis.getExtent();
  27645. var axisLength = axisExtent[1] - axisExtent[0];
  27646. // Get bars on current base axis and calculate min and max overflow
  27647. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  27648. if (barsOnCurrentAxis === undefined) {
  27649. return {min: min, max: max};
  27650. }
  27651. var minOverflow = Infinity;
  27652. each$1(barsOnCurrentAxis, function (item) {
  27653. minOverflow = Math.min(item.offset, minOverflow);
  27654. });
  27655. var maxOverflow = -Infinity;
  27656. each$1(barsOnCurrentAxis, function (item) {
  27657. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  27658. });
  27659. minOverflow = Math.abs(minOverflow);
  27660. maxOverflow = Math.abs(maxOverflow);
  27661. var totalOverFlow = minOverflow + maxOverflow;
  27662. // Calulate required buffer based on old range and overflow
  27663. var oldRange = max - min;
  27664. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  27665. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  27666. max += overflowBuffer * (maxOverflow / totalOverFlow);
  27667. min -= overflowBuffer * (minOverflow / totalOverFlow);
  27668. return {min: min, max: max};
  27669. }
  27670. function niceScaleExtent(scale, model) {
  27671. var extent = getScaleExtent(scale, model);
  27672. var fixMin = model.getMin() != null;
  27673. var fixMax = model.getMax() != null;
  27674. var splitNumber = model.get('splitNumber');
  27675. if (scale.type === 'log') {
  27676. scale.base = model.get('logBase');
  27677. }
  27678. var scaleType = scale.type;
  27679. scale.setExtent(extent[0], extent[1]);
  27680. scale.niceExtent({
  27681. splitNumber: splitNumber,
  27682. fixMin: fixMin,
  27683. fixMax: fixMax,
  27684. minInterval: (scaleType === 'interval' || scaleType === 'time')
  27685. ? model.get('minInterval') : null,
  27686. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  27687. ? model.get('maxInterval') : null
  27688. });
  27689. // If some one specified the min, max. And the default calculated interval
  27690. // is not good enough. He can specify the interval. It is often appeared
  27691. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  27692. // to be 60.
  27693. // FIXME
  27694. var interval = model.get('interval');
  27695. if (interval != null) {
  27696. scale.setInterval && scale.setInterval(interval);
  27697. }
  27698. }
  27699. /**
  27700. * @param {module:echarts/model/Model} model
  27701. * @param {string} [axisType] Default retrieve from model.type
  27702. * @return {module:echarts/scale/*}
  27703. */
  27704. function createScaleByModel(model, axisType) {
  27705. axisType = axisType || model.get('type');
  27706. if (axisType) {
  27707. switch (axisType) {
  27708. // Buildin scale
  27709. case 'category':
  27710. return new OrdinalScale(
  27711. model.getOrdinalMeta
  27712. ? model.getOrdinalMeta()
  27713. : model.getCategories(),
  27714. [Infinity, -Infinity]
  27715. );
  27716. case 'value':
  27717. return new IntervalScale();
  27718. // Extended scale, like time and log
  27719. default:
  27720. return (Scale.getClass(axisType) || IntervalScale).create(model);
  27721. }
  27722. }
  27723. }
  27724. /**
  27725. * Check if the axis corss 0
  27726. */
  27727. function ifAxisCrossZero(axis) {
  27728. var dataExtent = axis.scale.getExtent();
  27729. var min = dataExtent[0];
  27730. var max = dataExtent[1];
  27731. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  27732. }
  27733. /**
  27734. * @param {module:echarts/coord/Axis} axis
  27735. * @return {Function} Label formatter function.
  27736. * param: {number} tickValue,
  27737. * param: {number} idx, the index in all ticks.
  27738. * If category axis, this param is not requied.
  27739. * return: {string} label string.
  27740. */
  27741. function makeLabelFormatter(axis) {
  27742. var labelFormatter = axis.getLabelModel().get('formatter');
  27743. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  27744. if (typeof labelFormatter === 'string') {
  27745. labelFormatter = (function (tpl) {
  27746. return function (val) {
  27747. return tpl.replace('{value}', val != null ? val : '');
  27748. };
  27749. })(labelFormatter);
  27750. // Consider empty array
  27751. return labelFormatter;
  27752. }
  27753. else if (typeof labelFormatter === 'function') {
  27754. return function (tickValue, idx) {
  27755. // The original intention of `idx` is "the index of the tick in all ticks".
  27756. // But the previous implementation of category axis do not consider the
  27757. // `axisLabel.interval`, which cause that, for example, the `interval` is
  27758. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  27759. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  27760. // the definition here for back compatibility.
  27761. if (categoryTickStart != null) {
  27762. idx = tickValue - categoryTickStart;
  27763. }
  27764. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  27765. };
  27766. }
  27767. else {
  27768. return function (tick) {
  27769. return axis.scale.getLabel(tick);
  27770. };
  27771. }
  27772. }
  27773. function getAxisRawValue(axis, value) {
  27774. // In category axis with data zoom, tick is not the original
  27775. // index of axis.data. So tick should not be exposed to user
  27776. // in category axis.
  27777. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  27778. }
  27779. /**
  27780. * @param {module:echarts/coord/Axis} axis
  27781. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  27782. */
  27783. function estimateLabelUnionRect(axis) {
  27784. var axisModel = axis.model;
  27785. var scale = axis.scale;
  27786. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  27787. return;
  27788. }
  27789. var isCategory = axis.type === 'category';
  27790. var realNumberScaleTicks;
  27791. var tickCount;
  27792. var categoryScaleExtent = scale.getExtent();
  27793. // Optimize for large category data, avoid call `getTicks()`.
  27794. if (isCategory) {
  27795. tickCount = scale.count();
  27796. }
  27797. else {
  27798. realNumberScaleTicks = scale.getTicks();
  27799. tickCount = realNumberScaleTicks.length;
  27800. }
  27801. var axisLabelModel = axis.getLabelModel();
  27802. var labelFormatter = makeLabelFormatter(axis);
  27803. var rect;
  27804. var step = 1;
  27805. // Simple optimization for large amount of labels
  27806. if (tickCount > 40) {
  27807. step = Math.ceil(tickCount / 40);
  27808. }
  27809. for (var i = 0; i < tickCount; i += step) {
  27810. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  27811. var label = labelFormatter(tickValue);
  27812. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  27813. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  27814. rect ? rect.union(singleRect) : (rect = singleRect);
  27815. }
  27816. return rect;
  27817. }
  27818. function rotateTextRect(textRect, rotate) {
  27819. var rotateRadians = rotate * Math.PI / 180;
  27820. var boundingBox = textRect.plain();
  27821. var beforeWidth = boundingBox.width;
  27822. var beforeHeight = boundingBox.height;
  27823. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  27824. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  27825. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  27826. return rotatedRect;
  27827. }
  27828. /*
  27829. * Licensed to the Apache Software Foundation (ASF) under one
  27830. * or more contributor license agreements. See the NOTICE file
  27831. * distributed with this work for additional information
  27832. * regarding copyright ownership. The ASF licenses this file
  27833. * to you under the Apache License, Version 2.0 (the
  27834. * "License"); you may not use this file except in compliance
  27835. * with the License. You may obtain a copy of the License at
  27836. *
  27837. * http://www.apache.org/licenses/LICENSE-2.0
  27838. *
  27839. * Unless required by applicable law or agreed to in writing,
  27840. * software distributed under the License is distributed on an
  27841. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27842. * KIND, either express or implied. See the License for the
  27843. * specific language governing permissions and limitations
  27844. * under the License.
  27845. */
  27846. var axisModelCommonMixin = {
  27847. /**
  27848. * @param {boolean} origin
  27849. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  27850. */
  27851. getMin: function (origin) {
  27852. var option = this.option;
  27853. var min = (!origin && option.rangeStart != null)
  27854. ? option.rangeStart : option.min;
  27855. if (this.axis
  27856. && min != null
  27857. && min !== 'dataMin'
  27858. && typeof min !== 'function'
  27859. && !eqNaN(min)
  27860. ) {
  27861. min = this.axis.scale.parse(min);
  27862. }
  27863. return min;
  27864. },
  27865. /**
  27866. * @param {boolean} origin
  27867. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  27868. */
  27869. getMax: function (origin) {
  27870. var option = this.option;
  27871. var max = (!origin && option.rangeEnd != null)
  27872. ? option.rangeEnd : option.max;
  27873. if (this.axis
  27874. && max != null
  27875. && max !== 'dataMax'
  27876. && typeof max !== 'function'
  27877. && !eqNaN(max)
  27878. ) {
  27879. max = this.axis.scale.parse(max);
  27880. }
  27881. return max;
  27882. },
  27883. /**
  27884. * @return {boolean}
  27885. */
  27886. getNeedCrossZero: function () {
  27887. var option = this.option;
  27888. return (option.rangeStart != null || option.rangeEnd != null)
  27889. ? false : !option.scale;
  27890. },
  27891. /**
  27892. * Should be implemented by each axis model if necessary.
  27893. * @return {module:echarts/model/Component} coordinate system model
  27894. */
  27895. getCoordSysModel: noop,
  27896. /**
  27897. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  27898. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  27899. */
  27900. setRange: function (rangeStart, rangeEnd) {
  27901. this.option.rangeStart = rangeStart;
  27902. this.option.rangeEnd = rangeEnd;
  27903. },
  27904. /**
  27905. * Reset range
  27906. */
  27907. resetRange: function () {
  27908. // rangeStart and rangeEnd is readonly.
  27909. this.option.rangeStart = this.option.rangeEnd = null;
  27910. }
  27911. };
  27912. /*
  27913. * Licensed to the Apache Software Foundation (ASF) under one
  27914. * or more contributor license agreements. See the NOTICE file
  27915. * distributed with this work for additional information
  27916. * regarding copyright ownership. The ASF licenses this file
  27917. * to you under the Apache License, Version 2.0 (the
  27918. * "License"); you may not use this file except in compliance
  27919. * with the License. You may obtain a copy of the License at
  27920. *
  27921. * http://www.apache.org/licenses/LICENSE-2.0
  27922. *
  27923. * Unless required by applicable law or agreed to in writing,
  27924. * software distributed under the License is distributed on an
  27925. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27926. * KIND, either express or implied. See the License for the
  27927. * specific language governing permissions and limitations
  27928. * under the License.
  27929. */
  27930. // Symbol factory
  27931. /**
  27932. * Triangle shape
  27933. * @inner
  27934. */
  27935. var Triangle = extendShape({
  27936. type: 'triangle',
  27937. shape: {
  27938. cx: 0,
  27939. cy: 0,
  27940. width: 0,
  27941. height: 0
  27942. },
  27943. buildPath: function (path, shape) {
  27944. var cx = shape.cx;
  27945. var cy = shape.cy;
  27946. var width = shape.width / 2;
  27947. var height = shape.height / 2;
  27948. path.moveTo(cx, cy - height);
  27949. path.lineTo(cx + width, cy + height);
  27950. path.lineTo(cx - width, cy + height);
  27951. path.closePath();
  27952. }
  27953. });
  27954. /**
  27955. * Diamond shape
  27956. * @inner
  27957. */
  27958. var Diamond = extendShape({
  27959. type: 'diamond',
  27960. shape: {
  27961. cx: 0,
  27962. cy: 0,
  27963. width: 0,
  27964. height: 0
  27965. },
  27966. buildPath: function (path, shape) {
  27967. var cx = shape.cx;
  27968. var cy = shape.cy;
  27969. var width = shape.width / 2;
  27970. var height = shape.height / 2;
  27971. path.moveTo(cx, cy - height);
  27972. path.lineTo(cx + width, cy);
  27973. path.lineTo(cx, cy + height);
  27974. path.lineTo(cx - width, cy);
  27975. path.closePath();
  27976. }
  27977. });
  27978. /**
  27979. * Pin shape
  27980. * @inner
  27981. */
  27982. var Pin = extendShape({
  27983. type: 'pin',
  27984. shape: {
  27985. // x, y on the cusp
  27986. x: 0,
  27987. y: 0,
  27988. width: 0,
  27989. height: 0
  27990. },
  27991. buildPath: function (path, shape) {
  27992. var x = shape.x;
  27993. var y = shape.y;
  27994. var w = shape.width / 5 * 3;
  27995. // Height must be larger than width
  27996. var h = Math.max(w, shape.height);
  27997. var r = w / 2;
  27998. // Dist on y with tangent point and circle center
  27999. var dy = r * r / (h - r);
  28000. var cy = y - h + r + dy;
  28001. var angle = Math.asin(dy / r);
  28002. // Dist on x with tangent point and circle center
  28003. var dx = Math.cos(angle) * r;
  28004. var tanX = Math.sin(angle);
  28005. var tanY = Math.cos(angle);
  28006. var cpLen = r * 0.6;
  28007. var cpLen2 = r * 0.7;
  28008. path.moveTo(x - dx, cy + dy);
  28009. path.arc(
  28010. x, cy, r,
  28011. Math.PI - angle,
  28012. Math.PI * 2 + angle
  28013. );
  28014. path.bezierCurveTo(
  28015. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  28016. x, y - cpLen2,
  28017. x, y
  28018. );
  28019. path.bezierCurveTo(
  28020. x, y - cpLen2,
  28021. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  28022. x - dx, cy + dy
  28023. );
  28024. path.closePath();
  28025. }
  28026. });
  28027. /**
  28028. * Arrow shape
  28029. * @inner
  28030. */
  28031. var Arrow = extendShape({
  28032. type: 'arrow',
  28033. shape: {
  28034. x: 0,
  28035. y: 0,
  28036. width: 0,
  28037. height: 0
  28038. },
  28039. buildPath: function (ctx, shape) {
  28040. var height = shape.height;
  28041. var width = shape.width;
  28042. var x = shape.x;
  28043. var y = shape.y;
  28044. var dx = width / 3 * 2;
  28045. ctx.moveTo(x, y);
  28046. ctx.lineTo(x + dx, y + height);
  28047. ctx.lineTo(x, y + height / 4 * 3);
  28048. ctx.lineTo(x - dx, y + height);
  28049. ctx.lineTo(x, y);
  28050. ctx.closePath();
  28051. }
  28052. });
  28053. /**
  28054. * Map of path contructors
  28055. * @type {Object.<string, module:zrender/graphic/Path>}
  28056. */
  28057. var symbolCtors = {
  28058. line: Line,
  28059. rect: Rect,
  28060. roundRect: Rect,
  28061. square: Rect,
  28062. circle: Circle,
  28063. diamond: Diamond,
  28064. pin: Pin,
  28065. arrow: Arrow,
  28066. triangle: Triangle
  28067. };
  28068. var symbolShapeMakers = {
  28069. line: function (x, y, w, h, shape) {
  28070. // FIXME
  28071. shape.x1 = x;
  28072. shape.y1 = y + h / 2;
  28073. shape.x2 = x + w;
  28074. shape.y2 = y + h / 2;
  28075. },
  28076. rect: function (x, y, w, h, shape) {
  28077. shape.x = x;
  28078. shape.y = y;
  28079. shape.width = w;
  28080. shape.height = h;
  28081. },
  28082. roundRect: function (x, y, w, h, shape) {
  28083. shape.x = x;
  28084. shape.y = y;
  28085. shape.width = w;
  28086. shape.height = h;
  28087. shape.r = Math.min(w, h) / 4;
  28088. },
  28089. square: function (x, y, w, h, shape) {
  28090. var size = Math.min(w, h);
  28091. shape.x = x;
  28092. shape.y = y;
  28093. shape.width = size;
  28094. shape.height = size;
  28095. },
  28096. circle: function (x, y, w, h, shape) {
  28097. // Put circle in the center of square
  28098. shape.cx = x + w / 2;
  28099. shape.cy = y + h / 2;
  28100. shape.r = Math.min(w, h) / 2;
  28101. },
  28102. diamond: function (x, y, w, h, shape) {
  28103. shape.cx = x + w / 2;
  28104. shape.cy = y + h / 2;
  28105. shape.width = w;
  28106. shape.height = h;
  28107. },
  28108. pin: function (x, y, w, h, shape) {
  28109. shape.x = x + w / 2;
  28110. shape.y = y + h / 2;
  28111. shape.width = w;
  28112. shape.height = h;
  28113. },
  28114. arrow: function (x, y, w, h, shape) {
  28115. shape.x = x + w / 2;
  28116. shape.y = y + h / 2;
  28117. shape.width = w;
  28118. shape.height = h;
  28119. },
  28120. triangle: function (x, y, w, h, shape) {
  28121. shape.cx = x + w / 2;
  28122. shape.cy = y + h / 2;
  28123. shape.width = w;
  28124. shape.height = h;
  28125. }
  28126. };
  28127. var symbolBuildProxies = {};
  28128. each$1(symbolCtors, function (Ctor, name) {
  28129. symbolBuildProxies[name] = new Ctor();
  28130. });
  28131. var SymbolClz = extendShape({
  28132. type: 'symbol',
  28133. shape: {
  28134. symbolType: '',
  28135. x: 0,
  28136. y: 0,
  28137. width: 0,
  28138. height: 0
  28139. },
  28140. beforeBrush: function () {
  28141. var style = this.style;
  28142. var shape = this.shape;
  28143. // FIXME
  28144. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  28145. style.textPosition = ['50%', '40%'];
  28146. style.textAlign = 'center';
  28147. style.textVerticalAlign = 'middle';
  28148. }
  28149. },
  28150. buildPath: function (ctx, shape, inBundle) {
  28151. var symbolType = shape.symbolType;
  28152. var proxySymbol = symbolBuildProxies[symbolType];
  28153. if (shape.symbolType !== 'none') {
  28154. if (!proxySymbol) {
  28155. // Default rect
  28156. symbolType = 'rect';
  28157. proxySymbol = symbolBuildProxies[symbolType];
  28158. }
  28159. symbolShapeMakers[symbolType](
  28160. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  28161. );
  28162. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  28163. }
  28164. }
  28165. });
  28166. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  28167. function symbolPathSetColor(color, innerColor) {
  28168. if (this.type !== 'image') {
  28169. var symbolStyle = this.style;
  28170. var symbolShape = this.shape;
  28171. if (symbolShape && symbolShape.symbolType === 'line') {
  28172. symbolStyle.stroke = color;
  28173. }
  28174. else if (this.__isEmptyBrush) {
  28175. symbolStyle.stroke = color;
  28176. symbolStyle.fill = innerColor || '#fff';
  28177. }
  28178. else {
  28179. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  28180. symbolStyle.fill && (symbolStyle.fill = color);
  28181. symbolStyle.stroke && (symbolStyle.stroke = color);
  28182. }
  28183. this.dirty(false);
  28184. }
  28185. }
  28186. /**
  28187. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  28188. * @param {string} symbolType
  28189. * @param {number} x
  28190. * @param {number} y
  28191. * @param {number} w
  28192. * @param {number} h
  28193. * @param {string} color
  28194. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  28195. * for path and image only.
  28196. */
  28197. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  28198. // TODO Support image object, DynamicImage.
  28199. var isEmpty = symbolType.indexOf('empty') === 0;
  28200. if (isEmpty) {
  28201. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  28202. }
  28203. var symbolPath;
  28204. if (symbolType.indexOf('image://') === 0) {
  28205. symbolPath = makeImage(
  28206. symbolType.slice(8),
  28207. new BoundingRect(x, y, w, h),
  28208. keepAspect ? 'center' : 'cover'
  28209. );
  28210. }
  28211. else if (symbolType.indexOf('path://') === 0) {
  28212. symbolPath = makePath(
  28213. symbolType.slice(7),
  28214. {},
  28215. new BoundingRect(x, y, w, h),
  28216. keepAspect ? 'center' : 'cover'
  28217. );
  28218. }
  28219. else {
  28220. symbolPath = new SymbolClz({
  28221. shape: {
  28222. symbolType: symbolType,
  28223. x: x,
  28224. y: y,
  28225. width: w,
  28226. height: h
  28227. }
  28228. });
  28229. }
  28230. symbolPath.__isEmptyBrush = isEmpty;
  28231. symbolPath.setColor = symbolPathSetColor;
  28232. symbolPath.setColor(color);
  28233. return symbolPath;
  28234. }
  28235. /*
  28236. * Licensed to the Apache Software Foundation (ASF) under one
  28237. * or more contributor license agreements. See the NOTICE file
  28238. * distributed with this work for additional information
  28239. * regarding copyright ownership. The ASF licenses this file
  28240. * to you under the Apache License, Version 2.0 (the
  28241. * "License"); you may not use this file except in compliance
  28242. * with the License. You may obtain a copy of the License at
  28243. *
  28244. * http://www.apache.org/licenses/LICENSE-2.0
  28245. *
  28246. * Unless required by applicable law or agreed to in writing,
  28247. * software distributed under the License is distributed on an
  28248. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28249. * KIND, either express or implied. See the License for the
  28250. * specific language governing permissions and limitations
  28251. * under the License.
  28252. */
  28253. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  28254. /**
  28255. * Create a muti dimension List structure from seriesModel.
  28256. * @param {module:echarts/model/Model} seriesModel
  28257. * @return {module:echarts/data/List} list
  28258. */
  28259. function createList(seriesModel) {
  28260. return createListFromArray(seriesModel.getSource(), seriesModel);
  28261. }
  28262. var dataStack$1 = {
  28263. isDimensionStacked: isDimensionStacked,
  28264. enableDataStack: enableDataStack,
  28265. getStackedDimension: getStackedDimension
  28266. };
  28267. /**
  28268. * Create scale
  28269. * @param {Array.<number>} dataExtent
  28270. * @param {Object|module:echarts/Model} option
  28271. */
  28272. function createScale(dataExtent, option) {
  28273. var axisModel = option;
  28274. if (!Model.isInstance(option)) {
  28275. axisModel = new Model(option);
  28276. mixin(axisModel, axisModelCommonMixin);
  28277. }
  28278. var scale = createScaleByModel(axisModel);
  28279. scale.setExtent(dataExtent[0], dataExtent[1]);
  28280. niceScaleExtent(scale, axisModel);
  28281. return scale;
  28282. }
  28283. /**
  28284. * Mixin common methods to axis model,
  28285. *
  28286. * Inlcude methods
  28287. * `getFormattedLabels() => Array.<string>`
  28288. * `getCategories() => Array.<string>`
  28289. * `getMin(origin: boolean) => number`
  28290. * `getMax(origin: boolean) => number`
  28291. * `getNeedCrossZero() => boolean`
  28292. * `setRange(start: number, end: number)`
  28293. * `resetRange()`
  28294. */
  28295. function mixinAxisModelCommonMethods(Model$$1) {
  28296. mixin(Model$$1, axisModelCommonMixin);
  28297. }
  28298. var helper = (Object.freeze || Object)({
  28299. createList: createList,
  28300. getLayoutRect: getLayoutRect,
  28301. dataStack: dataStack$1,
  28302. createScale: createScale,
  28303. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  28304. completeDimensions: completeDimensions,
  28305. createDimensions: createDimensions,
  28306. createSymbol: createSymbol
  28307. });
  28308. var EPSILON$3 = 1e-8;
  28309. function isAroundEqual$1(a, b) {
  28310. return Math.abs(a - b) < EPSILON$3;
  28311. }
  28312. function contain$1(points, x, y) {
  28313. var w = 0;
  28314. var p = points[0];
  28315. if (!p) {
  28316. return false;
  28317. }
  28318. for (var i = 1; i < points.length; i++) {
  28319. var p2 = points[i];
  28320. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  28321. p = p2;
  28322. }
  28323. // Close polygon
  28324. var p0 = points[0];
  28325. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  28326. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  28327. }
  28328. return w !== 0;
  28329. }
  28330. /*
  28331. * Licensed to the Apache Software Foundation (ASF) under one
  28332. * or more contributor license agreements. See the NOTICE file
  28333. * distributed with this work for additional information
  28334. * regarding copyright ownership. The ASF licenses this file
  28335. * to you under the Apache License, Version 2.0 (the
  28336. * "License"); you may not use this file except in compliance
  28337. * with the License. You may obtain a copy of the License at
  28338. *
  28339. * http://www.apache.org/licenses/LICENSE-2.0
  28340. *
  28341. * Unless required by applicable law or agreed to in writing,
  28342. * software distributed under the License is distributed on an
  28343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28344. * KIND, either express or implied. See the License for the
  28345. * specific language governing permissions and limitations
  28346. * under the License.
  28347. */
  28348. /**
  28349. * @module echarts/coord/geo/Region
  28350. */
  28351. /**
  28352. * @param {string} name
  28353. * @param {Array} geometries
  28354. * @param {Array.<number>} cp
  28355. */
  28356. function Region(name, geometries, cp) {
  28357. /**
  28358. * @type {string}
  28359. * @readOnly
  28360. */
  28361. this.name = name;
  28362. /**
  28363. * @type {Array.<Array>}
  28364. * @readOnly
  28365. */
  28366. this.geometries = geometries;
  28367. if (!cp) {
  28368. var rect = this.getBoundingRect();
  28369. cp = [
  28370. rect.x + rect.width / 2,
  28371. rect.y + rect.height / 2
  28372. ];
  28373. }
  28374. else {
  28375. cp = [cp[0], cp[1]];
  28376. }
  28377. /**
  28378. * @type {Array.<number>}
  28379. */
  28380. this.center = cp;
  28381. }
  28382. Region.prototype = {
  28383. constructor: Region,
  28384. properties: null,
  28385. /**
  28386. * @return {module:zrender/core/BoundingRect}
  28387. */
  28388. getBoundingRect: function () {
  28389. var rect = this._rect;
  28390. if (rect) {
  28391. return rect;
  28392. }
  28393. var MAX_NUMBER = Number.MAX_VALUE;
  28394. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  28395. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  28396. var min2 = [];
  28397. var max2 = [];
  28398. var geometries = this.geometries;
  28399. for (var i = 0; i < geometries.length; i++) {
  28400. // Only support polygon
  28401. if (geometries[i].type !== 'polygon') {
  28402. continue;
  28403. }
  28404. // Doesn't consider hole
  28405. var exterior = geometries[i].exterior;
  28406. fromPoints(exterior, min2, max2);
  28407. min(min$$1, min$$1, min2);
  28408. max(max$$1, max$$1, max2);
  28409. }
  28410. // No data
  28411. if (i === 0) {
  28412. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  28413. }
  28414. return (this._rect = new BoundingRect(
  28415. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  28416. ));
  28417. },
  28418. /**
  28419. * @param {<Array.<number>} coord
  28420. * @return {boolean}
  28421. */
  28422. contain: function (coord) {
  28423. var rect = this.getBoundingRect();
  28424. var geometries = this.geometries;
  28425. if (!rect.contain(coord[0], coord[1])) {
  28426. return false;
  28427. }
  28428. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  28429. // Only support polygon.
  28430. if (geometries[i].type !== 'polygon') {
  28431. continue;
  28432. }
  28433. var exterior = geometries[i].exterior;
  28434. var interiors = geometries[i].interiors;
  28435. if (contain$1(exterior, coord[0], coord[1])) {
  28436. // Not in the region if point is in the hole.
  28437. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  28438. if (contain$1(interiors[k])) {
  28439. continue loopGeo;
  28440. }
  28441. }
  28442. return true;
  28443. }
  28444. }
  28445. return false;
  28446. },
  28447. transformTo: function (x, y, width, height) {
  28448. var rect = this.getBoundingRect();
  28449. var aspect = rect.width / rect.height;
  28450. if (!width) {
  28451. width = aspect * height;
  28452. }
  28453. else if (!height) {
  28454. height = width / aspect ;
  28455. }
  28456. var target = new BoundingRect(x, y, width, height);
  28457. var transform = rect.calculateTransform(target);
  28458. var geometries = this.geometries;
  28459. for (var i = 0; i < geometries.length; i++) {
  28460. // Only support polygon.
  28461. if (geometries[i].type !== 'polygon') {
  28462. continue;
  28463. }
  28464. var exterior = geometries[i].exterior;
  28465. var interiors = geometries[i].interiors;
  28466. for (var p = 0; p < exterior.length; p++) {
  28467. applyTransform(exterior[p], exterior[p], transform);
  28468. }
  28469. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  28470. for (var p = 0; p < interiors[h].length; p++) {
  28471. applyTransform(interiors[h][p], interiors[h][p], transform);
  28472. }
  28473. }
  28474. }
  28475. rect = this._rect;
  28476. rect.copy(target);
  28477. // Update center
  28478. this.center = [
  28479. rect.x + rect.width / 2,
  28480. rect.y + rect.height / 2
  28481. ];
  28482. }
  28483. };
  28484. /*
  28485. * Licensed to the Apache Software Foundation (ASF) under one
  28486. * or more contributor license agreements. See the NOTICE file
  28487. * distributed with this work for additional information
  28488. * regarding copyright ownership. The ASF licenses this file
  28489. * to you under the Apache License, Version 2.0 (the
  28490. * "License"); you may not use this file except in compliance
  28491. * with the License. You may obtain a copy of the License at
  28492. *
  28493. * http://www.apache.org/licenses/LICENSE-2.0
  28494. *
  28495. * Unless required by applicable law or agreed to in writing,
  28496. * software distributed under the License is distributed on an
  28497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28498. * KIND, either express or implied. See the License for the
  28499. * specific language governing permissions and limitations
  28500. * under the License.
  28501. */
  28502. /**
  28503. * Parse and decode geo json
  28504. * @module echarts/coord/geo/parseGeoJson
  28505. */
  28506. function decode(json) {
  28507. if (!json.UTF8Encoding) {
  28508. return json;
  28509. }
  28510. var encodeScale = json.UTF8Scale;
  28511. if (encodeScale == null) {
  28512. encodeScale = 1024;
  28513. }
  28514. var features = json.features;
  28515. for (var f = 0; f < features.length; f++) {
  28516. var feature = features[f];
  28517. var geometry = feature.geometry;
  28518. var coordinates = geometry.coordinates;
  28519. var encodeOffsets = geometry.encodeOffsets;
  28520. for (var c = 0; c < coordinates.length; c++) {
  28521. var coordinate = coordinates[c];
  28522. if (geometry.type === 'Polygon') {
  28523. coordinates[c] = decodePolygon(
  28524. coordinate,
  28525. encodeOffsets[c],
  28526. encodeScale
  28527. );
  28528. }
  28529. else if (geometry.type === 'MultiPolygon') {
  28530. for (var c2 = 0; c2 < coordinate.length; c2++) {
  28531. var polygon = coordinate[c2];
  28532. coordinate[c2] = decodePolygon(
  28533. polygon,
  28534. encodeOffsets[c][c2],
  28535. encodeScale
  28536. );
  28537. }
  28538. }
  28539. }
  28540. }
  28541. // Has been decoded
  28542. json.UTF8Encoding = false;
  28543. return json;
  28544. }
  28545. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  28546. var result = [];
  28547. var prevX = encodeOffsets[0];
  28548. var prevY = encodeOffsets[1];
  28549. for (var i = 0; i < coordinate.length; i += 2) {
  28550. var x = coordinate.charCodeAt(i) - 64;
  28551. var y = coordinate.charCodeAt(i + 1) - 64;
  28552. // ZigZag decoding
  28553. x = (x >> 1) ^ (-(x & 1));
  28554. y = (y >> 1) ^ (-(y & 1));
  28555. // Delta deocding
  28556. x += prevX;
  28557. y += prevY;
  28558. prevX = x;
  28559. prevY = y;
  28560. // Dequantize
  28561. result.push([x / encodeScale, y / encodeScale]);
  28562. }
  28563. return result;
  28564. }
  28565. /**
  28566. * @alias module:echarts/coord/geo/parseGeoJson
  28567. * @param {Object} geoJson
  28568. * @return {module:zrender/container/Group}
  28569. */
  28570. var parseGeoJson$1 = function (geoJson) {
  28571. decode(geoJson);
  28572. return map(filter(geoJson.features, function (featureObj) {
  28573. // Output of mapshaper may have geometry null
  28574. return featureObj.geometry
  28575. && featureObj.properties
  28576. && featureObj.geometry.coordinates.length > 0;
  28577. }), function (featureObj) {
  28578. var properties = featureObj.properties;
  28579. var geo = featureObj.geometry;
  28580. var coordinates = geo.coordinates;
  28581. var geometries = [];
  28582. if (geo.type === 'Polygon') {
  28583. geometries.push({
  28584. type: 'polygon',
  28585. // According to the GeoJSON specification.
  28586. // First must be exterior, and the rest are all interior(holes).
  28587. exterior: coordinates[0],
  28588. interiors: coordinates.slice(1)
  28589. });
  28590. }
  28591. if (geo.type === 'MultiPolygon') {
  28592. each$1(coordinates, function (item) {
  28593. if (item[0]) {
  28594. geometries.push({
  28595. type: 'polygon',
  28596. exterior: item[0],
  28597. interiors: item.slice(1)
  28598. });
  28599. }
  28600. });
  28601. }
  28602. var region = new Region(
  28603. properties.name,
  28604. geometries,
  28605. properties.cp
  28606. );
  28607. region.properties = properties;
  28608. return region;
  28609. });
  28610. };
  28611. /*
  28612. * Licensed to the Apache Software Foundation (ASF) under one
  28613. * or more contributor license agreements. See the NOTICE file
  28614. * distributed with this work for additional information
  28615. * regarding copyright ownership. The ASF licenses this file
  28616. * to you under the Apache License, Version 2.0 (the
  28617. * "License"); you may not use this file except in compliance
  28618. * with the License. You may obtain a copy of the License at
  28619. *
  28620. * http://www.apache.org/licenses/LICENSE-2.0
  28621. *
  28622. * Unless required by applicable law or agreed to in writing,
  28623. * software distributed under the License is distributed on an
  28624. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28625. * KIND, either express or implied. See the License for the
  28626. * specific language governing permissions and limitations
  28627. * under the License.
  28628. */
  28629. var inner$6 = makeInner();
  28630. /**
  28631. * @param {module:echats/coord/Axis} axis
  28632. * @return {Object} {
  28633. * labels: [{
  28634. * formattedLabel: string,
  28635. * rawLabel: string,
  28636. * tickValue: number
  28637. * }, ...],
  28638. * labelCategoryInterval: number
  28639. * }
  28640. */
  28641. function createAxisLabels(axis) {
  28642. // Only ordinal scale support tick interval
  28643. return axis.type === 'category'
  28644. ? makeCategoryLabels(axis)
  28645. : makeRealNumberLabels(axis);
  28646. }
  28647. /**
  28648. * @param {module:echats/coord/Axis} axis
  28649. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  28650. * @return {Object} {
  28651. * ticks: Array.<number>
  28652. * tickCategoryInterval: number
  28653. * }
  28654. */
  28655. function createAxisTicks(axis, tickModel) {
  28656. // Only ordinal scale support tick interval
  28657. return axis.type === 'category'
  28658. ? makeCategoryTicks(axis, tickModel)
  28659. : {ticks: axis.scale.getTicks()};
  28660. }
  28661. function makeCategoryLabels(axis) {
  28662. var labelModel = axis.getLabelModel();
  28663. var result = makeCategoryLabelsActually(axis, labelModel);
  28664. return (!labelModel.get('show') || axis.scale.isBlank())
  28665. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  28666. : result;
  28667. }
  28668. function makeCategoryLabelsActually(axis, labelModel) {
  28669. var labelsCache = getListCache(axis, 'labels');
  28670. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  28671. var result = listCacheGet(labelsCache, optionLabelInterval);
  28672. if (result) {
  28673. return result;
  28674. }
  28675. var labels;
  28676. var numericLabelInterval;
  28677. if (isFunction$1(optionLabelInterval)) {
  28678. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  28679. }
  28680. else {
  28681. numericLabelInterval = optionLabelInterval === 'auto'
  28682. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  28683. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  28684. }
  28685. // Cache to avoid calling interval function repeatly.
  28686. return listCacheSet(labelsCache, optionLabelInterval, {
  28687. labels: labels, labelCategoryInterval: numericLabelInterval
  28688. });
  28689. }
  28690. function makeCategoryTicks(axis, tickModel) {
  28691. var ticksCache = getListCache(axis, 'ticks');
  28692. var optionTickInterval = getOptionCategoryInterval(tickModel);
  28693. var result = listCacheGet(ticksCache, optionTickInterval);
  28694. if (result) {
  28695. return result;
  28696. }
  28697. var ticks;
  28698. var tickCategoryInterval;
  28699. // Optimize for the case that large category data and no label displayed,
  28700. // we should not return all ticks.
  28701. if (!tickModel.get('show') || axis.scale.isBlank()) {
  28702. ticks = [];
  28703. }
  28704. if (isFunction$1(optionTickInterval)) {
  28705. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  28706. }
  28707. // Always use label interval by default despite label show. Consider this
  28708. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  28709. // labels. `splitLine` and `axisTick` should be consistent in this case.
  28710. else if (optionTickInterval === 'auto') {
  28711. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  28712. tickCategoryInterval = labelsResult.labelCategoryInterval;
  28713. ticks = map(labelsResult.labels, function (labelItem) {
  28714. return labelItem.tickValue;
  28715. });
  28716. }
  28717. else {
  28718. tickCategoryInterval = optionTickInterval;
  28719. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  28720. }
  28721. // Cache to avoid calling interval function repeatly.
  28722. return listCacheSet(ticksCache, optionTickInterval, {
  28723. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  28724. });
  28725. }
  28726. function makeRealNumberLabels(axis) {
  28727. var ticks = axis.scale.getTicks();
  28728. var labelFormatter = makeLabelFormatter(axis);
  28729. return {
  28730. labels: map(ticks, function (tickValue, idx) {
  28731. return {
  28732. formattedLabel: labelFormatter(tickValue, idx),
  28733. rawLabel: axis.scale.getLabel(tickValue),
  28734. tickValue: tickValue
  28735. };
  28736. })
  28737. };
  28738. }
  28739. // Large category data calculation is performence sensitive, and ticks and label
  28740. // probably be fetched by multiple times. So we cache the result.
  28741. // axis is created each time during a ec process, so we do not need to clear cache.
  28742. function getListCache(axis, prop) {
  28743. // Because key can be funciton, and cache size always be small, we use array cache.
  28744. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  28745. }
  28746. function listCacheGet(cache, key) {
  28747. for (var i = 0; i < cache.length; i++) {
  28748. if (cache[i].key === key) {
  28749. return cache[i].value;
  28750. }
  28751. }
  28752. }
  28753. function listCacheSet(cache, key, value) {
  28754. cache.push({key: key, value: value});
  28755. return value;
  28756. }
  28757. function makeAutoCategoryInterval(axis) {
  28758. var result = inner$6(axis).autoInterval;
  28759. return result != null
  28760. ? result
  28761. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  28762. }
  28763. /**
  28764. * Calculate interval for category axis ticks and labels.
  28765. * To get precise result, at least one of `getRotate` and `isHorizontal`
  28766. * should be implemented in axis.
  28767. */
  28768. function calculateCategoryInterval(axis) {
  28769. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  28770. var labelFormatter = makeLabelFormatter(axis);
  28771. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  28772. var ordinalScale = axis.scale;
  28773. var ordinalExtent = ordinalScale.getExtent();
  28774. // Providing this method is for optimization:
  28775. // avoid generating a long array by `getTicks`
  28776. // in large category data case.
  28777. var tickCount = ordinalScale.count();
  28778. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  28779. return 0;
  28780. }
  28781. var step = 1;
  28782. // Simple optimization. Empirical value: tick count should less than 40.
  28783. if (tickCount > 40) {
  28784. step = Math.max(1, Math.floor(tickCount / 40));
  28785. }
  28786. var tickValue = ordinalExtent[0];
  28787. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  28788. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  28789. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  28790. var maxW = 0;
  28791. var maxH = 0;
  28792. // Caution: Performance sensitive for large category data.
  28793. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  28794. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  28795. var width = 0;
  28796. var height = 0;
  28797. // Polar is also calculated in assumptive linear layout here.
  28798. // Not precise, do not consider align and vertical align
  28799. // and each distance from axis line yet.
  28800. var rect = getBoundingRect(
  28801. labelFormatter(tickValue), params.font, 'center', 'top'
  28802. );
  28803. // Magic number
  28804. width = rect.width * 1.3;
  28805. height = rect.height * 1.3;
  28806. // Min size, void long loop.
  28807. maxW = Math.max(maxW, width, 7);
  28808. maxH = Math.max(maxH, height, 7);
  28809. }
  28810. var dw = maxW / unitW;
  28811. var dh = maxH / unitH;
  28812. // 0/0 is NaN, 1/0 is Infinity.
  28813. isNaN(dw) && (dw = Infinity);
  28814. isNaN(dh) && (dh = Infinity);
  28815. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  28816. var cache = inner$6(axis.model);
  28817. var lastAutoInterval = cache.lastAutoInterval;
  28818. var lastTickCount = cache.lastTickCount;
  28819. // Use cache to keep interval stable while moving zoom window,
  28820. // otherwise the calculated interval might jitter when the zoom
  28821. // window size is close to the interval-changing size.
  28822. if (lastAutoInterval != null
  28823. && lastTickCount != null
  28824. && Math.abs(lastAutoInterval - interval) <= 1
  28825. && Math.abs(lastTickCount - tickCount) <= 1
  28826. // Always choose the bigger one, otherwise the critical
  28827. // point is not the same when zooming in or zooming out.
  28828. && lastAutoInterval > interval
  28829. ) {
  28830. interval = lastAutoInterval;
  28831. }
  28832. // Only update cache if cache not used, otherwise the
  28833. // changing of interval is too insensitive.
  28834. else {
  28835. cache.lastTickCount = tickCount;
  28836. cache.lastAutoInterval = interval;
  28837. }
  28838. return interval;
  28839. }
  28840. function fetchAutoCategoryIntervalCalculationParams(axis) {
  28841. var labelModel = axis.getLabelModel();
  28842. return {
  28843. axisRotate: axis.getRotate
  28844. ? axis.getRotate()
  28845. : (axis.isHorizontal && !axis.isHorizontal())
  28846. ? 90
  28847. : 0,
  28848. labelRotate: labelModel.get('rotate') || 0,
  28849. font: labelModel.getFont()
  28850. };
  28851. }
  28852. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  28853. var labelFormatter = makeLabelFormatter(axis);
  28854. var ordinalScale = axis.scale;
  28855. var ordinalExtent = ordinalScale.getExtent();
  28856. var labelModel = axis.getLabelModel();
  28857. var result = [];
  28858. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  28859. var step = Math.max((categoryInterval || 0) + 1, 1);
  28860. var startTick = ordinalExtent[0];
  28861. var tickCount = ordinalScale.count();
  28862. // Calculate start tick based on zero if possible to keep label consistent
  28863. // while zooming and moving while interval > 0. Otherwise the selection
  28864. // of displayable ticks and symbols probably keep changing.
  28865. // 3 is empirical value.
  28866. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  28867. startTick = Math.round(Math.ceil(startTick / step) * step);
  28868. }
  28869. // (1) Only add min max label here but leave overlap checking
  28870. // to render stage, which also ensure the returned list
  28871. // suitable for splitLine and splitArea rendering.
  28872. // (2) Scales except category always contain min max label so
  28873. // do not need to perform this process.
  28874. var showMinMax = {
  28875. min: labelModel.get('showMinLabel'),
  28876. max: labelModel.get('showMaxLabel')
  28877. };
  28878. if (showMinMax.min && startTick !== ordinalExtent[0]) {
  28879. addItem(ordinalExtent[0]);
  28880. }
  28881. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  28882. var tickValue = startTick;
  28883. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  28884. addItem(tickValue);
  28885. }
  28886. if (showMinMax.max && tickValue !== ordinalExtent[1]) {
  28887. addItem(ordinalExtent[1]);
  28888. }
  28889. function addItem(tVal) {
  28890. result.push(onlyTick
  28891. ? tVal
  28892. : {
  28893. formattedLabel: labelFormatter(tVal),
  28894. rawLabel: ordinalScale.getLabel(tVal),
  28895. tickValue: tVal
  28896. }
  28897. );
  28898. }
  28899. return result;
  28900. }
  28901. // When interval is function, the result `false` means ignore the tick.
  28902. // It is time consuming for large category data.
  28903. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  28904. var ordinalScale = axis.scale;
  28905. var labelFormatter = makeLabelFormatter(axis);
  28906. var result = [];
  28907. each$1(ordinalScale.getTicks(), function (tickValue) {
  28908. var rawLabel = ordinalScale.getLabel(tickValue);
  28909. if (categoryInterval(tickValue, rawLabel)) {
  28910. result.push(onlyTick
  28911. ? tickValue
  28912. : {
  28913. formattedLabel: labelFormatter(tickValue),
  28914. rawLabel: rawLabel,
  28915. tickValue: tickValue
  28916. }
  28917. );
  28918. }
  28919. });
  28920. return result;
  28921. }
  28922. // Can be null|'auto'|number|function
  28923. function getOptionCategoryInterval(model) {
  28924. var interval = model.get('interval');
  28925. return interval == null ? 'auto' : interval;
  28926. }
  28927. /*
  28928. * Licensed to the Apache Software Foundation (ASF) under one
  28929. * or more contributor license agreements. See the NOTICE file
  28930. * distributed with this work for additional information
  28931. * regarding copyright ownership. The ASF licenses this file
  28932. * to you under the Apache License, Version 2.0 (the
  28933. * "License"); you may not use this file except in compliance
  28934. * with the License. You may obtain a copy of the License at
  28935. *
  28936. * http://www.apache.org/licenses/LICENSE-2.0
  28937. *
  28938. * Unless required by applicable law or agreed to in writing,
  28939. * software distributed under the License is distributed on an
  28940. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28941. * KIND, either express or implied. See the License for the
  28942. * specific language governing permissions and limitations
  28943. * under the License.
  28944. */
  28945. var NORMALIZED_EXTENT = [0, 1];
  28946. /**
  28947. * Base class of Axis.
  28948. * @constructor
  28949. */
  28950. var Axis = function (dim, scale, extent) {
  28951. /**
  28952. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  28953. * @type {string}
  28954. */
  28955. this.dim = dim;
  28956. /**
  28957. * Axis scale
  28958. * @type {module:echarts/coord/scale/*}
  28959. */
  28960. this.scale = scale;
  28961. /**
  28962. * @type {Array.<number>}
  28963. * @private
  28964. */
  28965. this._extent = extent || [0, 0];
  28966. /**
  28967. * @type {boolean}
  28968. */
  28969. this.inverse = false;
  28970. /**
  28971. * Usually true when axis has a ordinal scale
  28972. * @type {boolean}
  28973. */
  28974. this.onBand = false;
  28975. };
  28976. Axis.prototype = {
  28977. constructor: Axis,
  28978. /**
  28979. * If axis extent contain given coord
  28980. * @param {number} coord
  28981. * @return {boolean}
  28982. */
  28983. contain: function (coord) {
  28984. var extent = this._extent;
  28985. var min = Math.min(extent[0], extent[1]);
  28986. var max = Math.max(extent[0], extent[1]);
  28987. return coord >= min && coord <= max;
  28988. },
  28989. /**
  28990. * If axis extent contain given data
  28991. * @param {number} data
  28992. * @return {boolean}
  28993. */
  28994. containData: function (data) {
  28995. return this.contain(this.dataToCoord(data));
  28996. },
  28997. /**
  28998. * Get coord extent.
  28999. * @return {Array.<number>}
  29000. */
  29001. getExtent: function () {
  29002. return this._extent.slice();
  29003. },
  29004. /**
  29005. * Get precision used for formatting
  29006. * @param {Array.<number>} [dataExtent]
  29007. * @return {number}
  29008. */
  29009. getPixelPrecision: function (dataExtent) {
  29010. return getPixelPrecision(
  29011. dataExtent || this.scale.getExtent(),
  29012. this._extent
  29013. );
  29014. },
  29015. /**
  29016. * Set coord extent
  29017. * @param {number} start
  29018. * @param {number} end
  29019. */
  29020. setExtent: function (start, end) {
  29021. var extent = this._extent;
  29022. extent[0] = start;
  29023. extent[1] = end;
  29024. },
  29025. /**
  29026. * Convert data to coord. Data is the rank if it has an ordinal scale
  29027. * @param {number} data
  29028. * @param {boolean} clamp
  29029. * @return {number}
  29030. */
  29031. dataToCoord: function (data, clamp) {
  29032. var extent = this._extent;
  29033. var scale = this.scale;
  29034. data = scale.normalize(data);
  29035. if (this.onBand && scale.type === 'ordinal') {
  29036. extent = extent.slice();
  29037. fixExtentWithBands(extent, scale.count());
  29038. }
  29039. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  29040. },
  29041. /**
  29042. * Convert coord to data. Data is the rank if it has an ordinal scale
  29043. * @param {number} coord
  29044. * @param {boolean} clamp
  29045. * @return {number}
  29046. */
  29047. coordToData: function (coord, clamp) {
  29048. var extent = this._extent;
  29049. var scale = this.scale;
  29050. if (this.onBand && scale.type === 'ordinal') {
  29051. extent = extent.slice();
  29052. fixExtentWithBands(extent, scale.count());
  29053. }
  29054. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  29055. return this.scale.scale(t);
  29056. },
  29057. /**
  29058. * Convert pixel point to data in axis
  29059. * @param {Array.<number>} point
  29060. * @param {boolean} clamp
  29061. * @return {number} data
  29062. */
  29063. pointToData: function (point, clamp) {
  29064. // Should be implemented in derived class if necessary.
  29065. },
  29066. /**
  29067. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  29068. * `axis.getTicksCoords` considers `onBand`, which is used by
  29069. * `boundaryGap:true` of category axis and splitLine and splitArea.
  29070. * @param {Object} [opt]
  29071. * @param {number} [opt.tickModel=axis.model.getModel('axisTick')]
  29072. * @param {boolean} [opt.clamp] If `true`, the first and the last
  29073. * tick must be at the axis end points. Otherwise, clip ticks
  29074. * that outside the axis extent.
  29075. * @return {Array.<Object>} [{
  29076. * coord: ...,
  29077. * tickValue: ...
  29078. * }, ...]
  29079. */
  29080. getTicksCoords: function (opt) {
  29081. opt = opt || {};
  29082. var tickModel = opt.tickModel || this.getTickModel();
  29083. var result = createAxisTicks(this, tickModel);
  29084. var ticks = result.ticks;
  29085. var ticksCoords = map(ticks, function (tickValue) {
  29086. return {
  29087. coord: this.dataToCoord(tickValue),
  29088. tickValue: tickValue
  29089. };
  29090. }, this);
  29091. var alignWithLabel = tickModel.get('alignWithLabel');
  29092. fixOnBandTicksCoords(
  29093. this, ticksCoords, result.tickCategoryInterval, alignWithLabel, opt.clamp
  29094. );
  29095. return ticksCoords;
  29096. },
  29097. /**
  29098. * @return {Array.<Object>} [{
  29099. * formattedLabel: string,
  29100. * rawLabel: axis.scale.getLabel(tickValue)
  29101. * tickValue: number
  29102. * }, ...]
  29103. */
  29104. getViewLabels: function () {
  29105. return createAxisLabels(this).labels;
  29106. },
  29107. /**
  29108. * @return {module:echarts/coord/model/Model}
  29109. */
  29110. getLabelModel: function () {
  29111. return this.model.getModel('axisLabel');
  29112. },
  29113. /**
  29114. * Notice here we only get the default tick model. For splitLine
  29115. * or splitArea, we should pass the splitLineModel or splitAreaModel
  29116. * manually when calling `getTicksCoords`.
  29117. * In GL, this method may be overrided to:
  29118. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  29119. * @return {module:echarts/coord/model/Model}
  29120. */
  29121. getTickModel: function () {
  29122. return this.model.getModel('axisTick');
  29123. },
  29124. /**
  29125. * Get width of band
  29126. * @return {number}
  29127. */
  29128. getBandWidth: function () {
  29129. var axisExtent = this._extent;
  29130. var dataExtent = this.scale.getExtent();
  29131. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  29132. // Fix #2728, avoid NaN when only one data.
  29133. len === 0 && (len = 1);
  29134. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  29135. return Math.abs(size) / len;
  29136. },
  29137. /**
  29138. * @abstract
  29139. * @return {boolean} Is horizontal
  29140. */
  29141. isHorizontal: null,
  29142. /**
  29143. * @abstract
  29144. * @return {number} Get axis rotate, by degree.
  29145. */
  29146. getRotate: null,
  29147. /**
  29148. * Only be called in category axis.
  29149. * Can be overrided, consider other axes like in 3D.
  29150. * @return {number} Auto interval for cateogry axis tick and label
  29151. */
  29152. calculateCategoryInterval: function () {
  29153. return calculateCategoryInterval(this);
  29154. }
  29155. };
  29156. function fixExtentWithBands(extent, nTick) {
  29157. var size = extent[1] - extent[0];
  29158. var len = nTick;
  29159. var margin = size / len / 2;
  29160. extent[0] += margin;
  29161. extent[1] -= margin;
  29162. }
  29163. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  29164. // |---1---|---2---|---3---|---4---|.
  29165. // So the displayed ticks and splitLine/splitArea should between
  29166. // each data item, otherwise cause misleading (e.g., split tow bars
  29167. // of a single data item when there are two bar series).
  29168. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  29169. // splitLine/spliteArea should layout appropriately corresponding
  29170. // to displayed labels. (So we should not use `getBandWidth` in this
  29171. // case).
  29172. function fixOnBandTicksCoords(axis, ticksCoords, tickCategoryInterval, alignWithLabel, clamp) {
  29173. var ticksLen = ticksCoords.length;
  29174. if (!axis.onBand || alignWithLabel || !ticksLen) {
  29175. return;
  29176. }
  29177. var axisExtent = axis.getExtent();
  29178. var last;
  29179. if (ticksLen === 1) {
  29180. ticksCoords[0].coord = axisExtent[0];
  29181. last = ticksCoords[1] = {coord: axisExtent[0]};
  29182. }
  29183. else {
  29184. var shift = (ticksCoords[1].coord - ticksCoords[0].coord);
  29185. each$1(ticksCoords, function (ticksItem) {
  29186. ticksItem.coord -= shift / 2;
  29187. var tickCategoryInterval = tickCategoryInterval || 0;
  29188. // Avoid split a single data item when odd interval.
  29189. if (tickCategoryInterval % 2 > 0) {
  29190. ticksItem.coord -= shift / ((tickCategoryInterval + 1) * 2);
  29191. }
  29192. });
  29193. last = {coord: ticksCoords[ticksLen - 1].coord + shift};
  29194. ticksCoords.push(last);
  29195. }
  29196. var inverse = axisExtent[0] > axisExtent[1];
  29197. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  29198. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  29199. }
  29200. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  29201. ticksCoords.unshift({coord: axisExtent[0]});
  29202. }
  29203. if (littleThan(axisExtent[1], last.coord)) {
  29204. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  29205. }
  29206. if (clamp && littleThan(last.coord, axisExtent[1])) {
  29207. ticksCoords.push({coord: axisExtent[1]});
  29208. }
  29209. function littleThan(a, b) {
  29210. return inverse ? a > b : a < b;
  29211. }
  29212. }
  29213. /*
  29214. * Licensed to the Apache Software Foundation (ASF) under one
  29215. * or more contributor license agreements. See the NOTICE file
  29216. * distributed with this work for additional information
  29217. * regarding copyright ownership. The ASF licenses this file
  29218. * to you under the Apache License, Version 2.0 (the
  29219. * "License"); you may not use this file except in compliance
  29220. * with the License. You may obtain a copy of the License at
  29221. *
  29222. * http://www.apache.org/licenses/LICENSE-2.0
  29223. *
  29224. * Unless required by applicable law or agreed to in writing,
  29225. * software distributed under the License is distributed on an
  29226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29227. * KIND, either express or implied. See the License for the
  29228. * specific language governing permissions and limitations
  29229. * under the License.
  29230. */
  29231. /**
  29232. * Do not mount those modules on 'src/echarts' for better tree shaking.
  29233. */
  29234. var parseGeoJson = parseGeoJson$1;
  29235. var ecUtil = {};
  29236. each$1([
  29237. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  29238. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  29239. 'extend', 'defaults', 'clone', 'merge'
  29240. ],
  29241. function (name) {
  29242. ecUtil[name] = zrUtil[name];
  29243. }
  29244. );
  29245. /*
  29246. * Licensed to the Apache Software Foundation (ASF) under one
  29247. * or more contributor license agreements. See the NOTICE file
  29248. * distributed with this work for additional information
  29249. * regarding copyright ownership. The ASF licenses this file
  29250. * to you under the Apache License, Version 2.0 (the
  29251. * "License"); you may not use this file except in compliance
  29252. * with the License. You may obtain a copy of the License at
  29253. *
  29254. * http://www.apache.org/licenses/LICENSE-2.0
  29255. *
  29256. * Unless required by applicable law or agreed to in writing,
  29257. * software distributed under the License is distributed on an
  29258. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29259. * KIND, either express or implied. See the License for the
  29260. * specific language governing permissions and limitations
  29261. * under the License.
  29262. */
  29263. SeriesModel.extend({
  29264. type: 'series.line',
  29265. dependencies: ['grid', 'polar'],
  29266. getInitialData: function (option, ecModel) {
  29267. if (__DEV__) {
  29268. var coordSys = option.coordinateSystem;
  29269. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  29270. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  29271. }
  29272. }
  29273. return createListFromArray(this.getSource(), this);
  29274. },
  29275. defaultOption: {
  29276. zlevel: 0,
  29277. z: 2,
  29278. coordinateSystem: 'cartesian2d',
  29279. legendHoverLink: true,
  29280. hoverAnimation: true,
  29281. // stack: null
  29282. // xAxisIndex: 0,
  29283. // yAxisIndex: 0,
  29284. // polarIndex: 0,
  29285. // If clip the overflow value
  29286. clipOverflow: true,
  29287. // cursor: null,
  29288. label: {
  29289. position: 'top'
  29290. },
  29291. // itemStyle: {
  29292. // },
  29293. lineStyle: {
  29294. width: 2,
  29295. type: 'solid'
  29296. },
  29297. // areaStyle: {
  29298. // origin of areaStyle. Valid values:
  29299. // `'auto'/null/undefined`: from axisLine to data
  29300. // `'start'`: from min to data
  29301. // `'end'`: from data to max
  29302. // origin: 'auto'
  29303. // },
  29304. // false, 'start', 'end', 'middle'
  29305. step: false,
  29306. // Disabled if step is true
  29307. smooth: false,
  29308. smoothMonotone: null,
  29309. symbol: 'emptyCircle',
  29310. symbolSize: 4,
  29311. symbolRotate: null,
  29312. showSymbol: true,
  29313. // `false`: follow the label interval strategy.
  29314. // `true`: show all symbols.
  29315. // `'auto'`: If possible, show all symbols, otherwise
  29316. // follow the label interval strategy.
  29317. showAllSymbol: 'auto',
  29318. // Whether to connect break point.
  29319. connectNulls: false,
  29320. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  29321. sampling: 'none',
  29322. animationEasing: 'linear',
  29323. // Disable progressive
  29324. progressive: 0,
  29325. hoverLayerThreshold: Infinity
  29326. }
  29327. });
  29328. /*
  29329. * Licensed to the Apache Software Foundation (ASF) under one
  29330. * or more contributor license agreements. See the NOTICE file
  29331. * distributed with this work for additional information
  29332. * regarding copyright ownership. The ASF licenses this file
  29333. * to you under the Apache License, Version 2.0 (the
  29334. * "License"); you may not use this file except in compliance
  29335. * with the License. You may obtain a copy of the License at
  29336. *
  29337. * http://www.apache.org/licenses/LICENSE-2.0
  29338. *
  29339. * Unless required by applicable law or agreed to in writing,
  29340. * software distributed under the License is distributed on an
  29341. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29342. * KIND, either express or implied. See the License for the
  29343. * specific language governing permissions and limitations
  29344. * under the License.
  29345. */
  29346. /**
  29347. * @param {module:echarts/data/List} data
  29348. * @param {number} dataIndex
  29349. * @return {string} label string. Not null/undefined
  29350. */
  29351. function getDefaultLabel(data, dataIndex) {
  29352. var labelDims = data.mapDimension('defaultedLabel', true);
  29353. var len = labelDims.length;
  29354. // Simple optimization (in lots of cases, label dims length is 1)
  29355. if (len === 1) {
  29356. return retrieveRawValue(data, dataIndex, labelDims[0]);
  29357. }
  29358. else if (len) {
  29359. var vals = [];
  29360. for (var i = 0; i < labelDims.length; i++) {
  29361. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  29362. vals.push(val);
  29363. }
  29364. return vals.join(' ');
  29365. }
  29366. }
  29367. /*
  29368. * Licensed to the Apache Software Foundation (ASF) under one
  29369. * or more contributor license agreements. See the NOTICE file
  29370. * distributed with this work for additional information
  29371. * regarding copyright ownership. The ASF licenses this file
  29372. * to you under the Apache License, Version 2.0 (the
  29373. * "License"); you may not use this file except in compliance
  29374. * with the License. You may obtain a copy of the License at
  29375. *
  29376. * http://www.apache.org/licenses/LICENSE-2.0
  29377. *
  29378. * Unless required by applicable law or agreed to in writing,
  29379. * software distributed under the License is distributed on an
  29380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29381. * KIND, either express or implied. See the License for the
  29382. * specific language governing permissions and limitations
  29383. * under the License.
  29384. */
  29385. /**
  29386. * @module echarts/chart/helper/Symbol
  29387. */
  29388. /**
  29389. * @constructor
  29390. * @alias {module:echarts/chart/helper/Symbol}
  29391. * @param {module:echarts/data/List} data
  29392. * @param {number} idx
  29393. * @extends {module:zrender/graphic/Group}
  29394. */
  29395. function SymbolClz$1(data, idx, seriesScope) {
  29396. Group.call(this);
  29397. this.updateData(data, idx, seriesScope);
  29398. }
  29399. var symbolProto = SymbolClz$1.prototype;
  29400. /**
  29401. * @public
  29402. * @static
  29403. * @param {module:echarts/data/List} data
  29404. * @param {number} dataIndex
  29405. * @return {Array.<number>} [width, height]
  29406. */
  29407. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  29408. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  29409. return symbolSize instanceof Array
  29410. ? symbolSize.slice()
  29411. : [+symbolSize, +symbolSize];
  29412. };
  29413. function getScale(symbolSize) {
  29414. return [symbolSize[0] / 2, symbolSize[1] / 2];
  29415. }
  29416. function driftSymbol(dx, dy) {
  29417. this.parent.drift(dx, dy);
  29418. }
  29419. symbolProto._createSymbol = function (
  29420. symbolType,
  29421. data,
  29422. idx,
  29423. symbolSize,
  29424. keepAspect
  29425. ) {
  29426. // Remove paths created before
  29427. this.removeAll();
  29428. var color = data.getItemVisual(idx, 'color');
  29429. // var symbolPath = createSymbol(
  29430. // symbolType, -0.5, -0.5, 1, 1, color
  29431. // );
  29432. // If width/height are set too small (e.g., set to 1) on ios10
  29433. // and macOS Sierra, a circle stroke become a rect, no matter what
  29434. // the scale is set. So we set width/height as 2. See #4150.
  29435. var symbolPath = createSymbol(
  29436. symbolType, -1, -1, 2, 2, color, keepAspect
  29437. );
  29438. symbolPath.attr({
  29439. z2: 100,
  29440. culling: true,
  29441. scale: getScale(symbolSize)
  29442. });
  29443. // Rewrite drift method
  29444. symbolPath.drift = driftSymbol;
  29445. this._symbolType = symbolType;
  29446. this.add(symbolPath);
  29447. };
  29448. /**
  29449. * Stop animation
  29450. * @param {boolean} toLastFrame
  29451. */
  29452. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  29453. this.childAt(0).stopAnimation(toLastFrame);
  29454. };
  29455. /**
  29456. * FIXME:
  29457. * Caution: This method breaks the encapsulation of this module,
  29458. * but it indeed brings convenience. So do not use the method
  29459. * unless you detailedly know all the implements of `Symbol`,
  29460. * especially animation.
  29461. *
  29462. * Get symbol path element.
  29463. */
  29464. symbolProto.getSymbolPath = function () {
  29465. return this.childAt(0);
  29466. };
  29467. /**
  29468. * Get scale(aka, current symbol size).
  29469. * Including the change caused by animation
  29470. */
  29471. symbolProto.getScale = function () {
  29472. return this.childAt(0).scale;
  29473. };
  29474. /**
  29475. * Highlight symbol
  29476. */
  29477. symbolProto.highlight = function () {
  29478. this.childAt(0).trigger('emphasis');
  29479. };
  29480. /**
  29481. * Downplay symbol
  29482. */
  29483. symbolProto.downplay = function () {
  29484. this.childAt(0).trigger('normal');
  29485. };
  29486. /**
  29487. * @param {number} zlevel
  29488. * @param {number} z
  29489. */
  29490. symbolProto.setZ = function (zlevel, z) {
  29491. var symbolPath = this.childAt(0);
  29492. symbolPath.zlevel = zlevel;
  29493. symbolPath.z = z;
  29494. };
  29495. symbolProto.setDraggable = function (draggable) {
  29496. var symbolPath = this.childAt(0);
  29497. symbolPath.draggable = draggable;
  29498. symbolPath.cursor = draggable ? 'move' : 'pointer';
  29499. };
  29500. /**
  29501. * Update symbol properties
  29502. * @param {module:echarts/data/List} data
  29503. * @param {number} idx
  29504. * @param {Object} [seriesScope]
  29505. * @param {Object} [seriesScope.itemStyle]
  29506. * @param {Object} [seriesScope.hoverItemStyle]
  29507. * @param {Object} [seriesScope.symbolRotate]
  29508. * @param {Object} [seriesScope.symbolOffset]
  29509. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  29510. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  29511. * @param {boolean} [seriesScope.hoverAnimation]
  29512. * @param {Object} [seriesScope.cursorStyle]
  29513. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  29514. * @param {string} [seriesScope.symbolInnerColor]
  29515. * @param {Object} [seriesScope.fadeIn=false]
  29516. */
  29517. symbolProto.updateData = function (data, idx, seriesScope) {
  29518. this.silent = false;
  29519. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  29520. var seriesModel = data.hostModel;
  29521. var symbolSize = getSymbolSize(data, idx);
  29522. var isInit = symbolType !== this._symbolType;
  29523. if (isInit) {
  29524. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  29525. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  29526. }
  29527. else {
  29528. var symbolPath = this.childAt(0);
  29529. symbolPath.silent = false;
  29530. updateProps(symbolPath, {
  29531. scale: getScale(symbolSize)
  29532. }, seriesModel, idx);
  29533. }
  29534. this._updateCommon(data, idx, symbolSize, seriesScope);
  29535. if (isInit) {
  29536. var symbolPath = this.childAt(0);
  29537. var fadeIn = seriesScope && seriesScope.fadeIn;
  29538. var target = {scale: symbolPath.scale.slice()};
  29539. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  29540. symbolPath.scale = [0, 0];
  29541. fadeIn && (symbolPath.style.opacity = 0);
  29542. initProps(symbolPath, target, seriesModel, idx);
  29543. }
  29544. this._seriesModel = seriesModel;
  29545. };
  29546. // Update common properties
  29547. var normalStyleAccessPath = ['itemStyle'];
  29548. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  29549. var normalLabelAccessPath = ['label'];
  29550. var emphasisLabelAccessPath = ['emphasis', 'label'];
  29551. /**
  29552. * @param {module:echarts/data/List} data
  29553. * @param {number} idx
  29554. * @param {Array.<number>} symbolSize
  29555. * @param {Object} [seriesScope]
  29556. */
  29557. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  29558. var symbolPath = this.childAt(0);
  29559. var seriesModel = data.hostModel;
  29560. var color = data.getItemVisual(idx, 'color');
  29561. // Reset style
  29562. if (symbolPath.type !== 'image') {
  29563. symbolPath.useStyle({
  29564. strokeNoScale: true
  29565. });
  29566. }
  29567. var itemStyle = seriesScope && seriesScope.itemStyle;
  29568. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  29569. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  29570. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  29571. var labelModel = seriesScope && seriesScope.labelModel;
  29572. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  29573. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  29574. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  29575. if (!seriesScope || data.hasItemOption) {
  29576. var itemModel = (seriesScope && seriesScope.itemModel)
  29577. ? seriesScope.itemModel : data.getItemModel(idx);
  29578. // Color must be excluded.
  29579. // Because symbol provide setColor individually to set fill and stroke
  29580. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  29581. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  29582. symbolRotate = itemModel.getShallow('symbolRotate');
  29583. symbolOffset = itemModel.getShallow('symbolOffset');
  29584. labelModel = itemModel.getModel(normalLabelAccessPath);
  29585. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  29586. hoverAnimation = itemModel.getShallow('hoverAnimation');
  29587. cursorStyle = itemModel.getShallow('cursor');
  29588. }
  29589. else {
  29590. hoverItemStyle = extend({}, hoverItemStyle);
  29591. }
  29592. var elStyle = symbolPath.style;
  29593. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  29594. if (symbolOffset) {
  29595. symbolPath.attr('position', [
  29596. parsePercent$1(symbolOffset[0], symbolSize[0]),
  29597. parsePercent$1(symbolOffset[1], symbolSize[1])
  29598. ]);
  29599. }
  29600. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  29601. // PENDING setColor before setStyle!!!
  29602. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  29603. symbolPath.setStyle(itemStyle);
  29604. var opacity = data.getItemVisual(idx, 'opacity');
  29605. if (opacity != null) {
  29606. elStyle.opacity = opacity;
  29607. }
  29608. var liftZ = data.getItemVisual(idx, 'liftZ');
  29609. var z2Origin = symbolPath.__z2Origin;
  29610. if (liftZ != null) {
  29611. if (z2Origin == null) {
  29612. symbolPath.__z2Origin = symbolPath.z2;
  29613. symbolPath.z2 += liftZ;
  29614. }
  29615. }
  29616. else if (z2Origin != null) {
  29617. symbolPath.z2 = z2Origin;
  29618. symbolPath.__z2Origin = null;
  29619. }
  29620. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  29621. setLabelStyle(
  29622. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  29623. {
  29624. labelFetcher: seriesModel,
  29625. labelDataIndex: idx,
  29626. defaultText: getLabelDefaultText,
  29627. isRectText: true,
  29628. autoColor: color
  29629. }
  29630. );
  29631. // Do not execute util needed.
  29632. function getLabelDefaultText(idx, opt) {
  29633. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  29634. }
  29635. symbolPath.off('mouseover')
  29636. .off('mouseout')
  29637. .off('emphasis')
  29638. .off('normal');
  29639. symbolPath.hoverStyle = hoverItemStyle;
  29640. // FIXME
  29641. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  29642. setHoverStyle(symbolPath);
  29643. var scale = getScale(symbolSize);
  29644. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  29645. var onEmphasis = function() {
  29646. // Do not support this hover animation util some scenario required.
  29647. // Animation can only be supported in hover layer when using `el.incremetal`.
  29648. if (this.incremental) {
  29649. return;
  29650. }
  29651. var ratio = scale[1] / scale[0];
  29652. this.animateTo({
  29653. scale: [
  29654. Math.max(scale[0] * 1.1, scale[0] + 3),
  29655. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  29656. ]
  29657. }, 400, 'elasticOut');
  29658. };
  29659. var onNormal = function() {
  29660. if (this.incremental) {
  29661. return;
  29662. }
  29663. this.animateTo({
  29664. scale: scale
  29665. }, 400, 'elasticOut');
  29666. };
  29667. symbolPath.on('mouseover', onEmphasis)
  29668. .on('mouseout', onNormal)
  29669. .on('emphasis', onEmphasis)
  29670. .on('normal', onNormal);
  29671. }
  29672. };
  29673. /**
  29674. * @param {Function} cb
  29675. * @param {Object} [opt]
  29676. * @param {Object} [opt.keepLabel=true]
  29677. */
  29678. symbolProto.fadeOut = function (cb, opt) {
  29679. var symbolPath = this.childAt(0);
  29680. // Avoid mistaken hover when fading out
  29681. this.silent = symbolPath.silent = true;
  29682. // Not show text when animating
  29683. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  29684. updateProps(
  29685. symbolPath,
  29686. {
  29687. style: {opacity: 0},
  29688. scale: [0, 0]
  29689. },
  29690. this._seriesModel,
  29691. this.dataIndex,
  29692. cb
  29693. );
  29694. };
  29695. inherits(SymbolClz$1, Group);
  29696. /*
  29697. * Licensed to the Apache Software Foundation (ASF) under one
  29698. * or more contributor license agreements. See the NOTICE file
  29699. * distributed with this work for additional information
  29700. * regarding copyright ownership. The ASF licenses this file
  29701. * to you under the Apache License, Version 2.0 (the
  29702. * "License"); you may not use this file except in compliance
  29703. * with the License. You may obtain a copy of the License at
  29704. *
  29705. * http://www.apache.org/licenses/LICENSE-2.0
  29706. *
  29707. * Unless required by applicable law or agreed to in writing,
  29708. * software distributed under the License is distributed on an
  29709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29710. * KIND, either express or implied. See the License for the
  29711. * specific language governing permissions and limitations
  29712. * under the License.
  29713. */
  29714. /**
  29715. * @module echarts/chart/helper/SymbolDraw
  29716. */
  29717. /**
  29718. * @constructor
  29719. * @alias module:echarts/chart/helper/SymbolDraw
  29720. * @param {module:zrender/graphic/Group} [symbolCtor]
  29721. */
  29722. function SymbolDraw(symbolCtor) {
  29723. this.group = new Group();
  29724. this._symbolCtor = symbolCtor || SymbolClz$1;
  29725. }
  29726. var symbolDrawProto = SymbolDraw.prototype;
  29727. function symbolNeedsDraw(data, point, idx, opt) {
  29728. return point && !isNaN(point[0]) && !isNaN(point[1])
  29729. && !(opt.isIgnore && opt.isIgnore(idx))
  29730. // We do not set clipShape on group, because it will cut part of
  29731. // the symbol element shape. We use the same clip shape here as
  29732. // the line clip.
  29733. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  29734. && data.getItemVisual(idx, 'symbol') !== 'none';
  29735. }
  29736. /**
  29737. * Update symbols draw by new data
  29738. * @param {module:echarts/data/List} data
  29739. * @param {Object} [opt] Or isIgnore
  29740. * @param {Function} [opt.isIgnore]
  29741. * @param {Object} [opt.clipShape]
  29742. */
  29743. symbolDrawProto.updateData = function (data, opt) {
  29744. opt = normalizeUpdateOpt(opt);
  29745. var group = this.group;
  29746. var seriesModel = data.hostModel;
  29747. var oldData = this._data;
  29748. var SymbolCtor = this._symbolCtor;
  29749. var seriesScope = makeSeriesScope(data);
  29750. // There is no oldLineData only when first rendering or switching from
  29751. // stream mode to normal mode, where previous elements should be removed.
  29752. if (!oldData) {
  29753. group.removeAll();
  29754. }
  29755. data.diff(oldData)
  29756. .add(function (newIdx) {
  29757. var point = data.getItemLayout(newIdx);
  29758. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  29759. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  29760. symbolEl.attr('position', point);
  29761. data.setItemGraphicEl(newIdx, symbolEl);
  29762. group.add(symbolEl);
  29763. }
  29764. })
  29765. .update(function (newIdx, oldIdx) {
  29766. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  29767. var point = data.getItemLayout(newIdx);
  29768. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  29769. group.remove(symbolEl);
  29770. return;
  29771. }
  29772. if (!symbolEl) {
  29773. symbolEl = new SymbolCtor(data, newIdx);
  29774. symbolEl.attr('position', point);
  29775. }
  29776. else {
  29777. symbolEl.updateData(data, newIdx, seriesScope);
  29778. updateProps(symbolEl, {
  29779. position: point
  29780. }, seriesModel);
  29781. }
  29782. // Add back
  29783. group.add(symbolEl);
  29784. data.setItemGraphicEl(newIdx, symbolEl);
  29785. })
  29786. .remove(function (oldIdx) {
  29787. var el = oldData.getItemGraphicEl(oldIdx);
  29788. el && el.fadeOut(function () {
  29789. group.remove(el);
  29790. });
  29791. })
  29792. .execute();
  29793. this._data = data;
  29794. };
  29795. symbolDrawProto.isPersistent = function () {
  29796. return true;
  29797. };
  29798. symbolDrawProto.updateLayout = function () {
  29799. var data = this._data;
  29800. if (data) {
  29801. // Not use animation
  29802. data.eachItemGraphicEl(function (el, idx) {
  29803. var point = data.getItemLayout(idx);
  29804. el.attr('position', point);
  29805. });
  29806. }
  29807. };
  29808. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  29809. this._seriesScope = makeSeriesScope(data);
  29810. this._data = null;
  29811. this.group.removeAll();
  29812. };
  29813. /**
  29814. * Update symbols draw by new data
  29815. * @param {module:echarts/data/List} data
  29816. * @param {Object} [opt] Or isIgnore
  29817. * @param {Function} [opt.isIgnore]
  29818. * @param {Object} [opt.clipShape]
  29819. */
  29820. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  29821. opt = normalizeUpdateOpt(opt);
  29822. function updateIncrementalAndHover(el) {
  29823. if (!el.isGroup) {
  29824. el.incremental = el.useHoverLayer = true;
  29825. }
  29826. }
  29827. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  29828. var point = data.getItemLayout(idx);
  29829. if (symbolNeedsDraw(data, point, idx, opt)) {
  29830. var el = new this._symbolCtor(data, idx, this._seriesScope);
  29831. el.traverse(updateIncrementalAndHover);
  29832. el.attr('position', point);
  29833. this.group.add(el);
  29834. data.setItemGraphicEl(idx, el);
  29835. }
  29836. }
  29837. };
  29838. function normalizeUpdateOpt(opt) {
  29839. if (opt != null && !isObject$1(opt)) {
  29840. opt = {isIgnore: opt};
  29841. }
  29842. return opt || {};
  29843. }
  29844. symbolDrawProto.remove = function (enableAnimation) {
  29845. var group = this.group;
  29846. var data = this._data;
  29847. // Incremental model do not have this._data.
  29848. if (data && enableAnimation) {
  29849. data.eachItemGraphicEl(function (el) {
  29850. el.fadeOut(function () {
  29851. group.remove(el);
  29852. });
  29853. });
  29854. }
  29855. else {
  29856. group.removeAll();
  29857. }
  29858. };
  29859. function makeSeriesScope(data) {
  29860. var seriesModel = data.hostModel;
  29861. return {
  29862. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  29863. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  29864. symbolRotate: seriesModel.get('symbolRotate'),
  29865. symbolOffset: seriesModel.get('symbolOffset'),
  29866. hoverAnimation: seriesModel.get('hoverAnimation'),
  29867. labelModel: seriesModel.getModel('label'),
  29868. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  29869. cursorStyle: seriesModel.get('cursor')
  29870. };
  29871. }
  29872. /*
  29873. * Licensed to the Apache Software Foundation (ASF) under one
  29874. * or more contributor license agreements. See the NOTICE file
  29875. * distributed with this work for additional information
  29876. * regarding copyright ownership. The ASF licenses this file
  29877. * to you under the Apache License, Version 2.0 (the
  29878. * "License"); you may not use this file except in compliance
  29879. * with the License. You may obtain a copy of the License at
  29880. *
  29881. * http://www.apache.org/licenses/LICENSE-2.0
  29882. *
  29883. * Unless required by applicable law or agreed to in writing,
  29884. * software distributed under the License is distributed on an
  29885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29886. * KIND, either express or implied. See the License for the
  29887. * specific language governing permissions and limitations
  29888. * under the License.
  29889. */
  29890. /**
  29891. * @param {Object} coordSys
  29892. * @param {module:echarts/data/List} data
  29893. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  29894. */
  29895. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  29896. var baseAxis = coordSys.getBaseAxis();
  29897. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29898. var valueStart = getValueStart(valueAxis, valueOrigin);
  29899. var baseAxisDim = baseAxis.dim;
  29900. var valueAxisDim = valueAxis.dim;
  29901. var valueDim = data.mapDimension(valueAxisDim);
  29902. var baseDim = data.mapDimension(baseAxisDim);
  29903. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  29904. var dims = map(coordSys.dimensions, function (coordDim) {
  29905. return data.mapDimension(coordDim);
  29906. });
  29907. var stacked;
  29908. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  29909. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  29910. dims[0] = stackResultDim;
  29911. }
  29912. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  29913. dims[1] = stackResultDim;
  29914. }
  29915. return {
  29916. dataDimsForPoint: dims,
  29917. valueStart: valueStart,
  29918. valueAxisDim: valueAxisDim,
  29919. baseAxisDim: baseAxisDim,
  29920. stacked: !!stacked,
  29921. valueDim: valueDim,
  29922. baseDim: baseDim,
  29923. baseDataOffset: baseDataOffset,
  29924. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  29925. };
  29926. }
  29927. function getValueStart(valueAxis, valueOrigin) {
  29928. var valueStart = 0;
  29929. var extent = valueAxis.scale.getExtent();
  29930. if (valueOrigin === 'start') {
  29931. valueStart = extent[0];
  29932. }
  29933. else if (valueOrigin === 'end') {
  29934. valueStart = extent[1];
  29935. }
  29936. // auto
  29937. else {
  29938. // Both positive
  29939. if (extent[0] > 0) {
  29940. valueStart = extent[0];
  29941. }
  29942. // Both negative
  29943. else if (extent[1] < 0) {
  29944. valueStart = extent[1];
  29945. }
  29946. // If is one positive, and one negative, onZero shall be true
  29947. }
  29948. return valueStart;
  29949. }
  29950. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  29951. var value = NaN;
  29952. if (dataCoordInfo.stacked) {
  29953. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  29954. }
  29955. if (isNaN(value)) {
  29956. value = dataCoordInfo.valueStart;
  29957. }
  29958. var baseDataOffset = dataCoordInfo.baseDataOffset;
  29959. var stackedData = [];
  29960. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  29961. stackedData[1 - baseDataOffset] = value;
  29962. return coordSys.dataToPoint(stackedData);
  29963. }
  29964. /*
  29965. * Licensed to the Apache Software Foundation (ASF) under one
  29966. * or more contributor license agreements. See the NOTICE file
  29967. * distributed with this work for additional information
  29968. * regarding copyright ownership. The ASF licenses this file
  29969. * to you under the Apache License, Version 2.0 (the
  29970. * "License"); you may not use this file except in compliance
  29971. * with the License. You may obtain a copy of the License at
  29972. *
  29973. * http://www.apache.org/licenses/LICENSE-2.0
  29974. *
  29975. * Unless required by applicable law or agreed to in writing,
  29976. * software distributed under the License is distributed on an
  29977. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29978. * KIND, either express or implied. See the License for the
  29979. * specific language governing permissions and limitations
  29980. * under the License.
  29981. */
  29982. // var arrayDiff = require('zrender/src/core/arrayDiff');
  29983. // 'zrender/src/core/arrayDiff' has been used before, but it did
  29984. // not do well in performance when roam with fixed dataZoom window.
  29985. // function convertToIntId(newIdList, oldIdList) {
  29986. // // Generate int id instead of string id.
  29987. // // Compare string maybe slow in score function of arrDiff
  29988. // // Assume id in idList are all unique
  29989. // var idIndicesMap = {};
  29990. // var idx = 0;
  29991. // for (var i = 0; i < newIdList.length; i++) {
  29992. // idIndicesMap[newIdList[i]] = idx;
  29993. // newIdList[i] = idx++;
  29994. // }
  29995. // for (var i = 0; i < oldIdList.length; i++) {
  29996. // var oldId = oldIdList[i];
  29997. // // Same with newIdList
  29998. // if (idIndicesMap[oldId]) {
  29999. // oldIdList[i] = idIndicesMap[oldId];
  30000. // }
  30001. // else {
  30002. // oldIdList[i] = idx++;
  30003. // }
  30004. // }
  30005. // }
  30006. function diffData(oldData, newData) {
  30007. var diffResult = [];
  30008. newData.diff(oldData)
  30009. .add(function (idx) {
  30010. diffResult.push({cmd: '+', idx: idx});
  30011. })
  30012. .update(function (newIdx, oldIdx) {
  30013. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  30014. })
  30015. .remove(function (idx) {
  30016. diffResult.push({cmd: '-', idx: idx});
  30017. })
  30018. .execute();
  30019. return diffResult;
  30020. }
  30021. var lineAnimationDiff = function (
  30022. oldData, newData,
  30023. oldStackedOnPoints, newStackedOnPoints,
  30024. oldCoordSys, newCoordSys,
  30025. oldValueOrigin, newValueOrigin
  30026. ) {
  30027. var diff = diffData(oldData, newData);
  30028. // var newIdList = newData.mapArray(newData.getId);
  30029. // var oldIdList = oldData.mapArray(oldData.getId);
  30030. // convertToIntId(newIdList, oldIdList);
  30031. // // FIXME One data ?
  30032. // diff = arrayDiff(oldIdList, newIdList);
  30033. var currPoints = [];
  30034. var nextPoints = [];
  30035. // Points for stacking base line
  30036. var currStackedPoints = [];
  30037. var nextStackedPoints = [];
  30038. var status = [];
  30039. var sortedIndices = [];
  30040. var rawIndices = [];
  30041. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  30042. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  30043. for (var i = 0; i < diff.length; i++) {
  30044. var diffItem = diff[i];
  30045. var pointAdded = true;
  30046. // FIXME, animation is not so perfect when dataZoom window moves fast
  30047. // Which is in case remvoing or add more than one data in the tail or head
  30048. switch (diffItem.cmd) {
  30049. case '=':
  30050. var currentPt = oldData.getItemLayout(diffItem.idx);
  30051. var nextPt = newData.getItemLayout(diffItem.idx1);
  30052. // If previous data is NaN, use next point directly
  30053. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  30054. currentPt = nextPt.slice();
  30055. }
  30056. currPoints.push(currentPt);
  30057. nextPoints.push(nextPt);
  30058. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  30059. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  30060. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  30061. break;
  30062. case '+':
  30063. var idx = diffItem.idx;
  30064. currPoints.push(
  30065. oldCoordSys.dataToPoint([
  30066. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  30067. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  30068. ])
  30069. );
  30070. nextPoints.push(newData.getItemLayout(idx).slice());
  30071. currStackedPoints.push(
  30072. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  30073. );
  30074. nextStackedPoints.push(newStackedOnPoints[idx]);
  30075. rawIndices.push(newData.getRawIndex(idx));
  30076. break;
  30077. case '-':
  30078. var idx = diffItem.idx;
  30079. var rawIndex = oldData.getRawIndex(idx);
  30080. // Data is replaced. In the case of dynamic data queue
  30081. // FIXME FIXME FIXME
  30082. if (rawIndex !== idx) {
  30083. currPoints.push(oldData.getItemLayout(idx));
  30084. nextPoints.push(newCoordSys.dataToPoint([
  30085. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  30086. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  30087. ]));
  30088. currStackedPoints.push(oldStackedOnPoints[idx]);
  30089. nextStackedPoints.push(
  30090. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  30091. );
  30092. rawIndices.push(rawIndex);
  30093. }
  30094. else {
  30095. pointAdded = false;
  30096. }
  30097. }
  30098. // Original indices
  30099. if (pointAdded) {
  30100. status.push(diffItem);
  30101. sortedIndices.push(sortedIndices.length);
  30102. }
  30103. }
  30104. // Diff result may be crossed if all items are changed
  30105. // Sort by data index
  30106. sortedIndices.sort(function (a, b) {
  30107. return rawIndices[a] - rawIndices[b];
  30108. });
  30109. var sortedCurrPoints = [];
  30110. var sortedNextPoints = [];
  30111. var sortedCurrStackedPoints = [];
  30112. var sortedNextStackedPoints = [];
  30113. var sortedStatus = [];
  30114. for (var i = 0; i < sortedIndices.length; i++) {
  30115. var idx = sortedIndices[i];
  30116. sortedCurrPoints[i] = currPoints[idx];
  30117. sortedNextPoints[i] = nextPoints[idx];
  30118. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  30119. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  30120. sortedStatus[i] = status[idx];
  30121. }
  30122. return {
  30123. current: sortedCurrPoints,
  30124. next: sortedNextPoints,
  30125. stackedOnCurrent: sortedCurrStackedPoints,
  30126. stackedOnNext: sortedNextStackedPoints,
  30127. status: sortedStatus
  30128. };
  30129. };
  30130. /*
  30131. * Licensed to the Apache Software Foundation (ASF) under one
  30132. * or more contributor license agreements. See the NOTICE file
  30133. * distributed with this work for additional information
  30134. * regarding copyright ownership. The ASF licenses this file
  30135. * to you under the Apache License, Version 2.0 (the
  30136. * "License"); you may not use this file except in compliance
  30137. * with the License. You may obtain a copy of the License at
  30138. *
  30139. * http://www.apache.org/licenses/LICENSE-2.0
  30140. *
  30141. * Unless required by applicable law or agreed to in writing,
  30142. * software distributed under the License is distributed on an
  30143. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30144. * KIND, either express or implied. See the License for the
  30145. * specific language governing permissions and limitations
  30146. * under the License.
  30147. */
  30148. // Poly path support NaN point
  30149. var vec2Min = min;
  30150. var vec2Max = max;
  30151. var scaleAndAdd$1 = scaleAndAdd;
  30152. var v2Copy = copy;
  30153. // Temporary variable
  30154. var v = [];
  30155. var cp0 = [];
  30156. var cp1 = [];
  30157. function isPointNull(p) {
  30158. return isNaN(p[0]) || isNaN(p[1]);
  30159. }
  30160. function drawSegment(
  30161. ctx, points, start, segLen, allLen,
  30162. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  30163. ) {
  30164. // if (smoothMonotone == null) {
  30165. // if (isMono(points, 'x')) {
  30166. // return drawMono(ctx, points, start, segLen, allLen,
  30167. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  30168. // }
  30169. // else if (isMono(points, 'y')) {
  30170. // return drawMono(ctx, points, start, segLen, allLen,
  30171. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  30172. // }
  30173. // else {
  30174. // return drawNonMono.apply(this, arguments);
  30175. // }
  30176. // }
  30177. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  30178. // return drawMono.apply(this, arguments);
  30179. // }
  30180. // else {
  30181. // return drawNonMono.apply(this, arguments);
  30182. // }
  30183. if (smoothMonotone === 'none' || !smoothMonotone) {
  30184. return drawNonMono.apply(this, arguments);
  30185. }
  30186. else {
  30187. return drawMono.apply(this, arguments);
  30188. }
  30189. }
  30190. /**
  30191. * Check if points is in monotone.
  30192. *
  30193. * @param {number[][]} points Array of points which is in [x, y] form
  30194. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  30195. * dimension that is checking.
  30196. * If is 'none', `drawNonMono` should be
  30197. * called.
  30198. * If is undefined, either being monotone
  30199. * in 'x' or 'y' will call `drawMono`.
  30200. */
  30201. // function isMono(points, smoothMonotone) {
  30202. // if (points.length <= 1) {
  30203. // return true;
  30204. // }
  30205. // var dim = smoothMonotone === 'x' ? 0 : 1;
  30206. // var last = points[0][dim];
  30207. // var lastDiff = 0;
  30208. // for (var i = 1; i < points.length; ++i) {
  30209. // var diff = points[i][dim] - last;
  30210. // if (!isNaN(diff) && !isNaN(lastDiff)
  30211. // && diff !== 0 && lastDiff !== 0
  30212. // && ((diff >= 0) !== (lastDiff >= 0))
  30213. // ) {
  30214. // return false;
  30215. // }
  30216. // if (!isNaN(diff) && diff !== 0) {
  30217. // lastDiff = diff;
  30218. // last = points[i][dim];
  30219. // }
  30220. // }
  30221. // return true;
  30222. // }
  30223. /**
  30224. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  30225. * control points will be used. This should be used when points are monotone
  30226. * either in x or y dimension.
  30227. */
  30228. function drawMono(
  30229. ctx, points, start, segLen, allLen,
  30230. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  30231. ) {
  30232. var prevIdx = 0;
  30233. var idx = start;
  30234. for (var k = 0; k < segLen; k++) {
  30235. var p = points[idx];
  30236. if (idx >= allLen || idx < 0) {
  30237. break;
  30238. }
  30239. if (isPointNull(p)) {
  30240. if (connectNulls) {
  30241. idx += dir;
  30242. continue;
  30243. }
  30244. break;
  30245. }
  30246. if (idx === start) {
  30247. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  30248. }
  30249. else {
  30250. if (smooth > 0) {
  30251. var prevP = points[prevIdx];
  30252. var dim = smoothMonotone === 'y' ? 1 : 0;
  30253. // Length of control point to p, either in x or y, but not both
  30254. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  30255. v2Copy(cp0, prevP);
  30256. cp0[dim] = prevP[dim] + ctrlLen;
  30257. v2Copy(cp1, p);
  30258. cp1[dim] = p[dim] - ctrlLen;
  30259. ctx.bezierCurveTo(
  30260. cp0[0], cp0[1],
  30261. cp1[0], cp1[1],
  30262. p[0], p[1]
  30263. );
  30264. }
  30265. else {
  30266. ctx.lineTo(p[0], p[1]);
  30267. }
  30268. }
  30269. prevIdx = idx;
  30270. idx += dir;
  30271. }
  30272. return k;
  30273. }
  30274. /**
  30275. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  30276. * situations. This should be used when points are non-monotone neither in x or
  30277. * y dimension.
  30278. */
  30279. function drawNonMono(
  30280. ctx, points, start, segLen, allLen,
  30281. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  30282. ) {
  30283. var prevIdx = 0;
  30284. var idx = start;
  30285. for (var k = 0; k < segLen; k++) {
  30286. var p = points[idx];
  30287. if (idx >= allLen || idx < 0) {
  30288. break;
  30289. }
  30290. if (isPointNull(p)) {
  30291. if (connectNulls) {
  30292. idx += dir;
  30293. continue;
  30294. }
  30295. break;
  30296. }
  30297. if (idx === start) {
  30298. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  30299. v2Copy(cp0, p);
  30300. }
  30301. else {
  30302. if (smooth > 0) {
  30303. var nextIdx = idx + dir;
  30304. var nextP = points[nextIdx];
  30305. if (connectNulls) {
  30306. // Find next point not null
  30307. while (nextP && isPointNull(points[nextIdx])) {
  30308. nextIdx += dir;
  30309. nextP = points[nextIdx];
  30310. }
  30311. }
  30312. var ratioNextSeg = 0.5;
  30313. var prevP = points[prevIdx];
  30314. var nextP = points[nextIdx];
  30315. // Last point
  30316. if (!nextP || isPointNull(nextP)) {
  30317. v2Copy(cp1, p);
  30318. }
  30319. else {
  30320. // If next data is null in not connect case
  30321. if (isPointNull(nextP) && !connectNulls) {
  30322. nextP = p;
  30323. }
  30324. sub(v, nextP, prevP);
  30325. var lenPrevSeg;
  30326. var lenNextSeg;
  30327. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  30328. var dim = smoothMonotone === 'x' ? 0 : 1;
  30329. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  30330. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  30331. }
  30332. else {
  30333. lenPrevSeg = dist(p, prevP);
  30334. lenNextSeg = dist(p, nextP);
  30335. }
  30336. // Use ratio of seg length
  30337. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  30338. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  30339. }
  30340. // Smooth constraint
  30341. vec2Min(cp0, cp0, smoothMax);
  30342. vec2Max(cp0, cp0, smoothMin);
  30343. vec2Min(cp1, cp1, smoothMax);
  30344. vec2Max(cp1, cp1, smoothMin);
  30345. ctx.bezierCurveTo(
  30346. cp0[0], cp0[1],
  30347. cp1[0], cp1[1],
  30348. p[0], p[1]
  30349. );
  30350. // cp0 of next segment
  30351. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  30352. }
  30353. else {
  30354. ctx.lineTo(p[0], p[1]);
  30355. }
  30356. }
  30357. prevIdx = idx;
  30358. idx += dir;
  30359. }
  30360. return k;
  30361. }
  30362. function getBoundingBox(points, smoothConstraint) {
  30363. var ptMin = [Infinity, Infinity];
  30364. var ptMax = [-Infinity, -Infinity];
  30365. if (smoothConstraint) {
  30366. for (var i = 0; i < points.length; i++) {
  30367. var pt = points[i];
  30368. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  30369. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  30370. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  30371. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  30372. }
  30373. }
  30374. return {
  30375. min: smoothConstraint ? ptMin : ptMax,
  30376. max: smoothConstraint ? ptMax : ptMin
  30377. };
  30378. }
  30379. var Polyline$1 = Path.extend({
  30380. type: 'ec-polyline',
  30381. shape: {
  30382. points: [],
  30383. smooth: 0,
  30384. smoothConstraint: true,
  30385. smoothMonotone: null,
  30386. connectNulls: false
  30387. },
  30388. style: {
  30389. fill: null,
  30390. stroke: '#000'
  30391. },
  30392. brush: fixClipWithShadow(Path.prototype.brush),
  30393. buildPath: function (ctx, shape) {
  30394. var points = shape.points;
  30395. var i = 0;
  30396. var len$$1 = points.length;
  30397. var result = getBoundingBox(points, shape.smoothConstraint);
  30398. if (shape.connectNulls) {
  30399. // Must remove first and last null values avoid draw error in polygon
  30400. for (; len$$1 > 0; len$$1--) {
  30401. if (!isPointNull(points[len$$1 - 1])) {
  30402. break;
  30403. }
  30404. }
  30405. for (; i < len$$1; i++) {
  30406. if (!isPointNull(points[i])) {
  30407. break;
  30408. }
  30409. }
  30410. }
  30411. while (i < len$$1) {
  30412. i += drawSegment(
  30413. ctx, points, i, len$$1, len$$1,
  30414. 1, result.min, result.max, shape.smooth,
  30415. shape.smoothMonotone, shape.connectNulls
  30416. ) + 1;
  30417. }
  30418. }
  30419. });
  30420. var Polygon$1 = Path.extend({
  30421. type: 'ec-polygon',
  30422. shape: {
  30423. points: [],
  30424. // Offset between stacked base points and points
  30425. stackedOnPoints: [],
  30426. smooth: 0,
  30427. stackedOnSmooth: 0,
  30428. smoothConstraint: true,
  30429. smoothMonotone: null,
  30430. connectNulls: false
  30431. },
  30432. brush: fixClipWithShadow(Path.prototype.brush),
  30433. buildPath: function (ctx, shape) {
  30434. var points = shape.points;
  30435. var stackedOnPoints = shape.stackedOnPoints;
  30436. var i = 0;
  30437. var len$$1 = points.length;
  30438. var smoothMonotone = shape.smoothMonotone;
  30439. var bbox = getBoundingBox(points, shape.smoothConstraint);
  30440. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  30441. if (shape.connectNulls) {
  30442. // Must remove first and last null values avoid draw error in polygon
  30443. for (; len$$1 > 0; len$$1--) {
  30444. if (!isPointNull(points[len$$1 - 1])) {
  30445. break;
  30446. }
  30447. }
  30448. for (; i < len$$1; i++) {
  30449. if (!isPointNull(points[i])) {
  30450. break;
  30451. }
  30452. }
  30453. }
  30454. while (i < len$$1) {
  30455. var k = drawSegment(
  30456. ctx, points, i, len$$1, len$$1,
  30457. 1, bbox.min, bbox.max, shape.smooth,
  30458. smoothMonotone, shape.connectNulls
  30459. );
  30460. drawSegment(
  30461. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  30462. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  30463. smoothMonotone, shape.connectNulls
  30464. );
  30465. i += k + 1;
  30466. ctx.closePath();
  30467. }
  30468. }
  30469. });
  30470. /*
  30471. * Licensed to the Apache Software Foundation (ASF) under one
  30472. * or more contributor license agreements. See the NOTICE file
  30473. * distributed with this work for additional information
  30474. * regarding copyright ownership. The ASF licenses this file
  30475. * to you under the Apache License, Version 2.0 (the
  30476. * "License"); you may not use this file except in compliance
  30477. * with the License. You may obtain a copy of the License at
  30478. *
  30479. * http://www.apache.org/licenses/LICENSE-2.0
  30480. *
  30481. * Unless required by applicable law or agreed to in writing,
  30482. * software distributed under the License is distributed on an
  30483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30484. * KIND, either express or implied. See the License for the
  30485. * specific language governing permissions and limitations
  30486. * under the License.
  30487. */
  30488. // FIXME step not support polar
  30489. function isPointsSame(points1, points2) {
  30490. if (points1.length !== points2.length) {
  30491. return;
  30492. }
  30493. for (var i = 0; i < points1.length; i++) {
  30494. var p1 = points1[i];
  30495. var p2 = points2[i];
  30496. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  30497. return;
  30498. }
  30499. }
  30500. return true;
  30501. }
  30502. function getSmooth(smooth) {
  30503. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  30504. }
  30505. function getAxisExtentWithGap(axis) {
  30506. var extent = axis.getGlobalExtent();
  30507. if (axis.onBand) {
  30508. // Remove extra 1px to avoid line miter in clipped edge
  30509. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  30510. var dir = extent[1] > extent[0] ? 1 : -1;
  30511. extent[0] += dir * halfBandWidth;
  30512. extent[1] -= dir * halfBandWidth;
  30513. }
  30514. return extent;
  30515. }
  30516. /**
  30517. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  30518. * @param {module:echarts/data/List} data
  30519. * @param {Object} dataCoordInfo
  30520. * @param {Array.<Array.<number>>} points
  30521. */
  30522. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  30523. if (!dataCoordInfo.valueDim) {
  30524. return [];
  30525. }
  30526. var points = [];
  30527. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30528. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  30529. }
  30530. return points;
  30531. }
  30532. function createGridClipShape(cartesian, hasAnimation, forSymbol, seriesModel) {
  30533. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  30534. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  30535. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  30536. var x = Math.min(xExtent[0], xExtent[1]);
  30537. var y = Math.min(yExtent[0], yExtent[1]);
  30538. var width = Math.max(xExtent[0], xExtent[1]) - x;
  30539. var height = Math.max(yExtent[0], yExtent[1]) - y;
  30540. // Avoid float number rounding error for symbol on the edge of axis extent.
  30541. // See #7913 and `test/dataZoom-clip.html`.
  30542. if (forSymbol) {
  30543. x -= 0.5;
  30544. width += 0.5;
  30545. y -= 0.5;
  30546. height += 0.5;
  30547. }
  30548. else {
  30549. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  30550. // Expand clip shape to avoid clipping when line value exceeds axis
  30551. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  30552. if (isHorizontal) {
  30553. y -= expandSize;
  30554. height += expandSize * 2;
  30555. }
  30556. else {
  30557. x -= expandSize;
  30558. width += expandSize * 2;
  30559. }
  30560. }
  30561. var clipPath = new Rect({
  30562. shape: {
  30563. x: x,
  30564. y: y,
  30565. width: width,
  30566. height: height
  30567. }
  30568. });
  30569. if (hasAnimation) {
  30570. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  30571. initProps(clipPath, {
  30572. shape: {
  30573. width: width,
  30574. height: height
  30575. }
  30576. }, seriesModel);
  30577. }
  30578. return clipPath;
  30579. }
  30580. function createPolarClipShape(polar, hasAnimation, forSymbol, seriesModel) {
  30581. var angleAxis = polar.getAngleAxis();
  30582. var radiusAxis = polar.getRadiusAxis();
  30583. var radiusExtent = radiusAxis.getExtent().slice();
  30584. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  30585. var angleExtent = angleAxis.getExtent();
  30586. var RADIAN = Math.PI / 180;
  30587. // Avoid float number rounding error for symbol on the edge of axis extent.
  30588. if (forSymbol) {
  30589. radiusExtent[0] -= 0.5;
  30590. radiusExtent[1] += 0.5;
  30591. }
  30592. var clipPath = new Sector({
  30593. shape: {
  30594. cx: round$1(polar.cx, 1),
  30595. cy: round$1(polar.cy, 1),
  30596. r0: round$1(radiusExtent[0], 1),
  30597. r: round$1(radiusExtent[1], 1),
  30598. startAngle: -angleExtent[0] * RADIAN,
  30599. endAngle: -angleExtent[1] * RADIAN,
  30600. clockwise: angleAxis.inverse
  30601. }
  30602. });
  30603. if (hasAnimation) {
  30604. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  30605. initProps(clipPath, {
  30606. shape: {
  30607. endAngle: -angleExtent[1] * RADIAN
  30608. }
  30609. }, seriesModel);
  30610. }
  30611. return clipPath;
  30612. }
  30613. function createClipShape(coordSys, hasAnimation, forSymbol, seriesModel) {
  30614. return coordSys.type === 'polar'
  30615. ? createPolarClipShape(coordSys, hasAnimation, forSymbol, seriesModel)
  30616. : createGridClipShape(coordSys, hasAnimation, forSymbol, seriesModel);
  30617. }
  30618. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  30619. var baseAxis = coordSys.getBaseAxis();
  30620. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  30621. var stepPoints = [];
  30622. for (var i = 0; i < points.length - 1; i++) {
  30623. var nextPt = points[i + 1];
  30624. var pt = points[i];
  30625. stepPoints.push(pt);
  30626. var stepPt = [];
  30627. switch (stepTurnAt) {
  30628. case 'end':
  30629. stepPt[baseIndex] = nextPt[baseIndex];
  30630. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30631. // default is start
  30632. stepPoints.push(stepPt);
  30633. break;
  30634. case 'middle':
  30635. // default is start
  30636. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  30637. var stepPt2 = [];
  30638. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  30639. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30640. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  30641. stepPoints.push(stepPt);
  30642. stepPoints.push(stepPt2);
  30643. break;
  30644. default:
  30645. stepPt[baseIndex] = pt[baseIndex];
  30646. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  30647. // default is start
  30648. stepPoints.push(stepPt);
  30649. }
  30650. }
  30651. // Last points
  30652. points[i] && stepPoints.push(points[i]);
  30653. return stepPoints;
  30654. }
  30655. function getVisualGradient(data, coordSys) {
  30656. var visualMetaList = data.getVisual('visualMeta');
  30657. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  30658. // When data.count() is 0, gradient range can not be calculated.
  30659. return;
  30660. }
  30661. if (coordSys.type !== 'cartesian2d') {
  30662. if (__DEV__) {
  30663. console.warn('Visual map on line style is only supported on cartesian2d.');
  30664. }
  30665. return;
  30666. }
  30667. var coordDim;
  30668. var visualMeta;
  30669. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  30670. var dimIndex = visualMetaList[i].dimension;
  30671. var dimName = data.dimensions[dimIndex];
  30672. var dimInfo = data.getDimensionInfo(dimName);
  30673. coordDim = dimInfo && dimInfo.coordDim;
  30674. // Can only be x or y
  30675. if (coordDim === 'x' || coordDim === 'y') {
  30676. visualMeta = visualMetaList[i];
  30677. break;
  30678. }
  30679. }
  30680. if (!visualMeta) {
  30681. if (__DEV__) {
  30682. console.warn('Visual map on line style only support x or y dimension.');
  30683. }
  30684. return;
  30685. }
  30686. // If the area to be rendered is bigger than area defined by LinearGradient,
  30687. // the canvas spec prescribes that the color of the first stop and the last
  30688. // stop should be used. But if two stops are added at offset 0, in effect
  30689. // browsers use the color of the second stop to render area outside
  30690. // LinearGradient. So we can only infinitesimally extend area defined in
  30691. // LinearGradient to render `outerColors`.
  30692. var axis = coordSys.getAxis(coordDim);
  30693. // dataToCoor mapping may not be linear, but must be monotonic.
  30694. var colorStops = map(visualMeta.stops, function (stop) {
  30695. return {
  30696. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  30697. color: stop.color
  30698. };
  30699. });
  30700. var stopLen = colorStops.length;
  30701. var outerColors = visualMeta.outerColors.slice();
  30702. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  30703. colorStops.reverse();
  30704. outerColors.reverse();
  30705. }
  30706. var tinyExtent = 10; // Arbitrary value: 10px
  30707. var minCoord = colorStops[0].coord - tinyExtent;
  30708. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  30709. var coordSpan = maxCoord - minCoord;
  30710. if (coordSpan < 1e-3) {
  30711. return 'transparent';
  30712. }
  30713. each$1(colorStops, function (stop) {
  30714. stop.offset = (stop.coord - minCoord) / coordSpan;
  30715. });
  30716. colorStops.push({
  30717. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  30718. color: outerColors[1] || 'transparent'
  30719. });
  30720. colorStops.unshift({ // notice colorStops.length have been changed.
  30721. offset: stopLen ? colorStops[0].offset : 0.5,
  30722. color: outerColors[0] || 'transparent'
  30723. });
  30724. // zrUtil.each(colorStops, function (colorStop) {
  30725. // // Make sure each offset has rounded px to avoid not sharp edge
  30726. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  30727. // });
  30728. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  30729. gradient[coordDim] = minCoord;
  30730. gradient[coordDim + '2'] = maxCoord;
  30731. return gradient;
  30732. }
  30733. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  30734. var showAllSymbol = seriesModel.get('showAllSymbol');
  30735. var isAuto = showAllSymbol === 'auto';
  30736. if (showAllSymbol && !isAuto) {
  30737. return;
  30738. }
  30739. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  30740. if (!categoryAxis) {
  30741. return;
  30742. }
  30743. // Note that category label interval strategy might bring some weird effect
  30744. // in some scenario: users may wonder why some of the symbols are not
  30745. // displayed. So we show all symbols as possible as we can.
  30746. if (isAuto
  30747. // Simplify the logic, do not determine label overlap here.
  30748. && canShowAllSymbolForCategory(categoryAxis, data)
  30749. ) {
  30750. return;
  30751. }
  30752. // Otherwise follow the label interval strategy on category axis.
  30753. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  30754. var labelMap = {};
  30755. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  30756. labelMap[labelItem.tickValue] = 1;
  30757. });
  30758. return function (dataIndex) {
  30759. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  30760. };
  30761. }
  30762. function canShowAllSymbolForCategory(categoryAxis, data) {
  30763. // In mose cases, line is monotonous on category axis, and the label size
  30764. // is close with each other. So we check the symbol size and some of the
  30765. // label size alone with the category axis to estimate whether all symbol
  30766. // can be shown without overlap.
  30767. var axisExtent = categoryAxis.getExtent();
  30768. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  30769. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  30770. // Sampling some points, max 5.
  30771. var dataLen = data.count();
  30772. var step = Math.max(1, Math.round(dataLen / 5));
  30773. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  30774. if (SymbolClz$1.getSymbolSize(
  30775. data, dataIndex
  30776. // Only for cartesian, where `isHorizontal` exists.
  30777. )[categoryAxis.isHorizontal() ? 1 : 0]
  30778. // Empirical number
  30779. * 1.5 > availSize
  30780. ) {
  30781. return false;
  30782. }
  30783. }
  30784. return true;
  30785. }
  30786. Chart.extend({
  30787. type: 'line',
  30788. init: function () {
  30789. var lineGroup = new Group();
  30790. var symbolDraw = new SymbolDraw();
  30791. this.group.add(symbolDraw.group);
  30792. this._symbolDraw = symbolDraw;
  30793. this._lineGroup = lineGroup;
  30794. },
  30795. render: function (seriesModel, ecModel, api) {
  30796. var coordSys = seriesModel.coordinateSystem;
  30797. var group = this.group;
  30798. var data = seriesModel.getData();
  30799. var lineStyleModel = seriesModel.getModel('lineStyle');
  30800. var areaStyleModel = seriesModel.getModel('areaStyle');
  30801. var points = data.mapArray(data.getItemLayout);
  30802. var isCoordSysPolar = coordSys.type === 'polar';
  30803. var prevCoordSys = this._coordSys;
  30804. var symbolDraw = this._symbolDraw;
  30805. var polyline = this._polyline;
  30806. var polygon = this._polygon;
  30807. var lineGroup = this._lineGroup;
  30808. var hasAnimation = seriesModel.get('animation');
  30809. var isAreaChart = !areaStyleModel.isEmpty();
  30810. var valueOrigin = areaStyleModel.get('origin');
  30811. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  30812. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  30813. var showSymbol = seriesModel.get('showSymbol');
  30814. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  30815. && getIsIgnoreFunc(seriesModel, data, coordSys);
  30816. // Remove temporary symbols
  30817. var oldData = this._data;
  30818. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  30819. if (el.__temp) {
  30820. group.remove(el);
  30821. oldData.setItemGraphicEl(idx, null);
  30822. }
  30823. });
  30824. // Remove previous created symbols if showSymbol changed to false
  30825. if (!showSymbol) {
  30826. symbolDraw.remove();
  30827. }
  30828. group.add(lineGroup);
  30829. // FIXME step not support polar
  30830. var step = !isCoordSysPolar && seriesModel.get('step');
  30831. // Initialization animation or coordinate system changed
  30832. if (
  30833. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  30834. ) {
  30835. showSymbol && symbolDraw.updateData(data, {
  30836. isIgnore: isIgnoreFunc,
  30837. clipShape: createClipShape(coordSys, false, true, seriesModel)
  30838. });
  30839. if (step) {
  30840. // TODO If stacked series is not step
  30841. points = turnPointsIntoStep(points, coordSys, step);
  30842. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30843. }
  30844. polyline = this._newPolyline(points, coordSys, hasAnimation);
  30845. if (isAreaChart) {
  30846. polygon = this._newPolygon(
  30847. points, stackedOnPoints,
  30848. coordSys, hasAnimation
  30849. );
  30850. }
  30851. lineGroup.setClipPath(createClipShape(coordSys, true, false, seriesModel));
  30852. }
  30853. else {
  30854. if (isAreaChart && !polygon) {
  30855. // If areaStyle is added
  30856. polygon = this._newPolygon(
  30857. points, stackedOnPoints,
  30858. coordSys, hasAnimation
  30859. );
  30860. }
  30861. else if (polygon && !isAreaChart) {
  30862. // If areaStyle is removed
  30863. lineGroup.remove(polygon);
  30864. polygon = this._polygon = null;
  30865. }
  30866. // Update clipPath
  30867. lineGroup.setClipPath(createClipShape(coordSys, false, false, seriesModel));
  30868. // Always update, or it is wrong in the case turning on legend
  30869. // because points are not changed
  30870. showSymbol && symbolDraw.updateData(data, {
  30871. isIgnore: isIgnoreFunc,
  30872. clipShape: createClipShape(coordSys, false, true, seriesModel)
  30873. });
  30874. // Stop symbol animation and sync with line points
  30875. // FIXME performance?
  30876. data.eachItemGraphicEl(function (el) {
  30877. el.stopAnimation(true);
  30878. });
  30879. // In the case data zoom triggerred refreshing frequently
  30880. // Data may not change if line has a category axis. So it should animate nothing
  30881. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  30882. || !isPointsSame(this._points, points)
  30883. ) {
  30884. if (hasAnimation) {
  30885. this._updateAnimation(
  30886. data, stackedOnPoints, coordSys, api, step, valueOrigin
  30887. );
  30888. }
  30889. else {
  30890. // Not do it in update with animation
  30891. if (step) {
  30892. // TODO If stacked series is not step
  30893. points = turnPointsIntoStep(points, coordSys, step);
  30894. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30895. }
  30896. polyline.setShape({
  30897. points: points
  30898. });
  30899. polygon && polygon.setShape({
  30900. points: points,
  30901. stackedOnPoints: stackedOnPoints
  30902. });
  30903. }
  30904. }
  30905. }
  30906. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  30907. polyline.useStyle(defaults(
  30908. // Use color in lineStyle first
  30909. lineStyleModel.getLineStyle(),
  30910. {
  30911. fill: 'none',
  30912. stroke: visualColor,
  30913. lineJoin: 'bevel'
  30914. }
  30915. ));
  30916. var smooth = seriesModel.get('smooth');
  30917. smooth = getSmooth(seriesModel.get('smooth'));
  30918. polyline.setShape({
  30919. smooth: smooth,
  30920. smoothMonotone: seriesModel.get('smoothMonotone'),
  30921. connectNulls: seriesModel.get('connectNulls')
  30922. });
  30923. if (polygon) {
  30924. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  30925. var stackedOnSmooth = 0;
  30926. polygon.useStyle(defaults(
  30927. areaStyleModel.getAreaStyle(),
  30928. {
  30929. fill: visualColor,
  30930. opacity: 0.7,
  30931. lineJoin: 'bevel'
  30932. }
  30933. ));
  30934. if (stackedOnSeries) {
  30935. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  30936. }
  30937. polygon.setShape({
  30938. smooth: smooth,
  30939. stackedOnSmooth: stackedOnSmooth,
  30940. smoothMonotone: seriesModel.get('smoothMonotone'),
  30941. connectNulls: seriesModel.get('connectNulls')
  30942. });
  30943. }
  30944. this._data = data;
  30945. // Save the coordinate system for transition animation when data changed
  30946. this._coordSys = coordSys;
  30947. this._stackedOnPoints = stackedOnPoints;
  30948. this._points = points;
  30949. this._step = step;
  30950. this._valueOrigin = valueOrigin;
  30951. },
  30952. dispose: function () {},
  30953. highlight: function (seriesModel, ecModel, api, payload) {
  30954. var data = seriesModel.getData();
  30955. var dataIndex = queryDataIndex(data, payload);
  30956. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  30957. var symbol = data.getItemGraphicEl(dataIndex);
  30958. if (!symbol) {
  30959. // Create a temporary symbol if it is not exists
  30960. var pt = data.getItemLayout(dataIndex);
  30961. if (!pt) {
  30962. // Null data
  30963. return;
  30964. }
  30965. symbol = new SymbolClz$1(data, dataIndex);
  30966. symbol.position = pt;
  30967. symbol.setZ(
  30968. seriesModel.get('zlevel'),
  30969. seriesModel.get('z')
  30970. );
  30971. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  30972. symbol.__temp = true;
  30973. data.setItemGraphicEl(dataIndex, symbol);
  30974. // Stop scale animation
  30975. symbol.stopSymbolAnimation(true);
  30976. this.group.add(symbol);
  30977. }
  30978. symbol.highlight();
  30979. }
  30980. else {
  30981. // Highlight whole series
  30982. Chart.prototype.highlight.call(
  30983. this, seriesModel, ecModel, api, payload
  30984. );
  30985. }
  30986. },
  30987. downplay: function (seriesModel, ecModel, api, payload) {
  30988. var data = seriesModel.getData();
  30989. var dataIndex = queryDataIndex(data, payload);
  30990. if (dataIndex != null && dataIndex >= 0) {
  30991. var symbol = data.getItemGraphicEl(dataIndex);
  30992. if (symbol) {
  30993. if (symbol.__temp) {
  30994. data.setItemGraphicEl(dataIndex, null);
  30995. this.group.remove(symbol);
  30996. }
  30997. else {
  30998. symbol.downplay();
  30999. }
  31000. }
  31001. }
  31002. else {
  31003. // FIXME
  31004. // can not downplay completely.
  31005. // Downplay whole series
  31006. Chart.prototype.downplay.call(
  31007. this, seriesModel, ecModel, api, payload
  31008. );
  31009. }
  31010. },
  31011. /**
  31012. * @param {module:zrender/container/Group} group
  31013. * @param {Array.<Array.<number>>} points
  31014. * @private
  31015. */
  31016. _newPolyline: function (points) {
  31017. var polyline = this._polyline;
  31018. // Remove previous created polyline
  31019. if (polyline) {
  31020. this._lineGroup.remove(polyline);
  31021. }
  31022. polyline = new Polyline$1({
  31023. shape: {
  31024. points: points
  31025. },
  31026. silent: true,
  31027. z2: 10
  31028. });
  31029. this._lineGroup.add(polyline);
  31030. this._polyline = polyline;
  31031. return polyline;
  31032. },
  31033. /**
  31034. * @param {module:zrender/container/Group} group
  31035. * @param {Array.<Array.<number>>} stackedOnPoints
  31036. * @param {Array.<Array.<number>>} points
  31037. * @private
  31038. */
  31039. _newPolygon: function (points, stackedOnPoints) {
  31040. var polygon = this._polygon;
  31041. // Remove previous created polygon
  31042. if (polygon) {
  31043. this._lineGroup.remove(polygon);
  31044. }
  31045. polygon = new Polygon$1({
  31046. shape: {
  31047. points: points,
  31048. stackedOnPoints: stackedOnPoints
  31049. },
  31050. silent: true
  31051. });
  31052. this._lineGroup.add(polygon);
  31053. this._polygon = polygon;
  31054. return polygon;
  31055. },
  31056. /**
  31057. * @private
  31058. */
  31059. // FIXME Two value axis
  31060. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  31061. var polyline = this._polyline;
  31062. var polygon = this._polygon;
  31063. var seriesModel = data.hostModel;
  31064. var diff = lineAnimationDiff(
  31065. this._data, data,
  31066. this._stackedOnPoints, stackedOnPoints,
  31067. this._coordSys, coordSys,
  31068. this._valueOrigin, valueOrigin
  31069. );
  31070. var current = diff.current;
  31071. var stackedOnCurrent = diff.stackedOnCurrent;
  31072. var next = diff.next;
  31073. var stackedOnNext = diff.stackedOnNext;
  31074. if (step) {
  31075. // TODO If stacked series is not step
  31076. current = turnPointsIntoStep(diff.current, coordSys, step);
  31077. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  31078. next = turnPointsIntoStep(diff.next, coordSys, step);
  31079. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  31080. }
  31081. // `diff.current` is subset of `current` (which should be ensured by
  31082. // turnPointsIntoStep), so points in `__points` can be updated when
  31083. // points in `current` are update during animation.
  31084. polyline.shape.__points = diff.current;
  31085. polyline.shape.points = current;
  31086. updateProps(polyline, {
  31087. shape: {
  31088. points: next
  31089. }
  31090. }, seriesModel);
  31091. if (polygon) {
  31092. polygon.setShape({
  31093. points: current,
  31094. stackedOnPoints: stackedOnCurrent
  31095. });
  31096. updateProps(polygon, {
  31097. shape: {
  31098. points: next,
  31099. stackedOnPoints: stackedOnNext
  31100. }
  31101. }, seriesModel);
  31102. }
  31103. var updatedDataInfo = [];
  31104. var diffStatus = diff.status;
  31105. for (var i = 0; i < diffStatus.length; i++) {
  31106. var cmd = diffStatus[i].cmd;
  31107. if (cmd === '=') {
  31108. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  31109. if (el) {
  31110. updatedDataInfo.push({
  31111. el: el,
  31112. ptIdx: i // Index of points
  31113. });
  31114. }
  31115. }
  31116. }
  31117. if (polyline.animators && polyline.animators.length) {
  31118. polyline.animators[0].during(function () {
  31119. for (var i = 0; i < updatedDataInfo.length; i++) {
  31120. var el = updatedDataInfo[i].el;
  31121. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  31122. }
  31123. });
  31124. }
  31125. },
  31126. remove: function (ecModel) {
  31127. var group = this.group;
  31128. var oldData = this._data;
  31129. this._lineGroup.removeAll();
  31130. this._symbolDraw.remove(true);
  31131. // Remove temporary created elements when highlighting
  31132. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  31133. if (el.__temp) {
  31134. group.remove(el);
  31135. oldData.setItemGraphicEl(idx, null);
  31136. }
  31137. });
  31138. this._polyline =
  31139. this._polygon =
  31140. this._coordSys =
  31141. this._points =
  31142. this._stackedOnPoints =
  31143. this._data = null;
  31144. }
  31145. });
  31146. /*
  31147. * Licensed to the Apache Software Foundation (ASF) under one
  31148. * or more contributor license agreements. See the NOTICE file
  31149. * distributed with this work for additional information
  31150. * regarding copyright ownership. The ASF licenses this file
  31151. * to you under the Apache License, Version 2.0 (the
  31152. * "License"); you may not use this file except in compliance
  31153. * with the License. You may obtain a copy of the License at
  31154. *
  31155. * http://www.apache.org/licenses/LICENSE-2.0
  31156. *
  31157. * Unless required by applicable law or agreed to in writing,
  31158. * software distributed under the License is distributed on an
  31159. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31160. * KIND, either express or implied. See the License for the
  31161. * specific language governing permissions and limitations
  31162. * under the License.
  31163. */
  31164. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  31165. // Encoding visual for all series include which is filtered for legend drawing
  31166. return {
  31167. seriesType: seriesType,
  31168. // For legend.
  31169. performRawSeries: true,
  31170. reset: function (seriesModel, ecModel, api) {
  31171. var data = seriesModel.getData();
  31172. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  31173. var symbolSize = seriesModel.get('symbolSize');
  31174. var keepAspect = seriesModel.get('symbolKeepAspect');
  31175. data.setVisual({
  31176. legendSymbol: legendSymbol || symbolType,
  31177. symbol: symbolType,
  31178. symbolSize: symbolSize,
  31179. symbolKeepAspect: keepAspect
  31180. });
  31181. // Only visible series has each data be visual encoded
  31182. if (ecModel.isSeriesFiltered(seriesModel)) {
  31183. return;
  31184. }
  31185. var hasCallback = typeof symbolSize === 'function';
  31186. function dataEach(data, idx) {
  31187. if (typeof symbolSize === 'function') {
  31188. var rawValue = seriesModel.getRawValue(idx);
  31189. // FIXME
  31190. var params = seriesModel.getDataParams(idx);
  31191. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  31192. }
  31193. if (data.hasItemOption) {
  31194. var itemModel = data.getItemModel(idx);
  31195. var itemSymbolType = itemModel.getShallow('symbol', true);
  31196. var itemSymbolSize = itemModel.getShallow('symbolSize',
  31197. true);
  31198. var itemSymbolKeepAspect =
  31199. itemModel.getShallow('symbolKeepAspect',true);
  31200. // If has item symbol
  31201. if (itemSymbolType != null) {
  31202. data.setItemVisual(idx, 'symbol', itemSymbolType);
  31203. }
  31204. if (itemSymbolSize != null) {
  31205. // PENDING Transform symbolSize ?
  31206. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  31207. }
  31208. if (itemSymbolKeepAspect != null) {
  31209. data.setItemVisual(idx, 'symbolKeepAspect',
  31210. itemSymbolKeepAspect);
  31211. }
  31212. }
  31213. }
  31214. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  31215. }
  31216. };
  31217. };
  31218. /*
  31219. * Licensed to the Apache Software Foundation (ASF) under one
  31220. * or more contributor license agreements. See the NOTICE file
  31221. * distributed with this work for additional information
  31222. * regarding copyright ownership. The ASF licenses this file
  31223. * to you under the Apache License, Version 2.0 (the
  31224. * "License"); you may not use this file except in compliance
  31225. * with the License. You may obtain a copy of the License at
  31226. *
  31227. * http://www.apache.org/licenses/LICENSE-2.0
  31228. *
  31229. * Unless required by applicable law or agreed to in writing,
  31230. * software distributed under the License is distributed on an
  31231. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31232. * KIND, either express or implied. See the License for the
  31233. * specific language governing permissions and limitations
  31234. * under the License.
  31235. */
  31236. var pointsLayout = function (seriesType) {
  31237. return {
  31238. seriesType: seriesType,
  31239. plan: createRenderPlanner(),
  31240. reset: function (seriesModel) {
  31241. var data = seriesModel.getData();
  31242. var coordSys = seriesModel.coordinateSystem;
  31243. var pipelineContext = seriesModel.pipelineContext;
  31244. var isLargeRender = pipelineContext.large;
  31245. if (!coordSys) {
  31246. return;
  31247. }
  31248. var dims = map(coordSys.dimensions, function (dim) {
  31249. return data.mapDimension(dim);
  31250. }).slice(0, 2);
  31251. var dimLen = dims.length;
  31252. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  31253. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  31254. dims[0] = stackResultDim;
  31255. }
  31256. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  31257. dims[1] = stackResultDim;
  31258. }
  31259. function progress(params, data) {
  31260. var segCount = params.end - params.start;
  31261. var points = isLargeRender && new Float32Array(segCount * dimLen);
  31262. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  31263. var point;
  31264. if (dimLen === 1) {
  31265. var x = data.get(dims[0], i);
  31266. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  31267. }
  31268. else {
  31269. var x = tmpIn[0] = data.get(dims[0], i);
  31270. var y = tmpIn[1] = data.get(dims[1], i);
  31271. // Also {Array.<number>}, not undefined to avoid if...else... statement
  31272. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  31273. }
  31274. if (isLargeRender) {
  31275. points[offset++] = point ? point[0] : NaN;
  31276. points[offset++] = point ? point[1] : NaN;
  31277. }
  31278. else {
  31279. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  31280. }
  31281. }
  31282. isLargeRender && data.setLayout('symbolPoints', points);
  31283. }
  31284. return dimLen && {progress: progress};
  31285. }
  31286. };
  31287. };
  31288. /*
  31289. * Licensed to the Apache Software Foundation (ASF) under one
  31290. * or more contributor license agreements. See the NOTICE file
  31291. * distributed with this work for additional information
  31292. * regarding copyright ownership. The ASF licenses this file
  31293. * to you under the Apache License, Version 2.0 (the
  31294. * "License"); you may not use this file except in compliance
  31295. * with the License. You may obtain a copy of the License at
  31296. *
  31297. * http://www.apache.org/licenses/LICENSE-2.0
  31298. *
  31299. * Unless required by applicable law or agreed to in writing,
  31300. * software distributed under the License is distributed on an
  31301. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31302. * KIND, either express or implied. See the License for the
  31303. * specific language governing permissions and limitations
  31304. * under the License.
  31305. */
  31306. var samplers = {
  31307. average: function (frame) {
  31308. var sum = 0;
  31309. var count = 0;
  31310. for (var i = 0; i < frame.length; i++) {
  31311. if (!isNaN(frame[i])) {
  31312. sum += frame[i];
  31313. count++;
  31314. }
  31315. }
  31316. // Return NaN if count is 0
  31317. return count === 0 ? NaN : sum / count;
  31318. },
  31319. sum: function (frame) {
  31320. var sum = 0;
  31321. for (var i = 0; i < frame.length; i++) {
  31322. // Ignore NaN
  31323. sum += frame[i] || 0;
  31324. }
  31325. return sum;
  31326. },
  31327. max: function (frame) {
  31328. var max = -Infinity;
  31329. for (var i = 0; i < frame.length; i++) {
  31330. frame[i] > max && (max = frame[i]);
  31331. }
  31332. // NaN will cause illegal axis extent.
  31333. return isFinite(max) ? max : NaN;
  31334. },
  31335. min: function (frame) {
  31336. var min = Infinity;
  31337. for (var i = 0; i < frame.length; i++) {
  31338. frame[i] < min && (min = frame[i]);
  31339. }
  31340. // NaN will cause illegal axis extent.
  31341. return isFinite(min) ? min : NaN;
  31342. },
  31343. // TODO
  31344. // Median
  31345. nearest: function (frame) {
  31346. return frame[0];
  31347. }
  31348. };
  31349. var indexSampler = function (frame, value) {
  31350. return Math.round(frame.length / 2);
  31351. };
  31352. var dataSample = function (seriesType) {
  31353. return {
  31354. seriesType: seriesType,
  31355. modifyOutputEnd: true,
  31356. reset: function (seriesModel, ecModel, api) {
  31357. var data = seriesModel.getData();
  31358. var sampling = seriesModel.get('sampling');
  31359. var coordSys = seriesModel.coordinateSystem;
  31360. // Only cartesian2d support down sampling
  31361. if (coordSys.type === 'cartesian2d' && sampling) {
  31362. var baseAxis = coordSys.getBaseAxis();
  31363. var valueAxis = coordSys.getOtherAxis(baseAxis);
  31364. var extent = baseAxis.getExtent();
  31365. // Coordinste system has been resized
  31366. var size = extent[1] - extent[0];
  31367. var rate = Math.round(data.count() / size);
  31368. if (rate > 1) {
  31369. var sampler;
  31370. if (typeof sampling === 'string') {
  31371. sampler = samplers[sampling];
  31372. }
  31373. else if (typeof sampling === 'function') {
  31374. sampler = sampling;
  31375. }
  31376. if (sampler) {
  31377. // Only support sample the first dim mapped from value axis.
  31378. seriesModel.setData(data.downSample(
  31379. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  31380. ));
  31381. }
  31382. }
  31383. }
  31384. }
  31385. };
  31386. };
  31387. /*
  31388. * Licensed to the Apache Software Foundation (ASF) under one
  31389. * or more contributor license agreements. See the NOTICE file
  31390. * distributed with this work for additional information
  31391. * regarding copyright ownership. The ASF licenses this file
  31392. * to you under the Apache License, Version 2.0 (the
  31393. * "License"); you may not use this file except in compliance
  31394. * with the License. You may obtain a copy of the License at
  31395. *
  31396. * http://www.apache.org/licenses/LICENSE-2.0
  31397. *
  31398. * Unless required by applicable law or agreed to in writing,
  31399. * software distributed under the License is distributed on an
  31400. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31401. * KIND, either express or implied. See the License for the
  31402. * specific language governing permissions and limitations
  31403. * under the License.
  31404. */
  31405. /**
  31406. * Cartesian coordinate system
  31407. * @module echarts/coord/Cartesian
  31408. *
  31409. */
  31410. function dimAxisMapper(dim) {
  31411. return this._axes[dim];
  31412. }
  31413. /**
  31414. * @alias module:echarts/coord/Cartesian
  31415. * @constructor
  31416. */
  31417. var Cartesian = function (name) {
  31418. this._axes = {};
  31419. this._dimList = [];
  31420. /**
  31421. * @type {string}
  31422. */
  31423. this.name = name || '';
  31424. };
  31425. Cartesian.prototype = {
  31426. constructor: Cartesian,
  31427. type: 'cartesian',
  31428. /**
  31429. * Get axis
  31430. * @param {number|string} dim
  31431. * @return {module:echarts/coord/Cartesian~Axis}
  31432. */
  31433. getAxis: function (dim) {
  31434. return this._axes[dim];
  31435. },
  31436. /**
  31437. * Get axes list
  31438. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  31439. */
  31440. getAxes: function () {
  31441. return map(this._dimList, dimAxisMapper, this);
  31442. },
  31443. /**
  31444. * Get axes list by given scale type
  31445. */
  31446. getAxesByScale: function (scaleType) {
  31447. scaleType = scaleType.toLowerCase();
  31448. return filter(
  31449. this.getAxes(),
  31450. function (axis) {
  31451. return axis.scale.type === scaleType;
  31452. }
  31453. );
  31454. },
  31455. /**
  31456. * Add axis
  31457. * @param {module:echarts/coord/Cartesian.Axis}
  31458. */
  31459. addAxis: function (axis) {
  31460. var dim = axis.dim;
  31461. this._axes[dim] = axis;
  31462. this._dimList.push(dim);
  31463. },
  31464. /**
  31465. * Convert data to coord in nd space
  31466. * @param {Array.<number>|Object.<string, number>} val
  31467. * @return {Array.<number>|Object.<string, number>}
  31468. */
  31469. dataToCoord: function (val) {
  31470. return this._dataCoordConvert(val, 'dataToCoord');
  31471. },
  31472. /**
  31473. * Convert coord in nd space to data
  31474. * @param {Array.<number>|Object.<string, number>} val
  31475. * @return {Array.<number>|Object.<string, number>}
  31476. */
  31477. coordToData: function (val) {
  31478. return this._dataCoordConvert(val, 'coordToData');
  31479. },
  31480. _dataCoordConvert: function (input, method) {
  31481. var dimList = this._dimList;
  31482. var output = input instanceof Array ? [] : {};
  31483. for (var i = 0; i < dimList.length; i++) {
  31484. var dim = dimList[i];
  31485. var axis = this._axes[dim];
  31486. output[dim] = axis[method](input[dim]);
  31487. }
  31488. return output;
  31489. }
  31490. };
  31491. /*
  31492. * Licensed to the Apache Software Foundation (ASF) under one
  31493. * or more contributor license agreements. See the NOTICE file
  31494. * distributed with this work for additional information
  31495. * regarding copyright ownership. The ASF licenses this file
  31496. * to you under the Apache License, Version 2.0 (the
  31497. * "License"); you may not use this file except in compliance
  31498. * with the License. You may obtain a copy of the License at
  31499. *
  31500. * http://www.apache.org/licenses/LICENSE-2.0
  31501. *
  31502. * Unless required by applicable law or agreed to in writing,
  31503. * software distributed under the License is distributed on an
  31504. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31505. * KIND, either express or implied. See the License for the
  31506. * specific language governing permissions and limitations
  31507. * under the License.
  31508. */
  31509. function Cartesian2D(name) {
  31510. Cartesian.call(this, name);
  31511. }
  31512. Cartesian2D.prototype = {
  31513. constructor: Cartesian2D,
  31514. type: 'cartesian2d',
  31515. /**
  31516. * @type {Array.<string>}
  31517. * @readOnly
  31518. */
  31519. dimensions: ['x', 'y'],
  31520. /**
  31521. * Base axis will be used on stacking.
  31522. *
  31523. * @return {module:echarts/coord/cartesian/Axis2D}
  31524. */
  31525. getBaseAxis: function () {
  31526. return this.getAxesByScale('ordinal')[0]
  31527. || this.getAxesByScale('time')[0]
  31528. || this.getAxis('x');
  31529. },
  31530. /**
  31531. * If contain point
  31532. * @param {Array.<number>} point
  31533. * @return {boolean}
  31534. */
  31535. containPoint: function (point) {
  31536. var axisX = this.getAxis('x');
  31537. var axisY = this.getAxis('y');
  31538. return axisX.contain(axisX.toLocalCoord(point[0]))
  31539. && axisY.contain(axisY.toLocalCoord(point[1]));
  31540. },
  31541. /**
  31542. * If contain data
  31543. * @param {Array.<number>} data
  31544. * @return {boolean}
  31545. */
  31546. containData: function (data) {
  31547. return this.getAxis('x').containData(data[0])
  31548. && this.getAxis('y').containData(data[1]);
  31549. },
  31550. /**
  31551. * @param {Array.<number>} data
  31552. * @param {Array.<number>} out
  31553. * @return {Array.<number>}
  31554. */
  31555. dataToPoint: function (data, reserved, out) {
  31556. var xAxis = this.getAxis('x');
  31557. var yAxis = this.getAxis('y');
  31558. out = out || [];
  31559. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  31560. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  31561. return out;
  31562. },
  31563. /**
  31564. * @param {Array.<number>} data
  31565. * @param {Array.<number>} out
  31566. * @return {Array.<number>}
  31567. */
  31568. clampData: function (data, out) {
  31569. var xScale = this.getAxis('x').scale;
  31570. var yScale = this.getAxis('y').scale;
  31571. var xAxisExtent = xScale.getExtent();
  31572. var yAxisExtent = yScale.getExtent();
  31573. var x = xScale.parse(data[0]);
  31574. var y = yScale.parse(data[1]);
  31575. out = out || [];
  31576. out[0] = Math.min(
  31577. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  31578. Math.max(xAxisExtent[0], xAxisExtent[1])
  31579. );
  31580. out[1] = Math.min(
  31581. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  31582. Math.max(yAxisExtent[0], yAxisExtent[1])
  31583. );
  31584. return out;
  31585. },
  31586. /**
  31587. * @param {Array.<number>} point
  31588. * @param {Array.<number>} out
  31589. * @return {Array.<number>}
  31590. */
  31591. pointToData: function (point, out) {
  31592. var xAxis = this.getAxis('x');
  31593. var yAxis = this.getAxis('y');
  31594. out = out || [];
  31595. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  31596. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  31597. return out;
  31598. },
  31599. /**
  31600. * Get other axis
  31601. * @param {module:echarts/coord/cartesian/Axis2D} axis
  31602. */
  31603. getOtherAxis: function (axis) {
  31604. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  31605. }
  31606. };
  31607. inherits(Cartesian2D, Cartesian);
  31608. /*
  31609. * Licensed to the Apache Software Foundation (ASF) under one
  31610. * or more contributor license agreements. See the NOTICE file
  31611. * distributed with this work for additional information
  31612. * regarding copyright ownership. The ASF licenses this file
  31613. * to you under the Apache License, Version 2.0 (the
  31614. * "License"); you may not use this file except in compliance
  31615. * with the License. You may obtain a copy of the License at
  31616. *
  31617. * http://www.apache.org/licenses/LICENSE-2.0
  31618. *
  31619. * Unless required by applicable law or agreed to in writing,
  31620. * software distributed under the License is distributed on an
  31621. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31622. * KIND, either express or implied. See the License for the
  31623. * specific language governing permissions and limitations
  31624. * under the License.
  31625. */
  31626. /**
  31627. * Extend axis 2d
  31628. * @constructor module:echarts/coord/cartesian/Axis2D
  31629. * @extends {module:echarts/coord/cartesian/Axis}
  31630. * @param {string} dim
  31631. * @param {*} scale
  31632. * @param {Array.<number>} coordExtent
  31633. * @param {string} axisType
  31634. * @param {string} position
  31635. */
  31636. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  31637. Axis.call(this, dim, scale, coordExtent);
  31638. /**
  31639. * Axis type
  31640. * - 'category'
  31641. * - 'value'
  31642. * - 'time'
  31643. * - 'log'
  31644. * @type {string}
  31645. */
  31646. this.type = axisType || 'value';
  31647. /**
  31648. * Axis position
  31649. * - 'top'
  31650. * - 'bottom'
  31651. * - 'left'
  31652. * - 'right'
  31653. */
  31654. this.position = position || 'bottom';
  31655. };
  31656. Axis2D.prototype = {
  31657. constructor: Axis2D,
  31658. /**
  31659. * Index of axis, can be used as key
  31660. */
  31661. index: 0,
  31662. /**
  31663. * Implemented in <module:echarts/coord/cartesian/Grid>.
  31664. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  31665. * If not on zero of other axis, return null/undefined.
  31666. * If no axes, return an empty array.
  31667. */
  31668. getAxesOnZeroOf: null,
  31669. /**
  31670. * Axis model
  31671. * @param {module:echarts/coord/cartesian/AxisModel}
  31672. */
  31673. model: null,
  31674. isHorizontal: function () {
  31675. var position = this.position;
  31676. return position === 'top' || position === 'bottom';
  31677. },
  31678. /**
  31679. * Each item cooresponds to this.getExtent(), which
  31680. * means globalExtent[0] may greater than globalExtent[1],
  31681. * unless `asc` is input.
  31682. *
  31683. * @param {boolean} [asc]
  31684. * @return {Array.<number>}
  31685. */
  31686. getGlobalExtent: function (asc) {
  31687. var ret = this.getExtent();
  31688. ret[0] = this.toGlobalCoord(ret[0]);
  31689. ret[1] = this.toGlobalCoord(ret[1]);
  31690. asc && ret[0] > ret[1] && ret.reverse();
  31691. return ret;
  31692. },
  31693. getOtherAxis: function () {
  31694. this.grid.getOtherAxis();
  31695. },
  31696. /**
  31697. * @override
  31698. */
  31699. pointToData: function (point, clamp) {
  31700. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  31701. },
  31702. /**
  31703. * Transform global coord to local coord,
  31704. * i.e. var localCoord = axis.toLocalCoord(80);
  31705. * designate by module:echarts/coord/cartesian/Grid.
  31706. * @type {Function}
  31707. */
  31708. toLocalCoord: null,
  31709. /**
  31710. * Transform global coord to local coord,
  31711. * i.e. var globalCoord = axis.toLocalCoord(40);
  31712. * designate by module:echarts/coord/cartesian/Grid.
  31713. * @type {Function}
  31714. */
  31715. toGlobalCoord: null
  31716. };
  31717. inherits(Axis2D, Axis);
  31718. /*
  31719. * Licensed to the Apache Software Foundation (ASF) under one
  31720. * or more contributor license agreements. See the NOTICE file
  31721. * distributed with this work for additional information
  31722. * regarding copyright ownership. The ASF licenses this file
  31723. * to you under the Apache License, Version 2.0 (the
  31724. * "License"); you may not use this file except in compliance
  31725. * with the License. You may obtain a copy of the License at
  31726. *
  31727. * http://www.apache.org/licenses/LICENSE-2.0
  31728. *
  31729. * Unless required by applicable law or agreed to in writing,
  31730. * software distributed under the License is distributed on an
  31731. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31732. * KIND, either express or implied. See the License for the
  31733. * specific language governing permissions and limitations
  31734. * under the License.
  31735. */
  31736. var defaultOption = {
  31737. show: true,
  31738. zlevel: 0,
  31739. z: 0,
  31740. // Inverse the axis.
  31741. inverse: false,
  31742. // Axis name displayed.
  31743. name: '',
  31744. // 'start' | 'middle' | 'end'
  31745. nameLocation: 'end',
  31746. // By degree. By defualt auto rotate by nameLocation.
  31747. nameRotate: null,
  31748. nameTruncate: {
  31749. maxWidth: null,
  31750. ellipsis: '...',
  31751. placeholder: '.'
  31752. },
  31753. // Use global text style by default.
  31754. nameTextStyle: {},
  31755. // The gap between axisName and axisLine.
  31756. nameGap: 15,
  31757. // Default `false` to support tooltip.
  31758. silent: false,
  31759. // Default `false` to avoid legacy user event listener fail.
  31760. triggerEvent: false,
  31761. tooltip: {
  31762. show: false
  31763. },
  31764. axisPointer: {},
  31765. axisLine: {
  31766. show: true,
  31767. onZero: true,
  31768. onZeroAxisIndex: null,
  31769. lineStyle: {
  31770. color: '#333',
  31771. width: 1,
  31772. type: 'solid'
  31773. },
  31774. // The arrow at both ends the the axis.
  31775. symbol: ['none', 'none'],
  31776. symbolSize: [10, 15]
  31777. },
  31778. axisTick: {
  31779. show: true,
  31780. // Whether axisTick is inside the grid or outside the grid.
  31781. inside: false,
  31782. // The length of axisTick.
  31783. length: 5,
  31784. lineStyle: {
  31785. width: 1
  31786. }
  31787. },
  31788. axisLabel: {
  31789. show: true,
  31790. // Whether axisLabel is inside the grid or outside the grid.
  31791. inside: false,
  31792. rotate: 0,
  31793. // true | false | null/undefined (auto)
  31794. showMinLabel: null,
  31795. // true | false | null/undefined (auto)
  31796. showMaxLabel: null,
  31797. margin: 8,
  31798. // formatter: null,
  31799. fontSize: 12
  31800. },
  31801. splitLine: {
  31802. show: true,
  31803. lineStyle: {
  31804. color: ['#ccc'],
  31805. width: 1,
  31806. type: 'solid'
  31807. }
  31808. },
  31809. splitArea: {
  31810. show: false,
  31811. areaStyle: {
  31812. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  31813. }
  31814. }
  31815. };
  31816. var axisDefault = {};
  31817. axisDefault.categoryAxis = merge({
  31818. // The gap at both ends of the axis. For categoryAxis, boolean.
  31819. boundaryGap: true,
  31820. // Set false to faster category collection.
  31821. // Only usefull in the case like: category is
  31822. // ['2012-01-01', '2012-01-02', ...], where the input
  31823. // data has been ensured not duplicate and is large data.
  31824. // null means "auto":
  31825. // if axis.data provided, do not deduplication,
  31826. // else do deduplication.
  31827. deduplication: null,
  31828. // splitArea: {
  31829. // show: false
  31830. // },
  31831. splitLine: {
  31832. show: false
  31833. },
  31834. axisTick: {
  31835. // If tick is align with label when boundaryGap is true
  31836. alignWithLabel: false,
  31837. interval: 'auto'
  31838. },
  31839. axisLabel: {
  31840. interval: 'auto'
  31841. }
  31842. }, defaultOption);
  31843. axisDefault.valueAxis = merge({
  31844. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  31845. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  31846. boundaryGap: [0, 0],
  31847. // TODO
  31848. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  31849. // Min value of the axis. can be:
  31850. // + a number
  31851. // + 'dataMin': use the min value in data.
  31852. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  31853. // min: null,
  31854. // Max value of the axis. can be:
  31855. // + a number
  31856. // + 'dataMax': use the max value in data.
  31857. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  31858. // max: null,
  31859. // Readonly prop, specifies start value of the range when using data zoom.
  31860. // rangeStart: null
  31861. // Readonly prop, specifies end value of the range when using data zoom.
  31862. // rangeEnd: null
  31863. // Optional value can be:
  31864. // + `false`: always include value 0.
  31865. // + `true`: the extent do not consider value 0.
  31866. // scale: false,
  31867. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  31868. splitNumber: 5
  31869. // Interval specifies the span of the ticks is mandatorily.
  31870. // interval: null
  31871. // Specify min interval when auto calculate tick interval.
  31872. // minInterval: null
  31873. // Specify max interval when auto calculate tick interval.
  31874. // maxInterval: null
  31875. }, defaultOption);
  31876. axisDefault.timeAxis = defaults({
  31877. scale: true,
  31878. min: 'dataMin',
  31879. max: 'dataMax'
  31880. }, axisDefault.valueAxis);
  31881. axisDefault.logAxis = defaults({
  31882. scale: true,
  31883. logBase: 10
  31884. }, axisDefault.valueAxis);
  31885. /*
  31886. * Licensed to the Apache Software Foundation (ASF) under one
  31887. * or more contributor license agreements. See the NOTICE file
  31888. * distributed with this work for additional information
  31889. * regarding copyright ownership. The ASF licenses this file
  31890. * to you under the Apache License, Version 2.0 (the
  31891. * "License"); you may not use this file except in compliance
  31892. * with the License. You may obtain a copy of the License at
  31893. *
  31894. * http://www.apache.org/licenses/LICENSE-2.0
  31895. *
  31896. * Unless required by applicable law or agreed to in writing,
  31897. * software distributed under the License is distributed on an
  31898. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31899. * KIND, either express or implied. See the License for the
  31900. * specific language governing permissions and limitations
  31901. * under the License.
  31902. */
  31903. // FIXME axisType is fixed ?
  31904. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  31905. /**
  31906. * Generate sub axis model class
  31907. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  31908. * @param {module:echarts/model/Component} BaseAxisModelClass
  31909. * @param {Function} axisTypeDefaulter
  31910. * @param {Object} [extraDefaultOption]
  31911. */
  31912. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  31913. each$1(AXIS_TYPES, function (axisType) {
  31914. BaseAxisModelClass.extend({
  31915. /**
  31916. * @readOnly
  31917. */
  31918. type: axisName + 'Axis.' + axisType,
  31919. mergeDefaultAndTheme: function (option, ecModel) {
  31920. var layoutMode = this.layoutMode;
  31921. var inputPositionParams = layoutMode
  31922. ? getLayoutParams(option) : {};
  31923. var themeModel = ecModel.getTheme();
  31924. merge(option, themeModel.get(axisType + 'Axis'));
  31925. merge(option, this.getDefaultOption());
  31926. option.type = axisTypeDefaulter(axisName, option);
  31927. if (layoutMode) {
  31928. mergeLayoutParam(option, inputPositionParams, layoutMode);
  31929. }
  31930. },
  31931. /**
  31932. * @override
  31933. */
  31934. optionUpdated: function () {
  31935. var thisOption = this.option;
  31936. if (thisOption.type === 'category') {
  31937. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  31938. }
  31939. },
  31940. /**
  31941. * Should not be called before all of 'getInitailData' finished.
  31942. * Because categories are collected during initializing data.
  31943. */
  31944. getCategories: function (rawData) {
  31945. var option = this.option;
  31946. // FIXME
  31947. // warning if called before all of 'getInitailData' finished.
  31948. if (option.type === 'category') {
  31949. if (rawData) {
  31950. return option.data;
  31951. }
  31952. return this.__ordinalMeta.categories;
  31953. }
  31954. },
  31955. getOrdinalMeta: function () {
  31956. return this.__ordinalMeta;
  31957. },
  31958. defaultOption: mergeAll(
  31959. [
  31960. {},
  31961. axisDefault[axisType + 'Axis'],
  31962. extraDefaultOption
  31963. ],
  31964. true
  31965. )
  31966. });
  31967. });
  31968. ComponentModel.registerSubTypeDefaulter(
  31969. axisName + 'Axis',
  31970. curry(axisTypeDefaulter, axisName)
  31971. );
  31972. };
  31973. /*
  31974. * Licensed to the Apache Software Foundation (ASF) under one
  31975. * or more contributor license agreements. See the NOTICE file
  31976. * distributed with this work for additional information
  31977. * regarding copyright ownership. The ASF licenses this file
  31978. * to you under the Apache License, Version 2.0 (the
  31979. * "License"); you may not use this file except in compliance
  31980. * with the License. You may obtain a copy of the License at
  31981. *
  31982. * http://www.apache.org/licenses/LICENSE-2.0
  31983. *
  31984. * Unless required by applicable law or agreed to in writing,
  31985. * software distributed under the License is distributed on an
  31986. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31987. * KIND, either express or implied. See the License for the
  31988. * specific language governing permissions and limitations
  31989. * under the License.
  31990. */
  31991. var AxisModel = ComponentModel.extend({
  31992. type: 'cartesian2dAxis',
  31993. /**
  31994. * @type {module:echarts/coord/cartesian/Axis2D}
  31995. */
  31996. axis: null,
  31997. /**
  31998. * @override
  31999. */
  32000. init: function () {
  32001. AxisModel.superApply(this, 'init', arguments);
  32002. this.resetRange();
  32003. },
  32004. /**
  32005. * @override
  32006. */
  32007. mergeOption: function () {
  32008. AxisModel.superApply(this, 'mergeOption', arguments);
  32009. this.resetRange();
  32010. },
  32011. /**
  32012. * @override
  32013. */
  32014. restoreData: function () {
  32015. AxisModel.superApply(this, 'restoreData', arguments);
  32016. this.resetRange();
  32017. },
  32018. /**
  32019. * @override
  32020. * @return {module:echarts/model/Component}
  32021. */
  32022. getCoordSysModel: function () {
  32023. return this.ecModel.queryComponents({
  32024. mainType: 'grid',
  32025. index: this.option.gridIndex,
  32026. id: this.option.gridId
  32027. })[0];
  32028. }
  32029. });
  32030. function getAxisType(axisDim, option) {
  32031. // Default axis with data is category axis
  32032. return option.type || (option.data ? 'category' : 'value');
  32033. }
  32034. merge(AxisModel.prototype, axisModelCommonMixin);
  32035. var extraOption = {
  32036. // gridIndex: 0,
  32037. // gridId: '',
  32038. // Offset is for multiple axis on the same position
  32039. offset: 0
  32040. };
  32041. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  32042. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  32043. /*
  32044. * Licensed to the Apache Software Foundation (ASF) under one
  32045. * or more contributor license agreements. See the NOTICE file
  32046. * distributed with this work for additional information
  32047. * regarding copyright ownership. The ASF licenses this file
  32048. * to you under the Apache License, Version 2.0 (the
  32049. * "License"); you may not use this file except in compliance
  32050. * with the License. You may obtain a copy of the License at
  32051. *
  32052. * http://www.apache.org/licenses/LICENSE-2.0
  32053. *
  32054. * Unless required by applicable law or agreed to in writing,
  32055. * software distributed under the License is distributed on an
  32056. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32057. * KIND, either express or implied. See the License for the
  32058. * specific language governing permissions and limitations
  32059. * under the License.
  32060. */
  32061. // Grid 是在有直角坐标系的时候必须要存在的
  32062. // 所以这里也要被 Cartesian2D 依赖
  32063. ComponentModel.extend({
  32064. type: 'grid',
  32065. dependencies: ['xAxis', 'yAxis'],
  32066. layoutMode: 'box',
  32067. /**
  32068. * @type {module:echarts/coord/cartesian/Grid}
  32069. */
  32070. coordinateSystem: null,
  32071. defaultOption: {
  32072. show: false,
  32073. zlevel: 0,
  32074. z: 0,
  32075. left: '10%',
  32076. top: 60,
  32077. right: '10%',
  32078. bottom: 60,
  32079. // If grid size contain label
  32080. containLabel: false,
  32081. // width: {totalWidth} - left - right,
  32082. // height: {totalHeight} - top - bottom,
  32083. backgroundColor: 'rgba(0,0,0,0)',
  32084. borderWidth: 1,
  32085. borderColor: '#ccc'
  32086. }
  32087. });
  32088. /*
  32089. * Licensed to the Apache Software Foundation (ASF) under one
  32090. * or more contributor license agreements. See the NOTICE file
  32091. * distributed with this work for additional information
  32092. * regarding copyright ownership. The ASF licenses this file
  32093. * to you under the Apache License, Version 2.0 (the
  32094. * "License"); you may not use this file except in compliance
  32095. * with the License. You may obtain a copy of the License at
  32096. *
  32097. * http://www.apache.org/licenses/LICENSE-2.0
  32098. *
  32099. * Unless required by applicable law or agreed to in writing,
  32100. * software distributed under the License is distributed on an
  32101. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32102. * KIND, either express or implied. See the License for the
  32103. * specific language governing permissions and limitations
  32104. * under the License.
  32105. */
  32106. /**
  32107. * Grid is a region which contains at most 4 cartesian systems
  32108. *
  32109. * TODO Default cartesian
  32110. */
  32111. // Depends on GridModel, AxisModel, which performs preprocess.
  32112. /**
  32113. * Check if the axis is used in the specified grid
  32114. * @inner
  32115. */
  32116. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  32117. return axisModel.getCoordSysModel() === gridModel;
  32118. }
  32119. function Grid(gridModel, ecModel, api) {
  32120. /**
  32121. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  32122. * @private
  32123. */
  32124. this._coordsMap = {};
  32125. /**
  32126. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  32127. * @private
  32128. */
  32129. this._coordsList = [];
  32130. /**
  32131. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  32132. * @private
  32133. */
  32134. this._axesMap = {};
  32135. /**
  32136. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  32137. * @private
  32138. */
  32139. this._axesList = [];
  32140. this._initCartesian(gridModel, ecModel, api);
  32141. this.model = gridModel;
  32142. }
  32143. var gridProto = Grid.prototype;
  32144. gridProto.type = 'grid';
  32145. gridProto.axisPointerEnabled = true;
  32146. gridProto.getRect = function () {
  32147. return this._rect;
  32148. };
  32149. gridProto.update = function (ecModel, api) {
  32150. var axesMap = this._axesMap;
  32151. this._updateScale(ecModel, this.model);
  32152. each$1(axesMap.x, function (xAxis) {
  32153. niceScaleExtent(xAxis.scale, xAxis.model);
  32154. });
  32155. each$1(axesMap.y, function (yAxis) {
  32156. niceScaleExtent(yAxis.scale, yAxis.model);
  32157. });
  32158. each$1(axesMap.x, function (xAxis) {
  32159. fixAxisOnZero(axesMap, 'y', xAxis);
  32160. });
  32161. each$1(axesMap.y, function (yAxis) {
  32162. fixAxisOnZero(axesMap, 'x', yAxis);
  32163. });
  32164. // Resize again if containLabel is enabled
  32165. // FIXME It may cause getting wrong grid size in data processing stage
  32166. this.resize(this.model, api);
  32167. };
  32168. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  32169. axis.getAxesOnZeroOf = function () {
  32170. // TODO: onZero of multiple axes.
  32171. return otherAxis ? [otherAxis] : [];
  32172. };
  32173. // onZero can not be enabled in these two situations:
  32174. // 1. When any other axis is a category axis.
  32175. // 2. When no axis is cross 0 point.
  32176. var otherAxes = axesMap[otherAxisDim];
  32177. var otherAxis;
  32178. var axisModel = axis.model;
  32179. var onZero = axisModel.get('axisLine.onZero');
  32180. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  32181. if (!onZero) {
  32182. return;
  32183. }
  32184. // If target axis is specified.
  32185. if (onZeroAxisIndex != null) {
  32186. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  32187. otherAxis = otherAxes[onZeroAxisIndex];
  32188. }
  32189. return;
  32190. }
  32191. // Find the first available other axis.
  32192. for (var idx in otherAxes) {
  32193. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx])) {
  32194. otherAxis = otherAxes[idx];
  32195. break;
  32196. }
  32197. }
  32198. }
  32199. function canOnZeroToAxis(axis) {
  32200. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  32201. }
  32202. /**
  32203. * Resize the grid
  32204. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  32205. * @param {module:echarts/ExtensionAPI} api
  32206. */
  32207. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  32208. var gridRect = getLayoutRect(
  32209. gridModel.getBoxLayoutParams(), {
  32210. width: api.getWidth(),
  32211. height: api.getHeight()
  32212. });
  32213. this._rect = gridRect;
  32214. var axesList = this._axesList;
  32215. adjustAxes();
  32216. // Minus label size
  32217. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  32218. each$1(axesList, function (axis) {
  32219. if (!axis.model.get('axisLabel.inside')) {
  32220. var labelUnionRect = estimateLabelUnionRect(axis);
  32221. if (labelUnionRect) {
  32222. var dim = axis.isHorizontal() ? 'height' : 'width';
  32223. var margin = axis.model.get('axisLabel.margin');
  32224. gridRect[dim] -= labelUnionRect[dim] + margin;
  32225. if (axis.position === 'top') {
  32226. gridRect.y += labelUnionRect.height + margin;
  32227. }
  32228. else if (axis.position === 'left') {
  32229. gridRect.x += labelUnionRect.width + margin;
  32230. }
  32231. }
  32232. }
  32233. });
  32234. adjustAxes();
  32235. }
  32236. function adjustAxes() {
  32237. each$1(axesList, function (axis) {
  32238. var isHorizontal = axis.isHorizontal();
  32239. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  32240. var idx = axis.inverse ? 1 : 0;
  32241. axis.setExtent(extent[idx], extent[1 - idx]);
  32242. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  32243. });
  32244. }
  32245. };
  32246. /**
  32247. * @param {string} axisType
  32248. * @param {number} [axisIndex]
  32249. */
  32250. gridProto.getAxis = function (axisType, axisIndex) {
  32251. var axesMapOnDim = this._axesMap[axisType];
  32252. if (axesMapOnDim != null) {
  32253. if (axisIndex == null) {
  32254. // Find first axis
  32255. for (var name in axesMapOnDim) {
  32256. if (axesMapOnDim.hasOwnProperty(name)) {
  32257. return axesMapOnDim[name];
  32258. }
  32259. }
  32260. }
  32261. return axesMapOnDim[axisIndex];
  32262. }
  32263. };
  32264. /**
  32265. * @return {Array.<module:echarts/coord/Axis>}
  32266. */
  32267. gridProto.getAxes = function () {
  32268. return this._axesList.slice();
  32269. };
  32270. /**
  32271. * Usage:
  32272. * grid.getCartesian(xAxisIndex, yAxisIndex);
  32273. * grid.getCartesian(xAxisIndex);
  32274. * grid.getCartesian(null, yAxisIndex);
  32275. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  32276. *
  32277. * @param {number|Object} [xAxisIndex]
  32278. * @param {number} [yAxisIndex]
  32279. */
  32280. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  32281. if (xAxisIndex != null && yAxisIndex != null) {
  32282. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  32283. return this._coordsMap[key];
  32284. }
  32285. if (isObject$1(xAxisIndex)) {
  32286. yAxisIndex = xAxisIndex.yAxisIndex;
  32287. xAxisIndex = xAxisIndex.xAxisIndex;
  32288. }
  32289. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  32290. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  32291. if (coordList[i].getAxis('x').index === xAxisIndex
  32292. || coordList[i].getAxis('y').index === yAxisIndex
  32293. ) {
  32294. return coordList[i];
  32295. }
  32296. }
  32297. };
  32298. gridProto.getCartesians = function () {
  32299. return this._coordsList.slice();
  32300. };
  32301. /**
  32302. * @implements
  32303. * see {module:echarts/CoodinateSystem}
  32304. */
  32305. gridProto.convertToPixel = function (ecModel, finder, value) {
  32306. var target = this._findConvertTarget(ecModel, finder);
  32307. return target.cartesian
  32308. ? target.cartesian.dataToPoint(value)
  32309. : target.axis
  32310. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  32311. : null;
  32312. };
  32313. /**
  32314. * @implements
  32315. * see {module:echarts/CoodinateSystem}
  32316. */
  32317. gridProto.convertFromPixel = function (ecModel, finder, value) {
  32318. var target = this._findConvertTarget(ecModel, finder);
  32319. return target.cartesian
  32320. ? target.cartesian.pointToData(value)
  32321. : target.axis
  32322. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  32323. : null;
  32324. };
  32325. /**
  32326. * @inner
  32327. */
  32328. gridProto._findConvertTarget = function (ecModel, finder) {
  32329. var seriesModel = finder.seriesModel;
  32330. var xAxisModel = finder.xAxisModel
  32331. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  32332. var yAxisModel = finder.yAxisModel
  32333. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  32334. var gridModel = finder.gridModel;
  32335. var coordsList = this._coordsList;
  32336. var cartesian;
  32337. var axis;
  32338. if (seriesModel) {
  32339. cartesian = seriesModel.coordinateSystem;
  32340. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  32341. }
  32342. else if (xAxisModel && yAxisModel) {
  32343. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  32344. }
  32345. else if (xAxisModel) {
  32346. axis = this.getAxis('x', xAxisModel.componentIndex);
  32347. }
  32348. else if (yAxisModel) {
  32349. axis = this.getAxis('y', yAxisModel.componentIndex);
  32350. }
  32351. // Lowest priority.
  32352. else if (gridModel) {
  32353. var grid = gridModel.coordinateSystem;
  32354. if (grid === this) {
  32355. cartesian = this._coordsList[0];
  32356. }
  32357. }
  32358. return {cartesian: cartesian, axis: axis};
  32359. };
  32360. /**
  32361. * @implements
  32362. * see {module:echarts/CoodinateSystem}
  32363. */
  32364. gridProto.containPoint = function (point) {
  32365. var coord = this._coordsList[0];
  32366. if (coord) {
  32367. return coord.containPoint(point);
  32368. }
  32369. };
  32370. /**
  32371. * Initialize cartesian coordinate systems
  32372. * @private
  32373. */
  32374. gridProto._initCartesian = function (gridModel, ecModel, api) {
  32375. var axisPositionUsed = {
  32376. left: false,
  32377. right: false,
  32378. top: false,
  32379. bottom: false
  32380. };
  32381. var axesMap = {
  32382. x: {},
  32383. y: {}
  32384. };
  32385. var axesCount = {
  32386. x: 0,
  32387. y: 0
  32388. };
  32389. /// Create axis
  32390. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  32391. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  32392. if (!axesCount.x || !axesCount.y) {
  32393. // Roll back when there no either x or y axis
  32394. this._axesMap = {};
  32395. this._axesList = [];
  32396. return;
  32397. }
  32398. this._axesMap = axesMap;
  32399. /// Create cartesian2d
  32400. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  32401. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  32402. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  32403. var cartesian = new Cartesian2D(key);
  32404. cartesian.grid = this;
  32405. cartesian.model = gridModel;
  32406. this._coordsMap[key] = cartesian;
  32407. this._coordsList.push(cartesian);
  32408. cartesian.addAxis(xAxis);
  32409. cartesian.addAxis(yAxis);
  32410. }, this);
  32411. }, this);
  32412. function createAxisCreator(axisType) {
  32413. return function (axisModel, idx) {
  32414. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  32415. return;
  32416. }
  32417. var axisPosition = axisModel.get('position');
  32418. if (axisType === 'x') {
  32419. // Fix position
  32420. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  32421. // Default bottom of X
  32422. axisPosition = 'bottom';
  32423. if (axisPositionUsed[axisPosition]) {
  32424. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  32425. }
  32426. }
  32427. }
  32428. else {
  32429. // Fix position
  32430. if (axisPosition !== 'left' && axisPosition !== 'right') {
  32431. // Default left of Y
  32432. axisPosition = 'left';
  32433. if (axisPositionUsed[axisPosition]) {
  32434. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  32435. }
  32436. }
  32437. }
  32438. axisPositionUsed[axisPosition] = true;
  32439. var axis = new Axis2D(
  32440. axisType, createScaleByModel(axisModel),
  32441. [0, 0],
  32442. axisModel.get('type'),
  32443. axisPosition
  32444. );
  32445. var isCategory = axis.type === 'category';
  32446. axis.onBand = isCategory && axisModel.get('boundaryGap');
  32447. axis.inverse = axisModel.get('inverse');
  32448. // Inject axis into axisModel
  32449. axisModel.axis = axis;
  32450. // Inject axisModel into axis
  32451. axis.model = axisModel;
  32452. // Inject grid info axis
  32453. axis.grid = this;
  32454. // Index of axis, can be used as key
  32455. axis.index = idx;
  32456. this._axesList.push(axis);
  32457. axesMap[axisType][idx] = axis;
  32458. axesCount[axisType]++;
  32459. };
  32460. }
  32461. };
  32462. /**
  32463. * Update cartesian properties from series
  32464. * @param {module:echarts/model/Option} option
  32465. * @private
  32466. */
  32467. gridProto._updateScale = function (ecModel, gridModel) {
  32468. // Reset scale
  32469. each$1(this._axesList, function (axis) {
  32470. axis.scale.setExtent(Infinity, -Infinity);
  32471. });
  32472. ecModel.eachSeries(function (seriesModel) {
  32473. if (isCartesian2D(seriesModel)) {
  32474. var axesModels = findAxesModels(seriesModel, ecModel);
  32475. var xAxisModel = axesModels[0];
  32476. var yAxisModel = axesModels[1];
  32477. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  32478. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  32479. ) {
  32480. return;
  32481. }
  32482. var cartesian = this.getCartesian(
  32483. xAxisModel.componentIndex, yAxisModel.componentIndex
  32484. );
  32485. var data = seriesModel.getData();
  32486. var xAxis = cartesian.getAxis('x');
  32487. var yAxis = cartesian.getAxis('y');
  32488. if (data.type === 'list') {
  32489. unionExtent(data, xAxis, seriesModel);
  32490. unionExtent(data, yAxis, seriesModel);
  32491. }
  32492. }
  32493. }, this);
  32494. function unionExtent(data, axis, seriesModel) {
  32495. each$1(data.mapDimension(axis.dim, true), function (dim) {
  32496. axis.scale.unionExtentFromData(
  32497. // For example, the extent of the orginal dimension
  32498. // is [0.1, 0.5], the extent of the `stackResultDimension`
  32499. // is [7, 9], the final extent should not include [0.1, 0.5].
  32500. data, getStackedDimension(data, dim)
  32501. );
  32502. });
  32503. }
  32504. };
  32505. /**
  32506. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  32507. * @return {Object} {baseAxes: [], otherAxes: []}
  32508. */
  32509. gridProto.getTooltipAxes = function (dim) {
  32510. var baseAxes = [];
  32511. var otherAxes = [];
  32512. each$1(this.getCartesians(), function (cartesian) {
  32513. var baseAxis = (dim != null && dim !== 'auto')
  32514. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  32515. var otherAxis = cartesian.getOtherAxis(baseAxis);
  32516. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  32517. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  32518. });
  32519. return {baseAxes: baseAxes, otherAxes: otherAxes};
  32520. };
  32521. /**
  32522. * @inner
  32523. */
  32524. function updateAxisTransform(axis, coordBase) {
  32525. var axisExtent = axis.getExtent();
  32526. var axisExtentSum = axisExtent[0] + axisExtent[1];
  32527. // Fast transform
  32528. axis.toGlobalCoord = axis.dim === 'x'
  32529. ? function (coord) {
  32530. return coord + coordBase;
  32531. }
  32532. : function (coord) {
  32533. return axisExtentSum - coord + coordBase;
  32534. };
  32535. axis.toLocalCoord = axis.dim === 'x'
  32536. ? function (coord) {
  32537. return coord - coordBase;
  32538. }
  32539. : function (coord) {
  32540. return axisExtentSum - coord + coordBase;
  32541. };
  32542. }
  32543. var axesTypes = ['xAxis', 'yAxis'];
  32544. /**
  32545. * @inner
  32546. */
  32547. function findAxesModels(seriesModel, ecModel) {
  32548. return map(axesTypes, function (axisType) {
  32549. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  32550. if (__DEV__) {
  32551. if (!axisModel) {
  32552. throw new Error(axisType + ' "' + retrieve(
  32553. seriesModel.get(axisType + 'Index'),
  32554. seriesModel.get(axisType + 'Id'),
  32555. 0
  32556. ) + '" not found');
  32557. }
  32558. }
  32559. return axisModel;
  32560. });
  32561. }
  32562. /**
  32563. * @inner
  32564. */
  32565. function isCartesian2D(seriesModel) {
  32566. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  32567. }
  32568. Grid.create = function (ecModel, api) {
  32569. var grids = [];
  32570. ecModel.eachComponent('grid', function (gridModel, idx) {
  32571. var grid = new Grid(gridModel, ecModel, api);
  32572. grid.name = 'grid_' + idx;
  32573. // dataSampling requires axis extent, so resize
  32574. // should be performed in create stage.
  32575. grid.resize(gridModel, api, true);
  32576. gridModel.coordinateSystem = grid;
  32577. grids.push(grid);
  32578. });
  32579. // Inject the coordinateSystems into seriesModel
  32580. ecModel.eachSeries(function (seriesModel) {
  32581. if (!isCartesian2D(seriesModel)) {
  32582. return;
  32583. }
  32584. var axesModels = findAxesModels(seriesModel, ecModel);
  32585. var xAxisModel = axesModels[0];
  32586. var yAxisModel = axesModels[1];
  32587. var gridModel = xAxisModel.getCoordSysModel();
  32588. if (__DEV__) {
  32589. if (!gridModel) {
  32590. throw new Error(
  32591. 'Grid "' + retrieve(
  32592. xAxisModel.get('gridIndex'),
  32593. xAxisModel.get('gridId'),
  32594. 0
  32595. ) + '" not found'
  32596. );
  32597. }
  32598. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  32599. throw new Error('xAxis and yAxis must use the same grid');
  32600. }
  32601. }
  32602. var grid = gridModel.coordinateSystem;
  32603. seriesModel.coordinateSystem = grid.getCartesian(
  32604. xAxisModel.componentIndex, yAxisModel.componentIndex
  32605. );
  32606. });
  32607. return grids;
  32608. };
  32609. // For deciding which dimensions to use when creating list data
  32610. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  32611. CoordinateSystemManager.register('cartesian2d', Grid);
  32612. /*
  32613. * Licensed to the Apache Software Foundation (ASF) under one
  32614. * or more contributor license agreements. See the NOTICE file
  32615. * distributed with this work for additional information
  32616. * regarding copyright ownership. The ASF licenses this file
  32617. * to you under the Apache License, Version 2.0 (the
  32618. * "License"); you may not use this file except in compliance
  32619. * with the License. You may obtain a copy of the License at
  32620. *
  32621. * http://www.apache.org/licenses/LICENSE-2.0
  32622. *
  32623. * Unless required by applicable law or agreed to in writing,
  32624. * software distributed under the License is distributed on an
  32625. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32626. * KIND, either express or implied. See the License for the
  32627. * specific language governing permissions and limitations
  32628. * under the License.
  32629. */
  32630. var PI$2 = Math.PI;
  32631. function makeAxisEventDataBase(axisModel) {
  32632. var eventData = {
  32633. componentType: axisModel.mainType
  32634. };
  32635. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  32636. return eventData;
  32637. }
  32638. /**
  32639. * A final axis is translated and rotated from a "standard axis".
  32640. * So opt.position and opt.rotation is required.
  32641. *
  32642. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  32643. * for example: (0, 0) ------------> (0, 50)
  32644. *
  32645. * nameDirection or tickDirection or labelDirection is 1 means tick
  32646. * or label is below the standard axis, whereas is -1 means above
  32647. * the standard axis. labelOffset means offset between label and axis,
  32648. * which is useful when 'onZero', where axisLabel is in the grid and
  32649. * label in outside grid.
  32650. *
  32651. * Tips: like always,
  32652. * positive rotation represents anticlockwise, and negative rotation
  32653. * represents clockwise.
  32654. * The direction of position coordinate is the same as the direction
  32655. * of screen coordinate.
  32656. *
  32657. * Do not need to consider axis 'inverse', which is auto processed by
  32658. * axis extent.
  32659. *
  32660. * @param {module:zrender/container/Group} group
  32661. * @param {Object} axisModel
  32662. * @param {Object} opt Standard axis parameters.
  32663. * @param {Array.<number>} opt.position [x, y]
  32664. * @param {number} opt.rotation by radian
  32665. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  32666. * @param {number} [opt.tickDirection=1] 1 or -1
  32667. * @param {number} [opt.labelDirection=1] 1 or -1
  32668. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  32669. * @param {string} [opt.axisLabelShow] default get from axisModel.
  32670. * @param {string} [opt.axisName] default get from axisModel.
  32671. * @param {number} [opt.axisNameAvailableWidth]
  32672. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  32673. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  32674. * @param {number} [opt.nameTruncateMaxWidth]
  32675. */
  32676. var AxisBuilder = function (axisModel, opt) {
  32677. /**
  32678. * @readOnly
  32679. */
  32680. this.opt = opt;
  32681. /**
  32682. * @readOnly
  32683. */
  32684. this.axisModel = axisModel;
  32685. // Default value
  32686. defaults(
  32687. opt,
  32688. {
  32689. labelOffset: 0,
  32690. nameDirection: 1,
  32691. tickDirection: 1,
  32692. labelDirection: 1,
  32693. silent: true
  32694. }
  32695. );
  32696. /**
  32697. * @readOnly
  32698. */
  32699. this.group = new Group();
  32700. // FIXME Not use a seperate text group?
  32701. var dumbGroup = new Group({
  32702. position: opt.position.slice(),
  32703. rotation: opt.rotation
  32704. });
  32705. // this.group.add(dumbGroup);
  32706. // this._dumbGroup = dumbGroup;
  32707. dumbGroup.updateTransform();
  32708. this._transform = dumbGroup.transform;
  32709. this._dumbGroup = dumbGroup;
  32710. };
  32711. AxisBuilder.prototype = {
  32712. constructor: AxisBuilder,
  32713. hasBuilder: function (name) {
  32714. return !!builders[name];
  32715. },
  32716. add: function (name) {
  32717. builders[name].call(this);
  32718. },
  32719. getGroup: function () {
  32720. return this.group;
  32721. }
  32722. };
  32723. var builders = {
  32724. /**
  32725. * @private
  32726. */
  32727. axisLine: function () {
  32728. var opt = this.opt;
  32729. var axisModel = this.axisModel;
  32730. if (!axisModel.get('axisLine.show')) {
  32731. return;
  32732. }
  32733. var extent = this.axisModel.axis.getExtent();
  32734. var matrix = this._transform;
  32735. var pt1 = [extent[0], 0];
  32736. var pt2 = [extent[1], 0];
  32737. if (matrix) {
  32738. applyTransform(pt1, pt1, matrix);
  32739. applyTransform(pt2, pt2, matrix);
  32740. }
  32741. var lineStyle = extend(
  32742. {
  32743. lineCap: 'round'
  32744. },
  32745. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  32746. );
  32747. this.group.add(new Line(subPixelOptimizeLine({
  32748. // Id for animation
  32749. anid: 'line',
  32750. shape: {
  32751. x1: pt1[0],
  32752. y1: pt1[1],
  32753. x2: pt2[0],
  32754. y2: pt2[1]
  32755. },
  32756. style: lineStyle,
  32757. strokeContainThreshold: opt.strokeContainThreshold || 5,
  32758. silent: true,
  32759. z2: 1
  32760. })));
  32761. var arrows = axisModel.get('axisLine.symbol');
  32762. var arrowSize = axisModel.get('axisLine.symbolSize');
  32763. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  32764. if (typeof arrowOffset === 'number') {
  32765. arrowOffset = [arrowOffset, arrowOffset];
  32766. }
  32767. if (arrows != null) {
  32768. if (typeof arrows === 'string') {
  32769. // Use the same arrow for start and end point
  32770. arrows = [arrows, arrows];
  32771. }
  32772. if (typeof arrowSize === 'string'
  32773. || typeof arrowSize === 'number'
  32774. ) {
  32775. // Use the same size for width and height
  32776. arrowSize = [arrowSize, arrowSize];
  32777. }
  32778. var symbolWidth = arrowSize[0];
  32779. var symbolHeight = arrowSize[1];
  32780. each$1([{
  32781. rotate: opt.rotation + Math.PI / 2,
  32782. offset: arrowOffset[0],
  32783. r: 0
  32784. }, {
  32785. rotate: opt.rotation - Math.PI / 2,
  32786. offset: arrowOffset[1],
  32787. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  32788. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  32789. }], function (point, index) {
  32790. if (arrows[index] !== 'none' && arrows[index] != null) {
  32791. var symbol = createSymbol(
  32792. arrows[index],
  32793. -symbolWidth / 2,
  32794. -symbolHeight / 2,
  32795. symbolWidth,
  32796. symbolHeight,
  32797. lineStyle.stroke,
  32798. true
  32799. );
  32800. // Calculate arrow position with offset
  32801. var r = point.r + point.offset;
  32802. var pos = [
  32803. pt1[0] + r * Math.cos(opt.rotation),
  32804. pt1[1] - r * Math.sin(opt.rotation)
  32805. ];
  32806. symbol.attr({
  32807. rotation: point.rotate,
  32808. position: pos,
  32809. silent: true
  32810. });
  32811. this.group.add(symbol);
  32812. }
  32813. }, this);
  32814. }
  32815. },
  32816. /**
  32817. * @private
  32818. */
  32819. axisTickLabel: function () {
  32820. var axisModel = this.axisModel;
  32821. var opt = this.opt;
  32822. var tickEls = buildAxisTick(this, axisModel, opt);
  32823. var labelEls = buildAxisLabel(this, axisModel, opt);
  32824. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  32825. },
  32826. /**
  32827. * @private
  32828. */
  32829. axisName: function () {
  32830. var opt = this.opt;
  32831. var axisModel = this.axisModel;
  32832. var name = retrieve(opt.axisName, axisModel.get('name'));
  32833. if (!name) {
  32834. return;
  32835. }
  32836. var nameLocation = axisModel.get('nameLocation');
  32837. var nameDirection = opt.nameDirection;
  32838. var textStyleModel = axisModel.getModel('nameTextStyle');
  32839. var gap = axisModel.get('nameGap') || 0;
  32840. var extent = this.axisModel.axis.getExtent();
  32841. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  32842. var pos = [
  32843. nameLocation === 'start'
  32844. ? extent[0] - gapSignal * gap
  32845. : nameLocation === 'end'
  32846. ? extent[1] + gapSignal * gap
  32847. : (extent[0] + extent[1]) / 2, // 'middle'
  32848. // Reuse labelOffset.
  32849. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  32850. ];
  32851. var labelLayout;
  32852. var nameRotation = axisModel.get('nameRotate');
  32853. if (nameRotation != null) {
  32854. nameRotation = nameRotation * PI$2 / 180; // To radian.
  32855. }
  32856. var axisNameAvailableWidth;
  32857. if (isNameLocationCenter(nameLocation)) {
  32858. labelLayout = innerTextLayout(
  32859. opt.rotation,
  32860. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  32861. nameDirection
  32862. );
  32863. }
  32864. else {
  32865. labelLayout = endTextLayout(
  32866. opt, nameLocation, nameRotation || 0, extent
  32867. );
  32868. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  32869. if (axisNameAvailableWidth != null) {
  32870. axisNameAvailableWidth = Math.abs(
  32871. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  32872. );
  32873. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  32874. }
  32875. }
  32876. var textFont = textStyleModel.getFont();
  32877. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  32878. var ellipsis = truncateOpt.ellipsis;
  32879. var maxWidth = retrieve(
  32880. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  32881. );
  32882. // FIXME
  32883. // truncate rich text? (consider performance)
  32884. var truncatedText = (ellipsis != null && maxWidth != null)
  32885. ? truncateText$1(
  32886. name, maxWidth, textFont, ellipsis,
  32887. {minChar: 2, placeholder: truncateOpt.placeholder}
  32888. )
  32889. : name;
  32890. var tooltipOpt = axisModel.get('tooltip', true);
  32891. var mainType = axisModel.mainType;
  32892. var formatterParams = {
  32893. componentType: mainType,
  32894. name: name,
  32895. $vars: ['name']
  32896. };
  32897. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  32898. var textEl = new Text({
  32899. // Id for animation
  32900. anid: 'name',
  32901. __fullText: name,
  32902. __truncatedText: truncatedText,
  32903. position: pos,
  32904. rotation: labelLayout.rotation,
  32905. silent: isSilent(axisModel),
  32906. z2: 1,
  32907. tooltip: (tooltipOpt && tooltipOpt.show)
  32908. ? extend({
  32909. content: name,
  32910. formatter: function () {
  32911. return name;
  32912. },
  32913. formatterParams: formatterParams
  32914. }, tooltipOpt)
  32915. : null
  32916. });
  32917. setTextStyle(textEl.style, textStyleModel, {
  32918. text: truncatedText,
  32919. textFont: textFont,
  32920. textFill: textStyleModel.getTextColor()
  32921. || axisModel.get('axisLine.lineStyle.color'),
  32922. textAlign: labelLayout.textAlign,
  32923. textVerticalAlign: labelLayout.textVerticalAlign
  32924. });
  32925. if (axisModel.get('triggerEvent')) {
  32926. textEl.eventData = makeAxisEventDataBase(axisModel);
  32927. textEl.eventData.targetType = 'axisName';
  32928. textEl.eventData.name = name;
  32929. }
  32930. // FIXME
  32931. this._dumbGroup.add(textEl);
  32932. textEl.updateTransform();
  32933. this.group.add(textEl);
  32934. textEl.decomposeTransform();
  32935. }
  32936. };
  32937. /**
  32938. * @public
  32939. * @static
  32940. * @param {Object} opt
  32941. * @param {number} axisRotation in radian
  32942. * @param {number} textRotation in radian
  32943. * @param {number} direction
  32944. * @return {Object} {
  32945. * rotation, // according to axis
  32946. * textAlign,
  32947. * textVerticalAlign
  32948. * }
  32949. */
  32950. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  32951. var rotationDiff = remRadian(textRotation - axisRotation);
  32952. var textAlign;
  32953. var textVerticalAlign;
  32954. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  32955. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  32956. textAlign = 'center';
  32957. }
  32958. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  32959. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  32960. textAlign = 'center';
  32961. }
  32962. else {
  32963. textVerticalAlign = 'middle';
  32964. if (rotationDiff > 0 && rotationDiff < PI$2) {
  32965. textAlign = direction > 0 ? 'right' : 'left';
  32966. }
  32967. else {
  32968. textAlign = direction > 0 ? 'left' : 'right';
  32969. }
  32970. }
  32971. return {
  32972. rotation: rotationDiff,
  32973. textAlign: textAlign,
  32974. textVerticalAlign: textVerticalAlign
  32975. };
  32976. };
  32977. function endTextLayout(opt, textPosition, textRotate, extent) {
  32978. var rotationDiff = remRadian(textRotate - opt.rotation);
  32979. var textAlign;
  32980. var textVerticalAlign;
  32981. var inverse = extent[0] > extent[1];
  32982. var onLeft = (textPosition === 'start' && !inverse)
  32983. || (textPosition !== 'start' && inverse);
  32984. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  32985. textVerticalAlign = onLeft ? 'bottom' : 'top';
  32986. textAlign = 'center';
  32987. }
  32988. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  32989. textVerticalAlign = onLeft ? 'top' : 'bottom';
  32990. textAlign = 'center';
  32991. }
  32992. else {
  32993. textVerticalAlign = 'middle';
  32994. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  32995. textAlign = onLeft ? 'left' : 'right';
  32996. }
  32997. else {
  32998. textAlign = onLeft ? 'right' : 'left';
  32999. }
  33000. }
  33001. return {
  33002. rotation: rotationDiff,
  33003. textAlign: textAlign,
  33004. textVerticalAlign: textVerticalAlign
  33005. };
  33006. }
  33007. function isSilent(axisModel) {
  33008. var tooltipOpt = axisModel.get('tooltip');
  33009. return axisModel.get('silent')
  33010. // Consider mouse cursor, add these restrictions.
  33011. || !(
  33012. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  33013. );
  33014. }
  33015. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  33016. // If min or max are user set, we need to check
  33017. // If the tick on min(max) are overlap on their neighbour tick
  33018. // If they are overlapped, we need to hide the min(max) tick label
  33019. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  33020. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  33021. // FIXME
  33022. // Have not consider onBand yet, where tick els is more than label els.
  33023. labelEls = labelEls || [];
  33024. tickEls = tickEls || [];
  33025. var firstLabel = labelEls[0];
  33026. var nextLabel = labelEls[1];
  33027. var lastLabel = labelEls[labelEls.length - 1];
  33028. var prevLabel = labelEls[labelEls.length - 2];
  33029. var firstTick = tickEls[0];
  33030. var nextTick = tickEls[1];
  33031. var lastTick = tickEls[tickEls.length - 1];
  33032. var prevTick = tickEls[tickEls.length - 2];
  33033. if (showMinLabel === false) {
  33034. ignoreEl(firstLabel);
  33035. ignoreEl(firstTick);
  33036. }
  33037. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  33038. if (showMinLabel) {
  33039. ignoreEl(nextLabel);
  33040. ignoreEl(nextTick);
  33041. }
  33042. else {
  33043. ignoreEl(firstLabel);
  33044. ignoreEl(firstTick);
  33045. }
  33046. }
  33047. if (showMaxLabel === false) {
  33048. ignoreEl(lastLabel);
  33049. ignoreEl(lastTick);
  33050. }
  33051. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  33052. if (showMaxLabel) {
  33053. ignoreEl(prevLabel);
  33054. ignoreEl(prevTick);
  33055. }
  33056. else {
  33057. ignoreEl(lastLabel);
  33058. ignoreEl(lastTick);
  33059. }
  33060. }
  33061. }
  33062. function ignoreEl(el) {
  33063. el && (el.ignore = true);
  33064. }
  33065. function isTwoLabelOverlapped(current, next, labelLayout) {
  33066. // current and next has the same rotation.
  33067. var firstRect = current && current.getBoundingRect().clone();
  33068. var nextRect = next && next.getBoundingRect().clone();
  33069. if (!firstRect || !nextRect) {
  33070. return;
  33071. }
  33072. // When checking intersect of two rotated labels, we use mRotationBack
  33073. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  33074. var mRotationBack = identity([]);
  33075. rotate(mRotationBack, mRotationBack, -current.rotation);
  33076. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  33077. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  33078. return firstRect.intersect(nextRect);
  33079. }
  33080. function isNameLocationCenter(nameLocation) {
  33081. return nameLocation === 'middle' || nameLocation === 'center';
  33082. }
  33083. function buildAxisTick(axisBuilder, axisModel, opt) {
  33084. var axis = axisModel.axis;
  33085. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  33086. return;
  33087. }
  33088. var tickModel = axisModel.getModel('axisTick');
  33089. var lineStyleModel = tickModel.getModel('lineStyle');
  33090. var tickLen = tickModel.get('length');
  33091. var ticksCoords = axis.getTicksCoords();
  33092. var pt1 = [];
  33093. var pt2 = [];
  33094. var matrix = axisBuilder._transform;
  33095. var tickEls = [];
  33096. for (var i = 0; i < ticksCoords.length; i++) {
  33097. var tickCoord = ticksCoords[i].coord;
  33098. pt1[0] = tickCoord;
  33099. pt1[1] = 0;
  33100. pt2[0] = tickCoord;
  33101. pt2[1] = opt.tickDirection * tickLen;
  33102. if (matrix) {
  33103. applyTransform(pt1, pt1, matrix);
  33104. applyTransform(pt2, pt2, matrix);
  33105. }
  33106. // Tick line, Not use group transform to have better line draw
  33107. var tickEl = new Line(subPixelOptimizeLine({
  33108. // Id for animation
  33109. anid: 'tick_' + ticksCoords[i].tickValue,
  33110. shape: {
  33111. x1: pt1[0],
  33112. y1: pt1[1],
  33113. x2: pt2[0],
  33114. y2: pt2[1]
  33115. },
  33116. style: defaults(
  33117. lineStyleModel.getLineStyle(),
  33118. {
  33119. stroke: axisModel.get('axisLine.lineStyle.color')
  33120. }
  33121. ),
  33122. z2: 2,
  33123. silent: true
  33124. }));
  33125. axisBuilder.group.add(tickEl);
  33126. tickEls.push(tickEl);
  33127. }
  33128. return tickEls;
  33129. }
  33130. function buildAxisLabel(axisBuilder, axisModel, opt) {
  33131. var axis = axisModel.axis;
  33132. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  33133. if (!show || axis.scale.isBlank()) {
  33134. return;
  33135. }
  33136. var labelModel = axisModel.getModel('axisLabel');
  33137. var labelMargin = labelModel.get('margin');
  33138. var labels = axis.getViewLabels();
  33139. // Special label rotate.
  33140. var labelRotation = (
  33141. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  33142. ) * PI$2 / 180;
  33143. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  33144. var rawCategoryData = axisModel.getCategories(true);
  33145. var labelEls = [];
  33146. var silent = isSilent(axisModel);
  33147. var triggerEvent = axisModel.get('triggerEvent');
  33148. each$1(labels, function (labelItem, index) {
  33149. var tickValue = labelItem.tickValue;
  33150. var formattedLabel = labelItem.formattedLabel;
  33151. var rawLabel = labelItem.rawLabel;
  33152. var itemLabelModel = labelModel;
  33153. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  33154. itemLabelModel = new Model(
  33155. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  33156. );
  33157. }
  33158. var textColor = itemLabelModel.getTextColor()
  33159. || axisModel.get('axisLine.lineStyle.color');
  33160. var tickCoord = axis.dataToCoord(tickValue);
  33161. var pos = [
  33162. tickCoord,
  33163. opt.labelOffset + opt.labelDirection * labelMargin
  33164. ];
  33165. var textEl = new Text({
  33166. // Id for animation
  33167. anid: 'label_' + tickValue,
  33168. position: pos,
  33169. rotation: labelLayout.rotation,
  33170. silent: silent,
  33171. z2: 10
  33172. });
  33173. setTextStyle(textEl.style, itemLabelModel, {
  33174. text: formattedLabel,
  33175. textAlign: itemLabelModel.getShallow('align', true)
  33176. || labelLayout.textAlign,
  33177. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  33178. || itemLabelModel.getShallow('baseline', true)
  33179. || labelLayout.textVerticalAlign,
  33180. textFill: typeof textColor === 'function'
  33181. ? textColor(
  33182. // (1) In category axis with data zoom, tick is not the original
  33183. // index of axis.data. So tick should not be exposed to user
  33184. // in category axis.
  33185. // (2) Compatible with previous version, which always use formatted label as
  33186. // input. But in interval scale the formatted label is like '223,445', which
  33187. // maked user repalce ','. So we modify it to return original val but remain
  33188. // it as 'string' to avoid error in replacing.
  33189. axis.type === 'category'
  33190. ? rawLabel
  33191. : axis.type === 'value'
  33192. ? tickValue + ''
  33193. : tickValue,
  33194. index
  33195. )
  33196. : textColor
  33197. });
  33198. // Pack data for mouse event
  33199. if (triggerEvent) {
  33200. textEl.eventData = makeAxisEventDataBase(axisModel);
  33201. textEl.eventData.targetType = 'axisLabel';
  33202. textEl.eventData.value = rawLabel;
  33203. }
  33204. // FIXME
  33205. axisBuilder._dumbGroup.add(textEl);
  33206. textEl.updateTransform();
  33207. labelEls.push(textEl);
  33208. axisBuilder.group.add(textEl);
  33209. textEl.decomposeTransform();
  33210. });
  33211. return labelEls;
  33212. }
  33213. /*
  33214. * Licensed to the Apache Software Foundation (ASF) under one
  33215. * or more contributor license agreements. See the NOTICE file
  33216. * distributed with this work for additional information
  33217. * regarding copyright ownership. The ASF licenses this file
  33218. * to you under the Apache License, Version 2.0 (the
  33219. * "License"); you may not use this file except in compliance
  33220. * with the License. You may obtain a copy of the License at
  33221. *
  33222. * http://www.apache.org/licenses/LICENSE-2.0
  33223. *
  33224. * Unless required by applicable law or agreed to in writing,
  33225. * software distributed under the License is distributed on an
  33226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33227. * KIND, either express or implied. See the License for the
  33228. * specific language governing permissions and limitations
  33229. * under the License.
  33230. */
  33231. var each$6 = each$1;
  33232. var curry$1 = curry;
  33233. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  33234. // allAxesInfo should be updated when setOption performed.
  33235. function collect(ecModel, api) {
  33236. var result = {
  33237. /**
  33238. * key: makeKey(axis.model)
  33239. * value: {
  33240. * axis,
  33241. * coordSys,
  33242. * axisPointerModel,
  33243. * triggerTooltip,
  33244. * involveSeries,
  33245. * snap,
  33246. * seriesModels,
  33247. * seriesDataCount
  33248. * }
  33249. */
  33250. axesInfo: {},
  33251. seriesInvolved: false,
  33252. /**
  33253. * key: makeKey(coordSys.model)
  33254. * value: Object: key makeKey(axis.model), value: axisInfo
  33255. */
  33256. coordSysAxesInfo: {},
  33257. coordSysMap: {}
  33258. };
  33259. collectAxesInfo(result, ecModel, api);
  33260. // Check seriesInvolved for performance, in case too many series in some chart.
  33261. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  33262. return result;
  33263. }
  33264. function collectAxesInfo(result, ecModel, api) {
  33265. var globalTooltipModel = ecModel.getComponent('tooltip');
  33266. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  33267. // links can only be set on global.
  33268. var linksOption = globalAxisPointerModel.get('link', true) || [];
  33269. var linkGroups = [];
  33270. // Collect axes info.
  33271. each$6(api.getCoordinateSystems(), function (coordSys) {
  33272. // Some coordinate system do not support axes, like geo.
  33273. if (!coordSys.axisPointerEnabled) {
  33274. return;
  33275. }
  33276. var coordSysKey = makeKey(coordSys.model);
  33277. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  33278. result.coordSysMap[coordSysKey] = coordSys;
  33279. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  33280. // for user. So we enable seting tooltip on coordSys model.
  33281. var coordSysModel = coordSys.model;
  33282. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  33283. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  33284. // If axis tooltip used, choose tooltip axis for each coordSys.
  33285. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  33286. if (coordSys.getTooltipAxes
  33287. && globalTooltipModel
  33288. // If tooltip.showContent is set as false, tooltip will not
  33289. // show but axisPointer will show as normal.
  33290. && baseTooltipModel.get('show')
  33291. ) {
  33292. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  33293. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  33294. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  33295. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  33296. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  33297. if (triggerAxis || cross) {
  33298. each$6(tooltipAxes.baseAxes, curry$1(
  33299. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  33300. ));
  33301. }
  33302. if (cross) {
  33303. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  33304. }
  33305. }
  33306. // fromTooltip: true | false | 'cross'
  33307. // triggerTooltip: true | false | null
  33308. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  33309. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  33310. var axisPointerShow = axisPointerModel.get('show');
  33311. if (!axisPointerShow || (
  33312. axisPointerShow === 'auto'
  33313. && !fromTooltip
  33314. && !isHandleTrigger(axisPointerModel)
  33315. )) {
  33316. return;
  33317. }
  33318. if (triggerTooltip == null) {
  33319. triggerTooltip = axisPointerModel.get('triggerTooltip');
  33320. }
  33321. axisPointerModel = fromTooltip
  33322. ? makeAxisPointerModel(
  33323. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  33324. fromTooltip, triggerTooltip
  33325. )
  33326. : axisPointerModel;
  33327. var snap = axisPointerModel.get('snap');
  33328. var key = makeKey(axis.model);
  33329. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  33330. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  33331. var axisInfo = result.axesInfo[key] = {
  33332. key: key,
  33333. axis: axis,
  33334. coordSys: coordSys,
  33335. axisPointerModel: axisPointerModel,
  33336. triggerTooltip: triggerTooltip,
  33337. involveSeries: involveSeries,
  33338. snap: snap,
  33339. useHandle: isHandleTrigger(axisPointerModel),
  33340. seriesModels: []
  33341. };
  33342. axesInfoInCoordSys[key] = axisInfo;
  33343. result.seriesInvolved |= involveSeries;
  33344. var groupIndex = getLinkGroupIndex(linksOption, axis);
  33345. if (groupIndex != null) {
  33346. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  33347. linkGroup.axesInfo[key] = axisInfo;
  33348. linkGroup.mapper = linksOption[groupIndex].mapper;
  33349. axisInfo.linkGroup = linkGroup;
  33350. }
  33351. }
  33352. });
  33353. }
  33354. function makeAxisPointerModel(
  33355. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  33356. ) {
  33357. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  33358. var volatileOption = {};
  33359. each$6(
  33360. [
  33361. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  33362. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  33363. ],
  33364. function (field) {
  33365. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  33366. }
  33367. );
  33368. // category axis do not auto snap, otherwise some tick that do not
  33369. // has value can not be hovered. value/time/log axis default snap if
  33370. // triggered from tooltip and trigger tooltip.
  33371. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  33372. // Compatibel with previous behavior, tooltip axis do not show label by default.
  33373. // Only these properties can be overrided from tooltip to axisPointer.
  33374. if (tooltipAxisPointerModel.get('type') === 'cross') {
  33375. volatileOption.type = 'line';
  33376. }
  33377. var labelOption = volatileOption.label || (volatileOption.label = {});
  33378. // Follow the convention, do not show label when triggered by tooltip by default.
  33379. labelOption.show == null && (labelOption.show = false);
  33380. if (fromTooltip === 'cross') {
  33381. // When 'cross', both axes show labels.
  33382. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  33383. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  33384. // If triggerTooltip, this is a base axis, which should better not use cross style
  33385. // (cross style is dashed by default)
  33386. if (!triggerTooltip) {
  33387. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  33388. crossStyle && defaults(labelOption, crossStyle.textStyle);
  33389. }
  33390. }
  33391. return axis.model.getModel(
  33392. 'axisPointer',
  33393. new Model(volatileOption, globalAxisPointerModel, ecModel)
  33394. );
  33395. }
  33396. function collectSeriesInfo(result, ecModel) {
  33397. // Prepare data for axis trigger
  33398. ecModel.eachSeries(function (seriesModel) {
  33399. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  33400. var coordSys = seriesModel.coordinateSystem;
  33401. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  33402. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  33403. if (!coordSys
  33404. || seriesTooltipTrigger === 'none'
  33405. || seriesTooltipTrigger === false
  33406. || seriesTooltipTrigger === 'item'
  33407. || seriesTooltipShow === false
  33408. || seriesModel.get('axisPointer.show', true) === false
  33409. ) {
  33410. return;
  33411. }
  33412. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  33413. var axis = axisInfo.axis;
  33414. if (coordSys.getAxis(axis.dim) === axis) {
  33415. axisInfo.seriesModels.push(seriesModel);
  33416. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  33417. axisInfo.seriesDataCount += seriesModel.getData().count();
  33418. }
  33419. });
  33420. }, this);
  33421. }
  33422. /**
  33423. * For example:
  33424. * {
  33425. * axisPointer: {
  33426. * links: [{
  33427. * xAxisIndex: [2, 4],
  33428. * yAxisIndex: 'all'
  33429. * }, {
  33430. * xAxisId: ['a5', 'a7'],
  33431. * xAxisName: 'xxx'
  33432. * }]
  33433. * }
  33434. * }
  33435. */
  33436. function getLinkGroupIndex(linksOption, axis) {
  33437. var axisModel = axis.model;
  33438. var dim = axis.dim;
  33439. for (var i = 0; i < linksOption.length; i++) {
  33440. var linkOption = linksOption[i] || {};
  33441. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  33442. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  33443. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  33444. ) {
  33445. return i;
  33446. }
  33447. }
  33448. }
  33449. function checkPropInLink(linkPropValue, axisPropValue) {
  33450. return linkPropValue === 'all'
  33451. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  33452. || linkPropValue === axisPropValue;
  33453. }
  33454. function fixValue(axisModel) {
  33455. var axisInfo = getAxisInfo(axisModel);
  33456. if (!axisInfo) {
  33457. return;
  33458. }
  33459. var axisPointerModel = axisInfo.axisPointerModel;
  33460. var scale = axisInfo.axis.scale;
  33461. var option = axisPointerModel.option;
  33462. var status = axisPointerModel.get('status');
  33463. var value = axisPointerModel.get('value');
  33464. // Parse init value for category and time axis.
  33465. if (value != null) {
  33466. value = scale.parse(value);
  33467. }
  33468. var useHandle = isHandleTrigger(axisPointerModel);
  33469. // If `handle` used, `axisPointer` will always be displayed, so value
  33470. // and status should be initialized.
  33471. if (status == null) {
  33472. option.status = useHandle ? 'show' : 'hide';
  33473. }
  33474. var extent = scale.getExtent().slice();
  33475. extent[0] > extent[1] && extent.reverse();
  33476. if (// Pick a value on axis when initializing.
  33477. value == null
  33478. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  33479. // where we should re-pick a value to keep `handle` displaying normally.
  33480. || value > extent[1]
  33481. ) {
  33482. // Make handle displayed on the end of the axis when init, which looks better.
  33483. value = extent[1];
  33484. }
  33485. if (value < extent[0]) {
  33486. value = extent[0];
  33487. }
  33488. option.value = value;
  33489. if (useHandle) {
  33490. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  33491. }
  33492. }
  33493. function getAxisInfo(axisModel) {
  33494. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  33495. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  33496. }
  33497. function getAxisPointerModel(axisModel) {
  33498. var axisInfo = getAxisInfo(axisModel);
  33499. return axisInfo && axisInfo.axisPointerModel;
  33500. }
  33501. function isHandleTrigger(axisPointerModel) {
  33502. return !!axisPointerModel.get('handle.show');
  33503. }
  33504. /**
  33505. * @param {module:echarts/model/Model} model
  33506. * @return {string} unique key
  33507. */
  33508. function makeKey(model) {
  33509. return model.type + '||' + model.id;
  33510. }
  33511. /*
  33512. * Licensed to the Apache Software Foundation (ASF) under one
  33513. * or more contributor license agreements. See the NOTICE file
  33514. * distributed with this work for additional information
  33515. * regarding copyright ownership. The ASF licenses this file
  33516. * to you under the Apache License, Version 2.0 (the
  33517. * "License"); you may not use this file except in compliance
  33518. * with the License. You may obtain a copy of the License at
  33519. *
  33520. * http://www.apache.org/licenses/LICENSE-2.0
  33521. *
  33522. * Unless required by applicable law or agreed to in writing,
  33523. * software distributed under the License is distributed on an
  33524. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33525. * KIND, either express or implied. See the License for the
  33526. * specific language governing permissions and limitations
  33527. * under the License.
  33528. */
  33529. /**
  33530. * Base class of AxisView.
  33531. */
  33532. var AxisView = extendComponentView({
  33533. type: 'axis',
  33534. /**
  33535. * @private
  33536. */
  33537. _axisPointer: null,
  33538. /**
  33539. * @protected
  33540. * @type {string}
  33541. */
  33542. axisPointerClass: null,
  33543. /**
  33544. * @override
  33545. */
  33546. render: function (axisModel, ecModel, api, payload) {
  33547. // FIXME
  33548. // This process should proformed after coordinate systems updated
  33549. // (axis scale updated), and should be performed each time update.
  33550. // So put it here temporarily, although it is not appropriate to
  33551. // put a model-writing procedure in `view`.
  33552. this.axisPointerClass && fixValue(axisModel);
  33553. AxisView.superApply(this, 'render', arguments);
  33554. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  33555. },
  33556. /**
  33557. * Action handler.
  33558. * @public
  33559. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33560. * @param {module:echarts/model/Global} ecModel
  33561. * @param {module:echarts/ExtensionAPI} api
  33562. * @param {Object} payload
  33563. */
  33564. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  33565. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  33566. },
  33567. /**
  33568. * @override
  33569. */
  33570. remove: function (ecModel, api) {
  33571. var axisPointer = this._axisPointer;
  33572. axisPointer && axisPointer.remove(api);
  33573. AxisView.superApply(this, 'remove', arguments);
  33574. },
  33575. /**
  33576. * @override
  33577. */
  33578. dispose: function (ecModel, api) {
  33579. disposeAxisPointer(this, api);
  33580. AxisView.superApply(this, 'dispose', arguments);
  33581. }
  33582. });
  33583. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  33584. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  33585. if (!Clazz) {
  33586. return;
  33587. }
  33588. var axisPointerModel = getAxisPointerModel(axisModel);
  33589. axisPointerModel
  33590. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  33591. .render(axisModel, axisPointerModel, api, forceRender)
  33592. : disposeAxisPointer(axisView, api);
  33593. }
  33594. function disposeAxisPointer(axisView, ecModel, api) {
  33595. var axisPointer = axisView._axisPointer;
  33596. axisPointer && axisPointer.dispose(ecModel, api);
  33597. axisView._axisPointer = null;
  33598. }
  33599. var axisPointerClazz = [];
  33600. AxisView.registerAxisPointerClass = function (type, clazz) {
  33601. if (__DEV__) {
  33602. if (axisPointerClazz[type]) {
  33603. throw new Error('axisPointer ' + type + ' exists');
  33604. }
  33605. }
  33606. axisPointerClazz[type] = clazz;
  33607. };
  33608. AxisView.getAxisPointerClass = function (type) {
  33609. return type && axisPointerClazz[type];
  33610. };
  33611. /*
  33612. * Licensed to the Apache Software Foundation (ASF) under one
  33613. * or more contributor license agreements. See the NOTICE file
  33614. * distributed with this work for additional information
  33615. * regarding copyright ownership. The ASF licenses this file
  33616. * to you under the Apache License, Version 2.0 (the
  33617. * "License"); you may not use this file except in compliance
  33618. * with the License. You may obtain a copy of the License at
  33619. *
  33620. * http://www.apache.org/licenses/LICENSE-2.0
  33621. *
  33622. * Unless required by applicable law or agreed to in writing,
  33623. * software distributed under the License is distributed on an
  33624. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33625. * KIND, either express or implied. See the License for the
  33626. * specific language governing permissions and limitations
  33627. * under the License.
  33628. */
  33629. /**
  33630. * Can only be called after coordinate system creation stage.
  33631. * (Can be called before coordinate system update stage).
  33632. *
  33633. * @param {Object} opt {labelInside}
  33634. * @return {Object} {
  33635. * position, rotation, labelDirection, labelOffset,
  33636. * tickDirection, labelRotate, z2
  33637. * }
  33638. */
  33639. function layout$1(gridModel, axisModel, opt) {
  33640. opt = opt || {};
  33641. var grid = gridModel.coordinateSystem;
  33642. var axis = axisModel.axis;
  33643. var layout = {};
  33644. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  33645. var rawAxisPosition = axis.position;
  33646. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  33647. var axisDim = axis.dim;
  33648. var rect = grid.getRect();
  33649. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  33650. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  33651. var axisOffset = axisModel.get('offset') || 0;
  33652. var posBound = axisDim === 'x'
  33653. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  33654. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  33655. if (otherAxisOnZeroOf) {
  33656. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  33657. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  33658. }
  33659. // Axis position
  33660. layout.position = [
  33661. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  33662. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  33663. ];
  33664. // Axis rotation
  33665. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  33666. // Tick and label direction, x y is axisDim
  33667. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  33668. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  33669. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  33670. if (axisModel.get('axisTick.inside')) {
  33671. layout.tickDirection = -layout.tickDirection;
  33672. }
  33673. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  33674. layout.labelDirection = -layout.labelDirection;
  33675. }
  33676. // Special label rotation
  33677. var labelRotate = axisModel.get('axisLabel.rotate');
  33678. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  33679. // Over splitLine and splitArea
  33680. layout.z2 = 1;
  33681. return layout;
  33682. }
  33683. /*
  33684. * Licensed to the Apache Software Foundation (ASF) under one
  33685. * or more contributor license agreements. See the NOTICE file
  33686. * distributed with this work for additional information
  33687. * regarding copyright ownership. The ASF licenses this file
  33688. * to you under the Apache License, Version 2.0 (the
  33689. * "License"); you may not use this file except in compliance
  33690. * with the License. You may obtain a copy of the License at
  33691. *
  33692. * http://www.apache.org/licenses/LICENSE-2.0
  33693. *
  33694. * Unless required by applicable law or agreed to in writing,
  33695. * software distributed under the License is distributed on an
  33696. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33697. * KIND, either express or implied. See the License for the
  33698. * specific language governing permissions and limitations
  33699. * under the License.
  33700. */
  33701. var axisBuilderAttrs = [
  33702. 'axisLine', 'axisTickLabel', 'axisName'
  33703. ];
  33704. var selfBuilderAttrs = [
  33705. 'splitArea', 'splitLine'
  33706. ];
  33707. // function getAlignWithLabel(model, axisModel) {
  33708. // var alignWithLabel = model.get('alignWithLabel');
  33709. // if (alignWithLabel === 'auto') {
  33710. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  33711. // }
  33712. // return alignWithLabel;
  33713. // }
  33714. var CartesianAxisView = AxisView.extend({
  33715. type: 'cartesianAxis',
  33716. axisPointerClass: 'CartesianAxisPointer',
  33717. /**
  33718. * @override
  33719. */
  33720. render: function (axisModel, ecModel, api, payload) {
  33721. this.group.removeAll();
  33722. var oldAxisGroup = this._axisGroup;
  33723. this._axisGroup = new Group();
  33724. this.group.add(this._axisGroup);
  33725. if (!axisModel.get('show')) {
  33726. return;
  33727. }
  33728. var gridModel = axisModel.getCoordSysModel();
  33729. var layout = layout$1(gridModel, axisModel);
  33730. var axisBuilder = new AxisBuilder(axisModel, layout);
  33731. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  33732. this._axisGroup.add(axisBuilder.getGroup());
  33733. each$1(selfBuilderAttrs, function (name) {
  33734. if (axisModel.get(name + '.show')) {
  33735. this['_' + name](axisModel, gridModel);
  33736. }
  33737. }, this);
  33738. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  33739. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  33740. },
  33741. remove: function () {
  33742. this._splitAreaColors = null;
  33743. },
  33744. /**
  33745. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33746. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33747. * @private
  33748. */
  33749. _splitLine: function (axisModel, gridModel) {
  33750. var axis = axisModel.axis;
  33751. if (axis.scale.isBlank()) {
  33752. return;
  33753. }
  33754. var splitLineModel = axisModel.getModel('splitLine');
  33755. var lineStyleModel = splitLineModel.getModel('lineStyle');
  33756. var lineColors = lineStyleModel.get('color');
  33757. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  33758. var gridRect = gridModel.coordinateSystem.getRect();
  33759. var isHorizontal = axis.isHorizontal();
  33760. var lineCount = 0;
  33761. var ticksCoords = axis.getTicksCoords({
  33762. tickModel: splitLineModel
  33763. });
  33764. var p1 = [];
  33765. var p2 = [];
  33766. // Simple optimization
  33767. // Batching the lines if color are the same
  33768. var lineStyle = lineStyleModel.getLineStyle();
  33769. for (var i = 0; i < ticksCoords.length; i++) {
  33770. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  33771. if (isHorizontal) {
  33772. p1[0] = tickCoord;
  33773. p1[1] = gridRect.y;
  33774. p2[0] = tickCoord;
  33775. p2[1] = gridRect.y + gridRect.height;
  33776. }
  33777. else {
  33778. p1[0] = gridRect.x;
  33779. p1[1] = tickCoord;
  33780. p2[0] = gridRect.x + gridRect.width;
  33781. p2[1] = tickCoord;
  33782. }
  33783. var colorIndex = (lineCount++) % lineColors.length;
  33784. var tickValue = ticksCoords[i].tickValue;
  33785. this._axisGroup.add(new Line(subPixelOptimizeLine({
  33786. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  33787. shape: {
  33788. x1: p1[0],
  33789. y1: p1[1],
  33790. x2: p2[0],
  33791. y2: p2[1]
  33792. },
  33793. style: defaults({
  33794. stroke: lineColors[colorIndex]
  33795. }, lineStyle),
  33796. silent: true
  33797. })));
  33798. }
  33799. },
  33800. /**
  33801. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33802. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33803. * @private
  33804. */
  33805. _splitArea: function (axisModel, gridModel) {
  33806. var axis = axisModel.axis;
  33807. if (axis.scale.isBlank()) {
  33808. return;
  33809. }
  33810. var splitAreaModel = axisModel.getModel('splitArea');
  33811. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  33812. var areaColors = areaStyleModel.get('color');
  33813. var gridRect = gridModel.coordinateSystem.getRect();
  33814. var ticksCoords = axis.getTicksCoords({
  33815. tickModel: splitAreaModel,
  33816. clamp: true
  33817. });
  33818. if (!ticksCoords.length) {
  33819. return;
  33820. }
  33821. // For Making appropriate splitArea animation, the color and anid
  33822. // should be corresponding to previous one if possible.
  33823. var areaColorsLen = areaColors.length;
  33824. var lastSplitAreaColors = this._splitAreaColors;
  33825. var newSplitAreaColors = createHashMap();
  33826. var colorIndex = 0;
  33827. if (lastSplitAreaColors) {
  33828. for (var i = 0; i < ticksCoords.length; i++) {
  33829. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  33830. if (cIndex != null) {
  33831. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  33832. break;
  33833. }
  33834. }
  33835. }
  33836. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  33837. var areaStyle = areaStyleModel.getAreaStyle();
  33838. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  33839. for (var i = 1; i < ticksCoords.length; i++) {
  33840. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  33841. var x;
  33842. var y;
  33843. var width;
  33844. var height;
  33845. if (axis.isHorizontal()) {
  33846. x = prev;
  33847. y = gridRect.y;
  33848. width = tickCoord - x;
  33849. height = gridRect.height;
  33850. prev = x + width;
  33851. }
  33852. else {
  33853. x = gridRect.x;
  33854. y = prev;
  33855. width = gridRect.width;
  33856. height = tickCoord - y;
  33857. prev = y + height;
  33858. }
  33859. var tickValue = ticksCoords[i - 1].tickValue;
  33860. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  33861. this._axisGroup.add(new Rect({
  33862. anid: tickValue != null ? 'area_' + tickValue : null,
  33863. shape: {
  33864. x: x,
  33865. y: y,
  33866. width: width,
  33867. height: height
  33868. },
  33869. style: defaults({
  33870. fill: areaColors[colorIndex]
  33871. }, areaStyle),
  33872. silent: true
  33873. }));
  33874. colorIndex = (colorIndex + 1) % areaColorsLen;
  33875. }
  33876. this._splitAreaColors = newSplitAreaColors;
  33877. }
  33878. });
  33879. CartesianAxisView.extend({
  33880. type: 'xAxis'
  33881. });
  33882. CartesianAxisView.extend({
  33883. type: 'yAxis'
  33884. });
  33885. /*
  33886. * Licensed to the Apache Software Foundation (ASF) under one
  33887. * or more contributor license agreements. See the NOTICE file
  33888. * distributed with this work for additional information
  33889. * regarding copyright ownership. The ASF licenses this file
  33890. * to you under the Apache License, Version 2.0 (the
  33891. * "License"); you may not use this file except in compliance
  33892. * with the License. You may obtain a copy of the License at
  33893. *
  33894. * http://www.apache.org/licenses/LICENSE-2.0
  33895. *
  33896. * Unless required by applicable law or agreed to in writing,
  33897. * software distributed under the License is distributed on an
  33898. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33899. * KIND, either express or implied. See the License for the
  33900. * specific language governing permissions and limitations
  33901. * under the License.
  33902. */
  33903. /*
  33904. * Licensed to the Apache Software Foundation (ASF) under one
  33905. * or more contributor license agreements. See the NOTICE file
  33906. * distributed with this work for additional information
  33907. * regarding copyright ownership. The ASF licenses this file
  33908. * to you under the Apache License, Version 2.0 (the
  33909. * "License"); you may not use this file except in compliance
  33910. * with the License. You may obtain a copy of the License at
  33911. *
  33912. * http://www.apache.org/licenses/LICENSE-2.0
  33913. *
  33914. * Unless required by applicable law or agreed to in writing,
  33915. * software distributed under the License is distributed on an
  33916. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33917. * KIND, either express or implied. See the License for the
  33918. * specific language governing permissions and limitations
  33919. * under the License.
  33920. */
  33921. // Grid view
  33922. extendComponentView({
  33923. type: 'grid',
  33924. render: function (gridModel, ecModel) {
  33925. this.group.removeAll();
  33926. if (gridModel.get('show')) {
  33927. this.group.add(new Rect({
  33928. shape: gridModel.coordinateSystem.getRect(),
  33929. style: defaults({
  33930. fill: gridModel.get('backgroundColor')
  33931. }, gridModel.getItemStyle()),
  33932. silent: true,
  33933. z2: -1
  33934. }));
  33935. }
  33936. }
  33937. });
  33938. registerPreprocessor(function (option) {
  33939. // Only create grid when need
  33940. if (option.xAxis && option.yAxis && !option.grid) {
  33941. option.grid = {};
  33942. }
  33943. });
  33944. /*
  33945. * Licensed to the Apache Software Foundation (ASF) under one
  33946. * or more contributor license agreements. See the NOTICE file
  33947. * distributed with this work for additional information
  33948. * regarding copyright ownership. The ASF licenses this file
  33949. * to you under the Apache License, Version 2.0 (the
  33950. * "License"); you may not use this file except in compliance
  33951. * with the License. You may obtain a copy of the License at
  33952. *
  33953. * http://www.apache.org/licenses/LICENSE-2.0
  33954. *
  33955. * Unless required by applicable law or agreed to in writing,
  33956. * software distributed under the License is distributed on an
  33957. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33958. * KIND, either express or implied. See the License for the
  33959. * specific language governing permissions and limitations
  33960. * under the License.
  33961. */
  33962. // In case developer forget to include grid component
  33963. registerVisual(visualSymbol('line', 'circle', 'line'));
  33964. registerLayout(pointsLayout('line'));
  33965. // Down sample after filter
  33966. registerProcessor(
  33967. PRIORITY.PROCESSOR.STATISTIC,
  33968. dataSample('line')
  33969. );
  33970. /*
  33971. * Licensed to the Apache Software Foundation (ASF) under one
  33972. * or more contributor license agreements. See the NOTICE file
  33973. * distributed with this work for additional information
  33974. * regarding copyright ownership. The ASF licenses this file
  33975. * to you under the Apache License, Version 2.0 (the
  33976. * "License"); you may not use this file except in compliance
  33977. * with the License. You may obtain a copy of the License at
  33978. *
  33979. * http://www.apache.org/licenses/LICENSE-2.0
  33980. *
  33981. * Unless required by applicable law or agreed to in writing,
  33982. * software distributed under the License is distributed on an
  33983. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33984. * KIND, either express or implied. See the License for the
  33985. * specific language governing permissions and limitations
  33986. * under the License.
  33987. */
  33988. var BaseBarSeries = SeriesModel.extend({
  33989. type: 'series.__base_bar__',
  33990. getInitialData: function (option, ecModel) {
  33991. return createListFromArray(this.getSource(), this);
  33992. },
  33993. getMarkerPosition: function (value) {
  33994. var coordSys = this.coordinateSystem;
  33995. if (coordSys) {
  33996. // PENDING if clamp ?
  33997. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  33998. var data = this.getData();
  33999. var offset = data.getLayout('offset');
  34000. var size = data.getLayout('size');
  34001. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  34002. pt[offsetIndex] += offset + size / 2;
  34003. return pt;
  34004. }
  34005. return [NaN, NaN];
  34006. },
  34007. defaultOption: {
  34008. zlevel: 0, // 一级层叠
  34009. z: 2, // 二级层叠
  34010. coordinateSystem: 'cartesian2d',
  34011. legendHoverLink: true,
  34012. // stack: null
  34013. // Cartesian coordinate system
  34014. // xAxisIndex: 0,
  34015. // yAxisIndex: 0,
  34016. // 最小高度改为0
  34017. barMinHeight: 0,
  34018. // 最小角度为0,仅对极坐标系下的柱状图有效
  34019. barMinAngle: 0,
  34020. // cursor: null,
  34021. large: false,
  34022. largeThreshold: 400,
  34023. progressive: 3e3,
  34024. progressiveChunkMode: 'mod',
  34025. // barMaxWidth: null,
  34026. // 默认自适应
  34027. // barWidth: null,
  34028. // 柱间距离,默认为柱形宽度的30%,可设固定值
  34029. // barGap: '30%',
  34030. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  34031. // barCategoryGap: '20%',
  34032. // label: {
  34033. // show: false
  34034. // },
  34035. itemStyle: {},
  34036. emphasis: {}
  34037. }
  34038. });
  34039. /*
  34040. * Licensed to the Apache Software Foundation (ASF) under one
  34041. * or more contributor license agreements. See the NOTICE file
  34042. * distributed with this work for additional information
  34043. * regarding copyright ownership. The ASF licenses this file
  34044. * to you under the Apache License, Version 2.0 (the
  34045. * "License"); you may not use this file except in compliance
  34046. * with the License. You may obtain a copy of the License at
  34047. *
  34048. * http://www.apache.org/licenses/LICENSE-2.0
  34049. *
  34050. * Unless required by applicable law or agreed to in writing,
  34051. * software distributed under the License is distributed on an
  34052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34053. * KIND, either express or implied. See the License for the
  34054. * specific language governing permissions and limitations
  34055. * under the License.
  34056. */
  34057. BaseBarSeries.extend({
  34058. type: 'series.bar',
  34059. dependencies: ['grid', 'polar'],
  34060. brushSelector: 'rect',
  34061. /**
  34062. * @override
  34063. */
  34064. getProgressive: function () {
  34065. // Do not support progressive in normal mode.
  34066. return this.get('large')
  34067. ? this.get('progressive')
  34068. : false;
  34069. },
  34070. /**
  34071. * @override
  34072. */
  34073. getProgressiveThreshold: function () {
  34074. // Do not support progressive in normal mode.
  34075. var progressiveThreshold = this.get('progressiveThreshold');
  34076. var largeThreshold = this.get('largeThreshold');
  34077. if (largeThreshold > progressiveThreshold) {
  34078. progressiveThreshold = largeThreshold;
  34079. }
  34080. return progressiveThreshold;
  34081. }
  34082. });
  34083. /*
  34084. * Licensed to the Apache Software Foundation (ASF) under one
  34085. * or more contributor license agreements. See the NOTICE file
  34086. * distributed with this work for additional information
  34087. * regarding copyright ownership. The ASF licenses this file
  34088. * to you under the Apache License, Version 2.0 (the
  34089. * "License"); you may not use this file except in compliance
  34090. * with the License. You may obtain a copy of the License at
  34091. *
  34092. * http://www.apache.org/licenses/LICENSE-2.0
  34093. *
  34094. * Unless required by applicable law or agreed to in writing,
  34095. * software distributed under the License is distributed on an
  34096. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34097. * KIND, either express or implied. See the License for the
  34098. * specific language governing permissions and limitations
  34099. * under the License.
  34100. */
  34101. function setLabel(
  34102. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  34103. ) {
  34104. var labelModel = itemModel.getModel('label');
  34105. var hoverLabelModel = itemModel.getModel('emphasis.label');
  34106. setLabelStyle(
  34107. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  34108. {
  34109. labelFetcher: seriesModel,
  34110. labelDataIndex: dataIndex,
  34111. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  34112. isRectText: true,
  34113. autoColor: color
  34114. }
  34115. );
  34116. fixPosition(normalStyle);
  34117. fixPosition(hoverStyle);
  34118. }
  34119. function fixPosition(style, labelPositionOutside) {
  34120. if (style.textPosition === 'outside') {
  34121. style.textPosition = labelPositionOutside;
  34122. }
  34123. }
  34124. /*
  34125. * Licensed to the Apache Software Foundation (ASF) under one
  34126. * or more contributor license agreements. See the NOTICE file
  34127. * distributed with this work for additional information
  34128. * regarding copyright ownership. The ASF licenses this file
  34129. * to you under the Apache License, Version 2.0 (the
  34130. * "License"); you may not use this file except in compliance
  34131. * with the License. You may obtain a copy of the License at
  34132. *
  34133. * http://www.apache.org/licenses/LICENSE-2.0
  34134. *
  34135. * Unless required by applicable law or agreed to in writing,
  34136. * software distributed under the License is distributed on an
  34137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34138. * KIND, either express or implied. See the License for the
  34139. * specific language governing permissions and limitations
  34140. * under the License.
  34141. */
  34142. var getBarItemStyle = makeStyleMapper(
  34143. [
  34144. ['fill', 'color'],
  34145. ['stroke', 'borderColor'],
  34146. ['lineWidth', 'borderWidth'],
  34147. // Compatitable with 2
  34148. ['stroke', 'barBorderColor'],
  34149. ['lineWidth', 'barBorderWidth'],
  34150. ['opacity'],
  34151. ['shadowBlur'],
  34152. ['shadowOffsetX'],
  34153. ['shadowOffsetY'],
  34154. ['shadowColor']
  34155. ]
  34156. );
  34157. var barItemStyle = {
  34158. getBarItemStyle: function (excludes) {
  34159. var style = getBarItemStyle(this, excludes);
  34160. if (this.getBorderLineDash) {
  34161. var lineDash = this.getBorderLineDash();
  34162. lineDash && (style.lineDash = lineDash);
  34163. }
  34164. return style;
  34165. }
  34166. };
  34167. /*
  34168. * Licensed to the Apache Software Foundation (ASF) under one
  34169. * or more contributor license agreements. See the NOTICE file
  34170. * distributed with this work for additional information
  34171. * regarding copyright ownership. The ASF licenses this file
  34172. * to you under the Apache License, Version 2.0 (the
  34173. * "License"); you may not use this file except in compliance
  34174. * with the License. You may obtain a copy of the License at
  34175. *
  34176. * http://www.apache.org/licenses/LICENSE-2.0
  34177. *
  34178. * Unless required by applicable law or agreed to in writing,
  34179. * software distributed under the License is distributed on an
  34180. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34181. * KIND, either express or implied. See the License for the
  34182. * specific language governing permissions and limitations
  34183. * under the License.
  34184. */
  34185. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  34186. // FIXME
  34187. // Just for compatible with ec2.
  34188. extend(Model.prototype, barItemStyle);
  34189. extendChartView({
  34190. type: 'bar',
  34191. render: function (seriesModel, ecModel, api) {
  34192. this._updateDrawMode(seriesModel);
  34193. var coordinateSystemType = seriesModel.get('coordinateSystem');
  34194. if (coordinateSystemType === 'cartesian2d'
  34195. || coordinateSystemType === 'polar'
  34196. ) {
  34197. this._isLargeDraw
  34198. ? this._renderLarge(seriesModel, ecModel, api)
  34199. : this._renderNormal(seriesModel, ecModel, api);
  34200. }
  34201. else if (__DEV__) {
  34202. console.warn('Only cartesian2d and polar supported for bar.');
  34203. }
  34204. return this.group;
  34205. },
  34206. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  34207. this._clear();
  34208. this._updateDrawMode(seriesModel);
  34209. },
  34210. incrementalRender: function (params, seriesModel, ecModel, api) {
  34211. // Do not support progressive in normal mode.
  34212. this._incrementalRenderLarge(params, seriesModel);
  34213. },
  34214. _updateDrawMode: function (seriesModel) {
  34215. var isLargeDraw = seriesModel.pipelineContext.large;
  34216. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  34217. this._isLargeDraw = isLargeDraw;
  34218. this._clear();
  34219. }
  34220. },
  34221. _renderNormal: function (seriesModel, ecModel, api) {
  34222. var group = this.group;
  34223. var data = seriesModel.getData();
  34224. var oldData = this._data;
  34225. var coord = seriesModel.coordinateSystem;
  34226. var baseAxis = coord.getBaseAxis();
  34227. var isHorizontalOrRadial;
  34228. if (coord.type === 'cartesian2d') {
  34229. isHorizontalOrRadial = baseAxis.isHorizontal();
  34230. }
  34231. else if (coord.type === 'polar') {
  34232. isHorizontalOrRadial = baseAxis.dim === 'angle';
  34233. }
  34234. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  34235. data.diff(oldData)
  34236. .add(function (dataIndex) {
  34237. if (!data.hasValue(dataIndex)) {
  34238. return;
  34239. }
  34240. var itemModel = data.getItemModel(dataIndex);
  34241. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  34242. var el = elementCreator[coord.type](
  34243. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  34244. );
  34245. data.setItemGraphicEl(dataIndex, el);
  34246. group.add(el);
  34247. updateStyle(
  34248. el, data, dataIndex, itemModel, layout,
  34249. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34250. );
  34251. })
  34252. .update(function (newIndex, oldIndex) {
  34253. var el = oldData.getItemGraphicEl(oldIndex);
  34254. if (!data.hasValue(newIndex)) {
  34255. group.remove(el);
  34256. return;
  34257. }
  34258. var itemModel = data.getItemModel(newIndex);
  34259. var layout = getLayout[coord.type](data, newIndex, itemModel);
  34260. if (el) {
  34261. updateProps(el, {shape: layout}, animationModel, newIndex);
  34262. }
  34263. else {
  34264. el = elementCreator[coord.type](
  34265. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  34266. );
  34267. }
  34268. data.setItemGraphicEl(newIndex, el);
  34269. // Add back
  34270. group.add(el);
  34271. updateStyle(
  34272. el, data, newIndex, itemModel, layout,
  34273. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34274. );
  34275. })
  34276. .remove(function (dataIndex) {
  34277. var el = oldData.getItemGraphicEl(dataIndex);
  34278. if (coord.type === 'cartesian2d') {
  34279. el && removeRect(dataIndex, animationModel, el);
  34280. }
  34281. else {
  34282. el && removeSector(dataIndex, animationModel, el);
  34283. }
  34284. })
  34285. .execute();
  34286. this._data = data;
  34287. },
  34288. _renderLarge: function (seriesModel, ecModel, api) {
  34289. this._clear();
  34290. createLarge(seriesModel, this.group);
  34291. },
  34292. _incrementalRenderLarge: function (params, seriesModel) {
  34293. createLarge(seriesModel, this.group, true);
  34294. },
  34295. dispose: noop,
  34296. remove: function (ecModel) {
  34297. this._clear(ecModel);
  34298. },
  34299. _clear: function (ecModel) {
  34300. var group = this.group;
  34301. var data = this._data;
  34302. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  34303. data.eachItemGraphicEl(function (el) {
  34304. if (el.type === 'sector') {
  34305. removeSector(el.dataIndex, ecModel, el);
  34306. }
  34307. else {
  34308. removeRect(el.dataIndex, ecModel, el);
  34309. }
  34310. });
  34311. }
  34312. else {
  34313. group.removeAll();
  34314. }
  34315. this._data = null;
  34316. }
  34317. });
  34318. var elementCreator = {
  34319. cartesian2d: function (
  34320. data, dataIndex, itemModel, layout, isHorizontal,
  34321. animationModel, isUpdate
  34322. ) {
  34323. var rect = new Rect({shape: extend({}, layout)});
  34324. // Animation
  34325. if (animationModel) {
  34326. var rectShape = rect.shape;
  34327. var animateProperty = isHorizontal ? 'height' : 'width';
  34328. var animateTarget = {};
  34329. rectShape[animateProperty] = 0;
  34330. animateTarget[animateProperty] = layout[animateProperty];
  34331. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  34332. shape: animateTarget
  34333. }, animationModel, dataIndex);
  34334. }
  34335. return rect;
  34336. },
  34337. polar: function (
  34338. data, dataIndex, itemModel, layout, isRadial,
  34339. animationModel, isUpdate
  34340. ) {
  34341. // Keep the same logic with bar in catesion: use end value to control
  34342. // direction. Notice that if clockwise is true (by default), the sector
  34343. // will always draw clockwisely, no matter whether endAngle is greater
  34344. // or less than startAngle.
  34345. var clockwise = layout.startAngle < layout.endAngle;
  34346. var sector = new Sector({
  34347. shape: defaults({clockwise: clockwise}, layout)
  34348. });
  34349. // Animation
  34350. if (animationModel) {
  34351. var sectorShape = sector.shape;
  34352. var animateProperty = isRadial ? 'r' : 'endAngle';
  34353. var animateTarget = {};
  34354. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  34355. animateTarget[animateProperty] = layout[animateProperty];
  34356. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  34357. shape: animateTarget
  34358. }, animationModel, dataIndex);
  34359. }
  34360. return sector;
  34361. }
  34362. };
  34363. function removeRect(dataIndex, animationModel, el) {
  34364. // Not show text when animating
  34365. el.style.text = null;
  34366. updateProps(el, {
  34367. shape: {
  34368. width: 0
  34369. }
  34370. }, animationModel, dataIndex, function () {
  34371. el.parent && el.parent.remove(el);
  34372. });
  34373. }
  34374. function removeSector(dataIndex, animationModel, el) {
  34375. // Not show text when animating
  34376. el.style.text = null;
  34377. updateProps(el, {
  34378. shape: {
  34379. r: el.shape.r0
  34380. }
  34381. }, animationModel, dataIndex, function () {
  34382. el.parent && el.parent.remove(el);
  34383. });
  34384. }
  34385. var getLayout = {
  34386. cartesian2d: function (data, dataIndex, itemModel) {
  34387. var layout = data.getItemLayout(dataIndex);
  34388. var fixedLineWidth = getLineWidth(itemModel, layout);
  34389. // fix layout with lineWidth
  34390. var signX = layout.width > 0 ? 1 : -1;
  34391. var signY = layout.height > 0 ? 1 : -1;
  34392. return {
  34393. x: layout.x + signX * fixedLineWidth / 2,
  34394. y: layout.y + signY * fixedLineWidth / 2,
  34395. width: layout.width - signX * fixedLineWidth,
  34396. height: layout.height - signY * fixedLineWidth
  34397. };
  34398. },
  34399. polar: function (data, dataIndex, itemModel) {
  34400. var layout = data.getItemLayout(dataIndex);
  34401. return {
  34402. cx: layout.cx,
  34403. cy: layout.cy,
  34404. r0: layout.r0,
  34405. r: layout.r,
  34406. startAngle: layout.startAngle,
  34407. endAngle: layout.endAngle
  34408. };
  34409. }
  34410. };
  34411. function updateStyle(
  34412. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  34413. ) {
  34414. var color = data.getItemVisual(dataIndex, 'color');
  34415. var opacity = data.getItemVisual(dataIndex, 'opacity');
  34416. var itemStyleModel = itemModel.getModel('itemStyle');
  34417. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  34418. if (!isPolar) {
  34419. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  34420. }
  34421. el.useStyle(defaults(
  34422. {
  34423. fill: color,
  34424. opacity: opacity
  34425. },
  34426. itemStyleModel.getBarItemStyle()
  34427. ));
  34428. var cursorStyle = itemModel.getShallow('cursor');
  34429. cursorStyle && el.attr('cursor', cursorStyle);
  34430. var labelPositionOutside = isHorizontal
  34431. ? (layout.height > 0 ? 'bottom' : 'top')
  34432. : (layout.width > 0 ? 'left' : 'right');
  34433. if (!isPolar) {
  34434. setLabel(
  34435. el.style, hoverStyle, itemModel, color,
  34436. seriesModel, dataIndex, labelPositionOutside
  34437. );
  34438. }
  34439. setHoverStyle(el, hoverStyle);
  34440. }
  34441. // In case width or height are too small.
  34442. function getLineWidth(itemModel, rawLayout) {
  34443. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  34444. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  34445. }
  34446. var LargePath = Path.extend({
  34447. type: 'largeBar',
  34448. shape: {points: []},
  34449. buildPath: function (ctx, shape) {
  34450. // Drawing lines is more efficient than drawing
  34451. // a whole line or drawing rects.
  34452. var points = shape.points;
  34453. var startPoint = this.__startPoint;
  34454. var valueIdx = this.__valueIdx;
  34455. for (var i = 0; i < points.length; i += 2) {
  34456. startPoint[this.__valueIdx] = points[i + valueIdx];
  34457. ctx.moveTo(startPoint[0], startPoint[1]);
  34458. ctx.lineTo(points[i], points[i + 1]);
  34459. }
  34460. }
  34461. });
  34462. function createLarge(seriesModel, group, incremental) {
  34463. // TODO support polar
  34464. var data = seriesModel.getData();
  34465. var startPoint = [];
  34466. var valueIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  34467. startPoint[1 - valueIdx] = data.getLayout('valueAxisStart');
  34468. var el = new LargePath({
  34469. shape: {points: data.getLayout('largePoints')},
  34470. incremental: !!incremental,
  34471. __startPoint: startPoint,
  34472. __valueIdx: valueIdx
  34473. });
  34474. group.add(el);
  34475. setLargeStyle(el, seriesModel, data);
  34476. }
  34477. function setLargeStyle(el, seriesModel, data) {
  34478. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  34479. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  34480. el.useStyle(itemStyle);
  34481. el.style.fill = null;
  34482. el.style.stroke = borderColor;
  34483. el.style.lineWidth = data.getLayout('barWidth');
  34484. }
  34485. /*
  34486. * Licensed to the Apache Software Foundation (ASF) under one
  34487. * or more contributor license agreements. See the NOTICE file
  34488. * distributed with this work for additional information
  34489. * regarding copyright ownership. The ASF licenses this file
  34490. * to you under the Apache License, Version 2.0 (the
  34491. * "License"); you may not use this file except in compliance
  34492. * with the License. You may obtain a copy of the License at
  34493. *
  34494. * http://www.apache.org/licenses/LICENSE-2.0
  34495. *
  34496. * Unless required by applicable law or agreed to in writing,
  34497. * software distributed under the License is distributed on an
  34498. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34499. * KIND, either express or implied. See the License for the
  34500. * specific language governing permissions and limitations
  34501. * under the License.
  34502. */
  34503. // In case developer forget to include grid component
  34504. registerLayout(curry(layout, 'bar'));
  34505. // Should after normal bar layout, otherwise it is blocked by normal bar layout.
  34506. registerLayout(largeLayout);
  34507. registerVisual({
  34508. seriesType: 'bar',
  34509. reset: function (seriesModel) {
  34510. // Visual coding for legend
  34511. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  34512. }
  34513. });
  34514. /*
  34515. * Licensed to the Apache Software Foundation (ASF) under one
  34516. * or more contributor license agreements. See the NOTICE file
  34517. * distributed with this work for additional information
  34518. * regarding copyright ownership. The ASF licenses this file
  34519. * to you under the Apache License, Version 2.0 (the
  34520. * "License"); you may not use this file except in compliance
  34521. * with the License. You may obtain a copy of the License at
  34522. *
  34523. * http://www.apache.org/licenses/LICENSE-2.0
  34524. *
  34525. * Unless required by applicable law or agreed to in writing,
  34526. * software distributed under the License is distributed on an
  34527. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34528. * KIND, either express or implied. See the License for the
  34529. * specific language governing permissions and limitations
  34530. * under the License.
  34531. */
  34532. /**
  34533. * [Usage]:
  34534. * (1)
  34535. * createListSimply(seriesModel, ['value']);
  34536. * (2)
  34537. * createListSimply(seriesModel, {
  34538. * coordDimensions: ['value'],
  34539. * dimensionsCount: 5
  34540. * });
  34541. *
  34542. * @param {module:echarts/model/Series} seriesModel
  34543. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  34544. * The options in opt, see `echarts/data/helper/createDimensions`
  34545. * @param {Array.<string>} [nameList]
  34546. * @return {module:echarts/data/List}
  34547. */
  34548. var createListSimply = function (seriesModel, opt, nameList) {
  34549. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  34550. var source = seriesModel.getSource();
  34551. var dimensionsInfo = createDimensions(source, opt);
  34552. var list = new List(dimensionsInfo, seriesModel);
  34553. list.initData(source, nameList);
  34554. return list;
  34555. };
  34556. /*
  34557. * Licensed to the Apache Software Foundation (ASF) under one
  34558. * or more contributor license agreements. See the NOTICE file
  34559. * distributed with this work for additional information
  34560. * regarding copyright ownership. The ASF licenses this file
  34561. * to you under the Apache License, Version 2.0 (the
  34562. * "License"); you may not use this file except in compliance
  34563. * with the License. You may obtain a copy of the License at
  34564. *
  34565. * http://www.apache.org/licenses/LICENSE-2.0
  34566. *
  34567. * Unless required by applicable law or agreed to in writing,
  34568. * software distributed under the License is distributed on an
  34569. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34570. * KIND, either express or implied. See the License for the
  34571. * specific language governing permissions and limitations
  34572. * under the License.
  34573. */
  34574. /**
  34575. * Data selectable mixin for chart series.
  34576. * To eanble data select, option of series must have `selectedMode`.
  34577. * And each data item will use `selected` to toggle itself selected status
  34578. */
  34579. var selectableMixin = {
  34580. /**
  34581. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  34582. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  34583. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  34584. */
  34585. updateSelectedMap: function (targetList) {
  34586. this._targetList = isArray(targetList) ? targetList.slice() : [];
  34587. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  34588. targetMap.set(target.name, target);
  34589. return targetMap;
  34590. }, createHashMap());
  34591. },
  34592. /**
  34593. * Either name or id should be passed as input here.
  34594. * If both of them are defined, id is used.
  34595. *
  34596. * @param {string|undefined} name name of data
  34597. * @param {number|undefined} id dataIndex of data
  34598. */
  34599. // PENGING If selectedMode is null ?
  34600. select: function (name, id) {
  34601. var target = id != null
  34602. ? this._targetList[id]
  34603. : this._selectTargetMap.get(name);
  34604. var selectedMode = this.get('selectedMode');
  34605. if (selectedMode === 'single') {
  34606. this._selectTargetMap.each(function (target) {
  34607. target.selected = false;
  34608. });
  34609. }
  34610. target && (target.selected = true);
  34611. },
  34612. /**
  34613. * Either name or id should be passed as input here.
  34614. * If both of them are defined, id is used.
  34615. *
  34616. * @param {string|undefined} name name of data
  34617. * @param {number|undefined} id dataIndex of data
  34618. */
  34619. unSelect: function (name, id) {
  34620. var target = id != null
  34621. ? this._targetList[id]
  34622. : this._selectTargetMap.get(name);
  34623. // var selectedMode = this.get('selectedMode');
  34624. // selectedMode !== 'single' && target && (target.selected = false);
  34625. target && (target.selected = false);
  34626. },
  34627. /**
  34628. * Either name or id should be passed as input here.
  34629. * If both of them are defined, id is used.
  34630. *
  34631. * @param {string|undefined} name name of data
  34632. * @param {number|undefined} id dataIndex of data
  34633. */
  34634. toggleSelected: function (name, id) {
  34635. var target = id != null
  34636. ? this._targetList[id]
  34637. : this._selectTargetMap.get(name);
  34638. if (target != null) {
  34639. this[target.selected ? 'unSelect' : 'select'](name, id);
  34640. return target.selected;
  34641. }
  34642. },
  34643. /**
  34644. * Either name or id should be passed as input here.
  34645. * If both of them are defined, id is used.
  34646. *
  34647. * @param {string|undefined} name name of data
  34648. * @param {number|undefined} id dataIndex of data
  34649. */
  34650. isSelected: function (name, id) {
  34651. var target = id != null
  34652. ? this._targetList[id]
  34653. : this._selectTargetMap.get(name);
  34654. return target && target.selected;
  34655. }
  34656. };
  34657. /*
  34658. * Licensed to the Apache Software Foundation (ASF) under one
  34659. * or more contributor license agreements. See the NOTICE file
  34660. * distributed with this work for additional information
  34661. * regarding copyright ownership. The ASF licenses this file
  34662. * to you under the Apache License, Version 2.0 (the
  34663. * "License"); you may not use this file except in compliance
  34664. * with the License. You may obtain a copy of the License at
  34665. *
  34666. * http://www.apache.org/licenses/LICENSE-2.0
  34667. *
  34668. * Unless required by applicable law or agreed to in writing,
  34669. * software distributed under the License is distributed on an
  34670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34671. * KIND, either express or implied. See the License for the
  34672. * specific language governing permissions and limitations
  34673. * under the License.
  34674. */
  34675. var PieSeries = extendSeriesModel({
  34676. type: 'series.pie',
  34677. // Overwrite
  34678. init: function (option) {
  34679. PieSeries.superApply(this, 'init', arguments);
  34680. // Enable legend selection for each data item
  34681. // Use a function instead of direct access because data reference may changed
  34682. this.legendDataProvider = function () {
  34683. return this.getRawData();
  34684. };
  34685. this.updateSelectedMap(this._createSelectableList());
  34686. this._defaultLabelLine(option);
  34687. },
  34688. // Overwrite
  34689. mergeOption: function (newOption) {
  34690. PieSeries.superCall(this, 'mergeOption', newOption);
  34691. this.updateSelectedMap(this._createSelectableList());
  34692. },
  34693. getInitialData: function (option, ecModel) {
  34694. return createListSimply(this, ['value']);
  34695. },
  34696. _createSelectableList: function () {
  34697. var data = this.getRawData();
  34698. var valueDim = data.mapDimension('value');
  34699. var targetList = [];
  34700. for (var i = 0, len = data.count(); i < len; i++) {
  34701. targetList.push({
  34702. name: data.getName(i),
  34703. value: data.get(valueDim, i),
  34704. selected: retrieveRawAttr(data, i, 'selected')
  34705. });
  34706. }
  34707. return targetList;
  34708. },
  34709. // Overwrite
  34710. getDataParams: function (dataIndex) {
  34711. var data = this.getData();
  34712. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  34713. // FIXME toFixed?
  34714. var valueList = [];
  34715. data.each(data.mapDimension('value'), function (value) {
  34716. valueList.push(value);
  34717. });
  34718. params.percent = getPercentWithPrecision(
  34719. valueList,
  34720. dataIndex,
  34721. data.hostModel.get('percentPrecision')
  34722. );
  34723. params.$vars.push('percent');
  34724. return params;
  34725. },
  34726. _defaultLabelLine: function (option) {
  34727. // Extend labelLine emphasis
  34728. defaultEmphasis(option, 'labelLine', ['show']);
  34729. var labelLineNormalOpt = option.labelLine;
  34730. var labelLineEmphasisOpt = option.emphasis.labelLine;
  34731. // Not show label line if `label.normal.show = false`
  34732. labelLineNormalOpt.show = labelLineNormalOpt.show
  34733. && option.label.show;
  34734. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  34735. && option.emphasis.label.show;
  34736. },
  34737. defaultOption: {
  34738. zlevel: 0,
  34739. z: 2,
  34740. legendHoverLink: true,
  34741. hoverAnimation: true,
  34742. // 默认全局居中
  34743. center: ['50%', '50%'],
  34744. radius: [0, '75%'],
  34745. // 默认顺时针
  34746. clockwise: true,
  34747. startAngle: 90,
  34748. // 最小角度改为0
  34749. minAngle: 0,
  34750. // 选中时扇区偏移量
  34751. selectedOffset: 10,
  34752. // 高亮扇区偏移量
  34753. hoverOffset: 10,
  34754. // If use strategy to avoid label overlapping
  34755. avoidLabelOverlap: true,
  34756. // 选择模式,默认关闭,可选single,multiple
  34757. // selectedMode: false,
  34758. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  34759. // roseType: null,
  34760. percentPrecision: 2,
  34761. // If still show when all data zero.
  34762. stillShowZeroSum: true,
  34763. // cursor: null,
  34764. label: {
  34765. // If rotate around circle
  34766. rotate: false,
  34767. show: true,
  34768. // 'outer', 'inside', 'center'
  34769. position: 'outer'
  34770. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  34771. // 默认使用全局文本样式,详见TEXTSTYLE
  34772. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  34773. },
  34774. // Enabled when label.normal.position is 'outer'
  34775. labelLine: {
  34776. show: true,
  34777. // 引导线两段中的第一段长度
  34778. length: 15,
  34779. // 引导线两段中的第二段长度
  34780. length2: 15,
  34781. smooth: false,
  34782. lineStyle: {
  34783. // color: 各异,
  34784. width: 1,
  34785. type: 'solid'
  34786. }
  34787. },
  34788. itemStyle: {
  34789. borderWidth: 1
  34790. },
  34791. // Animation type canbe expansion, scale
  34792. animationType: 'expansion',
  34793. animationEasing: 'cubicOut'
  34794. }
  34795. });
  34796. mixin(PieSeries, selectableMixin);
  34797. /*
  34798. * Licensed to the Apache Software Foundation (ASF) under one
  34799. * or more contributor license agreements. See the NOTICE file
  34800. * distributed with this work for additional information
  34801. * regarding copyright ownership. The ASF licenses this file
  34802. * to you under the Apache License, Version 2.0 (the
  34803. * "License"); you may not use this file except in compliance
  34804. * with the License. You may obtain a copy of the License at
  34805. *
  34806. * http://www.apache.org/licenses/LICENSE-2.0
  34807. *
  34808. * Unless required by applicable law or agreed to in writing,
  34809. * software distributed under the License is distributed on an
  34810. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34811. * KIND, either express or implied. See the License for the
  34812. * specific language governing permissions and limitations
  34813. * under the License.
  34814. */
  34815. /**
  34816. * @param {module:echarts/model/Series} seriesModel
  34817. * @param {boolean} hasAnimation
  34818. * @inner
  34819. */
  34820. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  34821. var data = seriesModel.getData();
  34822. var dataIndex = this.dataIndex;
  34823. var name = data.getName(dataIndex);
  34824. var selectedOffset = seriesModel.get('selectedOffset');
  34825. api.dispatchAction({
  34826. type: 'pieToggleSelect',
  34827. from: uid,
  34828. name: name,
  34829. seriesId: seriesModel.id
  34830. });
  34831. data.each(function (idx) {
  34832. toggleItemSelected(
  34833. data.getItemGraphicEl(idx),
  34834. data.getItemLayout(idx),
  34835. seriesModel.isSelected(data.getName(idx)),
  34836. selectedOffset,
  34837. hasAnimation
  34838. );
  34839. });
  34840. }
  34841. /**
  34842. * @param {module:zrender/graphic/Sector} el
  34843. * @param {Object} layout
  34844. * @param {boolean} isSelected
  34845. * @param {number} selectedOffset
  34846. * @param {boolean} hasAnimation
  34847. * @inner
  34848. */
  34849. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  34850. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  34851. var dx = Math.cos(midAngle);
  34852. var dy = Math.sin(midAngle);
  34853. var offset = isSelected ? selectedOffset : 0;
  34854. var position = [dx * offset, dy * offset];
  34855. hasAnimation
  34856. // animateTo will stop revious animation like update transition
  34857. ? el.animate()
  34858. .when(200, {
  34859. position: position
  34860. })
  34861. .start('bounceOut')
  34862. : el.attr('position', position);
  34863. }
  34864. /**
  34865. * Piece of pie including Sector, Label, LabelLine
  34866. * @constructor
  34867. * @extends {module:zrender/graphic/Group}
  34868. */
  34869. function PiePiece(data, idx) {
  34870. Group.call(this);
  34871. var sector = new Sector({
  34872. z2: 2
  34873. });
  34874. var polyline = new Polyline();
  34875. var text = new Text();
  34876. this.add(sector);
  34877. this.add(polyline);
  34878. this.add(text);
  34879. this.updateData(data, idx, true);
  34880. // Hover to change label and labelLine
  34881. function onEmphasis() {
  34882. polyline.ignore = polyline.hoverIgnore;
  34883. text.ignore = text.hoverIgnore;
  34884. }
  34885. function onNormal() {
  34886. polyline.ignore = polyline.normalIgnore;
  34887. text.ignore = text.normalIgnore;
  34888. }
  34889. this.on('emphasis', onEmphasis)
  34890. .on('normal', onNormal)
  34891. .on('mouseover', onEmphasis)
  34892. .on('mouseout', onNormal);
  34893. }
  34894. var piePieceProto = PiePiece.prototype;
  34895. piePieceProto.updateData = function (data, idx, firstCreate) {
  34896. var sector = this.childAt(0);
  34897. var seriesModel = data.hostModel;
  34898. var itemModel = data.getItemModel(idx);
  34899. var layout = data.getItemLayout(idx);
  34900. var sectorShape = extend({}, layout);
  34901. sectorShape.label = null;
  34902. if (firstCreate) {
  34903. sector.setShape(sectorShape);
  34904. var animationType = seriesModel.getShallow('animationType');
  34905. if (animationType === 'scale') {
  34906. sector.shape.r = layout.r0;
  34907. initProps(sector, {
  34908. shape: {
  34909. r: layout.r
  34910. }
  34911. }, seriesModel, idx);
  34912. }
  34913. // Expansion
  34914. else {
  34915. sector.shape.endAngle = layout.startAngle;
  34916. updateProps(sector, {
  34917. shape: {
  34918. endAngle: layout.endAngle
  34919. }
  34920. }, seriesModel, idx);
  34921. }
  34922. }
  34923. else {
  34924. updateProps(sector, {
  34925. shape: sectorShape
  34926. }, seriesModel, idx);
  34927. }
  34928. // Update common style
  34929. var visualColor = data.getItemVisual(idx, 'color');
  34930. sector.useStyle(
  34931. defaults(
  34932. {
  34933. lineJoin: 'bevel',
  34934. fill: visualColor
  34935. },
  34936. itemModel.getModel('itemStyle').getItemStyle()
  34937. )
  34938. );
  34939. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  34940. var cursorStyle = itemModel.getShallow('cursor');
  34941. cursorStyle && sector.attr('cursor', cursorStyle);
  34942. // Toggle selected
  34943. toggleItemSelected(
  34944. this,
  34945. data.getItemLayout(idx),
  34946. seriesModel.isSelected(null, idx),
  34947. seriesModel.get('selectedOffset'),
  34948. seriesModel.get('animation')
  34949. );
  34950. function onEmphasis() {
  34951. // Sector may has animation of updating data. Force to move to the last frame
  34952. // Or it may stopped on the wrong shape
  34953. sector.stopAnimation(true);
  34954. sector.animateTo({
  34955. shape: {
  34956. r: layout.r + seriesModel.get('hoverOffset')
  34957. }
  34958. }, 300, 'elasticOut');
  34959. }
  34960. function onNormal() {
  34961. sector.stopAnimation(true);
  34962. sector.animateTo({
  34963. shape: {
  34964. r: layout.r
  34965. }
  34966. }, 300, 'elasticOut');
  34967. }
  34968. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  34969. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  34970. sector
  34971. .on('mouseover', onEmphasis)
  34972. .on('mouseout', onNormal)
  34973. .on('emphasis', onEmphasis)
  34974. .on('normal', onNormal);
  34975. }
  34976. this._updateLabel(data, idx);
  34977. setHoverStyle(this);
  34978. };
  34979. piePieceProto._updateLabel = function (data, idx) {
  34980. var labelLine = this.childAt(1);
  34981. var labelText = this.childAt(2);
  34982. var seriesModel = data.hostModel;
  34983. var itemModel = data.getItemModel(idx);
  34984. var layout = data.getItemLayout(idx);
  34985. var labelLayout = layout.label;
  34986. var visualColor = data.getItemVisual(idx, 'color');
  34987. updateProps(labelLine, {
  34988. shape: {
  34989. points: labelLayout.linePoints || [
  34990. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  34991. ]
  34992. }
  34993. }, seriesModel, idx);
  34994. updateProps(labelText, {
  34995. style: {
  34996. x: labelLayout.x,
  34997. y: labelLayout.y
  34998. }
  34999. }, seriesModel, idx);
  35000. labelText.attr({
  35001. rotation: labelLayout.rotation,
  35002. origin: [labelLayout.x, labelLayout.y],
  35003. z2: 10
  35004. });
  35005. var labelModel = itemModel.getModel('label');
  35006. var labelHoverModel = itemModel.getModel('emphasis.label');
  35007. var labelLineModel = itemModel.getModel('labelLine');
  35008. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  35009. var visualColor = data.getItemVisual(idx, 'color');
  35010. setLabelStyle(
  35011. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  35012. {
  35013. labelFetcher: data.hostModel,
  35014. labelDataIndex: idx,
  35015. defaultText: data.getName(idx),
  35016. autoColor: visualColor,
  35017. useInsideStyle: !!labelLayout.inside
  35018. },
  35019. {
  35020. textAlign: labelLayout.textAlign,
  35021. textVerticalAlign: labelLayout.verticalAlign,
  35022. opacity: data.getItemVisual(idx, 'opacity')
  35023. }
  35024. );
  35025. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  35026. labelText.hoverIgnore = !labelHoverModel.get('show');
  35027. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  35028. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  35029. // Default use item visual color
  35030. labelLine.setStyle({
  35031. stroke: visualColor,
  35032. opacity: data.getItemVisual(idx, 'opacity')
  35033. });
  35034. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  35035. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  35036. var smooth = labelLineModel.get('smooth');
  35037. if (smooth && smooth === true) {
  35038. smooth = 0.4;
  35039. }
  35040. labelLine.setShape({
  35041. smooth: smooth
  35042. });
  35043. };
  35044. inherits(PiePiece, Group);
  35045. // Pie view
  35046. var PieView = Chart.extend({
  35047. type: 'pie',
  35048. init: function () {
  35049. var sectorGroup = new Group();
  35050. this._sectorGroup = sectorGroup;
  35051. },
  35052. render: function (seriesModel, ecModel, api, payload) {
  35053. if (payload && (payload.from === this.uid)) {
  35054. return;
  35055. }
  35056. var data = seriesModel.getData();
  35057. var oldData = this._data;
  35058. var group = this.group;
  35059. var hasAnimation = ecModel.get('animation');
  35060. var isFirstRender = !oldData;
  35061. var animationType = seriesModel.get('animationType');
  35062. var onSectorClick = curry(
  35063. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  35064. );
  35065. var selectedMode = seriesModel.get('selectedMode');
  35066. data.diff(oldData)
  35067. .add(function (idx) {
  35068. var piePiece = new PiePiece(data, idx);
  35069. // Default expansion animation
  35070. if (isFirstRender && animationType !== 'scale') {
  35071. piePiece.eachChild(function (child) {
  35072. child.stopAnimation(true);
  35073. });
  35074. }
  35075. selectedMode && piePiece.on('click', onSectorClick);
  35076. data.setItemGraphicEl(idx, piePiece);
  35077. group.add(piePiece);
  35078. })
  35079. .update(function (newIdx, oldIdx) {
  35080. var piePiece = oldData.getItemGraphicEl(oldIdx);
  35081. piePiece.updateData(data, newIdx);
  35082. piePiece.off('click');
  35083. selectedMode && piePiece.on('click', onSectorClick);
  35084. group.add(piePiece);
  35085. data.setItemGraphicEl(newIdx, piePiece);
  35086. })
  35087. .remove(function (idx) {
  35088. var piePiece = oldData.getItemGraphicEl(idx);
  35089. group.remove(piePiece);
  35090. })
  35091. .execute();
  35092. if (
  35093. hasAnimation && isFirstRender && data.count() > 0
  35094. // Default expansion animation
  35095. && animationType !== 'scale'
  35096. ) {
  35097. var shape = data.getItemLayout(0);
  35098. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  35099. var removeClipPath = bind(group.removeClipPath, group);
  35100. group.setClipPath(this._createClipPath(
  35101. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  35102. ));
  35103. }
  35104. this._data = data;
  35105. },
  35106. dispose: function () {},
  35107. _createClipPath: function (
  35108. cx, cy, r, startAngle, clockwise, cb, seriesModel
  35109. ) {
  35110. var clipPath = new Sector({
  35111. shape: {
  35112. cx: cx,
  35113. cy: cy,
  35114. r0: 0,
  35115. r: r,
  35116. startAngle: startAngle,
  35117. endAngle: startAngle,
  35118. clockwise: clockwise
  35119. }
  35120. });
  35121. initProps(clipPath, {
  35122. shape: {
  35123. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  35124. }
  35125. }, seriesModel, cb);
  35126. return clipPath;
  35127. },
  35128. /**
  35129. * @implement
  35130. */
  35131. containPoint: function (point, seriesModel) {
  35132. var data = seriesModel.getData();
  35133. var itemLayout = data.getItemLayout(0);
  35134. if (itemLayout) {
  35135. var dx = point[0] - itemLayout.cx;
  35136. var dy = point[1] - itemLayout.cy;
  35137. var radius = Math.sqrt(dx * dx + dy * dy);
  35138. return radius <= itemLayout.r && radius >= itemLayout.r0;
  35139. }
  35140. }
  35141. });
  35142. /*
  35143. * Licensed to the Apache Software Foundation (ASF) under one
  35144. * or more contributor license agreements. See the NOTICE file
  35145. * distributed with this work for additional information
  35146. * regarding copyright ownership. The ASF licenses this file
  35147. * to you under the Apache License, Version 2.0 (the
  35148. * "License"); you may not use this file except in compliance
  35149. * with the License. You may obtain a copy of the License at
  35150. *
  35151. * http://www.apache.org/licenses/LICENSE-2.0
  35152. *
  35153. * Unless required by applicable law or agreed to in writing,
  35154. * software distributed under the License is distributed on an
  35155. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35156. * KIND, either express or implied. See the License for the
  35157. * specific language governing permissions and limitations
  35158. * under the License.
  35159. */
  35160. var createDataSelectAction = function (seriesType, actionInfos) {
  35161. each$1(actionInfos, function (actionInfo) {
  35162. actionInfo.update = 'updateView';
  35163. /**
  35164. * @payload
  35165. * @property {string} seriesName
  35166. * @property {string} name
  35167. */
  35168. registerAction(actionInfo, function (payload, ecModel) {
  35169. var selected = {};
  35170. ecModel.eachComponent(
  35171. {mainType: 'series', subType: seriesType, query: payload},
  35172. function (seriesModel) {
  35173. if (seriesModel[actionInfo.method]) {
  35174. seriesModel[actionInfo.method](
  35175. payload.name,
  35176. payload.dataIndex
  35177. );
  35178. }
  35179. var data = seriesModel.getData();
  35180. // Create selected map
  35181. data.each(function (idx) {
  35182. var name = data.getName(idx);
  35183. selected[name] = seriesModel.isSelected(name)
  35184. || false;
  35185. });
  35186. }
  35187. );
  35188. return {
  35189. name: payload.name,
  35190. selected: selected
  35191. };
  35192. });
  35193. });
  35194. };
  35195. /*
  35196. * Licensed to the Apache Software Foundation (ASF) under one
  35197. * or more contributor license agreements. See the NOTICE file
  35198. * distributed with this work for additional information
  35199. * regarding copyright ownership. The ASF licenses this file
  35200. * to you under the Apache License, Version 2.0 (the
  35201. * "License"); you may not use this file except in compliance
  35202. * with the License. You may obtain a copy of the License at
  35203. *
  35204. * http://www.apache.org/licenses/LICENSE-2.0
  35205. *
  35206. * Unless required by applicable law or agreed to in writing,
  35207. * software distributed under the License is distributed on an
  35208. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35209. * KIND, either express or implied. See the License for the
  35210. * specific language governing permissions and limitations
  35211. * under the License.
  35212. */
  35213. // Pick color from palette for each data item.
  35214. // Applicable for charts that require applying color palette
  35215. // in data level (like pie, funnel, chord).
  35216. var dataColor = function (seriesType) {
  35217. return {
  35218. getTargetSeries: function (ecModel) {
  35219. // Pie and funnel may use diferrent scope
  35220. var paletteScope = {};
  35221. var seiresModelMap = createHashMap();
  35222. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35223. seriesModel.__paletteScope = paletteScope;
  35224. seiresModelMap.set(seriesModel.uid, seriesModel);
  35225. });
  35226. return seiresModelMap;
  35227. },
  35228. reset: function (seriesModel, ecModel) {
  35229. var dataAll = seriesModel.getRawData();
  35230. var idxMap = {};
  35231. var data = seriesModel.getData();
  35232. data.each(function (idx) {
  35233. var rawIdx = data.getRawIndex(idx);
  35234. idxMap[rawIdx] = idx;
  35235. });
  35236. dataAll.each(function (rawIdx) {
  35237. var filteredIdx = idxMap[rawIdx];
  35238. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  35239. var singleDataColor = filteredIdx != null
  35240. && data.getItemVisual(filteredIdx, 'color', true);
  35241. if (!singleDataColor) {
  35242. // FIXME Performance
  35243. var itemModel = dataAll.getItemModel(rawIdx);
  35244. var color = itemModel.get('itemStyle.color')
  35245. || seriesModel.getColorFromPalette(
  35246. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  35247. dataAll.count()
  35248. );
  35249. // Legend may use the visual info in data before processed
  35250. dataAll.setItemVisual(rawIdx, 'color', color);
  35251. // Data is not filtered
  35252. if (filteredIdx != null) {
  35253. data.setItemVisual(filteredIdx, 'color', color);
  35254. }
  35255. }
  35256. else {
  35257. // Set data all color for legend
  35258. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  35259. }
  35260. });
  35261. }
  35262. };
  35263. };
  35264. /*
  35265. * Licensed to the Apache Software Foundation (ASF) under one
  35266. * or more contributor license agreements. See the NOTICE file
  35267. * distributed with this work for additional information
  35268. * regarding copyright ownership. The ASF licenses this file
  35269. * to you under the Apache License, Version 2.0 (the
  35270. * "License"); you may not use this file except in compliance
  35271. * with the License. You may obtain a copy of the License at
  35272. *
  35273. * http://www.apache.org/licenses/LICENSE-2.0
  35274. *
  35275. * Unless required by applicable law or agreed to in writing,
  35276. * software distributed under the License is distributed on an
  35277. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35278. * KIND, either express or implied. See the License for the
  35279. * specific language governing permissions and limitations
  35280. * under the License.
  35281. */
  35282. // FIXME emphasis label position is not same with normal label position
  35283. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  35284. list.sort(function (a, b) {
  35285. return a.y - b.y;
  35286. });
  35287. // 压
  35288. function shiftDown(start, end, delta, dir) {
  35289. for (var j = start; j < end; j++) {
  35290. list[j].y += delta;
  35291. if (j > start
  35292. && j + 1 < end
  35293. && list[j + 1].y > list[j].y + list[j].height
  35294. ) {
  35295. shiftUp(j, delta / 2);
  35296. return;
  35297. }
  35298. }
  35299. shiftUp(end - 1, delta / 2);
  35300. }
  35301. // 弹
  35302. function shiftUp(end, delta) {
  35303. for (var j = end; j >= 0; j--) {
  35304. list[j].y -= delta;
  35305. if (j > 0
  35306. && list[j].y > list[j - 1].y + list[j - 1].height
  35307. ) {
  35308. break;
  35309. }
  35310. }
  35311. }
  35312. function changeX(list, isDownList, cx, cy, r, dir) {
  35313. var lastDeltaX = dir > 0
  35314. ? isDownList // 右侧
  35315. ? Number.MAX_VALUE // 下
  35316. : 0 // 上
  35317. : isDownList // 左侧
  35318. ? Number.MAX_VALUE // 下
  35319. : 0; // 上
  35320. for (var i = 0, l = list.length; i < l; i++) {
  35321. // Not change x for center label
  35322. if (list[i].position === 'center') {
  35323. continue;
  35324. }
  35325. var deltaY = Math.abs(list[i].y - cy);
  35326. var length = list[i].len;
  35327. var length2 = list[i].len2;
  35328. var deltaX = (deltaY < r + length)
  35329. ? Math.sqrt(
  35330. (r + length + length2) * (r + length + length2)
  35331. - deltaY * deltaY
  35332. )
  35333. : Math.abs(list[i].x - cx);
  35334. if (isDownList && deltaX >= lastDeltaX) {
  35335. // 右下,左下
  35336. deltaX = lastDeltaX - 10;
  35337. }
  35338. if (!isDownList && deltaX <= lastDeltaX) {
  35339. // 右上,左上
  35340. deltaX = lastDeltaX + 10;
  35341. }
  35342. list[i].x = cx + deltaX * dir;
  35343. lastDeltaX = deltaX;
  35344. }
  35345. }
  35346. var lastY = 0;
  35347. var delta;
  35348. var len = list.length;
  35349. var upList = [];
  35350. var downList = [];
  35351. for (var i = 0; i < len; i++) {
  35352. delta = list[i].y - lastY;
  35353. if (delta < 0) {
  35354. shiftDown(i, len, -delta, dir);
  35355. }
  35356. lastY = list[i].y + list[i].height;
  35357. }
  35358. if (viewHeight - lastY < 0) {
  35359. shiftUp(len - 1, lastY - viewHeight);
  35360. }
  35361. for (var i = 0; i < len; i++) {
  35362. if (list[i].y >= cy) {
  35363. downList.push(list[i]);
  35364. }
  35365. else {
  35366. upList.push(list[i]);
  35367. }
  35368. }
  35369. changeX(upList, false, cx, cy, r, dir);
  35370. changeX(downList, true, cx, cy, r, dir);
  35371. }
  35372. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  35373. var leftList = [];
  35374. var rightList = [];
  35375. for (var i = 0; i < labelLayoutList.length; i++) {
  35376. if (labelLayoutList[i].x < cx) {
  35377. leftList.push(labelLayoutList[i]);
  35378. }
  35379. else {
  35380. rightList.push(labelLayoutList[i]);
  35381. }
  35382. }
  35383. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  35384. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  35385. for (var i = 0; i < labelLayoutList.length; i++) {
  35386. var linePoints = labelLayoutList[i].linePoints;
  35387. if (linePoints) {
  35388. var dist = linePoints[1][0] - linePoints[2][0];
  35389. if (labelLayoutList[i].x < cx) {
  35390. linePoints[2][0] = labelLayoutList[i].x + 3;
  35391. }
  35392. else {
  35393. linePoints[2][0] = labelLayoutList[i].x - 3;
  35394. }
  35395. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  35396. linePoints[1][0] = linePoints[2][0] + dist;
  35397. }
  35398. }
  35399. }
  35400. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  35401. var data = seriesModel.getData();
  35402. var labelLayoutList = [];
  35403. var cx;
  35404. var cy;
  35405. var hasLabelRotate = false;
  35406. data.each(function (idx) {
  35407. var layout = data.getItemLayout(idx);
  35408. var itemModel = data.getItemModel(idx);
  35409. var labelModel = itemModel.getModel('label');
  35410. // Use position in normal or emphasis
  35411. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  35412. var labelLineModel = itemModel.getModel('labelLine');
  35413. var labelLineLen = labelLineModel.get('length');
  35414. var labelLineLen2 = labelLineModel.get('length2');
  35415. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  35416. var dx = Math.cos(midAngle);
  35417. var dy = Math.sin(midAngle);
  35418. var textX;
  35419. var textY;
  35420. var linePoints;
  35421. var textAlign;
  35422. cx = layout.cx;
  35423. cy = layout.cy;
  35424. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  35425. if (labelPosition === 'center') {
  35426. textX = layout.cx;
  35427. textY = layout.cy;
  35428. textAlign = 'center';
  35429. }
  35430. else {
  35431. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  35432. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  35433. textX = x1 + dx * 3;
  35434. textY = y1 + dy * 3;
  35435. if (!isLabelInside) {
  35436. // For roseType
  35437. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  35438. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  35439. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  35440. var y3 = y2;
  35441. textX = x3 + (dx < 0 ? -5 : 5);
  35442. textY = y3;
  35443. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  35444. }
  35445. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  35446. }
  35447. var font = labelModel.getFont();
  35448. var labelRotate = labelModel.get('rotate')
  35449. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  35450. var text = seriesModel.getFormattedLabel(idx, 'normal')
  35451. || data.getName(idx);
  35452. var textRect = getBoundingRect(
  35453. text, font, textAlign, 'top'
  35454. );
  35455. hasLabelRotate = !!labelRotate;
  35456. layout.label = {
  35457. x: textX,
  35458. y: textY,
  35459. position: labelPosition,
  35460. height: textRect.height,
  35461. len: labelLineLen,
  35462. len2: labelLineLen2,
  35463. linePoints: linePoints,
  35464. textAlign: textAlign,
  35465. verticalAlign: 'middle',
  35466. rotation: labelRotate,
  35467. inside: isLabelInside
  35468. };
  35469. // Not layout the inside label
  35470. if (!isLabelInside) {
  35471. labelLayoutList.push(layout.label);
  35472. }
  35473. });
  35474. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  35475. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  35476. }
  35477. };
  35478. /*
  35479. * Licensed to the Apache Software Foundation (ASF) under one
  35480. * or more contributor license agreements. See the NOTICE file
  35481. * distributed with this work for additional information
  35482. * regarding copyright ownership. The ASF licenses this file
  35483. * to you under the Apache License, Version 2.0 (the
  35484. * "License"); you may not use this file except in compliance
  35485. * with the License. You may obtain a copy of the License at
  35486. *
  35487. * http://www.apache.org/licenses/LICENSE-2.0
  35488. *
  35489. * Unless required by applicable law or agreed to in writing,
  35490. * software distributed under the License is distributed on an
  35491. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35492. * KIND, either express or implied. See the License for the
  35493. * specific language governing permissions and limitations
  35494. * under the License.
  35495. */
  35496. var PI2$4 = Math.PI * 2;
  35497. var RADIAN = Math.PI / 180;
  35498. var pieLayout = function (seriesType, ecModel, api, payload) {
  35499. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35500. var data = seriesModel.getData();
  35501. var valueDim = data.mapDimension('value');
  35502. var center = seriesModel.get('center');
  35503. var radius = seriesModel.get('radius');
  35504. if (!isArray(radius)) {
  35505. radius = [0, radius];
  35506. }
  35507. if (!isArray(center)) {
  35508. center = [center, center];
  35509. }
  35510. var width = api.getWidth();
  35511. var height = api.getHeight();
  35512. var size = Math.min(width, height);
  35513. var cx = parsePercent$1(center[0], width);
  35514. var cy = parsePercent$1(center[1], height);
  35515. var r0 = parsePercent$1(radius[0], size / 2);
  35516. var r = parsePercent$1(radius[1], size / 2);
  35517. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  35518. var minAngle = seriesModel.get('minAngle') * RADIAN;
  35519. var validDataCount = 0;
  35520. data.each(valueDim, function (value) {
  35521. !isNaN(value) && validDataCount++;
  35522. });
  35523. var sum = data.getSum(valueDim);
  35524. // Sum may be 0
  35525. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  35526. var clockwise = seriesModel.get('clockwise');
  35527. var roseType = seriesModel.get('roseType');
  35528. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  35529. // [0...max]
  35530. var extent = data.getDataExtent(valueDim);
  35531. extent[0] = 0;
  35532. // In the case some sector angle is smaller than minAngle
  35533. var restAngle = PI2$4;
  35534. var valueSumLargerThanMinAngle = 0;
  35535. var currentAngle = startAngle;
  35536. var dir = clockwise ? 1 : -1;
  35537. data.each(valueDim, function (value, idx) {
  35538. var angle;
  35539. if (isNaN(value)) {
  35540. data.setItemLayout(idx, {
  35541. angle: NaN,
  35542. startAngle: NaN,
  35543. endAngle: NaN,
  35544. clockwise: clockwise,
  35545. cx: cx,
  35546. cy: cy,
  35547. r0: r0,
  35548. r: roseType
  35549. ? NaN
  35550. : r
  35551. });
  35552. return;
  35553. }
  35554. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  35555. if (roseType !== 'area') {
  35556. angle = (sum === 0 && stillShowZeroSum)
  35557. ? unitRadian : (value * unitRadian);
  35558. }
  35559. else {
  35560. angle = PI2$4 / validDataCount;
  35561. }
  35562. if (angle < minAngle) {
  35563. angle = minAngle;
  35564. restAngle -= minAngle;
  35565. }
  35566. else {
  35567. valueSumLargerThanMinAngle += value;
  35568. }
  35569. var endAngle = currentAngle + dir * angle;
  35570. data.setItemLayout(idx, {
  35571. angle: angle,
  35572. startAngle: currentAngle,
  35573. endAngle: endAngle,
  35574. clockwise: clockwise,
  35575. cx: cx,
  35576. cy: cy,
  35577. r0: r0,
  35578. r: roseType
  35579. ? linearMap(value, extent, [r0, r])
  35580. : r
  35581. });
  35582. currentAngle = endAngle;
  35583. });
  35584. // Some sector is constrained by minAngle
  35585. // Rest sectors needs recalculate angle
  35586. if (restAngle < PI2$4 && validDataCount) {
  35587. // Average the angle if rest angle is not enough after all angles is
  35588. // Constrained by minAngle
  35589. if (restAngle <= 1e-3) {
  35590. var angle = PI2$4 / validDataCount;
  35591. data.each(valueDim, function (value, idx) {
  35592. if (!isNaN(value)) {
  35593. var layout = data.getItemLayout(idx);
  35594. layout.angle = angle;
  35595. layout.startAngle = startAngle + dir * idx * angle;
  35596. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  35597. }
  35598. });
  35599. }
  35600. else {
  35601. unitRadian = restAngle / valueSumLargerThanMinAngle;
  35602. currentAngle = startAngle;
  35603. data.each(valueDim, function (value, idx) {
  35604. if (!isNaN(value)) {
  35605. var layout = data.getItemLayout(idx);
  35606. var angle = layout.angle === minAngle
  35607. ? minAngle : value * unitRadian;
  35608. layout.startAngle = currentAngle;
  35609. layout.endAngle = currentAngle + dir * angle;
  35610. currentAngle += dir * angle;
  35611. }
  35612. });
  35613. }
  35614. }
  35615. labelLayout(seriesModel, r, width, height);
  35616. });
  35617. };
  35618. /*
  35619. * Licensed to the Apache Software Foundation (ASF) under one
  35620. * or more contributor license agreements. See the NOTICE file
  35621. * distributed with this work for additional information
  35622. * regarding copyright ownership. The ASF licenses this file
  35623. * to you under the Apache License, Version 2.0 (the
  35624. * "License"); you may not use this file except in compliance
  35625. * with the License. You may obtain a copy of the License at
  35626. *
  35627. * http://www.apache.org/licenses/LICENSE-2.0
  35628. *
  35629. * Unless required by applicable law or agreed to in writing,
  35630. * software distributed under the License is distributed on an
  35631. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35632. * KIND, either express or implied. See the License for the
  35633. * specific language governing permissions and limitations
  35634. * under the License.
  35635. */
  35636. var dataFilter = function (seriesType) {
  35637. return {
  35638. seriesType: seriesType,
  35639. reset: function (seriesModel, ecModel) {
  35640. var legendModels = ecModel.findComponents({
  35641. mainType: 'legend'
  35642. });
  35643. if (!legendModels || !legendModels.length) {
  35644. return;
  35645. }
  35646. var data = seriesModel.getData();
  35647. data.filterSelf(function (idx) {
  35648. var name = data.getName(idx);
  35649. // If in any legend component the status is not selected.
  35650. for (var i = 0; i < legendModels.length; i++) {
  35651. if (!legendModels[i].isSelected(name)) {
  35652. return false;
  35653. }
  35654. }
  35655. return true;
  35656. });
  35657. }
  35658. };
  35659. };
  35660. /*
  35661. * Licensed to the Apache Software Foundation (ASF) under one
  35662. * or more contributor license agreements. See the NOTICE file
  35663. * distributed with this work for additional information
  35664. * regarding copyright ownership. The ASF licenses this file
  35665. * to you under the Apache License, Version 2.0 (the
  35666. * "License"); you may not use this file except in compliance
  35667. * with the License. You may obtain a copy of the License at
  35668. *
  35669. * http://www.apache.org/licenses/LICENSE-2.0
  35670. *
  35671. * Unless required by applicable law or agreed to in writing,
  35672. * software distributed under the License is distributed on an
  35673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35674. * KIND, either express or implied. See the License for the
  35675. * specific language governing permissions and limitations
  35676. * under the License.
  35677. */
  35678. createDataSelectAction('pie', [{
  35679. type: 'pieToggleSelect',
  35680. event: 'pieselectchanged',
  35681. method: 'toggleSelected'
  35682. }, {
  35683. type: 'pieSelect',
  35684. event: 'pieselected',
  35685. method: 'select'
  35686. }, {
  35687. type: 'pieUnSelect',
  35688. event: 'pieunselected',
  35689. method: 'unSelect'
  35690. }]);
  35691. registerVisual(dataColor('pie'));
  35692. registerLayout(curry(pieLayout, 'pie'));
  35693. registerProcessor(dataFilter('pie'));
  35694. /*
  35695. * Licensed to the Apache Software Foundation (ASF) under one
  35696. * or more contributor license agreements. See the NOTICE file
  35697. * distributed with this work for additional information
  35698. * regarding copyright ownership. The ASF licenses this file
  35699. * to you under the Apache License, Version 2.0 (the
  35700. * "License"); you may not use this file except in compliance
  35701. * with the License. You may obtain a copy of the License at
  35702. *
  35703. * http://www.apache.org/licenses/LICENSE-2.0
  35704. *
  35705. * Unless required by applicable law or agreed to in writing,
  35706. * software distributed under the License is distributed on an
  35707. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35708. * KIND, either express or implied. See the License for the
  35709. * specific language governing permissions and limitations
  35710. * under the License.
  35711. */
  35712. SeriesModel.extend({
  35713. type: 'series.scatter',
  35714. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  35715. getInitialData: function (option, ecModel) {
  35716. return createListFromArray(this.getSource(), this);
  35717. },
  35718. brushSelector: 'point',
  35719. getProgressive: function () {
  35720. var progressive = this.option.progressive;
  35721. if (progressive == null) {
  35722. // PENDING
  35723. return this.option.large ? 5e3 : this.get('progressive');
  35724. }
  35725. return progressive;
  35726. },
  35727. getProgressiveThreshold: function () {
  35728. var progressiveThreshold = this.option.progressiveThreshold;
  35729. if (progressiveThreshold == null) {
  35730. // PENDING
  35731. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  35732. }
  35733. return progressiveThreshold;
  35734. },
  35735. defaultOption: {
  35736. coordinateSystem: 'cartesian2d',
  35737. zlevel: 0,
  35738. z: 2,
  35739. legendHoverLink: true,
  35740. hoverAnimation: true,
  35741. // Cartesian coordinate system
  35742. // xAxisIndex: 0,
  35743. // yAxisIndex: 0,
  35744. // Polar coordinate system
  35745. // polarIndex: 0,
  35746. // Geo coordinate system
  35747. // geoIndex: 0,
  35748. // symbol: null, // 图形类型
  35749. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  35750. // symbolRotate: null, // 图形旋转控制
  35751. large: false,
  35752. // Available when large is true
  35753. largeThreshold: 2000,
  35754. // cursor: null,
  35755. // label: {
  35756. // show: false
  35757. // distance: 5,
  35758. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  35759. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  35760. // 'inside'|'left'|'right'|'top'|'bottom'
  35761. // 默认使用全局文本样式,详见TEXTSTYLE
  35762. // },
  35763. itemStyle: {
  35764. opacity: 0.8
  35765. // color: 各异
  35766. }
  35767. // progressive: null
  35768. }
  35769. });
  35770. /*
  35771. * Licensed to the Apache Software Foundation (ASF) under one
  35772. * or more contributor license agreements. See the NOTICE file
  35773. * distributed with this work for additional information
  35774. * regarding copyright ownership. The ASF licenses this file
  35775. * to you under the Apache License, Version 2.0 (the
  35776. * "License"); you may not use this file except in compliance
  35777. * with the License. You may obtain a copy of the License at
  35778. *
  35779. * http://www.apache.org/licenses/LICENSE-2.0
  35780. *
  35781. * Unless required by applicable law or agreed to in writing,
  35782. * software distributed under the License is distributed on an
  35783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35784. * KIND, either express or implied. See the License for the
  35785. * specific language governing permissions and limitations
  35786. * under the License.
  35787. */
  35788. // TODO Batch by color
  35789. var BOOST_SIZE_THRESHOLD = 4;
  35790. var LargeSymbolPath = extendShape({
  35791. shape: {
  35792. points: null
  35793. },
  35794. symbolProxy: null,
  35795. buildPath: function (path, shape) {
  35796. var points = shape.points;
  35797. var size = shape.size;
  35798. var symbolProxy = this.symbolProxy;
  35799. var symbolProxyShape = symbolProxy.shape;
  35800. var ctx = path.getContext ? path.getContext() : path;
  35801. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  35802. // Do draw in afterBrush.
  35803. if (canBoost) {
  35804. return;
  35805. }
  35806. for (var i = 0; i < points.length;) {
  35807. var x = points[i++];
  35808. var y = points[i++];
  35809. if (isNaN(x) || isNaN(y)) {
  35810. continue;
  35811. }
  35812. symbolProxyShape.x = x - size[0] / 2;
  35813. symbolProxyShape.y = y - size[1] / 2;
  35814. symbolProxyShape.width = size[0];
  35815. symbolProxyShape.height = size[1];
  35816. symbolProxy.buildPath(path, symbolProxyShape, true);
  35817. }
  35818. },
  35819. afterBrush: function (ctx) {
  35820. var shape = this.shape;
  35821. var points = shape.points;
  35822. var size = shape.size;
  35823. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  35824. if (!canBoost) {
  35825. return;
  35826. }
  35827. this.setTransform(ctx);
  35828. // PENDING If style or other canvas status changed?
  35829. for (var i = 0; i < points.length;) {
  35830. var x = points[i++];
  35831. var y = points[i++];
  35832. if (isNaN(x) || isNaN(y)) {
  35833. continue;
  35834. }
  35835. // fillRect is faster than building a rect path and draw.
  35836. // And it support light globalCompositeOperation.
  35837. ctx.fillRect(
  35838. x - size[0] / 2, y - size[1] / 2,
  35839. size[0], size[1]
  35840. );
  35841. }
  35842. this.restoreTransform(ctx);
  35843. },
  35844. findDataIndex: function (x, y) {
  35845. // TODO ???
  35846. // Consider transform
  35847. var shape = this.shape;
  35848. var points = shape.points;
  35849. var size = shape.size;
  35850. var w = Math.max(size[0], 4);
  35851. var h = Math.max(size[1], 4);
  35852. // Not consider transform
  35853. // Treat each element as a rect
  35854. // top down traverse
  35855. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  35856. var i = idx * 2;
  35857. var x0 = points[i] - w / 2;
  35858. var y0 = points[i + 1] - h / 2;
  35859. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  35860. return idx;
  35861. }
  35862. }
  35863. return -1;
  35864. }
  35865. });
  35866. function LargeSymbolDraw() {
  35867. this.group = new Group();
  35868. }
  35869. var largeSymbolProto = LargeSymbolDraw.prototype;
  35870. largeSymbolProto.isPersistent = function () {
  35871. return !this._incremental;
  35872. };
  35873. /**
  35874. * Update symbols draw by new data
  35875. * @param {module:echarts/data/List} data
  35876. */
  35877. largeSymbolProto.updateData = function (data) {
  35878. this.group.removeAll();
  35879. var symbolEl = new LargeSymbolPath({
  35880. rectHover: true,
  35881. cursor: 'default'
  35882. });
  35883. symbolEl.setShape({
  35884. points: data.getLayout('symbolPoints')
  35885. });
  35886. this._setCommon(symbolEl, data);
  35887. this.group.add(symbolEl);
  35888. this._incremental = null;
  35889. };
  35890. largeSymbolProto.updateLayout = function (data) {
  35891. if (this._incremental) {
  35892. return;
  35893. }
  35894. var points = data.getLayout('symbolPoints');
  35895. this.group.eachChild(function (child) {
  35896. if (child.startIndex != null) {
  35897. var len = (child.endIndex - child.startIndex) * 2;
  35898. var byteOffset = child.startIndex * 4 * 2;
  35899. points = new Float32Array(points.buffer, byteOffset, len);
  35900. }
  35901. child.setShape('points', points);
  35902. });
  35903. };
  35904. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  35905. this.group.removeAll();
  35906. this._clearIncremental();
  35907. // Only use incremental displayables when data amount is larger than 2 million.
  35908. // PENDING Incremental data?
  35909. if (data.count() > 2e6) {
  35910. if (!this._incremental) {
  35911. this._incremental = new IncrementalDisplayble({
  35912. silent: true
  35913. });
  35914. }
  35915. this.group.add(this._incremental);
  35916. }
  35917. else {
  35918. this._incremental = null;
  35919. }
  35920. };
  35921. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  35922. var symbolEl;
  35923. if (this._incremental) {
  35924. symbolEl = new LargeSymbolPath();
  35925. this._incremental.addDisplayable(symbolEl, true);
  35926. }
  35927. else {
  35928. symbolEl = new LargeSymbolPath({
  35929. rectHover: true,
  35930. cursor: 'default',
  35931. startIndex: taskParams.start,
  35932. endIndex: taskParams.end
  35933. });
  35934. symbolEl.incremental = true;
  35935. this.group.add(symbolEl);
  35936. }
  35937. symbolEl.setShape({
  35938. points: data.getLayout('symbolPoints')
  35939. });
  35940. this._setCommon(symbolEl, data, !!this._incremental);
  35941. };
  35942. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  35943. var hostModel = data.hostModel;
  35944. // TODO
  35945. // if (data.hasItemVisual.symbolSize) {
  35946. // // TODO typed array?
  35947. // symbolEl.setShape('sizes', data.mapArray(
  35948. // function (idx) {
  35949. // var size = data.getItemVisual(idx, 'symbolSize');
  35950. // return (size instanceof Array) ? size : [size, size];
  35951. // }
  35952. // ));
  35953. // }
  35954. // else {
  35955. var size = data.getVisual('symbolSize');
  35956. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  35957. // }
  35958. // Create symbolProxy to build path for each data
  35959. symbolEl.symbolProxy = createSymbol(
  35960. data.getVisual('symbol'), 0, 0, 0, 0
  35961. );
  35962. // Use symbolProxy setColor method
  35963. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  35964. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  35965. symbolEl.useStyle(
  35966. // Draw shadow when doing fillRect is extremely slow.
  35967. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  35968. );
  35969. var visualColor = data.getVisual('color');
  35970. if (visualColor) {
  35971. symbolEl.setColor(visualColor);
  35972. }
  35973. if (!isIncremental) {
  35974. // Enable tooltip
  35975. // PENDING May have performance issue when path is extremely large
  35976. symbolEl.seriesIndex = hostModel.seriesIndex;
  35977. symbolEl.on('mousemove', function (e) {
  35978. symbolEl.dataIndex = null;
  35979. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  35980. if (dataIndex >= 0) {
  35981. // Provide dataIndex for tooltip
  35982. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  35983. }
  35984. });
  35985. }
  35986. };
  35987. largeSymbolProto.remove = function () {
  35988. this._clearIncremental();
  35989. this._incremental = null;
  35990. this.group.removeAll();
  35991. };
  35992. largeSymbolProto._clearIncremental = function () {
  35993. var incremental = this._incremental;
  35994. if (incremental) {
  35995. incremental.clearDisplaybles();
  35996. }
  35997. };
  35998. /*
  35999. * Licensed to the Apache Software Foundation (ASF) under one
  36000. * or more contributor license agreements. See the NOTICE file
  36001. * distributed with this work for additional information
  36002. * regarding copyright ownership. The ASF licenses this file
  36003. * to you under the Apache License, Version 2.0 (the
  36004. * "License"); you may not use this file except in compliance
  36005. * with the License. You may obtain a copy of the License at
  36006. *
  36007. * http://www.apache.org/licenses/LICENSE-2.0
  36008. *
  36009. * Unless required by applicable law or agreed to in writing,
  36010. * software distributed under the License is distributed on an
  36011. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36012. * KIND, either express or implied. See the License for the
  36013. * specific language governing permissions and limitations
  36014. * under the License.
  36015. */
  36016. extendChartView({
  36017. type: 'scatter',
  36018. render: function (seriesModel, ecModel, api) {
  36019. var data = seriesModel.getData();
  36020. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  36021. symbolDraw.updateData(data);
  36022. this._finished = true;
  36023. },
  36024. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  36025. var data = seriesModel.getData();
  36026. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  36027. symbolDraw.incrementalPrepareUpdate(data);
  36028. this._finished = false;
  36029. },
  36030. incrementalRender: function (taskParams, seriesModel, ecModel) {
  36031. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  36032. this._finished = taskParams.end === seriesModel.getData().count();
  36033. },
  36034. updateTransform: function (seriesModel, ecModel, api) {
  36035. var data = seriesModel.getData();
  36036. // Must mark group dirty and make sure the incremental layer will be cleared
  36037. // PENDING
  36038. this.group.dirty();
  36039. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  36040. return {
  36041. update: true
  36042. };
  36043. }
  36044. else {
  36045. var res = pointsLayout().reset(seriesModel);
  36046. if (res.progress) {
  36047. res.progress({ start: 0, end: data.count() }, data);
  36048. }
  36049. this._symbolDraw.updateLayout(data);
  36050. }
  36051. },
  36052. _updateSymbolDraw: function (data, seriesModel) {
  36053. var symbolDraw = this._symbolDraw;
  36054. var pipelineContext = seriesModel.pipelineContext;
  36055. var isLargeDraw = pipelineContext.large;
  36056. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  36057. symbolDraw && symbolDraw.remove();
  36058. symbolDraw = this._symbolDraw = isLargeDraw
  36059. ? new LargeSymbolDraw()
  36060. : new SymbolDraw();
  36061. this._isLargeDraw = isLargeDraw;
  36062. this.group.removeAll();
  36063. }
  36064. this.group.add(symbolDraw.group);
  36065. return symbolDraw;
  36066. },
  36067. remove: function (ecModel, api) {
  36068. this._symbolDraw && this._symbolDraw.remove(true);
  36069. this._symbolDraw = null;
  36070. },
  36071. dispose: function () {}
  36072. });
  36073. /*
  36074. * Licensed to the Apache Software Foundation (ASF) under one
  36075. * or more contributor license agreements. See the NOTICE file
  36076. * distributed with this work for additional information
  36077. * regarding copyright ownership. The ASF licenses this file
  36078. * to you under the Apache License, Version 2.0 (the
  36079. * "License"); you may not use this file except in compliance
  36080. * with the License. You may obtain a copy of the License at
  36081. *
  36082. * http://www.apache.org/licenses/LICENSE-2.0
  36083. *
  36084. * Unless required by applicable law or agreed to in writing,
  36085. * software distributed under the License is distributed on an
  36086. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36087. * KIND, either express or implied. See the License for the
  36088. * specific language governing permissions and limitations
  36089. * under the License.
  36090. */
  36091. // import * as zrUtil from 'zrender/src/core/util';
  36092. // In case developer forget to include grid component
  36093. registerVisual(visualSymbol('scatter', 'circle'));
  36094. registerLayout(pointsLayout('scatter'));
  36095. // echarts.registerProcessor(function (ecModel, api) {
  36096. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  36097. // var data = seriesModel.getData();
  36098. // var coordSys = seriesModel.coordinateSystem;
  36099. // if (coordSys.type !== 'geo') {
  36100. // return;
  36101. // }
  36102. // var startPt = coordSys.pointToData([0, 0]);
  36103. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  36104. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  36105. // return data.mapDimension(dim);
  36106. // });
  36107. // var range = {};
  36108. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  36109. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  36110. // data.selectRange(range);
  36111. // });
  36112. // });
  36113. /*
  36114. * Licensed to the Apache Software Foundation (ASF) under one
  36115. * or more contributor license agreements. See the NOTICE file
  36116. * distributed with this work for additional information
  36117. * regarding copyright ownership. The ASF licenses this file
  36118. * to you under the Apache License, Version 2.0 (the
  36119. * "License"); you may not use this file except in compliance
  36120. * with the License. You may obtain a copy of the License at
  36121. *
  36122. * http://www.apache.org/licenses/LICENSE-2.0
  36123. *
  36124. * Unless required by applicable law or agreed to in writing,
  36125. * software distributed under the License is distributed on an
  36126. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36127. * KIND, either express or implied. See the License for the
  36128. * specific language governing permissions and limitations
  36129. * under the License.
  36130. */
  36131. function IndicatorAxis(dim, scale, radiusExtent) {
  36132. Axis.call(this, dim, scale, radiusExtent);
  36133. /**
  36134. * Axis type
  36135. * - 'category'
  36136. * - 'value'
  36137. * - 'time'
  36138. * - 'log'
  36139. * @type {string}
  36140. */
  36141. this.type = 'value';
  36142. this.angle = 0;
  36143. /**
  36144. * Indicator name
  36145. * @type {string}
  36146. */
  36147. this.name = '';
  36148. /**
  36149. * @type {module:echarts/model/Model}
  36150. */
  36151. this.model;
  36152. }
  36153. inherits(IndicatorAxis, Axis);
  36154. /*
  36155. * Licensed to the Apache Software Foundation (ASF) under one
  36156. * or more contributor license agreements. See the NOTICE file
  36157. * distributed with this work for additional information
  36158. * regarding copyright ownership. The ASF licenses this file
  36159. * to you under the Apache License, Version 2.0 (the
  36160. * "License"); you may not use this file except in compliance
  36161. * with the License. You may obtain a copy of the License at
  36162. *
  36163. * http://www.apache.org/licenses/LICENSE-2.0
  36164. *
  36165. * Unless required by applicable law or agreed to in writing,
  36166. * software distributed under the License is distributed on an
  36167. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36168. * KIND, either express or implied. See the License for the
  36169. * specific language governing permissions and limitations
  36170. * under the License.
  36171. */
  36172. // TODO clockwise
  36173. function Radar(radarModel, ecModel, api) {
  36174. this._model = radarModel;
  36175. /**
  36176. * Radar dimensions
  36177. * @type {Array.<string>}
  36178. */
  36179. this.dimensions = [];
  36180. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  36181. var dim = 'indicator_' + idx;
  36182. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  36183. indicatorAxis.name = indicatorModel.get('name');
  36184. // Inject model and axis
  36185. indicatorAxis.model = indicatorModel;
  36186. indicatorModel.axis = indicatorAxis;
  36187. this.dimensions.push(dim);
  36188. return indicatorAxis;
  36189. }, this);
  36190. this.resize(radarModel, api);
  36191. /**
  36192. * @type {number}
  36193. * @readOnly
  36194. */
  36195. this.cx;
  36196. /**
  36197. * @type {number}
  36198. * @readOnly
  36199. */
  36200. this.cy;
  36201. /**
  36202. * @type {number}
  36203. * @readOnly
  36204. */
  36205. this.r;
  36206. /**
  36207. * @type {number}
  36208. * @readOnly
  36209. */
  36210. this.startAngle;
  36211. }
  36212. Radar.prototype.getIndicatorAxes = function () {
  36213. return this._indicatorAxes;
  36214. };
  36215. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  36216. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  36217. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  36218. };
  36219. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  36220. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  36221. var angle = indicatorAxis.angle;
  36222. var x = this.cx + coord * Math.cos(angle);
  36223. var y = this.cy - coord * Math.sin(angle);
  36224. return [x, y];
  36225. };
  36226. Radar.prototype.pointToData = function (pt) {
  36227. var dx = pt[0] - this.cx;
  36228. var dy = pt[1] - this.cy;
  36229. var radius = Math.sqrt(dx * dx + dy * dy);
  36230. dx /= radius;
  36231. dy /= radius;
  36232. var radian = Math.atan2(-dy, dx);
  36233. // Find the closest angle
  36234. // FIXME index can calculated directly
  36235. var minRadianDiff = Infinity;
  36236. var closestAxis;
  36237. var closestAxisIdx = -1;
  36238. for (var i = 0; i < this._indicatorAxes.length; i++) {
  36239. var indicatorAxis = this._indicatorAxes[i];
  36240. var diff = Math.abs(radian - indicatorAxis.angle);
  36241. if (diff < minRadianDiff) {
  36242. closestAxis = indicatorAxis;
  36243. closestAxisIdx = i;
  36244. minRadianDiff = diff;
  36245. }
  36246. }
  36247. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  36248. };
  36249. Radar.prototype.resize = function (radarModel, api) {
  36250. var center = radarModel.get('center');
  36251. var viewWidth = api.getWidth();
  36252. var viewHeight = api.getHeight();
  36253. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  36254. this.cx = parsePercent$1(center[0], viewWidth);
  36255. this.cy = parsePercent$1(center[1], viewHeight);
  36256. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  36257. this.r = parsePercent$1(radarModel.get('radius'), viewSize);
  36258. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  36259. indicatorAxis.setExtent(0, this.r);
  36260. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  36261. // Normalize to [-PI, PI]
  36262. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  36263. indicatorAxis.angle = angle;
  36264. }, this);
  36265. };
  36266. Radar.prototype.update = function (ecModel, api) {
  36267. var indicatorAxes = this._indicatorAxes;
  36268. var radarModel = this._model;
  36269. each$1(indicatorAxes, function (indicatorAxis) {
  36270. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  36271. });
  36272. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  36273. if (radarSeries.get('coordinateSystem') !== 'radar'
  36274. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  36275. ) {
  36276. return;
  36277. }
  36278. var data = radarSeries.getData();
  36279. each$1(indicatorAxes, function (indicatorAxis) {
  36280. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  36281. });
  36282. }, this);
  36283. var splitNumber = radarModel.get('splitNumber');
  36284. function increaseInterval(interval) {
  36285. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  36286. // Increase interval
  36287. var f = interval / exp10;
  36288. if (f === 2) {
  36289. f = 5;
  36290. }
  36291. else { // f is 2 or 5
  36292. f *= 2;
  36293. }
  36294. return f * exp10;
  36295. }
  36296. // Force all the axis fixing the maxSplitNumber.
  36297. each$1(indicatorAxes, function (indicatorAxis, idx) {
  36298. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  36299. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  36300. var axisModel = indicatorAxis.model;
  36301. var scale = indicatorAxis.scale;
  36302. var fixedMin = axisModel.getMin();
  36303. var fixedMax = axisModel.getMax();
  36304. var interval = scale.getInterval();
  36305. if (fixedMin != null && fixedMax != null) {
  36306. // User set min, max, divide to get new interval
  36307. scale.setExtent(+fixedMin, +fixedMax);
  36308. scale.setInterval(
  36309. (fixedMax - fixedMin) / splitNumber
  36310. );
  36311. }
  36312. else if (fixedMin != null) {
  36313. var max;
  36314. // User set min, expand extent on the other side
  36315. do {
  36316. max = fixedMin + interval * splitNumber;
  36317. scale.setExtent(+fixedMin, max);
  36318. // Interval must been set after extent
  36319. // FIXME
  36320. scale.setInterval(interval);
  36321. interval = increaseInterval(interval);
  36322. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  36323. }
  36324. else if (fixedMax != null) {
  36325. var min;
  36326. // User set min, expand extent on the other side
  36327. do {
  36328. min = fixedMax - interval * splitNumber;
  36329. scale.setExtent(min, +fixedMax);
  36330. scale.setInterval(interval);
  36331. interval = increaseInterval(interval);
  36332. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  36333. }
  36334. else {
  36335. var nicedSplitNumber = scale.getTicks().length - 1;
  36336. if (nicedSplitNumber > splitNumber) {
  36337. interval = increaseInterval(interval);
  36338. }
  36339. // PENDING
  36340. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  36341. var halfSplitNumber = Math.round(splitNumber / 2);
  36342. scale.setExtent(
  36343. round$1(center - halfSplitNumber * interval),
  36344. round$1(center + (splitNumber - halfSplitNumber) * interval)
  36345. );
  36346. scale.setInterval(interval);
  36347. }
  36348. });
  36349. };
  36350. /**
  36351. * Radar dimensions is based on the data
  36352. * @type {Array}
  36353. */
  36354. Radar.dimensions = [];
  36355. Radar.create = function (ecModel, api) {
  36356. var radarList = [];
  36357. ecModel.eachComponent('radar', function (radarModel) {
  36358. var radar = new Radar(radarModel, ecModel, api);
  36359. radarList.push(radar);
  36360. radarModel.coordinateSystem = radar;
  36361. });
  36362. ecModel.eachSeriesByType('radar', function (radarSeries) {
  36363. if (radarSeries.get('coordinateSystem') === 'radar') {
  36364. // Inject coordinate system
  36365. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  36366. }
  36367. });
  36368. return radarList;
  36369. };
  36370. CoordinateSystemManager.register('radar', Radar);
  36371. /*
  36372. * Licensed to the Apache Software Foundation (ASF) under one
  36373. * or more contributor license agreements. See the NOTICE file
  36374. * distributed with this work for additional information
  36375. * regarding copyright ownership. The ASF licenses this file
  36376. * to you under the Apache License, Version 2.0 (the
  36377. * "License"); you may not use this file except in compliance
  36378. * with the License. You may obtain a copy of the License at
  36379. *
  36380. * http://www.apache.org/licenses/LICENSE-2.0
  36381. *
  36382. * Unless required by applicable law or agreed to in writing,
  36383. * software distributed under the License is distributed on an
  36384. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36385. * KIND, either express or implied. See the License for the
  36386. * specific language governing permissions and limitations
  36387. * under the License.
  36388. */
  36389. var valueAxisDefault = axisDefault.valueAxis;
  36390. function defaultsShow(opt, show) {
  36391. return defaults({
  36392. show: show
  36393. }, opt);
  36394. }
  36395. var RadarModel = extendComponentModel({
  36396. type: 'radar',
  36397. optionUpdated: function () {
  36398. var boundaryGap = this.get('boundaryGap');
  36399. var splitNumber = this.get('splitNumber');
  36400. var scale = this.get('scale');
  36401. var axisLine = this.get('axisLine');
  36402. var axisTick = this.get('axisTick');
  36403. var axisLabel = this.get('axisLabel');
  36404. var nameTextStyle = this.get('name');
  36405. var showName = this.get('name.show');
  36406. var nameFormatter = this.get('name.formatter');
  36407. var nameGap = this.get('nameGap');
  36408. var triggerEvent = this.get('triggerEvent');
  36409. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  36410. // PENDING
  36411. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  36412. indicatorOpt.min = 0;
  36413. }
  36414. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  36415. indicatorOpt.max = 0;
  36416. }
  36417. var iNameTextStyle = nameTextStyle;
  36418. if(indicatorOpt.color != null) {
  36419. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  36420. }
  36421. // Use same configuration
  36422. indicatorOpt = merge(clone(indicatorOpt), {
  36423. boundaryGap: boundaryGap,
  36424. splitNumber: splitNumber,
  36425. scale: scale,
  36426. axisLine: axisLine,
  36427. axisTick: axisTick,
  36428. axisLabel: axisLabel,
  36429. // Competitable with 2 and use text
  36430. name: indicatorOpt.text,
  36431. nameLocation: 'end',
  36432. nameGap: nameGap,
  36433. // min: 0,
  36434. nameTextStyle: iNameTextStyle,
  36435. triggerEvent: triggerEvent
  36436. }, false);
  36437. if (!showName) {
  36438. indicatorOpt.name = '';
  36439. }
  36440. if (typeof nameFormatter === 'string') {
  36441. var indName = indicatorOpt.name;
  36442. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  36443. }
  36444. else if (typeof nameFormatter === 'function') {
  36445. indicatorOpt.name = nameFormatter(
  36446. indicatorOpt.name, indicatorOpt
  36447. );
  36448. }
  36449. var model = extend(
  36450. new Model(indicatorOpt, null, this.ecModel),
  36451. axisModelCommonMixin
  36452. );
  36453. // For triggerEvent.
  36454. model.mainType = 'radar';
  36455. model.componentIndex = this.componentIndex;
  36456. return model;
  36457. }, this);
  36458. this.getIndicatorModels = function () {
  36459. return indicatorModels;
  36460. };
  36461. },
  36462. defaultOption: {
  36463. zlevel: 0,
  36464. z: 0,
  36465. center: ['50%', '50%'],
  36466. radius: '75%',
  36467. startAngle: 90,
  36468. name: {
  36469. show: true
  36470. // formatter: null
  36471. // textStyle: {}
  36472. },
  36473. boundaryGap: [0, 0],
  36474. splitNumber: 5,
  36475. nameGap: 15,
  36476. scale: false,
  36477. // Polygon or circle
  36478. shape: 'polygon',
  36479. axisLine: merge(
  36480. {
  36481. lineStyle: {
  36482. color: '#bbb'
  36483. }
  36484. },
  36485. valueAxisDefault.axisLine
  36486. ),
  36487. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  36488. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  36489. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  36490. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  36491. // {text, min, max}
  36492. indicator: []
  36493. }
  36494. });
  36495. /*
  36496. * Licensed to the Apache Software Foundation (ASF) under one
  36497. * or more contributor license agreements. See the NOTICE file
  36498. * distributed with this work for additional information
  36499. * regarding copyright ownership. The ASF licenses this file
  36500. * to you under the Apache License, Version 2.0 (the
  36501. * "License"); you may not use this file except in compliance
  36502. * with the License. You may obtain a copy of the License at
  36503. *
  36504. * http://www.apache.org/licenses/LICENSE-2.0
  36505. *
  36506. * Unless required by applicable law or agreed to in writing,
  36507. * software distributed under the License is distributed on an
  36508. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36509. * KIND, either express or implied. See the License for the
  36510. * specific language governing permissions and limitations
  36511. * under the License.
  36512. */
  36513. var axisBuilderAttrs$1 = [
  36514. 'axisLine', 'axisTickLabel', 'axisName'
  36515. ];
  36516. extendComponentView({
  36517. type: 'radar',
  36518. render: function (radarModel, ecModel, api) {
  36519. var group = this.group;
  36520. group.removeAll();
  36521. this._buildAxes(radarModel);
  36522. this._buildSplitLineAndArea(radarModel);
  36523. },
  36524. _buildAxes: function (radarModel) {
  36525. var radar = radarModel.coordinateSystem;
  36526. var indicatorAxes = radar.getIndicatorAxes();
  36527. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  36528. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  36529. position: [radar.cx, radar.cy],
  36530. rotation: indicatorAxis.angle,
  36531. labelDirection: -1,
  36532. tickDirection: -1,
  36533. nameDirection: 1
  36534. });
  36535. return axisBuilder;
  36536. });
  36537. each$1(axisBuilders, function (axisBuilder) {
  36538. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  36539. this.group.add(axisBuilder.getGroup());
  36540. }, this);
  36541. },
  36542. _buildSplitLineAndArea: function (radarModel) {
  36543. var radar = radarModel.coordinateSystem;
  36544. var indicatorAxes = radar.getIndicatorAxes();
  36545. if (!indicatorAxes.length) {
  36546. return;
  36547. }
  36548. var shape = radarModel.get('shape');
  36549. var splitLineModel = radarModel.getModel('splitLine');
  36550. var splitAreaModel = radarModel.getModel('splitArea');
  36551. var lineStyleModel = splitLineModel.getModel('lineStyle');
  36552. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  36553. var showSplitLine = splitLineModel.get('show');
  36554. var showSplitArea = splitAreaModel.get('show');
  36555. var splitLineColors = lineStyleModel.get('color');
  36556. var splitAreaColors = areaStyleModel.get('color');
  36557. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  36558. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  36559. var splitLines = [];
  36560. var splitAreas = [];
  36561. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  36562. var colorIndex = idx % areaOrLineColorList.length;
  36563. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  36564. return colorIndex;
  36565. }
  36566. if (shape === 'circle') {
  36567. var ticksRadius = indicatorAxes[0].getTicksCoords();
  36568. var cx = radar.cx;
  36569. var cy = radar.cy;
  36570. for (var i = 0; i < ticksRadius.length; i++) {
  36571. if (showSplitLine) {
  36572. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  36573. splitLines[colorIndex].push(new Circle({
  36574. shape: {
  36575. cx: cx,
  36576. cy: cy,
  36577. r: ticksRadius[i].coord
  36578. }
  36579. }));
  36580. }
  36581. if (showSplitArea && i < ticksRadius.length - 1) {
  36582. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  36583. splitAreas[colorIndex].push(new Ring({
  36584. shape: {
  36585. cx: cx,
  36586. cy: cy,
  36587. r0: ticksRadius[i].coord,
  36588. r: ticksRadius[i + 1].coord
  36589. }
  36590. }));
  36591. }
  36592. }
  36593. }
  36594. // Polyyon
  36595. else {
  36596. var realSplitNumber;
  36597. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  36598. var ticksCoords = indicatorAxis.getTicksCoords();
  36599. realSplitNumber = realSplitNumber == null
  36600. ? ticksCoords.length - 1
  36601. : Math.min(ticksCoords.length - 1, realSplitNumber);
  36602. return map(ticksCoords, function (tickCoord) {
  36603. return radar.coordToPoint(tickCoord.coord, idx);
  36604. });
  36605. });
  36606. var prevPoints = [];
  36607. for (var i = 0; i <= realSplitNumber; i++) {
  36608. var points = [];
  36609. for (var j = 0; j < indicatorAxes.length; j++) {
  36610. points.push(axesTicksPoints[j][i]);
  36611. }
  36612. // Close
  36613. if (points[0]) {
  36614. points.push(points[0].slice());
  36615. }
  36616. else {
  36617. if (__DEV__) {
  36618. console.error('Can\'t draw value axis ' + i);
  36619. }
  36620. }
  36621. if (showSplitLine) {
  36622. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  36623. splitLines[colorIndex].push(new Polyline({
  36624. shape: {
  36625. points: points
  36626. }
  36627. }));
  36628. }
  36629. if (showSplitArea && prevPoints) {
  36630. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  36631. splitAreas[colorIndex].push(new Polygon({
  36632. shape: {
  36633. points: points.concat(prevPoints)
  36634. }
  36635. }));
  36636. }
  36637. prevPoints = points.slice().reverse();
  36638. }
  36639. }
  36640. var lineStyle = lineStyleModel.getLineStyle();
  36641. var areaStyle = areaStyleModel.getAreaStyle();
  36642. // Add splitArea before splitLine
  36643. each$1(splitAreas, function (splitAreas, idx) {
  36644. this.group.add(mergePath(
  36645. splitAreas, {
  36646. style: defaults({
  36647. stroke: 'none',
  36648. fill: splitAreaColors[idx % splitAreaColors.length]
  36649. }, areaStyle),
  36650. silent: true
  36651. }
  36652. ));
  36653. }, this);
  36654. each$1(splitLines, function (splitLines, idx) {
  36655. this.group.add(mergePath(
  36656. splitLines, {
  36657. style: defaults({
  36658. fill: 'none',
  36659. stroke: splitLineColors[idx % splitLineColors.length]
  36660. }, lineStyle),
  36661. silent: true
  36662. }
  36663. ));
  36664. }, this);
  36665. }
  36666. });
  36667. /*
  36668. * Licensed to the Apache Software Foundation (ASF) under one
  36669. * or more contributor license agreements. See the NOTICE file
  36670. * distributed with this work for additional information
  36671. * regarding copyright ownership. The ASF licenses this file
  36672. * to you under the Apache License, Version 2.0 (the
  36673. * "License"); you may not use this file except in compliance
  36674. * with the License. You may obtain a copy of the License at
  36675. *
  36676. * http://www.apache.org/licenses/LICENSE-2.0
  36677. *
  36678. * Unless required by applicable law or agreed to in writing,
  36679. * software distributed under the License is distributed on an
  36680. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36681. * KIND, either express or implied. See the License for the
  36682. * specific language governing permissions and limitations
  36683. * under the License.
  36684. */
  36685. /*
  36686. * Licensed to the Apache Software Foundation (ASF) under one
  36687. * or more contributor license agreements. See the NOTICE file
  36688. * distributed with this work for additional information
  36689. * regarding copyright ownership. The ASF licenses this file
  36690. * to you under the Apache License, Version 2.0 (the
  36691. * "License"); you may not use this file except in compliance
  36692. * with the License. You may obtain a copy of the License at
  36693. *
  36694. * http://www.apache.org/licenses/LICENSE-2.0
  36695. *
  36696. * Unless required by applicable law or agreed to in writing,
  36697. * software distributed under the License is distributed on an
  36698. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36699. * KIND, either express or implied. See the License for the
  36700. * specific language governing permissions and limitations
  36701. * under the License.
  36702. */
  36703. var RadarSeries = SeriesModel.extend({
  36704. type: 'series.radar',
  36705. dependencies: ['radar'],
  36706. // Overwrite
  36707. init: function (option) {
  36708. RadarSeries.superApply(this, 'init', arguments);
  36709. // Enable legend selection for each data item
  36710. // Use a function instead of direct access because data reference may changed
  36711. this.legendDataProvider = function () {
  36712. return this.getRawData();
  36713. };
  36714. },
  36715. getInitialData: function (option, ecModel) {
  36716. return createListSimply(this, {
  36717. generateCoord: 'indicator_',
  36718. generateCoordCount: Infinity
  36719. });
  36720. },
  36721. formatTooltip: function (dataIndex) {
  36722. var data = this.getData();
  36723. var coordSys = this.coordinateSystem;
  36724. var indicatorAxes = coordSys.getIndicatorAxes();
  36725. var name = this.getData().getName(dataIndex);
  36726. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  36727. + map(indicatorAxes, function (axis, idx) {
  36728. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  36729. return encodeHTML(axis.name + ' : ' + val);
  36730. }).join('<br />');
  36731. },
  36732. defaultOption: {
  36733. zlevel: 0,
  36734. z: 2,
  36735. coordinateSystem: 'radar',
  36736. legendHoverLink: true,
  36737. radarIndex: 0,
  36738. lineStyle: {
  36739. width: 2,
  36740. type: 'solid'
  36741. },
  36742. label: {
  36743. position: 'top'
  36744. },
  36745. // areaStyle: {
  36746. // },
  36747. // itemStyle: {}
  36748. symbol: 'emptyCircle',
  36749. symbolSize: 4
  36750. // symbolRotate: null
  36751. }
  36752. });
  36753. /*
  36754. * Licensed to the Apache Software Foundation (ASF) under one
  36755. * or more contributor license agreements. See the NOTICE file
  36756. * distributed with this work for additional information
  36757. * regarding copyright ownership. The ASF licenses this file
  36758. * to you under the Apache License, Version 2.0 (the
  36759. * "License"); you may not use this file except in compliance
  36760. * with the License. You may obtain a copy of the License at
  36761. *
  36762. * http://www.apache.org/licenses/LICENSE-2.0
  36763. *
  36764. * Unless required by applicable law or agreed to in writing,
  36765. * software distributed under the License is distributed on an
  36766. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36767. * KIND, either express or implied. See the License for the
  36768. * specific language governing permissions and limitations
  36769. * under the License.
  36770. */
  36771. function normalizeSymbolSize(symbolSize) {
  36772. if (!isArray(symbolSize)) {
  36773. symbolSize = [+symbolSize, +symbolSize];
  36774. }
  36775. return symbolSize;
  36776. }
  36777. extendChartView({
  36778. type: 'radar',
  36779. render: function (seriesModel, ecModel, api) {
  36780. var polar = seriesModel.coordinateSystem;
  36781. var group = this.group;
  36782. var data = seriesModel.getData();
  36783. var oldData = this._data;
  36784. function createSymbol$$1(data, idx) {
  36785. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  36786. var color = data.getItemVisual(idx, 'color');
  36787. if (symbolType === 'none') {
  36788. return;
  36789. }
  36790. var symbolSize = normalizeSymbolSize(
  36791. data.getItemVisual(idx, 'symbolSize')
  36792. );
  36793. var symbolPath = createSymbol(
  36794. symbolType, -1, -1, 2, 2, color
  36795. );
  36796. symbolPath.attr({
  36797. style: {
  36798. strokeNoScale: true
  36799. },
  36800. z2: 100,
  36801. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  36802. });
  36803. return symbolPath;
  36804. }
  36805. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  36806. // Simply rerender all
  36807. symbolGroup.removeAll();
  36808. for (var i = 0; i < newPoints.length - 1; i++) {
  36809. var symbolPath = createSymbol$$1(data, idx);
  36810. if (symbolPath) {
  36811. symbolPath.__dimIdx = i;
  36812. if (oldPoints[i]) {
  36813. symbolPath.attr('position', oldPoints[i]);
  36814. graphic[isInit ? 'initProps' : 'updateProps'](
  36815. symbolPath, {
  36816. position: newPoints[i]
  36817. }, seriesModel, idx
  36818. );
  36819. }
  36820. else {
  36821. symbolPath.attr('position', newPoints[i]);
  36822. }
  36823. symbolGroup.add(symbolPath);
  36824. }
  36825. }
  36826. }
  36827. function getInitialPoints(points) {
  36828. return map(points, function (pt) {
  36829. return [polar.cx, polar.cy];
  36830. });
  36831. }
  36832. data.diff(oldData)
  36833. .add(function (idx) {
  36834. var points = data.getItemLayout(idx);
  36835. if (!points) {
  36836. return;
  36837. }
  36838. var polygon = new Polygon();
  36839. var polyline = new Polyline();
  36840. var target = {
  36841. shape: {
  36842. points: points
  36843. }
  36844. };
  36845. polygon.shape.points = getInitialPoints(points);
  36846. polyline.shape.points = getInitialPoints(points);
  36847. initProps(polygon, target, seriesModel, idx);
  36848. initProps(polyline, target, seriesModel, idx);
  36849. var itemGroup = new Group();
  36850. var symbolGroup = new Group();
  36851. itemGroup.add(polyline);
  36852. itemGroup.add(polygon);
  36853. itemGroup.add(symbolGroup);
  36854. updateSymbols(
  36855. polyline.shape.points, points, symbolGroup, data, idx, true
  36856. );
  36857. data.setItemGraphicEl(idx, itemGroup);
  36858. })
  36859. .update(function (newIdx, oldIdx) {
  36860. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  36861. var polyline = itemGroup.childAt(0);
  36862. var polygon = itemGroup.childAt(1);
  36863. var symbolGroup = itemGroup.childAt(2);
  36864. var target = {
  36865. shape: {
  36866. points: data.getItemLayout(newIdx)
  36867. }
  36868. };
  36869. if (!target.shape.points) {
  36870. return;
  36871. }
  36872. updateSymbols(
  36873. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  36874. );
  36875. updateProps(polyline, target, seriesModel);
  36876. updateProps(polygon, target, seriesModel);
  36877. data.setItemGraphicEl(newIdx, itemGroup);
  36878. })
  36879. .remove(function (idx) {
  36880. group.remove(oldData.getItemGraphicEl(idx));
  36881. })
  36882. .execute();
  36883. data.eachItemGraphicEl(function (itemGroup, idx) {
  36884. var itemModel = data.getItemModel(idx);
  36885. var polyline = itemGroup.childAt(0);
  36886. var polygon = itemGroup.childAt(1);
  36887. var symbolGroup = itemGroup.childAt(2);
  36888. var color = data.getItemVisual(idx, 'color');
  36889. group.add(itemGroup);
  36890. polyline.useStyle(
  36891. defaults(
  36892. itemModel.getModel('lineStyle').getLineStyle(),
  36893. {
  36894. fill: 'none',
  36895. stroke: color
  36896. }
  36897. )
  36898. );
  36899. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  36900. var areaStyleModel = itemModel.getModel('areaStyle');
  36901. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  36902. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  36903. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  36904. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  36905. polygon.ignore = polygonIgnore;
  36906. polygon.useStyle(
  36907. defaults(
  36908. areaStyleModel.getAreaStyle(),
  36909. {
  36910. fill: color,
  36911. opacity: 0.7
  36912. }
  36913. )
  36914. );
  36915. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  36916. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  36917. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36918. var labelModel = itemModel.getModel('label');
  36919. var labelHoverModel = itemModel.getModel('emphasis.label');
  36920. symbolGroup.eachChild(function (symbolPath) {
  36921. symbolPath.setStyle(itemStyle);
  36922. symbolPath.hoverStyle = clone(itemHoverStyle);
  36923. setLabelStyle(
  36924. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  36925. {
  36926. labelFetcher: data.hostModel,
  36927. labelDataIndex: idx,
  36928. labelDimIndex: symbolPath.__dimIdx,
  36929. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  36930. autoColor: color,
  36931. isRectText: true
  36932. }
  36933. );
  36934. });
  36935. function onEmphasis() {
  36936. polygon.attr('ignore', hoverPolygonIgnore);
  36937. }
  36938. function onNormal() {
  36939. polygon.attr('ignore', polygonIgnore);
  36940. }
  36941. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  36942. itemGroup.on('emphasis', onEmphasis)
  36943. .on('mouseover', onEmphasis)
  36944. .on('normal', onNormal)
  36945. .on('mouseout', onNormal);
  36946. setHoverStyle(itemGroup);
  36947. });
  36948. this._data = data;
  36949. },
  36950. remove: function () {
  36951. this.group.removeAll();
  36952. this._data = null;
  36953. },
  36954. dispose: function () {}
  36955. });
  36956. /*
  36957. * Licensed to the Apache Software Foundation (ASF) under one
  36958. * or more contributor license agreements. See the NOTICE file
  36959. * distributed with this work for additional information
  36960. * regarding copyright ownership. The ASF licenses this file
  36961. * to you under the Apache License, Version 2.0 (the
  36962. * "License"); you may not use this file except in compliance
  36963. * with the License. You may obtain a copy of the License at
  36964. *
  36965. * http://www.apache.org/licenses/LICENSE-2.0
  36966. *
  36967. * Unless required by applicable law or agreed to in writing,
  36968. * software distributed under the License is distributed on an
  36969. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36970. * KIND, either express or implied. See the License for the
  36971. * specific language governing permissions and limitations
  36972. * under the License.
  36973. */
  36974. var radarLayout = function (ecModel) {
  36975. ecModel.eachSeriesByType('radar', function (seriesModel) {
  36976. var data = seriesModel.getData();
  36977. var points = [];
  36978. var coordSys = seriesModel.coordinateSystem;
  36979. if (!coordSys) {
  36980. return;
  36981. }
  36982. function pointsConverter(val, idx) {
  36983. points[idx] = points[idx] || [];
  36984. points[idx][i] = coordSys.dataToPoint(val, i);
  36985. }
  36986. var axes = coordSys.getIndicatorAxes();
  36987. for (var i = 0; i < axes.length; i++) {
  36988. data.each(data.mapDimension(axes[i].dim), pointsConverter);
  36989. }
  36990. data.each(function (idx) {
  36991. // Close polygon
  36992. points[idx][0] && points[idx].push(points[idx][0].slice());
  36993. data.setItemLayout(idx, points[idx]);
  36994. });
  36995. });
  36996. };
  36997. /*
  36998. * Licensed to the Apache Software Foundation (ASF) under one
  36999. * or more contributor license agreements. See the NOTICE file
  37000. * distributed with this work for additional information
  37001. * regarding copyright ownership. The ASF licenses this file
  37002. * to you under the Apache License, Version 2.0 (the
  37003. * "License"); you may not use this file except in compliance
  37004. * with the License. You may obtain a copy of the License at
  37005. *
  37006. * http://www.apache.org/licenses/LICENSE-2.0
  37007. *
  37008. * Unless required by applicable law or agreed to in writing,
  37009. * software distributed under the License is distributed on an
  37010. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37011. * KIND, either express or implied. See the License for the
  37012. * specific language governing permissions and limitations
  37013. * under the License.
  37014. */
  37015. // Backward compat for radar chart in 2
  37016. var backwardCompat$1 = function (option) {
  37017. var polarOptArr = option.polar;
  37018. if (polarOptArr) {
  37019. if (!isArray(polarOptArr)) {
  37020. polarOptArr = [polarOptArr];
  37021. }
  37022. var polarNotRadar = [];
  37023. each$1(polarOptArr, function (polarOpt, idx) {
  37024. if (polarOpt.indicator) {
  37025. if (polarOpt.type && !polarOpt.shape) {
  37026. polarOpt.shape = polarOpt.type;
  37027. }
  37028. option.radar = option.radar || [];
  37029. if (!isArray(option.radar)) {
  37030. option.radar = [option.radar];
  37031. }
  37032. option.radar.push(polarOpt);
  37033. }
  37034. else {
  37035. polarNotRadar.push(polarOpt);
  37036. }
  37037. });
  37038. option.polar = polarNotRadar;
  37039. }
  37040. each$1(option.series, function (seriesOpt) {
  37041. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  37042. seriesOpt.radarIndex = seriesOpt.polarIndex;
  37043. }
  37044. });
  37045. };
  37046. /*
  37047. * Licensed to the Apache Software Foundation (ASF) under one
  37048. * or more contributor license agreements. See the NOTICE file
  37049. * distributed with this work for additional information
  37050. * regarding copyright ownership. The ASF licenses this file
  37051. * to you under the Apache License, Version 2.0 (the
  37052. * "License"); you may not use this file except in compliance
  37053. * with the License. You may obtain a copy of the License at
  37054. *
  37055. * http://www.apache.org/licenses/LICENSE-2.0
  37056. *
  37057. * Unless required by applicable law or agreed to in writing,
  37058. * software distributed under the License is distributed on an
  37059. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37060. * KIND, either express or implied. See the License for the
  37061. * specific language governing permissions and limitations
  37062. * under the License.
  37063. */
  37064. // Must use radar component
  37065. registerVisual(dataColor('radar'));
  37066. registerVisual(visualSymbol('radar', 'circle'));
  37067. registerLayout(radarLayout);
  37068. registerProcessor(dataFilter('radar'));
  37069. registerPreprocessor(backwardCompat$1);
  37070. /*
  37071. * Licensed to the Apache Software Foundation (ASF) under one
  37072. * or more contributor license agreements. See the NOTICE file
  37073. * distributed with this work for additional information
  37074. * regarding copyright ownership. The ASF licenses this file
  37075. * to you under the Apache License, Version 2.0 (the
  37076. * "License"); you may not use this file except in compliance
  37077. * with the License. You may obtain a copy of the License at
  37078. *
  37079. * http://www.apache.org/licenses/LICENSE-2.0
  37080. *
  37081. * Unless required by applicable law or agreed to in writing,
  37082. * software distributed under the License is distributed on an
  37083. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37084. * KIND, either express or implied. See the License for the
  37085. * specific language governing permissions and limitations
  37086. * under the License.
  37087. */
  37088. /**
  37089. * Simple view coordinate system
  37090. * Mapping given x, y to transformd view x, y
  37091. */
  37092. var v2ApplyTransform$1 = applyTransform;
  37093. // Dummy transform node
  37094. function TransformDummy() {
  37095. Transformable.call(this);
  37096. }
  37097. mixin(TransformDummy, Transformable);
  37098. function View(name) {
  37099. /**
  37100. * @type {string}
  37101. */
  37102. this.name = name;
  37103. /**
  37104. * @type {Object}
  37105. */
  37106. this.zoomLimit;
  37107. Transformable.call(this);
  37108. this._roamTransformable = new TransformDummy();
  37109. this._rawTransformable = new TransformDummy();
  37110. this._center;
  37111. this._zoom;
  37112. }
  37113. View.prototype = {
  37114. constructor: View,
  37115. type: 'view',
  37116. /**
  37117. * @param {Array.<string>}
  37118. * @readOnly
  37119. */
  37120. dimensions: ['x', 'y'],
  37121. /**
  37122. * Set bounding rect
  37123. * @param {number} x
  37124. * @param {number} y
  37125. * @param {number} width
  37126. * @param {number} height
  37127. */
  37128. // PENDING to getRect
  37129. setBoundingRect: function (x, y, width, height) {
  37130. this._rect = new BoundingRect(x, y, width, height);
  37131. return this._rect;
  37132. },
  37133. /**
  37134. * @return {module:zrender/core/BoundingRect}
  37135. */
  37136. // PENDING to getRect
  37137. getBoundingRect: function () {
  37138. return this._rect;
  37139. },
  37140. /**
  37141. * @param {number} x
  37142. * @param {number} y
  37143. * @param {number} width
  37144. * @param {number} height
  37145. */
  37146. setViewRect: function (x, y, width, height) {
  37147. this.transformTo(x, y, width, height);
  37148. this._viewRect = new BoundingRect(x, y, width, height);
  37149. },
  37150. /**
  37151. * Transformed to particular position and size
  37152. * @param {number} x
  37153. * @param {number} y
  37154. * @param {number} width
  37155. * @param {number} height
  37156. */
  37157. transformTo: function (x, y, width, height) {
  37158. var rect = this.getBoundingRect();
  37159. var rawTransform = this._rawTransformable;
  37160. rawTransform.transform = rect.calculateTransform(
  37161. new BoundingRect(x, y, width, height)
  37162. );
  37163. rawTransform.decomposeTransform();
  37164. this._updateTransform();
  37165. },
  37166. /**
  37167. * Set center of view
  37168. * @param {Array.<number>} [centerCoord]
  37169. */
  37170. setCenter: function (centerCoord) {
  37171. if (!centerCoord) {
  37172. return;
  37173. }
  37174. this._center = centerCoord;
  37175. this._updateCenterAndZoom();
  37176. },
  37177. /**
  37178. * @param {number} zoom
  37179. */
  37180. setZoom: function (zoom) {
  37181. zoom = zoom || 1;
  37182. var zoomLimit = this.zoomLimit;
  37183. if (zoomLimit) {
  37184. if (zoomLimit.max != null) {
  37185. zoom = Math.min(zoomLimit.max, zoom);
  37186. }
  37187. if (zoomLimit.min != null) {
  37188. zoom = Math.max(zoomLimit.min, zoom);
  37189. }
  37190. }
  37191. this._zoom = zoom;
  37192. this._updateCenterAndZoom();
  37193. },
  37194. /**
  37195. * Get default center without roam
  37196. */
  37197. getDefaultCenter: function () {
  37198. // Rect before any transform
  37199. var rawRect = this.getBoundingRect();
  37200. var cx = rawRect.x + rawRect.width / 2;
  37201. var cy = rawRect.y + rawRect.height / 2;
  37202. return [cx, cy];
  37203. },
  37204. getCenter: function () {
  37205. return this._center || this.getDefaultCenter();
  37206. },
  37207. getZoom: function () {
  37208. return this._zoom || 1;
  37209. },
  37210. /**
  37211. * @return {Array.<number}
  37212. */
  37213. getRoamTransform: function () {
  37214. return this._roamTransformable.getLocalTransform();
  37215. },
  37216. /**
  37217. * Remove roam
  37218. */
  37219. _updateCenterAndZoom: function () {
  37220. // Must update after view transform updated
  37221. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  37222. var roamTransform = this._roamTransformable;
  37223. var defaultCenter = this.getDefaultCenter();
  37224. var center = this.getCenter();
  37225. var zoom = this.getZoom();
  37226. center = applyTransform([], center, rawTransformMatrix);
  37227. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  37228. roamTransform.origin = center;
  37229. roamTransform.position = [
  37230. defaultCenter[0] - center[0],
  37231. defaultCenter[1] - center[1]
  37232. ];
  37233. roamTransform.scale = [zoom, zoom];
  37234. this._updateTransform();
  37235. },
  37236. /**
  37237. * Update transform from roam and mapLocation
  37238. * @private
  37239. */
  37240. _updateTransform: function () {
  37241. var roamTransformable = this._roamTransformable;
  37242. var rawTransformable = this._rawTransformable;
  37243. rawTransformable.parent = roamTransformable;
  37244. roamTransformable.updateTransform();
  37245. rawTransformable.updateTransform();
  37246. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  37247. this._rawTransform = rawTransformable.getLocalTransform();
  37248. this.invTransform = this.invTransform || [];
  37249. invert(this.invTransform, this.transform);
  37250. this.decomposeTransform();
  37251. },
  37252. /**
  37253. * @return {module:zrender/core/BoundingRect}
  37254. */
  37255. getViewRect: function () {
  37256. return this._viewRect;
  37257. },
  37258. /**
  37259. * Get view rect after roam transform
  37260. * @return {module:zrender/core/BoundingRect}
  37261. */
  37262. getViewRectAfterRoam: function () {
  37263. var rect = this.getBoundingRect().clone();
  37264. rect.applyTransform(this.transform);
  37265. return rect;
  37266. },
  37267. /**
  37268. * Convert a single (lon, lat) data item to (x, y) point.
  37269. * @param {Array.<number>} data
  37270. * @param {boolean} noRoam
  37271. * @param {Array.<number>} [out]
  37272. * @return {Array.<number>}
  37273. */
  37274. dataToPoint: function (data, noRoam, out) {
  37275. var transform = noRoam ? this._rawTransform : this.transform;
  37276. out = out || [];
  37277. return transform
  37278. ? v2ApplyTransform$1(out, data, transform)
  37279. : copy(out, data);
  37280. },
  37281. /**
  37282. * Convert a (x, y) point to (lon, lat) data
  37283. * @param {Array.<number>} point
  37284. * @return {Array.<number>}
  37285. */
  37286. pointToData: function (point) {
  37287. var invTransform = this.invTransform;
  37288. return invTransform
  37289. ? v2ApplyTransform$1([], point, invTransform)
  37290. : [point[0], point[1]];
  37291. },
  37292. /**
  37293. * @implements
  37294. * see {module:echarts/CoodinateSystem}
  37295. */
  37296. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  37297. /**
  37298. * @implements
  37299. * see {module:echarts/CoodinateSystem}
  37300. */
  37301. convertFromPixel: curry(doConvert$1, 'pointToData'),
  37302. /**
  37303. * @implements
  37304. * see {module:echarts/CoodinateSystem}
  37305. */
  37306. containPoint: function (point) {
  37307. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  37308. }
  37309. /**
  37310. * @return {number}
  37311. */
  37312. // getScalarScale: function () {
  37313. // // Use determinant square root of transform to mutiply scalar
  37314. // var m = this.transform;
  37315. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  37316. // return det;
  37317. // }
  37318. };
  37319. mixin(View, Transformable);
  37320. function doConvert$1(methodName, ecModel, finder, value) {
  37321. var seriesModel = finder.seriesModel;
  37322. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  37323. return coordSys === this ? coordSys[methodName](value) : null;
  37324. }
  37325. /*
  37326. * Licensed to the Apache Software Foundation (ASF) under one
  37327. * or more contributor license agreements. See the NOTICE file
  37328. * distributed with this work for additional information
  37329. * regarding copyright ownership. The ASF licenses this file
  37330. * to you under the Apache License, Version 2.0 (the
  37331. * "License"); you may not use this file except in compliance
  37332. * with the License. You may obtain a copy of the License at
  37333. *
  37334. * http://www.apache.org/licenses/LICENSE-2.0
  37335. *
  37336. * Unless required by applicable law or agreed to in writing,
  37337. * software distributed under the License is distributed on an
  37338. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37339. * KIND, either express or implied. See the License for the
  37340. * specific language governing permissions and limitations
  37341. * under the License.
  37342. */
  37343. // Fix for 南海诸岛
  37344. var geoCoord = [126, 25];
  37345. var points$1 = [
  37346. [[0,3.5],[7,11.2],[15,11.9],[30,7],[42,0.7],[52,0.7],
  37347. [56,7.7],[59,0.7],[64,0.7],[64,0],[5,0],[0,3.5]],
  37348. [[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],
  37349. [[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],
  37350. [[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],
  37351. [[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],
  37352. [[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],
  37353. [[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],
  37354. [[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],
  37355. [[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],
  37356. [[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],
  37357. [[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],
  37358. [[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],
  37359. [1,92.4],[1,3.5],[0,3.5]]
  37360. ];
  37361. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  37362. for (var k = 0; k < points$1[i$1].length; k++) {
  37363. points$1[i$1][k][0] /= 10.5;
  37364. points$1[i$1][k][1] /= -10.5 / 0.75;
  37365. points$1[i$1][k][0] += geoCoord[0];
  37366. points$1[i$1][k][1] += geoCoord[1];
  37367. }
  37368. }
  37369. var fixNanhai = function (geo) {
  37370. if (geo.map === 'china') {
  37371. geo.regions.push(new Region(
  37372. '南海诸岛',
  37373. map(points$1, function (exterior) {
  37374. return {
  37375. type: 'polygon',
  37376. exterior: exterior
  37377. };
  37378. }), geoCoord
  37379. ));
  37380. }
  37381. };
  37382. /*
  37383. * Licensed to the Apache Software Foundation (ASF) under one
  37384. * or more contributor license agreements. See the NOTICE file
  37385. * distributed with this work for additional information
  37386. * regarding copyright ownership. The ASF licenses this file
  37387. * to you under the Apache License, Version 2.0 (the
  37388. * "License"); you may not use this file except in compliance
  37389. * with the License. You may obtain a copy of the License at
  37390. *
  37391. * http://www.apache.org/licenses/LICENSE-2.0
  37392. *
  37393. * Unless required by applicable law or agreed to in writing,
  37394. * software distributed under the License is distributed on an
  37395. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37396. * KIND, either express or implied. See the License for the
  37397. * specific language governing permissions and limitations
  37398. * under the License.
  37399. */
  37400. var coordsOffsetMap = {
  37401. '南海诸岛' : [32, 80],
  37402. // 全国
  37403. '广东': [0, -10],
  37404. '香港': [10, 5],
  37405. '澳门': [-10, 10],
  37406. //'北京': [-10, 0],
  37407. '天津': [5, 5]
  37408. };
  37409. var fixTextCoord = function (geo) {
  37410. each$1(geo.regions, function (region) {
  37411. var coordFix = coordsOffsetMap[region.name];
  37412. if (coordFix) {
  37413. var cp = region.center;
  37414. cp[0] += coordFix[0] / 10.5;
  37415. cp[1] += -coordFix[1] / (10.5 / 0.75);
  37416. }
  37417. });
  37418. };
  37419. /*
  37420. * Licensed to the Apache Software Foundation (ASF) under one
  37421. * or more contributor license agreements. See the NOTICE file
  37422. * distributed with this work for additional information
  37423. * regarding copyright ownership. The ASF licenses this file
  37424. * to you under the Apache License, Version 2.0 (the
  37425. * "License"); you may not use this file except in compliance
  37426. * with the License. You may obtain a copy of the License at
  37427. *
  37428. * http://www.apache.org/licenses/LICENSE-2.0
  37429. *
  37430. * Unless required by applicable law or agreed to in writing,
  37431. * software distributed under the License is distributed on an
  37432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37433. * KIND, either express or implied. See the License for the
  37434. * specific language governing permissions and limitations
  37435. * under the License.
  37436. */
  37437. var geoCoordMap = {
  37438. 'Russia': [100, 60],
  37439. 'United States': [-99, 38],
  37440. 'United States of America': [-99, 38]
  37441. };
  37442. var fixGeoCoord = function (geo) {
  37443. each$1(geo.regions, function (region) {
  37444. var geoCoord = geoCoordMap[region.name];
  37445. if (geoCoord) {
  37446. var cp = region.center;
  37447. cp[0] = geoCoord[0];
  37448. cp[1] = geoCoord[1];
  37449. }
  37450. });
  37451. };
  37452. /*
  37453. * Licensed to the Apache Software Foundation (ASF) under one
  37454. * or more contributor license agreements. See the NOTICE file
  37455. * distributed with this work for additional information
  37456. * regarding copyright ownership. The ASF licenses this file
  37457. * to you under the Apache License, Version 2.0 (the
  37458. * "License"); you may not use this file except in compliance
  37459. * with the License. You may obtain a copy of the License at
  37460. *
  37461. * http://www.apache.org/licenses/LICENSE-2.0
  37462. *
  37463. * Unless required by applicable law or agreed to in writing,
  37464. * software distributed under the License is distributed on an
  37465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37466. * KIND, either express or implied. See the License for the
  37467. * specific language governing permissions and limitations
  37468. * under the License.
  37469. */
  37470. // Fix for 钓鱼岛
  37471. // var Region = require('../Region');
  37472. // var zrUtil = require('zrender/src/core/util');
  37473. // var geoCoord = [126, 25];
  37474. var points$2 = [
  37475. [
  37476. [123.45165252685547, 25.73527164402261],
  37477. [123.49731445312499, 25.73527164402261],
  37478. [123.49731445312499, 25.750734064600884],
  37479. [123.45165252685547, 25.750734064600884],
  37480. [123.45165252685547, 25.73527164402261]
  37481. ]
  37482. ];
  37483. var fixDiaoyuIsland = function (geo) {
  37484. if (geo.map === 'china') {
  37485. for (var i = 0, len = geo.regions.length; i < len; ++i) {
  37486. if (geo.regions[i].name === '台湾') {
  37487. geo.regions[i].geometries.push({
  37488. type: 'polygon',
  37489. exterior: points$2[0]
  37490. });
  37491. }
  37492. }
  37493. }
  37494. };
  37495. /*
  37496. * Licensed to the Apache Software Foundation (ASF) under one
  37497. * or more contributor license agreements. See the NOTICE file
  37498. * distributed with this work for additional information
  37499. * regarding copyright ownership. The ASF licenses this file
  37500. * to you under the Apache License, Version 2.0 (the
  37501. * "License"); you may not use this file except in compliance
  37502. * with the License. You may obtain a copy of the License at
  37503. *
  37504. * http://www.apache.org/licenses/LICENSE-2.0
  37505. *
  37506. * Unless required by applicable law or agreed to in writing,
  37507. * software distributed under the License is distributed on an
  37508. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37509. * KIND, either express or implied. See the License for the
  37510. * specific language governing permissions and limitations
  37511. * under the License.
  37512. */
  37513. // Geo fix functions
  37514. var geoFixFuncs = [
  37515. fixNanhai,
  37516. fixTextCoord,
  37517. fixGeoCoord,
  37518. fixDiaoyuIsland
  37519. ];
  37520. /**
  37521. * [Geo description]
  37522. * @param {string} name Geo name
  37523. * @param {string} map Map type
  37524. * @param {Object} geoJson
  37525. * @param {Object} [specialAreas]
  37526. * Specify the positioned areas by left, top, width, height
  37527. * @param {Object.<string, string>} [nameMap]
  37528. * Specify name alias
  37529. */
  37530. function Geo(name, map$$1, geoJson, specialAreas, nameMap) {
  37531. View.call(this, name);
  37532. /**
  37533. * Map type
  37534. * @type {string}
  37535. */
  37536. this.map = map$$1;
  37537. this._nameCoordMap = createHashMap();
  37538. this.loadGeoJson(geoJson, specialAreas, nameMap);
  37539. }
  37540. Geo.prototype = {
  37541. constructor: Geo,
  37542. type: 'geo',
  37543. /**
  37544. * @param {Array.<string>}
  37545. * @readOnly
  37546. */
  37547. dimensions: ['lng', 'lat'],
  37548. /**
  37549. * If contain given lng,lat coord
  37550. * @param {Array.<number>}
  37551. * @readOnly
  37552. */
  37553. containCoord: function (coord) {
  37554. var regions = this.regions;
  37555. for (var i = 0; i < regions.length; i++) {
  37556. if (regions[i].contain(coord)) {
  37557. return true;
  37558. }
  37559. }
  37560. return false;
  37561. },
  37562. /**
  37563. * @param {Object} geoJson
  37564. * @param {Object} [specialAreas]
  37565. * Specify the positioned areas by left, top, width, height
  37566. * @param {Object.<string, string>} [nameMap]
  37567. * Specify name alias
  37568. */
  37569. loadGeoJson: function (geoJson, specialAreas, nameMap) {
  37570. // https://jsperf.com/try-catch-performance-overhead
  37571. try {
  37572. this.regions = geoJson ? parseGeoJson$1(geoJson) : [];
  37573. }
  37574. catch (e) {
  37575. throw 'Invalid geoJson format\n' + e.message;
  37576. }
  37577. specialAreas = specialAreas || {};
  37578. nameMap = nameMap || {};
  37579. var regions = this.regions;
  37580. var regionsMap = createHashMap();
  37581. for (var i = 0; i < regions.length; i++) {
  37582. var regionName = regions[i].name;
  37583. // Try use the alias in nameMap
  37584. regionName = nameMap.hasOwnProperty(regionName) ? nameMap[regionName] : regionName;
  37585. regions[i].name = regionName;
  37586. regionsMap.set(regionName, regions[i]);
  37587. // Add geoJson
  37588. this.addGeoCoord(regionName, regions[i].center);
  37589. // Some area like Alaska in USA map needs to be tansformed
  37590. // to look better
  37591. var specialArea = specialAreas[regionName];
  37592. if (specialArea) {
  37593. regions[i].transformTo(
  37594. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  37595. );
  37596. }
  37597. }
  37598. this._regionsMap = regionsMap;
  37599. this._rect = null;
  37600. each$1(geoFixFuncs, function (fixFunc) {
  37601. fixFunc(this);
  37602. }, this);
  37603. },
  37604. // Overwrite
  37605. transformTo: function (x, y, width, height) {
  37606. var rect = this.getBoundingRect();
  37607. rect = rect.clone();
  37608. // Longitute is inverted
  37609. rect.y = -rect.y - rect.height;
  37610. var rawTransformable = this._rawTransformable;
  37611. rawTransformable.transform = rect.calculateTransform(
  37612. new BoundingRect(x, y, width, height)
  37613. );
  37614. rawTransformable.decomposeTransform();
  37615. var scale = rawTransformable.scale;
  37616. scale[1] = -scale[1];
  37617. rawTransformable.updateTransform();
  37618. this._updateTransform();
  37619. },
  37620. /**
  37621. * @param {string} name
  37622. * @return {module:echarts/coord/geo/Region}
  37623. */
  37624. getRegion: function (name) {
  37625. return this._regionsMap.get(name);
  37626. },
  37627. getRegionByCoord: function (coord) {
  37628. var regions = this.regions;
  37629. for (var i = 0; i < regions.length; i++) {
  37630. if (regions[i].contain(coord)) {
  37631. return regions[i];
  37632. }
  37633. }
  37634. },
  37635. /**
  37636. * Add geoCoord for indexing by name
  37637. * @param {string} name
  37638. * @param {Array.<number>} geoCoord
  37639. */
  37640. addGeoCoord: function (name, geoCoord) {
  37641. this._nameCoordMap.set(name, geoCoord);
  37642. },
  37643. /**
  37644. * Get geoCoord by name
  37645. * @param {string} name
  37646. * @return {Array.<number>}
  37647. */
  37648. getGeoCoord: function (name) {
  37649. return this._nameCoordMap.get(name);
  37650. },
  37651. // Overwrite
  37652. getBoundingRect: function () {
  37653. if (this._rect) {
  37654. return this._rect;
  37655. }
  37656. var rect;
  37657. var regions = this.regions;
  37658. for (var i = 0; i < regions.length; i++) {
  37659. var regionRect = regions[i].getBoundingRect();
  37660. rect = rect || regionRect.clone();
  37661. rect.union(regionRect);
  37662. }
  37663. // FIXME Always return new ?
  37664. return (this._rect = rect || new BoundingRect(0, 0, 0, 0));
  37665. },
  37666. /**
  37667. * @param {string|Array.<number>} data
  37668. * @param {boolean} noRoam
  37669. * @param {Array.<number>} [out]
  37670. * @return {Array.<number>}
  37671. */
  37672. dataToPoint: function (data, noRoam, out) {
  37673. if (typeof data === 'string') {
  37674. // Map area name to geoCoord
  37675. data = this.getGeoCoord(data);
  37676. }
  37677. if (data) {
  37678. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  37679. }
  37680. },
  37681. /**
  37682. * @inheritDoc
  37683. */
  37684. convertToPixel: curry(doConvert, 'dataToPoint'),
  37685. /**
  37686. * @inheritDoc
  37687. */
  37688. convertFromPixel: curry(doConvert, 'pointToData')
  37689. };
  37690. mixin(Geo, View);
  37691. function doConvert(methodName, ecModel, finder, value) {
  37692. var geoModel = finder.geoModel;
  37693. var seriesModel = finder.seriesModel;
  37694. var coordSys = geoModel
  37695. ? geoModel.coordinateSystem
  37696. : seriesModel
  37697. ? (
  37698. seriesModel.coordinateSystem // For map.
  37699. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  37700. )
  37701. : null;
  37702. return coordSys === this ? coordSys[methodName](value) : null;
  37703. }
  37704. /*
  37705. * Licensed to the Apache Software Foundation (ASF) under one
  37706. * or more contributor license agreements. See the NOTICE file
  37707. * distributed with this work for additional information
  37708. * regarding copyright ownership. The ASF licenses this file
  37709. * to you under the Apache License, Version 2.0 (the
  37710. * "License"); you may not use this file except in compliance
  37711. * with the License. You may obtain a copy of the License at
  37712. *
  37713. * http://www.apache.org/licenses/LICENSE-2.0
  37714. *
  37715. * Unless required by applicable law or agreed to in writing,
  37716. * software distributed under the License is distributed on an
  37717. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37718. * KIND, either express or implied. See the License for the
  37719. * specific language governing permissions and limitations
  37720. * under the License.
  37721. */
  37722. /**
  37723. * Resize method bound to the geo
  37724. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  37725. * @param {module:echarts/ExtensionAPI} api
  37726. */
  37727. function resizeGeo(geoModel, api) {
  37728. var boundingCoords = geoModel.get('boundingCoords');
  37729. if (boundingCoords != null) {
  37730. var leftTop = boundingCoords[0];
  37731. var rightBottom = boundingCoords[1];
  37732. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  37733. if (__DEV__) {
  37734. console.error('Invalid boundingCoords');
  37735. }
  37736. }
  37737. else {
  37738. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  37739. }
  37740. }
  37741. var rect = this.getBoundingRect();
  37742. var boxLayoutOption;
  37743. var center = geoModel.get('layoutCenter');
  37744. var size = geoModel.get('layoutSize');
  37745. var viewWidth = api.getWidth();
  37746. var viewHeight = api.getHeight();
  37747. var aspectScale = geoModel.get('aspectScale') || 0.75;
  37748. var aspect = rect.width / rect.height * aspectScale;
  37749. var useCenterAndSize = false;
  37750. if (center && size) {
  37751. center = [
  37752. parsePercent$1(center[0], viewWidth),
  37753. parsePercent$1(center[1], viewHeight)
  37754. ];
  37755. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  37756. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  37757. useCenterAndSize = true;
  37758. }
  37759. else {
  37760. if (__DEV__) {
  37761. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  37762. }
  37763. }
  37764. }
  37765. var viewRect;
  37766. if (useCenterAndSize) {
  37767. var viewRect = {};
  37768. if (aspect > 1) {
  37769. // Width is same with size
  37770. viewRect.width = size;
  37771. viewRect.height = size / aspect;
  37772. }
  37773. else {
  37774. viewRect.height = size;
  37775. viewRect.width = size * aspect;
  37776. }
  37777. viewRect.y = center[1] - viewRect.height / 2;
  37778. viewRect.x = center[0] - viewRect.width / 2;
  37779. }
  37780. else {
  37781. // Use left/top/width/height
  37782. boxLayoutOption = geoModel.getBoxLayoutParams();
  37783. // 0.75 rate
  37784. boxLayoutOption.aspect = aspect;
  37785. viewRect = getLayoutRect(boxLayoutOption, {
  37786. width: viewWidth,
  37787. height: viewHeight
  37788. });
  37789. }
  37790. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  37791. this.setCenter(geoModel.get('center'));
  37792. this.setZoom(geoModel.get('zoom'));
  37793. }
  37794. /**
  37795. * @param {module:echarts/coord/Geo} geo
  37796. * @param {module:echarts/model/Model} model
  37797. * @inner
  37798. */
  37799. function setGeoCoords(geo, model) {
  37800. each$1(model.get('geoCoord'), function (geoCoord, name) {
  37801. geo.addGeoCoord(name, geoCoord);
  37802. });
  37803. }
  37804. if (__DEV__) {
  37805. var mapNotExistsError = function (name) {
  37806. console.error('Map ' + name + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html');
  37807. };
  37808. }
  37809. var geoCreator = {
  37810. // For deciding which dimensions to use when creating list data
  37811. dimensions: Geo.prototype.dimensions,
  37812. create: function (ecModel, api) {
  37813. var geoList = [];
  37814. // FIXME Create each time may be slow
  37815. ecModel.eachComponent('geo', function (geoModel, idx) {
  37816. var name = geoModel.get('map');
  37817. var mapData = getMap(name);
  37818. if (__DEV__) {
  37819. if (!mapData) {
  37820. mapNotExistsError(name);
  37821. }
  37822. }
  37823. var geo = new Geo(
  37824. name + idx, name,
  37825. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  37826. geoModel.get('nameMap')
  37827. );
  37828. geo.zoomLimit = geoModel.get('scaleLimit');
  37829. geoList.push(geo);
  37830. setGeoCoords(geo, geoModel);
  37831. geoModel.coordinateSystem = geo;
  37832. geo.model = geoModel;
  37833. // Inject resize method
  37834. geo.resize = resizeGeo;
  37835. geo.resize(geoModel, api);
  37836. });
  37837. ecModel.eachSeries(function (seriesModel) {
  37838. var coordSys = seriesModel.get('coordinateSystem');
  37839. if (coordSys === 'geo') {
  37840. var geoIndex = seriesModel.get('geoIndex') || 0;
  37841. seriesModel.coordinateSystem = geoList[geoIndex];
  37842. }
  37843. });
  37844. // If has map series
  37845. var mapModelGroupBySeries = {};
  37846. ecModel.eachSeriesByType('map', function (seriesModel) {
  37847. if (!seriesModel.getHostGeoModel()) {
  37848. var mapType = seriesModel.getMapType();
  37849. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  37850. mapModelGroupBySeries[mapType].push(seriesModel);
  37851. }
  37852. });
  37853. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  37854. var mapData = getMap(mapType);
  37855. if (__DEV__) {
  37856. if (!mapData) {
  37857. mapNotExistsError(mapSeries[0].get('map'));
  37858. }
  37859. }
  37860. var nameMapList = map(mapSeries, function (singleMapSeries) {
  37861. return singleMapSeries.get('nameMap');
  37862. });
  37863. var geo = new Geo(
  37864. mapType, mapType,
  37865. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  37866. mergeAll(nameMapList)
  37867. );
  37868. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  37869. return singleMapSeries.get('scaleLimit');
  37870. }));
  37871. geoList.push(geo);
  37872. // Inject resize method
  37873. geo.resize = resizeGeo;
  37874. geo.resize(mapSeries[0], api);
  37875. each$1(mapSeries, function (singleMapSeries) {
  37876. singleMapSeries.coordinateSystem = geo;
  37877. setGeoCoords(geo, singleMapSeries);
  37878. });
  37879. });
  37880. return geoList;
  37881. },
  37882. /**
  37883. * Fill given regions array
  37884. * @param {Array.<Object>} originRegionArr
  37885. * @param {string} mapName
  37886. * @param {Object} [nameMap]
  37887. * @return {Array}
  37888. */
  37889. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  37890. // Not use the original
  37891. var regionsArr = (originRegionArr || []).slice();
  37892. nameMap = nameMap || {};
  37893. var map$$1 = getMap(mapName);
  37894. var geoJson = map$$1 && map$$1.geoJson;
  37895. if (!geoJson) {
  37896. if (__DEV__) {
  37897. mapNotExistsError(mapName);
  37898. }
  37899. return originRegionArr;
  37900. }
  37901. var dataNameMap = createHashMap();
  37902. var features = geoJson.features;
  37903. for (var i = 0; i < regionsArr.length; i++) {
  37904. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  37905. }
  37906. for (var i = 0; i < features.length; i++) {
  37907. var name = features[i].properties.name;
  37908. if (!dataNameMap.get(name)) {
  37909. if (nameMap.hasOwnProperty(name)) {
  37910. name = nameMap[name];
  37911. }
  37912. regionsArr.push({
  37913. name: name
  37914. });
  37915. }
  37916. }
  37917. return regionsArr;
  37918. }
  37919. };
  37920. registerCoordinateSystem('geo', geoCreator);
  37921. /*
  37922. * Licensed to the Apache Software Foundation (ASF) under one
  37923. * or more contributor license agreements. See the NOTICE file
  37924. * distributed with this work for additional information
  37925. * regarding copyright ownership. The ASF licenses this file
  37926. * to you under the Apache License, Version 2.0 (the
  37927. * "License"); you may not use this file except in compliance
  37928. * with the License. You may obtain a copy of the License at
  37929. *
  37930. * http://www.apache.org/licenses/LICENSE-2.0
  37931. *
  37932. * Unless required by applicable law or agreed to in writing,
  37933. * software distributed under the License is distributed on an
  37934. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37935. * KIND, either express or implied. See the License for the
  37936. * specific language governing permissions and limitations
  37937. * under the License.
  37938. */
  37939. var MapSeries = SeriesModel.extend({
  37940. type: 'series.map',
  37941. dependencies: ['geo'],
  37942. layoutMode: 'box',
  37943. /**
  37944. * Only first map series of same mapType will drawMap
  37945. * @type {boolean}
  37946. */
  37947. needsDrawMap: false,
  37948. /**
  37949. * Group of all map series with same mapType
  37950. * @type {boolean}
  37951. */
  37952. seriesGroup: [],
  37953. init: function (option) {
  37954. // this._fillOption(option, this.getMapType());
  37955. // this.option = option;
  37956. MapSeries.superApply(this, 'init', arguments);
  37957. this.updateSelectedMap(this._createSelectableList());
  37958. },
  37959. getInitialData: function (option) {
  37960. return createListSimply(this, ['value']);
  37961. },
  37962. mergeOption: function (newOption) {
  37963. // this._fillOption(newOption, this.getMapType());
  37964. MapSeries.superApply(this, 'mergeOption', arguments);
  37965. this.updateSelectedMap(this._createSelectableList());
  37966. },
  37967. _createSelectableList: function () {
  37968. var data = this.getRawData();
  37969. var valueDim = data.mapDimension('value');
  37970. var targetList = [];
  37971. for (var i = 0, len = data.count(); i < len; i++) {
  37972. targetList.push({
  37973. name: data.getName(i),
  37974. value: data.get(valueDim, i),
  37975. selected: retrieveRawAttr(data, i, 'selected')
  37976. });
  37977. }
  37978. targetList = geoCreator.getFilledRegions(targetList, this.getMapType(), this.option.nameMap);
  37979. return targetList;
  37980. },
  37981. /**
  37982. * If no host geo model, return null, which means using a
  37983. * inner exclusive geo model.
  37984. */
  37985. getHostGeoModel: function () {
  37986. var geoIndex = this.option.geoIndex;
  37987. return geoIndex != null
  37988. ? this.dependentModels.geo[geoIndex]
  37989. : null;
  37990. },
  37991. getMapType: function () {
  37992. return (this.getHostGeoModel() || this).option.map;
  37993. },
  37994. _fillOption: function (option, mapName) {
  37995. // Shallow clone
  37996. // option = zrUtil.extend({}, option);
  37997. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  37998. // return option;
  37999. },
  38000. getRawValue: function (dataIndex) {
  38001. // Use value stored in data instead because it is calculated from multiple series
  38002. // FIXME Provide all value of multiple series ?
  38003. var data = this.getData();
  38004. return data.get(data.mapDimension('value'), dataIndex);
  38005. },
  38006. /**
  38007. * Get model of region
  38008. * @param {string} name
  38009. * @return {module:echarts/model/Model}
  38010. */
  38011. getRegionModel: function (regionName) {
  38012. var data = this.getData();
  38013. return data.getItemModel(data.indexOfName(regionName));
  38014. },
  38015. /**
  38016. * Map tooltip formatter
  38017. *
  38018. * @param {number} dataIndex
  38019. */
  38020. formatTooltip: function (dataIndex) {
  38021. // FIXME orignalData and data is a bit confusing
  38022. var data = this.getData();
  38023. var formattedValue = addCommas(this.getRawValue(dataIndex));
  38024. var name = data.getName(dataIndex);
  38025. var seriesGroup = this.seriesGroup;
  38026. var seriesNames = [];
  38027. for (var i = 0; i < seriesGroup.length; i++) {
  38028. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  38029. var valueDim = data.mapDimension('value');
  38030. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  38031. seriesNames.push(
  38032. encodeHTML(seriesGroup[i].name)
  38033. );
  38034. }
  38035. }
  38036. return seriesNames.join(', ') + '<br />'
  38037. + encodeHTML(name + ' : ' + formattedValue);
  38038. },
  38039. /**
  38040. * @implement
  38041. */
  38042. getTooltipPosition: function (dataIndex) {
  38043. if (dataIndex != null) {
  38044. var name = this.getData().getName(dataIndex);
  38045. var geo = this.coordinateSystem;
  38046. var region = geo.getRegion(name);
  38047. return region && geo.dataToPoint(region.center);
  38048. }
  38049. },
  38050. setZoom: function (zoom) {
  38051. this.option.zoom = zoom;
  38052. },
  38053. setCenter: function (center) {
  38054. this.option.center = center;
  38055. },
  38056. defaultOption: {
  38057. // 一级层叠
  38058. zlevel: 0,
  38059. // 二级层叠
  38060. z: 2,
  38061. coordinateSystem: 'geo',
  38062. // map should be explicitly specified since ec3.
  38063. map: '',
  38064. // If `geoIndex` is not specified, a exclusive geo will be
  38065. // created. Otherwise use the specified geo component, and
  38066. // `map` and `mapType` are ignored.
  38067. // geoIndex: 0,
  38068. // 'center' | 'left' | 'right' | 'x%' | {number}
  38069. left: 'center',
  38070. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  38071. top: 'center',
  38072. // right
  38073. // bottom
  38074. // width:
  38075. // height
  38076. // Aspect is width / height. Inited to be geoJson bbox aspect
  38077. // This parameter is used for scale this aspect
  38078. aspectScale: 0.75,
  38079. ///// Layout with center and size
  38080. // If you wan't to put map in a fixed size box with right aspect ratio
  38081. // This two properties may more conveninet
  38082. // layoutCenter: [50%, 50%]
  38083. // layoutSize: 100
  38084. // 数值合并方式,默认加和,可选为:
  38085. // 'sum' | 'average' | 'max' | 'min'
  38086. // mapValueCalculation: 'sum',
  38087. // 地图数值计算结果小数精度
  38088. // mapValuePrecision: 0,
  38089. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  38090. showLegendSymbol: true,
  38091. // 选择模式,默认关闭,可选single,multiple
  38092. // selectedMode: false,
  38093. dataRangeHoverLink: true,
  38094. // 是否开启缩放及漫游模式
  38095. // roam: false,
  38096. // Define left-top, right-bottom coords to control view
  38097. // For example, [ [180, 90], [-180, -90] ],
  38098. // higher priority than center and zoom
  38099. boundingCoords: null,
  38100. // Default on center of map
  38101. center: null,
  38102. zoom: 1,
  38103. scaleLimit: null,
  38104. label: {
  38105. show: false,
  38106. color: '#000'
  38107. },
  38108. // scaleLimit: null,
  38109. itemStyle: {
  38110. borderWidth: 0.5,
  38111. borderColor: '#444',
  38112. areaColor: '#eee'
  38113. },
  38114. emphasis: {
  38115. label: {
  38116. show: true,
  38117. color: 'rgb(100,0,0)'
  38118. },
  38119. itemStyle: {
  38120. areaColor: 'rgba(255,215,0,0.8)'
  38121. }
  38122. }
  38123. }
  38124. });
  38125. mixin(MapSeries, selectableMixin);
  38126. /*
  38127. * Licensed to the Apache Software Foundation (ASF) under one
  38128. * or more contributor license agreements. See the NOTICE file
  38129. * distributed with this work for additional information
  38130. * regarding copyright ownership. The ASF licenses this file
  38131. * to you under the Apache License, Version 2.0 (the
  38132. * "License"); you may not use this file except in compliance
  38133. * with the License. You may obtain a copy of the License at
  38134. *
  38135. * http://www.apache.org/licenses/LICENSE-2.0
  38136. *
  38137. * Unless required by applicable law or agreed to in writing,
  38138. * software distributed under the License is distributed on an
  38139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38140. * KIND, either express or implied. See the License for the
  38141. * specific language governing permissions and limitations
  38142. * under the License.
  38143. */
  38144. var ATTR = '\0_ec_interaction_mutex';
  38145. function take(zr, resourceKey, userKey) {
  38146. var store = getStore(zr);
  38147. store[resourceKey] = userKey;
  38148. }
  38149. function release(zr, resourceKey, userKey) {
  38150. var store = getStore(zr);
  38151. var uKey = store[resourceKey];
  38152. if (uKey === userKey) {
  38153. store[resourceKey] = null;
  38154. }
  38155. }
  38156. function isTaken(zr, resourceKey) {
  38157. return !!getStore(zr)[resourceKey];
  38158. }
  38159. function getStore(zr) {
  38160. return zr[ATTR] || (zr[ATTR] = {});
  38161. }
  38162. /**
  38163. * payload: {
  38164. * type: 'takeGlobalCursor',
  38165. * key: 'dataZoomSelect', or 'brush', or ...,
  38166. * If no userKey, release global cursor.
  38167. * }
  38168. */
  38169. registerAction(
  38170. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  38171. function () {}
  38172. );
  38173. /*
  38174. * Licensed to the Apache Software Foundation (ASF) under one
  38175. * or more contributor license agreements. See the NOTICE file
  38176. * distributed with this work for additional information
  38177. * regarding copyright ownership. The ASF licenses this file
  38178. * to you under the Apache License, Version 2.0 (the
  38179. * "License"); you may not use this file except in compliance
  38180. * with the License. You may obtain a copy of the License at
  38181. *
  38182. * http://www.apache.org/licenses/LICENSE-2.0
  38183. *
  38184. * Unless required by applicable law or agreed to in writing,
  38185. * software distributed under the License is distributed on an
  38186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38187. * KIND, either express or implied. See the License for the
  38188. * specific language governing permissions and limitations
  38189. * under the License.
  38190. */
  38191. /**
  38192. * @alias module:echarts/component/helper/RoamController
  38193. * @constructor
  38194. * @mixin {module:zrender/mixin/Eventful}
  38195. *
  38196. * @param {module:zrender/zrender~ZRender} zr
  38197. */
  38198. function RoamController(zr) {
  38199. /**
  38200. * @type {Function}
  38201. */
  38202. this.pointerChecker;
  38203. /**
  38204. * @type {module:zrender}
  38205. */
  38206. this._zr = zr;
  38207. /**
  38208. * @type {Object}
  38209. */
  38210. this._opt = {};
  38211. // Avoid two roamController bind the same handler
  38212. var bind$$1 = bind;
  38213. var mousedownHandler = bind$$1(mousedown, this);
  38214. var mousemoveHandler = bind$$1(mousemove, this);
  38215. var mouseupHandler = bind$$1(mouseup, this);
  38216. var mousewheelHandler = bind$$1(mousewheel, this);
  38217. var pinchHandler = bind$$1(pinch, this);
  38218. Eventful.call(this);
  38219. /**
  38220. * @param {Function} pointerChecker
  38221. * input: x, y
  38222. * output: boolean
  38223. */
  38224. this.setPointerChecker = function (pointerChecker) {
  38225. this.pointerChecker = pointerChecker;
  38226. };
  38227. /**
  38228. * Notice: only enable needed types. For example, if 'zoom'
  38229. * is not needed, 'zoom' should not be enabled, otherwise
  38230. * default mousewheel behaviour (scroll page) will be disabled.
  38231. *
  38232. * @param {boolean|string} [controlType=true] Specify the control type,
  38233. * which can be null/undefined or true/false
  38234. * or 'pan/move' or 'zoom'/'scale'
  38235. * @param {Object} [opt]
  38236. * @param {Object} [opt.zoomOnMouseWheel=true]
  38237. * @param {Object} [opt.moveOnMouseMove=true]
  38238. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  38239. */
  38240. this.enable = function (controlType, opt) {
  38241. // Disable previous first
  38242. this.disable();
  38243. this._opt = defaults(clone(opt) || {}, {
  38244. zoomOnMouseWheel: true,
  38245. moveOnMouseMove: true,
  38246. preventDefaultMouseMove: true
  38247. });
  38248. if (controlType == null) {
  38249. controlType = true;
  38250. }
  38251. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  38252. zr.on('mousedown', mousedownHandler);
  38253. zr.on('mousemove', mousemoveHandler);
  38254. zr.on('mouseup', mouseupHandler);
  38255. }
  38256. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  38257. zr.on('mousewheel', mousewheelHandler);
  38258. zr.on('pinch', pinchHandler);
  38259. }
  38260. };
  38261. this.disable = function () {
  38262. zr.off('mousedown', mousedownHandler);
  38263. zr.off('mousemove', mousemoveHandler);
  38264. zr.off('mouseup', mouseupHandler);
  38265. zr.off('mousewheel', mousewheelHandler);
  38266. zr.off('pinch', pinchHandler);
  38267. };
  38268. this.dispose = this.disable;
  38269. this.isDragging = function () {
  38270. return this._dragging;
  38271. };
  38272. this.isPinching = function () {
  38273. return this._pinching;
  38274. };
  38275. }
  38276. mixin(RoamController, Eventful);
  38277. function mousedown(e) {
  38278. if (notLeftMouse(e)
  38279. || (e.target && e.target.draggable)
  38280. ) {
  38281. return;
  38282. }
  38283. var x = e.offsetX;
  38284. var y = e.offsetY;
  38285. // Only check on mosedown, but not mousemove.
  38286. // Mouse can be out of target when mouse moving.
  38287. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  38288. this._x = x;
  38289. this._y = y;
  38290. this._dragging = true;
  38291. }
  38292. }
  38293. function mousemove(e) {
  38294. if (notLeftMouse(e)
  38295. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  38296. || !this._dragging
  38297. || e.gestureEvent === 'pinch'
  38298. || isTaken(this._zr, 'globalPan')
  38299. ) {
  38300. return;
  38301. }
  38302. var x = e.offsetX;
  38303. var y = e.offsetY;
  38304. var oldX = this._x;
  38305. var oldY = this._y;
  38306. var dx = x - oldX;
  38307. var dy = y - oldY;
  38308. this._x = x;
  38309. this._y = y;
  38310. this._opt.preventDefaultMouseMove && stop(e.event);
  38311. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  38312. }
  38313. function mouseup(e) {
  38314. if (!notLeftMouse(e)) {
  38315. this._dragging = false;
  38316. }
  38317. }
  38318. function mousewheel(e) {
  38319. // wheelDelta maybe -0 in chrome mac.
  38320. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  38321. return;
  38322. }
  38323. // Convenience:
  38324. // Mac and VM Windows on Mac: scroll up: zoom out.
  38325. // Windows: scroll up: zoom in.
  38326. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  38327. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  38328. }
  38329. function pinch(e) {
  38330. if (isTaken(this._zr, 'globalPan')) {
  38331. return;
  38332. }
  38333. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  38334. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  38335. }
  38336. function zoom(e, zoomDelta, zoomX, zoomY) {
  38337. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  38338. // When mouse is out of roamController rect,
  38339. // default befavoius should not be be disabled, otherwise
  38340. // page sliding is disabled, contrary to expectation.
  38341. stop(e.event);
  38342. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  38343. }
  38344. }
  38345. function checkKeyBinding(roamController, prop, e) {
  38346. var setting = roamController._opt[prop];
  38347. return setting
  38348. && (!isString(setting) || e.event[setting + 'Key']);
  38349. }
  38350. /*
  38351. * Licensed to the Apache Software Foundation (ASF) under one
  38352. * or more contributor license agreements. See the NOTICE file
  38353. * distributed with this work for additional information
  38354. * regarding copyright ownership. The ASF licenses this file
  38355. * to you under the Apache License, Version 2.0 (the
  38356. * "License"); you may not use this file except in compliance
  38357. * with the License. You may obtain a copy of the License at
  38358. *
  38359. * http://www.apache.org/licenses/LICENSE-2.0
  38360. *
  38361. * Unless required by applicable law or agreed to in writing,
  38362. * software distributed under the License is distributed on an
  38363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38364. * KIND, either express or implied. See the License for the
  38365. * specific language governing permissions and limitations
  38366. * under the License.
  38367. */
  38368. /**
  38369. * For geo and graph.
  38370. *
  38371. * @param {Object} controllerHost
  38372. * @param {module:zrender/Element} controllerHost.target
  38373. */
  38374. function updateViewOnPan(controllerHost, dx, dy) {
  38375. var target = controllerHost.target;
  38376. var pos = target.position;
  38377. pos[0] += dx;
  38378. pos[1] += dy;
  38379. target.dirty();
  38380. }
  38381. /**
  38382. * For geo and graph.
  38383. *
  38384. * @param {Object} controllerHost
  38385. * @param {module:zrender/Element} controllerHost.target
  38386. * @param {number} controllerHost.zoom
  38387. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  38388. */
  38389. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  38390. var target = controllerHost.target;
  38391. var zoomLimit = controllerHost.zoomLimit;
  38392. var pos = target.position;
  38393. var scale = target.scale;
  38394. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  38395. newZoom *= zoomDelta;
  38396. if (zoomLimit) {
  38397. var zoomMin = zoomLimit.min || 0;
  38398. var zoomMax = zoomLimit.max || Infinity;
  38399. newZoom = Math.max(
  38400. Math.min(zoomMax, newZoom),
  38401. zoomMin
  38402. );
  38403. }
  38404. var zoomScale = newZoom / controllerHost.zoom;
  38405. controllerHost.zoom = newZoom;
  38406. // Keep the mouse center when scaling
  38407. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  38408. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  38409. scale[0] *= zoomScale;
  38410. scale[1] *= zoomScale;
  38411. target.dirty();
  38412. }
  38413. /*
  38414. * Licensed to the Apache Software Foundation (ASF) under one
  38415. * or more contributor license agreements. See the NOTICE file
  38416. * distributed with this work for additional information
  38417. * regarding copyright ownership. The ASF licenses this file
  38418. * to you under the Apache License, Version 2.0 (the
  38419. * "License"); you may not use this file except in compliance
  38420. * with the License. You may obtain a copy of the License at
  38421. *
  38422. * http://www.apache.org/licenses/LICENSE-2.0
  38423. *
  38424. * Unless required by applicable law or agreed to in writing,
  38425. * software distributed under the License is distributed on an
  38426. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38427. * KIND, either express or implied. See the License for the
  38428. * specific language governing permissions and limitations
  38429. * under the License.
  38430. */
  38431. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  38432. /**
  38433. * Avoid that: mouse click on a elements that is over geo or graph,
  38434. * but roam is triggered.
  38435. */
  38436. function onIrrelevantElement(e, api, targetCoordSysModel) {
  38437. var model = api.getComponentByElement(e.topTarget);
  38438. // If model is axisModel, it works only if it is injected with coordinateSystem.
  38439. var coordSys = model && model.coordinateSystem;
  38440. return model
  38441. && model !== targetCoordSysModel
  38442. && !IRRELEVANT_EXCLUDES[model.mainType]
  38443. && (coordSys && coordSys.model !== targetCoordSysModel);
  38444. }
  38445. /*
  38446. * Licensed to the Apache Software Foundation (ASF) under one
  38447. * or more contributor license agreements. See the NOTICE file
  38448. * distributed with this work for additional information
  38449. * regarding copyright ownership. The ASF licenses this file
  38450. * to you under the Apache License, Version 2.0 (the
  38451. * "License"); you may not use this file except in compliance
  38452. * with the License. You may obtain a copy of the License at
  38453. *
  38454. * http://www.apache.org/licenses/LICENSE-2.0
  38455. *
  38456. * Unless required by applicable law or agreed to in writing,
  38457. * software distributed under the License is distributed on an
  38458. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38459. * KIND, either express or implied. See the License for the
  38460. * specific language governing permissions and limitations
  38461. * under the License.
  38462. */
  38463. function getFixedItemStyle(model, scale) {
  38464. var itemStyle = model.getItemStyle();
  38465. var areaColor = model.get('areaColor');
  38466. // If user want the color not to be changed when hover,
  38467. // they should both set areaColor and color to be null.
  38468. if (areaColor != null) {
  38469. itemStyle.fill = areaColor;
  38470. }
  38471. return itemStyle;
  38472. }
  38473. function updateMapSelectHandler(mapDraw, mapOrGeoModel, group, api, fromView) {
  38474. group.off('click');
  38475. group.off('mousedown');
  38476. if (mapOrGeoModel.get('selectedMode')) {
  38477. group.on('mousedown', function () {
  38478. mapDraw._mouseDownFlag = true;
  38479. });
  38480. group.on('click', function (e) {
  38481. if (!mapDraw._mouseDownFlag) {
  38482. return;
  38483. }
  38484. mapDraw._mouseDownFlag = false;
  38485. var el = e.target;
  38486. while (!el.__regions) {
  38487. el = el.parent;
  38488. }
  38489. if (!el) {
  38490. return;
  38491. }
  38492. var action = {
  38493. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  38494. batch: map(el.__regions, function (region) {
  38495. return {
  38496. name: region.name,
  38497. from: fromView.uid
  38498. };
  38499. })
  38500. };
  38501. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  38502. api.dispatchAction(action);
  38503. updateMapSelected(mapOrGeoModel, group);
  38504. });
  38505. }
  38506. }
  38507. function updateMapSelected(mapOrGeoModel, group) {
  38508. // FIXME
  38509. group.eachChild(function (otherRegionEl) {
  38510. each$1(otherRegionEl.__regions, function (region) {
  38511. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  38512. });
  38513. });
  38514. }
  38515. /**
  38516. * @alias module:echarts/component/helper/MapDraw
  38517. * @param {module:echarts/ExtensionAPI} api
  38518. * @param {boolean} updateGroup
  38519. */
  38520. function MapDraw(api, updateGroup) {
  38521. var group = new Group();
  38522. /**
  38523. * @type {module:echarts/component/helper/RoamController}
  38524. * @private
  38525. */
  38526. this._controller = new RoamController(api.getZr());
  38527. /**
  38528. * @type {Object} {target, zoom, zoomLimit}
  38529. * @private
  38530. */
  38531. this._controllerHost = {target: updateGroup ? group : null};
  38532. /**
  38533. * @type {module:zrender/container/Group}
  38534. * @readOnly
  38535. */
  38536. this.group = group;
  38537. /**
  38538. * @type {boolean}
  38539. * @private
  38540. */
  38541. this._updateGroup = updateGroup;
  38542. /**
  38543. * This flag is used to make sure that only one among
  38544. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  38545. * action may be triggered when `pan`, which is unexpected.
  38546. * @type {booelan}
  38547. */
  38548. this._mouseDownFlag;
  38549. }
  38550. MapDraw.prototype = {
  38551. constructor: MapDraw,
  38552. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  38553. var isGeo = mapOrGeoModel.mainType === 'geo';
  38554. // Map series has data. GEO model that controlled by map series
  38555. // will be assigned with map data. Other GEO model has no data.
  38556. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  38557. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  38558. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  38559. data = mapSeries.getData();
  38560. }
  38561. });
  38562. var geo = mapOrGeoModel.coordinateSystem;
  38563. var group = this.group;
  38564. var scale = geo.scale;
  38565. var groupNewProp = {
  38566. position: geo.position,
  38567. scale: scale
  38568. };
  38569. // No animation when first draw or in action
  38570. if (!group.childAt(0) || payload) {
  38571. group.attr(groupNewProp);
  38572. }
  38573. else {
  38574. updateProps(group, groupNewProp, mapOrGeoModel);
  38575. }
  38576. group.removeAll();
  38577. var itemStyleAccessPath = ['itemStyle'];
  38578. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  38579. var labelAccessPath = ['label'];
  38580. var hoverLabelAccessPath = ['emphasis', 'label'];
  38581. var nameMap = createHashMap();
  38582. each$1(geo.regions, function (region) {
  38583. // Consider in GeoJson properties.name may be duplicated, for example,
  38584. // there is multiple region named "United Kindom" or "France" (so many
  38585. // colonies). And it is not appropriate to merge them in geo, which
  38586. // will make them share the same label and bring trouble in label
  38587. // location calculation.
  38588. var regionGroup = nameMap.get(region.name)
  38589. || nameMap.set(region.name, new Group());
  38590. var compoundPath = new CompoundPath({
  38591. shape: {
  38592. paths: []
  38593. }
  38594. });
  38595. regionGroup.add(compoundPath);
  38596. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  38597. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  38598. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  38599. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  38600. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  38601. var labelModel = regionModel.getModel(labelAccessPath);
  38602. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  38603. var dataIdx;
  38604. // Use the itemStyle in data if has data
  38605. if (data) {
  38606. dataIdx = data.indexOfName(region.name);
  38607. // Only visual color of each item will be used. It can be encoded by dataRange
  38608. // But visual color of series is used in symbol drawing
  38609. //
  38610. // Visual color for each series is for the symbol draw
  38611. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  38612. if (visualColor) {
  38613. itemStyle.fill = visualColor;
  38614. }
  38615. }
  38616. each$1(region.geometries, function (geometry) {
  38617. if (geometry.type !== 'polygon') {
  38618. return;
  38619. }
  38620. compoundPath.shape.paths.push(new Polygon({
  38621. shape: {
  38622. points: geometry.exterior
  38623. }
  38624. }));
  38625. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  38626. compoundPath.shape.paths.push(new Polygon({
  38627. shape: {
  38628. points: geometry.interiors[i]
  38629. }
  38630. }));
  38631. }
  38632. });
  38633. compoundPath.setStyle(itemStyle);
  38634. compoundPath.style.strokeNoScale = true;
  38635. compoundPath.culling = true;
  38636. // Label
  38637. var showLabel = labelModel.get('show');
  38638. var hoverShowLabel = hoverLabelModel.get('show');
  38639. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  38640. var itemLayout = data && data.getItemLayout(dataIdx);
  38641. // In the following cases label will be drawn
  38642. // 1. In map series and data value is NaN
  38643. // 2. In geo component
  38644. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  38645. if (
  38646. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  38647. || (itemLayout && itemLayout.showLabel)
  38648. ) {
  38649. var query = !isGeo ? dataIdx : region.name;
  38650. var labelFetcher;
  38651. // Consider dataIdx not found.
  38652. if (!data || dataIdx >= 0) {
  38653. labelFetcher = mapOrGeoModel;
  38654. }
  38655. var textEl = new Text({
  38656. position: region.center.slice(),
  38657. scale: [1 / scale[0], 1 / scale[1]],
  38658. z2: 10,
  38659. silent: true
  38660. });
  38661. setLabelStyle(
  38662. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  38663. {
  38664. labelFetcher: labelFetcher,
  38665. labelDataIndex: query,
  38666. defaultText: region.name,
  38667. useInsideStyle: false
  38668. },
  38669. {
  38670. textAlign: 'center',
  38671. textVerticalAlign: 'middle'
  38672. }
  38673. );
  38674. regionGroup.add(textEl);
  38675. }
  38676. // setItemGraphicEl, setHoverStyle after all polygons and labels
  38677. // are added to the rigionGroup
  38678. if (data) {
  38679. data.setItemGraphicEl(dataIdx, regionGroup);
  38680. }
  38681. else {
  38682. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  38683. // Package custom mouse event for geo component
  38684. compoundPath.eventData = {
  38685. componentType: 'geo',
  38686. geoIndex: mapOrGeoModel.componentIndex,
  38687. name: region.name,
  38688. region: (regionModel && regionModel.option) || {}
  38689. };
  38690. }
  38691. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  38692. groupRegions.push(region);
  38693. setHoverStyle(
  38694. regionGroup,
  38695. hoverItemStyle,
  38696. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  38697. );
  38698. group.add(regionGroup);
  38699. });
  38700. this._updateController(mapOrGeoModel, ecModel, api);
  38701. updateMapSelectHandler(this, mapOrGeoModel, group, api, fromView);
  38702. updateMapSelected(mapOrGeoModel, group);
  38703. },
  38704. remove: function () {
  38705. this.group.removeAll();
  38706. this._controller.dispose();
  38707. this._controllerHost = {};
  38708. },
  38709. _updateController: function (mapOrGeoModel, ecModel, api) {
  38710. var geo = mapOrGeoModel.coordinateSystem;
  38711. var controller = this._controller;
  38712. var controllerHost = this._controllerHost;
  38713. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  38714. controllerHost.zoom = geo.getZoom();
  38715. // roamType is will be set default true if it is null
  38716. controller.enable(mapOrGeoModel.get('roam') || false);
  38717. var mainType = mapOrGeoModel.mainType;
  38718. function makeActionBase() {
  38719. var action = {
  38720. type: 'geoRoam',
  38721. componentType: mainType
  38722. };
  38723. action[mainType + 'Id'] = mapOrGeoModel.id;
  38724. return action;
  38725. }
  38726. controller.off('pan').on('pan', function (dx, dy) {
  38727. this._mouseDownFlag = false;
  38728. updateViewOnPan(controllerHost, dx, dy);
  38729. api.dispatchAction(extend(makeActionBase(), {
  38730. dx: dx,
  38731. dy: dy
  38732. }));
  38733. }, this);
  38734. controller.off('zoom').on('zoom', function (zoom, mouseX, mouseY) {
  38735. this._mouseDownFlag = false;
  38736. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  38737. api.dispatchAction(extend(makeActionBase(), {
  38738. zoom: zoom,
  38739. originX: mouseX,
  38740. originY: mouseY
  38741. }));
  38742. if (this._updateGroup) {
  38743. var group = this.group;
  38744. var scale = group.scale;
  38745. group.traverse(function (el) {
  38746. if (el.type === 'text') {
  38747. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  38748. }
  38749. });
  38750. }
  38751. }, this);
  38752. controller.setPointerChecker(function (e, x, y) {
  38753. return geo.getViewRectAfterRoam().contain(x, y)
  38754. && !onIrrelevantElement(e, api, mapOrGeoModel);
  38755. });
  38756. }
  38757. };
  38758. /*
  38759. * Licensed to the Apache Software Foundation (ASF) under one
  38760. * or more contributor license agreements. See the NOTICE file
  38761. * distributed with this work for additional information
  38762. * regarding copyright ownership. The ASF licenses this file
  38763. * to you under the Apache License, Version 2.0 (the
  38764. * "License"); you may not use this file except in compliance
  38765. * with the License. You may obtain a copy of the License at
  38766. *
  38767. * http://www.apache.org/licenses/LICENSE-2.0
  38768. *
  38769. * Unless required by applicable law or agreed to in writing,
  38770. * software distributed under the License is distributed on an
  38771. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38772. * KIND, either express or implied. See the License for the
  38773. * specific language governing permissions and limitations
  38774. * under the License.
  38775. */
  38776. extendChartView({
  38777. type: 'map',
  38778. render: function (mapModel, ecModel, api, payload) {
  38779. // Not render if it is an toggleSelect action from self
  38780. if (payload && payload.type === 'mapToggleSelect'
  38781. && payload.from === this.uid
  38782. ) {
  38783. return;
  38784. }
  38785. var group = this.group;
  38786. group.removeAll();
  38787. if (mapModel.getHostGeoModel()) {
  38788. return;
  38789. }
  38790. // Not update map if it is an roam action from self
  38791. if (!(payload && payload.type === 'geoRoam'
  38792. && payload.componentType === 'series'
  38793. && payload.seriesId === mapModel.id
  38794. )
  38795. ) {
  38796. if (mapModel.needsDrawMap) {
  38797. var mapDraw = this._mapDraw || new MapDraw(api, true);
  38798. group.add(mapDraw.group);
  38799. mapDraw.draw(mapModel, ecModel, api, this, payload);
  38800. this._mapDraw = mapDraw;
  38801. }
  38802. else {
  38803. // Remove drawed map
  38804. this._mapDraw && this._mapDraw.remove();
  38805. this._mapDraw = null;
  38806. }
  38807. }
  38808. else {
  38809. var mapDraw = this._mapDraw;
  38810. mapDraw && group.add(mapDraw.group);
  38811. }
  38812. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  38813. && this._renderSymbols(mapModel, ecModel, api);
  38814. },
  38815. remove: function () {
  38816. this._mapDraw && this._mapDraw.remove();
  38817. this._mapDraw = null;
  38818. this.group.removeAll();
  38819. },
  38820. dispose: function () {
  38821. this._mapDraw && this._mapDraw.remove();
  38822. this._mapDraw = null;
  38823. },
  38824. _renderSymbols: function (mapModel, ecModel, api) {
  38825. var originalData = mapModel.originalData;
  38826. var group = this.group;
  38827. originalData.each(originalData.mapDimension('value'), function (value, idx) {
  38828. if (isNaN(value)) {
  38829. return;
  38830. }
  38831. var layout = originalData.getItemLayout(idx);
  38832. if (!layout || !layout.point) {
  38833. // Not exists in map
  38834. return;
  38835. }
  38836. var point = layout.point;
  38837. var offset = layout.offset;
  38838. var circle = new Circle({
  38839. style: {
  38840. // Because the special of map draw.
  38841. // Which needs statistic of multiple series and draw on one map.
  38842. // And each series also need a symbol with legend color
  38843. //
  38844. // Layout and visual are put one the different data
  38845. fill: mapModel.getData().getVisual('color')
  38846. },
  38847. shape: {
  38848. cx: point[0] + offset * 9,
  38849. cy: point[1],
  38850. r: 3
  38851. },
  38852. silent: true,
  38853. // Do not overlap the first series, on which labels are displayed.
  38854. z2: !offset ? 10 : 8
  38855. });
  38856. // First data on the same region
  38857. if (!offset) {
  38858. var fullData = mapModel.mainSeries.getData();
  38859. var name = originalData.getName(idx);
  38860. var fullIndex = fullData.indexOfName(name);
  38861. var itemModel = originalData.getItemModel(idx);
  38862. var labelModel = itemModel.getModel('label');
  38863. var hoverLabelModel = itemModel.getModel('emphasis.label');
  38864. var polygonGroups = fullData.getItemGraphicEl(fullIndex);
  38865. var normalText = retrieve2(
  38866. mapModel.getFormattedLabel(idx, 'normal'),
  38867. name
  38868. );
  38869. var emphasisText = retrieve2(
  38870. mapModel.getFormattedLabel(idx, 'emphasis'),
  38871. normalText
  38872. );
  38873. var onEmphasis = function () {
  38874. var hoverStyle = setTextStyle({}, hoverLabelModel, {
  38875. text: hoverLabelModel.get('show') ? emphasisText : null
  38876. }, {isRectText: true, useInsideStyle: false}, true);
  38877. circle.style.extendFrom(hoverStyle);
  38878. // Make label upper than others if overlaps.
  38879. circle.__mapOriginalZ2 = circle.z2;
  38880. circle.z2 += 1;
  38881. };
  38882. var onNormal = function () {
  38883. setTextStyle(circle.style, labelModel, {
  38884. text: labelModel.get('show') ? normalText : null,
  38885. textPosition: labelModel.getShallow('position') || 'bottom'
  38886. }, {isRectText: true, useInsideStyle: false});
  38887. if (circle.__mapOriginalZ2 != null) {
  38888. circle.z2 = circle.__mapOriginalZ2;
  38889. circle.__mapOriginalZ2 = null;
  38890. }
  38891. };
  38892. polygonGroups.on('mouseover', onEmphasis)
  38893. .on('mouseout', onNormal)
  38894. .on('emphasis', onEmphasis)
  38895. .on('normal', onNormal);
  38896. onNormal();
  38897. }
  38898. group.add(circle);
  38899. });
  38900. }
  38901. });
  38902. /*
  38903. * Licensed to the Apache Software Foundation (ASF) under one
  38904. * or more contributor license agreements. See the NOTICE file
  38905. * distributed with this work for additional information
  38906. * regarding copyright ownership. The ASF licenses this file
  38907. * to you under the Apache License, Version 2.0 (the
  38908. * "License"); you may not use this file except in compliance
  38909. * with the License. You may obtain a copy of the License at
  38910. *
  38911. * http://www.apache.org/licenses/LICENSE-2.0
  38912. *
  38913. * Unless required by applicable law or agreed to in writing,
  38914. * software distributed under the License is distributed on an
  38915. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38916. * KIND, either express or implied. See the License for the
  38917. * specific language governing permissions and limitations
  38918. * under the License.
  38919. */
  38920. /**
  38921. * @param {module:echarts/coord/View} view
  38922. * @param {Object} payload
  38923. * @param {Object} [zoomLimit]
  38924. */
  38925. function updateCenterAndZoom(
  38926. view, payload, zoomLimit
  38927. ) {
  38928. var previousZoom = view.getZoom();
  38929. var center = view.getCenter();
  38930. var zoom = payload.zoom;
  38931. var point = view.dataToPoint(center);
  38932. if (payload.dx != null && payload.dy != null) {
  38933. point[0] -= payload.dx;
  38934. point[1] -= payload.dy;
  38935. var center = view.pointToData(point);
  38936. view.setCenter(center);
  38937. }
  38938. if (zoom != null) {
  38939. if (zoomLimit) {
  38940. var zoomMin = zoomLimit.min || 0;
  38941. var zoomMax = zoomLimit.max || Infinity;
  38942. zoom = Math.max(
  38943. Math.min(previousZoom * zoom, zoomMax),
  38944. zoomMin
  38945. ) / previousZoom;
  38946. }
  38947. // Zoom on given point(originX, originY)
  38948. view.scale[0] *= zoom;
  38949. view.scale[1] *= zoom;
  38950. var position = view.position;
  38951. var fixX = (payload.originX - position[0]) * (zoom - 1);
  38952. var fixY = (payload.originY - position[1]) * (zoom - 1);
  38953. position[0] -= fixX;
  38954. position[1] -= fixY;
  38955. view.updateTransform();
  38956. // Get the new center
  38957. var center = view.pointToData(point);
  38958. view.setCenter(center);
  38959. view.setZoom(zoom * previousZoom);
  38960. }
  38961. return {
  38962. center: view.getCenter(),
  38963. zoom: view.getZoom()
  38964. };
  38965. }
  38966. /*
  38967. * Licensed to the Apache Software Foundation (ASF) under one
  38968. * or more contributor license agreements. See the NOTICE file
  38969. * distributed with this work for additional information
  38970. * regarding copyright ownership. The ASF licenses this file
  38971. * to you under the Apache License, Version 2.0 (the
  38972. * "License"); you may not use this file except in compliance
  38973. * with the License. You may obtain a copy of the License at
  38974. *
  38975. * http://www.apache.org/licenses/LICENSE-2.0
  38976. *
  38977. * Unless required by applicable law or agreed to in writing,
  38978. * software distributed under the License is distributed on an
  38979. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38980. * KIND, either express or implied. See the License for the
  38981. * specific language governing permissions and limitations
  38982. * under the License.
  38983. */
  38984. /**
  38985. * @payload
  38986. * @property {string} [componentType=series]
  38987. * @property {number} [dx]
  38988. * @property {number} [dy]
  38989. * @property {number} [zoom]
  38990. * @property {number} [originX]
  38991. * @property {number} [originY]
  38992. */
  38993. registerAction({
  38994. type: 'geoRoam',
  38995. event: 'geoRoam',
  38996. update: 'updateTransform'
  38997. }, function (payload, ecModel) {
  38998. var componentType = payload.componentType || 'series';
  38999. ecModel.eachComponent(
  39000. { mainType: componentType, query: payload },
  39001. function (componentModel) {
  39002. var geo = componentModel.coordinateSystem;
  39003. if (geo.type !== 'geo') {
  39004. return;
  39005. }
  39006. var res = updateCenterAndZoom(
  39007. geo, payload, componentModel.get('scaleLimit')
  39008. );
  39009. componentModel.setCenter
  39010. && componentModel.setCenter(res.center);
  39011. componentModel.setZoom
  39012. && componentModel.setZoom(res.zoom);
  39013. // All map series with same `map` use the same geo coordinate system
  39014. // So the center and zoom must be in sync. Include the series not selected by legend
  39015. if (componentType === 'series') {
  39016. each$1(componentModel.seriesGroup, function (seriesModel) {
  39017. seriesModel.setCenter(res.center);
  39018. seriesModel.setZoom(res.zoom);
  39019. });
  39020. }
  39021. }
  39022. );
  39023. });
  39024. /*
  39025. * Licensed to the Apache Software Foundation (ASF) under one
  39026. * or more contributor license agreements. See the NOTICE file
  39027. * distributed with this work for additional information
  39028. * regarding copyright ownership. The ASF licenses this file
  39029. * to you under the Apache License, Version 2.0 (the
  39030. * "License"); you may not use this file except in compliance
  39031. * with the License. You may obtain a copy of the License at
  39032. *
  39033. * http://www.apache.org/licenses/LICENSE-2.0
  39034. *
  39035. * Unless required by applicable law or agreed to in writing,
  39036. * software distributed under the License is distributed on an
  39037. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39038. * KIND, either express or implied. See the License for the
  39039. * specific language governing permissions and limitations
  39040. * under the License.
  39041. */
  39042. var mapSymbolLayout = function (ecModel) {
  39043. var processedMapType = {};
  39044. ecModel.eachSeriesByType('map', function (mapSeries) {
  39045. var mapType = mapSeries.getMapType();
  39046. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  39047. return;
  39048. }
  39049. var mapSymbolOffsets = {};
  39050. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  39051. var geo = subMapSeries.coordinateSystem;
  39052. var data = subMapSeries.originalData;
  39053. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  39054. data.each(data.mapDimension('value'), function (value, idx) {
  39055. var name = data.getName(idx);
  39056. var region = geo.getRegion(name);
  39057. // If input series.data is [11, 22, '-'/null/undefined, 44],
  39058. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  39059. // not be drawn. So here must validate if value is NaN.
  39060. if (!region || isNaN(value)) {
  39061. return;
  39062. }
  39063. var offset = mapSymbolOffsets[name] || 0;
  39064. var point = geo.dataToPoint(region.center);
  39065. mapSymbolOffsets[name] = offset + 1;
  39066. data.setItemLayout(idx, {
  39067. point: point,
  39068. offset: offset
  39069. });
  39070. });
  39071. }
  39072. });
  39073. // Show label of those region not has legendSymbol(which is offset 0)
  39074. var data = mapSeries.getData();
  39075. data.each(function (idx) {
  39076. var name = data.getName(idx);
  39077. var layout = data.getItemLayout(idx) || {};
  39078. layout.showLabel = !mapSymbolOffsets[name];
  39079. data.setItemLayout(idx, layout);
  39080. });
  39081. processedMapType[mapType] = true;
  39082. });
  39083. };
  39084. /*
  39085. * Licensed to the Apache Software Foundation (ASF) under one
  39086. * or more contributor license agreements. See the NOTICE file
  39087. * distributed with this work for additional information
  39088. * regarding copyright ownership. The ASF licenses this file
  39089. * to you under the Apache License, Version 2.0 (the
  39090. * "License"); you may not use this file except in compliance
  39091. * with the License. You may obtain a copy of the License at
  39092. *
  39093. * http://www.apache.org/licenses/LICENSE-2.0
  39094. *
  39095. * Unless required by applicable law or agreed to in writing,
  39096. * software distributed under the License is distributed on an
  39097. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39098. * KIND, either express or implied. See the License for the
  39099. * specific language governing permissions and limitations
  39100. * under the License.
  39101. */
  39102. var mapVisual = function (ecModel) {
  39103. ecModel.eachSeriesByType('map', function (seriesModel) {
  39104. var colorList = seriesModel.get('color');
  39105. var itemStyleModel = seriesModel.getModel('itemStyle');
  39106. var areaColor = itemStyleModel.get('areaColor');
  39107. var color = itemStyleModel.get('color')
  39108. || colorList[seriesModel.seriesIndex % colorList.length];
  39109. seriesModel.getData().setVisual({
  39110. 'areaColor': areaColor,
  39111. 'color': color
  39112. });
  39113. });
  39114. };
  39115. /*
  39116. * Licensed to the Apache Software Foundation (ASF) under one
  39117. * or more contributor license agreements. See the NOTICE file
  39118. * distributed with this work for additional information
  39119. * regarding copyright ownership. The ASF licenses this file
  39120. * to you under the Apache License, Version 2.0 (the
  39121. * "License"); you may not use this file except in compliance
  39122. * with the License. You may obtain a copy of the License at
  39123. *
  39124. * http://www.apache.org/licenses/LICENSE-2.0
  39125. *
  39126. * Unless required by applicable law or agreed to in writing,
  39127. * software distributed under the License is distributed on an
  39128. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39129. * KIND, either express or implied. See the License for the
  39130. * specific language governing permissions and limitations
  39131. * under the License.
  39132. */
  39133. // FIXME 公用?
  39134. /**
  39135. * @param {Array.<module:echarts/data/List>} datas
  39136. * @param {string} statisticType 'average' 'sum'
  39137. * @inner
  39138. */
  39139. function dataStatistics(datas, statisticType) {
  39140. var dataNameMap = {};
  39141. each$1(datas, function (data) {
  39142. data.each(data.mapDimension('value'), function (value, idx) {
  39143. // Add prefix to avoid conflict with Object.prototype.
  39144. var mapKey = 'ec-' + data.getName(idx);
  39145. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  39146. if (!isNaN(value)) {
  39147. dataNameMap[mapKey].push(value);
  39148. }
  39149. });
  39150. });
  39151. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  39152. var mapKey = 'ec-' + datas[0].getName(idx);
  39153. var sum = 0;
  39154. var min = Infinity;
  39155. var max = -Infinity;
  39156. var len = dataNameMap[mapKey].length;
  39157. for (var i = 0; i < len; i++) {
  39158. min = Math.min(min, dataNameMap[mapKey][i]);
  39159. max = Math.max(max, dataNameMap[mapKey][i]);
  39160. sum += dataNameMap[mapKey][i];
  39161. }
  39162. var result;
  39163. if (statisticType === 'min') {
  39164. result = min;
  39165. }
  39166. else if (statisticType === 'max') {
  39167. result = max;
  39168. }
  39169. else if (statisticType === 'average') {
  39170. result = sum / len;
  39171. }
  39172. else {
  39173. result = sum;
  39174. }
  39175. return len === 0 ? NaN : result;
  39176. });
  39177. }
  39178. var mapDataStatistic = function (ecModel) {
  39179. var seriesGroups = {};
  39180. ecModel.eachSeriesByType('map', function (seriesModel) {
  39181. var hostGeoModel = seriesModel.getHostGeoModel();
  39182. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  39183. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  39184. });
  39185. each$1(seriesGroups, function (seriesList, key) {
  39186. var data = dataStatistics(
  39187. map(seriesList, function (seriesModel) {
  39188. return seriesModel.getData();
  39189. }),
  39190. seriesList[0].get('mapValueCalculation')
  39191. );
  39192. for (var i = 0; i < seriesList.length; i++) {
  39193. seriesList[i].originalData = seriesList[i].getData();
  39194. }
  39195. // FIXME Put where?
  39196. for (var i = 0; i < seriesList.length; i++) {
  39197. seriesList[i].seriesGroup = seriesList;
  39198. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  39199. seriesList[i].setData(data.cloneShallow());
  39200. seriesList[i].mainSeries = seriesList[0];
  39201. }
  39202. });
  39203. };
  39204. /*
  39205. * Licensed to the Apache Software Foundation (ASF) under one
  39206. * or more contributor license agreements. See the NOTICE file
  39207. * distributed with this work for additional information
  39208. * regarding copyright ownership. The ASF licenses this file
  39209. * to you under the Apache License, Version 2.0 (the
  39210. * "License"); you may not use this file except in compliance
  39211. * with the License. You may obtain a copy of the License at
  39212. *
  39213. * http://www.apache.org/licenses/LICENSE-2.0
  39214. *
  39215. * Unless required by applicable law or agreed to in writing,
  39216. * software distributed under the License is distributed on an
  39217. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39218. * KIND, either express or implied. See the License for the
  39219. * specific language governing permissions and limitations
  39220. * under the License.
  39221. */
  39222. var backwardCompat$2 = function (option) {
  39223. // Save geoCoord
  39224. var mapSeries = [];
  39225. each$1(option.series, function (seriesOpt) {
  39226. if (seriesOpt && seriesOpt.type === 'map') {
  39227. mapSeries.push(seriesOpt);
  39228. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  39229. // Put x, y, width, height, x2, y2 in the top level
  39230. defaults(seriesOpt, seriesOpt.mapLocation);
  39231. }
  39232. });
  39233. };
  39234. /*
  39235. * Licensed to the Apache Software Foundation (ASF) under one
  39236. * or more contributor license agreements. See the NOTICE file
  39237. * distributed with this work for additional information
  39238. * regarding copyright ownership. The ASF licenses this file
  39239. * to you under the Apache License, Version 2.0 (the
  39240. * "License"); you may not use this file except in compliance
  39241. * with the License. You may obtain a copy of the License at
  39242. *
  39243. * http://www.apache.org/licenses/LICENSE-2.0
  39244. *
  39245. * Unless required by applicable law or agreed to in writing,
  39246. * software distributed under the License is distributed on an
  39247. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39248. * KIND, either express or implied. See the License for the
  39249. * specific language governing permissions and limitations
  39250. * under the License.
  39251. */
  39252. registerLayout(mapSymbolLayout);
  39253. registerVisual(mapVisual);
  39254. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  39255. registerPreprocessor(backwardCompat$2);
  39256. createDataSelectAction('map', [{
  39257. type: 'mapToggleSelect',
  39258. event: 'mapselectchanged',
  39259. method: 'toggleSelected'
  39260. }, {
  39261. type: 'mapSelect',
  39262. event: 'mapselected',
  39263. method: 'select'
  39264. }, {
  39265. type: 'mapUnSelect',
  39266. event: 'mapunselected',
  39267. method: 'unSelect'
  39268. }]);
  39269. /*
  39270. * Licensed to the Apache Software Foundation (ASF) under one
  39271. * or more contributor license agreements. See the NOTICE file
  39272. * distributed with this work for additional information
  39273. * regarding copyright ownership. The ASF licenses this file
  39274. * to you under the Apache License, Version 2.0 (the
  39275. * "License"); you may not use this file except in compliance
  39276. * with the License. You may obtain a copy of the License at
  39277. *
  39278. * http://www.apache.org/licenses/LICENSE-2.0
  39279. *
  39280. * Unless required by applicable law or agreed to in writing,
  39281. * software distributed under the License is distributed on an
  39282. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39283. * KIND, either express or implied. See the License for the
  39284. * specific language governing permissions and limitations
  39285. * under the License.
  39286. */
  39287. /**
  39288. * Link lists and struct (graph or tree)
  39289. */
  39290. var each$7 = each$1;
  39291. var DATAS = '\0__link_datas';
  39292. var MAIN_DATA = '\0__link_mainData';
  39293. // Caution:
  39294. // In most case, either list or its shallow clones (see list.cloneShallow)
  39295. // is active in echarts process. So considering heap memory consumption,
  39296. // we do not clone tree or graph, but share them among list and its shallow clones.
  39297. // But in some rare case, we have to keep old list (like do animation in chart). So
  39298. // please take care that both the old list and the new list share the same tree/graph.
  39299. /**
  39300. * @param {Object} opt
  39301. * @param {module:echarts/data/List} opt.mainData
  39302. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  39303. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  39304. * @param {Object} [opt.datas] {dataType: data},
  39305. * like: {node: nodeList, edge: edgeList}.
  39306. * Should contain mainData.
  39307. * @param {Object} [opt.datasAttr] {dataType: attr},
  39308. * designation: struct[datasAttr[dataType]] = list;
  39309. */
  39310. function linkList(opt) {
  39311. var mainData = opt.mainData;
  39312. var datas = opt.datas;
  39313. if (!datas) {
  39314. datas = {main: mainData};
  39315. opt.datasAttr = {main: 'data'};
  39316. }
  39317. opt.datas = opt.mainData = null;
  39318. linkAll(mainData, datas, opt);
  39319. // Porxy data original methods.
  39320. each$7(datas, function (data) {
  39321. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  39322. data.wrapMethod(methodName, curry(transferInjection, opt));
  39323. });
  39324. });
  39325. // Beyond transfer, additional features should be added to `cloneShallow`.
  39326. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  39327. // Only mainData trigger change, because struct.update may trigger
  39328. // another changable methods, which may bring about dead lock.
  39329. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  39330. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  39331. });
  39332. // Make sure datas contains mainData.
  39333. assert$1(datas[mainData.dataType] === mainData);
  39334. }
  39335. function transferInjection(opt, res) {
  39336. if (isMainData(this)) {
  39337. // Transfer datas to new main data.
  39338. var datas = extend({}, this[DATAS]);
  39339. datas[this.dataType] = res;
  39340. linkAll(res, datas, opt);
  39341. }
  39342. else {
  39343. // Modify the reference in main data to point newData.
  39344. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  39345. }
  39346. return res;
  39347. }
  39348. function changeInjection(opt, res) {
  39349. opt.struct && opt.struct.update(this);
  39350. return res;
  39351. }
  39352. function cloneShallowInjection(opt, res) {
  39353. // cloneShallow, which brings about some fragilities, may be inappropriate
  39354. // to be exposed as an API. So for implementation simplicity we can make
  39355. // the restriction that cloneShallow of not-mainData should not be invoked
  39356. // outside, but only be invoked here.
  39357. each$7(res[DATAS], function (data, dataType) {
  39358. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  39359. });
  39360. return res;
  39361. }
  39362. /**
  39363. * Supplement method to List.
  39364. *
  39365. * @public
  39366. * @param {string} [dataType] If not specified, return mainData.
  39367. * @return {module:echarts/data/List}
  39368. */
  39369. function getLinkedData(dataType) {
  39370. var mainData = this[MAIN_DATA];
  39371. return (dataType == null || mainData == null)
  39372. ? mainData
  39373. : mainData[DATAS][dataType];
  39374. }
  39375. function isMainData(data) {
  39376. return data[MAIN_DATA] === data;
  39377. }
  39378. function linkAll(mainData, datas, opt) {
  39379. mainData[DATAS] = {};
  39380. each$7(datas, function (data, dataType) {
  39381. linkSingle(data, dataType, mainData, opt);
  39382. });
  39383. }
  39384. function linkSingle(data, dataType, mainData, opt) {
  39385. mainData[DATAS][dataType] = data;
  39386. data[MAIN_DATA] = mainData;
  39387. data.dataType = dataType;
  39388. if (opt.struct) {
  39389. data[opt.structAttr] = opt.struct;
  39390. opt.struct[opt.datasAttr[dataType]] = data;
  39391. }
  39392. // Supplement method.
  39393. data.getLinkedData = getLinkedData;
  39394. }
  39395. /*
  39396. * Licensed to the Apache Software Foundation (ASF) under one
  39397. * or more contributor license agreements. See the NOTICE file
  39398. * distributed with this work for additional information
  39399. * regarding copyright ownership. The ASF licenses this file
  39400. * to you under the Apache License, Version 2.0 (the
  39401. * "License"); you may not use this file except in compliance
  39402. * with the License. You may obtain a copy of the License at
  39403. *
  39404. * http://www.apache.org/licenses/LICENSE-2.0
  39405. *
  39406. * Unless required by applicable law or agreed to in writing,
  39407. * software distributed under the License is distributed on an
  39408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39409. * KIND, either express or implied. See the License for the
  39410. * specific language governing permissions and limitations
  39411. * under the License.
  39412. */
  39413. /**
  39414. * Tree data structure
  39415. *
  39416. * @module echarts/data/Tree
  39417. */
  39418. /**
  39419. * @constructor module:echarts/data/Tree~TreeNode
  39420. * @param {string} name
  39421. * @param {module:echarts/data/Tree} hostTree
  39422. */
  39423. var TreeNode = function (name, hostTree) {
  39424. /**
  39425. * @type {string}
  39426. */
  39427. this.name = name || '';
  39428. /**
  39429. * Depth of node
  39430. *
  39431. * @type {number}
  39432. * @readOnly
  39433. */
  39434. this.depth = 0;
  39435. /**
  39436. * Height of the subtree rooted at this node.
  39437. * @type {number}
  39438. * @readOnly
  39439. */
  39440. this.height = 0;
  39441. /**
  39442. * @type {module:echarts/data/Tree~TreeNode}
  39443. * @readOnly
  39444. */
  39445. this.parentNode = null;
  39446. /**
  39447. * Reference to list item.
  39448. * Do not persistent dataIndex outside,
  39449. * besause it may be changed by list.
  39450. * If dataIndex -1,
  39451. * this node is logical deleted (filtered) in list.
  39452. *
  39453. * @type {Object}
  39454. * @readOnly
  39455. */
  39456. this.dataIndex = -1;
  39457. /**
  39458. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  39459. * @readOnly
  39460. */
  39461. this.children = [];
  39462. /**
  39463. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  39464. * @pubilc
  39465. */
  39466. this.viewChildren = [];
  39467. /**
  39468. * @type {moduel:echarts/data/Tree}
  39469. * @readOnly
  39470. */
  39471. this.hostTree = hostTree;
  39472. };
  39473. TreeNode.prototype = {
  39474. constructor: TreeNode,
  39475. /**
  39476. * The node is removed.
  39477. * @return {boolean} is removed.
  39478. */
  39479. isRemoved: function () {
  39480. return this.dataIndex < 0;
  39481. },
  39482. /**
  39483. * Travel this subtree (include this node).
  39484. * Usage:
  39485. * node.eachNode(function () { ... }); // preorder
  39486. * node.eachNode('preorder', function () { ... }); // preorder
  39487. * node.eachNode('postorder', function () { ... }); // postorder
  39488. * node.eachNode(
  39489. * {order: 'postorder', attr: 'viewChildren'},
  39490. * function () { ... }
  39491. * ); // postorder
  39492. *
  39493. * @param {(Object|string)} options If string, means order.
  39494. * @param {string=} options.order 'preorder' or 'postorder'
  39495. * @param {string=} options.attr 'children' or 'viewChildren'
  39496. * @param {Function} cb If in preorder and return false,
  39497. * its subtree will not be visited.
  39498. * @param {Object} [context]
  39499. */
  39500. eachNode: function (options, cb, context) {
  39501. if (typeof options === 'function') {
  39502. context = cb;
  39503. cb = options;
  39504. options = null;
  39505. }
  39506. options = options || {};
  39507. if (isString(options)) {
  39508. options = {order: options};
  39509. }
  39510. var order = options.order || 'preorder';
  39511. var children = this[options.attr || 'children'];
  39512. var suppressVisitSub;
  39513. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  39514. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  39515. children[i].eachNode(options, cb, context);
  39516. }
  39517. order === 'postorder' && cb.call(context, this);
  39518. },
  39519. /**
  39520. * Update depth and height of this subtree.
  39521. *
  39522. * @param {number} depth
  39523. */
  39524. updateDepthAndHeight: function (depth) {
  39525. var height = 0;
  39526. this.depth = depth;
  39527. for (var i = 0; i < this.children.length; i++) {
  39528. var child = this.children[i];
  39529. child.updateDepthAndHeight(depth + 1);
  39530. if (child.height > height) {
  39531. height = child.height;
  39532. }
  39533. }
  39534. this.height = height + 1;
  39535. },
  39536. /**
  39537. * @param {string} id
  39538. * @return {module:echarts/data/Tree~TreeNode}
  39539. */
  39540. getNodeById: function (id) {
  39541. if (this.getId() === id) {
  39542. return this;
  39543. }
  39544. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  39545. var res = children[i].getNodeById(id);
  39546. if (res) {
  39547. return res;
  39548. }
  39549. }
  39550. },
  39551. /**
  39552. * @param {module:echarts/data/Tree~TreeNode} node
  39553. * @return {boolean}
  39554. */
  39555. contains: function (node) {
  39556. if (node === this) {
  39557. return true;
  39558. }
  39559. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  39560. var res = children[i].contains(node);
  39561. if (res) {
  39562. return res;
  39563. }
  39564. }
  39565. },
  39566. /**
  39567. * @param {boolean} includeSelf Default false.
  39568. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  39569. */
  39570. getAncestors: function (includeSelf) {
  39571. var ancestors = [];
  39572. var node = includeSelf ? this : this.parentNode;
  39573. while (node) {
  39574. ancestors.push(node);
  39575. node = node.parentNode;
  39576. }
  39577. ancestors.reverse();
  39578. return ancestors;
  39579. },
  39580. /**
  39581. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  39582. * @return {number} Value.
  39583. */
  39584. getValue: function (dimension) {
  39585. var data = this.hostTree.data;
  39586. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  39587. },
  39588. /**
  39589. * @param {Object} layout
  39590. * @param {boolean=} [merge=false]
  39591. */
  39592. setLayout: function (layout, merge$$1) {
  39593. this.dataIndex >= 0
  39594. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  39595. },
  39596. /**
  39597. * @return {Object} layout
  39598. */
  39599. getLayout: function () {
  39600. return this.hostTree.data.getItemLayout(this.dataIndex);
  39601. },
  39602. /**
  39603. * @param {string} [path]
  39604. * @return {module:echarts/model/Model}
  39605. */
  39606. getModel: function (path) {
  39607. if (this.dataIndex < 0) {
  39608. return;
  39609. }
  39610. var hostTree = this.hostTree;
  39611. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  39612. var levelModel = this.getLevelModel();
  39613. var leavesModel;
  39614. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  39615. leavesModel = this.getLeavesModel();
  39616. }
  39617. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  39618. },
  39619. /**
  39620. * @return {module:echarts/model/Model}
  39621. */
  39622. getLevelModel: function () {
  39623. return (this.hostTree.levelModels || [])[this.depth];
  39624. },
  39625. /**
  39626. * @return {module:echarts/model/Model}
  39627. */
  39628. getLeavesModel: function () {
  39629. return this.hostTree.leavesModel;
  39630. },
  39631. /**
  39632. * @example
  39633. * setItemVisual('color', color);
  39634. * setItemVisual({
  39635. * 'color': color
  39636. * });
  39637. */
  39638. setVisual: function (key, value) {
  39639. this.dataIndex >= 0
  39640. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  39641. },
  39642. /**
  39643. * Get item visual
  39644. */
  39645. getVisual: function (key, ignoreParent) {
  39646. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  39647. },
  39648. /**
  39649. * @public
  39650. * @return {number}
  39651. */
  39652. getRawIndex: function () {
  39653. return this.hostTree.data.getRawIndex(this.dataIndex);
  39654. },
  39655. /**
  39656. * @public
  39657. * @return {string}
  39658. */
  39659. getId: function () {
  39660. return this.hostTree.data.getId(this.dataIndex);
  39661. },
  39662. /**
  39663. * if this is an ancestor of another node
  39664. *
  39665. * @public
  39666. * @param {TreeNode} node another node
  39667. * @return {boolean} if is ancestor
  39668. */
  39669. isAncestorOf: function (node) {
  39670. var parent = node.parentNode;
  39671. while (parent) {
  39672. if (parent === this) {
  39673. return true;
  39674. }
  39675. parent = parent.parentNode;
  39676. }
  39677. return false;
  39678. },
  39679. /**
  39680. * if this is an descendant of another node
  39681. *
  39682. * @public
  39683. * @param {TreeNode} node another node
  39684. * @return {boolean} if is descendant
  39685. */
  39686. isDescendantOf: function (node) {
  39687. return node !== this && node.isAncestorOf(this);
  39688. }
  39689. };
  39690. /**
  39691. * @constructor
  39692. * @alias module:echarts/data/Tree
  39693. * @param {module:echarts/model/Model} hostModel
  39694. * @param {Array.<Object>} levelOptions
  39695. * @param {Object} leavesOption
  39696. */
  39697. function Tree(hostModel, levelOptions, leavesOption) {
  39698. /**
  39699. * @type {module:echarts/data/Tree~TreeNode}
  39700. * @readOnly
  39701. */
  39702. this.root;
  39703. /**
  39704. * @type {module:echarts/data/List}
  39705. * @readOnly
  39706. */
  39707. this.data;
  39708. /**
  39709. * Index of each item is the same as the raw index of coresponding list item.
  39710. * @private
  39711. * @type {Array.<module:echarts/data/Tree~TreeNode}
  39712. */
  39713. this._nodes = [];
  39714. /**
  39715. * @private
  39716. * @readOnly
  39717. * @type {module:echarts/model/Model}
  39718. */
  39719. this.hostModel = hostModel;
  39720. /**
  39721. * @private
  39722. * @readOnly
  39723. * @type {Array.<module:echarts/model/Model}
  39724. */
  39725. this.levelModels = map(levelOptions || [], function (levelDefine) {
  39726. return new Model(levelDefine, hostModel, hostModel.ecModel);
  39727. });
  39728. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  39729. }
  39730. Tree.prototype = {
  39731. constructor: Tree,
  39732. type: 'tree',
  39733. /**
  39734. * Travel this subtree (include this node).
  39735. * Usage:
  39736. * node.eachNode(function () { ... }); // preorder
  39737. * node.eachNode('preorder', function () { ... }); // preorder
  39738. * node.eachNode('postorder', function () { ... }); // postorder
  39739. * node.eachNode(
  39740. * {order: 'postorder', attr: 'viewChildren'},
  39741. * function () { ... }
  39742. * ); // postorder
  39743. *
  39744. * @param {(Object|string)} options If string, means order.
  39745. * @param {string=} options.order 'preorder' or 'postorder'
  39746. * @param {string=} options.attr 'children' or 'viewChildren'
  39747. * @param {Function} cb
  39748. * @param {Object} [context]
  39749. */
  39750. eachNode: function(options, cb, context) {
  39751. this.root.eachNode(options, cb, context);
  39752. },
  39753. /**
  39754. * @param {number} dataIndex
  39755. * @return {module:echarts/data/Tree~TreeNode}
  39756. */
  39757. getNodeByDataIndex: function (dataIndex) {
  39758. var rawIndex = this.data.getRawIndex(dataIndex);
  39759. return this._nodes[rawIndex];
  39760. },
  39761. /**
  39762. * @param {string} name
  39763. * @return {module:echarts/data/Tree~TreeNode}
  39764. */
  39765. getNodeByName: function (name) {
  39766. return this.root.getNodeByName(name);
  39767. },
  39768. /**
  39769. * Update item available by list,
  39770. * when list has been performed options like 'filterSelf' or 'map'.
  39771. */
  39772. update: function () {
  39773. var data = this.data;
  39774. var nodes = this._nodes;
  39775. for (var i = 0, len = nodes.length; i < len; i++) {
  39776. nodes[i].dataIndex = -1;
  39777. }
  39778. for (var i = 0, len = data.count(); i < len; i++) {
  39779. nodes[data.getRawIndex(i)].dataIndex = i;
  39780. }
  39781. },
  39782. /**
  39783. * Clear all layouts
  39784. */
  39785. clearLayouts: function () {
  39786. this.data.clearItemLayouts();
  39787. }
  39788. };
  39789. /**
  39790. * data node format:
  39791. * {
  39792. * name: ...
  39793. * value: ...
  39794. * children: [
  39795. * {
  39796. * name: ...
  39797. * value: ...
  39798. * children: ...
  39799. * },
  39800. * ...
  39801. * ]
  39802. * }
  39803. *
  39804. * @static
  39805. * @param {Object} dataRoot Root node.
  39806. * @param {module:echarts/model/Model} hostModel
  39807. * @param {Object} treeOptions
  39808. * @param {Array.<Object>} treeOptions.levels
  39809. * @param {Array.<Object>} treeOptions.leaves
  39810. * @return module:echarts/data/Tree
  39811. */
  39812. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  39813. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  39814. var listData = [];
  39815. var dimMax = 1;
  39816. buildHierarchy(dataRoot);
  39817. function buildHierarchy(dataNode, parentNode) {
  39818. var value = dataNode.value;
  39819. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  39820. listData.push(dataNode);
  39821. var node = new TreeNode(dataNode.name, tree);
  39822. parentNode
  39823. ? addChild(node, parentNode)
  39824. : (tree.root = node);
  39825. tree._nodes.push(node);
  39826. var children = dataNode.children;
  39827. if (children) {
  39828. for (var i = 0; i < children.length; i++) {
  39829. buildHierarchy(children[i], node);
  39830. }
  39831. }
  39832. }
  39833. tree.root.updateDepthAndHeight(0);
  39834. var dimensionsInfo = createDimensions(listData, {
  39835. coordDimensions: ['value'],
  39836. dimensionsCount: dimMax
  39837. });
  39838. var list = new List(dimensionsInfo, hostModel);
  39839. list.initData(listData);
  39840. linkList({
  39841. mainData: list,
  39842. struct: tree,
  39843. structAttr: 'tree'
  39844. });
  39845. tree.update();
  39846. return tree;
  39847. };
  39848. /**
  39849. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  39850. * so this function is not ready and not necessary to be public.
  39851. *
  39852. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  39853. */
  39854. function addChild(child, node) {
  39855. var children = node.children;
  39856. if (child.parentNode === node) {
  39857. return;
  39858. }
  39859. children.push(child);
  39860. child.parentNode = node;
  39861. }
  39862. /*
  39863. * Licensed to the Apache Software Foundation (ASF) under one
  39864. * or more contributor license agreements. See the NOTICE file
  39865. * distributed with this work for additional information
  39866. * regarding copyright ownership. The ASF licenses this file
  39867. * to you under the Apache License, Version 2.0 (the
  39868. * "License"); you may not use this file except in compliance
  39869. * with the License. You may obtain a copy of the License at
  39870. *
  39871. * http://www.apache.org/licenses/LICENSE-2.0
  39872. *
  39873. * Unless required by applicable law or agreed to in writing,
  39874. * software distributed under the License is distributed on an
  39875. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39876. * KIND, either express or implied. See the License for the
  39877. * specific language governing permissions and limitations
  39878. * under the License.
  39879. */
  39880. /**
  39881. * @file Create data struct and define tree view's series model
  39882. */
  39883. SeriesModel.extend({
  39884. type: 'series.tree',
  39885. layoutInfo: null,
  39886. // can support the position parameters 'left', 'top','right','bottom', 'width',
  39887. // 'height' in the setOption() with 'merge' mode normal.
  39888. layoutMode: 'box',
  39889. /**
  39890. * Init a tree data structure from data in option series
  39891. * @param {Object} option the object used to config echarts view
  39892. * @return {module:echarts/data/List} storage initial data
  39893. */
  39894. getInitialData: function (option) {
  39895. //create an virtual root
  39896. var root = {name: option.name, children: option.data};
  39897. var leaves = option.leaves || {};
  39898. var treeOption = {};
  39899. treeOption.leaves = leaves;
  39900. var tree = Tree.createTree(root, this, treeOption);
  39901. var treeDepth = 0;
  39902. tree.eachNode('preorder', function (node) {
  39903. if (node.depth > treeDepth) {
  39904. treeDepth = node.depth;
  39905. }
  39906. });
  39907. var expandAndCollapse = option.expandAndCollapse;
  39908. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  39909. ? option.initialTreeDepth : treeDepth;
  39910. tree.root.eachNode('preorder', function (node) {
  39911. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  39912. // add item.collapsed != null, because users can collapse node original in the series.data.
  39913. node.isExpand = (item && item.collapsed != null)
  39914. ? !item.collapsed
  39915. : node.depth <= expandTreeDepth;
  39916. });
  39917. return tree.data;
  39918. },
  39919. /**
  39920. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  39921. * @returns {string} orient
  39922. */
  39923. getOrient: function () {
  39924. var orient = this.get('orient');
  39925. if (orient === 'horizontal') {
  39926. orient = 'LR';
  39927. }
  39928. else if (orient === 'vertical') {
  39929. orient = 'TB';
  39930. }
  39931. return orient;
  39932. },
  39933. /**
  39934. * @override
  39935. * @param {number} dataIndex
  39936. */
  39937. formatTooltip: function (dataIndex) {
  39938. var tree = this.getData().tree;
  39939. var realRoot = tree.root.children[0];
  39940. var node = tree.getNodeByDataIndex(dataIndex);
  39941. var value = node.getValue();
  39942. var name = node.name;
  39943. while (node && (node !== realRoot)) {
  39944. name = node.parentNode.name + '.' + name;
  39945. node = node.parentNode;
  39946. }
  39947. return encodeHTML(name + (
  39948. (isNaN(value) || value == null) ? '' : ' : ' + value
  39949. ));
  39950. },
  39951. defaultOption: {
  39952. zlevel: 0,
  39953. z: 2,
  39954. // the position of the whole view
  39955. left: '12%',
  39956. top: '12%',
  39957. right: '12%',
  39958. bottom: '12%',
  39959. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  39960. layout: 'orthogonal',
  39961. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  39962. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  39963. orient: 'LR',
  39964. symbol: 'emptyCircle',
  39965. symbolSize: 7,
  39966. expandAndCollapse: true,
  39967. initialTreeDepth: 2,
  39968. lineStyle: {
  39969. color: '#ccc',
  39970. width: 1.5,
  39971. curveness: 0.5
  39972. },
  39973. itemStyle: {
  39974. color: 'lightsteelblue',
  39975. borderColor: '#c23531',
  39976. borderWidth: 1.5
  39977. },
  39978. label: {
  39979. show: true,
  39980. color: '#555'
  39981. },
  39982. leaves: {
  39983. label: {
  39984. show: true
  39985. }
  39986. },
  39987. animationEasing: 'linear',
  39988. animationDuration: 700,
  39989. animationDurationUpdate: 1000
  39990. }
  39991. });
  39992. /*
  39993. * Licensed to the Apache Software Foundation (ASF) under one
  39994. * or more contributor license agreements. See the NOTICE file
  39995. * distributed with this work for additional information
  39996. * regarding copyright ownership. The ASF licenses this file
  39997. * to you under the Apache License, Version 2.0 (the
  39998. * "License"); you may not use this file except in compliance
  39999. * with the License. You may obtain a copy of the License at
  40000. *
  40001. * http://www.apache.org/licenses/LICENSE-2.0
  40002. *
  40003. * Unless required by applicable law or agreed to in writing,
  40004. * software distributed under the License is distributed on an
  40005. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40006. * KIND, either express or implied. See the License for the
  40007. * specific language governing permissions and limitations
  40008. * under the License.
  40009. */
  40010. /*
  40011. * The tree layout implementation references to d3.js
  40012. * (https://github.com/d3/d3-hierarchy). The use of the source
  40013. * code of this file is also subject to the terms and consitions
  40014. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  40015. */
  40016. /**
  40017. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  40018. * the tree.
  40019. * @see https://github.com/d3/d3-hierarchy
  40020. */
  40021. /**
  40022. * Initialize all computational message for following algorithm
  40023. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  40024. */
  40025. function init$2(root) {
  40026. root.hierNode = {
  40027. defaultAncestor: null,
  40028. ancestor: root,
  40029. prelim: 0,
  40030. modifier: 0,
  40031. change: 0,
  40032. shift: 0,
  40033. i: 0,
  40034. thread: null
  40035. };
  40036. var nodes = [root];
  40037. var node;
  40038. var children;
  40039. while (node = nodes.pop()) { // jshint ignore:line
  40040. children = node.children;
  40041. if (node.isExpand && children.length) {
  40042. var n = children.length;
  40043. for (var i = n - 1; i >= 0; i--) {
  40044. var child = children[i];
  40045. child.hierNode = {
  40046. defaultAncestor: null,
  40047. ancestor: child,
  40048. prelim: 0,
  40049. modifier: 0,
  40050. change: 0,
  40051. shift: 0,
  40052. i: i,
  40053. thread: null
  40054. };
  40055. nodes.push(child);
  40056. }
  40057. }
  40058. }
  40059. }
  40060. /**
  40061. * Computes a preliminary x coordinate for node. Before that, this function is
  40062. * applied recursively to the children of node, as well as the function
  40063. * apportion(). After spacing out the children by calling executeShifts(), the
  40064. * node is placed to the midpoint of its outermost children.
  40065. * @param {module:echarts/data/Tree~TreeNode} node
  40066. * @param {Function} separation
  40067. */
  40068. function firstWalk(node, separation) {
  40069. var children = node.isExpand ? node.children : [];
  40070. var siblings = node.parentNode.children;
  40071. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i -1] : null;
  40072. if (children.length) {
  40073. executeShifts(node);
  40074. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  40075. if (subtreeW) {
  40076. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  40077. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  40078. }
  40079. else {
  40080. node.hierNode.prelim = midPoint;
  40081. }
  40082. }
  40083. else if (subtreeW) {
  40084. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  40085. }
  40086. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  40087. }
  40088. /**
  40089. * Computes all real x-coordinates by summing up the modifiers recursively.
  40090. * @param {module:echarts/data/Tree~TreeNode} node
  40091. */
  40092. function secondWalk(node) {
  40093. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  40094. node.setLayout({x: nodeX}, true);
  40095. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  40096. }
  40097. function separation(cb) {
  40098. return arguments.length ? cb : defaultSeparation;
  40099. }
  40100. /**
  40101. * Transform the common coordinate to radial coordinate
  40102. * @param {number} x
  40103. * @param {number} y
  40104. * @return {Object}
  40105. */
  40106. function radialCoordinate(x, y) {
  40107. var radialCoor = {};
  40108. x -= Math.PI / 2;
  40109. radialCoor.x = y * Math.cos(x);
  40110. radialCoor.y = y * Math.sin(x);
  40111. return radialCoor;
  40112. }
  40113. /**
  40114. * Get the layout position of the whole view
  40115. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  40116. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  40117. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  40118. */
  40119. function getViewRect(seriesModel, api) {
  40120. return getLayoutRect(
  40121. seriesModel.getBoxLayoutParams(), {
  40122. width: api.getWidth(),
  40123. height: api.getHeight()
  40124. }
  40125. );
  40126. }
  40127. /**
  40128. * All other shifts, applied to the smaller subtrees between w- and w+, are
  40129. * performed by this function.
  40130. * @param {module:echarts/data/Tree~TreeNode} node
  40131. */
  40132. function executeShifts(node) {
  40133. var children = node.children;
  40134. var n = children.length;
  40135. var shift = 0;
  40136. var change = 0;
  40137. while (--n >= 0) {
  40138. var child = children[n];
  40139. child.hierNode.prelim += shift;
  40140. child.hierNode.modifier += shift;
  40141. change += child.hierNode.change;
  40142. shift += child.hierNode.shift + change;
  40143. }
  40144. }
  40145. /**
  40146. * The core of the algorithm. Here, a new subtree is combined with the
  40147. * previous subtrees. Threads are used to traverse the inside and outside
  40148. * contours of the left and right subtree up to the highest common level.
  40149. * Whenever two nodes of the inside contours conflict, we compute the left
  40150. * one of the greatest uncommon ancestors using the function nextAncestor()
  40151. * and call moveSubtree() to shift the subtree and prepare the shifts of
  40152. * smaller subtrees. Finally, we add a new thread (if necessary).
  40153. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  40154. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  40155. * @param {module:echarts/data/Tree~TreeNode} ancestor
  40156. * @param {Function} separation
  40157. * @return {module:echarts/data/Tree~TreeNode}
  40158. */
  40159. function apportion(subtreeV, subtreeW, ancestor, separation) {
  40160. if (subtreeW) {
  40161. var nodeOutRight = subtreeV;
  40162. var nodeInRight = subtreeV;
  40163. var nodeOutLeft = nodeInRight.parentNode.children[0];
  40164. var nodeInLeft = subtreeW;
  40165. var sumOutRight = nodeOutRight.hierNode.modifier;
  40166. var sumInRight = nodeInRight.hierNode.modifier;
  40167. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  40168. var sumInLeft = nodeInLeft.hierNode.modifier;
  40169. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  40170. nodeOutRight = nextRight(nodeOutRight);
  40171. nodeOutLeft = nextLeft(nodeOutLeft);
  40172. nodeOutRight.hierNode.ancestor = subtreeV;
  40173. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  40174. - sumInRight + separation(nodeInLeft, nodeInRight);
  40175. if (shift > 0) {
  40176. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  40177. sumInRight += shift;
  40178. sumOutRight += shift;
  40179. }
  40180. sumInLeft += nodeInLeft.hierNode.modifier;
  40181. sumInRight += nodeInRight.hierNode.modifier;
  40182. sumOutRight += nodeOutRight.hierNode.modifier;
  40183. sumOutLeft += nodeOutLeft.hierNode.modifier;
  40184. }
  40185. if (nodeInLeft && !nextRight(nodeOutRight)) {
  40186. nodeOutRight.hierNode.thread = nodeInLeft;
  40187. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  40188. }
  40189. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  40190. nodeOutLeft.hierNode.thread = nodeInRight;
  40191. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  40192. ancestor = subtreeV;
  40193. }
  40194. }
  40195. return ancestor;
  40196. }
  40197. /**
  40198. * This function is used to traverse the right contour of a subtree.
  40199. * It returns the rightmost child of node or the thread of node. The function
  40200. * returns null if and only if node is on the highest depth of its subtree.
  40201. * @param {module:echarts/data/Tree~TreeNode} node
  40202. * @return {module:echarts/data/Tree~TreeNode}
  40203. */
  40204. function nextRight(node) {
  40205. var children = node.children;
  40206. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  40207. }
  40208. /**
  40209. * This function is used to traverse the left contour of a subtree (or a subforest).
  40210. * It returns the leftmost child of node or the thread of node. The function
  40211. * returns null if and only if node is on the highest depth of its subtree.
  40212. * @param {module:echarts/data/Tree~TreeNode} node
  40213. * @return {module:echarts/data/Tree~TreeNode}
  40214. */
  40215. function nextLeft(node) {
  40216. var children = node.children;
  40217. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  40218. }
  40219. /**
  40220. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  40221. * Otherwise, returns the specified ancestor.
  40222. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  40223. * @param {module:echarts/data/Tree~TreeNode} node
  40224. * @param {module:echarts/data/Tree~TreeNode} ancestor
  40225. * @return {module:echarts/data/Tree~TreeNode}
  40226. */
  40227. function nextAncestor(nodeInLeft, node, ancestor) {
  40228. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  40229. ? nodeInLeft.hierNode.ancestor : ancestor;
  40230. }
  40231. /**
  40232. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  40233. * @param {module:echarts/data/Tree~TreeNode} wl
  40234. * @param {module:echarts/data/Tree~TreeNode} wr
  40235. * @param {number} shift [description]
  40236. */
  40237. function moveSubtree(wl, wr,shift) {
  40238. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  40239. wr.hierNode.change -= change;
  40240. wr.hierNode.shift += shift;
  40241. wr.hierNode.modifier += shift;
  40242. wr.hierNode.prelim += shift;
  40243. wl.hierNode.change += change;
  40244. }
  40245. function defaultSeparation(node1, node2) {
  40246. return node1.parentNode === node2.parentNode ? 1 : 2;
  40247. }
  40248. /*
  40249. * Licensed to the Apache Software Foundation (ASF) under one
  40250. * or more contributor license agreements. See the NOTICE file
  40251. * distributed with this work for additional information
  40252. * regarding copyright ownership. The ASF licenses this file
  40253. * to you under the Apache License, Version 2.0 (the
  40254. * "License"); you may not use this file except in compliance
  40255. * with the License. You may obtain a copy of the License at
  40256. *
  40257. * http://www.apache.org/licenses/LICENSE-2.0
  40258. *
  40259. * Unless required by applicable law or agreed to in writing,
  40260. * software distributed under the License is distributed on an
  40261. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40262. * KIND, either express or implied. See the License for the
  40263. * specific language governing permissions and limitations
  40264. * under the License.
  40265. */
  40266. /**
  40267. * @file This file used to draw tree view
  40268. */
  40269. extendChartView({
  40270. type: 'tree',
  40271. /**
  40272. * Init the chart
  40273. * @override
  40274. * @param {module:echarts/model/Global} ecModel
  40275. * @param {module:echarts/ExtensionAPI} api
  40276. */
  40277. init: function (ecModel, api) {
  40278. /**
  40279. * @private
  40280. * @type {module:echarts/data/Tree}
  40281. */
  40282. this._oldTree;
  40283. /**
  40284. * @private
  40285. * @type {module:zrender/container/Group}
  40286. */
  40287. this._mainGroup = new Group();
  40288. this.group.add(this._mainGroup);
  40289. },
  40290. render: function (seriesModel, ecModel, api, payload) {
  40291. var data = seriesModel.getData();
  40292. var layoutInfo = seriesModel.layoutInfo;
  40293. var group = this._mainGroup;
  40294. var layout = seriesModel.get('layout');
  40295. if (layout === 'radial') {
  40296. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  40297. }
  40298. else {
  40299. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  40300. }
  40301. var oldData = this._data;
  40302. var seriesScope = {
  40303. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  40304. layout: layout,
  40305. orient: seriesModel.getOrient(),
  40306. curvature: seriesModel.get('lineStyle.curveness'),
  40307. symbolRotate: seriesModel.get('symbolRotate'),
  40308. symbolOffset: seriesModel.get('symbolOffset'),
  40309. hoverAnimation: seriesModel.get('hoverAnimation'),
  40310. useNameLabel: true,
  40311. fadeIn: true
  40312. };
  40313. data.diff(oldData)
  40314. .add(function (newIdx) {
  40315. if (symbolNeedsDraw$1(data, newIdx)) {
  40316. // create node and edge
  40317. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  40318. }
  40319. })
  40320. .update(function (newIdx, oldIdx) {
  40321. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  40322. if (!symbolNeedsDraw$1(data, newIdx)) {
  40323. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  40324. return;
  40325. }
  40326. // update node and edge
  40327. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  40328. })
  40329. .remove(function (oldIdx) {
  40330. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  40331. // When remove a collapsed node of subtree, since the collapsed
  40332. // node haven't been initialized with a symbol element,
  40333. // you can't found it's symbol element through index.
  40334. // so if we want to remove the symbol element we should insure
  40335. // that the symbol element is not null.
  40336. if (symbolEl) {
  40337. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  40338. }
  40339. })
  40340. .execute();
  40341. if (seriesScope.expandAndCollapse === true) {
  40342. data.eachItemGraphicEl(function (el, dataIndex) {
  40343. el.off('click').on('click', function () {
  40344. api.dispatchAction({
  40345. type: 'treeExpandAndCollapse',
  40346. seriesId: seriesModel.id,
  40347. dataIndex: dataIndex
  40348. });
  40349. });
  40350. });
  40351. }
  40352. this._data = data;
  40353. },
  40354. dispose: function () {},
  40355. remove: function () {
  40356. this._mainGroup.removeAll();
  40357. this._data = null;
  40358. }
  40359. });
  40360. function symbolNeedsDraw$1(data, dataIndex) {
  40361. var layout = data.getItemLayout(dataIndex);
  40362. return layout
  40363. && !isNaN(layout.x) && !isNaN(layout.y)
  40364. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  40365. }
  40366. function getTreeNodeStyle(node, itemModel, seriesScope) {
  40367. seriesScope.itemModel = itemModel;
  40368. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  40369. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  40370. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  40371. seriesScope.labelModel = itemModel.getModel('label');
  40372. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  40373. if (node.isExpand === false && node.children.length !== 0) {
  40374. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  40375. }
  40376. else {
  40377. seriesScope.symbolInnerColor = '#fff';
  40378. }
  40379. return seriesScope;
  40380. }
  40381. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  40382. var isInit = !symbolEl;
  40383. var node = data.tree.getNodeByDataIndex(dataIndex);
  40384. var itemModel = node.getModel();
  40385. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  40386. var virtualRoot = data.tree.root;
  40387. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  40388. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  40389. var sourceLayout = source.getLayout();
  40390. var sourceOldLayout = sourceSymbolEl
  40391. ? {
  40392. x: sourceSymbolEl.position[0],
  40393. y: sourceSymbolEl.position[1],
  40394. rawX: sourceSymbolEl.__radialOldRawX,
  40395. rawY: sourceSymbolEl.__radialOldRawY
  40396. }
  40397. : sourceLayout;
  40398. var targetLayout = node.getLayout();
  40399. if (isInit) {
  40400. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  40401. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  40402. }
  40403. else {
  40404. symbolEl.updateData(data, dataIndex, seriesScope);
  40405. }
  40406. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  40407. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  40408. symbolEl.__radialRawX = targetLayout.rawX;
  40409. symbolEl.__radialRawY = targetLayout.rawY;
  40410. group.add(symbolEl);
  40411. data.setItemGraphicEl(dataIndex, symbolEl);
  40412. updateProps(symbolEl, {
  40413. position: [targetLayout.x, targetLayout.y]
  40414. }, seriesModel);
  40415. var symbolPath = symbolEl.getSymbolPath();
  40416. if (seriesScope.layout === 'radial') {
  40417. var realRoot = virtualRoot.children[0];
  40418. var rootLayout = realRoot.getLayout();
  40419. var length = realRoot.children.length;
  40420. var rad;
  40421. var isLeft;
  40422. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  40423. var center = {};
  40424. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  40425. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  40426. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  40427. if (rad < 0) {
  40428. rad = Math.PI * 2 + rad;
  40429. }
  40430. isLeft = center.x < rootLayout.x;
  40431. if (isLeft) {
  40432. rad = rad - Math.PI;
  40433. }
  40434. }
  40435. else {
  40436. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  40437. if (rad < 0) {
  40438. rad = Math.PI * 2 + rad;
  40439. }
  40440. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  40441. isLeft = targetLayout.x < rootLayout.x;
  40442. if (isLeft) {
  40443. rad = rad - Math.PI;
  40444. }
  40445. }
  40446. else {
  40447. isLeft = targetLayout.x > rootLayout.x;
  40448. if (!isLeft) {
  40449. rad = rad - Math.PI;
  40450. }
  40451. }
  40452. }
  40453. var textPosition = isLeft ? 'left' : 'right';
  40454. symbolPath.setStyle({
  40455. textPosition: textPosition,
  40456. textRotation: -rad,
  40457. textOrigin: 'center',
  40458. verticalAlign: 'middle'
  40459. });
  40460. }
  40461. if (node.parentNode && node.parentNode !== virtualRoot) {
  40462. var edge = symbolEl.__edge;
  40463. if (!edge) {
  40464. edge = symbolEl.__edge = new BezierCurve({
  40465. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  40466. style: defaults({opacity: 0}, seriesScope.lineStyle)
  40467. });
  40468. }
  40469. updateProps(edge, {
  40470. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  40471. style: {opacity: 1}
  40472. }, seriesModel);
  40473. group.add(edge);
  40474. }
  40475. }
  40476. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  40477. var node = data.tree.getNodeByDataIndex(dataIndex);
  40478. var virtualRoot = data.tree.root;
  40479. var itemModel = node.getModel();
  40480. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  40481. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  40482. var sourceLayout;
  40483. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  40484. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  40485. }
  40486. updateProps(symbolEl, {
  40487. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  40488. }, seriesModel, function () {
  40489. group.remove(symbolEl);
  40490. data.setItemGraphicEl(dataIndex, null);
  40491. });
  40492. symbolEl.fadeOut(null, {keepLabel: true});
  40493. var edge = symbolEl.__edge;
  40494. if (edge) {
  40495. updateProps(edge, {
  40496. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  40497. style: {
  40498. opacity: 0
  40499. }
  40500. }, seriesModel, function () {
  40501. group.remove(edge);
  40502. });
  40503. }
  40504. }
  40505. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  40506. var cpx1;
  40507. var cpy1;
  40508. var cpx2;
  40509. var cpy2;
  40510. var orient = seriesScope.orient;
  40511. if (seriesScope.layout === 'radial') {
  40512. var x1 = sourceLayout.rawX;
  40513. var y1 = sourceLayout.rawY;
  40514. var x2 = targetLayout.rawX;
  40515. var y2 = targetLayout.rawY;
  40516. var radialCoor1 = radialCoordinate(x1, y1);
  40517. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  40518. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  40519. var radialCoor4 = radialCoordinate(x2, y2);
  40520. return {
  40521. x1: radialCoor1.x,
  40522. y1: radialCoor1.y,
  40523. x2: radialCoor4.x,
  40524. y2: radialCoor4.y,
  40525. cpx1: radialCoor2.x,
  40526. cpy1: radialCoor2.y,
  40527. cpx2: radialCoor3.x,
  40528. cpy2: radialCoor3.y
  40529. };
  40530. }
  40531. else {
  40532. var x1 = sourceLayout.x;
  40533. var y1 = sourceLayout.y;
  40534. var x2 = targetLayout.x;
  40535. var y2 = targetLayout.y;
  40536. if (orient === 'LR' || orient === 'RL') {
  40537. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  40538. cpy1 = y1;
  40539. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  40540. cpy2 = y2;
  40541. }
  40542. if (orient === 'TB' || orient === 'BT') {
  40543. cpx1 = x1;
  40544. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  40545. cpx2 = x2;
  40546. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  40547. }
  40548. return {
  40549. x1: x1,
  40550. y1: y1,
  40551. x2: x2,
  40552. y2: y2,
  40553. cpx1: cpx1,
  40554. cpy1: cpy1,
  40555. cpx2: cpx2,
  40556. cpy2: cpy2
  40557. };
  40558. }
  40559. }
  40560. /*
  40561. * Licensed to the Apache Software Foundation (ASF) under one
  40562. * or more contributor license agreements. See the NOTICE file
  40563. * distributed with this work for additional information
  40564. * regarding copyright ownership. The ASF licenses this file
  40565. * to you under the Apache License, Version 2.0 (the
  40566. * "License"); you may not use this file except in compliance
  40567. * with the License. You may obtain a copy of the License at
  40568. *
  40569. * http://www.apache.org/licenses/LICENSE-2.0
  40570. *
  40571. * Unless required by applicable law or agreed to in writing,
  40572. * software distributed under the License is distributed on an
  40573. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40574. * KIND, either express or implied. See the License for the
  40575. * specific language governing permissions and limitations
  40576. * under the License.
  40577. */
  40578. registerAction({
  40579. type: 'treeExpandAndCollapse',
  40580. event: 'treeExpandAndCollapse',
  40581. update: 'update'
  40582. }, function (payload, ecModel) {
  40583. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  40584. var dataIndex = payload.dataIndex;
  40585. var tree = seriesModel.getData().tree;
  40586. var node = tree.getNodeByDataIndex(dataIndex);
  40587. node.isExpand = !node.isExpand;
  40588. });
  40589. });
  40590. /*
  40591. * Licensed to the Apache Software Foundation (ASF) under one
  40592. * or more contributor license agreements. See the NOTICE file
  40593. * distributed with this work for additional information
  40594. * regarding copyright ownership. The ASF licenses this file
  40595. * to you under the Apache License, Version 2.0 (the
  40596. * "License"); you may not use this file except in compliance
  40597. * with the License. You may obtain a copy of the License at
  40598. *
  40599. * http://www.apache.org/licenses/LICENSE-2.0
  40600. *
  40601. * Unless required by applicable law or agreed to in writing,
  40602. * software distributed under the License is distributed on an
  40603. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40604. * KIND, either express or implied. See the License for the
  40605. * specific language governing permissions and limitations
  40606. * under the License.
  40607. */
  40608. /**
  40609. * Traverse the tree from bottom to top and do something
  40610. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  40611. * @param {Function} callback
  40612. */
  40613. function eachAfter (root, callback, separation) {
  40614. var nodes = [root];
  40615. var next = [];
  40616. var node;
  40617. while (node = nodes.pop()) { // jshint ignore:line
  40618. next.push(node);
  40619. if (node.isExpand) {
  40620. var children = node.children;
  40621. if (children.length) {
  40622. for (var i = 0; i < children.length; i++) {
  40623. nodes.push(children[i]);
  40624. }
  40625. }
  40626. }
  40627. }
  40628. while (node = next.pop()) { // jshint ignore:line
  40629. callback(node, separation);
  40630. }
  40631. }
  40632. /**
  40633. * Traverse the tree from top to bottom and do something
  40634. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  40635. * @param {Function} callback
  40636. */
  40637. function eachBefore (root, callback) {
  40638. var nodes = [root];
  40639. var node;
  40640. while (node = nodes.pop()) { // jshint ignore:line
  40641. callback(node);
  40642. if (node.isExpand) {
  40643. var children = node.children;
  40644. if (children.length) {
  40645. for (var i = children.length - 1; i >= 0; i--) {
  40646. nodes.push(children[i]);
  40647. }
  40648. }
  40649. }
  40650. }
  40651. }
  40652. /*
  40653. * Licensed to the Apache Software Foundation (ASF) under one
  40654. * or more contributor license agreements. See the NOTICE file
  40655. * distributed with this work for additional information
  40656. * regarding copyright ownership. The ASF licenses this file
  40657. * to you under the Apache License, Version 2.0 (the
  40658. * "License"); you may not use this file except in compliance
  40659. * with the License. You may obtain a copy of the License at
  40660. *
  40661. * http://www.apache.org/licenses/LICENSE-2.0
  40662. *
  40663. * Unless required by applicable law or agreed to in writing,
  40664. * software distributed under the License is distributed on an
  40665. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40666. * KIND, either express or implied. See the License for the
  40667. * specific language governing permissions and limitations
  40668. * under the License.
  40669. */
  40670. var treeLayout = function (ecModel, api) {
  40671. ecModel.eachSeriesByType('tree', function (seriesModel) {
  40672. commonLayout(seriesModel, api);
  40673. });
  40674. };
  40675. function commonLayout(seriesModel, api) {
  40676. var layoutInfo = getViewRect(seriesModel, api);
  40677. seriesModel.layoutInfo = layoutInfo;
  40678. var layout = seriesModel.get('layout');
  40679. var width = 0;
  40680. var height = 0;
  40681. var separation$$1 = null;
  40682. if (layout === 'radial') {
  40683. width = 2 * Math.PI;
  40684. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  40685. separation$$1 = separation(function (node1, node2) {
  40686. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  40687. });
  40688. }
  40689. else {
  40690. width = layoutInfo.width;
  40691. height = layoutInfo.height;
  40692. separation$$1 = separation();
  40693. }
  40694. var virtualRoot = seriesModel.getData().tree.root;
  40695. var realRoot = virtualRoot.children[0];
  40696. if (realRoot) {
  40697. init$2(virtualRoot);
  40698. eachAfter(realRoot, firstWalk, separation$$1);
  40699. virtualRoot.hierNode.modifier = - realRoot.hierNode.prelim;
  40700. eachBefore(realRoot, secondWalk);
  40701. var left = realRoot;
  40702. var right = realRoot;
  40703. var bottom = realRoot;
  40704. eachBefore(realRoot, function (node) {
  40705. var x = node.getLayout().x;
  40706. if (x < left.getLayout().x) {
  40707. left = node;
  40708. }
  40709. if (x > right.getLayout().x) {
  40710. right = node;
  40711. }
  40712. if (node.depth > bottom.depth) {
  40713. bottom = node;
  40714. }
  40715. });
  40716. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  40717. var tx = delta - left.getLayout().x;
  40718. var kx = 0;
  40719. var ky = 0;
  40720. var coorX = 0;
  40721. var coorY = 0;
  40722. if (layout === 'radial') {
  40723. kx = width / (right.getLayout().x + delta + tx);
  40724. // here we use (node.depth - 1), bucause the real root's depth is 1
  40725. ky = height / ((bottom.depth - 1) || 1);
  40726. eachBefore(realRoot, function (node) {
  40727. coorX = (node.getLayout().x + tx) * kx;
  40728. coorY = (node.depth - 1) * ky;
  40729. var finalCoor = radialCoordinate(coorX, coorY);
  40730. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  40731. });
  40732. }
  40733. else {
  40734. var orient = seriesModel.getOrient();
  40735. if (orient === 'RL' || orient === 'LR') {
  40736. ky = height / (right.getLayout().x + delta + tx);
  40737. kx = width / ((bottom.depth - 1) || 1);
  40738. eachBefore(realRoot, function (node) {
  40739. coorY = (node.getLayout().x + tx) * ky;
  40740. coorX = orient === 'LR'
  40741. ? (node.depth - 1) * kx
  40742. : width - (node.depth - 1) * kx;
  40743. node.setLayout({x: coorX, y: coorY}, true);
  40744. });
  40745. }
  40746. else if (orient === 'TB' || orient === 'BT') {
  40747. kx = width / (right.getLayout().x + delta + tx);
  40748. ky = height / ((bottom.depth - 1) || 1);
  40749. eachBefore(realRoot, function (node) {
  40750. coorX = (node.getLayout().x + tx) * kx;
  40751. coorY = orient === 'TB'
  40752. ? (node.depth - 1) * ky
  40753. : height - (node.depth - 1) * ky;
  40754. node.setLayout({x: coorX, y: coorY}, true);
  40755. });
  40756. }
  40757. }
  40758. }
  40759. }
  40760. /*
  40761. * Licensed to the Apache Software Foundation (ASF) under one
  40762. * or more contributor license agreements. See the NOTICE file
  40763. * distributed with this work for additional information
  40764. * regarding copyright ownership. The ASF licenses this file
  40765. * to you under the Apache License, Version 2.0 (the
  40766. * "License"); you may not use this file except in compliance
  40767. * with the License. You may obtain a copy of the License at
  40768. *
  40769. * http://www.apache.org/licenses/LICENSE-2.0
  40770. *
  40771. * Unless required by applicable law or agreed to in writing,
  40772. * software distributed under the License is distributed on an
  40773. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40774. * KIND, either express or implied. See the License for the
  40775. * specific language governing permissions and limitations
  40776. * under the License.
  40777. */
  40778. registerVisual(visualSymbol('tree', 'circle'));
  40779. registerLayout(treeLayout);
  40780. /*
  40781. * Licensed to the Apache Software Foundation (ASF) under one
  40782. * or more contributor license agreements. See the NOTICE file
  40783. * distributed with this work for additional information
  40784. * regarding copyright ownership. The ASF licenses this file
  40785. * to you under the Apache License, Version 2.0 (the
  40786. * "License"); you may not use this file except in compliance
  40787. * with the License. You may obtain a copy of the License at
  40788. *
  40789. * http://www.apache.org/licenses/LICENSE-2.0
  40790. *
  40791. * Unless required by applicable law or agreed to in writing,
  40792. * software distributed under the License is distributed on an
  40793. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40794. * KIND, either express or implied. See the License for the
  40795. * specific language governing permissions and limitations
  40796. * under the License.
  40797. */
  40798. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  40799. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  40800. var root = seriesModel.getData().tree.root;
  40801. var targetNode = payload.targetNode;
  40802. if (targetNode && root.contains(targetNode)) {
  40803. return {node: targetNode};
  40804. }
  40805. var targetNodeId = payload.targetNodeId;
  40806. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  40807. return {node: targetNode};
  40808. }
  40809. }
  40810. }
  40811. // Not includes the given node at the last item.
  40812. function getPathToRoot(node) {
  40813. var path = [];
  40814. while (node) {
  40815. node = node.parentNode;
  40816. node && path.push(node);
  40817. }
  40818. return path.reverse();
  40819. }
  40820. function aboveViewRoot(viewRoot, node) {
  40821. var viewPath = getPathToRoot(viewRoot);
  40822. return indexOf(viewPath, node) >= 0;
  40823. }
  40824. // From root to the input node (the input node will be included).
  40825. function wrapTreePathInfo(node, seriesModel) {
  40826. var treePathInfo = [];
  40827. while (node) {
  40828. var nodeDataIndex = node.dataIndex;
  40829. treePathInfo.push({
  40830. name: node.name,
  40831. dataIndex: nodeDataIndex,
  40832. value: seriesModel.getRawValue(nodeDataIndex)
  40833. });
  40834. node = node.parentNode;
  40835. }
  40836. treePathInfo.reverse();
  40837. return treePathInfo;
  40838. }
  40839. /*
  40840. * Licensed to the Apache Software Foundation (ASF) under one
  40841. * or more contributor license agreements. See the NOTICE file
  40842. * distributed with this work for additional information
  40843. * regarding copyright ownership. The ASF licenses this file
  40844. * to you under the Apache License, Version 2.0 (the
  40845. * "License"); you may not use this file except in compliance
  40846. * with the License. You may obtain a copy of the License at
  40847. *
  40848. * http://www.apache.org/licenses/LICENSE-2.0
  40849. *
  40850. * Unless required by applicable law or agreed to in writing,
  40851. * software distributed under the License is distributed on an
  40852. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40853. * KIND, either express or implied. See the License for the
  40854. * specific language governing permissions and limitations
  40855. * under the License.
  40856. */
  40857. SeriesModel.extend({
  40858. type: 'series.treemap',
  40859. layoutMode: 'box',
  40860. dependencies: ['grid', 'polar'],
  40861. /**
  40862. * @type {module:echarts/data/Tree~Node}
  40863. */
  40864. _viewRoot: null,
  40865. defaultOption: {
  40866. // Disable progressive rendering
  40867. progressive: 0,
  40868. hoverLayerThreshold: Infinity,
  40869. // center: ['50%', '50%'], // not supported in ec3.
  40870. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  40871. left: 'center',
  40872. top: 'middle',
  40873. right: null,
  40874. bottom: null,
  40875. width: '80%',
  40876. height: '80%',
  40877. sort: true, // Can be null or false or true
  40878. // (order by desc default, asc not supported yet (strange effect))
  40879. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  40880. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  40881. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  40882. // Count from zero (zero represents only view root).
  40883. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  40884. // to align specialized icon. ▷▶❒❐▼✚
  40885. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  40886. // target node area in the view area.
  40887. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  40888. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  40889. // If leafDepth is set and clicking a node which has children but
  40890. // be on left depth, the behaviour would be changing root. Otherwise
  40891. // use behavious defined above.
  40892. animation: true,
  40893. animationDurationUpdate: 900,
  40894. animationEasing: 'quinticInOut',
  40895. breadcrumb: {
  40896. show: true,
  40897. height: 22,
  40898. left: 'center',
  40899. top: 'bottom',
  40900. // right
  40901. // bottom
  40902. emptyItemWidth: 25, // Width of empty node.
  40903. itemStyle: {
  40904. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  40905. borderColor: 'rgba(255,255,255,0.7)',
  40906. borderWidth: 1,
  40907. shadowColor: 'rgba(150,150,150,1)',
  40908. shadowBlur: 3,
  40909. shadowOffsetX: 0,
  40910. shadowOffsetY: 0,
  40911. textStyle: {
  40912. color: '#fff'
  40913. }
  40914. },
  40915. emphasis: {
  40916. textStyle: {}
  40917. }
  40918. },
  40919. label: {
  40920. show: true,
  40921. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  40922. distance: 0,
  40923. padding: 5,
  40924. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  40925. // formatter: null,
  40926. color: '#fff',
  40927. ellipsis: true
  40928. // align
  40929. // verticalAlign
  40930. },
  40931. upperLabel: { // Label when node is parent.
  40932. show: false,
  40933. position: [0, '50%'],
  40934. height: 20,
  40935. // formatter: null,
  40936. color: '#fff',
  40937. ellipsis: true,
  40938. // align: null,
  40939. verticalAlign: 'middle'
  40940. },
  40941. itemStyle: {
  40942. color: null, // Can be 'none' if not necessary.
  40943. colorAlpha: null, // Can be 'none' if not necessary.
  40944. colorSaturation: null, // Can be 'none' if not necessary.
  40945. borderWidth: 0,
  40946. gapWidth: 0,
  40947. borderColor: '#fff',
  40948. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  40949. // border color is evaluated by color of current node and
  40950. // borderColorSaturation.
  40951. },
  40952. emphasis: {
  40953. upperLabel: {
  40954. show: true,
  40955. position: [0, '50%'],
  40956. color: '#fff',
  40957. ellipsis: true,
  40958. verticalAlign: 'middle'
  40959. }
  40960. },
  40961. visualDimension: 0, // Can be 0, 1, 2, 3.
  40962. visualMin: null,
  40963. visualMax: null,
  40964. color: [], // + treemapSeries.color should not be modified. Please only modified
  40965. // level[n].color (if necessary).
  40966. // + Specify color list of each level. level[0].color would be global
  40967. // color list if not specified. (see method `setDefault`).
  40968. // + But set as a empty array to forbid fetch color from global palette
  40969. // when using nodeModel.get('color'), otherwise nodes on deep level
  40970. // will always has color palette set and are not able to inherit color
  40971. // from parent node.
  40972. // + TreemapSeries.color can not be set as 'none', otherwise effect
  40973. // legend color fetching (see seriesColor.js).
  40974. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  40975. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  40976. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  40977. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  40978. // be rendered. Only works when sort is 'asc' or 'desc'.
  40979. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  40980. // grandchildren will not show.
  40981. // Why grandchildren? If not grandchildren but children,
  40982. // some siblings show children and some not,
  40983. // the appearance may be mess and not consistent,
  40984. levels: [] // Each item: {
  40985. // visibleMin, itemStyle, visualDimension, label
  40986. // }
  40987. // data: {
  40988. // value: [],
  40989. // children: [],
  40990. // link: 'http://xxx.xxx.xxx',
  40991. // target: 'blank' or 'self'
  40992. // }
  40993. },
  40994. /**
  40995. * @override
  40996. */
  40997. getInitialData: function (option, ecModel) {
  40998. // Create a virtual root.
  40999. var root = {name: option.name, children: option.data};
  41000. completeTreeValue(root);
  41001. var levels = option.levels || [];
  41002. levels = option.levels = setDefault(levels, ecModel);
  41003. var treeOption = {};
  41004. treeOption.levels = levels;
  41005. // Make sure always a new tree is created when setOption,
  41006. // in TreemapView, we check whether oldTree === newTree
  41007. // to choose mappings approach among old shapes and new shapes.
  41008. return Tree.createTree(root, this, treeOption).data;
  41009. },
  41010. optionUpdated: function () {
  41011. this.resetViewRoot();
  41012. },
  41013. /**
  41014. * @override
  41015. * @param {number} dataIndex
  41016. * @param {boolean} [mutipleSeries=false]
  41017. */
  41018. formatTooltip: function (dataIndex) {
  41019. var data = this.getData();
  41020. var value = this.getRawValue(dataIndex);
  41021. var formattedValue = isArray(value)
  41022. ? addCommas(value[0]) : addCommas(value);
  41023. var name = data.getName(dataIndex);
  41024. return encodeHTML(name + ': ' + formattedValue);
  41025. },
  41026. /**
  41027. * Add tree path to tooltip param
  41028. *
  41029. * @override
  41030. * @param {number} dataIndex
  41031. * @return {Object}
  41032. */
  41033. getDataParams: function (dataIndex) {
  41034. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  41035. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  41036. params.treePathInfo = wrapTreePathInfo(node, this);
  41037. return params;
  41038. },
  41039. /**
  41040. * @public
  41041. * @param {Object} layoutInfo {
  41042. * x: containerGroup x
  41043. * y: containerGroup y
  41044. * width: containerGroup width
  41045. * height: containerGroup height
  41046. * }
  41047. */
  41048. setLayoutInfo: function (layoutInfo) {
  41049. /**
  41050. * @readOnly
  41051. * @type {Object}
  41052. */
  41053. this.layoutInfo = this.layoutInfo || {};
  41054. extend(this.layoutInfo, layoutInfo);
  41055. },
  41056. /**
  41057. * @param {string} id
  41058. * @return {number} index
  41059. */
  41060. mapIdToIndex: function (id) {
  41061. // A feature is implemented:
  41062. // index is monotone increasing with the sequence of
  41063. // input id at the first time.
  41064. // This feature can make sure that each data item and its
  41065. // mapped color have the same index between data list and
  41066. // color list at the beginning, which is useful for user
  41067. // to adjust data-color mapping.
  41068. /**
  41069. * @private
  41070. * @type {Object}
  41071. */
  41072. var idIndexMap = this._idIndexMap;
  41073. if (!idIndexMap) {
  41074. idIndexMap = this._idIndexMap = createHashMap();
  41075. /**
  41076. * @private
  41077. * @type {number}
  41078. */
  41079. this._idIndexMapCount = 0;
  41080. }
  41081. var index = idIndexMap.get(id);
  41082. if (index == null) {
  41083. idIndexMap.set(id, index = this._idIndexMapCount++);
  41084. }
  41085. return index;
  41086. },
  41087. getViewRoot: function () {
  41088. return this._viewRoot;
  41089. },
  41090. /**
  41091. * @param {module:echarts/data/Tree~Node} [viewRoot]
  41092. */
  41093. resetViewRoot: function (viewRoot) {
  41094. viewRoot
  41095. ? (this._viewRoot = viewRoot)
  41096. : (viewRoot = this._viewRoot);
  41097. var root = this.getRawData().tree.root;
  41098. if (!viewRoot
  41099. || (viewRoot !== root && !root.contains(viewRoot))
  41100. ) {
  41101. this._viewRoot = root;
  41102. }
  41103. }
  41104. });
  41105. /**
  41106. * @param {Object} dataNode
  41107. */
  41108. function completeTreeValue(dataNode) {
  41109. // Postorder travel tree.
  41110. // If value of none-leaf node is not set,
  41111. // calculate it by suming up the value of all children.
  41112. var sum = 0;
  41113. each$1(dataNode.children, function (child) {
  41114. completeTreeValue(child);
  41115. var childValue = child.value;
  41116. isArray(childValue) && (childValue = childValue[0]);
  41117. sum += childValue;
  41118. });
  41119. var thisValue = dataNode.value;
  41120. if (isArray(thisValue)) {
  41121. thisValue = thisValue[0];
  41122. }
  41123. if (thisValue == null || isNaN(thisValue)) {
  41124. thisValue = sum;
  41125. }
  41126. // Value should not less than 0.
  41127. if (thisValue < 0) {
  41128. thisValue = 0;
  41129. }
  41130. isArray(dataNode.value)
  41131. ? (dataNode.value[0] = thisValue)
  41132. : (dataNode.value = thisValue);
  41133. }
  41134. /**
  41135. * set default to level configuration
  41136. */
  41137. function setDefault(levels, ecModel) {
  41138. var globalColorList = ecModel.get('color');
  41139. if (!globalColorList) {
  41140. return;
  41141. }
  41142. levels = levels || [];
  41143. var hasColorDefine;
  41144. each$1(levels, function (levelDefine) {
  41145. var model = new Model(levelDefine);
  41146. var modelColor = model.get('color');
  41147. if (model.get('itemStyle.color')
  41148. || (modelColor && modelColor !== 'none')
  41149. ) {
  41150. hasColorDefine = true;
  41151. }
  41152. });
  41153. if (!hasColorDefine) {
  41154. var level0 = levels[0] || (levels[0] = {});
  41155. level0.color = globalColorList.slice();
  41156. }
  41157. return levels;
  41158. }
  41159. /*
  41160. * Licensed to the Apache Software Foundation (ASF) under one
  41161. * or more contributor license agreements. See the NOTICE file
  41162. * distributed with this work for additional information
  41163. * regarding copyright ownership. The ASF licenses this file
  41164. * to you under the Apache License, Version 2.0 (the
  41165. * "License"); you may not use this file except in compliance
  41166. * with the License. You may obtain a copy of the License at
  41167. *
  41168. * http://www.apache.org/licenses/LICENSE-2.0
  41169. *
  41170. * Unless required by applicable law or agreed to in writing,
  41171. * software distributed under the License is distributed on an
  41172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41173. * KIND, either express or implied. See the License for the
  41174. * specific language governing permissions and limitations
  41175. * under the License.
  41176. */
  41177. var TEXT_PADDING = 8;
  41178. var ITEM_GAP = 8;
  41179. var ARRAY_LENGTH = 5;
  41180. function Breadcrumb(containerGroup) {
  41181. /**
  41182. * @private
  41183. * @type {module:zrender/container/Group}
  41184. */
  41185. this.group = new Group();
  41186. containerGroup.add(this.group);
  41187. }
  41188. Breadcrumb.prototype = {
  41189. constructor: Breadcrumb,
  41190. render: function (seriesModel, api, targetNode, onSelect) {
  41191. var model = seriesModel.getModel('breadcrumb');
  41192. var thisGroup = this.group;
  41193. thisGroup.removeAll();
  41194. if (!model.get('show') || !targetNode) {
  41195. return;
  41196. }
  41197. var normalStyleModel = model.getModel('itemStyle');
  41198. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  41199. var textStyleModel = normalStyleModel.getModel('textStyle');
  41200. var layoutParam = {
  41201. pos: {
  41202. left: model.get('left'),
  41203. right: model.get('right'),
  41204. top: model.get('top'),
  41205. bottom: model.get('bottom')
  41206. },
  41207. box: {
  41208. width: api.getWidth(),
  41209. height: api.getHeight()
  41210. },
  41211. emptyItemWidth: model.get('emptyItemWidth'),
  41212. totalWidth: 0,
  41213. renderList: []
  41214. };
  41215. this._prepare(targetNode, layoutParam, textStyleModel);
  41216. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  41217. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  41218. },
  41219. /**
  41220. * Prepare render list and total width
  41221. * @private
  41222. */
  41223. _prepare: function (targetNode, layoutParam, textStyleModel) {
  41224. for (var node = targetNode; node; node = node.parentNode) {
  41225. var text = node.getModel().get('name');
  41226. var textRect = textStyleModel.getTextRect(text);
  41227. var itemWidth = Math.max(
  41228. textRect.width + TEXT_PADDING * 2,
  41229. layoutParam.emptyItemWidth
  41230. );
  41231. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  41232. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  41233. }
  41234. },
  41235. /**
  41236. * @private
  41237. */
  41238. _renderContent: function (
  41239. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  41240. ) {
  41241. // Start rendering.
  41242. var lastX = 0;
  41243. var emptyItemWidth = layoutParam.emptyItemWidth;
  41244. var height = seriesModel.get('breadcrumb.height');
  41245. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  41246. var totalWidth = layoutParam.totalWidth;
  41247. var renderList = layoutParam.renderList;
  41248. for (var i = renderList.length - 1; i >= 0; i--) {
  41249. var item = renderList[i];
  41250. var itemNode = item.node;
  41251. var itemWidth = item.width;
  41252. var text = item.text;
  41253. // Hdie text and shorten width if necessary.
  41254. if (totalWidth > availableSize.width) {
  41255. totalWidth -= itemWidth - emptyItemWidth;
  41256. itemWidth = emptyItemWidth;
  41257. text = null;
  41258. }
  41259. var el = new Polygon({
  41260. shape: {
  41261. points: makeItemPoints(
  41262. lastX, 0, itemWidth, height,
  41263. i === renderList.length - 1, i === 0
  41264. )
  41265. },
  41266. style: defaults(
  41267. normalStyleModel.getItemStyle(),
  41268. {
  41269. lineJoin: 'bevel',
  41270. text: text,
  41271. textFill: textStyleModel.getTextColor(),
  41272. textFont: textStyleModel.getFont()
  41273. }
  41274. ),
  41275. z: 10,
  41276. onclick: curry(onSelect, itemNode)
  41277. });
  41278. this.group.add(el);
  41279. packEventData(el, seriesModel, itemNode);
  41280. lastX += itemWidth + ITEM_GAP;
  41281. }
  41282. },
  41283. /**
  41284. * @override
  41285. */
  41286. remove: function () {
  41287. this.group.removeAll();
  41288. }
  41289. };
  41290. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  41291. var points = [
  41292. [head ? x : x - ARRAY_LENGTH, y],
  41293. [x + itemWidth, y],
  41294. [x + itemWidth, y + itemHeight],
  41295. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  41296. ];
  41297. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  41298. !head && points.push([x, y + itemHeight / 2]);
  41299. return points;
  41300. }
  41301. // Package custom mouse event.
  41302. function packEventData(el, seriesModel, itemNode) {
  41303. el.eventData = {
  41304. componentType: 'series',
  41305. componentSubType: 'treemap',
  41306. seriesIndex: seriesModel.componentIndex,
  41307. seriesName: seriesModel.name,
  41308. seriesType: 'treemap',
  41309. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  41310. nodeData: {
  41311. dataIndex: itemNode && itemNode.dataIndex,
  41312. name: itemNode && itemNode.name
  41313. },
  41314. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  41315. };
  41316. }
  41317. /*
  41318. * Licensed to the Apache Software Foundation (ASF) under one
  41319. * or more contributor license agreements. See the NOTICE file
  41320. * distributed with this work for additional information
  41321. * regarding copyright ownership. The ASF licenses this file
  41322. * to you under the Apache License, Version 2.0 (the
  41323. * "License"); you may not use this file except in compliance
  41324. * with the License. You may obtain a copy of the License at
  41325. *
  41326. * http://www.apache.org/licenses/LICENSE-2.0
  41327. *
  41328. * Unless required by applicable law or agreed to in writing,
  41329. * software distributed under the License is distributed on an
  41330. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41331. * KIND, either express or implied. See the License for the
  41332. * specific language governing permissions and limitations
  41333. * under the License.
  41334. */
  41335. /**
  41336. * @param {number} [time=500] Time in ms
  41337. * @param {string} [easing='linear']
  41338. * @param {number} [delay=0]
  41339. * @param {Function} [callback]
  41340. *
  41341. * @example
  41342. * // Animate position
  41343. * animation
  41344. * .createWrap()
  41345. * .add(el1, {position: [10, 10]})
  41346. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  41347. * .done(function () { // done })
  41348. * .start('cubicOut');
  41349. */
  41350. function createWrap() {
  41351. var storage = [];
  41352. var elExistsMap = {};
  41353. var doneCallback;
  41354. return {
  41355. /**
  41356. * Caution: a el can only be added once, otherwise 'done'
  41357. * might not be called. This method checks this (by el.id),
  41358. * suppresses adding and returns false when existing el found.
  41359. *
  41360. * @param {modele:zrender/Element} el
  41361. * @param {Object} target
  41362. * @param {number} [time=500]
  41363. * @param {number} [delay=0]
  41364. * @param {string} [easing='linear']
  41365. * @return {boolean} Whether adding succeeded.
  41366. *
  41367. * @example
  41368. * add(el, target, time, delay, easing);
  41369. * add(el, target, time, easing);
  41370. * add(el, target, time);
  41371. * add(el, target);
  41372. */
  41373. add: function (el, target, time, delay, easing) {
  41374. if (isString(delay)) {
  41375. easing = delay;
  41376. delay = 0;
  41377. }
  41378. if (elExistsMap[el.id]) {
  41379. return false;
  41380. }
  41381. elExistsMap[el.id] = 1;
  41382. storage.push(
  41383. {el: el, target: target, time: time, delay: delay, easing: easing}
  41384. );
  41385. return true;
  41386. },
  41387. /**
  41388. * Only execute when animation finished. Will not execute when any
  41389. * of 'stop' or 'stopAnimation' called.
  41390. *
  41391. * @param {Function} callback
  41392. */
  41393. done: function (callback) {
  41394. doneCallback = callback;
  41395. return this;
  41396. },
  41397. /**
  41398. * Will stop exist animation firstly.
  41399. */
  41400. start: function () {
  41401. var count = storage.length;
  41402. for (var i = 0, len = storage.length; i < len; i++) {
  41403. var item = storage[i];
  41404. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  41405. }
  41406. return this;
  41407. function done() {
  41408. count--;
  41409. if (!count) {
  41410. storage.length = 0;
  41411. elExistsMap = {};
  41412. doneCallback && doneCallback();
  41413. }
  41414. }
  41415. }
  41416. };
  41417. }
  41418. /*
  41419. * Licensed to the Apache Software Foundation (ASF) under one
  41420. * or more contributor license agreements. See the NOTICE file
  41421. * distributed with this work for additional information
  41422. * regarding copyright ownership. The ASF licenses this file
  41423. * to you under the Apache License, Version 2.0 (the
  41424. * "License"); you may not use this file except in compliance
  41425. * with the License. You may obtain a copy of the License at
  41426. *
  41427. * http://www.apache.org/licenses/LICENSE-2.0
  41428. *
  41429. * Unless required by applicable law or agreed to in writing,
  41430. * software distributed under the License is distributed on an
  41431. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41432. * KIND, either express or implied. See the License for the
  41433. * specific language governing permissions and limitations
  41434. * under the License.
  41435. */
  41436. var bind$1 = bind;
  41437. var Group$2 = Group;
  41438. var Rect$1 = Rect;
  41439. var each$8 = each$1;
  41440. var DRAG_THRESHOLD = 3;
  41441. var PATH_LABEL_NOAMAL = ['label'];
  41442. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  41443. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  41444. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  41445. var Z_BASE = 10; // Should bigger than every z.
  41446. var Z_BG = 1;
  41447. var Z_CONTENT = 2;
  41448. var getItemStyleEmphasis = makeStyleMapper([
  41449. ['fill', 'color'],
  41450. // `borderColor` and `borderWidth` has been occupied,
  41451. // so use `stroke` to indicate the stroke of the rect.
  41452. ['stroke', 'strokeColor'],
  41453. ['lineWidth', 'strokeWidth'],
  41454. ['shadowBlur'],
  41455. ['shadowOffsetX'],
  41456. ['shadowOffsetY'],
  41457. ['shadowColor']
  41458. ]);
  41459. var getItemStyleNormal = function (model) {
  41460. // Normal style props should include emphasis style props.
  41461. var itemStyle = getItemStyleEmphasis(model);
  41462. // Clear styles set by emphasis.
  41463. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  41464. return itemStyle;
  41465. };
  41466. extendChartView({
  41467. type: 'treemap',
  41468. /**
  41469. * @override
  41470. */
  41471. init: function (o, api) {
  41472. /**
  41473. * @private
  41474. * @type {module:zrender/container/Group}
  41475. */
  41476. this._containerGroup;
  41477. /**
  41478. * @private
  41479. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  41480. */
  41481. this._storage = createStorage();
  41482. /**
  41483. * @private
  41484. * @type {module:echarts/data/Tree}
  41485. */
  41486. this._oldTree;
  41487. /**
  41488. * @private
  41489. * @type {module:echarts/chart/treemap/Breadcrumb}
  41490. */
  41491. this._breadcrumb;
  41492. /**
  41493. * @private
  41494. * @type {module:echarts/component/helper/RoamController}
  41495. */
  41496. this._controller;
  41497. /**
  41498. * 'ready', 'animating'
  41499. * @private
  41500. */
  41501. this._state = 'ready';
  41502. },
  41503. /**
  41504. * @override
  41505. */
  41506. render: function (seriesModel, ecModel, api, payload) {
  41507. var models = ecModel.findComponents({
  41508. mainType: 'series', subType: 'treemap', query: payload
  41509. });
  41510. if (indexOf(models, seriesModel) < 0) {
  41511. return;
  41512. }
  41513. this.seriesModel = seriesModel;
  41514. this.api = api;
  41515. this.ecModel = ecModel;
  41516. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  41517. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  41518. var payloadType = payload && payload.type;
  41519. var layoutInfo = seriesModel.layoutInfo;
  41520. var isInit = !this._oldTree;
  41521. var thisStorage = this._storage;
  41522. // Mark new root when action is treemapRootToNode.
  41523. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  41524. ? {
  41525. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  41526. direction: payload.direction
  41527. }
  41528. : null;
  41529. var containerGroup = this._giveContainerGroup(layoutInfo);
  41530. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  41531. (
  41532. !isInit && (
  41533. !payloadType
  41534. || payloadType === 'treemapZoomToNode'
  41535. || payloadType === 'treemapRootToNode'
  41536. )
  41537. )
  41538. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  41539. : renderResult.renderFinally();
  41540. this._resetController(api);
  41541. this._renderBreadcrumb(seriesModel, api, targetInfo);
  41542. },
  41543. /**
  41544. * @private
  41545. */
  41546. _giveContainerGroup: function (layoutInfo) {
  41547. var containerGroup = this._containerGroup;
  41548. if (!containerGroup) {
  41549. // FIXME
  41550. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  41551. containerGroup = this._containerGroup = new Group$2();
  41552. this._initEvents(containerGroup);
  41553. this.group.add(containerGroup);
  41554. }
  41555. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  41556. return containerGroup;
  41557. },
  41558. /**
  41559. * @private
  41560. */
  41561. _doRender: function (containerGroup, seriesModel, reRoot) {
  41562. var thisTree = seriesModel.getData().tree;
  41563. var oldTree = this._oldTree;
  41564. // Clear last shape records.
  41565. var lastsForAnimation = createStorage();
  41566. var thisStorage = createStorage();
  41567. var oldStorage = this._storage;
  41568. var willInvisibleEls = [];
  41569. var doRenderNode = curry(
  41570. renderNode, seriesModel,
  41571. thisStorage, oldStorage, reRoot,
  41572. lastsForAnimation, willInvisibleEls
  41573. );
  41574. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  41575. // the oldTree is actually losted, so we can not find all of the old graphic
  41576. // elements from tree. So we use this stragegy: make element storage, move
  41577. // from old storage to new storage, clear old storage.
  41578. dualTravel(
  41579. thisTree.root ? [thisTree.root] : [],
  41580. (oldTree && oldTree.root) ? [oldTree.root] : [],
  41581. containerGroup,
  41582. thisTree === oldTree || !oldTree,
  41583. 0
  41584. );
  41585. // Process all removing.
  41586. var willDeleteEls = clearStorage(oldStorage);
  41587. this._oldTree = thisTree;
  41588. this._storage = thisStorage;
  41589. return {
  41590. lastsForAnimation: lastsForAnimation,
  41591. willDeleteEls: willDeleteEls,
  41592. renderFinally: renderFinally
  41593. };
  41594. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  41595. // When 'render' is triggered by action,
  41596. // 'this' and 'old' may be the same tree,
  41597. // we use rawIndex in that case.
  41598. if (sameTree) {
  41599. oldViewChildren = thisViewChildren;
  41600. each$8(thisViewChildren, function (child, index) {
  41601. !child.isRemoved() && processNode(index, index);
  41602. });
  41603. }
  41604. // Diff hierarchically (diff only in each subtree, but not whole).
  41605. // because, consistency of view is important.
  41606. else {
  41607. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  41608. .add(processNode)
  41609. .update(processNode)
  41610. .remove(curry(processNode, null))
  41611. .execute();
  41612. }
  41613. function getKey(node) {
  41614. // Identify by name or raw index.
  41615. return node.getId();
  41616. }
  41617. function processNode(newIndex, oldIndex) {
  41618. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  41619. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  41620. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  41621. group && dualTravel(
  41622. thisNode && thisNode.viewChildren || [],
  41623. oldNode && oldNode.viewChildren || [],
  41624. group,
  41625. sameTree,
  41626. depth + 1
  41627. );
  41628. }
  41629. }
  41630. function clearStorage(storage) {
  41631. var willDeleteEls = createStorage();
  41632. storage && each$8(storage, function (store, storageName) {
  41633. var delEls = willDeleteEls[storageName];
  41634. each$8(store, function (el) {
  41635. el && (delEls.push(el), el.__tmWillDelete = 1);
  41636. });
  41637. });
  41638. return willDeleteEls;
  41639. }
  41640. function renderFinally() {
  41641. each$8(willDeleteEls, function (els) {
  41642. each$8(els, function (el) {
  41643. el.parent && el.parent.remove(el);
  41644. });
  41645. });
  41646. each$8(willInvisibleEls, function (el) {
  41647. el.invisible = true;
  41648. // Setting invisible is for optimizing, so no need to set dirty,
  41649. // just mark as invisible.
  41650. el.dirty();
  41651. });
  41652. }
  41653. },
  41654. /**
  41655. * @private
  41656. */
  41657. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  41658. if (!seriesModel.get('animation')) {
  41659. return;
  41660. }
  41661. var duration = seriesModel.get('animationDurationUpdate');
  41662. var easing = seriesModel.get('animationEasing');
  41663. var animationWrap = createWrap();
  41664. // Make delete animations.
  41665. each$8(renderResult.willDeleteEls, function (store, storageName) {
  41666. each$8(store, function (el, rawIndex) {
  41667. if (el.invisible) {
  41668. return;
  41669. }
  41670. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  41671. var target;
  41672. if (reRoot && reRoot.direction === 'drillDown') {
  41673. target = parent === reRoot.rootNodeGroup
  41674. // This is the content element of view root.
  41675. // Only `content` will enter this branch, because
  41676. // `background` and `nodeGroup` will not be deleted.
  41677. ? {
  41678. shape: {
  41679. x: 0,
  41680. y: 0,
  41681. width: parent.__tmNodeWidth,
  41682. height: parent.__tmNodeHeight
  41683. },
  41684. style: {
  41685. opacity: 0
  41686. }
  41687. }
  41688. // Others.
  41689. : {style: {opacity: 0}};
  41690. }
  41691. else {
  41692. var targetX = 0;
  41693. var targetY = 0;
  41694. if (!parent.__tmWillDelete) {
  41695. // Let node animate to right-bottom corner, cooperating with fadeout,
  41696. // which is appropriate for user understanding.
  41697. // Divided by 2 for reRoot rolling up effect.
  41698. targetX = parent.__tmNodeWidth / 2;
  41699. targetY = parent.__tmNodeHeight / 2;
  41700. }
  41701. target = storageName === 'nodeGroup'
  41702. ? {position: [targetX, targetY], style: {opacity: 0}}
  41703. : {
  41704. shape: {x: targetX, y: targetY, width: 0, height: 0},
  41705. style: {opacity: 0}
  41706. };
  41707. }
  41708. target && animationWrap.add(el, target, duration, easing);
  41709. });
  41710. });
  41711. // Make other animations
  41712. each$8(this._storage, function (store, storageName) {
  41713. each$8(store, function (el, rawIndex) {
  41714. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  41715. var target = {};
  41716. if (!last) {
  41717. return;
  41718. }
  41719. if (storageName === 'nodeGroup') {
  41720. if (last.old) {
  41721. target.position = el.position.slice();
  41722. el.attr('position', last.old);
  41723. }
  41724. }
  41725. else {
  41726. if (last.old) {
  41727. target.shape = extend({}, el.shape);
  41728. el.setShape(last.old);
  41729. }
  41730. if (last.fadein) {
  41731. el.setStyle('opacity', 0);
  41732. target.style = {opacity: 1};
  41733. }
  41734. // When animation is stopped for succedent animation starting,
  41735. // el.style.opacity might not be 1
  41736. else if (el.style.opacity !== 1) {
  41737. target.style = {opacity: 1};
  41738. }
  41739. }
  41740. animationWrap.add(el, target, duration, easing);
  41741. });
  41742. }, this);
  41743. this._state = 'animating';
  41744. animationWrap
  41745. .done(bind$1(function () {
  41746. this._state = 'ready';
  41747. renderResult.renderFinally();
  41748. }, this))
  41749. .start();
  41750. },
  41751. /**
  41752. * @private
  41753. */
  41754. _resetController: function (api) {
  41755. var controller = this._controller;
  41756. // Init controller.
  41757. if (!controller) {
  41758. controller = this._controller = new RoamController(api.getZr());
  41759. controller.enable(this.seriesModel.get('roam'));
  41760. controller.on('pan', bind$1(this._onPan, this));
  41761. controller.on('zoom', bind$1(this._onZoom, this));
  41762. }
  41763. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  41764. controller.setPointerChecker(function (e, x, y) {
  41765. return rect.contain(x, y);
  41766. });
  41767. },
  41768. /**
  41769. * @private
  41770. */
  41771. _clearController: function () {
  41772. var controller = this._controller;
  41773. if (controller) {
  41774. controller.dispose();
  41775. controller = null;
  41776. }
  41777. },
  41778. /**
  41779. * @private
  41780. */
  41781. _onPan: function (dx, dy) {
  41782. if (this._state !== 'animating'
  41783. && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
  41784. ) {
  41785. // These param must not be cached.
  41786. var root = this.seriesModel.getData().tree.root;
  41787. if (!root) {
  41788. return;
  41789. }
  41790. var rootLayout = root.getLayout();
  41791. if (!rootLayout) {
  41792. return;
  41793. }
  41794. this.api.dispatchAction({
  41795. type: 'treemapMove',
  41796. from: this.uid,
  41797. seriesId: this.seriesModel.id,
  41798. rootRect: {
  41799. x: rootLayout.x + dx, y: rootLayout.y + dy,
  41800. width: rootLayout.width, height: rootLayout.height
  41801. }
  41802. });
  41803. }
  41804. },
  41805. /**
  41806. * @private
  41807. */
  41808. _onZoom: function (scale, mouseX, mouseY) {
  41809. if (this._state !== 'animating') {
  41810. // These param must not be cached.
  41811. var root = this.seriesModel.getData().tree.root;
  41812. if (!root) {
  41813. return;
  41814. }
  41815. var rootLayout = root.getLayout();
  41816. if (!rootLayout) {
  41817. return;
  41818. }
  41819. var rect = new BoundingRect(
  41820. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  41821. );
  41822. var layoutInfo = this.seriesModel.layoutInfo;
  41823. // Transform mouse coord from global to containerGroup.
  41824. mouseX -= layoutInfo.x;
  41825. mouseY -= layoutInfo.y;
  41826. // Scale root bounding rect.
  41827. var m = create$1();
  41828. translate(m, m, [-mouseX, -mouseY]);
  41829. scale$1(m, m, [scale, scale]);
  41830. translate(m, m, [mouseX, mouseY]);
  41831. rect.applyTransform(m);
  41832. this.api.dispatchAction({
  41833. type: 'treemapRender',
  41834. from: this.uid,
  41835. seriesId: this.seriesModel.id,
  41836. rootRect: {
  41837. x: rect.x, y: rect.y,
  41838. width: rect.width, height: rect.height
  41839. }
  41840. });
  41841. }
  41842. },
  41843. /**
  41844. * @private
  41845. */
  41846. _initEvents: function (containerGroup) {
  41847. containerGroup.on('click', function (e) {
  41848. if (this._state !== 'ready') {
  41849. return;
  41850. }
  41851. var nodeClick = this.seriesModel.get('nodeClick', true);
  41852. if (!nodeClick) {
  41853. return;
  41854. }
  41855. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  41856. if (!targetInfo) {
  41857. return;
  41858. }
  41859. var node = targetInfo.node;
  41860. if (node.getLayout().isLeafRoot) {
  41861. this._rootToNode(targetInfo);
  41862. }
  41863. else {
  41864. if (nodeClick === 'zoomToNode') {
  41865. this._zoomToNode(targetInfo);
  41866. }
  41867. else if (nodeClick === 'link') {
  41868. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  41869. var link = itemModel.get('link', true);
  41870. var linkTarget = itemModel.get('target', true) || 'blank';
  41871. link && window.open(link, linkTarget);
  41872. }
  41873. }
  41874. }, this);
  41875. },
  41876. /**
  41877. * @private
  41878. */
  41879. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  41880. if (!targetInfo) {
  41881. targetInfo = seriesModel.get('leafDepth', true) != null
  41882. ? {node: seriesModel.getViewRoot()}
  41883. // FIXME
  41884. // better way?
  41885. // Find breadcrumb tail on center of containerGroup.
  41886. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  41887. if (!targetInfo) {
  41888. targetInfo = {node: seriesModel.getData().tree.root};
  41889. }
  41890. }
  41891. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  41892. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  41893. function onSelect(node) {
  41894. if (this._state !== 'animating') {
  41895. aboveViewRoot(seriesModel.getViewRoot(), node)
  41896. ? this._rootToNode({node: node})
  41897. : this._zoomToNode({node: node});
  41898. }
  41899. }
  41900. },
  41901. /**
  41902. * @override
  41903. */
  41904. remove: function () {
  41905. this._clearController();
  41906. this._containerGroup && this._containerGroup.removeAll();
  41907. this._storage = createStorage();
  41908. this._state = 'ready';
  41909. this._breadcrumb && this._breadcrumb.remove();
  41910. },
  41911. dispose: function () {
  41912. this._clearController();
  41913. },
  41914. /**
  41915. * @private
  41916. */
  41917. _zoomToNode: function (targetInfo) {
  41918. this.api.dispatchAction({
  41919. type: 'treemapZoomToNode',
  41920. from: this.uid,
  41921. seriesId: this.seriesModel.id,
  41922. targetNode: targetInfo.node
  41923. });
  41924. },
  41925. /**
  41926. * @private
  41927. */
  41928. _rootToNode: function (targetInfo) {
  41929. this.api.dispatchAction({
  41930. type: 'treemapRootToNode',
  41931. from: this.uid,
  41932. seriesId: this.seriesModel.id,
  41933. targetNode: targetInfo.node
  41934. });
  41935. },
  41936. /**
  41937. * @public
  41938. * @param {number} x Global coord x.
  41939. * @param {number} y Global coord y.
  41940. * @return {Object} info If not found, return undefined;
  41941. * @return {number} info.node Target node.
  41942. * @return {number} info.offsetX x refer to target node.
  41943. * @return {number} info.offsetY y refer to target node.
  41944. */
  41945. findTarget: function (x, y) {
  41946. var targetInfo;
  41947. var viewRoot = this.seriesModel.getViewRoot();
  41948. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  41949. var bgEl = this._storage.background[node.getRawIndex()];
  41950. // If invisible, there might be no element.
  41951. if (bgEl) {
  41952. var point = bgEl.transformCoordToLocal(x, y);
  41953. var shape = bgEl.shape;
  41954. // For performance consideration, dont use 'getBoundingRect'.
  41955. if (shape.x <= point[0]
  41956. && point[0] <= shape.x + shape.width
  41957. && shape.y <= point[1]
  41958. && point[1] <= shape.y + shape.height
  41959. ) {
  41960. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  41961. }
  41962. else {
  41963. return false; // Suppress visit subtree.
  41964. }
  41965. }
  41966. }, this);
  41967. return targetInfo;
  41968. }
  41969. });
  41970. /**
  41971. * @inner
  41972. */
  41973. function createStorage() {
  41974. return {nodeGroup: [], background: [], content: []};
  41975. }
  41976. /**
  41977. * @inner
  41978. * @return Return undefined means do not travel further.
  41979. */
  41980. function renderNode(
  41981. seriesModel, thisStorage, oldStorage, reRoot,
  41982. lastsForAnimation, willInvisibleEls,
  41983. thisNode, oldNode, parentGroup, depth
  41984. ) {
  41985. // Whether under viewRoot.
  41986. if (!thisNode) {
  41987. // Deleting nodes will be performed finally. This method just find
  41988. // element from old storage, or create new element, set them to new
  41989. // storage, and set styles.
  41990. return;
  41991. }
  41992. // -------------------------------------------------------------------
  41993. // Start of closure variables available in "Procedures in renderNode".
  41994. var thisLayout = thisNode.getLayout();
  41995. if (!thisLayout || !thisLayout.isInView) {
  41996. return;
  41997. }
  41998. var thisWidth = thisLayout.width;
  41999. var thisHeight = thisLayout.height;
  42000. var borderWidth = thisLayout.borderWidth;
  42001. var thisInvisible = thisLayout.invisible;
  42002. var thisRawIndex = thisNode.getRawIndex();
  42003. var oldRawIndex = oldNode && oldNode.getRawIndex();
  42004. var thisViewChildren = thisNode.viewChildren;
  42005. var upperHeight = thisLayout.upperHeight;
  42006. var isParent = thisViewChildren && thisViewChildren.length;
  42007. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  42008. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  42009. // End of closure ariables available in "Procedures in renderNode".
  42010. // -----------------------------------------------------------------
  42011. // Node group
  42012. var group = giveGraphic('nodeGroup', Group$2);
  42013. if (!group) {
  42014. return;
  42015. }
  42016. parentGroup.add(group);
  42017. // x,y are not set when el is above view root.
  42018. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  42019. group.__tmNodeWidth = thisWidth;
  42020. group.__tmNodeHeight = thisHeight;
  42021. if (thisLayout.isAboveViewRoot) {
  42022. return group;
  42023. }
  42024. // Background
  42025. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  42026. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  42027. // No children, render content.
  42028. if (!isParent) {
  42029. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  42030. content && renderContent(group, content);
  42031. }
  42032. return group;
  42033. // ----------------------------
  42034. // | Procedures in renderNode |
  42035. // ----------------------------
  42036. function renderBackground(group, bg, useUpperLabel) {
  42037. // For tooltip.
  42038. bg.dataIndex = thisNode.dataIndex;
  42039. bg.seriesIndex = seriesModel.seriesIndex;
  42040. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  42041. var visualBorderColor = thisNode.getVisual('borderColor', true);
  42042. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  42043. updateStyle(bg, function () {
  42044. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  42045. normalStyle.fill = visualBorderColor;
  42046. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  42047. emphasisStyle.fill = emphasisBorderColor;
  42048. if (useUpperLabel) {
  42049. var upperLabelWidth = thisWidth - 2 * borderWidth;
  42050. prepareText(
  42051. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  42052. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  42053. );
  42054. }
  42055. // For old bg.
  42056. else {
  42057. normalStyle.text = emphasisStyle.text = null;
  42058. }
  42059. bg.setStyle(normalStyle);
  42060. setHoverStyle(bg, emphasisStyle);
  42061. });
  42062. group.add(bg);
  42063. }
  42064. function renderContent(group, content) {
  42065. // For tooltip.
  42066. content.dataIndex = thisNode.dataIndex;
  42067. content.seriesIndex = seriesModel.seriesIndex;
  42068. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  42069. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  42070. content.culling = true;
  42071. content.setShape({
  42072. x: borderWidth,
  42073. y: borderWidth,
  42074. width: contentWidth,
  42075. height: contentHeight
  42076. });
  42077. var visualColor = thisNode.getVisual('color', true);
  42078. updateStyle(content, function () {
  42079. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  42080. normalStyle.fill = visualColor;
  42081. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  42082. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  42083. content.setStyle(normalStyle);
  42084. setHoverStyle(content, emphasisStyle);
  42085. });
  42086. group.add(content);
  42087. }
  42088. function updateStyle(element, cb) {
  42089. if (!thisInvisible) {
  42090. // If invisible, do not set visual, otherwise the element will
  42091. // change immediately before animation. We think it is OK to
  42092. // remain its origin color when moving out of the view window.
  42093. cb();
  42094. if (!element.__tmWillVisible) {
  42095. element.invisible = false;
  42096. }
  42097. }
  42098. else {
  42099. // Delay invisible setting utill animation finished,
  42100. // avoid element vanish suddenly before animation.
  42101. !element.invisible && willInvisibleEls.push(element);
  42102. }
  42103. }
  42104. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  42105. var nodeModel = thisNode.getModel();
  42106. var text = retrieve(
  42107. seriesModel.getFormattedLabel(
  42108. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  42109. ),
  42110. nodeModel.get('name')
  42111. );
  42112. if (!upperLabelRect && thisLayout.isLeafRoot) {
  42113. var iconChar = seriesModel.get('drillDownIcon', true);
  42114. text = iconChar ? iconChar + ' ' + text : text;
  42115. }
  42116. var normalLabelModel = nodeModel.getModel(
  42117. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  42118. );
  42119. var emphasisLabelModel = nodeModel.getModel(
  42120. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  42121. );
  42122. var isShow = normalLabelModel.getShallow('show');
  42123. setLabelStyle(
  42124. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  42125. {
  42126. defaultText: isShow ? text : null,
  42127. autoColor: visualColor,
  42128. isRectText: true
  42129. }
  42130. );
  42131. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  42132. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  42133. ? {
  42134. outerWidth: width,
  42135. outerHeight: height,
  42136. minChar: 2
  42137. }
  42138. : null;
  42139. }
  42140. function giveGraphic(storageName, Ctor, depth, z) {
  42141. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  42142. var lasts = lastsForAnimation[storageName];
  42143. if (element) {
  42144. // Remove from oldStorage
  42145. oldStorage[storageName][oldRawIndex] = null;
  42146. prepareAnimationWhenHasOld(lasts, element, storageName);
  42147. }
  42148. // If invisible and no old element, do not create new element (for optimizing).
  42149. else if (!thisInvisible) {
  42150. element = new Ctor({z: calculateZ(depth, z)});
  42151. element.__tmDepth = depth;
  42152. element.__tmStorageName = storageName;
  42153. prepareAnimationWhenNoOld(lasts, element, storageName);
  42154. }
  42155. // Set to thisStorage
  42156. return (thisStorage[storageName][thisRawIndex] = element);
  42157. }
  42158. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  42159. var lastCfg = lasts[thisRawIndex] = {};
  42160. lastCfg.old = storageName === 'nodeGroup'
  42161. ? element.position.slice()
  42162. : extend({}, element.shape);
  42163. }
  42164. // If a element is new, we need to find the animation start point carefully,
  42165. // otherwise it will looks strange when 'zoomToNode'.
  42166. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  42167. var lastCfg = lasts[thisRawIndex] = {};
  42168. var parentNode = thisNode.parentNode;
  42169. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  42170. var parentOldX = 0;
  42171. var parentOldY = 0;
  42172. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  42173. // For convenience, get old bounding rect from background.
  42174. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  42175. if (!reRoot && parentOldBg && parentOldBg.old) {
  42176. parentOldX = parentOldBg.old.width;
  42177. parentOldY = parentOldBg.old.height;
  42178. }
  42179. // When no parent old shape found, its parent is new too,
  42180. // so we can just use {x:0, y:0}.
  42181. lastCfg.old = storageName === 'nodeGroup'
  42182. ? [0, parentOldY]
  42183. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  42184. }
  42185. // Fade in, user can be aware that these nodes are new.
  42186. lastCfg.fadein = storageName !== 'nodeGroup';
  42187. }
  42188. }
  42189. // We can not set all backgroud with the same z, Because the behaviour of
  42190. // drill down and roll up differ background creation sequence from tree
  42191. // hierarchy sequence, which cause that lowser background element overlap
  42192. // upper ones. So we calculate z based on depth.
  42193. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  42194. // treemap with large z overlaps other components.
  42195. function calculateZ(depth, zInLevel) {
  42196. var zb = depth * Z_BASE + zInLevel;
  42197. return (zb - 1) / zb;
  42198. }
  42199. /*
  42200. * Licensed to the Apache Software Foundation (ASF) under one
  42201. * or more contributor license agreements. See the NOTICE file
  42202. * distributed with this work for additional information
  42203. * regarding copyright ownership. The ASF licenses this file
  42204. * to you under the Apache License, Version 2.0 (the
  42205. * "License"); you may not use this file except in compliance
  42206. * with the License. You may obtain a copy of the License at
  42207. *
  42208. * http://www.apache.org/licenses/LICENSE-2.0
  42209. *
  42210. * Unless required by applicable law or agreed to in writing,
  42211. * software distributed under the License is distributed on an
  42212. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42213. * KIND, either express or implied. See the License for the
  42214. * specific language governing permissions and limitations
  42215. * under the License.
  42216. */
  42217. /**
  42218. * @file Treemap action
  42219. */
  42220. var noop$1 = function () {};
  42221. var actionTypes = [
  42222. 'treemapZoomToNode',
  42223. 'treemapRender',
  42224. 'treemapMove'
  42225. ];
  42226. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  42227. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  42228. }
  42229. registerAction(
  42230. {type: 'treemapRootToNode', update: 'updateView'},
  42231. function (payload, ecModel) {
  42232. ecModel.eachComponent(
  42233. {mainType: 'series', subType: 'treemap', query: payload},
  42234. handleRootToNode
  42235. );
  42236. function handleRootToNode(model, index) {
  42237. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  42238. var targetInfo = retrieveTargetInfo(payload, types, model);
  42239. if (targetInfo) {
  42240. var originViewRoot = model.getViewRoot();
  42241. if (originViewRoot) {
  42242. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  42243. ? 'rollUp' : 'drillDown';
  42244. }
  42245. model.resetViewRoot(targetInfo.node);
  42246. }
  42247. }
  42248. }
  42249. );
  42250. /*
  42251. * Licensed to the Apache Software Foundation (ASF) under one
  42252. * or more contributor license agreements. See the NOTICE file
  42253. * distributed with this work for additional information
  42254. * regarding copyright ownership. The ASF licenses this file
  42255. * to you under the Apache License, Version 2.0 (the
  42256. * "License"); you may not use this file except in compliance
  42257. * with the License. You may obtain a copy of the License at
  42258. *
  42259. * http://www.apache.org/licenses/LICENSE-2.0
  42260. *
  42261. * Unless required by applicable law or agreed to in writing,
  42262. * software distributed under the License is distributed on an
  42263. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42264. * KIND, either express or implied. See the License for the
  42265. * specific language governing permissions and limitations
  42266. * under the License.
  42267. */
  42268. var each$9 = each$1;
  42269. var isObject$5 = isObject$1;
  42270. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  42271. /**
  42272. * @param {Object} option
  42273. * @param {string} [option.type] See visualHandlers.
  42274. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  42275. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  42276. * required when mappingMethod is 'linear'
  42277. * @param {Array.<Object>=} [option.pieceList] [
  42278. * {value: someValue},
  42279. * {interval: [min1, max1], visual: {...}},
  42280. * {interval: [min2, max2]}
  42281. * ],
  42282. * required when mappingMethod is 'piecewise'.
  42283. * Visual for only each piece can be specified.
  42284. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  42285. * required when mappingMethod is 'category'.
  42286. * If no option.categories, categories is set
  42287. * as [0, 1, 2, ...].
  42288. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  42289. * @param {(Array|Object|*)} [option.visual] Visual data.
  42290. * when mappingMethod is 'category',
  42291. * visual data can be array or object
  42292. * (like: {cate1: '#222', none: '#fff'})
  42293. * or primary types (which represents
  42294. * defualt category visual), otherwise visual
  42295. * can be array or primary (which will be
  42296. * normalized to array).
  42297. *
  42298. */
  42299. var VisualMapping = function (option) {
  42300. var mappingMethod = option.mappingMethod;
  42301. var visualType = option.type;
  42302. /**
  42303. * @readOnly
  42304. * @type {Object}
  42305. */
  42306. var thisOption = this.option = clone(option);
  42307. /**
  42308. * @readOnly
  42309. * @type {string}
  42310. */
  42311. this.type = visualType;
  42312. /**
  42313. * @readOnly
  42314. * @type {string}
  42315. */
  42316. this.mappingMethod = mappingMethod;
  42317. /**
  42318. * @private
  42319. * @type {Function}
  42320. */
  42321. this._normalizeData = normalizers[mappingMethod];
  42322. var visualHandler = visualHandlers[visualType];
  42323. /**
  42324. * @public
  42325. * @type {Function}
  42326. */
  42327. this.applyVisual = visualHandler.applyVisual;
  42328. /**
  42329. * @public
  42330. * @type {Function}
  42331. */
  42332. this.getColorMapper = visualHandler.getColorMapper;
  42333. /**
  42334. * @private
  42335. * @type {Function}
  42336. */
  42337. this._doMap = visualHandler._doMap[mappingMethod];
  42338. if (mappingMethod === 'piecewise') {
  42339. normalizeVisualRange(thisOption);
  42340. preprocessForPiecewise(thisOption);
  42341. }
  42342. else if (mappingMethod === 'category') {
  42343. thisOption.categories
  42344. ? preprocessForSpecifiedCategory(thisOption)
  42345. // categories is ordinal when thisOption.categories not specified,
  42346. // which need no more preprocess except normalize visual.
  42347. : normalizeVisualRange(thisOption, true);
  42348. }
  42349. else { // mappingMethod === 'linear' or 'fixed'
  42350. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  42351. normalizeVisualRange(thisOption);
  42352. }
  42353. };
  42354. VisualMapping.prototype = {
  42355. constructor: VisualMapping,
  42356. mapValueToVisual: function (value) {
  42357. var normalized = this._normalizeData(value);
  42358. return this._doMap(normalized, value);
  42359. },
  42360. getNormalizer: function () {
  42361. return bind(this._normalizeData, this);
  42362. }
  42363. };
  42364. var visualHandlers = VisualMapping.visualHandlers = {
  42365. color: {
  42366. applyVisual: makeApplyVisual('color'),
  42367. /**
  42368. * Create a mapper function
  42369. * @return {Function}
  42370. */
  42371. getColorMapper: function () {
  42372. var thisOption = this.option;
  42373. return bind(
  42374. thisOption.mappingMethod === 'category'
  42375. ? function (value, isNormalized) {
  42376. !isNormalized && (value = this._normalizeData(value));
  42377. return doMapCategory.call(this, value);
  42378. }
  42379. : function (value, isNormalized, out) {
  42380. // If output rgb array
  42381. // which will be much faster and useful in pixel manipulation
  42382. var returnRGBArray = !!out;
  42383. !isNormalized && (value = this._normalizeData(value));
  42384. out = fastLerp(value, thisOption.parsedVisual, out);
  42385. return returnRGBArray ? out : stringify(out, 'rgba');
  42386. },
  42387. this
  42388. );
  42389. },
  42390. _doMap: {
  42391. linear: function (normalized) {
  42392. return stringify(
  42393. fastLerp(normalized, this.option.parsedVisual),
  42394. 'rgba'
  42395. );
  42396. },
  42397. category: doMapCategory,
  42398. piecewise: function (normalized, value) {
  42399. var result = getSpecifiedVisual.call(this, value);
  42400. if (result == null) {
  42401. result = stringify(
  42402. fastLerp(normalized, this.option.parsedVisual),
  42403. 'rgba'
  42404. );
  42405. }
  42406. return result;
  42407. },
  42408. fixed: doMapFixed
  42409. }
  42410. },
  42411. colorHue: makePartialColorVisualHandler(function (color, value) {
  42412. return modifyHSL(color, value);
  42413. }),
  42414. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  42415. return modifyHSL(color, null, value);
  42416. }),
  42417. colorLightness: makePartialColorVisualHandler(function (color, value) {
  42418. return modifyHSL(color, null, null, value);
  42419. }),
  42420. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  42421. return modifyAlpha(color, value);
  42422. }),
  42423. opacity: {
  42424. applyVisual: makeApplyVisual('opacity'),
  42425. _doMap: makeDoMap([0, 1])
  42426. },
  42427. liftZ: {
  42428. applyVisual: makeApplyVisual('liftZ'),
  42429. _doMap: {
  42430. linear: doMapFixed,
  42431. category: doMapFixed,
  42432. piecewise: doMapFixed,
  42433. fixed: doMapFixed
  42434. }
  42435. },
  42436. symbol: {
  42437. applyVisual: function (value, getter, setter) {
  42438. var symbolCfg = this.mapValueToVisual(value);
  42439. if (isString(symbolCfg)) {
  42440. setter('symbol', symbolCfg);
  42441. }
  42442. else if (isObject$5(symbolCfg)) {
  42443. for (var name in symbolCfg) {
  42444. if (symbolCfg.hasOwnProperty(name)) {
  42445. setter(name, symbolCfg[name]);
  42446. }
  42447. }
  42448. }
  42449. },
  42450. _doMap: {
  42451. linear: doMapToArray,
  42452. category: doMapCategory,
  42453. piecewise: function (normalized, value) {
  42454. var result = getSpecifiedVisual.call(this, value);
  42455. if (result == null) {
  42456. result = doMapToArray.call(this, normalized);
  42457. }
  42458. return result;
  42459. },
  42460. fixed: doMapFixed
  42461. }
  42462. },
  42463. symbolSize: {
  42464. applyVisual: makeApplyVisual('symbolSize'),
  42465. _doMap: makeDoMap([0, 1])
  42466. }
  42467. };
  42468. function preprocessForPiecewise(thisOption) {
  42469. var pieceList = thisOption.pieceList;
  42470. thisOption.hasSpecialVisual = false;
  42471. each$1(pieceList, function (piece, index) {
  42472. piece.originIndex = index;
  42473. // piece.visual is "result visual value" but not
  42474. // a visual range, so it does not need to be normalized.
  42475. if (piece.visual != null) {
  42476. thisOption.hasSpecialVisual = true;
  42477. }
  42478. });
  42479. }
  42480. function preprocessForSpecifiedCategory(thisOption) {
  42481. // Hash categories.
  42482. var categories = thisOption.categories;
  42483. var visual = thisOption.visual;
  42484. var categoryMap = thisOption.categoryMap = {};
  42485. each$9(categories, function (cate, index) {
  42486. categoryMap[cate] = index;
  42487. });
  42488. // Process visual map input.
  42489. if (!isArray(visual)) {
  42490. var visualArr = [];
  42491. if (isObject$1(visual)) {
  42492. each$9(visual, function (v, cate) {
  42493. var index = categoryMap[cate];
  42494. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  42495. });
  42496. }
  42497. else { // Is primary type, represents default visual.
  42498. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  42499. }
  42500. visual = setVisualToOption(thisOption, visualArr);
  42501. }
  42502. // Remove categories that has no visual,
  42503. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  42504. for (var i = categories.length - 1; i >= 0; i--) {
  42505. if (visual[i] == null) {
  42506. delete categoryMap[categories[i]];
  42507. categories.pop();
  42508. }
  42509. }
  42510. }
  42511. function normalizeVisualRange(thisOption, isCategory) {
  42512. var visual = thisOption.visual;
  42513. var visualArr = [];
  42514. if (isObject$1(visual)) {
  42515. each$9(visual, function (v) {
  42516. visualArr.push(v);
  42517. });
  42518. }
  42519. else if (visual != null) {
  42520. visualArr.push(visual);
  42521. }
  42522. var doNotNeedPair = {color: 1, symbol: 1};
  42523. if (!isCategory
  42524. && visualArr.length === 1
  42525. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  42526. ) {
  42527. // Do not care visualArr.length === 0, which is illegal.
  42528. visualArr[1] = visualArr[0];
  42529. }
  42530. setVisualToOption(thisOption, visualArr);
  42531. }
  42532. function makePartialColorVisualHandler(applyValue) {
  42533. return {
  42534. applyVisual: function (value, getter, setter) {
  42535. value = this.mapValueToVisual(value);
  42536. // Must not be array value
  42537. setter('color', applyValue(getter('color'), value));
  42538. },
  42539. _doMap: makeDoMap([0, 1])
  42540. };
  42541. }
  42542. function doMapToArray(normalized) {
  42543. var visual = this.option.visual;
  42544. return visual[
  42545. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  42546. ] || {};
  42547. }
  42548. function makeApplyVisual(visualType) {
  42549. return function (value, getter, setter) {
  42550. setter(visualType, this.mapValueToVisual(value));
  42551. };
  42552. }
  42553. function doMapCategory(normalized) {
  42554. var visual = this.option.visual;
  42555. return visual[
  42556. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  42557. ? normalized % visual.length
  42558. : normalized
  42559. ];
  42560. }
  42561. function doMapFixed() {
  42562. return this.option.visual[0];
  42563. }
  42564. function makeDoMap(sourceExtent) {
  42565. return {
  42566. linear: function (normalized) {
  42567. return linearMap(normalized, sourceExtent, this.option.visual, true);
  42568. },
  42569. category: doMapCategory,
  42570. piecewise: function (normalized, value) {
  42571. var result = getSpecifiedVisual.call(this, value);
  42572. if (result == null) {
  42573. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  42574. }
  42575. return result;
  42576. },
  42577. fixed: doMapFixed
  42578. };
  42579. }
  42580. function getSpecifiedVisual(value) {
  42581. var thisOption = this.option;
  42582. var pieceList = thisOption.pieceList;
  42583. if (thisOption.hasSpecialVisual) {
  42584. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  42585. var piece = pieceList[pieceIndex];
  42586. if (piece && piece.visual) {
  42587. return piece.visual[this.type];
  42588. }
  42589. }
  42590. }
  42591. function setVisualToOption(thisOption, visualArr) {
  42592. thisOption.visual = visualArr;
  42593. if (thisOption.type === 'color') {
  42594. thisOption.parsedVisual = map(visualArr, function (item) {
  42595. return parse(item);
  42596. });
  42597. }
  42598. return visualArr;
  42599. }
  42600. /**
  42601. * Normalizers by mapping methods.
  42602. */
  42603. var normalizers = {
  42604. linear: function (value) {
  42605. return linearMap(value, this.option.dataExtent, [0, 1], true);
  42606. },
  42607. piecewise: function (value) {
  42608. var pieceList = this.option.pieceList;
  42609. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  42610. if (pieceIndex != null) {
  42611. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  42612. }
  42613. },
  42614. category: function (value) {
  42615. var index = this.option.categories
  42616. ? this.option.categoryMap[value]
  42617. : value; // ordinal
  42618. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  42619. },
  42620. fixed: noop
  42621. };
  42622. /**
  42623. * List available visual types.
  42624. *
  42625. * @public
  42626. * @return {Array.<string>}
  42627. */
  42628. VisualMapping.listVisualTypes = function () {
  42629. var visualTypes = [];
  42630. each$1(visualHandlers, function (handler, key) {
  42631. visualTypes.push(key);
  42632. });
  42633. return visualTypes;
  42634. };
  42635. /**
  42636. * @public
  42637. */
  42638. VisualMapping.addVisualHandler = function (name, handler) {
  42639. visualHandlers[name] = handler;
  42640. };
  42641. /**
  42642. * @public
  42643. */
  42644. VisualMapping.isValidType = function (visualType) {
  42645. return visualHandlers.hasOwnProperty(visualType);
  42646. };
  42647. /**
  42648. * Convinent method.
  42649. * Visual can be Object or Array or primary type.
  42650. *
  42651. * @public
  42652. */
  42653. VisualMapping.eachVisual = function (visual, callback, context) {
  42654. if (isObject$1(visual)) {
  42655. each$1(visual, callback, context);
  42656. }
  42657. else {
  42658. callback.call(context, visual);
  42659. }
  42660. };
  42661. VisualMapping.mapVisual = function (visual, callback, context) {
  42662. var isPrimary;
  42663. var newVisual = isArray(visual)
  42664. ? []
  42665. : isObject$1(visual)
  42666. ? {}
  42667. : (isPrimary = true, null);
  42668. VisualMapping.eachVisual(visual, function (v, key) {
  42669. var newVal = callback.call(context, v, key);
  42670. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  42671. });
  42672. return newVisual;
  42673. };
  42674. /**
  42675. * @public
  42676. * @param {Object} obj
  42677. * @return {Object} new object containers visual values.
  42678. * If no visuals, return null.
  42679. */
  42680. VisualMapping.retrieveVisuals = function (obj) {
  42681. var ret = {};
  42682. var hasVisual;
  42683. obj && each$9(visualHandlers, function (h, visualType) {
  42684. if (obj.hasOwnProperty(visualType)) {
  42685. ret[visualType] = obj[visualType];
  42686. hasVisual = true;
  42687. }
  42688. });
  42689. return hasVisual ? ret : null;
  42690. };
  42691. /**
  42692. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  42693. *
  42694. * @public
  42695. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  42696. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  42697. * @return {Array.<string>} Sorted visual types.
  42698. */
  42699. VisualMapping.prepareVisualTypes = function (visualTypes) {
  42700. if (isObject$5(visualTypes)) {
  42701. var types = [];
  42702. each$9(visualTypes, function (item, type) {
  42703. types.push(type);
  42704. });
  42705. visualTypes = types;
  42706. }
  42707. else if (isArray(visualTypes)) {
  42708. visualTypes = visualTypes.slice();
  42709. }
  42710. else {
  42711. return [];
  42712. }
  42713. visualTypes.sort(function (type1, type2) {
  42714. // color should be front of colorSaturation, colorAlpha, ...
  42715. // symbol and symbolSize do not matter.
  42716. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  42717. ? 1 : -1;
  42718. });
  42719. return visualTypes;
  42720. };
  42721. /**
  42722. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  42723. * Other visuals are only depends on themself.
  42724. *
  42725. * @public
  42726. * @param {string} visualType1
  42727. * @param {string} visualType2
  42728. * @return {boolean}
  42729. */
  42730. VisualMapping.dependsOn = function (visualType1, visualType2) {
  42731. return visualType2 === 'color'
  42732. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  42733. : visualType1 === visualType2;
  42734. };
  42735. /**
  42736. * @param {number} value
  42737. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  42738. * Always from small to big.
  42739. * @param {boolean} [findClosestWhenOutside=false]
  42740. * @return {number} index
  42741. */
  42742. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  42743. var possibleI;
  42744. var abs = Infinity;
  42745. // value has the higher priority.
  42746. for (var i = 0, len = pieceList.length; i < len; i++) {
  42747. var pieceValue = pieceList[i].value;
  42748. if (pieceValue != null) {
  42749. if (pieceValue === value
  42750. // FIXME
  42751. // It is supposed to compare value according to value type of dimension,
  42752. // but currently value type can exactly be string or number.
  42753. // Compromise for numeric-like string (like '12'), especially
  42754. // in the case that visualMap.categories is ['22', '33'].
  42755. || (typeof pieceValue === 'string' && pieceValue === value + '')
  42756. ) {
  42757. return i;
  42758. }
  42759. findClosestWhenOutside && updatePossible(pieceValue, i);
  42760. }
  42761. }
  42762. for (var i = 0, len = pieceList.length; i < len; i++) {
  42763. var piece = pieceList[i];
  42764. var interval = piece.interval;
  42765. var close = piece.close;
  42766. if (interval) {
  42767. if (interval[0] === -Infinity) {
  42768. if (littleThan(close[1], value, interval[1])) {
  42769. return i;
  42770. }
  42771. }
  42772. else if (interval[1] === Infinity) {
  42773. if (littleThan(close[0], interval[0], value)) {
  42774. return i;
  42775. }
  42776. }
  42777. else if (
  42778. littleThan(close[0], interval[0], value)
  42779. && littleThan(close[1], value, interval[1])
  42780. ) {
  42781. return i;
  42782. }
  42783. findClosestWhenOutside && updatePossible(interval[0], i);
  42784. findClosestWhenOutside && updatePossible(interval[1], i);
  42785. }
  42786. }
  42787. if (findClosestWhenOutside) {
  42788. return value === Infinity
  42789. ? pieceList.length - 1
  42790. : value === -Infinity
  42791. ? 0
  42792. : possibleI;
  42793. }
  42794. function updatePossible(val, index) {
  42795. var newAbs = Math.abs(val - value);
  42796. if (newAbs < abs) {
  42797. abs = newAbs;
  42798. possibleI = index;
  42799. }
  42800. }
  42801. };
  42802. function littleThan(close, a, b) {
  42803. return close ? a <= b : a < b;
  42804. }
  42805. /*
  42806. * Licensed to the Apache Software Foundation (ASF) under one
  42807. * or more contributor license agreements. See the NOTICE file
  42808. * distributed with this work for additional information
  42809. * regarding copyright ownership. The ASF licenses this file
  42810. * to you under the Apache License, Version 2.0 (the
  42811. * "License"); you may not use this file except in compliance
  42812. * with the License. You may obtain a copy of the License at
  42813. *
  42814. * http://www.apache.org/licenses/LICENSE-2.0
  42815. *
  42816. * Unless required by applicable law or agreed to in writing,
  42817. * software distributed under the License is distributed on an
  42818. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42819. * KIND, either express or implied. See the License for the
  42820. * specific language governing permissions and limitations
  42821. * under the License.
  42822. */
  42823. var isArray$2 = isArray;
  42824. var ITEM_STYLE_NORMAL = 'itemStyle';
  42825. var treemapVisual = {
  42826. seriesType: 'treemap',
  42827. reset: function (seriesModel, ecModel, api, payload) {
  42828. var tree = seriesModel.getData().tree;
  42829. var root = tree.root;
  42830. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  42831. if (root.isRemoved()) {
  42832. return;
  42833. }
  42834. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  42835. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  42836. });
  42837. travelTree(
  42838. root, // Visual should calculate from tree root but not view root.
  42839. {},
  42840. levelItemStyles,
  42841. seriesItemStyleModel,
  42842. seriesModel.getViewRoot().getAncestors(),
  42843. seriesModel
  42844. );
  42845. }
  42846. };
  42847. function travelTree(
  42848. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  42849. viewRootAncestors, seriesModel
  42850. ) {
  42851. var nodeModel = node.getModel();
  42852. var nodeLayout = node.getLayout();
  42853. // Optimize
  42854. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  42855. return;
  42856. }
  42857. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  42858. var levelItemStyle = levelItemStyles[node.depth];
  42859. var visuals = buildVisuals(
  42860. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  42861. );
  42862. // calculate border color
  42863. var borderColor = nodeItemStyleModel.get('borderColor');
  42864. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  42865. var thisNodeColor;
  42866. if (borderColorSaturation != null) {
  42867. // For performance, do not always execute 'calculateColor'.
  42868. thisNodeColor = calculateColor(visuals, node);
  42869. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  42870. }
  42871. node.setVisual('borderColor', borderColor);
  42872. var viewChildren = node.viewChildren;
  42873. if (!viewChildren || !viewChildren.length) {
  42874. thisNodeColor = calculateColor(visuals, node);
  42875. // Apply visual to this node.
  42876. node.setVisual('color', thisNodeColor);
  42877. }
  42878. else {
  42879. var mapping = buildVisualMapping(
  42880. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  42881. );
  42882. // Designate visual to children.
  42883. each$1(viewChildren, function (child, index) {
  42884. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  42885. if (child.depth >= viewRootAncestors.length
  42886. || child === viewRootAncestors[child.depth]
  42887. ) {
  42888. var childVisual = mapVisual$1(
  42889. nodeModel, visuals, child, index, mapping, seriesModel
  42890. );
  42891. travelTree(
  42892. child, childVisual, levelItemStyles, seriesItemStyleModel,
  42893. viewRootAncestors, seriesModel
  42894. );
  42895. }
  42896. });
  42897. }
  42898. }
  42899. function buildVisuals(
  42900. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  42901. ) {
  42902. var visuals = extend({}, designatedVisual);
  42903. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  42904. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  42905. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  42906. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  42907. val == null && (val = designatedVisual[visualName]);
  42908. val == null && (val = seriesItemStyleModel.get(visualName));
  42909. val != null && (visuals[visualName] = val);
  42910. });
  42911. return visuals;
  42912. }
  42913. function calculateColor(visuals) {
  42914. var color = getValueVisualDefine(visuals, 'color');
  42915. if (color) {
  42916. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  42917. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  42918. if (colorSaturation) {
  42919. color = modifyHSL(color, null, null, colorSaturation);
  42920. }
  42921. if (colorAlpha) {
  42922. color = modifyAlpha(color, colorAlpha);
  42923. }
  42924. return color;
  42925. }
  42926. }
  42927. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  42928. return thisNodeColor != null
  42929. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  42930. : null;
  42931. }
  42932. function getValueVisualDefine(visuals, name) {
  42933. var value = visuals[name];
  42934. if (value != null && value !== 'none') {
  42935. return value;
  42936. }
  42937. }
  42938. function buildVisualMapping(
  42939. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  42940. ) {
  42941. if (!viewChildren || !viewChildren.length) {
  42942. return;
  42943. }
  42944. var rangeVisual = getRangeVisual(nodeModel, 'color')
  42945. || (
  42946. visuals.color != null
  42947. && visuals.color !== 'none'
  42948. && (
  42949. getRangeVisual(nodeModel, 'colorAlpha')
  42950. || getRangeVisual(nodeModel, 'colorSaturation')
  42951. )
  42952. );
  42953. if (!rangeVisual) {
  42954. return;
  42955. }
  42956. var visualMin = nodeModel.get('visualMin');
  42957. var visualMax = nodeModel.get('visualMax');
  42958. var dataExtent = nodeLayout.dataExtent.slice();
  42959. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  42960. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  42961. var colorMappingBy = nodeModel.get('colorMappingBy');
  42962. var opt = {
  42963. type: rangeVisual.name,
  42964. dataExtent: dataExtent,
  42965. visual: rangeVisual.range
  42966. };
  42967. if (opt.type === 'color'
  42968. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  42969. ) {
  42970. opt.mappingMethod = 'category';
  42971. opt.loop = true;
  42972. // categories is ordinal, so do not set opt.categories.
  42973. }
  42974. else {
  42975. opt.mappingMethod = 'linear';
  42976. }
  42977. var mapping = new VisualMapping(opt);
  42978. mapping.__drColorMappingBy = colorMappingBy;
  42979. return mapping;
  42980. }
  42981. // Notice: If we dont have the attribute 'colorRange', but only use
  42982. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  42983. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  42984. // this problem will be encountered:
  42985. // If a level-1 node dont have children, and its siblings has children,
  42986. // and colorRange is set on level-1, then the node can not be colored.
  42987. // So we separate 'colorRange' and 'color' to different attributes.
  42988. function getRangeVisual(nodeModel, name) {
  42989. // 'colorRange', 'colorARange', 'colorSRange'.
  42990. // If not exsits on this node, fetch from levels and series.
  42991. var range = nodeModel.get(name);
  42992. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  42993. }
  42994. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  42995. var childVisuals = extend({}, visuals);
  42996. if (mapping) {
  42997. var mappingType = mapping.type;
  42998. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  42999. var value =
  43000. colorMappingBy === 'index'
  43001. ? index
  43002. : colorMappingBy === 'id'
  43003. ? seriesModel.mapIdToIndex(child.getId())
  43004. : child.getValue(nodeModel.get('visualDimension'));
  43005. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  43006. }
  43007. return childVisuals;
  43008. }
  43009. /*
  43010. * Licensed to the Apache Software Foundation (ASF) under one
  43011. * or more contributor license agreements. See the NOTICE file
  43012. * distributed with this work for additional information
  43013. * regarding copyright ownership. The ASF licenses this file
  43014. * to you under the Apache License, Version 2.0 (the
  43015. * "License"); you may not use this file except in compliance
  43016. * with the License. You may obtain a copy of the License at
  43017. *
  43018. * http://www.apache.org/licenses/LICENSE-2.0
  43019. *
  43020. * Unless required by applicable law or agreed to in writing,
  43021. * software distributed under the License is distributed on an
  43022. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43023. * KIND, either express or implied. See the License for the
  43024. * specific language governing permissions and limitations
  43025. * under the License.
  43026. */
  43027. /*
  43028. * The treemap layout implementation references to the treemap
  43029. * layout of d3.js (d3/src/layout/treemap.js in v3). The use of
  43030. * the source code of this file is also subject to the terms
  43031. * and consitions of its license (BSD-3Clause, see
  43032. * <echarts/src/licenses/LICENSE-d3>).
  43033. */
  43034. var mathMax$4 = Math.max;
  43035. var mathMin$4 = Math.min;
  43036. var retrieveValue = retrieve;
  43037. var each$10 = each$1;
  43038. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  43039. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  43040. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  43041. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  43042. /**
  43043. * @public
  43044. */
  43045. var treemapLayout = {
  43046. seriesType: 'treemap',
  43047. reset: function (seriesModel, ecModel, api, payload) {
  43048. // Layout result in each node:
  43049. // {x, y, width, height, area, borderWidth}
  43050. var ecWidth = api.getWidth();
  43051. var ecHeight = api.getHeight();
  43052. var seriesOption = seriesModel.option;
  43053. var layoutInfo = getLayoutRect(
  43054. seriesModel.getBoxLayoutParams(),
  43055. {
  43056. width: api.getWidth(),
  43057. height: api.getHeight()
  43058. }
  43059. );
  43060. var size = seriesOption.size || []; // Compatible with ec2.
  43061. var containerWidth = parsePercent$1(
  43062. retrieveValue(layoutInfo.width, size[0]),
  43063. ecWidth
  43064. );
  43065. var containerHeight = parsePercent$1(
  43066. retrieveValue(layoutInfo.height, size[1]),
  43067. ecHeight
  43068. );
  43069. // Fetch payload info.
  43070. var payloadType = payload && payload.type;
  43071. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  43072. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  43073. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  43074. ? payload.rootRect : null;
  43075. var viewRoot = seriesModel.getViewRoot();
  43076. var viewAbovePath = getPathToRoot(viewRoot);
  43077. if (payloadType !== 'treemapMove') {
  43078. var rootSize = payloadType === 'treemapZoomToNode'
  43079. ? estimateRootSize(
  43080. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  43081. )
  43082. : rootRect
  43083. ? [rootRect.width, rootRect.height]
  43084. : [containerWidth, containerHeight];
  43085. var sort = seriesOption.sort;
  43086. if (sort && sort !== 'asc' && sort !== 'desc') {
  43087. sort = 'desc';
  43088. }
  43089. var options = {
  43090. squareRatio: seriesOption.squareRatio,
  43091. sort: sort,
  43092. leafDepth: seriesOption.leafDepth
  43093. };
  43094. // layout should be cleared because using updateView but not update.
  43095. viewRoot.hostTree.clearLayouts();
  43096. // TODO
  43097. // optimize: if out of view clip, do not layout.
  43098. // But take care that if do not render node out of view clip,
  43099. // how to calculate start po
  43100. var viewRootLayout = {
  43101. x: 0, y: 0,
  43102. width: rootSize[0], height: rootSize[1],
  43103. area: rootSize[0] * rootSize[1]
  43104. };
  43105. viewRoot.setLayout(viewRootLayout);
  43106. squarify(viewRoot, options, false, 0);
  43107. // Supplement layout.
  43108. var viewRootLayout = viewRoot.getLayout();
  43109. each$10(viewAbovePath, function (node, index) {
  43110. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  43111. node.setLayout(extend(
  43112. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  43113. viewRootLayout
  43114. ));
  43115. });
  43116. }
  43117. var treeRoot = seriesModel.getData().tree.root;
  43118. treeRoot.setLayout(
  43119. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  43120. true
  43121. );
  43122. seriesModel.setLayoutInfo(layoutInfo);
  43123. // FIXME
  43124. // 现在没有clip功能,暂时取ec高宽。
  43125. prunning(
  43126. treeRoot,
  43127. // Transform to base element coordinate system.
  43128. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  43129. viewAbovePath,
  43130. viewRoot,
  43131. 0
  43132. );
  43133. }
  43134. };
  43135. /**
  43136. * Layout treemap with squarify algorithm.
  43137. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  43138. * The implementation references to the treemap layout of d3.js.
  43139. * See the license statement at the head of this file.
  43140. *
  43141. * @protected
  43142. * @param {module:echarts/data/Tree~TreeNode} node
  43143. * @param {Object} options
  43144. * @param {string} options.sort 'asc' or 'desc'
  43145. * @param {number} options.squareRatio
  43146. * @param {boolean} hideChildren
  43147. * @param {number} depth
  43148. */
  43149. function squarify(node, options, hideChildren, depth) {
  43150. var width;
  43151. var height;
  43152. if (node.isRemoved()) {
  43153. return;
  43154. }
  43155. var thisLayout = node.getLayout();
  43156. width = thisLayout.width;
  43157. height = thisLayout.height;
  43158. // Considering border and gap
  43159. var nodeModel = node.getModel();
  43160. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  43161. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  43162. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  43163. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  43164. var layoutOffset = borderWidth - halfGapWidth;
  43165. var layoutOffsetUpper = upperHeight - halfGapWidth;
  43166. var nodeModel = node.getModel();
  43167. node.setLayout({
  43168. borderWidth: borderWidth,
  43169. upperHeight: upperHeight,
  43170. upperLabelHeight: upperLabelHeight
  43171. }, true);
  43172. width = mathMax$4(width - 2 * layoutOffset, 0);
  43173. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  43174. var totalArea = width * height;
  43175. var viewChildren = initChildren(
  43176. node, nodeModel, totalArea, options, hideChildren, depth
  43177. );
  43178. if (!viewChildren.length) {
  43179. return;
  43180. }
  43181. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  43182. var rowFixedLength = mathMin$4(width, height);
  43183. var best = Infinity; // the best row score so far
  43184. var row = [];
  43185. row.area = 0;
  43186. for (var i = 0, len = viewChildren.length; i < len;) {
  43187. var child = viewChildren[i];
  43188. row.push(child);
  43189. row.area += child.getLayout().area;
  43190. var score = worst(row, rowFixedLength, options.squareRatio);
  43191. // continue with this orientation
  43192. if (score <= best) {
  43193. i++;
  43194. best = score;
  43195. }
  43196. // abort, and try a different orientation
  43197. else {
  43198. row.area -= row.pop().getLayout().area;
  43199. position(row, rowFixedLength, rect, halfGapWidth, false);
  43200. rowFixedLength = mathMin$4(rect.width, rect.height);
  43201. row.length = row.area = 0;
  43202. best = Infinity;
  43203. }
  43204. }
  43205. if (row.length) {
  43206. position(row, rowFixedLength, rect, halfGapWidth, true);
  43207. }
  43208. if (!hideChildren) {
  43209. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  43210. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  43211. hideChildren = true;
  43212. }
  43213. }
  43214. for (var i = 0, len = viewChildren.length; i < len; i++) {
  43215. squarify(viewChildren[i], options, hideChildren, depth + 1);
  43216. }
  43217. }
  43218. /**
  43219. * Set area to each child, and calculate data extent for visual coding.
  43220. */
  43221. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  43222. var viewChildren = node.children || [];
  43223. var orderBy = options.sort;
  43224. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  43225. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  43226. // leafDepth has higher priority.
  43227. if (hideChildren && !overLeafDepth) {
  43228. return (node.viewChildren = []);
  43229. }
  43230. // Sort children, order by desc.
  43231. viewChildren = filter(viewChildren, function (child) {
  43232. return !child.isRemoved();
  43233. });
  43234. sort$1(viewChildren, orderBy);
  43235. var info = statistic(nodeModel, viewChildren, orderBy);
  43236. if (info.sum === 0) {
  43237. return (node.viewChildren = []);
  43238. }
  43239. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  43240. if (info.sum === 0) {
  43241. return (node.viewChildren = []);
  43242. }
  43243. // Set area to each child.
  43244. for (var i = 0, len = viewChildren.length; i < len; i++) {
  43245. var area = viewChildren[i].getValue() / info.sum * totalArea;
  43246. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  43247. viewChildren[i].setLayout({area: area});
  43248. }
  43249. if (overLeafDepth) {
  43250. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  43251. viewChildren.length = 0;
  43252. }
  43253. node.viewChildren = viewChildren;
  43254. node.setLayout({dataExtent: info.dataExtent}, true);
  43255. return viewChildren;
  43256. }
  43257. /**
  43258. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  43259. */
  43260. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  43261. // visibleMin is not supported yet when no option.sort.
  43262. if (!orderBy) {
  43263. return sum;
  43264. }
  43265. var visibleMin = nodeModel.get('visibleMin');
  43266. var len = orderedChildren.length;
  43267. var deletePoint = len;
  43268. // Always travel from little value to big value.
  43269. for (var i = len - 1; i >= 0; i--) {
  43270. var value = orderedChildren[
  43271. orderBy === 'asc' ? len - i - 1 : i
  43272. ].getValue();
  43273. if (value / sum * totalArea < visibleMin) {
  43274. deletePoint = i;
  43275. sum -= value;
  43276. }
  43277. }
  43278. orderBy === 'asc'
  43279. ? orderedChildren.splice(0, len - deletePoint)
  43280. : orderedChildren.splice(deletePoint, len - deletePoint);
  43281. return sum;
  43282. }
  43283. /**
  43284. * Sort
  43285. */
  43286. function sort$1(viewChildren, orderBy) {
  43287. if (orderBy) {
  43288. viewChildren.sort(function (a, b) {
  43289. var diff = orderBy === 'asc'
  43290. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  43291. return diff === 0
  43292. ? (orderBy === 'asc'
  43293. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  43294. )
  43295. : diff;
  43296. });
  43297. }
  43298. return viewChildren;
  43299. }
  43300. /**
  43301. * Statistic
  43302. */
  43303. function statistic(nodeModel, children, orderBy) {
  43304. // Calculate sum.
  43305. var sum = 0;
  43306. for (var i = 0, len = children.length; i < len; i++) {
  43307. sum += children[i].getValue();
  43308. }
  43309. // Statistic data extent for latter visual coding.
  43310. // Notice: data extent should be calculate based on raw children
  43311. // but not filtered view children, otherwise visual mapping will not
  43312. // be stable when zoom (where children is filtered by visibleMin).
  43313. var dimension = nodeModel.get('visualDimension');
  43314. var dataExtent;
  43315. // The same as area dimension.
  43316. if (!children || !children.length) {
  43317. dataExtent = [NaN, NaN];
  43318. }
  43319. else if (dimension === 'value' && orderBy) {
  43320. dataExtent = [
  43321. children[children.length - 1].getValue(),
  43322. children[0].getValue()
  43323. ];
  43324. orderBy === 'asc' && dataExtent.reverse();
  43325. }
  43326. // Other dimension.
  43327. else {
  43328. var dataExtent = [Infinity, -Infinity];
  43329. each$10(children, function (child) {
  43330. var value = child.getValue(dimension);
  43331. value < dataExtent[0] && (dataExtent[0] = value);
  43332. value > dataExtent[1] && (dataExtent[1] = value);
  43333. });
  43334. }
  43335. return {sum: sum, dataExtent: dataExtent};
  43336. }
  43337. /**
  43338. * Computes the score for the specified row,
  43339. * as the worst aspect ratio.
  43340. */
  43341. function worst(row, rowFixedLength, ratio) {
  43342. var areaMax = 0;
  43343. var areaMin = Infinity;
  43344. for (var i = 0, area, len = row.length; i < len; i++) {
  43345. area = row[i].getLayout().area;
  43346. if (area) {
  43347. area < areaMin && (areaMin = area);
  43348. area > areaMax && (areaMax = area);
  43349. }
  43350. }
  43351. var squareArea = row.area * row.area;
  43352. var f = rowFixedLength * rowFixedLength * ratio;
  43353. return squareArea
  43354. ? mathMax$4(
  43355. (f * areaMax) / squareArea,
  43356. squareArea / (f * areaMin)
  43357. )
  43358. : Infinity;
  43359. }
  43360. /**
  43361. * Positions the specified row of nodes. Modifies `rect`.
  43362. */
  43363. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  43364. // When rowFixedLength === rect.width,
  43365. // it is horizontal subdivision,
  43366. // rowFixedLength is the width of the subdivision,
  43367. // rowOtherLength is the height of the subdivision,
  43368. // and nodes will be positioned from left to right.
  43369. // wh[idx0WhenH] means: when horizontal,
  43370. // wh[idx0WhenH] => wh[0] => 'width'.
  43371. // xy[idx1WhenH] => xy[1] => 'y'.
  43372. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  43373. var idx1WhenH = 1 - idx0WhenH;
  43374. var xy = ['x', 'y'];
  43375. var wh = ['width', 'height'];
  43376. var last = rect[xy[idx0WhenH]];
  43377. var rowOtherLength = rowFixedLength
  43378. ? row.area / rowFixedLength : 0;
  43379. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  43380. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  43381. }
  43382. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  43383. var node = row[i];
  43384. var nodeLayout = {};
  43385. var step = rowOtherLength
  43386. ? node.getLayout().area / rowOtherLength : 0;
  43387. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  43388. // We use Math.max/min to avoid negative width/height when considering gap width.
  43389. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  43390. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  43391. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  43392. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  43393. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  43394. last += modWH;
  43395. node.setLayout(nodeLayout, true);
  43396. }
  43397. rect[xy[idx1WhenH]] += rowOtherLength;
  43398. rect[wh[idx1WhenH]] -= rowOtherLength;
  43399. }
  43400. // Return [containerWidth, containerHeight] as defualt.
  43401. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  43402. // If targetInfo.node exists, we zoom to the node,
  43403. // so estimate whold width and heigth by target node.
  43404. var currNode = (targetInfo || {}).node;
  43405. var defaultSize = [containerWidth, containerHeight];
  43406. if (!currNode || currNode === viewRoot) {
  43407. return defaultSize;
  43408. }
  43409. var parent;
  43410. var viewArea = containerWidth * containerHeight;
  43411. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  43412. while (parent = currNode.parentNode) { // jshint ignore:line
  43413. var sum = 0;
  43414. var siblings = parent.children;
  43415. for (var i = 0, len = siblings.length; i < len; i++) {
  43416. sum += siblings[i].getValue();
  43417. }
  43418. var currNodeValue = currNode.getValue();
  43419. if (currNodeValue === 0) {
  43420. return defaultSize;
  43421. }
  43422. area *= sum / currNodeValue;
  43423. // Considering border, suppose aspect ratio is 1.
  43424. var parentModel = parent.getModel();
  43425. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  43426. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  43427. area += 4 * borderWidth * borderWidth
  43428. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  43429. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  43430. currNode = parent;
  43431. }
  43432. area < viewArea && (area = viewArea);
  43433. var scale = Math.pow(area / viewArea, 0.5);
  43434. return [containerWidth * scale, containerHeight * scale];
  43435. }
  43436. // Root postion base on coord of containerGroup
  43437. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  43438. if (rootRect) {
  43439. return {x: rootRect.x, y: rootRect.y};
  43440. }
  43441. var defaultPosition = {x: 0, y: 0};
  43442. if (!targetInfo) {
  43443. return defaultPosition;
  43444. }
  43445. // If targetInfo is fetched by 'retrieveTargetInfo',
  43446. // old tree and new tree are the same tree,
  43447. // so the node still exists and we can visit it.
  43448. var targetNode = targetInfo.node;
  43449. var layout = targetNode.getLayout();
  43450. if (!layout) {
  43451. return defaultPosition;
  43452. }
  43453. // Transform coord from local to container.
  43454. var targetCenter = [layout.width / 2, layout.height / 2];
  43455. var node = targetNode;
  43456. while (node) {
  43457. var nodeLayout = node.getLayout();
  43458. targetCenter[0] += nodeLayout.x;
  43459. targetCenter[1] += nodeLayout.y;
  43460. node = node.parentNode;
  43461. }
  43462. return {
  43463. x: layoutInfo.width / 2 - targetCenter[0],
  43464. y: layoutInfo.height / 2 - targetCenter[1]
  43465. };
  43466. }
  43467. // Mark nodes visible for prunning when visual coding and rendering.
  43468. // Prunning depends on layout and root position, so we have to do it after layout.
  43469. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  43470. var nodeLayout = node.getLayout();
  43471. var nodeInViewAbovePath = viewAbovePath[depth];
  43472. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  43473. if (
  43474. (nodeInViewAbovePath && !isAboveViewRoot)
  43475. || (depth === viewAbovePath.length && node !== viewRoot)
  43476. ) {
  43477. return;
  43478. }
  43479. node.setLayout({
  43480. // isInView means: viewRoot sub tree + viewAbovePath
  43481. isInView: true,
  43482. // invisible only means: outside view clip so that the node can not
  43483. // see but still layout for animation preparation but not render.
  43484. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  43485. isAboveViewRoot: isAboveViewRoot
  43486. }, true);
  43487. // Transform to child coordinate.
  43488. var childClipRect = new BoundingRect(
  43489. clipRect.x - nodeLayout.x,
  43490. clipRect.y - nodeLayout.y,
  43491. clipRect.width,
  43492. clipRect.height
  43493. );
  43494. each$10(node.viewChildren || [], function (child) {
  43495. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  43496. });
  43497. }
  43498. function getUpperLabelHeight(model) {
  43499. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  43500. }
  43501. /*
  43502. * Licensed to the Apache Software Foundation (ASF) under one
  43503. * or more contributor license agreements. See the NOTICE file
  43504. * distributed with this work for additional information
  43505. * regarding copyright ownership. The ASF licenses this file
  43506. * to you under the Apache License, Version 2.0 (the
  43507. * "License"); you may not use this file except in compliance
  43508. * with the License. You may obtain a copy of the License at
  43509. *
  43510. * http://www.apache.org/licenses/LICENSE-2.0
  43511. *
  43512. * Unless required by applicable law or agreed to in writing,
  43513. * software distributed under the License is distributed on an
  43514. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43515. * KIND, either express or implied. See the License for the
  43516. * specific language governing permissions and limitations
  43517. * under the License.
  43518. */
  43519. registerVisual(treemapVisual);
  43520. registerLayout(treemapLayout);
  43521. /*
  43522. * Licensed to the Apache Software Foundation (ASF) under one
  43523. * or more contributor license agreements. See the NOTICE file
  43524. * distributed with this work for additional information
  43525. * regarding copyright ownership. The ASF licenses this file
  43526. * to you under the Apache License, Version 2.0 (the
  43527. * "License"); you may not use this file except in compliance
  43528. * with the License. You may obtain a copy of the License at
  43529. *
  43530. * http://www.apache.org/licenses/LICENSE-2.0
  43531. *
  43532. * Unless required by applicable law or agreed to in writing,
  43533. * software distributed under the License is distributed on an
  43534. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43535. * KIND, either express or implied. See the License for the
  43536. * specific language governing permissions and limitations
  43537. * under the License.
  43538. */
  43539. /**
  43540. * Graph data structure
  43541. *
  43542. * @module echarts/data/Graph
  43543. * @author Yi Shen(https://www.github.com/pissang)
  43544. */
  43545. // id may be function name of Object, add a prefix to avoid this problem.
  43546. function generateNodeKey (id) {
  43547. return '_EC_' + id;
  43548. }
  43549. /**
  43550. * @alias module:echarts/data/Graph
  43551. * @constructor
  43552. * @param {boolean} directed
  43553. */
  43554. var Graph = function(directed) {
  43555. /**
  43556. * 是否是有向图
  43557. * @type {boolean}
  43558. * @private
  43559. */
  43560. this._directed = directed || false;
  43561. /**
  43562. * @type {Array.<module:echarts/data/Graph.Node>}
  43563. * @readOnly
  43564. */
  43565. this.nodes = [];
  43566. /**
  43567. * @type {Array.<module:echarts/data/Graph.Edge>}
  43568. * @readOnly
  43569. */
  43570. this.edges = [];
  43571. /**
  43572. * @type {Object.<string, module:echarts/data/Graph.Node>}
  43573. * @private
  43574. */
  43575. this._nodesMap = {};
  43576. /**
  43577. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  43578. * @private
  43579. */
  43580. this._edgesMap = {};
  43581. /**
  43582. * @type {module:echarts/data/List}
  43583. * @readOnly
  43584. */
  43585. this.data;
  43586. /**
  43587. * @type {module:echarts/data/List}
  43588. * @readOnly
  43589. */
  43590. this.edgeData;
  43591. };
  43592. var graphProto = Graph.prototype;
  43593. /**
  43594. * @type {string}
  43595. */
  43596. graphProto.type = 'graph';
  43597. /**
  43598. * If is directed graph
  43599. * @return {boolean}
  43600. */
  43601. graphProto.isDirected = function () {
  43602. return this._directed;
  43603. };
  43604. /**
  43605. * Add a new node
  43606. * @param {string} id
  43607. * @param {number} [dataIndex]
  43608. */
  43609. graphProto.addNode = function (id, dataIndex) {
  43610. id = id || ('' + dataIndex);
  43611. var nodesMap = this._nodesMap;
  43612. if (nodesMap[generateNodeKey(id)]) {
  43613. if (__DEV__) {
  43614. console.error('Graph nodes have duplicate name or id');
  43615. }
  43616. return;
  43617. }
  43618. var node = new Node(id, dataIndex);
  43619. node.hostGraph = this;
  43620. this.nodes.push(node);
  43621. nodesMap[generateNodeKey(id)] = node;
  43622. return node;
  43623. };
  43624. /**
  43625. * Get node by data index
  43626. * @param {number} dataIndex
  43627. * @return {module:echarts/data/Graph~Node}
  43628. */
  43629. graphProto.getNodeByIndex = function (dataIndex) {
  43630. var rawIdx = this.data.getRawIndex(dataIndex);
  43631. return this.nodes[rawIdx];
  43632. };
  43633. /**
  43634. * Get node by id
  43635. * @param {string} id
  43636. * @return {module:echarts/data/Graph.Node}
  43637. */
  43638. graphProto.getNodeById = function (id) {
  43639. return this._nodesMap[generateNodeKey(id)];
  43640. };
  43641. /**
  43642. * Add a new edge
  43643. * @param {number|string|module:echarts/data/Graph.Node} n1
  43644. * @param {number|string|module:echarts/data/Graph.Node} n2
  43645. * @param {number} [dataIndex=-1]
  43646. * @return {module:echarts/data/Graph.Edge}
  43647. */
  43648. graphProto.addEdge = function (n1, n2, dataIndex) {
  43649. var nodesMap = this._nodesMap;
  43650. var edgesMap = this._edgesMap;
  43651. // PNEDING
  43652. if (typeof n1 === 'number') {
  43653. n1 = this.nodes[n1];
  43654. }
  43655. if (typeof n2 === 'number') {
  43656. n2 = this.nodes[n2];
  43657. }
  43658. if (!Node.isInstance(n1)) {
  43659. n1 = nodesMap[generateNodeKey(n1)];
  43660. }
  43661. if (!Node.isInstance(n2)) {
  43662. n2 = nodesMap[generateNodeKey(n2)];
  43663. }
  43664. if (!n1 || !n2) {
  43665. return;
  43666. }
  43667. var key = n1.id + '-' + n2.id;
  43668. // PENDING
  43669. if (edgesMap[key]) {
  43670. return;
  43671. }
  43672. var edge = new Edge(n1, n2, dataIndex);
  43673. edge.hostGraph = this;
  43674. if (this._directed) {
  43675. n1.outEdges.push(edge);
  43676. n2.inEdges.push(edge);
  43677. }
  43678. n1.edges.push(edge);
  43679. if (n1 !== n2) {
  43680. n2.edges.push(edge);
  43681. }
  43682. this.edges.push(edge);
  43683. edgesMap[key] = edge;
  43684. return edge;
  43685. };
  43686. /**
  43687. * Get edge by data index
  43688. * @param {number} dataIndex
  43689. * @return {module:echarts/data/Graph~Node}
  43690. */
  43691. graphProto.getEdgeByIndex = function (dataIndex) {
  43692. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  43693. return this.edges[rawIdx];
  43694. };
  43695. /**
  43696. * Get edge by two linked nodes
  43697. * @param {module:echarts/data/Graph.Node|string} n1
  43698. * @param {module:echarts/data/Graph.Node|string} n2
  43699. * @return {module:echarts/data/Graph.Edge}
  43700. */
  43701. graphProto.getEdge = function (n1, n2) {
  43702. if (Node.isInstance(n1)) {
  43703. n1 = n1.id;
  43704. }
  43705. if (Node.isInstance(n2)) {
  43706. n2 = n2.id;
  43707. }
  43708. var edgesMap = this._edgesMap;
  43709. if (this._directed) {
  43710. return edgesMap[n1 + '-' + n2];
  43711. } else {
  43712. return edgesMap[n1 + '-' + n2]
  43713. || edgesMap[n2 + '-' + n1];
  43714. }
  43715. };
  43716. /**
  43717. * Iterate all nodes
  43718. * @param {Function} cb
  43719. * @param {*} [context]
  43720. */
  43721. graphProto.eachNode = function (cb, context) {
  43722. var nodes = this.nodes;
  43723. var len = nodes.length;
  43724. for (var i = 0; i < len; i++) {
  43725. if (nodes[i].dataIndex >= 0) {
  43726. cb.call(context, nodes[i], i);
  43727. }
  43728. }
  43729. };
  43730. /**
  43731. * Iterate all edges
  43732. * @param {Function} cb
  43733. * @param {*} [context]
  43734. */
  43735. graphProto.eachEdge = function (cb, context) {
  43736. var edges = this.edges;
  43737. var len = edges.length;
  43738. for (var i = 0; i < len; i++) {
  43739. if (edges[i].dataIndex >= 0
  43740. && edges[i].node1.dataIndex >= 0
  43741. && edges[i].node2.dataIndex >= 0
  43742. ) {
  43743. cb.call(context, edges[i], i);
  43744. }
  43745. }
  43746. };
  43747. /**
  43748. * Breadth first traverse
  43749. * @param {Function} cb
  43750. * @param {module:echarts/data/Graph.Node} startNode
  43751. * @param {string} [direction='none'] 'none'|'in'|'out'
  43752. * @param {*} [context]
  43753. */
  43754. graphProto.breadthFirstTraverse = function (
  43755. cb, startNode, direction, context
  43756. ) {
  43757. if (!Node.isInstance(startNode)) {
  43758. startNode = this._nodesMap[generateNodeKey(startNode)];
  43759. }
  43760. if (!startNode) {
  43761. return;
  43762. }
  43763. var edgeType = direction === 'out'
  43764. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  43765. for (var i = 0; i < this.nodes.length; i++) {
  43766. this.nodes[i].__visited = false;
  43767. }
  43768. if (cb.call(context, startNode, null)) {
  43769. return;
  43770. }
  43771. var queue = [startNode];
  43772. while (queue.length) {
  43773. var currentNode = queue.shift();
  43774. var edges = currentNode[edgeType];
  43775. for (var i = 0; i < edges.length; i++) {
  43776. var e = edges[i];
  43777. var otherNode = e.node1 === currentNode
  43778. ? e.node2 : e.node1;
  43779. if (!otherNode.__visited) {
  43780. if (cb.call(context, otherNode, currentNode)) {
  43781. // Stop traversing
  43782. return;
  43783. }
  43784. queue.push(otherNode);
  43785. otherNode.__visited = true;
  43786. }
  43787. }
  43788. }
  43789. };
  43790. // TODO
  43791. // graphProto.depthFirstTraverse = function (
  43792. // cb, startNode, direction, context
  43793. // ) {
  43794. // };
  43795. // Filter update
  43796. graphProto.update = function () {
  43797. var data = this.data;
  43798. var edgeData = this.edgeData;
  43799. var nodes = this.nodes;
  43800. var edges = this.edges;
  43801. for (var i = 0, len = nodes.length; i < len; i++) {
  43802. nodes[i].dataIndex = -1;
  43803. }
  43804. for (var i = 0, len = data.count(); i < len; i++) {
  43805. nodes[data.getRawIndex(i)].dataIndex = i;
  43806. }
  43807. edgeData.filterSelf(function (idx) {
  43808. var edge = edges[edgeData.getRawIndex(idx)];
  43809. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  43810. });
  43811. // Update edge
  43812. for (var i = 0, len = edges.length; i < len; i++) {
  43813. edges[i].dataIndex = -1;
  43814. }
  43815. for (var i = 0, len = edgeData.count(); i < len; i++) {
  43816. edges[edgeData.getRawIndex(i)].dataIndex = i;
  43817. }
  43818. };
  43819. /**
  43820. * @return {module:echarts/data/Graph}
  43821. */
  43822. graphProto.clone = function () {
  43823. var graph = new Graph(this._directed);
  43824. var nodes = this.nodes;
  43825. var edges = this.edges;
  43826. for (var i = 0; i < nodes.length; i++) {
  43827. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  43828. }
  43829. for (var i = 0; i < edges.length; i++) {
  43830. var e = edges[i];
  43831. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  43832. }
  43833. return graph;
  43834. };
  43835. /**
  43836. * @alias module:echarts/data/Graph.Node
  43837. */
  43838. function Node(id, dataIndex) {
  43839. /**
  43840. * @type {string}
  43841. */
  43842. this.id = id == null ? '' : id;
  43843. /**
  43844. * @type {Array.<module:echarts/data/Graph.Edge>}
  43845. */
  43846. this.inEdges = [];
  43847. /**
  43848. * @type {Array.<module:echarts/data/Graph.Edge>}
  43849. */
  43850. this.outEdges = [];
  43851. /**
  43852. * @type {Array.<module:echarts/data/Graph.Edge>}
  43853. */
  43854. this.edges = [];
  43855. /**
  43856. * @type {module:echarts/data/Graph}
  43857. */
  43858. this.hostGraph;
  43859. /**
  43860. * @type {number}
  43861. */
  43862. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  43863. }
  43864. Node.prototype = {
  43865. constructor: Node,
  43866. /**
  43867. * @return {number}
  43868. */
  43869. degree: function () {
  43870. return this.edges.length;
  43871. },
  43872. /**
  43873. * @return {number}
  43874. */
  43875. inDegree: function () {
  43876. return this.inEdges.length;
  43877. },
  43878. /**
  43879. * @return {number}
  43880. */
  43881. outDegree: function () {
  43882. return this.outEdges.length;
  43883. },
  43884. /**
  43885. * @param {string} [path]
  43886. * @return {module:echarts/model/Model}
  43887. */
  43888. getModel: function (path) {
  43889. if (this.dataIndex < 0) {
  43890. return;
  43891. }
  43892. var graph = this.hostGraph;
  43893. var itemModel = graph.data.getItemModel(this.dataIndex);
  43894. return itemModel.getModel(path);
  43895. }
  43896. };
  43897. /**
  43898. * 图边
  43899. * @alias module:echarts/data/Graph.Edge
  43900. * @param {module:echarts/data/Graph.Node} n1
  43901. * @param {module:echarts/data/Graph.Node} n2
  43902. * @param {number} [dataIndex=-1]
  43903. */
  43904. function Edge(n1, n2, dataIndex) {
  43905. /**
  43906. * 节点1,如果是有向图则为源节点
  43907. * @type {module:echarts/data/Graph.Node}
  43908. */
  43909. this.node1 = n1;
  43910. /**
  43911. * 节点2,如果是有向图则为目标节点
  43912. * @type {module:echarts/data/Graph.Node}
  43913. */
  43914. this.node2 = n2;
  43915. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  43916. }
  43917. /**
  43918. * @param {string} [path]
  43919. * @return {module:echarts/model/Model}
  43920. */
  43921. Edge.prototype.getModel = function (path) {
  43922. if (this.dataIndex < 0) {
  43923. return;
  43924. }
  43925. var graph = this.hostGraph;
  43926. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  43927. return itemModel.getModel(path);
  43928. };
  43929. var createGraphDataProxyMixin = function (hostName, dataName) {
  43930. return {
  43931. /**
  43932. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  43933. * @return {number}
  43934. */
  43935. getValue: function (dimension) {
  43936. var data = this[hostName][dataName];
  43937. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  43938. },
  43939. /**
  43940. * @param {Object|string} key
  43941. * @param {*} [value]
  43942. */
  43943. setVisual: function (key, value) {
  43944. this.dataIndex >= 0
  43945. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  43946. },
  43947. /**
  43948. * @param {string} key
  43949. * @return {boolean}
  43950. */
  43951. getVisual: function (key, ignoreParent) {
  43952. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  43953. },
  43954. /**
  43955. * @param {Object} layout
  43956. * @return {boolean} [merge=false]
  43957. */
  43958. setLayout: function (layout, merge$$1) {
  43959. this.dataIndex >= 0
  43960. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  43961. },
  43962. /**
  43963. * @return {Object}
  43964. */
  43965. getLayout: function () {
  43966. return this[hostName][dataName].getItemLayout(this.dataIndex);
  43967. },
  43968. /**
  43969. * @return {module:zrender/Element}
  43970. */
  43971. getGraphicEl: function () {
  43972. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  43973. },
  43974. /**
  43975. * @return {number}
  43976. */
  43977. getRawIndex: function () {
  43978. return this[hostName][dataName].getRawIndex(this.dataIndex);
  43979. }
  43980. };
  43981. };
  43982. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  43983. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  43984. Graph.Node = Node;
  43985. Graph.Edge = Edge;
  43986. enableClassCheck(Node);
  43987. enableClassCheck(Edge);
  43988. /*
  43989. * Licensed to the Apache Software Foundation (ASF) under one
  43990. * or more contributor license agreements. See the NOTICE file
  43991. * distributed with this work for additional information
  43992. * regarding copyright ownership. The ASF licenses this file
  43993. * to you under the Apache License, Version 2.0 (the
  43994. * "License"); you may not use this file except in compliance
  43995. * with the License. You may obtain a copy of the License at
  43996. *
  43997. * http://www.apache.org/licenses/LICENSE-2.0
  43998. *
  43999. * Unless required by applicable law or agreed to in writing,
  44000. * software distributed under the License is distributed on an
  44001. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44002. * KIND, either express or implied. See the License for the
  44003. * specific language governing permissions and limitations
  44004. * under the License.
  44005. */
  44006. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  44007. // ??? TODO
  44008. // support dataset?
  44009. var graph = new Graph(directed);
  44010. for (var i = 0; i < nodes.length; i++) {
  44011. graph.addNode(retrieve(
  44012. // Id, name, dataIndex
  44013. nodes[i].id, nodes[i].name, i
  44014. ), i);
  44015. }
  44016. var linkNameList = [];
  44017. var validEdges = [];
  44018. var linkCount = 0;
  44019. for (var i = 0; i < edges.length; i++) {
  44020. var link = edges[i];
  44021. var source = link.source;
  44022. var target = link.target;
  44023. // addEdge may fail when source or target not exists
  44024. if (graph.addEdge(source, target, linkCount)) {
  44025. validEdges.push(link);
  44026. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  44027. linkCount++;
  44028. }
  44029. }
  44030. var coordSys = seriesModel.get('coordinateSystem');
  44031. var nodeData;
  44032. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  44033. nodeData = createListFromArray(nodes, seriesModel);
  44034. }
  44035. else {
  44036. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  44037. var coordDimensions = (coordSysCtor && coordSysCtor.type !== 'view')
  44038. ? (coordSysCtor.dimensions || []) : [];
  44039. // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  44040. // `value` dimension, but graph need `value` dimension. It's better to
  44041. // uniform this behavior.
  44042. if (indexOf(coordDimensions, 'value') < 0) {
  44043. coordDimensions.concat(['value']);
  44044. }
  44045. var dimensionNames = createDimensions(nodes, {
  44046. coordDimensions: coordDimensions
  44047. });
  44048. nodeData = new List(dimensionNames, seriesModel);
  44049. nodeData.initData(nodes);
  44050. }
  44051. var edgeData = new List(['value'], seriesModel);
  44052. edgeData.initData(validEdges, linkNameList);
  44053. beforeLink && beforeLink(nodeData, edgeData);
  44054. linkList({
  44055. mainData: nodeData,
  44056. struct: graph,
  44057. structAttr: 'graph',
  44058. datas: {node: nodeData, edge: edgeData},
  44059. datasAttr: {node: 'data', edge: 'edgeData'}
  44060. });
  44061. // Update dataIndex of nodes and edges because invalid edge may be removed
  44062. graph.update();
  44063. return graph;
  44064. };
  44065. /*
  44066. * Licensed to the Apache Software Foundation (ASF) under one
  44067. * or more contributor license agreements. See the NOTICE file
  44068. * distributed with this work for additional information
  44069. * regarding copyright ownership. The ASF licenses this file
  44070. * to you under the Apache License, Version 2.0 (the
  44071. * "License"); you may not use this file except in compliance
  44072. * with the License. You may obtain a copy of the License at
  44073. *
  44074. * http://www.apache.org/licenses/LICENSE-2.0
  44075. *
  44076. * Unless required by applicable law or agreed to in writing,
  44077. * software distributed under the License is distributed on an
  44078. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44079. * KIND, either express or implied. See the License for the
  44080. * specific language governing permissions and limitations
  44081. * under the License.
  44082. */
  44083. var GraphSeries = extendSeriesModel({
  44084. type: 'series.graph',
  44085. init: function (option) {
  44086. GraphSeries.superApply(this, 'init', arguments);
  44087. // Provide data for legend select
  44088. this.legendDataProvider = function () {
  44089. return this._categoriesData;
  44090. };
  44091. this.fillDataTextStyle(option.edges || option.links);
  44092. this._updateCategoriesData();
  44093. },
  44094. mergeOption: function (option) {
  44095. GraphSeries.superApply(this, 'mergeOption', arguments);
  44096. this.fillDataTextStyle(option.edges || option.links);
  44097. this._updateCategoriesData();
  44098. },
  44099. mergeDefaultAndTheme: function (option) {
  44100. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  44101. defaultEmphasis(option, ['edgeLabel'], ['show']);
  44102. },
  44103. getInitialData: function (option, ecModel) {
  44104. var edges = option.edges || option.links || [];
  44105. var nodes = option.data || option.nodes || [];
  44106. var self = this;
  44107. if (nodes && edges) {
  44108. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  44109. }
  44110. function beforeLink(nodeData, edgeData) {
  44111. // Overwrite nodeData.getItemModel to
  44112. nodeData.wrapMethod('getItemModel', function (model) {
  44113. var categoriesModels = self._categoriesModels;
  44114. var categoryIdx = model.getShallow('category');
  44115. var categoryModel = categoriesModels[categoryIdx];
  44116. if (categoryModel) {
  44117. categoryModel.parentModel = model.parentModel;
  44118. model.parentModel = categoryModel;
  44119. }
  44120. return model;
  44121. });
  44122. var edgeLabelModel = self.getModel('edgeLabel');
  44123. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  44124. var fakeSeriesModel = new Model(
  44125. {label: edgeLabelModel.option},
  44126. edgeLabelModel.parentModel,
  44127. ecModel
  44128. );
  44129. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  44130. var emphasisFakeSeriesModel = new Model(
  44131. {emphasis: {label: emphasisEdgeLabelModel.option}},
  44132. emphasisEdgeLabelModel.parentModel,
  44133. ecModel
  44134. );
  44135. edgeData.wrapMethod('getItemModel', function (model) {
  44136. model.customizeGetParent(edgeGetParent);
  44137. return model;
  44138. });
  44139. function edgeGetParent(path) {
  44140. path = this.parsePath(path);
  44141. return (path && path[0] === 'label')
  44142. ? fakeSeriesModel
  44143. : (path && path[0] === 'emphasis' && path[1] === 'label')
  44144. ? emphasisFakeSeriesModel
  44145. : this.parentModel;
  44146. }
  44147. }
  44148. },
  44149. /**
  44150. * @return {module:echarts/data/Graph}
  44151. */
  44152. getGraph: function () {
  44153. return this.getData().graph;
  44154. },
  44155. /**
  44156. * @return {module:echarts/data/List}
  44157. */
  44158. getEdgeData: function () {
  44159. return this.getGraph().edgeData;
  44160. },
  44161. /**
  44162. * @return {module:echarts/data/List}
  44163. */
  44164. getCategoriesData: function () {
  44165. return this._categoriesData;
  44166. },
  44167. /**
  44168. * @override
  44169. */
  44170. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  44171. if (dataType === 'edge') {
  44172. var nodeData = this.getData();
  44173. var params = this.getDataParams(dataIndex, dataType);
  44174. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  44175. var sourceName = nodeData.getName(edge.node1.dataIndex);
  44176. var targetName = nodeData.getName(edge.node2.dataIndex);
  44177. var html = [];
  44178. sourceName != null && html.push(sourceName);
  44179. targetName != null && html.push(targetName);
  44180. html = encodeHTML(html.join(' > '));
  44181. if (params.value) {
  44182. html += ' : ' + encodeHTML(params.value);
  44183. }
  44184. return html;
  44185. }
  44186. else { // dataType === 'node' or empty
  44187. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  44188. }
  44189. },
  44190. _updateCategoriesData: function () {
  44191. var categories = map(this.option.categories || [], function (category) {
  44192. // Data must has value
  44193. return category.value != null ? category : extend({
  44194. value: 0
  44195. }, category);
  44196. });
  44197. var categoriesData = new List(['value'], this);
  44198. categoriesData.initData(categories);
  44199. this._categoriesData = categoriesData;
  44200. this._categoriesModels = categoriesData.mapArray(function (idx) {
  44201. return categoriesData.getItemModel(idx, true);
  44202. });
  44203. },
  44204. setZoom: function (zoom) {
  44205. this.option.zoom = zoom;
  44206. },
  44207. setCenter: function (center) {
  44208. this.option.center = center;
  44209. },
  44210. isAnimationEnabled: function () {
  44211. return GraphSeries.superCall(this, 'isAnimationEnabled')
  44212. // Not enable animation when do force layout
  44213. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  44214. },
  44215. defaultOption: {
  44216. zlevel: 0,
  44217. z: 2,
  44218. coordinateSystem: 'view',
  44219. // Default option for all coordinate systems
  44220. // xAxisIndex: 0,
  44221. // yAxisIndex: 0,
  44222. // polarIndex: 0,
  44223. // geoIndex: 0,
  44224. legendHoverLink: true,
  44225. hoverAnimation: true,
  44226. layout: null,
  44227. focusNodeAdjacency: false,
  44228. // Configuration of circular layout
  44229. circular: {
  44230. rotateLabel: false
  44231. },
  44232. // Configuration of force directed layout
  44233. force: {
  44234. initLayout: null,
  44235. // Node repulsion. Can be an array to represent range.
  44236. repulsion: [0, 50],
  44237. gravity: 0.1,
  44238. // Edge length. Can be an array to represent range.
  44239. edgeLength: 30,
  44240. layoutAnimation: true
  44241. },
  44242. left: 'center',
  44243. top: 'center',
  44244. // right: null,
  44245. // bottom: null,
  44246. // width: '80%',
  44247. // height: '80%',
  44248. symbol: 'circle',
  44249. symbolSize: 10,
  44250. edgeSymbol: ['none', 'none'],
  44251. edgeSymbolSize: 10,
  44252. edgeLabel: {
  44253. position: 'middle'
  44254. },
  44255. draggable: false,
  44256. roam: false,
  44257. // Default on center of graph
  44258. center: null,
  44259. zoom: 1,
  44260. // Symbol size scale ratio in roam
  44261. nodeScaleRatio: 0.6,
  44262. // cursor: null,
  44263. // categories: [],
  44264. // data: []
  44265. // Or
  44266. // nodes: []
  44267. //
  44268. // links: []
  44269. // Or
  44270. // edges: []
  44271. label: {
  44272. show: false,
  44273. formatter: '{b}'
  44274. },
  44275. itemStyle: {},
  44276. lineStyle: {
  44277. color: '#aaa',
  44278. width: 1,
  44279. curveness: 0,
  44280. opacity: 0.5
  44281. },
  44282. emphasis: {
  44283. label: {
  44284. show: true
  44285. }
  44286. }
  44287. }
  44288. });
  44289. /*
  44290. * Licensed to the Apache Software Foundation (ASF) under one
  44291. * or more contributor license agreements. See the NOTICE file
  44292. * distributed with this work for additional information
  44293. * regarding copyright ownership. The ASF licenses this file
  44294. * to you under the Apache License, Version 2.0 (the
  44295. * "License"); you may not use this file except in compliance
  44296. * with the License. You may obtain a copy of the License at
  44297. *
  44298. * http://www.apache.org/licenses/LICENSE-2.0
  44299. *
  44300. * Unless required by applicable law or agreed to in writing,
  44301. * software distributed under the License is distributed on an
  44302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44303. * KIND, either express or implied. See the License for the
  44304. * specific language governing permissions and limitations
  44305. * under the License.
  44306. */
  44307. /**
  44308. * Line path for bezier and straight line draw
  44309. */
  44310. var straightLineProto = Line.prototype;
  44311. var bezierCurveProto = BezierCurve.prototype;
  44312. function isLine(shape) {
  44313. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  44314. }
  44315. var LinePath = extendShape({
  44316. type: 'ec-line',
  44317. style: {
  44318. stroke: '#000',
  44319. fill: null
  44320. },
  44321. shape: {
  44322. x1: 0,
  44323. y1: 0,
  44324. x2: 0,
  44325. y2: 0,
  44326. percent: 1,
  44327. cpx1: null,
  44328. cpy1: null
  44329. },
  44330. buildPath: function (ctx, shape) {
  44331. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  44332. },
  44333. pointAt: function (t) {
  44334. return isLine(this.shape)
  44335. ? straightLineProto.pointAt.call(this, t)
  44336. : bezierCurveProto.pointAt.call(this, t);
  44337. },
  44338. tangentAt: function (t) {
  44339. var shape = this.shape;
  44340. var p = isLine(shape)
  44341. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  44342. : bezierCurveProto.tangentAt.call(this, t);
  44343. return normalize(p, p);
  44344. }
  44345. });
  44346. /*
  44347. * Licensed to the Apache Software Foundation (ASF) under one
  44348. * or more contributor license agreements. See the NOTICE file
  44349. * distributed with this work for additional information
  44350. * regarding copyright ownership. The ASF licenses this file
  44351. * to you under the Apache License, Version 2.0 (the
  44352. * "License"); you may not use this file except in compliance
  44353. * with the License. You may obtain a copy of the License at
  44354. *
  44355. * http://www.apache.org/licenses/LICENSE-2.0
  44356. *
  44357. * Unless required by applicable law or agreed to in writing,
  44358. * software distributed under the License is distributed on an
  44359. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44360. * KIND, either express or implied. See the License for the
  44361. * specific language governing permissions and limitations
  44362. * under the License.
  44363. */
  44364. /**
  44365. * @module echarts/chart/helper/Line
  44366. */
  44367. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  44368. function makeSymbolTypeKey(symbolCategory) {
  44369. return '_' + symbolCategory + 'Type';
  44370. }
  44371. /**
  44372. * @inner
  44373. */
  44374. function createSymbol$1(name, lineData, idx) {
  44375. var color = lineData.getItemVisual(idx, 'color');
  44376. var symbolType = lineData.getItemVisual(idx, name);
  44377. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  44378. if (!symbolType || symbolType === 'none') {
  44379. return;
  44380. }
  44381. if (!isArray(symbolSize)) {
  44382. symbolSize = [symbolSize, symbolSize];
  44383. }
  44384. var symbolPath = createSymbol(
  44385. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  44386. symbolSize[0], symbolSize[1], color
  44387. );
  44388. symbolPath.name = name;
  44389. return symbolPath;
  44390. }
  44391. function createLine(points) {
  44392. var line = new LinePath({
  44393. name: 'line'
  44394. });
  44395. setLinePoints(line.shape, points);
  44396. return line;
  44397. }
  44398. function setLinePoints(targetShape, points) {
  44399. var p1 = points[0];
  44400. var p2 = points[1];
  44401. var cp1 = points[2];
  44402. targetShape.x1 = p1[0];
  44403. targetShape.y1 = p1[1];
  44404. targetShape.x2 = p2[0];
  44405. targetShape.y2 = p2[1];
  44406. targetShape.percent = 1;
  44407. if (cp1) {
  44408. targetShape.cpx1 = cp1[0];
  44409. targetShape.cpy1 = cp1[1];
  44410. }
  44411. else {
  44412. targetShape.cpx1 = NaN;
  44413. targetShape.cpy1 = NaN;
  44414. }
  44415. }
  44416. function updateSymbolAndLabelBeforeLineUpdate () {
  44417. var lineGroup = this;
  44418. var symbolFrom = lineGroup.childOfName('fromSymbol');
  44419. var symbolTo = lineGroup.childOfName('toSymbol');
  44420. var label = lineGroup.childOfName('label');
  44421. // Quick reject
  44422. if (!symbolFrom && !symbolTo && label.ignore) {
  44423. return;
  44424. }
  44425. var invScale = 1;
  44426. var parentNode = this.parent;
  44427. while (parentNode) {
  44428. if (parentNode.scale) {
  44429. invScale /= parentNode.scale[0];
  44430. }
  44431. parentNode = parentNode.parent;
  44432. }
  44433. var line = lineGroup.childOfName('line');
  44434. // If line not changed
  44435. // FIXME Parent scale changed
  44436. if (!this.__dirty && !line.__dirty) {
  44437. return;
  44438. }
  44439. var percent = line.shape.percent;
  44440. var fromPos = line.pointAt(0);
  44441. var toPos = line.pointAt(percent);
  44442. var d = sub([], toPos, fromPos);
  44443. normalize(d, d);
  44444. if (symbolFrom) {
  44445. symbolFrom.attr('position', fromPos);
  44446. var tangent = line.tangentAt(0);
  44447. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  44448. tangent[1], tangent[0]
  44449. ));
  44450. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  44451. }
  44452. if (symbolTo) {
  44453. symbolTo.attr('position', toPos);
  44454. var tangent = line.tangentAt(1);
  44455. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  44456. tangent[1], tangent[0]
  44457. ));
  44458. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  44459. }
  44460. if (!label.ignore) {
  44461. label.attr('position', toPos);
  44462. var textPosition;
  44463. var textAlign;
  44464. var textVerticalAlign;
  44465. var distance$$1 = 5 * invScale;
  44466. // End
  44467. if (label.__position === 'end') {
  44468. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  44469. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  44470. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  44471. }
  44472. // Middle
  44473. else if (label.__position === 'middle') {
  44474. var halfPercent = percent / 2;
  44475. var tangent = line.tangentAt(halfPercent);
  44476. var n = [tangent[1], -tangent[0]];
  44477. var cp = line.pointAt(halfPercent);
  44478. if (n[1] > 0) {
  44479. n[0] = -n[0];
  44480. n[1] = -n[1];
  44481. }
  44482. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  44483. textAlign = 'center';
  44484. textVerticalAlign = 'bottom';
  44485. var rotation = -Math.atan2(tangent[1], tangent[0]);
  44486. if (toPos[0] < fromPos[0]) {
  44487. rotation = Math.PI + rotation;
  44488. }
  44489. label.attr('rotation', rotation);
  44490. }
  44491. // Start
  44492. else {
  44493. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  44494. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  44495. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  44496. }
  44497. label.attr({
  44498. style: {
  44499. // Use the user specified text align and baseline first
  44500. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  44501. textAlign: label.__textAlign || textAlign
  44502. },
  44503. position: textPosition,
  44504. scale: [invScale, invScale]
  44505. });
  44506. }
  44507. }
  44508. /**
  44509. * @constructor
  44510. * @extends {module:zrender/graphic/Group}
  44511. * @alias {module:echarts/chart/helper/Line}
  44512. */
  44513. function Line$1(lineData, idx, seriesScope) {
  44514. Group.call(this);
  44515. this._createLine(lineData, idx, seriesScope);
  44516. }
  44517. var lineProto = Line$1.prototype;
  44518. // Update symbol position and rotation
  44519. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  44520. lineProto._createLine = function (lineData, idx, seriesScope) {
  44521. var seriesModel = lineData.hostModel;
  44522. var linePoints = lineData.getItemLayout(idx);
  44523. var line = createLine(linePoints);
  44524. line.shape.percent = 0;
  44525. initProps(line, {
  44526. shape: {
  44527. percent: 1
  44528. }
  44529. }, seriesModel, idx);
  44530. this.add(line);
  44531. var label = new Text({
  44532. name: 'label'
  44533. });
  44534. this.add(label);
  44535. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  44536. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  44537. // symbols must added after line to make sure
  44538. // it will be updated after line#update.
  44539. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  44540. this.add(symbol);
  44541. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  44542. }, this);
  44543. this._updateCommonStl(lineData, idx, seriesScope);
  44544. };
  44545. lineProto.updateData = function (lineData, idx, seriesScope) {
  44546. var seriesModel = lineData.hostModel;
  44547. var line = this.childOfName('line');
  44548. var linePoints = lineData.getItemLayout(idx);
  44549. var target = {
  44550. shape: {}
  44551. };
  44552. setLinePoints(target.shape, linePoints);
  44553. updateProps(line, target, seriesModel, idx);
  44554. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  44555. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  44556. var key = makeSymbolTypeKey(symbolCategory);
  44557. // Symbol changed
  44558. if (this[key] !== symbolType) {
  44559. this.remove(this.childOfName(symbolCategory));
  44560. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  44561. this.add(symbol);
  44562. }
  44563. this[key] = symbolType;
  44564. }, this);
  44565. this._updateCommonStl(lineData, idx, seriesScope);
  44566. };
  44567. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  44568. var seriesModel = lineData.hostModel;
  44569. var line = this.childOfName('line');
  44570. var lineStyle = seriesScope && seriesScope.lineStyle;
  44571. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  44572. var labelModel = seriesScope && seriesScope.labelModel;
  44573. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  44574. // Optimization for large dataset
  44575. if (!seriesScope || lineData.hasItemOption) {
  44576. var itemModel = lineData.getItemModel(idx);
  44577. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  44578. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  44579. labelModel = itemModel.getModel('label');
  44580. hoverLabelModel = itemModel.getModel('emphasis.label');
  44581. }
  44582. var visualColor = lineData.getItemVisual(idx, 'color');
  44583. var visualOpacity = retrieve3(
  44584. lineData.getItemVisual(idx, 'opacity'),
  44585. lineStyle.opacity,
  44586. 1
  44587. );
  44588. line.useStyle(defaults(
  44589. {
  44590. strokeNoScale: true,
  44591. fill: 'none',
  44592. stroke: visualColor,
  44593. opacity: visualOpacity
  44594. },
  44595. lineStyle
  44596. ));
  44597. line.hoverStyle = hoverLineStyle;
  44598. // Update symbol
  44599. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  44600. var symbol = this.childOfName(symbolCategory);
  44601. if (symbol) {
  44602. symbol.setColor(visualColor);
  44603. symbol.setStyle({
  44604. opacity: visualOpacity
  44605. });
  44606. }
  44607. }, this);
  44608. var showLabel = labelModel.getShallow('show');
  44609. var hoverShowLabel = hoverLabelModel.getShallow('show');
  44610. var label = this.childOfName('label');
  44611. var defaultLabelColor;
  44612. var baseText;
  44613. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  44614. if (showLabel || hoverShowLabel) {
  44615. defaultLabelColor = visualColor || '#000';
  44616. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  44617. if (baseText == null) {
  44618. var rawVal = seriesModel.getRawValue(idx);
  44619. baseText = rawVal == null
  44620. ? lineData.getName(idx)
  44621. : isFinite(rawVal)
  44622. ? round$1(rawVal)
  44623. : rawVal;
  44624. }
  44625. }
  44626. var normalText = showLabel ? baseText : null;
  44627. var emphasisText = hoverShowLabel
  44628. ? retrieve2(
  44629. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  44630. baseText
  44631. )
  44632. : null;
  44633. var labelStyle = label.style;
  44634. // Always set `textStyle` even if `normalStyle.text` is null, because default
  44635. // values have to be set on `normalStyle`.
  44636. if (normalText != null || emphasisText != null) {
  44637. setTextStyle(label.style, labelModel, {
  44638. text: normalText
  44639. }, {
  44640. autoColor: defaultLabelColor
  44641. });
  44642. label.__textAlign = labelStyle.textAlign;
  44643. label.__verticalAlign = labelStyle.textVerticalAlign;
  44644. // 'start', 'middle', 'end'
  44645. label.__position = labelModel.get('position') || 'middle';
  44646. }
  44647. if (emphasisText != null) {
  44648. // Only these properties supported in this emphasis style here.
  44649. label.hoverStyle = {
  44650. text: emphasisText,
  44651. textFill: hoverLabelModel.getTextColor(true),
  44652. // For merging hover style to normal style, do not use
  44653. // `hoverLabelModel.getFont()` here.
  44654. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  44655. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  44656. fontSize: hoverLabelModel.getShallow('fontSize'),
  44657. fontFamily: hoverLabelModel.getShallow('fontFamily')
  44658. };
  44659. }
  44660. else {
  44661. label.hoverStyle = {
  44662. text: null
  44663. };
  44664. }
  44665. label.ignore = !showLabel && !hoverShowLabel;
  44666. setHoverStyle(this);
  44667. };
  44668. lineProto.highlight = function () {
  44669. this.trigger('emphasis');
  44670. };
  44671. lineProto.downplay = function () {
  44672. this.trigger('normal');
  44673. };
  44674. lineProto.updateLayout = function (lineData, idx) {
  44675. this.setLinePoints(lineData.getItemLayout(idx));
  44676. };
  44677. lineProto.setLinePoints = function (points) {
  44678. var linePath = this.childOfName('line');
  44679. setLinePoints(linePath.shape, points);
  44680. linePath.dirty();
  44681. };
  44682. inherits(Line$1, Group);
  44683. /*
  44684. * Licensed to the Apache Software Foundation (ASF) under one
  44685. * or more contributor license agreements. See the NOTICE file
  44686. * distributed with this work for additional information
  44687. * regarding copyright ownership. The ASF licenses this file
  44688. * to you under the Apache License, Version 2.0 (the
  44689. * "License"); you may not use this file except in compliance
  44690. * with the License. You may obtain a copy of the License at
  44691. *
  44692. * http://www.apache.org/licenses/LICENSE-2.0
  44693. *
  44694. * Unless required by applicable law or agreed to in writing,
  44695. * software distributed under the License is distributed on an
  44696. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44697. * KIND, either express or implied. See the License for the
  44698. * specific language governing permissions and limitations
  44699. * under the License.
  44700. */
  44701. /**
  44702. * @module echarts/chart/helper/LineDraw
  44703. */
  44704. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  44705. /**
  44706. * @alias module:echarts/component/marker/LineDraw
  44707. * @constructor
  44708. */
  44709. function LineDraw(ctor) {
  44710. this._ctor = ctor || Line$1;
  44711. this.group = new Group();
  44712. }
  44713. var lineDrawProto = LineDraw.prototype;
  44714. lineDrawProto.isPersistent = function () {
  44715. return true;
  44716. };
  44717. /**
  44718. * @param {module:echarts/data/List} lineData
  44719. */
  44720. lineDrawProto.updateData = function (lineData) {
  44721. var lineDraw = this;
  44722. var group = lineDraw.group;
  44723. var oldLineData = lineDraw._lineData;
  44724. lineDraw._lineData = lineData;
  44725. // There is no oldLineData only when first rendering or switching from
  44726. // stream mode to normal mode, where previous elements should be removed.
  44727. if (!oldLineData) {
  44728. group.removeAll();
  44729. }
  44730. var seriesScope = makeSeriesScope$1(lineData);
  44731. lineData.diff(oldLineData)
  44732. .add(function (idx) {
  44733. doAdd(lineDraw, lineData, idx, seriesScope);
  44734. })
  44735. .update(function (newIdx, oldIdx) {
  44736. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  44737. })
  44738. .remove(function (idx) {
  44739. group.remove(oldLineData.getItemGraphicEl(idx));
  44740. })
  44741. .execute();
  44742. };
  44743. function doAdd(lineDraw, lineData, idx, seriesScope) {
  44744. var itemLayout = lineData.getItemLayout(idx);
  44745. if (!lineNeedsDraw(itemLayout)) {
  44746. return;
  44747. }
  44748. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  44749. lineData.setItemGraphicEl(idx, el);
  44750. lineDraw.group.add(el);
  44751. }
  44752. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  44753. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  44754. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  44755. lineDraw.group.remove(itemEl);
  44756. return;
  44757. }
  44758. if (!itemEl) {
  44759. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  44760. }
  44761. else {
  44762. itemEl.updateData(newLineData, newIdx, seriesScope);
  44763. }
  44764. newLineData.setItemGraphicEl(newIdx, itemEl);
  44765. lineDraw.group.add(itemEl);
  44766. }
  44767. lineDrawProto.updateLayout = function () {
  44768. var lineData = this._lineData;
  44769. // Do not support update layout in incremental mode.
  44770. if (!lineData) {
  44771. return;
  44772. }
  44773. lineData.eachItemGraphicEl(function (el, idx) {
  44774. el.updateLayout(lineData, idx);
  44775. }, this);
  44776. };
  44777. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  44778. this._seriesScope = makeSeriesScope$1(lineData);
  44779. this._lineData = null;
  44780. this.group.removeAll();
  44781. };
  44782. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  44783. function updateIncrementalAndHover(el) {
  44784. if (!el.isGroup) {
  44785. el.incremental = el.useHoverLayer = true;
  44786. }
  44787. }
  44788. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  44789. var itemLayout = lineData.getItemLayout(idx);
  44790. if (lineNeedsDraw(itemLayout)) {
  44791. var el = new this._ctor(lineData, idx, this._seriesScope);
  44792. el.traverse(updateIncrementalAndHover);
  44793. this.group.add(el);
  44794. lineData.setItemGraphicEl(idx, el);
  44795. }
  44796. }
  44797. };
  44798. function makeSeriesScope$1(lineData) {
  44799. var hostModel = lineData.hostModel;
  44800. return {
  44801. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  44802. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  44803. labelModel: hostModel.getModel('label'),
  44804. hoverLabelModel: hostModel.getModel('emphasis.label')
  44805. };
  44806. }
  44807. lineDrawProto.remove = function () {
  44808. this._clearIncremental();
  44809. this._incremental = null;
  44810. this.group.removeAll();
  44811. };
  44812. lineDrawProto._clearIncremental = function () {
  44813. var incremental = this._incremental;
  44814. if (incremental) {
  44815. incremental.clearDisplaybles();
  44816. }
  44817. };
  44818. function isPointNaN(pt) {
  44819. return isNaN(pt[0]) || isNaN(pt[1]);
  44820. }
  44821. function lineNeedsDraw(pts) {
  44822. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  44823. }
  44824. /*
  44825. * Licensed to the Apache Software Foundation (ASF) under one
  44826. * or more contributor license agreements. See the NOTICE file
  44827. * distributed with this work for additional information
  44828. * regarding copyright ownership. The ASF licenses this file
  44829. * to you under the Apache License, Version 2.0 (the
  44830. * "License"); you may not use this file except in compliance
  44831. * with the License. You may obtain a copy of the License at
  44832. *
  44833. * http://www.apache.org/licenses/LICENSE-2.0
  44834. *
  44835. * Unless required by applicable law or agreed to in writing,
  44836. * software distributed under the License is distributed on an
  44837. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44838. * KIND, either express or implied. See the License for the
  44839. * specific language governing permissions and limitations
  44840. * under the License.
  44841. */
  44842. var v1 = [];
  44843. var v2 = [];
  44844. var v3 = [];
  44845. var quadraticAt$1 = quadraticAt;
  44846. var v2DistSquare = distSquare;
  44847. var mathAbs$1 = Math.abs;
  44848. function intersectCurveCircle(curvePoints, center, radius) {
  44849. var p0 = curvePoints[0];
  44850. var p1 = curvePoints[1];
  44851. var p2 = curvePoints[2];
  44852. var d = Infinity;
  44853. var t;
  44854. var radiusSquare = radius * radius;
  44855. var interval = 0.1;
  44856. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  44857. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  44858. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  44859. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  44860. if (diff < d) {
  44861. d = diff;
  44862. t = _t;
  44863. }
  44864. }
  44865. // Assume the segment is monotone,Find root through Bisection method
  44866. // At most 32 iteration
  44867. for (var i = 0; i < 32; i++) {
  44868. // var prev = t - interval;
  44869. var next = t + interval;
  44870. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  44871. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  44872. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  44873. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  44874. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  44875. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  44876. var diff = v2DistSquare(v2, center) - radiusSquare;
  44877. if (mathAbs$1(diff) < 1e-2) {
  44878. break;
  44879. }
  44880. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  44881. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  44882. interval /= 2;
  44883. if (diff < 0) {
  44884. if (nextDiff >= 0) {
  44885. t = t + interval;
  44886. }
  44887. else {
  44888. t = t - interval;
  44889. }
  44890. }
  44891. else {
  44892. if (nextDiff >= 0) {
  44893. t = t - interval;
  44894. }
  44895. else {
  44896. t = t + interval;
  44897. }
  44898. }
  44899. }
  44900. return t;
  44901. }
  44902. // Adjust edge to avoid
  44903. var adjustEdge = function (graph, scale$$1) {
  44904. var tmp0 = [];
  44905. var quadraticSubdivide$$1 = quadraticSubdivide;
  44906. var pts = [[], [], []];
  44907. var pts2 = [[], []];
  44908. var v = [];
  44909. scale$$1 /= 2;
  44910. function getSymbolSize(node) {
  44911. var symbolSize = node.getVisual('symbolSize');
  44912. if (symbolSize instanceof Array) {
  44913. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  44914. }
  44915. return symbolSize;
  44916. }
  44917. graph.eachEdge(function (edge, idx) {
  44918. var linePoints = edge.getLayout();
  44919. var fromSymbol = edge.getVisual('fromSymbol');
  44920. var toSymbol = edge.getVisual('toSymbol');
  44921. if (!linePoints.__original) {
  44922. linePoints.__original = [
  44923. clone$1(linePoints[0]),
  44924. clone$1(linePoints[1])
  44925. ];
  44926. if (linePoints[2]) {
  44927. linePoints.__original.push(clone$1(linePoints[2]));
  44928. }
  44929. }
  44930. var originalPoints = linePoints.__original;
  44931. // Quadratic curve
  44932. if (linePoints[2] != null) {
  44933. copy(pts[0], originalPoints[0]);
  44934. copy(pts[1], originalPoints[2]);
  44935. copy(pts[2], originalPoints[1]);
  44936. if (fromSymbol && fromSymbol != 'none') {
  44937. var symbolSize = getSymbolSize(edge.node1);
  44938. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  44939. // Subdivide and get the second
  44940. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  44941. pts[0][0] = tmp0[3];
  44942. pts[1][0] = tmp0[4];
  44943. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  44944. pts[0][1] = tmp0[3];
  44945. pts[1][1] = tmp0[4];
  44946. }
  44947. if (toSymbol && toSymbol != 'none') {
  44948. var symbolSize = getSymbolSize(edge.node2);
  44949. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  44950. // Subdivide and get the first
  44951. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  44952. pts[1][0] = tmp0[1];
  44953. pts[2][0] = tmp0[2];
  44954. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  44955. pts[1][1] = tmp0[1];
  44956. pts[2][1] = tmp0[2];
  44957. }
  44958. // Copy back to layout
  44959. copy(linePoints[0], pts[0]);
  44960. copy(linePoints[1], pts[2]);
  44961. copy(linePoints[2], pts[1]);
  44962. }
  44963. // Line
  44964. else {
  44965. copy(pts2[0], originalPoints[0]);
  44966. copy(pts2[1], originalPoints[1]);
  44967. sub(v, pts2[1], pts2[0]);
  44968. normalize(v, v);
  44969. if (fromSymbol && fromSymbol != 'none') {
  44970. var symbolSize = getSymbolSize(edge.node1);
  44971. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  44972. }
  44973. if (toSymbol && toSymbol != 'none') {
  44974. var symbolSize = getSymbolSize(edge.node2);
  44975. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  44976. }
  44977. copy(linePoints[0], pts2[0]);
  44978. copy(linePoints[1], pts2[1]);
  44979. }
  44980. });
  44981. };
  44982. /*
  44983. * Licensed to the Apache Software Foundation (ASF) under one
  44984. * or more contributor license agreements. See the NOTICE file
  44985. * distributed with this work for additional information
  44986. * regarding copyright ownership. The ASF licenses this file
  44987. * to you under the Apache License, Version 2.0 (the
  44988. * "License"); you may not use this file except in compliance
  44989. * with the License. You may obtain a copy of the License at
  44990. *
  44991. * http://www.apache.org/licenses/LICENSE-2.0
  44992. *
  44993. * Unless required by applicable law or agreed to in writing,
  44994. * software distributed under the License is distributed on an
  44995. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44996. * KIND, either express or implied. See the License for the
  44997. * specific language governing permissions and limitations
  44998. * under the License.
  44999. */
  45000. var nodeOpacityPath = ['itemStyle', 'opacity'];
  45001. var lineOpacityPath = ['lineStyle', 'opacity'];
  45002. function getItemOpacity(item, opacityPath) {
  45003. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  45004. }
  45005. function fadeOutItem(item, opacityPath, opacityRatio) {
  45006. var el = item.getGraphicEl();
  45007. var opacity = getItemOpacity(item, opacityPath);
  45008. if (opacityRatio != null) {
  45009. opacity == null && (opacity = 1);
  45010. opacity *= opacityRatio;
  45011. }
  45012. el.downplay && el.downplay();
  45013. el.traverse(function (child) {
  45014. if (child.type !== 'group') {
  45015. child.setStyle('opacity', opacity);
  45016. }
  45017. });
  45018. }
  45019. function fadeInItem(item, opacityPath) {
  45020. var opacity = getItemOpacity(item, opacityPath);
  45021. var el = item.getGraphicEl();
  45022. el.highlight && el.highlight();
  45023. el.traverse(function (child) {
  45024. if (child.type !== 'group') {
  45025. child.setStyle('opacity', opacity);
  45026. }
  45027. });
  45028. }
  45029. extendChartView({
  45030. type: 'graph',
  45031. init: function (ecModel, api) {
  45032. var symbolDraw = new SymbolDraw();
  45033. var lineDraw = new LineDraw();
  45034. var group = this.group;
  45035. this._controller = new RoamController(api.getZr());
  45036. this._controllerHost = {target: group};
  45037. group.add(symbolDraw.group);
  45038. group.add(lineDraw.group);
  45039. this._symbolDraw = symbolDraw;
  45040. this._lineDraw = lineDraw;
  45041. this._firstRender = true;
  45042. },
  45043. render: function (seriesModel, ecModel, api) {
  45044. var coordSys = seriesModel.coordinateSystem;
  45045. this._model = seriesModel;
  45046. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  45047. var symbolDraw = this._symbolDraw;
  45048. var lineDraw = this._lineDraw;
  45049. var group = this.group;
  45050. if (coordSys.type === 'view') {
  45051. var groupNewProp = {
  45052. position: coordSys.position,
  45053. scale: coordSys.scale
  45054. };
  45055. if (this._firstRender) {
  45056. group.attr(groupNewProp);
  45057. }
  45058. else {
  45059. updateProps(group, groupNewProp, seriesModel);
  45060. }
  45061. }
  45062. // Fix edge contact point with node
  45063. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  45064. var data = seriesModel.getData();
  45065. symbolDraw.updateData(data);
  45066. var edgeData = seriesModel.getEdgeData();
  45067. lineDraw.updateData(edgeData);
  45068. this._updateNodeAndLinkScale();
  45069. this._updateController(seriesModel, ecModel, api);
  45070. clearTimeout(this._layoutTimeout);
  45071. var forceLayout = seriesModel.forceLayout;
  45072. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  45073. if (forceLayout) {
  45074. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  45075. }
  45076. data.eachItemGraphicEl(function (el, idx) {
  45077. var itemModel = data.getItemModel(idx);
  45078. // Update draggable
  45079. el.off('drag').off('dragend');
  45080. var draggable = data.getItemModel(idx).get('draggable');
  45081. if (draggable) {
  45082. el.on('drag', function () {
  45083. if (forceLayout) {
  45084. forceLayout.warmUp();
  45085. !this._layouting
  45086. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  45087. forceLayout.setFixed(idx);
  45088. // Write position back to layout
  45089. data.setItemLayout(idx, el.position);
  45090. }
  45091. }, this).on('dragend', function () {
  45092. if (forceLayout) {
  45093. forceLayout.setUnfixed(idx);
  45094. }
  45095. }, this);
  45096. }
  45097. el.setDraggable(draggable && forceLayout);
  45098. el.off('mouseover', el.__focusNodeAdjacency);
  45099. el.off('mouseout', el.__unfocusNodeAdjacency);
  45100. if (itemModel.get('focusNodeAdjacency')) {
  45101. el.on('mouseover', el.__focusNodeAdjacency = function () {
  45102. api.dispatchAction({
  45103. type: 'focusNodeAdjacency',
  45104. seriesId: seriesModel.id,
  45105. dataIndex: el.dataIndex
  45106. });
  45107. });
  45108. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  45109. api.dispatchAction({
  45110. type: 'unfocusNodeAdjacency',
  45111. seriesId: seriesModel.id
  45112. });
  45113. });
  45114. }
  45115. }, this);
  45116. data.graph.eachEdge(function (edge) {
  45117. var el = edge.getGraphicEl();
  45118. el.off('mouseover', el.__focusNodeAdjacency);
  45119. el.off('mouseout', el.__unfocusNodeAdjacency);
  45120. if (edge.getModel().get('focusNodeAdjacency')) {
  45121. el.on('mouseover', el.__focusNodeAdjacency = function () {
  45122. api.dispatchAction({
  45123. type: 'focusNodeAdjacency',
  45124. seriesId: seriesModel.id,
  45125. edgeDataIndex: edge.dataIndex
  45126. });
  45127. });
  45128. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  45129. api.dispatchAction({
  45130. type: 'unfocusNodeAdjacency',
  45131. seriesId: seriesModel.id
  45132. });
  45133. });
  45134. }
  45135. });
  45136. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  45137. && seriesModel.get('circular.rotateLabel');
  45138. var cx = data.getLayout('cx');
  45139. var cy = data.getLayout('cy');
  45140. data.eachItemGraphicEl(function (el, idx) {
  45141. var symbolPath = el.getSymbolPath();
  45142. if (circularRotateLabel) {
  45143. var pos = data.getItemLayout(idx);
  45144. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  45145. if (rad < 0) {
  45146. rad = Math.PI * 2 + rad;
  45147. }
  45148. var isLeft = pos[0] < cx;
  45149. if (isLeft) {
  45150. rad = rad - Math.PI;
  45151. }
  45152. var textPosition = isLeft ? 'left' : 'right';
  45153. symbolPath.setStyle({
  45154. textRotation: -rad,
  45155. textPosition: textPosition,
  45156. textOrigin: 'center'
  45157. });
  45158. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  45159. }
  45160. else {
  45161. symbolPath.setStyle({
  45162. textRotation: 0
  45163. });
  45164. }
  45165. });
  45166. this._firstRender = false;
  45167. },
  45168. dispose: function () {
  45169. this._controller && this._controller.dispose();
  45170. this._controllerHost = {};
  45171. },
  45172. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  45173. var data = this._model.getData();
  45174. var graph = data.graph;
  45175. var dataIndex = payload.dataIndex;
  45176. var edgeDataIndex = payload.edgeDataIndex;
  45177. var node = graph.getNodeByIndex(dataIndex);
  45178. var edge = graph.getEdgeByIndex(edgeDataIndex);
  45179. if (!node && !edge) {
  45180. return;
  45181. }
  45182. graph.eachNode(function (node) {
  45183. fadeOutItem(node, nodeOpacityPath, 0.1);
  45184. });
  45185. graph.eachEdge(function (edge) {
  45186. fadeOutItem(edge, lineOpacityPath, 0.1);
  45187. });
  45188. if (node) {
  45189. fadeInItem(node, nodeOpacityPath);
  45190. each$1(node.edges, function (adjacentEdge) {
  45191. if (adjacentEdge.dataIndex < 0) {
  45192. return;
  45193. }
  45194. fadeInItem(adjacentEdge, lineOpacityPath);
  45195. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  45196. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  45197. });
  45198. }
  45199. if (edge) {
  45200. fadeInItem(edge, lineOpacityPath);
  45201. fadeInItem(edge.node1, nodeOpacityPath);
  45202. fadeInItem(edge.node2, nodeOpacityPath);
  45203. }
  45204. },
  45205. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  45206. var graph = this._model.getData().graph;
  45207. graph.eachNode(function (node) {
  45208. fadeOutItem(node, nodeOpacityPath);
  45209. });
  45210. graph.eachEdge(function (edge) {
  45211. fadeOutItem(edge, lineOpacityPath);
  45212. });
  45213. },
  45214. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  45215. var self = this;
  45216. (function step() {
  45217. forceLayout.step(function (stopped) {
  45218. self.updateLayout(self._model);
  45219. (self._layouting = !stopped) && (
  45220. layoutAnimation
  45221. ? (self._layoutTimeout = setTimeout(step, 16))
  45222. : step()
  45223. );
  45224. });
  45225. })();
  45226. },
  45227. _updateController: function (seriesModel, ecModel, api) {
  45228. var controller = this._controller;
  45229. var controllerHost = this._controllerHost;
  45230. var group = this.group;
  45231. controller.setPointerChecker(function (e, x, y) {
  45232. var rect = group.getBoundingRect();
  45233. rect.applyTransform(group.transform);
  45234. return rect.contain(x, y)
  45235. && !onIrrelevantElement(e, api, seriesModel);
  45236. });
  45237. if (seriesModel.coordinateSystem.type !== 'view') {
  45238. controller.disable();
  45239. return;
  45240. }
  45241. controller.enable(seriesModel.get('roam'));
  45242. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  45243. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  45244. controller
  45245. .off('pan')
  45246. .off('zoom')
  45247. .on('pan', function (dx, dy) {
  45248. updateViewOnPan(controllerHost, dx, dy);
  45249. api.dispatchAction({
  45250. seriesId: seriesModel.id,
  45251. type: 'graphRoam',
  45252. dx: dx,
  45253. dy: dy
  45254. });
  45255. })
  45256. .on('zoom', function (zoom, mouseX, mouseY) {
  45257. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  45258. api.dispatchAction({
  45259. seriesId: seriesModel.id,
  45260. type: 'graphRoam',
  45261. zoom: zoom,
  45262. originX: mouseX,
  45263. originY: mouseY
  45264. });
  45265. this._updateNodeAndLinkScale();
  45266. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  45267. this._lineDraw.updateLayout();
  45268. }, this);
  45269. },
  45270. _updateNodeAndLinkScale: function () {
  45271. var seriesModel = this._model;
  45272. var data = seriesModel.getData();
  45273. var nodeScale = this._getNodeGlobalScale(seriesModel);
  45274. var invScale = [nodeScale, nodeScale];
  45275. data.eachItemGraphicEl(function (el, idx) {
  45276. el.attr('scale', invScale);
  45277. });
  45278. },
  45279. _getNodeGlobalScale: function (seriesModel) {
  45280. var coordSys = seriesModel.coordinateSystem;
  45281. if (coordSys.type !== 'view') {
  45282. return 1;
  45283. }
  45284. var nodeScaleRatio = this._nodeScaleRatio;
  45285. var groupScale = coordSys.scale;
  45286. var groupZoom = (groupScale && groupScale[0]) || 1;
  45287. // Scale node when zoom changes
  45288. var roamZoom = coordSys.getZoom();
  45289. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  45290. return nodeScale / groupZoom;
  45291. },
  45292. updateLayout: function (seriesModel) {
  45293. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  45294. this._symbolDraw.updateLayout();
  45295. this._lineDraw.updateLayout();
  45296. },
  45297. remove: function (ecModel, api) {
  45298. this._symbolDraw && this._symbolDraw.remove();
  45299. this._lineDraw && this._lineDraw.remove();
  45300. }
  45301. });
  45302. /*
  45303. * Licensed to the Apache Software Foundation (ASF) under one
  45304. * or more contributor license agreements. See the NOTICE file
  45305. * distributed with this work for additional information
  45306. * regarding copyright ownership. The ASF licenses this file
  45307. * to you under the Apache License, Version 2.0 (the
  45308. * "License"); you may not use this file except in compliance
  45309. * with the License. You may obtain a copy of the License at
  45310. *
  45311. * http://www.apache.org/licenses/LICENSE-2.0
  45312. *
  45313. * Unless required by applicable law or agreed to in writing,
  45314. * software distributed under the License is distributed on an
  45315. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45316. * KIND, either express or implied. See the License for the
  45317. * specific language governing permissions and limitations
  45318. * under the License.
  45319. */
  45320. var actionInfo = {
  45321. type: 'graphRoam',
  45322. event: 'graphRoam',
  45323. update: 'none'
  45324. };
  45325. /**
  45326. * @payload
  45327. * @property {string} name Series name
  45328. * @property {number} [dx]
  45329. * @property {number} [dy]
  45330. * @property {number} [zoom]
  45331. * @property {number} [originX]
  45332. * @property {number} [originY]
  45333. */
  45334. registerAction(actionInfo, function (payload, ecModel) {
  45335. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  45336. var coordSys = seriesModel.coordinateSystem;
  45337. var res = updateCenterAndZoom(coordSys, payload);
  45338. seriesModel.setCenter
  45339. && seriesModel.setCenter(res.center);
  45340. seriesModel.setZoom
  45341. && seriesModel.setZoom(res.zoom);
  45342. });
  45343. });
  45344. /**
  45345. * @payload
  45346. * @property {number} [seriesIndex]
  45347. * @property {string} [seriesId]
  45348. * @property {string} [seriesName]
  45349. * @property {number} [dataIndex]
  45350. */
  45351. registerAction({
  45352. type: 'focusNodeAdjacency',
  45353. event: 'focusNodeAdjacency',
  45354. update: 'series.graph:focusNodeAdjacency'
  45355. }, function () {});
  45356. /**
  45357. * @payload
  45358. * @property {number} [seriesIndex]
  45359. * @property {string} [seriesId]
  45360. * @property {string} [seriesName]
  45361. */
  45362. registerAction({
  45363. type: 'unfocusNodeAdjacency',
  45364. event: 'unfocusNodeAdjacency',
  45365. update: 'series.graph:unfocusNodeAdjacency'
  45366. }, function () {});
  45367. /*
  45368. * Licensed to the Apache Software Foundation (ASF) under one
  45369. * or more contributor license agreements. See the NOTICE file
  45370. * distributed with this work for additional information
  45371. * regarding copyright ownership. The ASF licenses this file
  45372. * to you under the Apache License, Version 2.0 (the
  45373. * "License"); you may not use this file except in compliance
  45374. * with the License. You may obtain a copy of the License at
  45375. *
  45376. * http://www.apache.org/licenses/LICENSE-2.0
  45377. *
  45378. * Unless required by applicable law or agreed to in writing,
  45379. * software distributed under the License is distributed on an
  45380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45381. * KIND, either express or implied. See the License for the
  45382. * specific language governing permissions and limitations
  45383. * under the License.
  45384. */
  45385. var categoryFilter = function (ecModel) {
  45386. var legendModels = ecModel.findComponents({
  45387. mainType: 'legend'
  45388. });
  45389. if (!legendModels || !legendModels.length) {
  45390. return;
  45391. }
  45392. ecModel.eachSeriesByType('graph', function (graphSeries) {
  45393. var categoriesData = graphSeries.getCategoriesData();
  45394. var graph = graphSeries.getGraph();
  45395. var data = graph.data;
  45396. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  45397. data.filterSelf(function (idx) {
  45398. var model = data.getItemModel(idx);
  45399. var category = model.getShallow('category');
  45400. if (category != null) {
  45401. if (typeof category === 'number') {
  45402. category = categoryNames[category];
  45403. }
  45404. // If in any legend component the status is not selected.
  45405. for (var i = 0; i < legendModels.length; i++) {
  45406. if (!legendModels[i].isSelected(category)) {
  45407. return false;
  45408. }
  45409. }
  45410. }
  45411. return true;
  45412. });
  45413. }, this);
  45414. };
  45415. /*
  45416. * Licensed to the Apache Software Foundation (ASF) under one
  45417. * or more contributor license agreements. See the NOTICE file
  45418. * distributed with this work for additional information
  45419. * regarding copyright ownership. The ASF licenses this file
  45420. * to you under the Apache License, Version 2.0 (the
  45421. * "License"); you may not use this file except in compliance
  45422. * with the License. You may obtain a copy of the License at
  45423. *
  45424. * http://www.apache.org/licenses/LICENSE-2.0
  45425. *
  45426. * Unless required by applicable law or agreed to in writing,
  45427. * software distributed under the License is distributed on an
  45428. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45429. * KIND, either express or implied. See the License for the
  45430. * specific language governing permissions and limitations
  45431. * under the License.
  45432. */
  45433. var categoryVisual = function (ecModel) {
  45434. var paletteScope = {};
  45435. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45436. var categoriesData = seriesModel.getCategoriesData();
  45437. var data = seriesModel.getData();
  45438. var categoryNameIdxMap = {};
  45439. categoriesData.each(function (idx) {
  45440. var name = categoriesData.getName(idx);
  45441. // Add prefix to avoid conflict with Object.prototype.
  45442. categoryNameIdxMap['ec-' + name] = idx;
  45443. var itemModel = categoriesData.getItemModel(idx);
  45444. var color = itemModel.get('itemStyle.color')
  45445. || seriesModel.getColorFromPalette(name, paletteScope);
  45446. categoriesData.setItemVisual(idx, 'color', color);
  45447. });
  45448. // Assign category color to visual
  45449. if (categoriesData.count()) {
  45450. data.each(function (idx) {
  45451. var model = data.getItemModel(idx);
  45452. var category = model.getShallow('category');
  45453. if (category != null) {
  45454. if (typeof category === 'string') {
  45455. category = categoryNameIdxMap['ec-' + category];
  45456. }
  45457. if (!data.getItemVisual(idx, 'color', true)) {
  45458. data.setItemVisual(
  45459. idx, 'color',
  45460. categoriesData.getItemVisual(category, 'color')
  45461. );
  45462. }
  45463. }
  45464. });
  45465. }
  45466. });
  45467. };
  45468. /*
  45469. * Licensed to the Apache Software Foundation (ASF) under one
  45470. * or more contributor license agreements. See the NOTICE file
  45471. * distributed with this work for additional information
  45472. * regarding copyright ownership. The ASF licenses this file
  45473. * to you under the Apache License, Version 2.0 (the
  45474. * "License"); you may not use this file except in compliance
  45475. * with the License. You may obtain a copy of the License at
  45476. *
  45477. * http://www.apache.org/licenses/LICENSE-2.0
  45478. *
  45479. * Unless required by applicable law or agreed to in writing,
  45480. * software distributed under the License is distributed on an
  45481. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45482. * KIND, either express or implied. See the License for the
  45483. * specific language governing permissions and limitations
  45484. * under the License.
  45485. */
  45486. function normalize$1(a) {
  45487. if (!(a instanceof Array)) {
  45488. a = [a, a];
  45489. }
  45490. return a;
  45491. }
  45492. var edgeVisual = function (ecModel) {
  45493. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45494. var graph = seriesModel.getGraph();
  45495. var edgeData = seriesModel.getEdgeData();
  45496. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  45497. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  45498. var colorQuery = 'lineStyle.color'.split('.');
  45499. var opacityQuery = 'lineStyle.opacity'.split('.');
  45500. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  45501. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  45502. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  45503. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  45504. edgeData.setVisual('color', seriesModel.get(colorQuery));
  45505. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  45506. edgeData.each(function (idx) {
  45507. var itemModel = edgeData.getItemModel(idx);
  45508. var edge = graph.getEdgeByIndex(idx);
  45509. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  45510. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  45511. // Edge visual must after node visual
  45512. var color = itemModel.get(colorQuery);
  45513. var opacity = itemModel.get(opacityQuery);
  45514. switch (color) {
  45515. case 'source':
  45516. color = edge.node1.getVisual('color');
  45517. break;
  45518. case 'target':
  45519. color = edge.node2.getVisual('color');
  45520. break;
  45521. }
  45522. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  45523. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  45524. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  45525. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  45526. edge.setVisual('color', color);
  45527. edge.setVisual('opacity', opacity);
  45528. });
  45529. });
  45530. };
  45531. /*
  45532. * Licensed to the Apache Software Foundation (ASF) under one
  45533. * or more contributor license agreements. See the NOTICE file
  45534. * distributed with this work for additional information
  45535. * regarding copyright ownership. The ASF licenses this file
  45536. * to you under the Apache License, Version 2.0 (the
  45537. * "License"); you may not use this file except in compliance
  45538. * with the License. You may obtain a copy of the License at
  45539. *
  45540. * http://www.apache.org/licenses/LICENSE-2.0
  45541. *
  45542. * Unless required by applicable law or agreed to in writing,
  45543. * software distributed under the License is distributed on an
  45544. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45545. * KIND, either express or implied. See the License for the
  45546. * specific language governing permissions and limitations
  45547. * under the License.
  45548. */
  45549. function simpleLayout$1(seriesModel) {
  45550. var coordSys = seriesModel.coordinateSystem;
  45551. if (coordSys && coordSys.type !== 'view') {
  45552. return;
  45553. }
  45554. var graph = seriesModel.getGraph();
  45555. graph.eachNode(function (node) {
  45556. var model = node.getModel();
  45557. node.setLayout([+model.get('x'), +model.get('y')]);
  45558. });
  45559. simpleLayoutEdge(graph);
  45560. }
  45561. function simpleLayoutEdge(graph) {
  45562. graph.eachEdge(function (edge) {
  45563. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  45564. var p1 = clone$1(edge.node1.getLayout());
  45565. var p2 = clone$1(edge.node2.getLayout());
  45566. var points = [p1, p2];
  45567. if (+curveness) {
  45568. points.push([
  45569. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  45570. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  45571. ]);
  45572. }
  45573. edge.setLayout(points);
  45574. });
  45575. }
  45576. /*
  45577. * Licensed to the Apache Software Foundation (ASF) under one
  45578. * or more contributor license agreements. See the NOTICE file
  45579. * distributed with this work for additional information
  45580. * regarding copyright ownership. The ASF licenses this file
  45581. * to you under the Apache License, Version 2.0 (the
  45582. * "License"); you may not use this file except in compliance
  45583. * with the License. You may obtain a copy of the License at
  45584. *
  45585. * http://www.apache.org/licenses/LICENSE-2.0
  45586. *
  45587. * Unless required by applicable law or agreed to in writing,
  45588. * software distributed under the License is distributed on an
  45589. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45590. * KIND, either express or implied. See the License for the
  45591. * specific language governing permissions and limitations
  45592. * under the License.
  45593. */
  45594. var simpleLayout = function (ecModel, api) {
  45595. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45596. var layout = seriesModel.get('layout');
  45597. var coordSys = seriesModel.coordinateSystem;
  45598. if (coordSys && coordSys.type !== 'view') {
  45599. var data = seriesModel.getData();
  45600. var dimensions = [];
  45601. each$1(coordSys.dimensions, function (coordDim) {
  45602. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  45603. });
  45604. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  45605. var value = [];
  45606. var hasValue = false;
  45607. for (var i = 0; i < dimensions.length; i++) {
  45608. var val = data.get(dimensions[i], dataIndex);
  45609. if (!isNaN(val)) {
  45610. hasValue = true;
  45611. }
  45612. value.push(val);
  45613. }
  45614. if (hasValue) {
  45615. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  45616. }
  45617. else {
  45618. // Also {Array.<number>}, not undefined to avoid if...else... statement
  45619. data.setItemLayout(dataIndex, [NaN, NaN]);
  45620. }
  45621. }
  45622. simpleLayoutEdge(data.graph);
  45623. }
  45624. else if (!layout || layout === 'none') {
  45625. simpleLayout$1(seriesModel);
  45626. }
  45627. });
  45628. };
  45629. /*
  45630. * Licensed to the Apache Software Foundation (ASF) under one
  45631. * or more contributor license agreements. See the NOTICE file
  45632. * distributed with this work for additional information
  45633. * regarding copyright ownership. The ASF licenses this file
  45634. * to you under the Apache License, Version 2.0 (the
  45635. * "License"); you may not use this file except in compliance
  45636. * with the License. You may obtain a copy of the License at
  45637. *
  45638. * http://www.apache.org/licenses/LICENSE-2.0
  45639. *
  45640. * Unless required by applicable law or agreed to in writing,
  45641. * software distributed under the License is distributed on an
  45642. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45643. * KIND, either express or implied. See the License for the
  45644. * specific language governing permissions and limitations
  45645. * under the License.
  45646. */
  45647. function circularLayout$1(seriesModel) {
  45648. var coordSys = seriesModel.coordinateSystem;
  45649. if (coordSys && coordSys.type !== 'view') {
  45650. return;
  45651. }
  45652. var rect = coordSys.getBoundingRect();
  45653. var nodeData = seriesModel.getData();
  45654. var graph = nodeData.graph;
  45655. var angle = 0;
  45656. var sum = nodeData.getSum('value');
  45657. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  45658. var cx = rect.width / 2 + rect.x;
  45659. var cy = rect.height / 2 + rect.y;
  45660. var r = Math.min(rect.width, rect.height) / 2;
  45661. graph.eachNode(function (node) {
  45662. var value = node.getValue('value');
  45663. angle += unitAngle * (sum ? value : 1) / 2;
  45664. node.setLayout([
  45665. r * Math.cos(angle) + cx,
  45666. r * Math.sin(angle) + cy
  45667. ]);
  45668. angle += unitAngle * (sum ? value : 1) / 2;
  45669. });
  45670. nodeData.setLayout({
  45671. cx: cx,
  45672. cy: cy
  45673. });
  45674. graph.eachEdge(function (edge) {
  45675. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  45676. var p1 = clone$1(edge.node1.getLayout());
  45677. var p2 = clone$1(edge.node2.getLayout());
  45678. var cp1;
  45679. var x12 = (p1[0] + p2[0]) / 2;
  45680. var y12 = (p1[1] + p2[1]) / 2;
  45681. if (+curveness) {
  45682. curveness *= 3;
  45683. cp1 = [
  45684. cx * curveness + x12 * (1 - curveness),
  45685. cy * curveness + y12 * (1 - curveness)
  45686. ];
  45687. }
  45688. edge.setLayout([p1, p2, cp1]);
  45689. });
  45690. }
  45691. /*
  45692. * Licensed to the Apache Software Foundation (ASF) under one
  45693. * or more contributor license agreements. See the NOTICE file
  45694. * distributed with this work for additional information
  45695. * regarding copyright ownership. The ASF licenses this file
  45696. * to you under the Apache License, Version 2.0 (the
  45697. * "License"); you may not use this file except in compliance
  45698. * with the License. You may obtain a copy of the License at
  45699. *
  45700. * http://www.apache.org/licenses/LICENSE-2.0
  45701. *
  45702. * Unless required by applicable law or agreed to in writing,
  45703. * software distributed under the License is distributed on an
  45704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45705. * KIND, either express or implied. See the License for the
  45706. * specific language governing permissions and limitations
  45707. * under the License.
  45708. */
  45709. var circularLayout = function (ecModel) {
  45710. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45711. if (seriesModel.get('layout') === 'circular') {
  45712. circularLayout$1(seriesModel);
  45713. }
  45714. });
  45715. };
  45716. /*
  45717. * Licensed to the Apache Software Foundation (ASF) under one
  45718. * or more contributor license agreements. See the NOTICE file
  45719. * distributed with this work for additional information
  45720. * regarding copyright ownership. The ASF licenses this file
  45721. * to you under the Apache License, Version 2.0 (the
  45722. * "License"); you may not use this file except in compliance
  45723. * with the License. You may obtain a copy of the License at
  45724. *
  45725. * http://www.apache.org/licenses/LICENSE-2.0
  45726. *
  45727. * Unless required by applicable law or agreed to in writing,
  45728. * software distributed under the License is distributed on an
  45729. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45730. * KIND, either express or implied. See the License for the
  45731. * specific language governing permissions and limitations
  45732. * under the License.
  45733. */
  45734. /*
  45735. * The layout implementation references to d3.js. The use of
  45736. * the source code of this file is also subject to the terms
  45737. * and consitions of its license (BSD-3Clause, see
  45738. * <echarts/src/licenses/LICENSE-d3>).
  45739. */
  45740. var scaleAndAdd$2 = scaleAndAdd;
  45741. // function adjacentNode(n, e) {
  45742. // return e.n1 === n ? e.n2 : e.n1;
  45743. // }
  45744. function forceLayout$1(nodes, edges, opts) {
  45745. var rect = opts.rect;
  45746. var width = rect.width;
  45747. var height = rect.height;
  45748. var center = [rect.x + width / 2, rect.y + height / 2];
  45749. // var scale = opts.scale || 1;
  45750. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  45751. // for (var i = 0; i < edges.length; i++) {
  45752. // var e = edges[i];
  45753. // var n1 = e.n1;
  45754. // var n2 = e.n2;
  45755. // n1.edges = n1.edges || [];
  45756. // n2.edges = n2.edges || [];
  45757. // n1.edges.push(e);
  45758. // n2.edges.push(e);
  45759. // }
  45760. // Init position
  45761. for (var i = 0; i < nodes.length; i++) {
  45762. var n = nodes[i];
  45763. if (!n.p) {
  45764. // Use the position from first adjecent node with defined position
  45765. // Or use a random position
  45766. // From d3
  45767. // if (n.edges) {
  45768. // var j = -1;
  45769. // while (++j < n.edges.length) {
  45770. // var e = n.edges[j];
  45771. // var other = adjacentNode(n, e);
  45772. // if (other.p) {
  45773. // n.p = vec2.clone(other.p);
  45774. // break;
  45775. // }
  45776. // }
  45777. // }
  45778. // if (!n.p) {
  45779. n.p = create(
  45780. width * (Math.random() - 0.5) + center[0],
  45781. height * (Math.random() - 0.5) + center[1]
  45782. );
  45783. // }
  45784. }
  45785. n.pp = clone$1(n.p);
  45786. n.edges = null;
  45787. }
  45788. // Formula in 'Graph Drawing by Force-directed Placement'
  45789. // var k = scale * Math.sqrt(width * height / nodes.length);
  45790. // var k2 = k * k;
  45791. var friction = 0.6;
  45792. return {
  45793. warmUp: function () {
  45794. friction = 0.5;
  45795. },
  45796. setFixed: function (idx) {
  45797. nodes[idx].fixed = true;
  45798. },
  45799. setUnfixed: function (idx) {
  45800. nodes[idx].fixed = false;
  45801. },
  45802. step: function (cb) {
  45803. var v12 = [];
  45804. var nLen = nodes.length;
  45805. for (var i = 0; i < edges.length; i++) {
  45806. var e = edges[i];
  45807. var n1 = e.n1;
  45808. var n2 = e.n2;
  45809. sub(v12, n2.p, n1.p);
  45810. var d = len(v12) - e.d;
  45811. var w = n2.w / (n1.w + n2.w);
  45812. if (isNaN(w)) {
  45813. w = 0;
  45814. }
  45815. normalize(v12, v12);
  45816. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  45817. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  45818. }
  45819. // Gravity
  45820. for (var i = 0; i < nLen; i++) {
  45821. var n = nodes[i];
  45822. if (!n.fixed) {
  45823. sub(v12, center, n.p);
  45824. // var d = vec2.len(v12);
  45825. // vec2.scale(v12, v12, 1 / d);
  45826. // var gravityFactor = gravity;
  45827. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  45828. }
  45829. }
  45830. // Repulsive
  45831. // PENDING
  45832. for (var i = 0; i < nLen; i++) {
  45833. var n1 = nodes[i];
  45834. for (var j = i + 1; j < nLen; j++) {
  45835. var n2 = nodes[j];
  45836. sub(v12, n2.p, n1.p);
  45837. var d = len(v12);
  45838. if (d === 0) {
  45839. // Random repulse
  45840. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  45841. d = 1;
  45842. }
  45843. var repFact = (n1.rep + n2.rep) / d / d;
  45844. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  45845. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  45846. }
  45847. }
  45848. var v = [];
  45849. for (var i = 0; i < nLen; i++) {
  45850. var n = nodes[i];
  45851. if (!n.fixed) {
  45852. sub(v, n.p, n.pp);
  45853. scaleAndAdd$2(n.p, n.p, v, friction);
  45854. copy(n.pp, n.p);
  45855. }
  45856. }
  45857. friction = friction * 0.992;
  45858. cb && cb(nodes, edges, friction < 0.01);
  45859. }
  45860. };
  45861. }
  45862. /*
  45863. * Licensed to the Apache Software Foundation (ASF) under one
  45864. * or more contributor license agreements. See the NOTICE file
  45865. * distributed with this work for additional information
  45866. * regarding copyright ownership. The ASF licenses this file
  45867. * to you under the Apache License, Version 2.0 (the
  45868. * "License"); you may not use this file except in compliance
  45869. * with the License. You may obtain a copy of the License at
  45870. *
  45871. * http://www.apache.org/licenses/LICENSE-2.0
  45872. *
  45873. * Unless required by applicable law or agreed to in writing,
  45874. * software distributed under the License is distributed on an
  45875. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45876. * KIND, either express or implied. See the License for the
  45877. * specific language governing permissions and limitations
  45878. * under the License.
  45879. */
  45880. var forceLayout = function (ecModel) {
  45881. ecModel.eachSeriesByType('graph', function (graphSeries) {
  45882. var coordSys = graphSeries.coordinateSystem;
  45883. if (coordSys && coordSys.type !== 'view') {
  45884. return;
  45885. }
  45886. if (graphSeries.get('layout') === 'force') {
  45887. var preservedPoints = graphSeries.preservedPoints || {};
  45888. var graph = graphSeries.getGraph();
  45889. var nodeData = graph.data;
  45890. var edgeData = graph.edgeData;
  45891. var forceModel = graphSeries.getModel('force');
  45892. var initLayout = forceModel.get('initLayout');
  45893. if (graphSeries.preservedPoints) {
  45894. nodeData.each(function (idx) {
  45895. var id = nodeData.getId(idx);
  45896. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  45897. });
  45898. }
  45899. else if (!initLayout || initLayout === 'none') {
  45900. simpleLayout$1(graphSeries);
  45901. }
  45902. else if (initLayout === 'circular') {
  45903. circularLayout$1(graphSeries);
  45904. }
  45905. var nodeDataExtent = nodeData.getDataExtent('value');
  45906. var edgeDataExtent = edgeData.getDataExtent('value');
  45907. // var edgeDataExtent = edgeData.getDataExtent('value');
  45908. var repulsion = forceModel.get('repulsion');
  45909. var edgeLength = forceModel.get('edgeLength');
  45910. if (!isArray(repulsion)) {
  45911. repulsion = [repulsion, repulsion];
  45912. }
  45913. if (!isArray(edgeLength)) {
  45914. edgeLength = [edgeLength, edgeLength];
  45915. }
  45916. // Larger value has smaller length
  45917. edgeLength = [edgeLength[1], edgeLength[0]];
  45918. var nodes = nodeData.mapArray('value', function (value, idx) {
  45919. var point = nodeData.getItemLayout(idx);
  45920. var rep = linearMap(value, nodeDataExtent, repulsion);
  45921. if (isNaN(rep)) {
  45922. rep = (repulsion[0] + repulsion[1]) / 2;
  45923. }
  45924. return {
  45925. w: rep,
  45926. rep: rep,
  45927. fixed: nodeData.getItemModel(idx).get('fixed'),
  45928. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  45929. };
  45930. });
  45931. var edges = edgeData.mapArray('value', function (value, idx) {
  45932. var edge = graph.getEdgeByIndex(idx);
  45933. var d = linearMap(value, edgeDataExtent, edgeLength);
  45934. if (isNaN(d)) {
  45935. d = (edgeLength[0] + edgeLength[1]) / 2;
  45936. }
  45937. return {
  45938. n1: nodes[edge.node1.dataIndex],
  45939. n2: nodes[edge.node2.dataIndex],
  45940. d: d,
  45941. curveness: edge.getModel().get('lineStyle.curveness') || 0
  45942. };
  45943. });
  45944. var coordSys = graphSeries.coordinateSystem;
  45945. var rect = coordSys.getBoundingRect();
  45946. var forceInstance = forceLayout$1(nodes, edges, {
  45947. rect: rect,
  45948. gravity: forceModel.get('gravity')
  45949. });
  45950. var oldStep = forceInstance.step;
  45951. forceInstance.step = function (cb) {
  45952. for (var i = 0, l = nodes.length; i < l; i++) {
  45953. if (nodes[i].fixed) {
  45954. // Write back to layout instance
  45955. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  45956. }
  45957. }
  45958. oldStep(function (nodes, edges, stopped) {
  45959. for (var i = 0, l = nodes.length; i < l; i++) {
  45960. if (!nodes[i].fixed) {
  45961. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  45962. }
  45963. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  45964. }
  45965. for (var i = 0, l = edges.length; i < l; i++) {
  45966. var e = edges[i];
  45967. var edge = graph.getEdgeByIndex(i);
  45968. var p1 = e.n1.p;
  45969. var p2 = e.n2.p;
  45970. var points = edge.getLayout();
  45971. points = points ? points.slice() : [];
  45972. points[0] = points[0] || [];
  45973. points[1] = points[1] || [];
  45974. copy(points[0], p1);
  45975. copy(points[1], p2);
  45976. if (+e.curveness) {
  45977. points[2] = [
  45978. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  45979. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  45980. ];
  45981. }
  45982. edge.setLayout(points);
  45983. }
  45984. // Update layout
  45985. cb && cb(stopped);
  45986. });
  45987. };
  45988. graphSeries.forceLayout = forceInstance;
  45989. graphSeries.preservedPoints = preservedPoints;
  45990. // Step to get the layout
  45991. forceInstance.step();
  45992. }
  45993. else {
  45994. // Remove prev injected forceLayout instance
  45995. graphSeries.forceLayout = null;
  45996. }
  45997. });
  45998. };
  45999. /*
  46000. * Licensed to the Apache Software Foundation (ASF) under one
  46001. * or more contributor license agreements. See the NOTICE file
  46002. * distributed with this work for additional information
  46003. * regarding copyright ownership. The ASF licenses this file
  46004. * to you under the Apache License, Version 2.0 (the
  46005. * "License"); you may not use this file except in compliance
  46006. * with the License. You may obtain a copy of the License at
  46007. *
  46008. * http://www.apache.org/licenses/LICENSE-2.0
  46009. *
  46010. * Unless required by applicable law or agreed to in writing,
  46011. * software distributed under the License is distributed on an
  46012. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46013. * KIND, either express or implied. See the License for the
  46014. * specific language governing permissions and limitations
  46015. * under the License.
  46016. */
  46017. // FIXME Where to create the simple view coordinate system
  46018. function getViewRect$1(seriesModel, api, aspect) {
  46019. var option = seriesModel.getBoxLayoutParams();
  46020. option.aspect = aspect;
  46021. return getLayoutRect(option, {
  46022. width: api.getWidth(),
  46023. height: api.getHeight()
  46024. });
  46025. }
  46026. var createView = function (ecModel, api) {
  46027. var viewList = [];
  46028. ecModel.eachSeriesByType('graph', function (seriesModel) {
  46029. var coordSysType = seriesModel.get('coordinateSystem');
  46030. if (!coordSysType || coordSysType === 'view') {
  46031. var data = seriesModel.getData();
  46032. var positions = data.mapArray(function (idx) {
  46033. var itemModel = data.getItemModel(idx);
  46034. return [+itemModel.get('x'), +itemModel.get('y')];
  46035. });
  46036. var min = [];
  46037. var max = [];
  46038. fromPoints(positions, min, max);
  46039. // If width or height is 0
  46040. if (max[0] - min[0] === 0) {
  46041. max[0] += 1;
  46042. min[0] -= 1;
  46043. }
  46044. if (max[1] - min[1] === 0) {
  46045. max[1] += 1;
  46046. min[1] -= 1;
  46047. }
  46048. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  46049. // FIXME If get view rect after data processed?
  46050. var viewRect = getViewRect$1(seriesModel, api, aspect);
  46051. // Position may be NaN, use view rect instead
  46052. if (isNaN(aspect)) {
  46053. min = [viewRect.x, viewRect.y];
  46054. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  46055. }
  46056. var bbWidth = max[0] - min[0];
  46057. var bbHeight = max[1] - min[1];
  46058. var viewWidth = viewRect.width;
  46059. var viewHeight = viewRect.height;
  46060. var viewCoordSys = seriesModel.coordinateSystem = new View();
  46061. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  46062. viewCoordSys.setBoundingRect(
  46063. min[0], min[1], bbWidth, bbHeight
  46064. );
  46065. viewCoordSys.setViewRect(
  46066. viewRect.x, viewRect.y, viewWidth, viewHeight
  46067. );
  46068. // Update roam info
  46069. viewCoordSys.setCenter(seriesModel.get('center'));
  46070. viewCoordSys.setZoom(seriesModel.get('zoom'));
  46071. viewList.push(viewCoordSys);
  46072. }
  46073. });
  46074. return viewList;
  46075. };
  46076. /*
  46077. * Licensed to the Apache Software Foundation (ASF) under one
  46078. * or more contributor license agreements. See the NOTICE file
  46079. * distributed with this work for additional information
  46080. * regarding copyright ownership. The ASF licenses this file
  46081. * to you under the Apache License, Version 2.0 (the
  46082. * "License"); you may not use this file except in compliance
  46083. * with the License. You may obtain a copy of the License at
  46084. *
  46085. * http://www.apache.org/licenses/LICENSE-2.0
  46086. *
  46087. * Unless required by applicable law or agreed to in writing,
  46088. * software distributed under the License is distributed on an
  46089. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46090. * KIND, either express or implied. See the License for the
  46091. * specific language governing permissions and limitations
  46092. * under the License.
  46093. */
  46094. registerProcessor(categoryFilter);
  46095. registerVisual(visualSymbol('graph', 'circle', null));
  46096. registerVisual(categoryVisual);
  46097. registerVisual(edgeVisual);
  46098. registerLayout(simpleLayout);
  46099. registerLayout(circularLayout);
  46100. registerLayout(forceLayout);
  46101. // Graph view coordinate system
  46102. registerCoordinateSystem('graphView', {
  46103. create: createView
  46104. });
  46105. /*
  46106. * Licensed to the Apache Software Foundation (ASF) under one
  46107. * or more contributor license agreements. See the NOTICE file
  46108. * distributed with this work for additional information
  46109. * regarding copyright ownership. The ASF licenses this file
  46110. * to you under the Apache License, Version 2.0 (the
  46111. * "License"); you may not use this file except in compliance
  46112. * with the License. You may obtain a copy of the License at
  46113. *
  46114. * http://www.apache.org/licenses/LICENSE-2.0
  46115. *
  46116. * Unless required by applicable law or agreed to in writing,
  46117. * software distributed under the License is distributed on an
  46118. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46119. * KIND, either express or implied. See the License for the
  46120. * specific language governing permissions and limitations
  46121. * under the License.
  46122. */
  46123. var GaugeSeries = SeriesModel.extend({
  46124. type: 'series.gauge',
  46125. getInitialData: function (option, ecModel) {
  46126. var dataOpt = option.data || [];
  46127. if (!isArray(dataOpt)) {
  46128. dataOpt = [dataOpt];
  46129. }
  46130. option.data = dataOpt;
  46131. return createListSimply(this, ['value']);
  46132. },
  46133. defaultOption: {
  46134. zlevel: 0,
  46135. z: 2,
  46136. // 默认全局居中
  46137. center: ['50%', '50%'],
  46138. legendHoverLink: true,
  46139. radius: '75%',
  46140. startAngle: 225,
  46141. endAngle: -45,
  46142. clockwise: true,
  46143. // 最小值
  46144. min: 0,
  46145. // 最大值
  46146. max: 100,
  46147. // 分割段数,默认为10
  46148. splitNumber: 10,
  46149. // 坐标轴线
  46150. axisLine: {
  46151. // 默认显示,属性show控制显示与否
  46152. show: true,
  46153. lineStyle: { // 属性lineStyle控制线条样式
  46154. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  46155. width: 30
  46156. }
  46157. },
  46158. // 分隔线
  46159. splitLine: {
  46160. // 默认显示,属性show控制显示与否
  46161. show: true,
  46162. // 属性length控制线长
  46163. length: 30,
  46164. // 属性lineStyle(详见lineStyle)控制线条样式
  46165. lineStyle: {
  46166. color: '#eee',
  46167. width: 2,
  46168. type: 'solid'
  46169. }
  46170. },
  46171. // 坐标轴小标记
  46172. axisTick: {
  46173. // 属性show控制显示与否,默认不显示
  46174. show: true,
  46175. // 每份split细分多少段
  46176. splitNumber: 5,
  46177. // 属性length控制线长
  46178. length: 8,
  46179. // 属性lineStyle控制线条样式
  46180. lineStyle: {
  46181. color: '#eee',
  46182. width: 1,
  46183. type: 'solid'
  46184. }
  46185. },
  46186. axisLabel: {
  46187. show: true,
  46188. distance: 5,
  46189. // formatter: null,
  46190. color: 'auto'
  46191. },
  46192. pointer: {
  46193. show: true,
  46194. length: '80%',
  46195. width: 8
  46196. },
  46197. itemStyle: {
  46198. color: 'auto'
  46199. },
  46200. title: {
  46201. show: true,
  46202. // x, y,单位px
  46203. offsetCenter: [0, '-40%'],
  46204. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  46205. color: '#333',
  46206. fontSize: 15
  46207. },
  46208. detail: {
  46209. show: true,
  46210. backgroundColor: 'rgba(0,0,0,0)',
  46211. borderWidth: 0,
  46212. borderColor: '#ccc',
  46213. width: 100,
  46214. height: null, // self-adaption
  46215. padding: [5, 10],
  46216. // x, y,单位px
  46217. offsetCenter: [0, '40%'],
  46218. // formatter: null,
  46219. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  46220. color: 'auto',
  46221. fontSize: 30
  46222. }
  46223. }
  46224. });
  46225. /*
  46226. * Licensed to the Apache Software Foundation (ASF) under one
  46227. * or more contributor license agreements. See the NOTICE file
  46228. * distributed with this work for additional information
  46229. * regarding copyright ownership. The ASF licenses this file
  46230. * to you under the Apache License, Version 2.0 (the
  46231. * "License"); you may not use this file except in compliance
  46232. * with the License. You may obtain a copy of the License at
  46233. *
  46234. * http://www.apache.org/licenses/LICENSE-2.0
  46235. *
  46236. * Unless required by applicable law or agreed to in writing,
  46237. * software distributed under the License is distributed on an
  46238. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46239. * KIND, either express or implied. See the License for the
  46240. * specific language governing permissions and limitations
  46241. * under the License.
  46242. */
  46243. var PointerPath = Path.extend({
  46244. type: 'echartsGaugePointer',
  46245. shape: {
  46246. angle: 0,
  46247. width: 10,
  46248. r: 10,
  46249. x: 0,
  46250. y: 0
  46251. },
  46252. buildPath: function (ctx, shape) {
  46253. var mathCos = Math.cos;
  46254. var mathSin = Math.sin;
  46255. var r = shape.r;
  46256. var width = shape.width;
  46257. var angle = shape.angle;
  46258. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  46259. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  46260. angle = shape.angle - Math.PI / 2;
  46261. ctx.moveTo(x, y);
  46262. ctx.lineTo(
  46263. shape.x + mathCos(angle) * width,
  46264. shape.y + mathSin(angle) * width
  46265. );
  46266. ctx.lineTo(
  46267. shape.x + mathCos(shape.angle) * r,
  46268. shape.y + mathSin(shape.angle) * r
  46269. );
  46270. ctx.lineTo(
  46271. shape.x - mathCos(angle) * width,
  46272. shape.y - mathSin(angle) * width
  46273. );
  46274. ctx.lineTo(x, y);
  46275. return;
  46276. }
  46277. });
  46278. /*
  46279. * Licensed to the Apache Software Foundation (ASF) under one
  46280. * or more contributor license agreements. See the NOTICE file
  46281. * distributed with this work for additional information
  46282. * regarding copyright ownership. The ASF licenses this file
  46283. * to you under the Apache License, Version 2.0 (the
  46284. * "License"); you may not use this file except in compliance
  46285. * with the License. You may obtain a copy of the License at
  46286. *
  46287. * http://www.apache.org/licenses/LICENSE-2.0
  46288. *
  46289. * Unless required by applicable law or agreed to in writing,
  46290. * software distributed under the License is distributed on an
  46291. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46292. * KIND, either express or implied. See the License for the
  46293. * specific language governing permissions and limitations
  46294. * under the License.
  46295. */
  46296. function parsePosition(seriesModel, api) {
  46297. var center = seriesModel.get('center');
  46298. var width = api.getWidth();
  46299. var height = api.getHeight();
  46300. var size = Math.min(width, height);
  46301. var cx = parsePercent$1(center[0], api.getWidth());
  46302. var cy = parsePercent$1(center[1], api.getHeight());
  46303. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  46304. return {
  46305. cx: cx,
  46306. cy: cy,
  46307. r: r
  46308. };
  46309. }
  46310. function formatLabel(label, labelFormatter) {
  46311. if (labelFormatter) {
  46312. if (typeof labelFormatter === 'string') {
  46313. label = labelFormatter.replace('{value}', label != null ? label : '');
  46314. }
  46315. else if (typeof labelFormatter === 'function') {
  46316. label = labelFormatter(label);
  46317. }
  46318. }
  46319. return label;
  46320. }
  46321. var PI2$5 = Math.PI * 2;
  46322. var GaugeView = Chart.extend({
  46323. type: 'gauge',
  46324. render: function (seriesModel, ecModel, api) {
  46325. this.group.removeAll();
  46326. var colorList = seriesModel.get('axisLine.lineStyle.color');
  46327. var posInfo = parsePosition(seriesModel, api);
  46328. this._renderMain(
  46329. seriesModel, ecModel, api, colorList, posInfo
  46330. );
  46331. },
  46332. dispose: function () {},
  46333. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  46334. var group = this.group;
  46335. var axisLineModel = seriesModel.getModel('axisLine');
  46336. var lineStyleModel = axisLineModel.getModel('lineStyle');
  46337. var clockwise = seriesModel.get('clockwise');
  46338. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  46339. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  46340. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  46341. var prevEndAngle = startAngle;
  46342. var axisLineWidth = lineStyleModel.get('width');
  46343. for (var i = 0; i < colorList.length; i++) {
  46344. // Clamp
  46345. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  46346. var endAngle = startAngle + angleRangeSpan * percent;
  46347. var sector = new Sector({
  46348. shape: {
  46349. startAngle: prevEndAngle,
  46350. endAngle: endAngle,
  46351. cx: posInfo.cx,
  46352. cy: posInfo.cy,
  46353. clockwise: clockwise,
  46354. r0: posInfo.r - axisLineWidth,
  46355. r: posInfo.r
  46356. },
  46357. silent: true
  46358. });
  46359. sector.setStyle({
  46360. fill: colorList[i][1]
  46361. });
  46362. sector.setStyle(lineStyleModel.getLineStyle(
  46363. // Because we use sector to simulate arc
  46364. // so the properties for stroking are useless
  46365. ['color', 'borderWidth', 'borderColor']
  46366. ));
  46367. group.add(sector);
  46368. prevEndAngle = endAngle;
  46369. }
  46370. var getColor = function (percent) {
  46371. // Less than 0
  46372. if (percent <= 0) {
  46373. return colorList[0][1];
  46374. }
  46375. for (var i = 0; i < colorList.length; i++) {
  46376. if (colorList[i][0] >= percent
  46377. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  46378. ) {
  46379. return colorList[i][1];
  46380. }
  46381. }
  46382. // More than 1
  46383. return colorList[i - 1][1];
  46384. };
  46385. if (!clockwise) {
  46386. var tmp = startAngle;
  46387. startAngle = endAngle;
  46388. endAngle = tmp;
  46389. }
  46390. this._renderTicks(
  46391. seriesModel, ecModel, api, getColor, posInfo,
  46392. startAngle, endAngle, clockwise
  46393. );
  46394. this._renderPointer(
  46395. seriesModel, ecModel, api, getColor, posInfo,
  46396. startAngle, endAngle, clockwise
  46397. );
  46398. this._renderTitle(
  46399. seriesModel, ecModel, api, getColor, posInfo
  46400. );
  46401. this._renderDetail(
  46402. seriesModel, ecModel, api, getColor, posInfo
  46403. );
  46404. },
  46405. _renderTicks: function (
  46406. seriesModel, ecModel, api, getColor, posInfo,
  46407. startAngle, endAngle, clockwise
  46408. ) {
  46409. var group = this.group;
  46410. var cx = posInfo.cx;
  46411. var cy = posInfo.cy;
  46412. var r = posInfo.r;
  46413. var minVal = +seriesModel.get('min');
  46414. var maxVal = +seriesModel.get('max');
  46415. var splitLineModel = seriesModel.getModel('splitLine');
  46416. var tickModel = seriesModel.getModel('axisTick');
  46417. var labelModel = seriesModel.getModel('axisLabel');
  46418. var splitNumber = seriesModel.get('splitNumber');
  46419. var subSplitNumber = tickModel.get('splitNumber');
  46420. var splitLineLen = parsePercent$1(
  46421. splitLineModel.get('length'), r
  46422. );
  46423. var tickLen = parsePercent$1(
  46424. tickModel.get('length'), r
  46425. );
  46426. var angle = startAngle;
  46427. var step = (endAngle - startAngle) / splitNumber;
  46428. var subStep = step / subSplitNumber;
  46429. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  46430. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  46431. for (var i = 0; i <= splitNumber; i++) {
  46432. var unitX = Math.cos(angle);
  46433. var unitY = Math.sin(angle);
  46434. // Split line
  46435. if (splitLineModel.get('show')) {
  46436. var splitLine = new Line({
  46437. shape: {
  46438. x1: unitX * r + cx,
  46439. y1: unitY * r + cy,
  46440. x2: unitX * (r - splitLineLen) + cx,
  46441. y2: unitY * (r - splitLineLen) + cy
  46442. },
  46443. style: splitLineStyle,
  46444. silent: true
  46445. });
  46446. if (splitLineStyle.stroke === 'auto') {
  46447. splitLine.setStyle({
  46448. stroke: getColor(i / splitNumber)
  46449. });
  46450. }
  46451. group.add(splitLine);
  46452. }
  46453. // Label
  46454. if (labelModel.get('show')) {
  46455. var label = formatLabel(
  46456. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  46457. labelModel.get('formatter')
  46458. );
  46459. var distance = labelModel.get('distance');
  46460. var autoColor = getColor(i / splitNumber);
  46461. group.add(new Text({
  46462. style: setTextStyle({}, labelModel, {
  46463. text: label,
  46464. x: unitX * (r - splitLineLen - distance) + cx,
  46465. y: unitY * (r - splitLineLen - distance) + cy,
  46466. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  46467. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  46468. }, {autoColor: autoColor}),
  46469. silent: true
  46470. }));
  46471. }
  46472. // Axis tick
  46473. if (tickModel.get('show') && i !== splitNumber) {
  46474. for (var j = 0; j <= subSplitNumber; j++) {
  46475. var unitX = Math.cos(angle);
  46476. var unitY = Math.sin(angle);
  46477. var tickLine = new Line({
  46478. shape: {
  46479. x1: unitX * r + cx,
  46480. y1: unitY * r + cy,
  46481. x2: unitX * (r - tickLen) + cx,
  46482. y2: unitY * (r - tickLen) + cy
  46483. },
  46484. silent: true,
  46485. style: tickLineStyle
  46486. });
  46487. if (tickLineStyle.stroke === 'auto') {
  46488. tickLine.setStyle({
  46489. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  46490. });
  46491. }
  46492. group.add(tickLine);
  46493. angle += subStep;
  46494. }
  46495. angle -= subStep;
  46496. }
  46497. else {
  46498. angle += step;
  46499. }
  46500. }
  46501. },
  46502. _renderPointer: function (
  46503. seriesModel, ecModel, api, getColor, posInfo,
  46504. startAngle, endAngle, clockwise
  46505. ) {
  46506. var group = this.group;
  46507. var oldData = this._data;
  46508. if (!seriesModel.get('pointer.show')) {
  46509. // Remove old element
  46510. oldData && oldData.eachItemGraphicEl(function (el) {
  46511. group.remove(el);
  46512. });
  46513. return;
  46514. }
  46515. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  46516. var angleExtent = [startAngle, endAngle];
  46517. var data = seriesModel.getData();
  46518. var valueDim = data.mapDimension('value');
  46519. data.diff(oldData)
  46520. .add(function (idx) {
  46521. var pointer = new PointerPath({
  46522. shape: {
  46523. angle: startAngle
  46524. }
  46525. });
  46526. initProps(pointer, {
  46527. shape: {
  46528. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  46529. }
  46530. }, seriesModel);
  46531. group.add(pointer);
  46532. data.setItemGraphicEl(idx, pointer);
  46533. })
  46534. .update(function (newIdx, oldIdx) {
  46535. var pointer = oldData.getItemGraphicEl(oldIdx);
  46536. updateProps(pointer, {
  46537. shape: {
  46538. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  46539. }
  46540. }, seriesModel);
  46541. group.add(pointer);
  46542. data.setItemGraphicEl(newIdx, pointer);
  46543. })
  46544. .remove(function (idx) {
  46545. var pointer = oldData.getItemGraphicEl(idx);
  46546. group.remove(pointer);
  46547. })
  46548. .execute();
  46549. data.eachItemGraphicEl(function (pointer, idx) {
  46550. var itemModel = data.getItemModel(idx);
  46551. var pointerModel = itemModel.getModel('pointer');
  46552. pointer.setShape({
  46553. x: posInfo.cx,
  46554. y: posInfo.cy,
  46555. width: parsePercent$1(
  46556. pointerModel.get('width'), posInfo.r
  46557. ),
  46558. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  46559. });
  46560. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  46561. if (pointer.style.fill === 'auto') {
  46562. pointer.setStyle('fill', getColor(
  46563. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  46564. ));
  46565. }
  46566. setHoverStyle(
  46567. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  46568. );
  46569. });
  46570. this._data = data;
  46571. },
  46572. _renderTitle: function (
  46573. seriesModel, ecModel, api, getColor, posInfo
  46574. ) {
  46575. var data = seriesModel.getData();
  46576. var valueDim = data.mapDimension('value');
  46577. var titleModel = seriesModel.getModel('title');
  46578. if (titleModel.get('show')) {
  46579. var offsetCenter = titleModel.get('offsetCenter');
  46580. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  46581. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  46582. var minVal = +seriesModel.get('min');
  46583. var maxVal = +seriesModel.get('max');
  46584. var value = seriesModel.getData().get(valueDim, 0);
  46585. var autoColor = getColor(
  46586. linearMap(value, [minVal, maxVal], [0, 1], true)
  46587. );
  46588. this.group.add(new Text({
  46589. silent: true,
  46590. style: setTextStyle({}, titleModel, {
  46591. x: x,
  46592. y: y,
  46593. // FIXME First data name ?
  46594. text: data.getName(0),
  46595. textAlign: 'center',
  46596. textVerticalAlign: 'middle'
  46597. }, {autoColor: autoColor, forceRich: true})
  46598. }));
  46599. }
  46600. },
  46601. _renderDetail: function (
  46602. seriesModel, ecModel, api, getColor, posInfo
  46603. ) {
  46604. var detailModel = seriesModel.getModel('detail');
  46605. var minVal = +seriesModel.get('min');
  46606. var maxVal = +seriesModel.get('max');
  46607. if (detailModel.get('show')) {
  46608. var offsetCenter = detailModel.get('offsetCenter');
  46609. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  46610. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  46611. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  46612. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  46613. var data = seriesModel.getData();
  46614. var value = data.get(data.mapDimension('value'), 0);
  46615. var autoColor = getColor(
  46616. linearMap(value, [minVal, maxVal], [0, 1], true)
  46617. );
  46618. this.group.add(new Text({
  46619. silent: true,
  46620. style: setTextStyle({}, detailModel, {
  46621. x: x,
  46622. y: y,
  46623. text: formatLabel(
  46624. // FIXME First data name ?
  46625. value, detailModel.get('formatter')
  46626. ),
  46627. textWidth: isNaN(width) ? null : width,
  46628. textHeight: isNaN(height) ? null : height,
  46629. textAlign: 'center',
  46630. textVerticalAlign: 'middle'
  46631. }, {autoColor: autoColor, forceRich: true})
  46632. }));
  46633. }
  46634. }
  46635. });
  46636. /*
  46637. * Licensed to the Apache Software Foundation (ASF) under one
  46638. * or more contributor license agreements. See the NOTICE file
  46639. * distributed with this work for additional information
  46640. * regarding copyright ownership. The ASF licenses this file
  46641. * to you under the Apache License, Version 2.0 (the
  46642. * "License"); you may not use this file except in compliance
  46643. * with the License. You may obtain a copy of the License at
  46644. *
  46645. * http://www.apache.org/licenses/LICENSE-2.0
  46646. *
  46647. * Unless required by applicable law or agreed to in writing,
  46648. * software distributed under the License is distributed on an
  46649. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46650. * KIND, either express or implied. See the License for the
  46651. * specific language governing permissions and limitations
  46652. * under the License.
  46653. */
  46654. /*
  46655. * Licensed to the Apache Software Foundation (ASF) under one
  46656. * or more contributor license agreements. See the NOTICE file
  46657. * distributed with this work for additional information
  46658. * regarding copyright ownership. The ASF licenses this file
  46659. * to you under the Apache License, Version 2.0 (the
  46660. * "License"); you may not use this file except in compliance
  46661. * with the License. You may obtain a copy of the License at
  46662. *
  46663. * http://www.apache.org/licenses/LICENSE-2.0
  46664. *
  46665. * Unless required by applicable law or agreed to in writing,
  46666. * software distributed under the License is distributed on an
  46667. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46668. * KIND, either express or implied. See the License for the
  46669. * specific language governing permissions and limitations
  46670. * under the License.
  46671. */
  46672. var FunnelSeries = extendSeriesModel({
  46673. type: 'series.funnel',
  46674. init: function (option) {
  46675. FunnelSeries.superApply(this, 'init', arguments);
  46676. // Enable legend selection for each data item
  46677. // Use a function instead of direct access because data reference may changed
  46678. this.legendDataProvider = function () {
  46679. return this.getRawData();
  46680. };
  46681. // Extend labelLine emphasis
  46682. this._defaultLabelLine(option);
  46683. },
  46684. getInitialData: function (option, ecModel) {
  46685. return createListSimply(this, ['value']);
  46686. },
  46687. _defaultLabelLine: function (option) {
  46688. // Extend labelLine emphasis
  46689. defaultEmphasis(option, 'labelLine', ['show']);
  46690. var labelLineNormalOpt = option.labelLine;
  46691. var labelLineEmphasisOpt = option.emphasis.labelLine;
  46692. // Not show label line if `label.normal.show = false`
  46693. labelLineNormalOpt.show = labelLineNormalOpt.show
  46694. && option.label.show;
  46695. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  46696. && option.emphasis.label.show;
  46697. },
  46698. // Overwrite
  46699. getDataParams: function (dataIndex) {
  46700. var data = this.getData();
  46701. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  46702. var valueDim = data.mapDimension('value');
  46703. var sum = data.getSum(valueDim);
  46704. // Percent is 0 if sum is 0
  46705. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  46706. params.$vars.push('percent');
  46707. return params;
  46708. },
  46709. defaultOption: {
  46710. zlevel: 0, // 一级层叠
  46711. z: 2, // 二级层叠
  46712. legendHoverLink: true,
  46713. left: 80,
  46714. top: 60,
  46715. right: 80,
  46716. bottom: 60,
  46717. // width: {totalWidth} - left - right,
  46718. // height: {totalHeight} - top - bottom,
  46719. // 默认取数据最小最大值
  46720. // min: 0,
  46721. // max: 100,
  46722. minSize: '0%',
  46723. maxSize: '100%',
  46724. sort: 'descending', // 'ascending', 'descending'
  46725. gap: 0,
  46726. funnelAlign: 'center',
  46727. label: {
  46728. show: true,
  46729. position: 'outer'
  46730. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  46731. },
  46732. labelLine: {
  46733. show: true,
  46734. length: 20,
  46735. lineStyle: {
  46736. // color: 各异,
  46737. width: 1,
  46738. type: 'solid'
  46739. }
  46740. },
  46741. itemStyle: {
  46742. // color: 各异,
  46743. borderColor: '#fff',
  46744. borderWidth: 1
  46745. },
  46746. emphasis: {
  46747. label: {
  46748. show: true
  46749. }
  46750. }
  46751. }
  46752. });
  46753. /*
  46754. * Licensed to the Apache Software Foundation (ASF) under one
  46755. * or more contributor license agreements. See the NOTICE file
  46756. * distributed with this work for additional information
  46757. * regarding copyright ownership. The ASF licenses this file
  46758. * to you under the Apache License, Version 2.0 (the
  46759. * "License"); you may not use this file except in compliance
  46760. * with the License. You may obtain a copy of the License at
  46761. *
  46762. * http://www.apache.org/licenses/LICENSE-2.0
  46763. *
  46764. * Unless required by applicable law or agreed to in writing,
  46765. * software distributed under the License is distributed on an
  46766. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46767. * KIND, either express or implied. See the License for the
  46768. * specific language governing permissions and limitations
  46769. * under the License.
  46770. */
  46771. /**
  46772. * Piece of pie including Sector, Label, LabelLine
  46773. * @constructor
  46774. * @extends {module:zrender/graphic/Group}
  46775. */
  46776. function FunnelPiece(data, idx) {
  46777. Group.call(this);
  46778. var polygon = new Polygon();
  46779. var labelLine = new Polyline();
  46780. var text = new Text();
  46781. this.add(polygon);
  46782. this.add(labelLine);
  46783. this.add(text);
  46784. this.updateData(data, idx, true);
  46785. // Hover to change label and labelLine
  46786. function onEmphasis() {
  46787. labelLine.ignore = labelLine.hoverIgnore;
  46788. text.ignore = text.hoverIgnore;
  46789. }
  46790. function onNormal() {
  46791. labelLine.ignore = labelLine.normalIgnore;
  46792. text.ignore = text.normalIgnore;
  46793. }
  46794. this.on('emphasis', onEmphasis)
  46795. .on('normal', onNormal)
  46796. .on('mouseover', onEmphasis)
  46797. .on('mouseout', onNormal);
  46798. }
  46799. var funnelPieceProto = FunnelPiece.prototype;
  46800. var opacityAccessPath = ['itemStyle', 'opacity'];
  46801. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  46802. var polygon = this.childAt(0);
  46803. var seriesModel = data.hostModel;
  46804. var itemModel = data.getItemModel(idx);
  46805. var layout = data.getItemLayout(idx);
  46806. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  46807. opacity = opacity == null ? 1 : opacity;
  46808. // Reset style
  46809. polygon.useStyle({});
  46810. if (firstCreate) {
  46811. polygon.setShape({
  46812. points: layout.points
  46813. });
  46814. polygon.setStyle({ opacity : 0 });
  46815. initProps(polygon, {
  46816. style: {
  46817. opacity: opacity
  46818. }
  46819. }, seriesModel, idx);
  46820. }
  46821. else {
  46822. updateProps(polygon, {
  46823. style: {
  46824. opacity: opacity
  46825. },
  46826. shape: {
  46827. points: layout.points
  46828. }
  46829. }, seriesModel, idx);
  46830. }
  46831. // Update common style
  46832. var itemStyleModel = itemModel.getModel('itemStyle');
  46833. var visualColor = data.getItemVisual(idx, 'color');
  46834. polygon.setStyle(
  46835. defaults(
  46836. {
  46837. lineJoin: 'round',
  46838. fill: visualColor
  46839. },
  46840. itemStyleModel.getItemStyle(['opacity'])
  46841. )
  46842. );
  46843. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  46844. this._updateLabel(data, idx);
  46845. setHoverStyle(this);
  46846. };
  46847. funnelPieceProto._updateLabel = function (data, idx) {
  46848. var labelLine = this.childAt(1);
  46849. var labelText = this.childAt(2);
  46850. var seriesModel = data.hostModel;
  46851. var itemModel = data.getItemModel(idx);
  46852. var layout = data.getItemLayout(idx);
  46853. var labelLayout = layout.label;
  46854. var visualColor = data.getItemVisual(idx, 'color');
  46855. updateProps(labelLine, {
  46856. shape: {
  46857. points: labelLayout.linePoints || labelLayout.linePoints
  46858. }
  46859. }, seriesModel, idx);
  46860. updateProps(labelText, {
  46861. style: {
  46862. x: labelLayout.x,
  46863. y: labelLayout.y
  46864. }
  46865. }, seriesModel, idx);
  46866. labelText.attr({
  46867. rotation: labelLayout.rotation,
  46868. origin: [labelLayout.x, labelLayout.y],
  46869. z2: 10
  46870. });
  46871. var labelModel = itemModel.getModel('label');
  46872. var labelHoverModel = itemModel.getModel('emphasis.label');
  46873. var labelLineModel = itemModel.getModel('labelLine');
  46874. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  46875. var visualColor = data.getItemVisual(idx, 'color');
  46876. setLabelStyle(
  46877. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  46878. {
  46879. labelFetcher: data.hostModel,
  46880. labelDataIndex: idx,
  46881. defaultText: data.getName(idx),
  46882. autoColor: visualColor,
  46883. useInsideStyle: !!labelLayout.inside
  46884. },
  46885. {
  46886. textAlign: labelLayout.textAlign,
  46887. textVerticalAlign: labelLayout.verticalAlign
  46888. }
  46889. );
  46890. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  46891. labelText.hoverIgnore = !labelHoverModel.get('show');
  46892. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  46893. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  46894. // Default use item visual color
  46895. labelLine.setStyle({
  46896. stroke: visualColor
  46897. });
  46898. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  46899. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  46900. };
  46901. inherits(FunnelPiece, Group);
  46902. var FunnelView = Chart.extend({
  46903. type: 'funnel',
  46904. render: function (seriesModel, ecModel, api) {
  46905. var data = seriesModel.getData();
  46906. var oldData = this._data;
  46907. var group = this.group;
  46908. data.diff(oldData)
  46909. .add(function (idx) {
  46910. var funnelPiece = new FunnelPiece(data, idx);
  46911. data.setItemGraphicEl(idx, funnelPiece);
  46912. group.add(funnelPiece);
  46913. })
  46914. .update(function (newIdx, oldIdx) {
  46915. var piePiece = oldData.getItemGraphicEl(oldIdx);
  46916. piePiece.updateData(data, newIdx);
  46917. group.add(piePiece);
  46918. data.setItemGraphicEl(newIdx, piePiece);
  46919. })
  46920. .remove(function (idx) {
  46921. var piePiece = oldData.getItemGraphicEl(idx);
  46922. group.remove(piePiece);
  46923. })
  46924. .execute();
  46925. this._data = data;
  46926. },
  46927. remove: function () {
  46928. this.group.removeAll();
  46929. this._data = null;
  46930. },
  46931. dispose: function () {}
  46932. });
  46933. /*
  46934. * Licensed to the Apache Software Foundation (ASF) under one
  46935. * or more contributor license agreements. See the NOTICE file
  46936. * distributed with this work for additional information
  46937. * regarding copyright ownership. The ASF licenses this file
  46938. * to you under the Apache License, Version 2.0 (the
  46939. * "License"); you may not use this file except in compliance
  46940. * with the License. You may obtain a copy of the License at
  46941. *
  46942. * http://www.apache.org/licenses/LICENSE-2.0
  46943. *
  46944. * Unless required by applicable law or agreed to in writing,
  46945. * software distributed under the License is distributed on an
  46946. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46947. * KIND, either express or implied. See the License for the
  46948. * specific language governing permissions and limitations
  46949. * under the License.
  46950. */
  46951. function getViewRect$2(seriesModel, api) {
  46952. return getLayoutRect(
  46953. seriesModel.getBoxLayoutParams(), {
  46954. width: api.getWidth(),
  46955. height: api.getHeight()
  46956. }
  46957. );
  46958. }
  46959. function getSortedIndices(data, sort) {
  46960. var valueDim = data.mapDimension('value');
  46961. var valueArr = data.mapArray(valueDim, function (val) {
  46962. return val;
  46963. });
  46964. var indices = [];
  46965. var isAscending = sort === 'ascending';
  46966. for (var i = 0, len = data.count(); i < len; i++) {
  46967. indices[i] = i;
  46968. }
  46969. // Add custom sortable function & none sortable opetion by "options.sort"
  46970. if (typeof sort === 'function') {
  46971. indices.sort(sort);
  46972. } else if (sort !== 'none') {
  46973. indices.sort(function (a, b) {
  46974. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  46975. });
  46976. }
  46977. return indices;
  46978. }
  46979. function labelLayout$1(data) {
  46980. data.each(function (idx) {
  46981. var itemModel = data.getItemModel(idx);
  46982. var labelModel = itemModel.getModel('label');
  46983. var labelPosition = labelModel.get('position');
  46984. var labelLineModel = itemModel.getModel('labelLine');
  46985. var layout = data.getItemLayout(idx);
  46986. var points = layout.points;
  46987. var isLabelInside = labelPosition === 'inner'
  46988. || labelPosition === 'inside' || labelPosition === 'center';
  46989. var textAlign;
  46990. var textX;
  46991. var textY;
  46992. var linePoints;
  46993. if (isLabelInside) {
  46994. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  46995. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  46996. textAlign = 'center';
  46997. linePoints = [
  46998. [textX, textY], [textX, textY]
  46999. ];
  47000. }
  47001. else {
  47002. var x1;
  47003. var y1;
  47004. var x2;
  47005. var labelLineLen = labelLineModel.get('length');
  47006. if (labelPosition === 'left') {
  47007. // Left side
  47008. x1 = (points[3][0] + points[0][0]) / 2;
  47009. y1 = (points[3][1] + points[0][1]) / 2;
  47010. x2 = x1 - labelLineLen;
  47011. textX = x2 - 5;
  47012. textAlign = 'right';
  47013. }
  47014. else {
  47015. // Right side
  47016. x1 = (points[1][0] + points[2][0]) / 2;
  47017. y1 = (points[1][1] + points[2][1]) / 2;
  47018. x2 = x1 + labelLineLen;
  47019. textX = x2 + 5;
  47020. textAlign = 'left';
  47021. }
  47022. var y2 = y1;
  47023. linePoints = [[x1, y1], [x2, y2]];
  47024. textY = y2;
  47025. }
  47026. layout.label = {
  47027. linePoints: linePoints,
  47028. x: textX,
  47029. y: textY,
  47030. verticalAlign: 'middle',
  47031. textAlign: textAlign,
  47032. inside: isLabelInside
  47033. };
  47034. });
  47035. }
  47036. var funnelLayout = function (ecModel, api, payload) {
  47037. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  47038. var data = seriesModel.getData();
  47039. var valueDim = data.mapDimension('value');
  47040. var sort = seriesModel.get('sort');
  47041. var viewRect = getViewRect$2(seriesModel, api);
  47042. var indices = getSortedIndices(data, sort);
  47043. var sizeExtent = [
  47044. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  47045. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  47046. ];
  47047. var dataExtent = data.getDataExtent(valueDim);
  47048. var min = seriesModel.get('min');
  47049. var max = seriesModel.get('max');
  47050. if (min == null) {
  47051. min = Math.min(dataExtent[0], 0);
  47052. }
  47053. if (max == null) {
  47054. max = dataExtent[1];
  47055. }
  47056. var funnelAlign = seriesModel.get('funnelAlign');
  47057. var gap = seriesModel.get('gap');
  47058. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  47059. var y = viewRect.y;
  47060. var getLinePoints = function (idx, offY) {
  47061. // End point index is data.count() and we assign it 0
  47062. var val = data.get(valueDim, idx) || 0;
  47063. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  47064. var x0;
  47065. switch (funnelAlign) {
  47066. case 'left':
  47067. x0 = viewRect.x;
  47068. break;
  47069. case 'center':
  47070. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  47071. break;
  47072. case 'right':
  47073. x0 = viewRect.x + viewRect.width - itemWidth;
  47074. break;
  47075. }
  47076. return [
  47077. [x0, offY],
  47078. [x0 + itemWidth, offY]
  47079. ];
  47080. };
  47081. if (sort === 'ascending') {
  47082. // From bottom to top
  47083. itemHeight = -itemHeight;
  47084. gap = -gap;
  47085. y += viewRect.height;
  47086. indices = indices.reverse();
  47087. }
  47088. for (var i = 0; i < indices.length; i++) {
  47089. var idx = indices[i];
  47090. var nextIdx = indices[i + 1];
  47091. var itemModel = data.getItemModel(idx);
  47092. var height = itemModel.get('itemStyle.height');
  47093. if (height == null) {
  47094. height = itemHeight;
  47095. }
  47096. else {
  47097. height = parsePercent$1(height, viewRect.height);
  47098. if (sort === 'ascending') {
  47099. height = -height;
  47100. }
  47101. }
  47102. var start = getLinePoints(idx, y);
  47103. var end = getLinePoints(nextIdx, y + height);
  47104. y += height + gap;
  47105. data.setItemLayout(idx, {
  47106. points: start.concat(end.slice().reverse())
  47107. });
  47108. }
  47109. labelLayout$1(data);
  47110. });
  47111. };
  47112. /*
  47113. * Licensed to the Apache Software Foundation (ASF) under one
  47114. * or more contributor license agreements. See the NOTICE file
  47115. * distributed with this work for additional information
  47116. * regarding copyright ownership. The ASF licenses this file
  47117. * to you under the Apache License, Version 2.0 (the
  47118. * "License"); you may not use this file except in compliance
  47119. * with the License. You may obtain a copy of the License at
  47120. *
  47121. * http://www.apache.org/licenses/LICENSE-2.0
  47122. *
  47123. * Unless required by applicable law or agreed to in writing,
  47124. * software distributed under the License is distributed on an
  47125. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47126. * KIND, either express or implied. See the License for the
  47127. * specific language governing permissions and limitations
  47128. * under the License.
  47129. */
  47130. registerVisual(dataColor('funnel'));
  47131. registerLayout(funnelLayout);
  47132. registerProcessor(dataFilter('funnel'));
  47133. /*
  47134. * Licensed to the Apache Software Foundation (ASF) under one
  47135. * or more contributor license agreements. See the NOTICE file
  47136. * distributed with this work for additional information
  47137. * regarding copyright ownership. The ASF licenses this file
  47138. * to you under the Apache License, Version 2.0 (the
  47139. * "License"); you may not use this file except in compliance
  47140. * with the License. You may obtain a copy of the License at
  47141. *
  47142. * http://www.apache.org/licenses/LICENSE-2.0
  47143. *
  47144. * Unless required by applicable law or agreed to in writing,
  47145. * software distributed under the License is distributed on an
  47146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47147. * KIND, either express or implied. See the License for the
  47148. * specific language governing permissions and limitations
  47149. * under the License.
  47150. */
  47151. var parallelPreprocessor = function (option) {
  47152. createParallelIfNeeded(option);
  47153. mergeAxisOptionFromParallel(option);
  47154. };
  47155. /**
  47156. * Create a parallel coordinate if not exists.
  47157. * @inner
  47158. */
  47159. function createParallelIfNeeded(option) {
  47160. if (option.parallel) {
  47161. return;
  47162. }
  47163. var hasParallelSeries = false;
  47164. each$1(option.series, function (seriesOpt) {
  47165. if (seriesOpt && seriesOpt.type === 'parallel') {
  47166. hasParallelSeries = true;
  47167. }
  47168. });
  47169. if (hasParallelSeries) {
  47170. option.parallel = [{}];
  47171. }
  47172. }
  47173. /**
  47174. * Merge aixs definition from parallel option (if exists) to axis option.
  47175. * @inner
  47176. */
  47177. function mergeAxisOptionFromParallel(option) {
  47178. var axes = normalizeToArray(option.parallelAxis);
  47179. each$1(axes, function (axisOption) {
  47180. if (!isObject$1(axisOption)) {
  47181. return;
  47182. }
  47183. var parallelIndex = axisOption.parallelIndex || 0;
  47184. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  47185. if (parallelOption && parallelOption.parallelAxisDefault) {
  47186. merge(axisOption, parallelOption.parallelAxisDefault, false);
  47187. }
  47188. });
  47189. }
  47190. /*
  47191. * Licensed to the Apache Software Foundation (ASF) under one
  47192. * or more contributor license agreements. See the NOTICE file
  47193. * distributed with this work for additional information
  47194. * regarding copyright ownership. The ASF licenses this file
  47195. * to you under the Apache License, Version 2.0 (the
  47196. * "License"); you may not use this file except in compliance
  47197. * with the License. You may obtain a copy of the License at
  47198. *
  47199. * http://www.apache.org/licenses/LICENSE-2.0
  47200. *
  47201. * Unless required by applicable law or agreed to in writing,
  47202. * software distributed under the License is distributed on an
  47203. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47204. * KIND, either express or implied. See the License for the
  47205. * specific language governing permissions and limitations
  47206. * under the License.
  47207. */
  47208. /**
  47209. * @constructor module:echarts/coord/parallel/ParallelAxis
  47210. * @extends {module:echarts/coord/Axis}
  47211. * @param {string} dim
  47212. * @param {*} scale
  47213. * @param {Array.<number>} coordExtent
  47214. * @param {string} axisType
  47215. */
  47216. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  47217. Axis.call(this, dim, scale, coordExtent);
  47218. /**
  47219. * Axis type
  47220. * - 'category'
  47221. * - 'value'
  47222. * - 'time'
  47223. * - 'log'
  47224. * @type {string}
  47225. */
  47226. this.type = axisType || 'value';
  47227. /**
  47228. * @type {number}
  47229. * @readOnly
  47230. */
  47231. this.axisIndex = axisIndex;
  47232. };
  47233. ParallelAxis.prototype = {
  47234. constructor: ParallelAxis,
  47235. /**
  47236. * Axis model
  47237. * @param {module:echarts/coord/parallel/AxisModel}
  47238. */
  47239. model: null,
  47240. /**
  47241. * @override
  47242. */
  47243. isHorizontal: function () {
  47244. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  47245. }
  47246. };
  47247. inherits(ParallelAxis, Axis);
  47248. /*
  47249. * Licensed to the Apache Software Foundation (ASF) under one
  47250. * or more contributor license agreements. See the NOTICE file
  47251. * distributed with this work for additional information
  47252. * regarding copyright ownership. The ASF licenses this file
  47253. * to you under the Apache License, Version 2.0 (the
  47254. * "License"); you may not use this file except in compliance
  47255. * with the License. You may obtain a copy of the License at
  47256. *
  47257. * http://www.apache.org/licenses/LICENSE-2.0
  47258. *
  47259. * Unless required by applicable law or agreed to in writing,
  47260. * software distributed under the License is distributed on an
  47261. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47262. * KIND, either express or implied. See the License for the
  47263. * specific language governing permissions and limitations
  47264. * under the License.
  47265. */
  47266. /**
  47267. * Calculate slider move result.
  47268. * Usage:
  47269. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  47270. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  47271. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  47272. *
  47273. * @param {number} delta Move length.
  47274. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  47275. * handleEnds will be modified in this method.
  47276. * @param {Array.<number>} extent handleEnds is restricted by extent.
  47277. * extent[0] should less or equals than extent[1].
  47278. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  47279. * where the input minSpan and maxSpan will not work.
  47280. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  47281. * If not set, handle0 and cross handle1. If set as a non-negative
  47282. * number (including `0`), handles will push each other when reaching
  47283. * the minSpan.
  47284. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  47285. * @return {Array.<number>} The input handleEnds.
  47286. */
  47287. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  47288. // Normalize firstly.
  47289. handleEnds[0] = restrict$1(handleEnds[0], extent);
  47290. handleEnds[1] = restrict$1(handleEnds[1], extent);
  47291. delta = delta || 0;
  47292. var extentSpan = extent[1] - extent[0];
  47293. // Notice maxSpan and minSpan can be null/undefined.
  47294. if (minSpan != null) {
  47295. minSpan = restrict$1(minSpan, [0, extentSpan]);
  47296. }
  47297. if (maxSpan != null) {
  47298. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  47299. }
  47300. if (handleIndex === 'all') {
  47301. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  47302. handleIndex = 0;
  47303. }
  47304. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  47305. handleEnds[handleIndex] += delta;
  47306. // Restrict in extent.
  47307. var extentMinSpan = minSpan || 0;
  47308. var realExtent = extent.slice();
  47309. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  47310. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  47311. // Expand span.
  47312. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47313. if (minSpan != null && (
  47314. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  47315. )) {
  47316. // If minSpan exists, 'cross' is forbinden.
  47317. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  47318. }
  47319. // Shrink span.
  47320. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47321. if (maxSpan != null && currDistSign.span > maxSpan) {
  47322. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  47323. }
  47324. return handleEnds;
  47325. };
  47326. function getSpanSign(handleEnds, handleIndex) {
  47327. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  47328. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  47329. // is at left of handleEnds[1] for non-cross case.
  47330. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  47331. }
  47332. function restrict$1(value, extend) {
  47333. return Math.min(extend[1], Math.max(extend[0], value));
  47334. }
  47335. /*
  47336. * Licensed to the Apache Software Foundation (ASF) under one
  47337. * or more contributor license agreements. See the NOTICE file
  47338. * distributed with this work for additional information
  47339. * regarding copyright ownership. The ASF licenses this file
  47340. * to you under the Apache License, Version 2.0 (the
  47341. * "License"); you may not use this file except in compliance
  47342. * with the License. You may obtain a copy of the License at
  47343. *
  47344. * http://www.apache.org/licenses/LICENSE-2.0
  47345. *
  47346. * Unless required by applicable law or agreed to in writing,
  47347. * software distributed under the License is distributed on an
  47348. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47349. * KIND, either express or implied. See the License for the
  47350. * specific language governing permissions and limitations
  47351. * under the License.
  47352. */
  47353. /**
  47354. * Parallel Coordinates
  47355. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  47356. */
  47357. var each$11 = each$1;
  47358. var mathMin$5 = Math.min;
  47359. var mathMax$5 = Math.max;
  47360. var mathFloor$2 = Math.floor;
  47361. var mathCeil$2 = Math.ceil;
  47362. var round$2 = round$1;
  47363. var PI$3 = Math.PI;
  47364. function Parallel(parallelModel, ecModel, api) {
  47365. /**
  47366. * key: dimension
  47367. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  47368. * @private
  47369. */
  47370. this._axesMap = createHashMap();
  47371. /**
  47372. * key: dimension
  47373. * value: {position: [], rotation, }
  47374. * @type {Object.<string, Object>}
  47375. * @private
  47376. */
  47377. this._axesLayout = {};
  47378. /**
  47379. * Always follow axis order.
  47380. * @type {Array.<string>}
  47381. * @readOnly
  47382. */
  47383. this.dimensions = parallelModel.dimensions;
  47384. /**
  47385. * @type {module:zrender/core/BoundingRect}
  47386. */
  47387. this._rect;
  47388. /**
  47389. * @type {module:echarts/coord/parallel/ParallelModel}
  47390. */
  47391. this._model = parallelModel;
  47392. this._init(parallelModel, ecModel, api);
  47393. }
  47394. Parallel.prototype = {
  47395. type: 'parallel',
  47396. constructor: Parallel,
  47397. /**
  47398. * Initialize cartesian coordinate systems
  47399. * @private
  47400. */
  47401. _init: function (parallelModel, ecModel, api) {
  47402. var dimensions = parallelModel.dimensions;
  47403. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  47404. each$11(dimensions, function (dim, idx) {
  47405. var axisIndex = parallelAxisIndex[idx];
  47406. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  47407. var axis = this._axesMap.set(dim, new ParallelAxis(
  47408. dim,
  47409. createScaleByModel(axisModel),
  47410. [0, 0],
  47411. axisModel.get('type'),
  47412. axisIndex
  47413. ));
  47414. var isCategory = axis.type === 'category';
  47415. axis.onBand = isCategory && axisModel.get('boundaryGap');
  47416. axis.inverse = axisModel.get('inverse');
  47417. // Injection
  47418. axisModel.axis = axis;
  47419. axis.model = axisModel;
  47420. axis.coordinateSystem = axisModel.coordinateSystem = this;
  47421. }, this);
  47422. },
  47423. /**
  47424. * Update axis scale after data processed
  47425. * @param {module:echarts/model/Global} ecModel
  47426. * @param {module:echarts/ExtensionAPI} api
  47427. */
  47428. update: function (ecModel, api) {
  47429. this._updateAxesFromSeries(this._model, ecModel);
  47430. },
  47431. /**
  47432. * @override
  47433. */
  47434. containPoint: function (point) {
  47435. var layoutInfo = this._makeLayoutInfo();
  47436. var axisBase = layoutInfo.axisBase;
  47437. var layoutBase = layoutInfo.layoutBase;
  47438. var pixelDimIndex = layoutInfo.pixelDimIndex;
  47439. var pAxis = point[1 - pixelDimIndex];
  47440. var pLayout = point[pixelDimIndex];
  47441. return pAxis >= axisBase
  47442. && pAxis <= axisBase + layoutInfo.axisLength
  47443. && pLayout >= layoutBase
  47444. && pLayout <= layoutBase + layoutInfo.layoutLength;
  47445. },
  47446. getModel: function () {
  47447. return this._model;
  47448. },
  47449. /**
  47450. * Update properties from series
  47451. * @private
  47452. */
  47453. _updateAxesFromSeries: function (parallelModel, ecModel) {
  47454. ecModel.eachSeries(function (seriesModel) {
  47455. if (!parallelModel.contains(seriesModel, ecModel)) {
  47456. return;
  47457. }
  47458. var data = seriesModel.getData();
  47459. each$11(this.dimensions, function (dim) {
  47460. var axis = this._axesMap.get(dim);
  47461. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  47462. niceScaleExtent(axis.scale, axis.model);
  47463. }, this);
  47464. }, this);
  47465. },
  47466. /**
  47467. * Resize the parallel coordinate system.
  47468. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  47469. * @param {module:echarts/ExtensionAPI} api
  47470. */
  47471. resize: function (parallelModel, api) {
  47472. this._rect = getLayoutRect(
  47473. parallelModel.getBoxLayoutParams(),
  47474. {
  47475. width: api.getWidth(),
  47476. height: api.getHeight()
  47477. }
  47478. );
  47479. this._layoutAxes();
  47480. },
  47481. /**
  47482. * @return {module:zrender/core/BoundingRect}
  47483. */
  47484. getRect: function () {
  47485. return this._rect;
  47486. },
  47487. /**
  47488. * @private
  47489. */
  47490. _makeLayoutInfo: function () {
  47491. var parallelModel = this._model;
  47492. var rect = this._rect;
  47493. var xy = ['x', 'y'];
  47494. var wh = ['width', 'height'];
  47495. var layout = parallelModel.get('layout');
  47496. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  47497. var layoutLength = rect[wh[pixelDimIndex]];
  47498. var layoutExtent = [0, layoutLength];
  47499. var axisCount = this.dimensions.length;
  47500. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  47501. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  47502. var axisExpandable = parallelModel.get('axisExpandable')
  47503. && axisCount > 3
  47504. && axisCount > axisExpandCount
  47505. && axisExpandCount > 1
  47506. && axisExpandWidth > 0
  47507. && layoutLength > 0;
  47508. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  47509. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  47510. // where collapsed axes should be overlapped.
  47511. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  47512. var winSize;
  47513. if (!axisExpandWindow) {
  47514. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  47515. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  47516. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  47517. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  47518. }
  47519. else {
  47520. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  47521. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  47522. }
  47523. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  47524. // Avoid axisCollapseWidth is too small.
  47525. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  47526. // Find the first and last indices > ewin[0] and < ewin[1].
  47527. var winInnerIndices = [
  47528. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  47529. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  47530. ];
  47531. // Pos in ec coordinates.
  47532. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  47533. return {
  47534. layout: layout,
  47535. pixelDimIndex: pixelDimIndex,
  47536. layoutBase: rect[xy[pixelDimIndex]],
  47537. layoutLength: layoutLength,
  47538. axisBase: rect[xy[1 - pixelDimIndex]],
  47539. axisLength: rect[wh[1 - pixelDimIndex]],
  47540. axisExpandable: axisExpandable,
  47541. axisExpandWidth: axisExpandWidth,
  47542. axisCollapseWidth: axisCollapseWidth,
  47543. axisExpandWindow: axisExpandWindow,
  47544. axisCount: axisCount,
  47545. winInnerIndices: winInnerIndices,
  47546. axisExpandWindow0Pos: axisExpandWindow0Pos
  47547. };
  47548. },
  47549. /**
  47550. * @private
  47551. */
  47552. _layoutAxes: function () {
  47553. var rect = this._rect;
  47554. var axes = this._axesMap;
  47555. var dimensions = this.dimensions;
  47556. var layoutInfo = this._makeLayoutInfo();
  47557. var layout = layoutInfo.layout;
  47558. axes.each(function (axis) {
  47559. var axisExtent = [0, layoutInfo.axisLength];
  47560. var idx = axis.inverse ? 1 : 0;
  47561. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  47562. });
  47563. each$11(dimensions, function (dim, idx) {
  47564. var posInfo = (layoutInfo.axisExpandable
  47565. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  47566. )(idx, layoutInfo);
  47567. var positionTable = {
  47568. horizontal: {
  47569. x: posInfo.position,
  47570. y: layoutInfo.axisLength
  47571. },
  47572. vertical: {
  47573. x: 0,
  47574. y: posInfo.position
  47575. }
  47576. };
  47577. var rotationTable = {
  47578. horizontal: PI$3 / 2,
  47579. vertical: 0
  47580. };
  47581. var position = [
  47582. positionTable[layout].x + rect.x,
  47583. positionTable[layout].y + rect.y
  47584. ];
  47585. var rotation = rotationTable[layout];
  47586. var transform = create$1();
  47587. rotate(transform, transform, rotation);
  47588. translate(transform, transform, position);
  47589. // TODO
  47590. // tick等排布信息。
  47591. // TODO
  47592. // 根据axis order 更新 dimensions顺序。
  47593. this._axesLayout[dim] = {
  47594. position: position,
  47595. rotation: rotation,
  47596. transform: transform,
  47597. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  47598. axisLabelShow: posInfo.axisLabelShow,
  47599. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  47600. tickDirection: 1,
  47601. labelDirection: 1
  47602. };
  47603. }, this);
  47604. },
  47605. /**
  47606. * Get axis by dim.
  47607. * @param {string} dim
  47608. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  47609. */
  47610. getAxis: function (dim) {
  47611. return this._axesMap.get(dim);
  47612. },
  47613. /**
  47614. * Convert a dim value of a single item of series data to Point.
  47615. * @param {*} value
  47616. * @param {string} dim
  47617. * @return {Array}
  47618. */
  47619. dataToPoint: function (value, dim) {
  47620. return this.axisCoordToPoint(
  47621. this._axesMap.get(dim).dataToCoord(value),
  47622. dim
  47623. );
  47624. },
  47625. /**
  47626. * Travel data for one time, get activeState of each data item.
  47627. * @param {module:echarts/data/List} data
  47628. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  47629. * {number} dataIndex
  47630. * @param {number} [start=0] the start dataIndex that travel from.
  47631. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  47632. */
  47633. eachActiveState: function (data, callback, start, end) {
  47634. start == null && (start = 0);
  47635. end == null && (end = data.count());
  47636. var axesMap = this._axesMap;
  47637. var dimensions = this.dimensions;
  47638. var dataDimensions = [];
  47639. var axisModels = [];
  47640. each$1(dimensions, function (axisDim) {
  47641. dataDimensions.push(data.mapDimension(axisDim));
  47642. axisModels.push(axesMap.get(axisDim).model);
  47643. });
  47644. var hasActiveSet = this.hasAxisBrushed();
  47645. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  47646. var activeState;
  47647. if (!hasActiveSet) {
  47648. activeState = 'normal';
  47649. }
  47650. else {
  47651. activeState = 'active';
  47652. var values = data.getValues(dataDimensions, dataIndex);
  47653. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  47654. var state = axisModels[j].getActiveState(values[j]);
  47655. if (state === 'inactive') {
  47656. activeState = 'inactive';
  47657. break;
  47658. }
  47659. }
  47660. }
  47661. callback(activeState, dataIndex);
  47662. }
  47663. },
  47664. /**
  47665. * Whether has any activeSet.
  47666. * @return {boolean}
  47667. */
  47668. hasAxisBrushed: function () {
  47669. var dimensions = this.dimensions;
  47670. var axesMap = this._axesMap;
  47671. var hasActiveSet = false;
  47672. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  47673. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  47674. hasActiveSet = true;
  47675. }
  47676. }
  47677. return hasActiveSet;
  47678. },
  47679. /**
  47680. * Convert coords of each axis to Point.
  47681. * Return point. For example: [10, 20]
  47682. * @param {Array.<number>} coords
  47683. * @param {string} dim
  47684. * @return {Array.<number>}
  47685. */
  47686. axisCoordToPoint: function (coord, dim) {
  47687. var axisLayout = this._axesLayout[dim];
  47688. return applyTransform$1([coord, 0], axisLayout.transform);
  47689. },
  47690. /**
  47691. * Get axis layout.
  47692. */
  47693. getAxisLayout: function (dim) {
  47694. return clone(this._axesLayout[dim]);
  47695. },
  47696. /**
  47697. * @param {Array.<number>} point
  47698. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  47699. */
  47700. getSlidedAxisExpandWindow: function (point) {
  47701. var layoutInfo = this._makeLayoutInfo();
  47702. var pixelDimIndex = layoutInfo.pixelDimIndex;
  47703. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  47704. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  47705. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  47706. // Out of the area of coordinate system.
  47707. if (!this.containPoint(point)) {
  47708. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  47709. }
  47710. // Conver the point from global to expand coordinates.
  47711. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  47712. // For dragging operation convenience, the window should not be
  47713. // slided when mouse is the center area of the window.
  47714. var delta;
  47715. var behavior = 'slide';
  47716. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  47717. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  47718. // But consider touch device, jump is necessary.
  47719. var useJump = triggerArea[0] != null;
  47720. if (axisCollapseWidth) {
  47721. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  47722. behavior = 'jump';
  47723. delta = pointCoord - winSize * triggerArea[2];
  47724. }
  47725. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  47726. behavior = 'jump';
  47727. delta = pointCoord - winSize * (1 - triggerArea[2]);
  47728. }
  47729. else {
  47730. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  47731. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  47732. && (delta = 0);
  47733. }
  47734. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  47735. delta
  47736. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  47737. // Avoid nonsense triger on mousemove.
  47738. : (behavior = 'none');
  47739. }
  47740. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  47741. else {
  47742. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  47743. var pos = extent[1] * pointCoord / winSize;
  47744. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  47745. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  47746. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  47747. }
  47748. return {
  47749. axisExpandWindow: axisExpandWindow,
  47750. behavior: behavior
  47751. };
  47752. }
  47753. };
  47754. function restrict(len, extent) {
  47755. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  47756. }
  47757. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  47758. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  47759. return {
  47760. position: step * axisIndex,
  47761. axisNameAvailableWidth: step,
  47762. axisLabelShow: true
  47763. };
  47764. }
  47765. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  47766. var layoutLength = layoutInfo.layoutLength;
  47767. var axisExpandWidth = layoutInfo.axisExpandWidth;
  47768. var axisCount = layoutInfo.axisCount;
  47769. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  47770. var winInnerIndices = layoutInfo.winInnerIndices;
  47771. var position;
  47772. var axisNameAvailableWidth = axisCollapseWidth;
  47773. var axisLabelShow = false;
  47774. var nameTruncateMaxWidth;
  47775. if (axisIndex < winInnerIndices[0]) {
  47776. position = axisIndex * axisCollapseWidth;
  47777. nameTruncateMaxWidth = axisCollapseWidth;
  47778. }
  47779. else if (axisIndex <= winInnerIndices[1]) {
  47780. position = layoutInfo.axisExpandWindow0Pos
  47781. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  47782. axisNameAvailableWidth = axisExpandWidth;
  47783. axisLabelShow = true;
  47784. }
  47785. else {
  47786. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  47787. nameTruncateMaxWidth = axisCollapseWidth;
  47788. }
  47789. return {
  47790. position: position,
  47791. axisNameAvailableWidth: axisNameAvailableWidth,
  47792. axisLabelShow: axisLabelShow,
  47793. nameTruncateMaxWidth: nameTruncateMaxWidth
  47794. };
  47795. }
  47796. /*
  47797. * Licensed to the Apache Software Foundation (ASF) under one
  47798. * or more contributor license agreements. See the NOTICE file
  47799. * distributed with this work for additional information
  47800. * regarding copyright ownership. The ASF licenses this file
  47801. * to you under the Apache License, Version 2.0 (the
  47802. * "License"); you may not use this file except in compliance
  47803. * with the License. You may obtain a copy of the License at
  47804. *
  47805. * http://www.apache.org/licenses/LICENSE-2.0
  47806. *
  47807. * Unless required by applicable law or agreed to in writing,
  47808. * software distributed under the License is distributed on an
  47809. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47810. * KIND, either express or implied. See the License for the
  47811. * specific language governing permissions and limitations
  47812. * under the License.
  47813. */
  47814. /**
  47815. * Parallel coordinate system creater.
  47816. */
  47817. function create$2(ecModel, api) {
  47818. var coordSysList = [];
  47819. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  47820. var coordSys = new Parallel(parallelModel, ecModel, api);
  47821. coordSys.name = 'parallel_' + idx;
  47822. coordSys.resize(parallelModel, api);
  47823. parallelModel.coordinateSystem = coordSys;
  47824. coordSys.model = parallelModel;
  47825. coordSysList.push(coordSys);
  47826. });
  47827. // Inject the coordinateSystems into seriesModel
  47828. ecModel.eachSeries(function (seriesModel) {
  47829. if (seriesModel.get('coordinateSystem') === 'parallel') {
  47830. var parallelModel = ecModel.queryComponents({
  47831. mainType: 'parallel',
  47832. index: seriesModel.get('parallelIndex'),
  47833. id: seriesModel.get('parallelId')
  47834. })[0];
  47835. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  47836. }
  47837. });
  47838. return coordSysList;
  47839. }
  47840. CoordinateSystemManager.register('parallel', {create: create$2});
  47841. /*
  47842. * Licensed to the Apache Software Foundation (ASF) under one
  47843. * or more contributor license agreements. See the NOTICE file
  47844. * distributed with this work for additional information
  47845. * regarding copyright ownership. The ASF licenses this file
  47846. * to you under the Apache License, Version 2.0 (the
  47847. * "License"); you may not use this file except in compliance
  47848. * with the License. You may obtain a copy of the License at
  47849. *
  47850. * http://www.apache.org/licenses/LICENSE-2.0
  47851. *
  47852. * Unless required by applicable law or agreed to in writing,
  47853. * software distributed under the License is distributed on an
  47854. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47855. * KIND, either express or implied. See the License for the
  47856. * specific language governing permissions and limitations
  47857. * under the License.
  47858. */
  47859. var AxisModel$2 = ComponentModel.extend({
  47860. type: 'baseParallelAxis',
  47861. /**
  47862. * @type {module:echarts/coord/parallel/Axis}
  47863. */
  47864. axis: null,
  47865. /**
  47866. * @type {Array.<Array.<number>}
  47867. * @readOnly
  47868. */
  47869. activeIntervals: [],
  47870. /**
  47871. * @return {Object}
  47872. */
  47873. getAreaSelectStyle: function () {
  47874. return makeStyleMapper(
  47875. [
  47876. ['fill', 'color'],
  47877. ['lineWidth', 'borderWidth'],
  47878. ['stroke', 'borderColor'],
  47879. ['width', 'width'],
  47880. ['opacity', 'opacity']
  47881. ]
  47882. )(this.getModel('areaSelectStyle'));
  47883. },
  47884. /**
  47885. * The code of this feature is put on AxisModel but not ParallelAxis,
  47886. * because axisModel can be alive after echarts updating but instance of
  47887. * ParallelAxis having been disposed. this._activeInterval should be kept
  47888. * when action dispatched (i.e. legend click).
  47889. *
  47890. * @param {Array.<Array<number>>} intervals interval.length === 0
  47891. * means set all active.
  47892. * @public
  47893. */
  47894. setActiveIntervals: function (intervals) {
  47895. var activeIntervals = this.activeIntervals = clone(intervals);
  47896. // Normalize
  47897. if (activeIntervals) {
  47898. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  47899. asc(activeIntervals[i]);
  47900. }
  47901. }
  47902. },
  47903. /**
  47904. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  47905. * value can not be input.
  47906. * @return {string} 'normal': no activeIntervals set,
  47907. * 'active',
  47908. * 'inactive'.
  47909. * @public
  47910. */
  47911. getActiveState: function (value) {
  47912. var activeIntervals = this.activeIntervals;
  47913. if (!activeIntervals.length) {
  47914. return 'normal';
  47915. }
  47916. if (value == null || isNaN(value)) {
  47917. return 'inactive';
  47918. }
  47919. // Simple optimization
  47920. if (activeIntervals.length === 1) {
  47921. var interval = activeIntervals[0];
  47922. if (interval[0] <= value && value <= interval[1]) {
  47923. return 'active';
  47924. }
  47925. }
  47926. else {
  47927. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  47928. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  47929. return 'active';
  47930. }
  47931. }
  47932. }
  47933. return 'inactive';
  47934. }
  47935. });
  47936. var defaultOption$1 = {
  47937. type: 'value',
  47938. /**
  47939. * @type {Array.<number>}
  47940. */
  47941. dim: null, // 0, 1, 2, ...
  47942. // parallelIndex: null,
  47943. areaSelectStyle: {
  47944. width: 20,
  47945. borderWidth: 1,
  47946. borderColor: 'rgba(160,197,232)',
  47947. color: 'rgba(160,197,232)',
  47948. opacity: 0.3
  47949. },
  47950. realtime: true, // Whether realtime update view when select.
  47951. z: 10
  47952. };
  47953. merge(AxisModel$2.prototype, axisModelCommonMixin);
  47954. function getAxisType$1(axisName, option) {
  47955. return option.type || (option.data ? 'category' : 'value');
  47956. }
  47957. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  47958. /*
  47959. * Licensed to the Apache Software Foundation (ASF) under one
  47960. * or more contributor license agreements. See the NOTICE file
  47961. * distributed with this work for additional information
  47962. * regarding copyright ownership. The ASF licenses this file
  47963. * to you under the Apache License, Version 2.0 (the
  47964. * "License"); you may not use this file except in compliance
  47965. * with the License. You may obtain a copy of the License at
  47966. *
  47967. * http://www.apache.org/licenses/LICENSE-2.0
  47968. *
  47969. * Unless required by applicable law or agreed to in writing,
  47970. * software distributed under the License is distributed on an
  47971. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47972. * KIND, either express or implied. See the License for the
  47973. * specific language governing permissions and limitations
  47974. * under the License.
  47975. */
  47976. ComponentModel.extend({
  47977. type: 'parallel',
  47978. dependencies: ['parallelAxis'],
  47979. /**
  47980. * @type {module:echarts/coord/parallel/Parallel}
  47981. */
  47982. coordinateSystem: null,
  47983. /**
  47984. * Each item like: 'dim0', 'dim1', 'dim2', ...
  47985. * @type {Array.<string>}
  47986. * @readOnly
  47987. */
  47988. dimensions: null,
  47989. /**
  47990. * Coresponding to dimensions.
  47991. * @type {Array.<number>}
  47992. * @readOnly
  47993. */
  47994. parallelAxisIndex: null,
  47995. layoutMode: 'box',
  47996. defaultOption: {
  47997. zlevel: 0,
  47998. z: 0,
  47999. left: 80,
  48000. top: 60,
  48001. right: 80,
  48002. bottom: 60,
  48003. // width: {totalWidth} - left - right,
  48004. // height: {totalHeight} - top - bottom,
  48005. layout: 'horizontal', // 'horizontal' or 'vertical'
  48006. // FIXME
  48007. // naming?
  48008. axisExpandable: false,
  48009. axisExpandCenter: null,
  48010. axisExpandCount: 0,
  48011. axisExpandWidth: 50, // FIXME '10%' ?
  48012. axisExpandRate: 17,
  48013. axisExpandDebounce: 50,
  48014. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  48015. // Do not doc to user until necessary.
  48016. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  48017. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  48018. parallelAxisDefault: null
  48019. },
  48020. /**
  48021. * @override
  48022. */
  48023. init: function () {
  48024. ComponentModel.prototype.init.apply(this, arguments);
  48025. this.mergeOption({});
  48026. },
  48027. /**
  48028. * @override
  48029. */
  48030. mergeOption: function (newOption) {
  48031. var thisOption = this.option;
  48032. newOption && merge(thisOption, newOption, true);
  48033. this._initDimensions();
  48034. },
  48035. /**
  48036. * Whether series or axis is in this coordinate system.
  48037. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  48038. * @param {module:echarts/model/Global} ecModel
  48039. */
  48040. contains: function (model, ecModel) {
  48041. var parallelIndex = model.get('parallelIndex');
  48042. return parallelIndex != null
  48043. && ecModel.getComponent('parallel', parallelIndex) === this;
  48044. },
  48045. setAxisExpand: function (opt) {
  48046. each$1(
  48047. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  48048. function (name) {
  48049. if (opt.hasOwnProperty(name)) {
  48050. this.option[name] = opt[name];
  48051. }
  48052. },
  48053. this
  48054. );
  48055. },
  48056. /**
  48057. * @private
  48058. */
  48059. _initDimensions: function () {
  48060. var dimensions = this.dimensions = [];
  48061. var parallelAxisIndex = this.parallelAxisIndex = [];
  48062. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  48063. // Can not use this.contains here, because
  48064. // initialization has not been completed yet.
  48065. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  48066. }, this);
  48067. each$1(axisModels, function (axisModel) {
  48068. dimensions.push('dim' + axisModel.get('dim'));
  48069. parallelAxisIndex.push(axisModel.componentIndex);
  48070. });
  48071. }
  48072. });
  48073. /*
  48074. * Licensed to the Apache Software Foundation (ASF) under one
  48075. * or more contributor license agreements. See the NOTICE file
  48076. * distributed with this work for additional information
  48077. * regarding copyright ownership. The ASF licenses this file
  48078. * to you under the Apache License, Version 2.0 (the
  48079. * "License"); you may not use this file except in compliance
  48080. * with the License. You may obtain a copy of the License at
  48081. *
  48082. * http://www.apache.org/licenses/LICENSE-2.0
  48083. *
  48084. * Unless required by applicable law or agreed to in writing,
  48085. * software distributed under the License is distributed on an
  48086. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48087. * KIND, either express or implied. See the License for the
  48088. * specific language governing permissions and limitations
  48089. * under the License.
  48090. */
  48091. /**
  48092. * @payload
  48093. * @property {string} parallelAxisId
  48094. * @property {Array.<Array.<number>>} intervals
  48095. */
  48096. var actionInfo$1 = {
  48097. type: 'axisAreaSelect',
  48098. event: 'axisAreaSelected'
  48099. // update: 'updateVisual'
  48100. };
  48101. registerAction(actionInfo$1, function (payload, ecModel) {
  48102. ecModel.eachComponent(
  48103. {mainType: 'parallelAxis', query: payload},
  48104. function (parallelAxisModel) {
  48105. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  48106. }
  48107. );
  48108. });
  48109. /**
  48110. * @payload
  48111. */
  48112. registerAction('parallelAxisExpand', function (payload, ecModel) {
  48113. ecModel.eachComponent(
  48114. {mainType: 'parallel', query: payload},
  48115. function (parallelModel) {
  48116. parallelModel.setAxisExpand(payload);
  48117. }
  48118. );
  48119. });
  48120. /*
  48121. * Licensed to the Apache Software Foundation (ASF) under one
  48122. * or more contributor license agreements. See the NOTICE file
  48123. * distributed with this work for additional information
  48124. * regarding copyright ownership. The ASF licenses this file
  48125. * to you under the Apache License, Version 2.0 (the
  48126. * "License"); you may not use this file except in compliance
  48127. * with the License. You may obtain a copy of the License at
  48128. *
  48129. * http://www.apache.org/licenses/LICENSE-2.0
  48130. *
  48131. * Unless required by applicable law or agreed to in writing,
  48132. * software distributed under the License is distributed on an
  48133. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48134. * KIND, either express or implied. See the License for the
  48135. * specific language governing permissions and limitations
  48136. * under the License.
  48137. */
  48138. var curry$2 = curry;
  48139. var each$12 = each$1;
  48140. var map$2 = map;
  48141. var mathMin$6 = Math.min;
  48142. var mathMax$6 = Math.max;
  48143. var mathPow$2 = Math.pow;
  48144. var COVER_Z = 10000;
  48145. var UNSELECT_THRESHOLD = 6;
  48146. var MIN_RESIZE_LINE_WIDTH = 6;
  48147. var MUTEX_RESOURCE_KEY = 'globalPan';
  48148. var DIRECTION_MAP = {
  48149. w: [0, 0],
  48150. e: [0, 1],
  48151. n: [1, 0],
  48152. s: [1, 1]
  48153. };
  48154. var CURSOR_MAP = {
  48155. w: 'ew',
  48156. e: 'ew',
  48157. n: 'ns',
  48158. s: 'ns',
  48159. ne: 'nesw',
  48160. sw: 'nesw',
  48161. nw: 'nwse',
  48162. se: 'nwse'
  48163. };
  48164. var DEFAULT_BRUSH_OPT = {
  48165. brushStyle: {
  48166. lineWidth: 2,
  48167. stroke: 'rgba(0,0,0,0.3)',
  48168. fill: 'rgba(0,0,0,0.1)'
  48169. },
  48170. transformable: true,
  48171. brushMode: 'single',
  48172. removeOnClick: false
  48173. };
  48174. var baseUID = 0;
  48175. /**
  48176. * @alias module:echarts/component/helper/BrushController
  48177. * @constructor
  48178. * @mixin {module:zrender/mixin/Eventful}
  48179. * @event module:echarts/component/helper/BrushController#brush
  48180. * params:
  48181. * areas: Array.<Array>, coord relates to container group,
  48182. * If no container specified, to global.
  48183. * opt {
  48184. * isEnd: boolean,
  48185. * removeOnClick: boolean
  48186. * }
  48187. *
  48188. * @param {module:zrender/zrender~ZRender} zr
  48189. */
  48190. function BrushController(zr) {
  48191. if (__DEV__) {
  48192. assert$1(zr);
  48193. }
  48194. Eventful.call(this);
  48195. /**
  48196. * @type {module:zrender/zrender~ZRender}
  48197. * @private
  48198. */
  48199. this._zr = zr;
  48200. /**
  48201. * @type {module:zrender/container/Group}
  48202. * @readOnly
  48203. */
  48204. this.group = new Group();
  48205. /**
  48206. * Only for drawing (after enabledBrush).
  48207. * 'line', 'rect', 'polygon' or false
  48208. * If passing false/null/undefined, disable brush.
  48209. * If passing 'auto', determined by panel.defaultBrushType
  48210. * @private
  48211. * @type {string}
  48212. */
  48213. this._brushType;
  48214. /**
  48215. * Only for drawing (after enabledBrush).
  48216. *
  48217. * @private
  48218. * @type {Object}
  48219. */
  48220. this._brushOption;
  48221. /**
  48222. * @private
  48223. * @type {Object}
  48224. */
  48225. this._panels;
  48226. /**
  48227. * @private
  48228. * @type {Array.<nubmer>}
  48229. */
  48230. this._track = [];
  48231. /**
  48232. * @private
  48233. * @type {boolean}
  48234. */
  48235. this._dragging;
  48236. /**
  48237. * @private
  48238. * @type {Array}
  48239. */
  48240. this._covers = [];
  48241. /**
  48242. * @private
  48243. * @type {moudule:zrender/container/Group}
  48244. */
  48245. this._creatingCover;
  48246. /**
  48247. * `true` means global panel
  48248. * @private
  48249. * @type {module:zrender/container/Group|boolean}
  48250. */
  48251. this._creatingPanel;
  48252. /**
  48253. * @private
  48254. * @type {boolean}
  48255. */
  48256. this._enableGlobalPan;
  48257. /**
  48258. * @private
  48259. * @type {boolean}
  48260. */
  48261. if (__DEV__) {
  48262. this._mounted;
  48263. }
  48264. /**
  48265. * @private
  48266. * @type {string}
  48267. */
  48268. this._uid = 'brushController_' + baseUID++;
  48269. /**
  48270. * @private
  48271. * @type {Object}
  48272. */
  48273. this._handlers = {};
  48274. each$12(mouseHandlers, function (handler, eventName) {
  48275. this._handlers[eventName] = bind(handler, this);
  48276. }, this);
  48277. }
  48278. BrushController.prototype = {
  48279. constructor: BrushController,
  48280. /**
  48281. * If set to null/undefined/false, select disabled.
  48282. * @param {Object} brushOption
  48283. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  48284. * If passing false/null/undefined, disable brush.
  48285. * If passing 'auto', determined by panel.defaultBrushType.
  48286. * ('auto' can not be used in global panel)
  48287. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  48288. * @param {boolean} [brushOption.transformable=true]
  48289. * @param {boolean} [brushOption.removeOnClick=false]
  48290. * @param {Object} [brushOption.brushStyle]
  48291. * @param {number} [brushOption.brushStyle.width]
  48292. * @param {number} [brushOption.brushStyle.lineWidth]
  48293. * @param {string} [brushOption.brushStyle.stroke]
  48294. * @param {string} [brushOption.brushStyle.fill]
  48295. * @param {number} [brushOption.z]
  48296. */
  48297. enableBrush: function (brushOption) {
  48298. if (__DEV__) {
  48299. assert$1(this._mounted);
  48300. }
  48301. this._brushType && doDisableBrush(this);
  48302. brushOption.brushType && doEnableBrush(this, brushOption);
  48303. return this;
  48304. },
  48305. /**
  48306. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  48307. * Each items: {
  48308. * panelId, // mandatory.
  48309. * clipPath, // mandatory. function.
  48310. * isTargetByCursor, // mandatory. function.
  48311. * defaultBrushType, // optional, only used when brushType is 'auto'.
  48312. * getLinearBrushOtherExtent, // optional. function.
  48313. * }
  48314. */
  48315. setPanels: function (panelOpts) {
  48316. if (panelOpts && panelOpts.length) {
  48317. var panels = this._panels = {};
  48318. each$1(panelOpts, function (panelOpts) {
  48319. panels[panelOpts.panelId] = clone(panelOpts);
  48320. });
  48321. }
  48322. else {
  48323. this._panels = null;
  48324. }
  48325. return this;
  48326. },
  48327. /**
  48328. * @param {Object} [opt]
  48329. * @return {boolean} [opt.enableGlobalPan=false]
  48330. */
  48331. mount: function (opt) {
  48332. opt = opt || {};
  48333. if (__DEV__) {
  48334. this._mounted = true; // should be at first.
  48335. }
  48336. this._enableGlobalPan = opt.enableGlobalPan;
  48337. var thisGroup = this.group;
  48338. this._zr.add(thisGroup);
  48339. thisGroup.attr({
  48340. position: opt.position || [0, 0],
  48341. rotation: opt.rotation || 0,
  48342. scale: opt.scale || [1, 1]
  48343. });
  48344. this._transform = thisGroup.getLocalTransform();
  48345. return this;
  48346. },
  48347. eachCover: function (cb, context) {
  48348. each$12(this._covers, cb, context);
  48349. },
  48350. /**
  48351. * Update covers.
  48352. * @param {Array.<Object>} brushOptionList Like:
  48353. * [
  48354. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  48355. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  48356. * ...
  48357. * ]
  48358. * `brushType` is required in each cover info. (can not be 'auto')
  48359. * `id` is not mandatory.
  48360. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  48361. * If brushOptionList is null/undefined, all covers removed.
  48362. */
  48363. updateCovers: function (brushOptionList) {
  48364. if (__DEV__) {
  48365. assert$1(this._mounted);
  48366. }
  48367. brushOptionList = map(brushOptionList, function (brushOption) {
  48368. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48369. });
  48370. var tmpIdPrefix = '\0-brush-index-';
  48371. var oldCovers = this._covers;
  48372. var newCovers = this._covers = [];
  48373. var controller = this;
  48374. var creatingCover = this._creatingCover;
  48375. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  48376. .add(addOrUpdate)
  48377. .update(addOrUpdate)
  48378. .remove(remove)
  48379. .execute();
  48380. return this;
  48381. function getKey(brushOption, index) {
  48382. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  48383. + '-' + brushOption.brushType;
  48384. }
  48385. function oldGetKey(cover, index) {
  48386. return getKey(cover.__brushOption, index);
  48387. }
  48388. function addOrUpdate(newIndex, oldIndex) {
  48389. var newBrushOption = brushOptionList[newIndex];
  48390. // Consider setOption in event listener of brushSelect,
  48391. // where updating cover when creating should be forbiden.
  48392. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  48393. newCovers[newIndex] = oldCovers[oldIndex];
  48394. }
  48395. else {
  48396. var cover = newCovers[newIndex] = oldIndex != null
  48397. ? (
  48398. oldCovers[oldIndex].__brushOption = newBrushOption,
  48399. oldCovers[oldIndex]
  48400. )
  48401. : endCreating(controller, createCover(controller, newBrushOption));
  48402. updateCoverAfterCreation(controller, cover);
  48403. }
  48404. }
  48405. function remove(oldIndex) {
  48406. if (oldCovers[oldIndex] !== creatingCover) {
  48407. controller.group.remove(oldCovers[oldIndex]);
  48408. }
  48409. }
  48410. },
  48411. unmount: function () {
  48412. if (__DEV__) {
  48413. if (!this._mounted) {
  48414. return;
  48415. }
  48416. }
  48417. this.enableBrush(false);
  48418. // container may 'removeAll' outside.
  48419. clearCovers(this);
  48420. this._zr.remove(this.group);
  48421. if (__DEV__) {
  48422. this._mounted = false; // should be at last.
  48423. }
  48424. return this;
  48425. },
  48426. dispose: function () {
  48427. this.unmount();
  48428. this.off();
  48429. }
  48430. };
  48431. mixin(BrushController, Eventful);
  48432. function doEnableBrush(controller, brushOption) {
  48433. var zr = controller._zr;
  48434. // Consider roam, which takes globalPan too.
  48435. if (!controller._enableGlobalPan) {
  48436. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  48437. }
  48438. each$12(controller._handlers, function (handler, eventName) {
  48439. zr.on(eventName, handler);
  48440. });
  48441. controller._brushType = brushOption.brushType;
  48442. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48443. }
  48444. function doDisableBrush(controller) {
  48445. var zr = controller._zr;
  48446. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  48447. each$12(controller._handlers, function (handler, eventName) {
  48448. zr.off(eventName, handler);
  48449. });
  48450. controller._brushType = controller._brushOption = null;
  48451. }
  48452. function createCover(controller, brushOption) {
  48453. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  48454. cover.__brushOption = brushOption;
  48455. updateZ$1(cover, brushOption);
  48456. controller.group.add(cover);
  48457. return cover;
  48458. }
  48459. function endCreating(controller, creatingCover) {
  48460. var coverRenderer = getCoverRenderer(creatingCover);
  48461. if (coverRenderer.endCreating) {
  48462. coverRenderer.endCreating(controller, creatingCover);
  48463. updateZ$1(creatingCover, creatingCover.__brushOption);
  48464. }
  48465. return creatingCover;
  48466. }
  48467. function updateCoverShape(controller, cover) {
  48468. var brushOption = cover.__brushOption;
  48469. getCoverRenderer(cover).updateCoverShape(
  48470. controller, cover, brushOption.range, brushOption
  48471. );
  48472. }
  48473. function updateZ$1(cover, brushOption) {
  48474. var z = brushOption.z;
  48475. z == null && (z = COVER_Z);
  48476. cover.traverse(function (el) {
  48477. el.z = z;
  48478. el.z2 = z; // Consider in given container.
  48479. });
  48480. }
  48481. function updateCoverAfterCreation(controller, cover) {
  48482. getCoverRenderer(cover).updateCommon(controller, cover);
  48483. updateCoverShape(controller, cover);
  48484. }
  48485. function getCoverRenderer(cover) {
  48486. return coverRenderers[cover.__brushOption.brushType];
  48487. }
  48488. // return target panel or `true` (means global panel)
  48489. function getPanelByPoint(controller, e, localCursorPoint) {
  48490. var panels = controller._panels;
  48491. if (!panels) {
  48492. return true; // Global panel
  48493. }
  48494. var panel;
  48495. var transform = controller._transform;
  48496. each$12(panels, function (pn) {
  48497. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  48498. });
  48499. return panel;
  48500. }
  48501. // Return a panel or true
  48502. function getPanelByCover(controller, cover) {
  48503. var panels = controller._panels;
  48504. if (!panels) {
  48505. return true; // Global panel
  48506. }
  48507. var panelId = cover.__brushOption.panelId;
  48508. // User may give cover without coord sys info,
  48509. // which is then treated as global panel.
  48510. return panelId != null ? panels[panelId] : true;
  48511. }
  48512. function clearCovers(controller) {
  48513. var covers = controller._covers;
  48514. var originalLength = covers.length;
  48515. each$12(covers, function (cover) {
  48516. controller.group.remove(cover);
  48517. }, controller);
  48518. covers.length = 0;
  48519. return !!originalLength;
  48520. }
  48521. function trigger(controller, opt) {
  48522. var areas = map$2(controller._covers, function (cover) {
  48523. var brushOption = cover.__brushOption;
  48524. var range = clone(brushOption.range);
  48525. return {
  48526. brushType: brushOption.brushType,
  48527. panelId: brushOption.panelId,
  48528. range: range
  48529. };
  48530. });
  48531. controller.trigger('brush', areas, {
  48532. isEnd: !!opt.isEnd,
  48533. removeOnClick: !!opt.removeOnClick
  48534. });
  48535. }
  48536. function shouldShowCover(controller) {
  48537. var track = controller._track;
  48538. if (!track.length) {
  48539. return false;
  48540. }
  48541. var p2 = track[track.length - 1];
  48542. var p1 = track[0];
  48543. var dx = p2[0] - p1[0];
  48544. var dy = p2[1] - p1[1];
  48545. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  48546. return dist > UNSELECT_THRESHOLD;
  48547. }
  48548. function getTrackEnds(track) {
  48549. var tail = track.length - 1;
  48550. tail < 0 && (tail = 0);
  48551. return [track[0], track[tail]];
  48552. }
  48553. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  48554. var cover = new Group();
  48555. cover.add(new Rect({
  48556. name: 'main',
  48557. style: makeStyle(brushOption),
  48558. silent: true,
  48559. draggable: true,
  48560. cursor: 'move',
  48561. drift: curry$2(doDrift, controller, cover, 'nswe'),
  48562. ondragend: curry$2(trigger, controller, {isEnd: true})
  48563. }));
  48564. each$12(
  48565. edgeNames,
  48566. function (name) {
  48567. cover.add(new Rect({
  48568. name: name,
  48569. style: {opacity: 0},
  48570. draggable: true,
  48571. silent: true,
  48572. invisible: true,
  48573. drift: curry$2(doDrift, controller, cover, name),
  48574. ondragend: curry$2(trigger, controller, {isEnd: true})
  48575. }));
  48576. }
  48577. );
  48578. return cover;
  48579. }
  48580. function updateBaseRect(controller, cover, localRange, brushOption) {
  48581. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  48582. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  48583. var x = localRange[0][0];
  48584. var y = localRange[1][0];
  48585. var xa = x - lineWidth / 2;
  48586. var ya = y - lineWidth / 2;
  48587. var x2 = localRange[0][1];
  48588. var y2 = localRange[1][1];
  48589. var x2a = x2 - handleSize + lineWidth / 2;
  48590. var y2a = y2 - handleSize + lineWidth / 2;
  48591. var width = x2 - x;
  48592. var height = y2 - y;
  48593. var widtha = width + lineWidth;
  48594. var heighta = height + lineWidth;
  48595. updateRectShape(controller, cover, 'main', x, y, width, height);
  48596. if (brushOption.transformable) {
  48597. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  48598. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  48599. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  48600. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  48601. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  48602. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  48603. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  48604. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  48605. }
  48606. }
  48607. function updateCommon(controller, cover) {
  48608. var brushOption = cover.__brushOption;
  48609. var transformable = brushOption.transformable;
  48610. var mainEl = cover.childAt(0);
  48611. mainEl.useStyle(makeStyle(brushOption));
  48612. mainEl.attr({
  48613. silent: !transformable,
  48614. cursor: transformable ? 'move' : 'default'
  48615. });
  48616. each$12(
  48617. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  48618. function (name) {
  48619. var el = cover.childOfName(name);
  48620. var globalDir = getGlobalDirection(controller, name);
  48621. el && el.attr({
  48622. silent: !transformable,
  48623. invisible: !transformable,
  48624. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  48625. });
  48626. }
  48627. );
  48628. }
  48629. function updateRectShape(controller, cover, name, x, y, w, h) {
  48630. var el = cover.childOfName(name);
  48631. el && el.setShape(pointsToRect(
  48632. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  48633. ));
  48634. }
  48635. function makeStyle(brushOption) {
  48636. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  48637. }
  48638. function formatRectRange(x, y, x2, y2) {
  48639. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  48640. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  48641. return [
  48642. [min[0], max[0]], // x range
  48643. [min[1], max[1]] // y range
  48644. ];
  48645. }
  48646. function getTransform$1(controller) {
  48647. return getTransform(controller.group);
  48648. }
  48649. function getGlobalDirection(controller, localDirection) {
  48650. if (localDirection.length > 1) {
  48651. localDirection = localDirection.split('');
  48652. var globalDir = [
  48653. getGlobalDirection(controller, localDirection[0]),
  48654. getGlobalDirection(controller, localDirection[1])
  48655. ];
  48656. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  48657. return globalDir.join('');
  48658. }
  48659. else {
  48660. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  48661. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  48662. var globalDir = transformDirection(
  48663. map$$1[localDirection], getTransform$1(controller)
  48664. );
  48665. return inverseMap[globalDir];
  48666. }
  48667. }
  48668. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  48669. var brushOption = cover.__brushOption;
  48670. var rectRange = toRectRange(brushOption.range);
  48671. var localDelta = toLocalDelta(controller, dx, dy);
  48672. each$12(name.split(''), function (namePart) {
  48673. var ind = DIRECTION_MAP[namePart];
  48674. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  48675. });
  48676. brushOption.range = fromRectRange(formatRectRange(
  48677. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  48678. ));
  48679. updateCoverAfterCreation(controller, cover);
  48680. trigger(controller, {isEnd: false});
  48681. }
  48682. function driftPolygon(controller, cover, dx, dy, e) {
  48683. var range = cover.__brushOption.range;
  48684. var localDelta = toLocalDelta(controller, dx, dy);
  48685. each$12(range, function (point) {
  48686. point[0] += localDelta[0];
  48687. point[1] += localDelta[1];
  48688. });
  48689. updateCoverAfterCreation(controller, cover);
  48690. trigger(controller, {isEnd: false});
  48691. }
  48692. function toLocalDelta(controller, dx, dy) {
  48693. var thisGroup = controller.group;
  48694. var localD = thisGroup.transformCoordToLocal(dx, dy);
  48695. var localZero = thisGroup.transformCoordToLocal(0, 0);
  48696. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  48697. }
  48698. function clipByPanel(controller, cover, data) {
  48699. var panel = getPanelByCover(controller, cover);
  48700. return (panel && panel !== true)
  48701. ? panel.clipPath(data, controller._transform)
  48702. : clone(data);
  48703. }
  48704. function pointsToRect(points) {
  48705. var xmin = mathMin$6(points[0][0], points[1][0]);
  48706. var ymin = mathMin$6(points[0][1], points[1][1]);
  48707. var xmax = mathMax$6(points[0][0], points[1][0]);
  48708. var ymax = mathMax$6(points[0][1], points[1][1]);
  48709. return {
  48710. x: xmin,
  48711. y: ymin,
  48712. width: xmax - xmin,
  48713. height: ymax - ymin
  48714. };
  48715. }
  48716. function resetCursor(controller, e, localCursorPoint) {
  48717. // Check active
  48718. if (!controller._brushType) {
  48719. return;
  48720. }
  48721. var zr = controller._zr;
  48722. var covers = controller._covers;
  48723. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  48724. // Check whether in covers.
  48725. if (!controller._dragging) {
  48726. for (var i = 0; i < covers.length; i++) {
  48727. var brushOption = covers[i].__brushOption;
  48728. if (currPanel
  48729. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  48730. && coverRenderers[brushOption.brushType].contain(
  48731. covers[i], localCursorPoint[0], localCursorPoint[1]
  48732. )
  48733. ) {
  48734. // Use cursor style set on cover.
  48735. return;
  48736. }
  48737. }
  48738. }
  48739. currPanel && zr.setCursorStyle('crosshair');
  48740. }
  48741. function preventDefault(e) {
  48742. var rawE = e.event;
  48743. rawE.preventDefault && rawE.preventDefault();
  48744. }
  48745. function mainShapeContain(cover, x, y) {
  48746. return cover.childOfName('main').contain(x, y);
  48747. }
  48748. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  48749. var creatingCover = controller._creatingCover;
  48750. var panel = controller._creatingPanel;
  48751. var thisBrushOption = controller._brushOption;
  48752. var eventParams;
  48753. controller._track.push(localCursorPoint.slice());
  48754. if (shouldShowCover(controller) || creatingCover) {
  48755. if (panel && !creatingCover) {
  48756. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  48757. var brushOption = clone(thisBrushOption);
  48758. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  48759. brushOption.panelId = panel === true ? null : panel.panelId;
  48760. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  48761. controller._covers.push(creatingCover);
  48762. }
  48763. if (creatingCover) {
  48764. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  48765. var coverBrushOption = creatingCover.__brushOption;
  48766. coverBrushOption.range = coverRenderer.getCreatingRange(
  48767. clipByPanel(controller, creatingCover, controller._track)
  48768. );
  48769. if (isEnd) {
  48770. endCreating(controller, creatingCover);
  48771. coverRenderer.updateCommon(controller, creatingCover);
  48772. }
  48773. updateCoverShape(controller, creatingCover);
  48774. eventParams = {isEnd: isEnd};
  48775. }
  48776. }
  48777. else if (
  48778. isEnd
  48779. && thisBrushOption.brushMode === 'single'
  48780. && thisBrushOption.removeOnClick
  48781. ) {
  48782. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  48783. // But a single click do not clear covers, because user may have casual
  48784. // clicks (for example, click on other component and do not expect covers
  48785. // disappear).
  48786. // Only some cover removed, trigger action, but not every click trigger action.
  48787. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  48788. eventParams = {isEnd: isEnd, removeOnClick: true};
  48789. }
  48790. }
  48791. return eventParams;
  48792. }
  48793. function determineBrushType(brushType, panel) {
  48794. if (brushType === 'auto') {
  48795. if (__DEV__) {
  48796. assert$1(
  48797. panel && panel.defaultBrushType,
  48798. 'MUST have defaultBrushType when brushType is "atuo"'
  48799. );
  48800. }
  48801. return panel.defaultBrushType;
  48802. }
  48803. return brushType;
  48804. }
  48805. var mouseHandlers = {
  48806. mousedown: function (e) {
  48807. if (this._dragging) {
  48808. // In case some browser do not support globalOut,
  48809. // and release mose out side the browser.
  48810. handleDragEnd.call(this, e);
  48811. }
  48812. else if (!e.target || !e.target.draggable) {
  48813. preventDefault(e);
  48814. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  48815. this._creatingCover = null;
  48816. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  48817. if (panel) {
  48818. this._dragging = true;
  48819. this._track = [localCursorPoint.slice()];
  48820. }
  48821. }
  48822. },
  48823. mousemove: function (e) {
  48824. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  48825. resetCursor(this, e, localCursorPoint);
  48826. if (this._dragging) {
  48827. preventDefault(e);
  48828. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  48829. eventParams && trigger(this, eventParams);
  48830. }
  48831. },
  48832. mouseup: handleDragEnd //,
  48833. // FIXME
  48834. // in tooltip, globalout should not be triggered.
  48835. // globalout: handleDragEnd
  48836. };
  48837. function handleDragEnd(e) {
  48838. if (this._dragging) {
  48839. preventDefault(e);
  48840. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  48841. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  48842. this._dragging = false;
  48843. this._track = [];
  48844. this._creatingCover = null;
  48845. // trigger event shoule be at final, after procedure will be nested.
  48846. eventParams && trigger(this, eventParams);
  48847. }
  48848. }
  48849. /**
  48850. * key: brushType
  48851. * @type {Object}
  48852. */
  48853. var coverRenderers = {
  48854. lineX: getLineRenderer(0),
  48855. lineY: getLineRenderer(1),
  48856. rect: {
  48857. createCover: function (controller, brushOption) {
  48858. return createBaseRectCover(
  48859. curry$2(
  48860. driftRect,
  48861. function (range) {
  48862. return range;
  48863. },
  48864. function (range) {
  48865. return range;
  48866. }
  48867. ),
  48868. controller,
  48869. brushOption,
  48870. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  48871. );
  48872. },
  48873. getCreatingRange: function (localTrack) {
  48874. var ends = getTrackEnds(localTrack);
  48875. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  48876. },
  48877. updateCoverShape: function (controller, cover, localRange, brushOption) {
  48878. updateBaseRect(controller, cover, localRange, brushOption);
  48879. },
  48880. updateCommon: updateCommon,
  48881. contain: mainShapeContain
  48882. },
  48883. polygon: {
  48884. createCover: function (controller, brushOption) {
  48885. var cover = new Group();
  48886. // Do not use graphic.Polygon because graphic.Polyline do not close the
  48887. // border of the shape when drawing, which is a better experience for user.
  48888. cover.add(new Polyline({
  48889. name: 'main',
  48890. style: makeStyle(brushOption),
  48891. silent: true
  48892. }));
  48893. return cover;
  48894. },
  48895. getCreatingRange: function (localTrack) {
  48896. return localTrack;
  48897. },
  48898. endCreating: function (controller, cover) {
  48899. cover.remove(cover.childAt(0));
  48900. // Use graphic.Polygon close the shape.
  48901. cover.add(new Polygon({
  48902. name: 'main',
  48903. draggable: true,
  48904. drift: curry$2(driftPolygon, controller, cover),
  48905. ondragend: curry$2(trigger, controller, {isEnd: true})
  48906. }));
  48907. },
  48908. updateCoverShape: function (controller, cover, localRange, brushOption) {
  48909. cover.childAt(0).setShape({
  48910. points: clipByPanel(controller, cover, localRange)
  48911. });
  48912. },
  48913. updateCommon: updateCommon,
  48914. contain: mainShapeContain
  48915. }
  48916. };
  48917. function getLineRenderer(xyIndex) {
  48918. return {
  48919. createCover: function (controller, brushOption) {
  48920. return createBaseRectCover(
  48921. curry$2(
  48922. driftRect,
  48923. function (range) {
  48924. var rectRange = [range, [0, 100]];
  48925. xyIndex && rectRange.reverse();
  48926. return rectRange;
  48927. },
  48928. function (rectRange) {
  48929. return rectRange[xyIndex];
  48930. }
  48931. ),
  48932. controller,
  48933. brushOption,
  48934. [['w', 'e'], ['n', 's']][xyIndex]
  48935. );
  48936. },
  48937. getCreatingRange: function (localTrack) {
  48938. var ends = getTrackEnds(localTrack);
  48939. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  48940. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  48941. return [min, max];
  48942. },
  48943. updateCoverShape: function (controller, cover, localRange, brushOption) {
  48944. var otherExtent;
  48945. // If brushWidth not specified, fit the panel.
  48946. var panel = getPanelByCover(controller, cover);
  48947. if (panel !== true && panel.getLinearBrushOtherExtent) {
  48948. otherExtent = panel.getLinearBrushOtherExtent(
  48949. xyIndex, controller._transform
  48950. );
  48951. }
  48952. else {
  48953. var zr = controller._zr;
  48954. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  48955. }
  48956. var rectRange = [localRange, otherExtent];
  48957. xyIndex && rectRange.reverse();
  48958. updateBaseRect(controller, cover, rectRange, brushOption);
  48959. },
  48960. updateCommon: updateCommon,
  48961. contain: mainShapeContain
  48962. };
  48963. }
  48964. /*
  48965. * Licensed to the Apache Software Foundation (ASF) under one
  48966. * or more contributor license agreements. See the NOTICE file
  48967. * distributed with this work for additional information
  48968. * regarding copyright ownership. The ASF licenses this file
  48969. * to you under the Apache License, Version 2.0 (the
  48970. * "License"); you may not use this file except in compliance
  48971. * with the License. You may obtain a copy of the License at
  48972. *
  48973. * http://www.apache.org/licenses/LICENSE-2.0
  48974. *
  48975. * Unless required by applicable law or agreed to in writing,
  48976. * software distributed under the License is distributed on an
  48977. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48978. * KIND, either express or implied. See the License for the
  48979. * specific language governing permissions and limitations
  48980. * under the License.
  48981. */
  48982. function makeRectPanelClipPath(rect) {
  48983. rect = normalizeRect(rect);
  48984. return function (localPoints, transform) {
  48985. return clipPointsByRect(localPoints, rect);
  48986. };
  48987. }
  48988. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  48989. rect = normalizeRect(rect);
  48990. return function (xyIndex) {
  48991. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  48992. var brushWidth = idx ? rect.width : rect.height;
  48993. var base = idx ? rect.x : rect.y;
  48994. return [base, base + (brushWidth || 0)];
  48995. };
  48996. }
  48997. function makeRectIsTargetByCursor(rect, api, targetModel) {
  48998. rect = normalizeRect(rect);
  48999. return function (e, localCursorPoint, transform) {
  49000. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  49001. && !onIrrelevantElement(e, api, targetModel);
  49002. };
  49003. }
  49004. // Consider width/height is negative.
  49005. function normalizeRect(rect) {
  49006. return BoundingRect.create(rect);
  49007. }
  49008. /*
  49009. * Licensed to the Apache Software Foundation (ASF) under one
  49010. * or more contributor license agreements. See the NOTICE file
  49011. * distributed with this work for additional information
  49012. * regarding copyright ownership. The ASF licenses this file
  49013. * to you under the Apache License, Version 2.0 (the
  49014. * "License"); you may not use this file except in compliance
  49015. * with the License. You may obtain a copy of the License at
  49016. *
  49017. * http://www.apache.org/licenses/LICENSE-2.0
  49018. *
  49019. * Unless required by applicable law or agreed to in writing,
  49020. * software distributed under the License is distributed on an
  49021. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49022. * KIND, either express or implied. See the License for the
  49023. * specific language governing permissions and limitations
  49024. * under the License.
  49025. */
  49026. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  49027. var AxisView$2 = extendComponentView({
  49028. type: 'parallelAxis',
  49029. /**
  49030. * @override
  49031. */
  49032. init: function (ecModel, api) {
  49033. AxisView$2.superApply(this, 'init', arguments);
  49034. /**
  49035. * @type {module:echarts/component/helper/BrushController}
  49036. */
  49037. (this._brushController = new BrushController(api.getZr()))
  49038. .on('brush', bind(this._onBrush, this));
  49039. },
  49040. /**
  49041. * @override
  49042. */
  49043. render: function (axisModel, ecModel, api, payload) {
  49044. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  49045. return;
  49046. }
  49047. this.axisModel = axisModel;
  49048. this.api = api;
  49049. this.group.removeAll();
  49050. var oldAxisGroup = this._axisGroup;
  49051. this._axisGroup = new Group();
  49052. this.group.add(this._axisGroup);
  49053. if (!axisModel.get('show')) {
  49054. return;
  49055. }
  49056. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  49057. var coordSys = coordSysModel.coordinateSystem;
  49058. var areaSelectStyle = axisModel.getAreaSelectStyle();
  49059. var areaWidth = areaSelectStyle.width;
  49060. var dim = axisModel.axis.dim;
  49061. var axisLayout = coordSys.getAxisLayout(dim);
  49062. var builderOpt = extend(
  49063. {strokeContainThreshold: areaWidth},
  49064. axisLayout
  49065. );
  49066. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  49067. each$1(elementList, axisBuilder.add, axisBuilder);
  49068. this._axisGroup.add(axisBuilder.getGroup());
  49069. this._refreshBrushController(
  49070. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  49071. );
  49072. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  49073. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  49074. },
  49075. // /**
  49076. // * @override
  49077. // */
  49078. // updateVisual: function (axisModel, ecModel, api, payload) {
  49079. // this._brushController && this._brushController
  49080. // .updateCovers(getCoverInfoList(axisModel));
  49081. // },
  49082. _refreshBrushController: function (
  49083. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  49084. ) {
  49085. // After filtering, axis may change, select area needs to be update.
  49086. var extent = axisModel.axis.getExtent();
  49087. var extentLen = extent[1] - extent[0];
  49088. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  49089. // width/height might be negative, which will be
  49090. // normalized in BoundingRect.
  49091. var rect = BoundingRect.create({
  49092. x: extent[0],
  49093. y: -areaWidth / 2,
  49094. width: extentLen,
  49095. height: areaWidth
  49096. });
  49097. rect.x -= extra;
  49098. rect.width += 2 * extra;
  49099. this._brushController
  49100. .mount({
  49101. enableGlobalPan: true,
  49102. rotation: builderOpt.rotation,
  49103. position: builderOpt.position
  49104. })
  49105. .setPanels([{
  49106. panelId: 'pl',
  49107. clipPath: makeRectPanelClipPath(rect),
  49108. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  49109. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  49110. }])
  49111. .enableBrush({
  49112. brushType: 'lineX',
  49113. brushStyle: areaSelectStyle,
  49114. removeOnClick: true
  49115. })
  49116. .updateCovers(getCoverInfoList(axisModel));
  49117. },
  49118. _onBrush: function (coverInfoList, opt) {
  49119. // Do not cache these object, because the mey be changed.
  49120. var axisModel = this.axisModel;
  49121. var axis = axisModel.axis;
  49122. var intervals = map(coverInfoList, function (coverInfo) {
  49123. return [
  49124. axis.coordToData(coverInfo.range[0], true),
  49125. axis.coordToData(coverInfo.range[1], true)
  49126. ];
  49127. });
  49128. // If realtime is true, action is not dispatched on drag end, because
  49129. // the drag end emits the same params with the last drag move event,
  49130. // and may have some delay when using touch pad.
  49131. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  49132. this.api.dispatchAction({
  49133. type: 'axisAreaSelect',
  49134. parallelAxisId: axisModel.id,
  49135. intervals: intervals
  49136. });
  49137. }
  49138. },
  49139. /**
  49140. * @override
  49141. */
  49142. dispose: function () {
  49143. this._brushController.dispose();
  49144. }
  49145. });
  49146. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  49147. return payload
  49148. && payload.type === 'axisAreaSelect'
  49149. && ecModel.findComponents(
  49150. {mainType: 'parallelAxis', query: payload}
  49151. )[0] === axisModel;
  49152. }
  49153. function getCoverInfoList(axisModel) {
  49154. var axis = axisModel.axis;
  49155. return map(axisModel.activeIntervals, function (interval) {
  49156. return {
  49157. brushType: 'lineX',
  49158. panelId: 'pl',
  49159. range: [
  49160. axis.dataToCoord(interval[0], true),
  49161. axis.dataToCoord(interval[1], true)
  49162. ]
  49163. };
  49164. });
  49165. }
  49166. function getCoordSysModel(axisModel, ecModel) {
  49167. return ecModel.getComponent(
  49168. 'parallel', axisModel.get('parallelIndex')
  49169. );
  49170. }
  49171. /*
  49172. * Licensed to the Apache Software Foundation (ASF) under one
  49173. * or more contributor license agreements. See the NOTICE file
  49174. * distributed with this work for additional information
  49175. * regarding copyright ownership. The ASF licenses this file
  49176. * to you under the Apache License, Version 2.0 (the
  49177. * "License"); you may not use this file except in compliance
  49178. * with the License. You may obtain a copy of the License at
  49179. *
  49180. * http://www.apache.org/licenses/LICENSE-2.0
  49181. *
  49182. * Unless required by applicable law or agreed to in writing,
  49183. * software distributed under the License is distributed on an
  49184. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49185. * KIND, either express or implied. See the License for the
  49186. * specific language governing permissions and limitations
  49187. * under the License.
  49188. */
  49189. /*
  49190. * Licensed to the Apache Software Foundation (ASF) under one
  49191. * or more contributor license agreements. See the NOTICE file
  49192. * distributed with this work for additional information
  49193. * regarding copyright ownership. The ASF licenses this file
  49194. * to you under the Apache License, Version 2.0 (the
  49195. * "License"); you may not use this file except in compliance
  49196. * with the License. You may obtain a copy of the License at
  49197. *
  49198. * http://www.apache.org/licenses/LICENSE-2.0
  49199. *
  49200. * Unless required by applicable law or agreed to in writing,
  49201. * software distributed under the License is distributed on an
  49202. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49203. * KIND, either express or implied. See the License for the
  49204. * specific language governing permissions and limitations
  49205. * under the License.
  49206. */
  49207. var CLICK_THRESHOLD = 5; // > 4
  49208. // Parallel view
  49209. extendComponentView({
  49210. type: 'parallel',
  49211. render: function (parallelModel, ecModel, api) {
  49212. this._model = parallelModel;
  49213. this._api = api;
  49214. if (!this._handlers) {
  49215. this._handlers = {};
  49216. each$1(handlers, function (handler, eventName) {
  49217. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  49218. }, this);
  49219. }
  49220. createOrUpdate(
  49221. this,
  49222. '_throttledDispatchExpand',
  49223. parallelModel.get('axisExpandRate'),
  49224. 'fixRate'
  49225. );
  49226. },
  49227. dispose: function (ecModel, api) {
  49228. each$1(this._handlers, function (handler, eventName) {
  49229. api.getZr().off(eventName, handler);
  49230. });
  49231. this._handlers = null;
  49232. },
  49233. /**
  49234. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  49235. */
  49236. _throttledDispatchExpand: function (opt) {
  49237. this._dispatchExpand(opt);
  49238. },
  49239. _dispatchExpand: function (opt) {
  49240. opt && this._api.dispatchAction(
  49241. extend({type: 'parallelAxisExpand'}, opt)
  49242. );
  49243. }
  49244. });
  49245. var handlers = {
  49246. mousedown: function (e) {
  49247. if (checkTrigger(this, 'click')) {
  49248. this._mouseDownPoint = [e.offsetX, e.offsetY];
  49249. }
  49250. },
  49251. mouseup: function (e) {
  49252. var mouseDownPoint = this._mouseDownPoint;
  49253. if (checkTrigger(this, 'click') && mouseDownPoint) {
  49254. var point = [e.offsetX, e.offsetY];
  49255. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  49256. + Math.pow(mouseDownPoint[1] - point[1], 2);
  49257. if (dist > CLICK_THRESHOLD) {
  49258. return;
  49259. }
  49260. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  49261. [e.offsetX, e.offsetY]
  49262. );
  49263. result.behavior !== 'none' && this._dispatchExpand({
  49264. axisExpandWindow: result.axisExpandWindow
  49265. });
  49266. }
  49267. this._mouseDownPoint = null;
  49268. },
  49269. mousemove: function (e) {
  49270. // Should do nothing when brushing.
  49271. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  49272. return;
  49273. }
  49274. var model = this._model;
  49275. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  49276. [e.offsetX, e.offsetY]
  49277. );
  49278. var behavior = result.behavior;
  49279. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  49280. this._throttledDispatchExpand(
  49281. behavior === 'none'
  49282. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  49283. : {
  49284. axisExpandWindow: result.axisExpandWindow,
  49285. // Jumping uses animation, and sliding suppresses animation.
  49286. animation: behavior === 'jump' ? null : false
  49287. }
  49288. );
  49289. }
  49290. };
  49291. function checkTrigger(view, triggerOn) {
  49292. var model = view._model;
  49293. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  49294. }
  49295. registerPreprocessor(parallelPreprocessor);
  49296. /*
  49297. * Licensed to the Apache Software Foundation (ASF) under one
  49298. * or more contributor license agreements. See the NOTICE file
  49299. * distributed with this work for additional information
  49300. * regarding copyright ownership. The ASF licenses this file
  49301. * to you under the Apache License, Version 2.0 (the
  49302. * "License"); you may not use this file except in compliance
  49303. * with the License. You may obtain a copy of the License at
  49304. *
  49305. * http://www.apache.org/licenses/LICENSE-2.0
  49306. *
  49307. * Unless required by applicable law or agreed to in writing,
  49308. * software distributed under the License is distributed on an
  49309. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49310. * KIND, either express or implied. See the License for the
  49311. * specific language governing permissions and limitations
  49312. * under the License.
  49313. */
  49314. SeriesModel.extend({
  49315. type: 'series.parallel',
  49316. dependencies: ['parallel'],
  49317. visualColorAccessPath: 'lineStyle.color',
  49318. getInitialData: function (option, ecModel) {
  49319. var source = this.getSource();
  49320. setEncodeAndDimensions(source, this);
  49321. return createListFromArray(source, this);
  49322. },
  49323. /**
  49324. * User can get data raw indices on 'axisAreaSelected' event received.
  49325. *
  49326. * @public
  49327. * @param {string} activeState 'active' or 'inactive' or 'normal'
  49328. * @return {Array.<number>} Raw indices
  49329. */
  49330. getRawIndicesByActiveState: function (activeState) {
  49331. var coordSys = this.coordinateSystem;
  49332. var data = this.getData();
  49333. var indices = [];
  49334. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  49335. if (activeState === theActiveState) {
  49336. indices.push(data.getRawIndex(dataIndex));
  49337. }
  49338. });
  49339. return indices;
  49340. },
  49341. defaultOption: {
  49342. zlevel: 0, // 一级层叠
  49343. z: 2, // 二级层叠
  49344. coordinateSystem: 'parallel',
  49345. parallelIndex: 0,
  49346. label: {
  49347. show: false
  49348. },
  49349. inactiveOpacity: 0.05,
  49350. activeOpacity: 1,
  49351. lineStyle: {
  49352. width: 1,
  49353. opacity: 0.45,
  49354. type: 'solid'
  49355. },
  49356. emphasis: {
  49357. label: {
  49358. show: false
  49359. }
  49360. },
  49361. progressive: 500,
  49362. smooth: false, // true | false | number
  49363. animationEasing: 'linear'
  49364. }
  49365. });
  49366. function setEncodeAndDimensions(source, seriesModel) {
  49367. // The mapping of parallelAxis dimension to data dimension can
  49368. // be specified in parallelAxis.option.dim. For example, if
  49369. // parallelAxis.option.dim is 'dim3', it mapping to the third
  49370. // dimension of data. But `data.encode` has higher priority.
  49371. // Moreover, parallelModel.dimension should not be regarded as data
  49372. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  49373. if (source.encodeDefine) {
  49374. return;
  49375. }
  49376. var parallelModel = seriesModel.ecModel.getComponent(
  49377. 'parallel', seriesModel.get('parallelIndex')
  49378. );
  49379. if (!parallelModel) {
  49380. return;
  49381. }
  49382. var encodeDefine = source.encodeDefine = createHashMap();
  49383. each$1(parallelModel.dimensions, function (axisDim) {
  49384. var dataDimIndex = convertDimNameToNumber(axisDim);
  49385. encodeDefine.set(axisDim, dataDimIndex);
  49386. });
  49387. }
  49388. function convertDimNameToNumber(dimName) {
  49389. return +dimName.replace('dim', '');
  49390. }
  49391. /*
  49392. * Licensed to the Apache Software Foundation (ASF) under one
  49393. * or more contributor license agreements. See the NOTICE file
  49394. * distributed with this work for additional information
  49395. * regarding copyright ownership. The ASF licenses this file
  49396. * to you under the Apache License, Version 2.0 (the
  49397. * "License"); you may not use this file except in compliance
  49398. * with the License. You may obtain a copy of the License at
  49399. *
  49400. * http://www.apache.org/licenses/LICENSE-2.0
  49401. *
  49402. * Unless required by applicable law or agreed to in writing,
  49403. * software distributed under the License is distributed on an
  49404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49405. * KIND, either express or implied. See the License for the
  49406. * specific language governing permissions and limitations
  49407. * under the License.
  49408. */
  49409. var DEFAULT_SMOOTH = 0.3;
  49410. var ParallelView = Chart.extend({
  49411. type: 'parallel',
  49412. init: function () {
  49413. /**
  49414. * @type {module:zrender/container/Group}
  49415. * @private
  49416. */
  49417. this._dataGroup = new Group();
  49418. this.group.add(this._dataGroup);
  49419. /**
  49420. * @type {module:echarts/data/List}
  49421. */
  49422. this._data;
  49423. /**
  49424. * @type {boolean}
  49425. */
  49426. this._initialized;
  49427. },
  49428. /**
  49429. * @override
  49430. */
  49431. render: function (seriesModel, ecModel, api, payload) {
  49432. var dataGroup = this._dataGroup;
  49433. var data = seriesModel.getData();
  49434. var oldData = this._data;
  49435. var coordSys = seriesModel.coordinateSystem;
  49436. var dimensions = coordSys.dimensions;
  49437. var seriesScope = makeSeriesScope$2(seriesModel);
  49438. data.diff(oldData)
  49439. .add(add)
  49440. .update(update)
  49441. .remove(remove)
  49442. .execute();
  49443. function add(newDataIndex) {
  49444. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  49445. updateElCommon(line, data, newDataIndex, seriesScope);
  49446. }
  49447. function update(newDataIndex, oldDataIndex) {
  49448. var line = oldData.getItemGraphicEl(oldDataIndex);
  49449. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  49450. data.setItemGraphicEl(newDataIndex, line);
  49451. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  49452. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  49453. updateElCommon(line, data, newDataIndex, seriesScope);
  49454. }
  49455. function remove(oldDataIndex) {
  49456. var line = oldData.getItemGraphicEl(oldDataIndex);
  49457. dataGroup.remove(line);
  49458. }
  49459. // First create
  49460. if (!this._initialized) {
  49461. this._initialized = true;
  49462. var clipPath = createGridClipShape$1(
  49463. coordSys, seriesModel, function () {
  49464. // Callback will be invoked immediately if there is no animation
  49465. setTimeout(function () {
  49466. dataGroup.removeClipPath();
  49467. });
  49468. }
  49469. );
  49470. dataGroup.setClipPath(clipPath);
  49471. }
  49472. this._data = data;
  49473. },
  49474. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  49475. this._initialized = true;
  49476. this._data = null;
  49477. this._dataGroup.removeAll();
  49478. },
  49479. incrementalRender: function (taskParams, seriesModel, ecModel) {
  49480. var data = seriesModel.getData();
  49481. var coordSys = seriesModel.coordinateSystem;
  49482. var dimensions = coordSys.dimensions;
  49483. var seriesScope = makeSeriesScope$2(seriesModel);
  49484. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  49485. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  49486. line.incremental = true;
  49487. updateElCommon(line, data, dataIndex, seriesScope);
  49488. }
  49489. },
  49490. dispose: function () {},
  49491. // _renderForProgressive: function (seriesModel) {
  49492. // var dataGroup = this._dataGroup;
  49493. // var data = seriesModel.getData();
  49494. // var oldData = this._data;
  49495. // var coordSys = seriesModel.coordinateSystem;
  49496. // var dimensions = coordSys.dimensions;
  49497. // var option = seriesModel.option;
  49498. // var progressive = option.progressive;
  49499. // var smooth = option.smooth ? SMOOTH : null;
  49500. // // In progressive animation is disabled, so use simple data diff,
  49501. // // which effects performance less.
  49502. // // (Typically performance for data with length 7000+ like:
  49503. // // simpleDiff: 60ms, addEl: 184ms,
  49504. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  49505. // if (simpleDiff(oldData, data, dimensions)) {
  49506. // dataGroup.removeAll();
  49507. // data.each(function (dataIndex) {
  49508. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  49509. // });
  49510. // }
  49511. // updateElCommon(data, progressive, smooth);
  49512. // // Consider switch between progressive and not.
  49513. // data.__plProgressive = true;
  49514. // this._data = data;
  49515. // },
  49516. /**
  49517. * @override
  49518. */
  49519. remove: function () {
  49520. this._dataGroup && this._dataGroup.removeAll();
  49521. this._data = null;
  49522. }
  49523. });
  49524. function createGridClipShape$1(coordSys, seriesModel, cb) {
  49525. var parallelModel = coordSys.model;
  49526. var rect = coordSys.getRect();
  49527. var rectEl = new Rect({
  49528. shape: {
  49529. x: rect.x,
  49530. y: rect.y,
  49531. width: rect.width,
  49532. height: rect.height
  49533. }
  49534. });
  49535. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  49536. rectEl.setShape(dim, 0);
  49537. initProps(rectEl, {
  49538. shape: {
  49539. width: rect.width,
  49540. height: rect.height
  49541. }
  49542. }, seriesModel, cb);
  49543. return rectEl;
  49544. }
  49545. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  49546. var points = [];
  49547. for (var i = 0; i < dimensions.length; i++) {
  49548. var dimName = dimensions[i];
  49549. var value = data.get(data.mapDimension(dimName), dataIndex);
  49550. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  49551. points.push(coordSys.dataToPoint(value, dimName));
  49552. }
  49553. }
  49554. return points;
  49555. }
  49556. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  49557. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  49558. var line = new Polyline({
  49559. shape: {points: points},
  49560. silent: true,
  49561. z2: 10
  49562. });
  49563. dataGroup.add(line);
  49564. data.setItemGraphicEl(dataIndex, line);
  49565. return line;
  49566. }
  49567. function makeSeriesScope$2(seriesModel) {
  49568. var smooth = seriesModel.get('smooth', true);
  49569. smooth === true && (smooth = DEFAULT_SMOOTH);
  49570. return {
  49571. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  49572. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  49573. };
  49574. }
  49575. function updateElCommon(el, data, dataIndex, seriesScope) {
  49576. var lineStyle = seriesScope.lineStyle;
  49577. if (data.hasItemOption) {
  49578. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  49579. lineStyle = lineStyleModel.getLineStyle();
  49580. }
  49581. el.useStyle(lineStyle);
  49582. var elStyle = el.style;
  49583. elStyle.fill = null;
  49584. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  49585. elStyle.stroke = data.getItemVisual(dataIndex, 'color');
  49586. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  49587. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  49588. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  49589. }
  49590. // function simpleDiff(oldData, newData, dimensions) {
  49591. // var oldLen;
  49592. // if (!oldData
  49593. // || !oldData.__plProgressive
  49594. // || (oldLen = oldData.count()) !== newData.count()
  49595. // ) {
  49596. // return true;
  49597. // }
  49598. // var dimLen = dimensions.length;
  49599. // for (var i = 0; i < oldLen; i++) {
  49600. // for (var j = 0; j < dimLen; j++) {
  49601. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  49602. // return true;
  49603. // }
  49604. // }
  49605. // }
  49606. // return false;
  49607. // }
  49608. // FIXME
  49609. // 公用方法?
  49610. function isEmptyValue(val, axisType) {
  49611. return axisType === 'category'
  49612. ? val == null
  49613. : (val == null || isNaN(val)); // axisType === 'value'
  49614. }
  49615. /*
  49616. * Licensed to the Apache Software Foundation (ASF) under one
  49617. * or more contributor license agreements. See the NOTICE file
  49618. * distributed with this work for additional information
  49619. * regarding copyright ownership. The ASF licenses this file
  49620. * to you under the Apache License, Version 2.0 (the
  49621. * "License"); you may not use this file except in compliance
  49622. * with the License. You may obtain a copy of the License at
  49623. *
  49624. * http://www.apache.org/licenses/LICENSE-2.0
  49625. *
  49626. * Unless required by applicable law or agreed to in writing,
  49627. * software distributed under the License is distributed on an
  49628. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49629. * KIND, either express or implied. See the License for the
  49630. * specific language governing permissions and limitations
  49631. * under the License.
  49632. */
  49633. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  49634. var parallelVisual = {
  49635. seriesType: 'parallel',
  49636. reset: function (seriesModel, ecModel, api) {
  49637. var itemStyleModel = seriesModel.getModel('itemStyle');
  49638. var lineStyleModel = seriesModel.getModel('lineStyle');
  49639. var globalColors = ecModel.get('color');
  49640. var color = lineStyleModel.get('color')
  49641. || itemStyleModel.get('color')
  49642. || globalColors[seriesModel.seriesIndex % globalColors.length];
  49643. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  49644. var activeOpacity = seriesModel.get('activeOpacity');
  49645. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  49646. var coordSys = seriesModel.coordinateSystem;
  49647. var data = seriesModel.getData();
  49648. var opacityMap = {
  49649. normal: lineStyle.opacity,
  49650. active: activeOpacity,
  49651. inactive: inactiveOpacity
  49652. };
  49653. data.setVisual('color', color);
  49654. function progress(params, data) {
  49655. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  49656. var opacity = opacityMap[activeState];
  49657. if (activeState === 'normal' && data.hasItemOption) {
  49658. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  49659. itemOpacity != null && (opacity = itemOpacity);
  49660. }
  49661. data.setItemVisual(dataIndex, 'opacity', opacity);
  49662. }, params.start, params.end);
  49663. }
  49664. return {progress: progress};
  49665. }
  49666. };
  49667. /*
  49668. * Licensed to the Apache Software Foundation (ASF) under one
  49669. * or more contributor license agreements. See the NOTICE file
  49670. * distributed with this work for additional information
  49671. * regarding copyright ownership. The ASF licenses this file
  49672. * to you under the Apache License, Version 2.0 (the
  49673. * "License"); you may not use this file except in compliance
  49674. * with the License. You may obtain a copy of the License at
  49675. *
  49676. * http://www.apache.org/licenses/LICENSE-2.0
  49677. *
  49678. * Unless required by applicable law or agreed to in writing,
  49679. * software distributed under the License is distributed on an
  49680. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49681. * KIND, either express or implied. See the License for the
  49682. * specific language governing permissions and limitations
  49683. * under the License.
  49684. */
  49685. registerVisual(parallelVisual);
  49686. /*
  49687. * Licensed to the Apache Software Foundation (ASF) under one
  49688. * or more contributor license agreements. See the NOTICE file
  49689. * distributed with this work for additional information
  49690. * regarding copyright ownership. The ASF licenses this file
  49691. * to you under the Apache License, Version 2.0 (the
  49692. * "License"); you may not use this file except in compliance
  49693. * with the License. You may obtain a copy of the License at
  49694. *
  49695. * http://www.apache.org/licenses/LICENSE-2.0
  49696. *
  49697. * Unless required by applicable law or agreed to in writing,
  49698. * software distributed under the License is distributed on an
  49699. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49700. * KIND, either express or implied. See the License for the
  49701. * specific language governing permissions and limitations
  49702. * under the License.
  49703. */
  49704. /**
  49705. * @file Get initial data and define sankey view's series model
  49706. * @author Deqing Li(annong035@gmail.com)
  49707. */
  49708. var SankeySeries = SeriesModel.extend({
  49709. type: 'series.sankey',
  49710. layoutInfo: null,
  49711. /**
  49712. * Init a graph data structure from data in option series
  49713. *
  49714. * @param {Object} option the object used to config echarts view
  49715. * @return {module:echarts/data/List} storage initial data
  49716. */
  49717. getInitialData: function (option) {
  49718. var links = option.edges || option.links;
  49719. var nodes = option.data || option.nodes;
  49720. if (nodes && links) {
  49721. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  49722. return graph.data;
  49723. }
  49724. },
  49725. setNodePosition: function (dataIndex, localPosition) {
  49726. var dataItem = this.option.data[dataIndex];
  49727. dataItem.localX = localPosition[0];
  49728. dataItem.localY = localPosition[1];
  49729. },
  49730. /**
  49731. * Return the graphic data structure
  49732. *
  49733. * @return {module:echarts/data/Graph} graphic data structure
  49734. */
  49735. getGraph: function () {
  49736. return this.getData().graph;
  49737. },
  49738. /**
  49739. * Get edge data of graphic data structure
  49740. *
  49741. * @return {module:echarts/data/List} data structure of list
  49742. */
  49743. getEdgeData: function () {
  49744. return this.getGraph().edgeData;
  49745. },
  49746. /**
  49747. * @override
  49748. */
  49749. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  49750. // dataType === 'node' or empty do not show tooltip by default
  49751. if (dataType === 'edge') {
  49752. var params = this.getDataParams(dataIndex, dataType);
  49753. var rawDataOpt = params.data;
  49754. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  49755. if (params.value) {
  49756. html += ' : ' + params.value;
  49757. }
  49758. return encodeHTML(html);
  49759. }
  49760. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  49761. },
  49762. defaultOption: {
  49763. zlevel: 0,
  49764. z: 2,
  49765. coordinateSystem: 'view',
  49766. layout: null,
  49767. // the position of the whole view
  49768. left: '5%',
  49769. top: '5%',
  49770. right: '20%',
  49771. bottom: '5%',
  49772. // the dx of the node
  49773. nodeWidth: 20,
  49774. // the vertical distance between two nodes
  49775. nodeGap: 8,
  49776. // control if the node can move or not
  49777. draggable: true,
  49778. // the number of iterations to change the position of the node
  49779. layoutIterations: 32,
  49780. label: {
  49781. show: true,
  49782. position: 'right',
  49783. color: '#000',
  49784. fontSize: 12
  49785. },
  49786. itemStyle: {
  49787. borderWidth: 1,
  49788. borderColor: '#333'
  49789. },
  49790. lineStyle: {
  49791. color: '#314656',
  49792. opacity: 0.2,
  49793. curveness: 0.5
  49794. },
  49795. emphasis: {
  49796. label: {
  49797. show: true
  49798. },
  49799. lineStyle: {
  49800. opacity: 0.6
  49801. }
  49802. },
  49803. animationEasing: 'linear',
  49804. animationDuration: 1000
  49805. }
  49806. });
  49807. /*
  49808. * Licensed to the Apache Software Foundation (ASF) under one
  49809. * or more contributor license agreements. See the NOTICE file
  49810. * distributed with this work for additional information
  49811. * regarding copyright ownership. The ASF licenses this file
  49812. * to you under the Apache License, Version 2.0 (the
  49813. * "License"); you may not use this file except in compliance
  49814. * with the License. You may obtain a copy of the License at
  49815. *
  49816. * http://www.apache.org/licenses/LICENSE-2.0
  49817. *
  49818. * Unless required by applicable law or agreed to in writing,
  49819. * software distributed under the License is distributed on an
  49820. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49821. * KIND, either express or implied. See the License for the
  49822. * specific language governing permissions and limitations
  49823. * under the License.
  49824. */
  49825. /**
  49826. * @file The file used to draw sankey view
  49827. * @author Deqing Li(annong035@gmail.com)
  49828. */
  49829. var SankeyShape = extendShape({
  49830. shape: {
  49831. x1: 0, y1: 0,
  49832. x2: 0, y2: 0,
  49833. cpx1: 0, cpy1: 0,
  49834. cpx2: 0, cpy2: 0,
  49835. extent: 0
  49836. },
  49837. buildPath: function (ctx, shape) {
  49838. var halfExtent = shape.extent / 2;
  49839. ctx.moveTo(shape.x1, shape.y1 - halfExtent);
  49840. ctx.bezierCurveTo(
  49841. shape.cpx1, shape.cpy1 - halfExtent,
  49842. shape.cpx2, shape.cpy2 - halfExtent,
  49843. shape.x2, shape.y2 - halfExtent
  49844. );
  49845. ctx.lineTo(shape.x2, shape.y2 + halfExtent);
  49846. ctx.bezierCurveTo(
  49847. shape.cpx2, shape.cpy2 + halfExtent,
  49848. shape.cpx1, shape.cpy1 + halfExtent,
  49849. shape.x1, shape.y1 + halfExtent
  49850. );
  49851. ctx.closePath();
  49852. }
  49853. });
  49854. extendChartView({
  49855. type: 'sankey',
  49856. /**
  49857. * @private
  49858. * @type {module:echarts/chart/sankey/SankeySeries}
  49859. */
  49860. _model: null,
  49861. render: function (seriesModel, ecModel, api) {
  49862. var graph = seriesModel.getGraph();
  49863. var group = this.group;
  49864. var layoutInfo = seriesModel.layoutInfo;
  49865. // view width
  49866. var width = layoutInfo.width;
  49867. // view height
  49868. var height = layoutInfo.height;
  49869. var nodeData = seriesModel.getData();
  49870. var edgeData = seriesModel.getData('edge');
  49871. this._model = seriesModel;
  49872. group.removeAll();
  49873. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  49874. // generate a bezire Curve for each edge
  49875. graph.eachEdge(function (edge) {
  49876. var curve = new SankeyShape();
  49877. curve.dataIndex = edge.dataIndex;
  49878. curve.seriesIndex = seriesModel.seriesIndex;
  49879. curve.dataType = 'edge';
  49880. var lineStyleModel = edge.getModel('lineStyle');
  49881. var curvature = lineStyleModel.get('curveness');
  49882. var n1Layout = edge.node1.getLayout();
  49883. var node1Model =edge.node1.getModel();
  49884. var dragX1 = node1Model.get('localX');
  49885. var dragY1 = node1Model.get('localY');
  49886. var n2Layout = edge.node2.getLayout();
  49887. var node2Model = edge.node2.getModel();
  49888. var dragX2 = node2Model.get('localX');
  49889. var dragY2 = node2Model.get('localY');
  49890. var edgeLayout = edge.getLayout();
  49891. curve.shape.extent = Math.max(1, edgeLayout.dy);
  49892. var x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  49893. var y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy + edgeLayout.dy / 2;
  49894. var x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  49895. var y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty + edgeLayout.dy / 2;
  49896. var cpx1 = x1 * (1 - curvature) + x2 * curvature;
  49897. var cpy1 = y1;
  49898. var cpx2 = x1 * curvature + x2 * (1 - curvature);
  49899. var cpy2 = y2;
  49900. curve.setShape({
  49901. x1: x1,
  49902. y1: y1,
  49903. x2: x2,
  49904. y2: y2,
  49905. cpx1: cpx1,
  49906. cpy1: cpy1,
  49907. cpx2: cpx2,
  49908. cpy2: cpy2
  49909. });
  49910. curve.setStyle(lineStyleModel.getItemStyle());
  49911. // Special color, use source node color or target node color
  49912. switch (curve.style.fill) {
  49913. case 'source':
  49914. curve.style.fill = edge.node1.getVisual('color');
  49915. break;
  49916. case 'target':
  49917. curve.style.fill = edge.node2.getVisual('color');
  49918. break;
  49919. }
  49920. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  49921. group.add(curve);
  49922. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  49923. });
  49924. // generate a rect for each node
  49925. graph.eachNode(function (node) {
  49926. var layout = node.getLayout();
  49927. var itemModel = node.getModel();
  49928. var dragX = itemModel.get('localX');
  49929. var dragY = itemModel.get('localY');
  49930. var labelModel = itemModel.getModel('label');
  49931. var labelHoverModel = itemModel.getModel('emphasis.label');
  49932. var rect = new Rect({
  49933. shape: {
  49934. x: dragX != null ? dragX * width : layout.x,
  49935. y: dragY != null ? dragY * height : layout.y,
  49936. width: layout.dx,
  49937. height: layout.dy
  49938. },
  49939. style: itemModel.getModel('itemStyle').getItemStyle()
  49940. });
  49941. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  49942. setLabelStyle(
  49943. rect.style, hoverStyle, labelModel, labelHoverModel,
  49944. {
  49945. labelFetcher: seriesModel,
  49946. labelDataIndex: node.dataIndex,
  49947. defaultText: node.id,
  49948. isRectText: true
  49949. }
  49950. );
  49951. rect.setStyle('fill', node.getVisual('color'));
  49952. setHoverStyle(rect, hoverStyle);
  49953. group.add(rect);
  49954. nodeData.setItemGraphicEl(node.dataIndex, rect);
  49955. rect.dataType = 'node';
  49956. });
  49957. var draggable = seriesModel.get('draggable');
  49958. if (draggable) {
  49959. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  49960. el.drift = function (dx, dy) {
  49961. this.shape.x += dx;
  49962. this.shape.y += dy;
  49963. this.dirty();
  49964. api.dispatchAction({
  49965. type: 'dragNode',
  49966. seriesId: seriesModel.id,
  49967. dataIndex: nodeData.getRawIndex(dataIndex),
  49968. localX: this.shape.x / width,
  49969. localY: this.shape.y / height
  49970. });
  49971. };
  49972. el.draggable = true;
  49973. el.cursor = 'move';
  49974. });
  49975. }
  49976. if (!this._data && seriesModel.get('animation')) {
  49977. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  49978. group.removeClipPath();
  49979. }));
  49980. }
  49981. this._data = seriesModel.getData();
  49982. },
  49983. dispose: function () {}
  49984. });
  49985. // add animation to the view
  49986. function createGridClipShape$2(rect, seriesModel, cb) {
  49987. var rectEl = new Rect({
  49988. shape: {
  49989. x: rect.x - 10,
  49990. y: rect.y - 10,
  49991. width: 0,
  49992. height: rect.height + 20
  49993. }
  49994. });
  49995. initProps(rectEl, {
  49996. shape: {
  49997. width: rect.width + 20,
  49998. height: rect.height + 20
  49999. }
  50000. }, seriesModel, cb);
  50001. return rectEl;
  50002. }
  50003. /*
  50004. * Licensed to the Apache Software Foundation (ASF) under one
  50005. * or more contributor license agreements. See the NOTICE file
  50006. * distributed with this work for additional information
  50007. * regarding copyright ownership. The ASF licenses this file
  50008. * to you under the Apache License, Version 2.0 (the
  50009. * "License"); you may not use this file except in compliance
  50010. * with the License. You may obtain a copy of the License at
  50011. *
  50012. * http://www.apache.org/licenses/LICENSE-2.0
  50013. *
  50014. * Unless required by applicable law or agreed to in writing,
  50015. * software distributed under the License is distributed on an
  50016. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50017. * KIND, either express or implied. See the License for the
  50018. * specific language governing permissions and limitations
  50019. * under the License.
  50020. */
  50021. registerAction({
  50022. type: 'dragNode',
  50023. event: 'dragNode',
  50024. // here can only use 'update' now, other value is not support in echarts.
  50025. update: 'update'
  50026. }, function (payload, ecModel) {
  50027. ecModel.eachComponent({mainType: 'series', subType: 'sankey', query: payload}, function (seriesModel) {
  50028. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  50029. });
  50030. });
  50031. /*
  50032. * Licensed to the Apache Software Foundation (ASF) under one
  50033. * or more contributor license agreements. See the NOTICE file
  50034. * distributed with this work for additional information
  50035. * regarding copyright ownership. The ASF licenses this file
  50036. * to you under the Apache License, Version 2.0 (the
  50037. * "License"); you may not use this file except in compliance
  50038. * with the License. You may obtain a copy of the License at
  50039. *
  50040. * http://www.apache.org/licenses/LICENSE-2.0
  50041. *
  50042. * Unless required by applicable law or agreed to in writing,
  50043. * software distributed under the License is distributed on an
  50044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50045. * KIND, either express or implied. See the License for the
  50046. * specific language governing permissions and limitations
  50047. * under the License.
  50048. */
  50049. /*
  50050. * The implementation references to d3.js. The use of the source
  50051. * code of this file is also subject to the terms and consitions
  50052. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  50053. */
  50054. /**
  50055. * nest helper used to group by the array.
  50056. * can specified the keys and sort the keys.
  50057. */
  50058. function nest() {
  50059. var keysFunction = [];
  50060. var sortKeysFunction = [];
  50061. /**
  50062. * map an Array into the mapObject.
  50063. * @param {Array} array
  50064. * @param {number} depth
  50065. */
  50066. function map$$1(array, depth) {
  50067. if (depth >= keysFunction.length) {
  50068. return array;
  50069. }
  50070. var i = -1;
  50071. var n = array.length;
  50072. var keyFunction = keysFunction[depth++];
  50073. var mapObject = {};
  50074. var valuesByKey = {};
  50075. while (++i < n) {
  50076. var keyValue = keyFunction(array[i]);
  50077. var values = valuesByKey[keyValue];
  50078. if (values) {
  50079. values.push(array[i]);
  50080. }
  50081. else {
  50082. valuesByKey[keyValue] = [array[i]];
  50083. }
  50084. }
  50085. each$1(valuesByKey, function (value, key) {
  50086. mapObject[key] = map$$1(value, depth);
  50087. });
  50088. return mapObject;
  50089. }
  50090. /**
  50091. * transform the Map Object to multidimensional Array
  50092. * @param {Object} map
  50093. * @param {number} depth
  50094. */
  50095. function entriesMap(mapObject, depth) {
  50096. if (depth >= keysFunction.length) {
  50097. return mapObject;
  50098. }
  50099. var array = [];
  50100. var sortKeyFunction = sortKeysFunction[depth++];
  50101. each$1(mapObject, function (value, key) {
  50102. array.push({
  50103. key: key, values: entriesMap(value, depth)
  50104. });
  50105. });
  50106. if (sortKeyFunction) {
  50107. return array.sort(function (a, b) {
  50108. return sortKeyFunction(a.key, b.key);
  50109. });
  50110. }
  50111. else {
  50112. return array;
  50113. }
  50114. }
  50115. return {
  50116. /**
  50117. * specified the key to groupby the arrays.
  50118. * users can specified one more keys.
  50119. * @param {Function} d
  50120. */
  50121. key: function (d) {
  50122. keysFunction.push(d);
  50123. return this;
  50124. },
  50125. /**
  50126. * specified the comparator to sort the keys
  50127. * @param {Function} order
  50128. */
  50129. sortKeys: function (order) {
  50130. sortKeysFunction[keysFunction.length - 1] = order;
  50131. return this;
  50132. },
  50133. /**
  50134. * the array to be grouped by.
  50135. * @param {Array} array
  50136. */
  50137. entries: function (array) {
  50138. return entriesMap(map$$1(array, 0), 0);
  50139. }
  50140. };
  50141. }
  50142. /*
  50143. * Licensed to the Apache Software Foundation (ASF) under one
  50144. * or more contributor license agreements. See the NOTICE file
  50145. * distributed with this work for additional information
  50146. * regarding copyright ownership. The ASF licenses this file
  50147. * to you under the Apache License, Version 2.0 (the
  50148. * "License"); you may not use this file except in compliance
  50149. * with the License. You may obtain a copy of the License at
  50150. *
  50151. * http://www.apache.org/licenses/LICENSE-2.0
  50152. *
  50153. * Unless required by applicable law or agreed to in writing,
  50154. * software distributed under the License is distributed on an
  50155. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50156. * KIND, either express or implied. See the License for the
  50157. * specific language governing permissions and limitations
  50158. * under the License.
  50159. */
  50160. /**
  50161. * @file The layout algorithm of sankey view
  50162. * @author Deqing Li(annong035@gmail.com)
  50163. */
  50164. var sankeyLayout = function (ecModel, api, payload) {
  50165. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  50166. var nodeWidth = seriesModel.get('nodeWidth');
  50167. var nodeGap = seriesModel.get('nodeGap');
  50168. var layoutInfo = getViewRect$3(seriesModel, api);
  50169. seriesModel.layoutInfo = layoutInfo;
  50170. var width = layoutInfo.width;
  50171. var height = layoutInfo.height;
  50172. var graph = seriesModel.getGraph();
  50173. var nodes = graph.nodes;
  50174. var edges = graph.edges;
  50175. computeNodeValues(nodes);
  50176. var filteredNodes = filter(nodes, function (node) {
  50177. return node.getLayout().value === 0;
  50178. });
  50179. var iterations = filteredNodes.length !== 0
  50180. ? 0 : seriesModel.get('layoutIterations');
  50181. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations);
  50182. });
  50183. };
  50184. /**
  50185. * Get the layout position of the whole view
  50186. *
  50187. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  50188. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  50189. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  50190. */
  50191. function getViewRect$3(seriesModel, api) {
  50192. return getLayoutRect(
  50193. seriesModel.getBoxLayoutParams(), {
  50194. width: api.getWidth(),
  50195. height: api.getHeight()
  50196. }
  50197. );
  50198. }
  50199. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations) {
  50200. computeNodeBreadths(nodes, edges, nodeWidth, width);
  50201. computeNodeDepths(nodes, edges, height, nodeGap, iterations);
  50202. computeEdgeDepths(nodes);
  50203. }
  50204. /**
  50205. * Compute the value of each node by summing the associated edge's value
  50206. *
  50207. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50208. */
  50209. function computeNodeValues(nodes) {
  50210. each$1(nodes, function (node) {
  50211. var value1 = sum(node.outEdges, getEdgeValue);
  50212. var value2 = sum(node.inEdges, getEdgeValue);
  50213. var value = Math.max(value1, value2);
  50214. node.setLayout({value: value}, true);
  50215. });
  50216. }
  50217. /**
  50218. * Compute the x-position for each node.
  50219. *
  50220. * Here we use Kahn algorithm to detect cycle when we traverse
  50221. * the node to computer the initial x position.
  50222. *
  50223. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50224. * @param {number} nodeWidth the dx of the node
  50225. * @param {number} width the whole width of the area to draw the view
  50226. */
  50227. function computeNodeBreadths(nodes, edges, nodeWidth, width) {
  50228. // Used to mark whether the edge is deleted. if it is deleted,
  50229. // the value is 0, otherwise it is 1.
  50230. var remainEdges = [];
  50231. // Storage each node's indegree.
  50232. var indegreeArr = [];
  50233. //Used to storage the node with indegree is equal to 0.
  50234. var zeroIndegrees = [];
  50235. var nextNode = [];
  50236. var x = 0;
  50237. var kx = 0;
  50238. for (var i = 0; i < edges.length; i++) {
  50239. remainEdges[i] = 1;
  50240. }
  50241. for (var i = 0; i < nodes.length; i++) {
  50242. indegreeArr[i] = nodes[i].inEdges.length;
  50243. if (indegreeArr[i] === 0) {
  50244. zeroIndegrees.push(nodes[i]);
  50245. }
  50246. }
  50247. while (zeroIndegrees.length) {
  50248. each$1(zeroIndegrees, function (node) {
  50249. node.setLayout({x: x}, true);
  50250. node.setLayout({dx: nodeWidth}, true);
  50251. each$1(node.outEdges, function (edge) {
  50252. var indexEdge = edges.indexOf(edge);
  50253. remainEdges[indexEdge] = 0;
  50254. var targetNode = edge.node2;
  50255. var nodeIndex = nodes.indexOf(targetNode);
  50256. if (--indegreeArr[nodeIndex] === 0) {
  50257. nextNode.push(targetNode);
  50258. }
  50259. });
  50260. });
  50261. ++x;
  50262. zeroIndegrees = nextNode;
  50263. nextNode = [];
  50264. }
  50265. for (var i = 0; i < remainEdges.length; i++) {
  50266. if (__DEV__) {
  50267. if (remainEdges[i] === 1) {
  50268. throw new Error('Sankey is a DAG, the original data has cycle!');
  50269. }
  50270. }
  50271. }
  50272. moveSinksRight(nodes, x);
  50273. kx = (width - nodeWidth) / (x - 1);
  50274. scaleNodeBreadths(nodes, kx);
  50275. }
  50276. /**
  50277. * All the node without outEgdes are assigned maximum x-position and
  50278. * be aligned in the last column.
  50279. *
  50280. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50281. * @param {number} x value (x-1) use to assign to node without outEdges
  50282. * as x-position
  50283. */
  50284. function moveSinksRight(nodes, x) {
  50285. each$1(nodes, function (node) {
  50286. if (!node.outEdges.length) {
  50287. node.setLayout({x: x - 1}, true);
  50288. }
  50289. });
  50290. }
  50291. /**
  50292. * Scale node x-position to the width
  50293. *
  50294. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50295. * @param {number} kx multiple used to scale nodes
  50296. */
  50297. function scaleNodeBreadths(nodes, kx) {
  50298. each$1(nodes, function (node) {
  50299. var nodeX = node.getLayout().x * kx;
  50300. node.setLayout({x: nodeX}, true);
  50301. });
  50302. }
  50303. /**
  50304. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  50305. *
  50306. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50307. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  50308. * @param {number} height the whole height of the area to draw the view
  50309. * @param {number} nodeGap the vertical distance between two nodes
  50310. * in the same column.
  50311. * @param {number} iterations the number of iterations for the algorithm
  50312. */
  50313. function computeNodeDepths(nodes, edges, height, nodeGap, iterations) {
  50314. var nodesByBreadth = nest()
  50315. .key(function (d) {
  50316. return d.getLayout().x;
  50317. })
  50318. .sortKeys(ascending)
  50319. .entries(nodes)
  50320. .map(function (d) {
  50321. return d.values;
  50322. });
  50323. initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap);
  50324. resolveCollisions(nodesByBreadth, nodeGap, height);
  50325. for (var alpha = 1; iterations > 0; iterations--) {
  50326. // 0.99 is a experience parameter, ensure that each iterations of
  50327. // changes as small as possible.
  50328. alpha *= 0.99;
  50329. relaxRightToLeft(nodesByBreadth, alpha);
  50330. resolveCollisions(nodesByBreadth, nodeGap, height);
  50331. relaxLeftToRight(nodesByBreadth, alpha);
  50332. resolveCollisions(nodesByBreadth, nodeGap, height);
  50333. }
  50334. }
  50335. /**
  50336. * Compute the original y-position for each node
  50337. *
  50338. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50339. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50340. * group by the array of all sankey nodes based on the nodes x-position.
  50341. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  50342. * @param {number} height the whole height of the area to draw the view
  50343. * @param {number} nodeGap the vertical distance between two nodes
  50344. */
  50345. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap) {
  50346. var kyArray = [];
  50347. each$1(nodesByBreadth, function (nodes) {
  50348. var n = nodes.length;
  50349. var sum = 0;
  50350. each$1(nodes, function (node) {
  50351. sum += node.getLayout().value;
  50352. });
  50353. var ky = (height - (n - 1) * nodeGap) / sum;
  50354. kyArray.push(ky);
  50355. });
  50356. kyArray.sort(function (a, b) {
  50357. return a - b;
  50358. });
  50359. var ky0 = kyArray[0];
  50360. each$1(nodesByBreadth, function (nodes) {
  50361. each$1(nodes, function (node, i) {
  50362. node.setLayout({y: i}, true);
  50363. var nodeDy = node.getLayout().value * ky0;
  50364. node.setLayout({dy: nodeDy}, true);
  50365. });
  50366. });
  50367. each$1(edges, function (edge) {
  50368. var edgeDy = +edge.getValue() * ky0;
  50369. edge.setLayout({dy: edgeDy}, true);
  50370. });
  50371. }
  50372. /**
  50373. * Resolve the collision of initialized depth (y-position)
  50374. *
  50375. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50376. * group by the array of all sankey nodes based on the nodes x-position.
  50377. * @param {number} nodeGap the vertical distance between two nodes
  50378. * @param {number} height the whole height of the area to draw the view
  50379. */
  50380. function resolveCollisions(nodesByBreadth, nodeGap, height) {
  50381. each$1(nodesByBreadth, function (nodes) {
  50382. var node;
  50383. var dy;
  50384. var y0 = 0;
  50385. var n = nodes.length;
  50386. var i;
  50387. nodes.sort(ascendingDepth);
  50388. for (i = 0; i < n; i++) {
  50389. node = nodes[i];
  50390. dy = y0 - node.getLayout().y;
  50391. if (dy > 0) {
  50392. var nodeY = node.getLayout().y + dy;
  50393. node.setLayout({y: nodeY}, true);
  50394. }
  50395. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  50396. }
  50397. // If the bottommost node goes outside the bounds, push it back up
  50398. dy = y0 - nodeGap - height;
  50399. if (dy > 0) {
  50400. var nodeY = node.getLayout().y - dy;
  50401. node.setLayout({y: nodeY}, true);
  50402. y0 = node.getLayout().y;
  50403. for (i = n - 2; i >= 0; --i) {
  50404. node = nodes[i];
  50405. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  50406. if (dy > 0) {
  50407. nodeY = node.getLayout().y - dy;
  50408. node.setLayout({y: nodeY}, true);
  50409. }
  50410. y0 = node.getLayout().y;
  50411. }
  50412. }
  50413. });
  50414. }
  50415. /**
  50416. * Change the y-position of the nodes, except most the right side nodes
  50417. *
  50418. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50419. * group by the array of all sankey nodes based on the node x-position.
  50420. * @param {number} alpha parameter used to adjust the nodes y-position
  50421. */
  50422. function relaxRightToLeft(nodesByBreadth, alpha) {
  50423. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  50424. each$1(nodes, function (node) {
  50425. if (node.outEdges.length) {
  50426. var y = sum(node.outEdges, weightedTarget) / sum(node.outEdges, getEdgeValue);
  50427. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  50428. node.setLayout({y: nodeY}, true);
  50429. }
  50430. });
  50431. });
  50432. }
  50433. function weightedTarget(edge) {
  50434. return center$1(edge.node2) * edge.getValue();
  50435. }
  50436. /**
  50437. * Change the y-position of the nodes, except most the left side nodes
  50438. *
  50439. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50440. * group by the array of all sankey nodes based on the node x-position.
  50441. * @param {number} alpha parameter used to adjust the nodes y-position
  50442. */
  50443. function relaxLeftToRight(nodesByBreadth, alpha) {
  50444. each$1(nodesByBreadth, function (nodes) {
  50445. each$1(nodes, function (node) {
  50446. if (node.inEdges.length) {
  50447. var y = sum(node.inEdges, weightedSource) / sum(node.inEdges, getEdgeValue);
  50448. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  50449. node.setLayout({y: nodeY}, true);
  50450. }
  50451. });
  50452. });
  50453. }
  50454. function weightedSource(edge) {
  50455. return center$1(edge.node1) * edge.getValue();
  50456. }
  50457. /**
  50458. * Compute the depth(y-position) of each edge
  50459. *
  50460. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50461. */
  50462. function computeEdgeDepths(nodes) {
  50463. each$1(nodes, function (node) {
  50464. node.outEdges.sort(ascendingTargetDepth);
  50465. node.inEdges.sort(ascendingSourceDepth);
  50466. });
  50467. each$1(nodes, function (node) {
  50468. var sy = 0;
  50469. var ty = 0;
  50470. each$1(node.outEdges, function (edge) {
  50471. edge.setLayout({sy: sy}, true);
  50472. sy += edge.getLayout().dy;
  50473. });
  50474. each$1(node.inEdges, function (edge) {
  50475. edge.setLayout({ty: ty}, true);
  50476. ty += edge.getLayout().dy;
  50477. });
  50478. });
  50479. }
  50480. function ascendingTargetDepth(a, b) {
  50481. return a.node2.getLayout().y - b.node2.getLayout().y;
  50482. }
  50483. function ascendingSourceDepth(a, b) {
  50484. return a.node1.getLayout().y - b.node1.getLayout().y;
  50485. }
  50486. function sum(array, f) {
  50487. var sum = 0;
  50488. var len = array.length;
  50489. var i = -1;
  50490. while (++i < len) {
  50491. var value = +f.call(array, array[i], i);
  50492. if (!isNaN(value)) {
  50493. sum += value;
  50494. }
  50495. }
  50496. return sum;
  50497. }
  50498. function center$1(node) {
  50499. return node.getLayout().y + node.getLayout().dy / 2;
  50500. }
  50501. function ascendingDepth(a, b) {
  50502. return a.getLayout().y - b.getLayout().y;
  50503. }
  50504. function ascending(a, b) {
  50505. return a - b;
  50506. }
  50507. function getEdgeValue(edge) {
  50508. return edge.getValue();
  50509. }
  50510. /*
  50511. * Licensed to the Apache Software Foundation (ASF) under one
  50512. * or more contributor license agreements. See the NOTICE file
  50513. * distributed with this work for additional information
  50514. * regarding copyright ownership. The ASF licenses this file
  50515. * to you under the Apache License, Version 2.0 (the
  50516. * "License"); you may not use this file except in compliance
  50517. * with the License. You may obtain a copy of the License at
  50518. *
  50519. * http://www.apache.org/licenses/LICENSE-2.0
  50520. *
  50521. * Unless required by applicable law or agreed to in writing,
  50522. * software distributed under the License is distributed on an
  50523. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50524. * KIND, either express or implied. See the License for the
  50525. * specific language governing permissions and limitations
  50526. * under the License.
  50527. */
  50528. /**
  50529. * @file Visual encoding for sankey view
  50530. * @author Deqing Li(annong035@gmail.com)
  50531. */
  50532. var sankeyVisual = function (ecModel, payload) {
  50533. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  50534. var graph = seriesModel.getGraph();
  50535. var nodes = graph.nodes;
  50536. if (nodes.length) {
  50537. var minValue = Infinity;
  50538. var maxValue = -Infinity;
  50539. each$1(nodes, function (node) {
  50540. var nodeValue = node.getLayout().value;
  50541. if (nodeValue < minValue) {
  50542. minValue = nodeValue;
  50543. }
  50544. if (nodeValue > maxValue) {
  50545. maxValue = nodeValue;
  50546. }
  50547. });
  50548. each$1(nodes, function (node) {
  50549. var mapping = new VisualMapping({
  50550. type: 'color',
  50551. mappingMethod: 'linear',
  50552. dataExtent: [minValue, maxValue],
  50553. visual: seriesModel.get('color')
  50554. });
  50555. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  50556. node.setVisual('color', mapValueToColor);
  50557. // If set itemStyle.normal.color
  50558. var itemModel = node.getModel();
  50559. var customColor = itemModel.get('itemStyle.color');
  50560. if (customColor != null) {
  50561. node.setVisual('color', customColor);
  50562. }
  50563. });
  50564. }
  50565. });
  50566. };
  50567. /*
  50568. * Licensed to the Apache Software Foundation (ASF) under one
  50569. * or more contributor license agreements. See the NOTICE file
  50570. * distributed with this work for additional information
  50571. * regarding copyright ownership. The ASF licenses this file
  50572. * to you under the Apache License, Version 2.0 (the
  50573. * "License"); you may not use this file except in compliance
  50574. * with the License. You may obtain a copy of the License at
  50575. *
  50576. * http://www.apache.org/licenses/LICENSE-2.0
  50577. *
  50578. * Unless required by applicable law or agreed to in writing,
  50579. * software distributed under the License is distributed on an
  50580. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50581. * KIND, either express or implied. See the License for the
  50582. * specific language governing permissions and limitations
  50583. * under the License.
  50584. */
  50585. registerLayout(sankeyLayout);
  50586. registerVisual(sankeyVisual);
  50587. /*
  50588. * Licensed to the Apache Software Foundation (ASF) under one
  50589. * or more contributor license agreements. See the NOTICE file
  50590. * distributed with this work for additional information
  50591. * regarding copyright ownership. The ASF licenses this file
  50592. * to you under the Apache License, Version 2.0 (the
  50593. * "License"); you may not use this file except in compliance
  50594. * with the License. You may obtain a copy of the License at
  50595. *
  50596. * http://www.apache.org/licenses/LICENSE-2.0
  50597. *
  50598. * Unless required by applicable law or agreed to in writing,
  50599. * software distributed under the License is distributed on an
  50600. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50601. * KIND, either express or implied. See the License for the
  50602. * specific language governing permissions and limitations
  50603. * under the License.
  50604. */
  50605. var seriesModelMixin = {
  50606. /**
  50607. * @private
  50608. * @type {string}
  50609. */
  50610. _baseAxisDim: null,
  50611. /**
  50612. * @override
  50613. */
  50614. getInitialData: function (option, ecModel) {
  50615. // When both types of xAxis and yAxis are 'value', layout is
  50616. // needed to be specified by user. Otherwise, layout can be
  50617. // judged by which axis is category.
  50618. var ordinalMeta;
  50619. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  50620. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  50621. var xAxisType = xAxisModel.get('type');
  50622. var yAxisType = yAxisModel.get('type');
  50623. var addOrdinal;
  50624. // FIXME
  50625. // 考虑时间轴
  50626. if (xAxisType === 'category') {
  50627. option.layout = 'horizontal';
  50628. ordinalMeta = xAxisModel.getOrdinalMeta();
  50629. addOrdinal = true;
  50630. }
  50631. else if (yAxisType === 'category') {
  50632. option.layout = 'vertical';
  50633. ordinalMeta = yAxisModel.getOrdinalMeta();
  50634. addOrdinal = true;
  50635. }
  50636. else {
  50637. option.layout = option.layout || 'horizontal';
  50638. }
  50639. var coordDims = ['x', 'y'];
  50640. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  50641. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  50642. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  50643. var axisModels = [xAxisModel, yAxisModel];
  50644. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  50645. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  50646. var data = option.data;
  50647. // ??? FIXME make a stage to perform data transfrom.
  50648. // MUST create a new data, consider setOption({}) again.
  50649. if (data && addOrdinal) {
  50650. var newOptionData = [];
  50651. each$1(data, function (item, index) {
  50652. var newItem;
  50653. if (item.value && isArray(item.value)) {
  50654. newItem = item.value.slice();
  50655. item.value.unshift(index);
  50656. }
  50657. else if (isArray(item)) {
  50658. newItem = item.slice();
  50659. item.unshift(index);
  50660. }
  50661. else {
  50662. newItem = item;
  50663. }
  50664. newOptionData.push(newItem);
  50665. });
  50666. option.data = newOptionData;
  50667. }
  50668. var defaultValueDimensions = this.defaultValueDimensions;
  50669. return createListSimply(
  50670. this,
  50671. {
  50672. coordDimensions: [{
  50673. name: baseAxisDim,
  50674. type: getDimensionTypeByAxis(baseAxisType),
  50675. ordinalMeta: ordinalMeta,
  50676. otherDims: {
  50677. tooltip: false,
  50678. itemName: 0
  50679. },
  50680. dimsDef: ['base']
  50681. }, {
  50682. name: otherAxisDim,
  50683. type: getDimensionTypeByAxis(otherAxisType),
  50684. dimsDef: defaultValueDimensions.slice()
  50685. }],
  50686. dimensionsCount: defaultValueDimensions.length + 1
  50687. }
  50688. );
  50689. },
  50690. /**
  50691. * If horizontal, base axis is x, otherwise y.
  50692. * @override
  50693. */
  50694. getBaseAxis: function () {
  50695. var dim = this._baseAxisDim;
  50696. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  50697. }
  50698. };
  50699. /*
  50700. * Licensed to the Apache Software Foundation (ASF) under one
  50701. * or more contributor license agreements. See the NOTICE file
  50702. * distributed with this work for additional information
  50703. * regarding copyright ownership. The ASF licenses this file
  50704. * to you under the Apache License, Version 2.0 (the
  50705. * "License"); you may not use this file except in compliance
  50706. * with the License. You may obtain a copy of the License at
  50707. *
  50708. * http://www.apache.org/licenses/LICENSE-2.0
  50709. *
  50710. * Unless required by applicable law or agreed to in writing,
  50711. * software distributed under the License is distributed on an
  50712. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50713. * KIND, either express or implied. See the License for the
  50714. * specific language governing permissions and limitations
  50715. * under the License.
  50716. */
  50717. var BoxplotSeries = SeriesModel.extend({
  50718. type: 'series.boxplot',
  50719. dependencies: ['xAxis', 'yAxis', 'grid'],
  50720. // TODO
  50721. // box width represents group size, so dimension should have 'size'.
  50722. /**
  50723. * @see <https://en.wikipedia.org/wiki/Box_plot>
  50724. * The meanings of 'min' and 'max' depend on user,
  50725. * and echarts do not need to know it.
  50726. * @readOnly
  50727. */
  50728. defaultValueDimensions: [
  50729. {name: 'min', defaultTooltip: true},
  50730. {name: 'Q1', defaultTooltip: true},
  50731. {name: 'median', defaultTooltip: true},
  50732. {name: 'Q3', defaultTooltip: true},
  50733. {name: 'max', defaultTooltip: true}
  50734. ],
  50735. /**
  50736. * @type {Array.<string>}
  50737. * @readOnly
  50738. */
  50739. dimensions: null,
  50740. /**
  50741. * @override
  50742. */
  50743. defaultOption: {
  50744. zlevel: 0, // 一级层叠
  50745. z: 2, // 二级层叠
  50746. coordinateSystem: 'cartesian2d',
  50747. legendHoverLink: true,
  50748. hoverAnimation: true,
  50749. // xAxisIndex: 0,
  50750. // yAxisIndex: 0,
  50751. layout: null, // 'horizontal' or 'vertical'
  50752. boxWidth: [7, 50], // [min, max] can be percent of band width.
  50753. itemStyle: {
  50754. color: '#fff',
  50755. borderWidth: 1
  50756. },
  50757. emphasis: {
  50758. itemStyle: {
  50759. borderWidth: 2,
  50760. shadowBlur: 5,
  50761. shadowOffsetX: 2,
  50762. shadowOffsetY: 2,
  50763. shadowColor: 'rgba(0,0,0,0.4)'
  50764. }
  50765. },
  50766. animationEasing: 'elasticOut',
  50767. animationDuration: 800
  50768. }
  50769. });
  50770. mixin(BoxplotSeries, seriesModelMixin, true);
  50771. /*
  50772. * Licensed to the Apache Software Foundation (ASF) under one
  50773. * or more contributor license agreements. See the NOTICE file
  50774. * distributed with this work for additional information
  50775. * regarding copyright ownership. The ASF licenses this file
  50776. * to you under the Apache License, Version 2.0 (the
  50777. * "License"); you may not use this file except in compliance
  50778. * with the License. You may obtain a copy of the License at
  50779. *
  50780. * http://www.apache.org/licenses/LICENSE-2.0
  50781. *
  50782. * Unless required by applicable law or agreed to in writing,
  50783. * software distributed under the License is distributed on an
  50784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50785. * KIND, either express or implied. See the License for the
  50786. * specific language governing permissions and limitations
  50787. * under the License.
  50788. */
  50789. // Update common properties
  50790. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  50791. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  50792. var BoxplotView = Chart.extend({
  50793. type: 'boxplot',
  50794. render: function (seriesModel, ecModel, api) {
  50795. var data = seriesModel.getData();
  50796. var group = this.group;
  50797. var oldData = this._data;
  50798. // There is no old data only when first rendering or switching from
  50799. // stream mode to normal mode, where previous elements should be removed.
  50800. if (!this._data) {
  50801. group.removeAll();
  50802. }
  50803. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  50804. data.diff(oldData)
  50805. .add(function (newIdx) {
  50806. if (data.hasValue(newIdx)) {
  50807. var itemLayout = data.getItemLayout(newIdx);
  50808. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  50809. data.setItemGraphicEl(newIdx, symbolEl);
  50810. group.add(symbolEl);
  50811. }
  50812. })
  50813. .update(function (newIdx, oldIdx) {
  50814. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  50815. // Empty data
  50816. if (!data.hasValue(newIdx)) {
  50817. group.remove(symbolEl);
  50818. return;
  50819. }
  50820. var itemLayout = data.getItemLayout(newIdx);
  50821. if (!symbolEl) {
  50822. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  50823. }
  50824. else {
  50825. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  50826. }
  50827. group.add(symbolEl);
  50828. data.setItemGraphicEl(newIdx, symbolEl);
  50829. })
  50830. .remove(function (oldIdx) {
  50831. var el = oldData.getItemGraphicEl(oldIdx);
  50832. el && group.remove(el);
  50833. })
  50834. .execute();
  50835. this._data = data;
  50836. },
  50837. remove: function (ecModel) {
  50838. var group = this.group;
  50839. var data = this._data;
  50840. this._data = null;
  50841. data && data.eachItemGraphicEl(function (el) {
  50842. el && group.remove(el);
  50843. });
  50844. },
  50845. dispose: noop
  50846. });
  50847. var BoxPath = Path.extend({
  50848. type: 'boxplotBoxPath',
  50849. shape: {},
  50850. buildPath: function (ctx, shape) {
  50851. var ends = shape.points;
  50852. var i = 0;
  50853. ctx.moveTo(ends[i][0], ends[i][1]);
  50854. i++;
  50855. for (; i < 4; i++) {
  50856. ctx.lineTo(ends[i][0], ends[i][1]);
  50857. }
  50858. ctx.closePath();
  50859. for (; i < ends.length; i++) {
  50860. ctx.moveTo(ends[i][0], ends[i][1]);
  50861. i++;
  50862. ctx.lineTo(ends[i][0], ends[i][1]);
  50863. }
  50864. }
  50865. });
  50866. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  50867. var ends = itemLayout.ends;
  50868. var el = new BoxPath({
  50869. shape: {
  50870. points: isInit
  50871. ? transInit(ends, constDim, itemLayout)
  50872. : ends
  50873. }
  50874. });
  50875. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  50876. return el;
  50877. }
  50878. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  50879. var seriesModel = data.hostModel;
  50880. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  50881. updateMethod(
  50882. el,
  50883. {shape: {points: itemLayout.ends}},
  50884. seriesModel,
  50885. dataIndex
  50886. );
  50887. var itemModel = data.getItemModel(dataIndex);
  50888. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  50889. var borderColor = data.getItemVisual(dataIndex, 'color');
  50890. // Exclude borderColor.
  50891. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  50892. itemStyle.stroke = borderColor;
  50893. itemStyle.strokeNoScale = true;
  50894. el.useStyle(itemStyle);
  50895. el.z2 = 100;
  50896. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  50897. setHoverStyle(el, hoverStyle);
  50898. }
  50899. function transInit(points, dim, itemLayout) {
  50900. return map(points, function (point) {
  50901. point = point.slice();
  50902. point[dim] = itemLayout.initBaseline;
  50903. return point;
  50904. });
  50905. }
  50906. /*
  50907. * Licensed to the Apache Software Foundation (ASF) under one
  50908. * or more contributor license agreements. See the NOTICE file
  50909. * distributed with this work for additional information
  50910. * regarding copyright ownership. The ASF licenses this file
  50911. * to you under the Apache License, Version 2.0 (the
  50912. * "License"); you may not use this file except in compliance
  50913. * with the License. You may obtain a copy of the License at
  50914. *
  50915. * http://www.apache.org/licenses/LICENSE-2.0
  50916. *
  50917. * Unless required by applicable law or agreed to in writing,
  50918. * software distributed under the License is distributed on an
  50919. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50920. * KIND, either express or implied. See the License for the
  50921. * specific language governing permissions and limitations
  50922. * under the License.
  50923. */
  50924. var borderColorQuery = ['itemStyle', 'borderColor'];
  50925. var boxplotVisual = function (ecModel, api) {
  50926. var globalColors = ecModel.get('color');
  50927. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  50928. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  50929. var data = seriesModel.getData();
  50930. data.setVisual({
  50931. legendSymbol: 'roundRect',
  50932. // Use name 'color' but not 'borderColor' for legend usage and
  50933. // visual coding from other component like dataRange.
  50934. color: seriesModel.get(borderColorQuery) || defaulColor
  50935. });
  50936. // Only visible series has each data be visual encoded
  50937. if (!ecModel.isSeriesFiltered(seriesModel)) {
  50938. data.each(function (idx) {
  50939. var itemModel = data.getItemModel(idx);
  50940. data.setItemVisual(
  50941. idx,
  50942. {color: itemModel.get(borderColorQuery, true)}
  50943. );
  50944. });
  50945. }
  50946. });
  50947. };
  50948. /*
  50949. * Licensed to the Apache Software Foundation (ASF) under one
  50950. * or more contributor license agreements. See the NOTICE file
  50951. * distributed with this work for additional information
  50952. * regarding copyright ownership. The ASF licenses this file
  50953. * to you under the Apache License, Version 2.0 (the
  50954. * "License"); you may not use this file except in compliance
  50955. * with the License. You may obtain a copy of the License at
  50956. *
  50957. * http://www.apache.org/licenses/LICENSE-2.0
  50958. *
  50959. * Unless required by applicable law or agreed to in writing,
  50960. * software distributed under the License is distributed on an
  50961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50962. * KIND, either express or implied. See the License for the
  50963. * specific language governing permissions and limitations
  50964. * under the License.
  50965. */
  50966. var each$13 = each$1;
  50967. var boxplotLayout = function (ecModel) {
  50968. var groupResult = groupSeriesByAxis(ecModel);
  50969. each$13(groupResult, function (groupItem) {
  50970. var seriesModels = groupItem.seriesModels;
  50971. if (!seriesModels.length) {
  50972. return;
  50973. }
  50974. calculateBase(groupItem);
  50975. each$13(seriesModels, function (seriesModel, idx) {
  50976. layoutSingleSeries(
  50977. seriesModel,
  50978. groupItem.boxOffsetList[idx],
  50979. groupItem.boxWidthList[idx]
  50980. );
  50981. });
  50982. });
  50983. };
  50984. /**
  50985. * Group series by axis.
  50986. */
  50987. function groupSeriesByAxis(ecModel) {
  50988. var result = [];
  50989. var axisList = [];
  50990. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  50991. var baseAxis = seriesModel.getBaseAxis();
  50992. var idx = indexOf(axisList, baseAxis);
  50993. if (idx < 0) {
  50994. idx = axisList.length;
  50995. axisList[idx] = baseAxis;
  50996. result[idx] = {axis: baseAxis, seriesModels: []};
  50997. }
  50998. result[idx].seriesModels.push(seriesModel);
  50999. });
  51000. return result;
  51001. }
  51002. /**
  51003. * Calculate offset and box width for each series.
  51004. */
  51005. function calculateBase(groupItem) {
  51006. var extent;
  51007. var baseAxis = groupItem.axis;
  51008. var seriesModels = groupItem.seriesModels;
  51009. var seriesCount = seriesModels.length;
  51010. var boxWidthList = groupItem.boxWidthList = [];
  51011. var boxOffsetList = groupItem.boxOffsetList = [];
  51012. var boundList = [];
  51013. var bandWidth;
  51014. if (baseAxis.type === 'category') {
  51015. bandWidth = baseAxis.getBandWidth();
  51016. }
  51017. else {
  51018. var maxDataCount = 0;
  51019. each$13(seriesModels, function (seriesModel) {
  51020. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  51021. });
  51022. extent = baseAxis.getExtent(),
  51023. Math.abs(extent[1] - extent[0]) / maxDataCount;
  51024. }
  51025. each$13(seriesModels, function (seriesModel) {
  51026. var boxWidthBound = seriesModel.get('boxWidth');
  51027. if (!isArray(boxWidthBound)) {
  51028. boxWidthBound = [boxWidthBound, boxWidthBound];
  51029. }
  51030. boundList.push([
  51031. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  51032. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  51033. ]);
  51034. });
  51035. var availableWidth = bandWidth * 0.8 - 2;
  51036. var boxGap = availableWidth / seriesCount * 0.3;
  51037. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  51038. var base = boxWidth / 2 - availableWidth / 2;
  51039. each$13(seriesModels, function (seriesModel, idx) {
  51040. boxOffsetList.push(base);
  51041. base += boxGap + boxWidth;
  51042. boxWidthList.push(
  51043. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  51044. );
  51045. });
  51046. }
  51047. /**
  51048. * Calculate points location for each series.
  51049. */
  51050. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  51051. var coordSys = seriesModel.coordinateSystem;
  51052. var data = seriesModel.getData();
  51053. var halfWidth = boxWidth / 2;
  51054. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  51055. var vDimIdx = 1 - cDimIdx;
  51056. var coordDims = ['x', 'y'];
  51057. var cDim = data.mapDimension(coordDims[cDimIdx]);
  51058. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  51059. if (cDim == null || vDims.length < 5) {
  51060. return;
  51061. }
  51062. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  51063. var axisDimVal = data.get(cDim, dataIndex);
  51064. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  51065. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  51066. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  51067. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  51068. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  51069. var ends = [];
  51070. addBodyEnd(ends, end2, 0);
  51071. addBodyEnd(ends, end4, 1);
  51072. ends.push(end1, end2, end5, end4);
  51073. layEndLine(ends, end1);
  51074. layEndLine(ends, end5);
  51075. layEndLine(ends, median);
  51076. data.setItemLayout(dataIndex, {
  51077. initBaseline: median[vDimIdx],
  51078. ends: ends
  51079. });
  51080. }
  51081. function getPoint(axisDimVal, dimIdx, dataIndex) {
  51082. var val = data.get(dimIdx, dataIndex);
  51083. var p = [];
  51084. p[cDimIdx] = axisDimVal;
  51085. p[vDimIdx] = val;
  51086. var point;
  51087. if (isNaN(axisDimVal) || isNaN(val)) {
  51088. point = [NaN, NaN];
  51089. }
  51090. else {
  51091. point = coordSys.dataToPoint(p);
  51092. point[cDimIdx] += offset;
  51093. }
  51094. return point;
  51095. }
  51096. function addBodyEnd(ends, point, start) {
  51097. var point1 = point.slice();
  51098. var point2 = point.slice();
  51099. point1[cDimIdx] += halfWidth;
  51100. point2[cDimIdx] -= halfWidth;
  51101. start
  51102. ? ends.push(point1, point2)
  51103. : ends.push(point2, point1);
  51104. }
  51105. function layEndLine(ends, endCenter) {
  51106. var from = endCenter.slice();
  51107. var to = endCenter.slice();
  51108. from[cDimIdx] -= halfWidth;
  51109. to[cDimIdx] += halfWidth;
  51110. ends.push(from, to);
  51111. }
  51112. }
  51113. /*
  51114. * Licensed to the Apache Software Foundation (ASF) under one
  51115. * or more contributor license agreements. See the NOTICE file
  51116. * distributed with this work for additional information
  51117. * regarding copyright ownership. The ASF licenses this file
  51118. * to you under the Apache License, Version 2.0 (the
  51119. * "License"); you may not use this file except in compliance
  51120. * with the License. You may obtain a copy of the License at
  51121. *
  51122. * http://www.apache.org/licenses/LICENSE-2.0
  51123. *
  51124. * Unless required by applicable law or agreed to in writing,
  51125. * software distributed under the License is distributed on an
  51126. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51127. * KIND, either express or implied. See the License for the
  51128. * specific language governing permissions and limitations
  51129. * under the License.
  51130. */
  51131. registerVisual(boxplotVisual);
  51132. registerLayout(boxplotLayout);
  51133. /*
  51134. * Licensed to the Apache Software Foundation (ASF) under one
  51135. * or more contributor license agreements. See the NOTICE file
  51136. * distributed with this work for additional information
  51137. * regarding copyright ownership. The ASF licenses this file
  51138. * to you under the Apache License, Version 2.0 (the
  51139. * "License"); you may not use this file except in compliance
  51140. * with the License. You may obtain a copy of the License at
  51141. *
  51142. * http://www.apache.org/licenses/LICENSE-2.0
  51143. *
  51144. * Unless required by applicable law or agreed to in writing,
  51145. * software distributed under the License is distributed on an
  51146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51147. * KIND, either express or implied. See the License for the
  51148. * specific language governing permissions and limitations
  51149. * under the License.
  51150. */
  51151. var CandlestickSeries = SeriesModel.extend({
  51152. type: 'series.candlestick',
  51153. dependencies: ['xAxis', 'yAxis', 'grid'],
  51154. /**
  51155. * @readOnly
  51156. */
  51157. defaultValueDimensions: [
  51158. {name: 'open', defaultTooltip: true},
  51159. {name: 'close', defaultTooltip: true},
  51160. {name: 'lowest', defaultTooltip: true},
  51161. {name: 'highest', defaultTooltip: true}
  51162. ],
  51163. /**
  51164. * @type {Array.<string>}
  51165. * @readOnly
  51166. */
  51167. dimensions: null,
  51168. /**
  51169. * @override
  51170. */
  51171. defaultOption: {
  51172. zlevel: 0,
  51173. z: 2,
  51174. coordinateSystem: 'cartesian2d',
  51175. legendHoverLink: true,
  51176. hoverAnimation: true,
  51177. // xAxisIndex: 0,
  51178. // yAxisIndex: 0,
  51179. layout: null, // 'horizontal' or 'vertical'
  51180. itemStyle: {
  51181. color: '#c23531', // 阳线 positive
  51182. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  51183. borderWidth: 1,
  51184. // FIXME
  51185. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  51186. borderColor: '#c23531',
  51187. borderColor0: '#314656'
  51188. },
  51189. emphasis: {
  51190. itemStyle: {
  51191. borderWidth: 2
  51192. }
  51193. },
  51194. barMaxWidth: null,
  51195. barMinWidth: null,
  51196. barWidth: null,
  51197. large: true,
  51198. largeThreshold: 600,
  51199. progressive: 3e3,
  51200. progressiveThreshold: 1e4,
  51201. progressiveChunkMode: 'mod',
  51202. animationUpdate: false,
  51203. animationEasing: 'linear',
  51204. animationDuration: 300
  51205. },
  51206. /**
  51207. * Get dimension for shadow in dataZoom
  51208. * @return {string} dimension name
  51209. */
  51210. getShadowDim: function () {
  51211. return 'open';
  51212. },
  51213. brushSelector: function (dataIndex, data, selectors) {
  51214. var itemLayout = data.getItemLayout(dataIndex);
  51215. return itemLayout && selectors.rect(itemLayout.brushRect);
  51216. }
  51217. });
  51218. mixin(CandlestickSeries, seriesModelMixin, true);
  51219. /*
  51220. * Licensed to the Apache Software Foundation (ASF) under one
  51221. * or more contributor license agreements. See the NOTICE file
  51222. * distributed with this work for additional information
  51223. * regarding copyright ownership. The ASF licenses this file
  51224. * to you under the Apache License, Version 2.0 (the
  51225. * "License"); you may not use this file except in compliance
  51226. * with the License. You may obtain a copy of the License at
  51227. *
  51228. * http://www.apache.org/licenses/LICENSE-2.0
  51229. *
  51230. * Unless required by applicable law or agreed to in writing,
  51231. * software distributed under the License is distributed on an
  51232. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51233. * KIND, either express or implied. See the License for the
  51234. * specific language governing permissions and limitations
  51235. * under the License.
  51236. */
  51237. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  51238. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  51239. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  51240. var CandlestickView = Chart.extend({
  51241. type: 'candlestick',
  51242. render: function (seriesModel, ecModel, api) {
  51243. this._updateDrawMode(seriesModel);
  51244. this._isLargeDraw
  51245. ? this._renderLarge(seriesModel)
  51246. : this._renderNormal(seriesModel);
  51247. },
  51248. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  51249. this._clear();
  51250. this._updateDrawMode(seriesModel);
  51251. },
  51252. incrementalRender: function (params, seriesModel, ecModel, api) {
  51253. this._isLargeDraw
  51254. ? this._incrementalRenderLarge(params, seriesModel)
  51255. : this._incrementalRenderNormal(params, seriesModel);
  51256. },
  51257. _updateDrawMode: function (seriesModel) {
  51258. var isLargeDraw = seriesModel.pipelineContext.large;
  51259. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  51260. this._isLargeDraw = isLargeDraw;
  51261. this._clear();
  51262. }
  51263. },
  51264. _renderNormal: function (seriesModel) {
  51265. var data = seriesModel.getData();
  51266. var oldData = this._data;
  51267. var group = this.group;
  51268. var isSimpleBox = data.getLayout('isSimpleBox');
  51269. // There is no old data only when first rendering or switching from
  51270. // stream mode to normal mode, where previous elements should be removed.
  51271. if (!this._data) {
  51272. group.removeAll();
  51273. }
  51274. data.diff(oldData)
  51275. .add(function (newIdx) {
  51276. if (data.hasValue(newIdx)) {
  51277. var el;
  51278. var itemLayout = data.getItemLayout(newIdx);
  51279. el = createNormalBox$1(itemLayout, newIdx, true);
  51280. initProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  51281. setBoxCommon(el, data, newIdx, isSimpleBox);
  51282. group.add(el);
  51283. data.setItemGraphicEl(newIdx, el);
  51284. }
  51285. })
  51286. .update(function (newIdx, oldIdx) {
  51287. var el = oldData.getItemGraphicEl(oldIdx);
  51288. // Empty data
  51289. if (!data.hasValue(newIdx)) {
  51290. group.remove(el);
  51291. return;
  51292. }
  51293. var itemLayout = data.getItemLayout(newIdx);
  51294. if (!el) {
  51295. el = createNormalBox$1(itemLayout, newIdx);
  51296. }
  51297. else {
  51298. updateProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  51299. }
  51300. setBoxCommon(el, data, newIdx, isSimpleBox);
  51301. group.add(el);
  51302. data.setItemGraphicEl(newIdx, el);
  51303. })
  51304. .remove(function (oldIdx) {
  51305. var el = oldData.getItemGraphicEl(oldIdx);
  51306. el && group.remove(el);
  51307. })
  51308. .execute();
  51309. this._data = data;
  51310. },
  51311. _renderLarge: function (seriesModel) {
  51312. this._clear();
  51313. createLarge$1(seriesModel, this.group);
  51314. },
  51315. _incrementalRenderNormal: function (params, seriesModel) {
  51316. var data = seriesModel.getData();
  51317. var isSimpleBox = data.getLayout('isSimpleBox');
  51318. var dataIndex;
  51319. while ((dataIndex = params.next()) != null) {
  51320. var el;
  51321. var itemLayout = data.getItemLayout(dataIndex);
  51322. el = createNormalBox$1(itemLayout, dataIndex);
  51323. setBoxCommon(el, data, dataIndex, isSimpleBox);
  51324. el.incremental = true;
  51325. this.group.add(el);
  51326. }
  51327. },
  51328. _incrementalRenderLarge: function (params, seriesModel) {
  51329. createLarge$1(seriesModel, this.group, true);
  51330. },
  51331. remove: function (ecModel) {
  51332. this._clear();
  51333. },
  51334. _clear: function () {
  51335. this.group.removeAll();
  51336. this._data = null;
  51337. },
  51338. dispose: noop
  51339. });
  51340. var NormalBoxPath = Path.extend({
  51341. type: 'normalCandlestickBox',
  51342. shape: {},
  51343. buildPath: function (ctx, shape) {
  51344. var ends = shape.points;
  51345. if (this.__simpleBox) {
  51346. ctx.moveTo(ends[4][0], ends[4][1]);
  51347. ctx.lineTo(ends[6][0], ends[6][1]);
  51348. }
  51349. else {
  51350. ctx.moveTo(ends[0][0], ends[0][1]);
  51351. ctx.lineTo(ends[1][0], ends[1][1]);
  51352. ctx.lineTo(ends[2][0], ends[2][1]);
  51353. ctx.lineTo(ends[3][0], ends[3][1]);
  51354. ctx.closePath();
  51355. ctx.moveTo(ends[4][0], ends[4][1]);
  51356. ctx.lineTo(ends[5][0], ends[5][1]);
  51357. ctx.moveTo(ends[6][0], ends[6][1]);
  51358. ctx.lineTo(ends[7][0], ends[7][1]);
  51359. }
  51360. }
  51361. });
  51362. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  51363. var ends = itemLayout.ends;
  51364. return new NormalBoxPath({
  51365. shape: {
  51366. points: isInit
  51367. ? transInit$1(ends, itemLayout)
  51368. : ends
  51369. },
  51370. z2: 100
  51371. });
  51372. }
  51373. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  51374. var itemModel = data.getItemModel(dataIndex);
  51375. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  51376. var color = data.getItemVisual(dataIndex, 'color');
  51377. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color;
  51378. // Color must be excluded.
  51379. // Because symbol provide setColor individually to set fill and stroke
  51380. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  51381. el.useStyle(itemStyle);
  51382. el.style.strokeNoScale = true;
  51383. el.style.fill = color;
  51384. el.style.stroke = borderColor;
  51385. el.__simpleBox = isSimpleBox;
  51386. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  51387. setHoverStyle(el, hoverStyle);
  51388. }
  51389. function transInit$1(points, itemLayout) {
  51390. return map(points, function (point) {
  51391. point = point.slice();
  51392. point[1] = itemLayout.initBaseline;
  51393. return point;
  51394. });
  51395. }
  51396. var LargeBoxPath = Path.extend({
  51397. type: 'largeCandlestickBox',
  51398. shape: {},
  51399. buildPath: function (ctx, shape) {
  51400. // Drawing lines is more efficient than drawing
  51401. // a whole line or drawing rects.
  51402. var points = shape.points;
  51403. for (var i = 0; i < points.length;) {
  51404. if (this.__sign === points[i++]) {
  51405. var x = points[i++];
  51406. ctx.moveTo(x, points[i++]);
  51407. ctx.lineTo(x, points[i++]);
  51408. }
  51409. else {
  51410. i += 3;
  51411. }
  51412. }
  51413. }
  51414. });
  51415. function createLarge$1(seriesModel, group, incremental) {
  51416. var data = seriesModel.getData();
  51417. var largePoints = data.getLayout('largePoints');
  51418. var elP = new LargeBoxPath({
  51419. shape: {points: largePoints},
  51420. __sign: 1
  51421. });
  51422. group.add(elP);
  51423. var elN = new LargeBoxPath({
  51424. shape: {points: largePoints},
  51425. __sign: -1
  51426. });
  51427. group.add(elN);
  51428. setLargeStyle$1(1, elP, seriesModel, data);
  51429. setLargeStyle$1(-1, elN, seriesModel, data);
  51430. if (incremental) {
  51431. elP.incremental = true;
  51432. elN.incremental = true;
  51433. }
  51434. }
  51435. function setLargeStyle$1(sign, el, seriesModel, data) {
  51436. var suffix = sign > 0 ? 'P' : 'N';
  51437. var borderColor = data.getVisual('borderColor' + suffix)
  51438. || data.getVisual('color' + suffix);
  51439. // Color must be excluded.
  51440. // Because symbol provide setColor individually to set fill and stroke
  51441. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH$1).getItemStyle(SKIP_PROPS);
  51442. el.useStyle(itemStyle);
  51443. el.style.fill = null;
  51444. el.style.stroke = borderColor;
  51445. // No different
  51446. // el.style.lineWidth = .5;
  51447. }
  51448. /*
  51449. * Licensed to the Apache Software Foundation (ASF) under one
  51450. * or more contributor license agreements. See the NOTICE file
  51451. * distributed with this work for additional information
  51452. * regarding copyright ownership. The ASF licenses this file
  51453. * to you under the Apache License, Version 2.0 (the
  51454. * "License"); you may not use this file except in compliance
  51455. * with the License. You may obtain a copy of the License at
  51456. *
  51457. * http://www.apache.org/licenses/LICENSE-2.0
  51458. *
  51459. * Unless required by applicable law or agreed to in writing,
  51460. * software distributed under the License is distributed on an
  51461. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51462. * KIND, either express or implied. See the License for the
  51463. * specific language governing permissions and limitations
  51464. * under the License.
  51465. */
  51466. var preprocessor = function (option) {
  51467. if (!option || !isArray(option.series)) {
  51468. return;
  51469. }
  51470. // Translate 'k' to 'candlestick'.
  51471. each$1(option.series, function (seriesItem) {
  51472. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  51473. seriesItem.type = 'candlestick';
  51474. }
  51475. });
  51476. };
  51477. /*
  51478. * Licensed to the Apache Software Foundation (ASF) under one
  51479. * or more contributor license agreements. See the NOTICE file
  51480. * distributed with this work for additional information
  51481. * regarding copyright ownership. The ASF licenses this file
  51482. * to you under the Apache License, Version 2.0 (the
  51483. * "License"); you may not use this file except in compliance
  51484. * with the License. You may obtain a copy of the License at
  51485. *
  51486. * http://www.apache.org/licenses/LICENSE-2.0
  51487. *
  51488. * Unless required by applicable law or agreed to in writing,
  51489. * software distributed under the License is distributed on an
  51490. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51491. * KIND, either express or implied. See the License for the
  51492. * specific language governing permissions and limitations
  51493. * under the License.
  51494. */
  51495. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  51496. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  51497. var positiveColorQuery = ['itemStyle', 'color'];
  51498. var negativeColorQuery = ['itemStyle', 'color0'];
  51499. var candlestickVisual = {
  51500. seriesType: 'candlestick',
  51501. plan: createRenderPlanner(),
  51502. // For legend.
  51503. performRawSeries: true,
  51504. reset: function (seriesModel, ecModel) {
  51505. var data = seriesModel.getData();
  51506. var isLargeRender = seriesModel.pipelineContext.large;
  51507. data.setVisual({
  51508. legendSymbol: 'roundRect',
  51509. colorP: getColor(1, seriesModel),
  51510. colorN: getColor(-1, seriesModel),
  51511. borderColorP: getBorderColor(1, seriesModel),
  51512. borderColorN: getBorderColor(-1, seriesModel)
  51513. });
  51514. // Only visible series has each data be visual encoded
  51515. if (ecModel.isSeriesFiltered(seriesModel)) {
  51516. return;
  51517. }
  51518. return !isLargeRender && {progress: progress};
  51519. function progress(params, data) {
  51520. var dataIndex;
  51521. while ((dataIndex = params.next()) != null) {
  51522. var itemModel = data.getItemModel(dataIndex);
  51523. var sign = data.getItemLayout(dataIndex).sign;
  51524. data.setItemVisual(
  51525. dataIndex,
  51526. {
  51527. color: getColor(sign, itemModel),
  51528. borderColor: getBorderColor(sign, itemModel)
  51529. }
  51530. );
  51531. }
  51532. }
  51533. function getColor(sign, model) {
  51534. return model.get(
  51535. sign > 0 ? positiveColorQuery : negativeColorQuery
  51536. );
  51537. }
  51538. function getBorderColor(sign, model) {
  51539. return model.get(
  51540. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  51541. );
  51542. }
  51543. }
  51544. };
  51545. /*
  51546. * Licensed to the Apache Software Foundation (ASF) under one
  51547. * or more contributor license agreements. See the NOTICE file
  51548. * distributed with this work for additional information
  51549. * regarding copyright ownership. The ASF licenses this file
  51550. * to you under the Apache License, Version 2.0 (the
  51551. * "License"); you may not use this file except in compliance
  51552. * with the License. You may obtain a copy of the License at
  51553. *
  51554. * http://www.apache.org/licenses/LICENSE-2.0
  51555. *
  51556. * Unless required by applicable law or agreed to in writing,
  51557. * software distributed under the License is distributed on an
  51558. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51559. * KIND, either express or implied. See the License for the
  51560. * specific language governing permissions and limitations
  51561. * under the License.
  51562. */
  51563. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  51564. var candlestickLayout = {
  51565. seriesType: 'candlestick',
  51566. plan: createRenderPlanner(),
  51567. reset: function (seriesModel) {
  51568. var coordSys = seriesModel.coordinateSystem;
  51569. var data = seriesModel.getData();
  51570. var candleWidth = calculateCandleWidth(seriesModel, data);
  51571. var cDimIdx = 0;
  51572. var vDimIdx = 1;
  51573. var coordDims = ['x', 'y'];
  51574. var cDim = data.mapDimension(coordDims[cDimIdx]);
  51575. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  51576. var openDim = vDims[0];
  51577. var closeDim = vDims[1];
  51578. var lowestDim = vDims[2];
  51579. var highestDim = vDims[3];
  51580. data.setLayout({
  51581. candleWidth: candleWidth,
  51582. // The value is experimented visually.
  51583. isSimpleBox: candleWidth <= 1.3
  51584. });
  51585. if (cDim == null || vDims.length < 4) {
  51586. return;
  51587. }
  51588. return {
  51589. progress: seriesModel.pipelineContext.large
  51590. ? largeProgress : normalProgress
  51591. };
  51592. function normalProgress(params, data) {
  51593. var dataIndex;
  51594. while ((dataIndex = params.next()) != null) {
  51595. var axisDimVal = data.get(cDim, dataIndex);
  51596. var openVal = data.get(openDim, dataIndex);
  51597. var closeVal = data.get(closeDim, dataIndex);
  51598. var lowestVal = data.get(lowestDim, dataIndex);
  51599. var highestVal = data.get(highestDim, dataIndex);
  51600. var ocLow = Math.min(openVal, closeVal);
  51601. var ocHigh = Math.max(openVal, closeVal);
  51602. var ocLowPoint = getPoint(ocLow, axisDimVal);
  51603. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  51604. var lowestPoint = getPoint(lowestVal, axisDimVal);
  51605. var highestPoint = getPoint(highestVal, axisDimVal);
  51606. var ends = [];
  51607. addBodyEnd(ends, ocHighPoint, 0);
  51608. addBodyEnd(ends, ocLowPoint, 1);
  51609. ends.push(
  51610. subPixelOptimizePoint(highestPoint),
  51611. subPixelOptimizePoint(ocHighPoint),
  51612. subPixelOptimizePoint(lowestPoint),
  51613. subPixelOptimizePoint(ocLowPoint)
  51614. );
  51615. data.setItemLayout(dataIndex, {
  51616. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  51617. initBaseline: openVal > closeVal
  51618. ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
  51619. ends: ends,
  51620. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  51621. });
  51622. }
  51623. function getPoint(val, axisDimVal) {
  51624. var p = [];
  51625. p[cDimIdx] = axisDimVal;
  51626. p[vDimIdx] = val;
  51627. return (isNaN(axisDimVal) || isNaN(val))
  51628. ? [NaN, NaN]
  51629. : coordSys.dataToPoint(p);
  51630. }
  51631. function addBodyEnd(ends, point, start) {
  51632. var point1 = point.slice();
  51633. var point2 = point.slice();
  51634. point1[cDimIdx] = subPixelOptimize(
  51635. point1[cDimIdx] + candleWidth / 2, 1, false
  51636. );
  51637. point2[cDimIdx] = subPixelOptimize(
  51638. point2[cDimIdx] - candleWidth / 2, 1, true
  51639. );
  51640. start
  51641. ? ends.push(point1, point2)
  51642. : ends.push(point2, point1);
  51643. }
  51644. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  51645. var pmin = getPoint(lowestVal, axisDimVal);
  51646. var pmax = getPoint(highestVal, axisDimVal);
  51647. pmin[cDimIdx] -= candleWidth / 2;
  51648. pmax[cDimIdx] -= candleWidth / 2;
  51649. return {
  51650. x: pmin[0],
  51651. y: pmin[1],
  51652. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  51653. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  51654. };
  51655. }
  51656. function subPixelOptimizePoint(point) {
  51657. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  51658. return point;
  51659. }
  51660. }
  51661. function largeProgress(params, data) {
  51662. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  51663. var points = new LargeArr$1(params.count * 5);
  51664. var offset = 0;
  51665. var point;
  51666. var tmpIn = [];
  51667. var tmpOut = [];
  51668. var dataIndex;
  51669. while ((dataIndex = params.next()) != null) {
  51670. var axisDimVal = data.get(cDim, dataIndex);
  51671. var openVal = data.get(openDim, dataIndex);
  51672. var closeVal = data.get(closeDim, dataIndex);
  51673. var lowestVal = data.get(lowestDim, dataIndex);
  51674. var highestVal = data.get(highestDim, dataIndex);
  51675. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  51676. points[offset++] = NaN;
  51677. offset += 4;
  51678. continue;
  51679. }
  51680. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  51681. tmpIn[cDimIdx] = axisDimVal;
  51682. tmpIn[vDimIdx] = lowestVal;
  51683. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  51684. points[offset++] = point ? point[0] : NaN;
  51685. points[offset++] = point ? point[1] : NaN;
  51686. tmpIn[vDimIdx] = highestVal;
  51687. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  51688. points[offset++] = point ? point[1] : NaN;
  51689. }
  51690. data.setLayout('largePoints', points);
  51691. }
  51692. }
  51693. };
  51694. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  51695. var sign;
  51696. if (openVal > closeVal) {
  51697. sign = -1;
  51698. }
  51699. else if (openVal < closeVal) {
  51700. sign = 1;
  51701. }
  51702. else {
  51703. sign = dataIndex > 0
  51704. // If close === open, compare with close of last record
  51705. ? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
  51706. // No record of previous, set to be positive
  51707. : 1;
  51708. }
  51709. return sign;
  51710. }
  51711. function calculateCandleWidth(seriesModel, data) {
  51712. var baseAxis = seriesModel.getBaseAxis();
  51713. var extent;
  51714. var bandWidth = baseAxis.type === 'category'
  51715. ? baseAxis.getBandWidth()
  51716. : (
  51717. extent = baseAxis.getExtent(),
  51718. Math.abs(extent[1] - extent[0]) / data.count()
  51719. );
  51720. var barMaxWidth = parsePercent$1(
  51721. retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
  51722. bandWidth
  51723. );
  51724. var barMinWidth = parsePercent$1(
  51725. retrieve2(seriesModel.get('barMinWidth'), 1),
  51726. bandWidth
  51727. );
  51728. var barWidth = seriesModel.get('barWidth');
  51729. return barWidth != null
  51730. ? parsePercent$1(barWidth, bandWidth)
  51731. // Put max outer to ensure bar visible in spite of overlap.
  51732. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  51733. }
  51734. /*
  51735. * Licensed to the Apache Software Foundation (ASF) under one
  51736. * or more contributor license agreements. See the NOTICE file
  51737. * distributed with this work for additional information
  51738. * regarding copyright ownership. The ASF licenses this file
  51739. * to you under the Apache License, Version 2.0 (the
  51740. * "License"); you may not use this file except in compliance
  51741. * with the License. You may obtain a copy of the License at
  51742. *
  51743. * http://www.apache.org/licenses/LICENSE-2.0
  51744. *
  51745. * Unless required by applicable law or agreed to in writing,
  51746. * software distributed under the License is distributed on an
  51747. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51748. * KIND, either express or implied. See the License for the
  51749. * specific language governing permissions and limitations
  51750. * under the License.
  51751. */
  51752. registerPreprocessor(preprocessor);
  51753. registerVisual(candlestickVisual);
  51754. registerLayout(candlestickLayout);
  51755. /*
  51756. * Licensed to the Apache Software Foundation (ASF) under one
  51757. * or more contributor license agreements. See the NOTICE file
  51758. * distributed with this work for additional information
  51759. * regarding copyright ownership. The ASF licenses this file
  51760. * to you under the Apache License, Version 2.0 (the
  51761. * "License"); you may not use this file except in compliance
  51762. * with the License. You may obtain a copy of the License at
  51763. *
  51764. * http://www.apache.org/licenses/LICENSE-2.0
  51765. *
  51766. * Unless required by applicable law or agreed to in writing,
  51767. * software distributed under the License is distributed on an
  51768. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51769. * KIND, either express or implied. See the License for the
  51770. * specific language governing permissions and limitations
  51771. * under the License.
  51772. */
  51773. SeriesModel.extend({
  51774. type: 'series.effectScatter',
  51775. dependencies: ['grid', 'polar'],
  51776. getInitialData: function (option, ecModel) {
  51777. return createListFromArray(this.getSource(), this);
  51778. },
  51779. brushSelector: 'point',
  51780. defaultOption: {
  51781. coordinateSystem: 'cartesian2d',
  51782. zlevel: 0,
  51783. z: 2,
  51784. legendHoverLink: true,
  51785. effectType: 'ripple',
  51786. progressive: 0,
  51787. // When to show the effect, option: 'render'|'emphasis'
  51788. showEffectOn: 'render',
  51789. // Ripple effect config
  51790. rippleEffect: {
  51791. period: 4,
  51792. // Scale of ripple
  51793. scale: 2.5,
  51794. // Brush type can be fill or stroke
  51795. brushType: 'fill'
  51796. },
  51797. // Cartesian coordinate system
  51798. // xAxisIndex: 0,
  51799. // yAxisIndex: 0,
  51800. // Polar coordinate system
  51801. // polarIndex: 0,
  51802. // Geo coordinate system
  51803. // geoIndex: 0,
  51804. // symbol: null, // 图形类型
  51805. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  51806. // symbolRotate: null, // 图形旋转控制
  51807. // large: false,
  51808. // Available when large is true
  51809. // largeThreshold: 2000,
  51810. // itemStyle: {
  51811. // opacity: 1
  51812. // }
  51813. }
  51814. });
  51815. /*
  51816. * Licensed to the Apache Software Foundation (ASF) under one
  51817. * or more contributor license agreements. See the NOTICE file
  51818. * distributed with this work for additional information
  51819. * regarding copyright ownership. The ASF licenses this file
  51820. * to you under the Apache License, Version 2.0 (the
  51821. * "License"); you may not use this file except in compliance
  51822. * with the License. You may obtain a copy of the License at
  51823. *
  51824. * http://www.apache.org/licenses/LICENSE-2.0
  51825. *
  51826. * Unless required by applicable law or agreed to in writing,
  51827. * software distributed under the License is distributed on an
  51828. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51829. * KIND, either express or implied. See the License for the
  51830. * specific language governing permissions and limitations
  51831. * under the License.
  51832. */
  51833. /**
  51834. * Symbol with ripple effect
  51835. * @module echarts/chart/helper/EffectSymbol
  51836. */
  51837. var EFFECT_RIPPLE_NUMBER = 3;
  51838. function normalizeSymbolSize$1(symbolSize) {
  51839. if (!isArray(symbolSize)) {
  51840. symbolSize = [+symbolSize, +symbolSize];
  51841. }
  51842. return symbolSize;
  51843. }
  51844. function updateRipplePath(rippleGroup, effectCfg) {
  51845. rippleGroup.eachChild(function (ripplePath) {
  51846. ripplePath.attr({
  51847. z: effectCfg.z,
  51848. zlevel: effectCfg.zlevel,
  51849. style: {
  51850. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  51851. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  51852. }
  51853. });
  51854. });
  51855. }
  51856. /**
  51857. * @constructor
  51858. * @param {module:echarts/data/List} data
  51859. * @param {number} idx
  51860. * @extends {module:zrender/graphic/Group}
  51861. */
  51862. function EffectSymbol(data, idx) {
  51863. Group.call(this);
  51864. var symbol = new SymbolClz$1(data, idx);
  51865. var rippleGroup = new Group();
  51866. this.add(symbol);
  51867. this.add(rippleGroup);
  51868. rippleGroup.beforeUpdate = function () {
  51869. this.attr(symbol.getScale());
  51870. };
  51871. this.updateData(data, idx);
  51872. }
  51873. var effectSymbolProto = EffectSymbol.prototype;
  51874. effectSymbolProto.stopEffectAnimation = function () {
  51875. this.childAt(1).removeAll();
  51876. };
  51877. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  51878. var symbolType = effectCfg.symbolType;
  51879. var color = effectCfg.color;
  51880. var rippleGroup = this.childAt(1);
  51881. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  51882. // var ripplePath = createSymbol(
  51883. // symbolType, -0.5, -0.5, 1, 1, color
  51884. // );
  51885. // If width/height are set too small (e.g., set to 1) on ios10
  51886. // and macOS Sierra, a circle stroke become a rect, no matter what
  51887. // the scale is set. So we set width/height as 2. See #4136.
  51888. var ripplePath = createSymbol(
  51889. symbolType, -1, -1, 2, 2, color
  51890. );
  51891. ripplePath.attr({
  51892. style: {
  51893. strokeNoScale: true
  51894. },
  51895. z2: 99,
  51896. silent: true,
  51897. scale: [0.5, 0.5]
  51898. });
  51899. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  51900. // TODO Configurable effectCfg.period
  51901. ripplePath.animate('', true)
  51902. .when(effectCfg.period, {
  51903. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  51904. })
  51905. .delay(delay)
  51906. .start();
  51907. ripplePath.animateStyle(true)
  51908. .when(effectCfg.period, {
  51909. opacity: 0
  51910. })
  51911. .delay(delay)
  51912. .start();
  51913. rippleGroup.add(ripplePath);
  51914. }
  51915. updateRipplePath(rippleGroup, effectCfg);
  51916. };
  51917. /**
  51918. * Update effect symbol
  51919. */
  51920. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  51921. var oldEffectCfg = this._effectCfg;
  51922. var rippleGroup = this.childAt(1);
  51923. // Must reinitialize effect if following configuration changed
  51924. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  51925. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  51926. var propName = DIFFICULT_PROPS[i];
  51927. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  51928. this.stopEffectAnimation();
  51929. this.startEffectAnimation(effectCfg);
  51930. return;
  51931. }
  51932. }
  51933. updateRipplePath(rippleGroup, effectCfg);
  51934. };
  51935. /**
  51936. * Highlight symbol
  51937. */
  51938. effectSymbolProto.highlight = function () {
  51939. this.trigger('emphasis');
  51940. };
  51941. /**
  51942. * Downplay symbol
  51943. */
  51944. effectSymbolProto.downplay = function () {
  51945. this.trigger('normal');
  51946. };
  51947. /**
  51948. * Update symbol properties
  51949. * @param {module:echarts/data/List} data
  51950. * @param {number} idx
  51951. */
  51952. effectSymbolProto.updateData = function (data, idx) {
  51953. var seriesModel = data.hostModel;
  51954. this.childAt(0).updateData(data, idx);
  51955. var rippleGroup = this.childAt(1);
  51956. var itemModel = data.getItemModel(idx);
  51957. var symbolType = data.getItemVisual(idx, 'symbol');
  51958. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  51959. var color = data.getItemVisual(idx, 'color');
  51960. rippleGroup.attr('scale', symbolSize);
  51961. rippleGroup.traverse(function (ripplePath) {
  51962. ripplePath.attr({
  51963. fill: color
  51964. });
  51965. });
  51966. var symbolOffset = itemModel.getShallow('symbolOffset');
  51967. if (symbolOffset) {
  51968. var pos = rippleGroup.position;
  51969. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  51970. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  51971. }
  51972. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  51973. var effectCfg = {};
  51974. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  51975. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  51976. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  51977. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  51978. effectCfg.effectOffset = idx / data.count();
  51979. effectCfg.z = itemModel.getShallow('z') || 0;
  51980. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  51981. effectCfg.symbolType = symbolType;
  51982. effectCfg.color = color;
  51983. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  51984. if (effectCfg.showEffectOn === 'render') {
  51985. this._effectCfg
  51986. ? this.updateEffectAnimation(effectCfg)
  51987. : this.startEffectAnimation(effectCfg);
  51988. this._effectCfg = effectCfg;
  51989. }
  51990. else {
  51991. // Not keep old effect config
  51992. this._effectCfg = null;
  51993. this.stopEffectAnimation();
  51994. var symbol = this.childAt(0);
  51995. var onEmphasis = function () {
  51996. symbol.highlight();
  51997. if (effectCfg.showEffectOn !== 'render') {
  51998. this.startEffectAnimation(effectCfg);
  51999. }
  52000. };
  52001. var onNormal = function () {
  52002. symbol.downplay();
  52003. if (effectCfg.showEffectOn !== 'render') {
  52004. this.stopEffectAnimation();
  52005. }
  52006. };
  52007. this.on('mouseover', onEmphasis, this)
  52008. .on('mouseout', onNormal, this)
  52009. .on('emphasis', onEmphasis, this)
  52010. .on('normal', onNormal, this);
  52011. }
  52012. this._effectCfg = effectCfg;
  52013. };
  52014. effectSymbolProto.fadeOut = function (cb) {
  52015. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  52016. cb && cb();
  52017. };
  52018. inherits(EffectSymbol, Group);
  52019. /*
  52020. * Licensed to the Apache Software Foundation (ASF) under one
  52021. * or more contributor license agreements. See the NOTICE file
  52022. * distributed with this work for additional information
  52023. * regarding copyright ownership. The ASF licenses this file
  52024. * to you under the Apache License, Version 2.0 (the
  52025. * "License"); you may not use this file except in compliance
  52026. * with the License. You may obtain a copy of the License at
  52027. *
  52028. * http://www.apache.org/licenses/LICENSE-2.0
  52029. *
  52030. * Unless required by applicable law or agreed to in writing,
  52031. * software distributed under the License is distributed on an
  52032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52033. * KIND, either express or implied. See the License for the
  52034. * specific language governing permissions and limitations
  52035. * under the License.
  52036. */
  52037. extendChartView({
  52038. type: 'effectScatter',
  52039. init: function () {
  52040. this._symbolDraw = new SymbolDraw(EffectSymbol);
  52041. },
  52042. render: function (seriesModel, ecModel, api) {
  52043. var data = seriesModel.getData();
  52044. var effectSymbolDraw = this._symbolDraw;
  52045. effectSymbolDraw.updateData(data);
  52046. this.group.add(effectSymbolDraw.group);
  52047. },
  52048. updateTransform: function (seriesModel, ecModel, api) {
  52049. var data = seriesModel.getData();
  52050. this.group.dirty();
  52051. var res = pointsLayout().reset(seriesModel);
  52052. if (res.progress) {
  52053. res.progress({ start: 0, end: data.count() }, data);
  52054. }
  52055. this._symbolDraw.updateLayout(data);
  52056. },
  52057. _updateGroupTransform: function (seriesModel) {
  52058. var coordSys = seriesModel.coordinateSystem;
  52059. if (coordSys && coordSys.getRoamTransform) {
  52060. this.group.transform = clone$2(coordSys.getRoamTransform());
  52061. this.group.decomposeTransform();
  52062. }
  52063. },
  52064. remove: function (ecModel, api) {
  52065. this._symbolDraw && this._symbolDraw.remove(api);
  52066. },
  52067. dispose: function () {}
  52068. });
  52069. /*
  52070. * Licensed to the Apache Software Foundation (ASF) under one
  52071. * or more contributor license agreements. See the NOTICE file
  52072. * distributed with this work for additional information
  52073. * regarding copyright ownership. The ASF licenses this file
  52074. * to you under the Apache License, Version 2.0 (the
  52075. * "License"); you may not use this file except in compliance
  52076. * with the License. You may obtain a copy of the License at
  52077. *
  52078. * http://www.apache.org/licenses/LICENSE-2.0
  52079. *
  52080. * Unless required by applicable law or agreed to in writing,
  52081. * software distributed under the License is distributed on an
  52082. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52083. * KIND, either express or implied. See the License for the
  52084. * specific language governing permissions and limitations
  52085. * under the License.
  52086. */
  52087. registerVisual(visualSymbol('effectScatter', 'circle'));
  52088. registerLayout(pointsLayout('effectScatter'));
  52089. /*
  52090. * Licensed to the Apache Software Foundation (ASF) under one
  52091. * or more contributor license agreements. See the NOTICE file
  52092. * distributed with this work for additional information
  52093. * regarding copyright ownership. The ASF licenses this file
  52094. * to you under the Apache License, Version 2.0 (the
  52095. * "License"); you may not use this file except in compliance
  52096. * with the License. You may obtain a copy of the License at
  52097. *
  52098. * http://www.apache.org/licenses/LICENSE-2.0
  52099. *
  52100. * Unless required by applicable law or agreed to in writing,
  52101. * software distributed under the License is distributed on an
  52102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52103. * KIND, either express or implied. See the License for the
  52104. * specific language governing permissions and limitations
  52105. * under the License.
  52106. */
  52107. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  52108. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  52109. function compatEc2(seriesOpt) {
  52110. var data = seriesOpt.data;
  52111. if (data && data[0] && data[0][0] && data[0][0].coord) {
  52112. if (__DEV__) {
  52113. console.warn('Lines data configuration has been changed to'
  52114. + ' { coords:[[1,2],[2,3]] }');
  52115. }
  52116. seriesOpt.data = map(data, function (itemOpt) {
  52117. var coords = [
  52118. itemOpt[0].coord, itemOpt[1].coord
  52119. ];
  52120. var target = {
  52121. coords: coords
  52122. };
  52123. if (itemOpt[0].name) {
  52124. target.fromName = itemOpt[0].name;
  52125. }
  52126. if (itemOpt[1].name) {
  52127. target.toName = itemOpt[1].name;
  52128. }
  52129. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  52130. });
  52131. }
  52132. }
  52133. var LinesSeries = SeriesModel.extend({
  52134. type: 'series.lines',
  52135. dependencies: ['grid', 'polar'],
  52136. visualColorAccessPath: 'lineStyle.color',
  52137. init: function (option) {
  52138. // The input data may be null/undefined.
  52139. option.data = option.data || [];
  52140. // Not using preprocessor because mergeOption may not have series.type
  52141. compatEc2(option);
  52142. var result = this._processFlatCoordsArray(option.data);
  52143. this._flatCoords = result.flatCoords;
  52144. this._flatCoordsOffset = result.flatCoordsOffset;
  52145. if (result.flatCoords) {
  52146. option.data = new Float32Array(result.count);
  52147. }
  52148. LinesSeries.superApply(this, 'init', arguments);
  52149. },
  52150. mergeOption: function (option) {
  52151. // The input data may be null/undefined.
  52152. option.data = option.data || [];
  52153. compatEc2(option);
  52154. if (option.data) {
  52155. // Only update when have option data to merge.
  52156. var result = this._processFlatCoordsArray(option.data);
  52157. this._flatCoords = result.flatCoords;
  52158. this._flatCoordsOffset = result.flatCoordsOffset;
  52159. if (result.flatCoords) {
  52160. option.data = new Float32Array(result.count);
  52161. }
  52162. }
  52163. LinesSeries.superApply(this, 'mergeOption', arguments);
  52164. },
  52165. appendData: function (params) {
  52166. var result = this._processFlatCoordsArray(params.data);
  52167. if (result.flatCoords) {
  52168. if (!this._flatCoords) {
  52169. this._flatCoords = result.flatCoords;
  52170. this._flatCoordsOffset = result.flatCoordsOffset;
  52171. }
  52172. else {
  52173. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  52174. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  52175. }
  52176. params.data = new Float32Array(result.count);
  52177. }
  52178. this.getRawData().appendData(params.data);
  52179. },
  52180. _getCoordsFromItemModel: function (idx) {
  52181. var itemModel = this.getData().getItemModel(idx);
  52182. var coords = (itemModel.option instanceof Array)
  52183. ? itemModel.option : itemModel.getShallow('coords');
  52184. if (__DEV__) {
  52185. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  52186. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  52187. }
  52188. }
  52189. return coords;
  52190. },
  52191. getLineCoordsCount: function (idx) {
  52192. if (this._flatCoordsOffset) {
  52193. return this._flatCoordsOffset[idx * 2 + 1];
  52194. }
  52195. else {
  52196. return this._getCoordsFromItemModel(idx).length;
  52197. }
  52198. },
  52199. getLineCoords: function (idx, out) {
  52200. if (this._flatCoordsOffset) {
  52201. var offset = this._flatCoordsOffset[idx * 2];
  52202. var len = this._flatCoordsOffset[idx * 2 + 1];
  52203. for (var i = 0; i < len; i++) {
  52204. out[i] = out[i] || [];
  52205. out[i][0] = this._flatCoords[offset + i * 2];
  52206. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  52207. }
  52208. return len;
  52209. }
  52210. else {
  52211. var coords = this._getCoordsFromItemModel(idx);
  52212. for (var i = 0; i < coords.length; i++) {
  52213. out[i] = out[i] || [];
  52214. out[i][0] = coords[i][0];
  52215. out[i][1] = coords[i][1];
  52216. }
  52217. return coords.length;
  52218. }
  52219. },
  52220. _processFlatCoordsArray: function (data) {
  52221. var startOffset = 0;
  52222. if (this._flatCoords) {
  52223. startOffset = this._flatCoords.length;
  52224. }
  52225. // Stored as a typed array. In format
  52226. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  52227. if (typeof data[0] === 'number') {
  52228. var len = data.length;
  52229. // Store offset and len of each segment
  52230. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  52231. var coordsStorage = new Float64Arr(len);
  52232. var coordsCursor = 0;
  52233. var offsetCursor = 0;
  52234. var dataCount = 0;
  52235. for (var i = 0; i < len;) {
  52236. dataCount++;
  52237. var count = data[i++];
  52238. // Offset
  52239. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  52240. // Len
  52241. coordsOffsetAndLenStorage[offsetCursor++] = count;
  52242. for (var k = 0; k < count; k++) {
  52243. var x = data[i++];
  52244. var y = data[i++];
  52245. coordsStorage[coordsCursor++] = x;
  52246. coordsStorage[coordsCursor++] = y;
  52247. if (i > len) {
  52248. if (__DEV__) {
  52249. throw new Error('Invalid data format.');
  52250. }
  52251. }
  52252. }
  52253. }
  52254. return {
  52255. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  52256. flatCoords: coordsStorage,
  52257. count: dataCount
  52258. };
  52259. }
  52260. return {
  52261. flatCoordsOffset: null,
  52262. flatCoords: null,
  52263. count: data.length
  52264. };
  52265. },
  52266. getInitialData: function (option, ecModel) {
  52267. if (__DEV__) {
  52268. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  52269. if (!CoordSys) {
  52270. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  52271. }
  52272. }
  52273. var lineData = new List(['value'], this);
  52274. lineData.hasItemOption = false;
  52275. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  52276. // dataItem is simply coords
  52277. if (dataItem instanceof Array) {
  52278. return NaN;
  52279. }
  52280. else {
  52281. lineData.hasItemOption = true;
  52282. var value = dataItem.value;
  52283. if (value != null) {
  52284. return value instanceof Array ? value[dimIndex] : value;
  52285. }
  52286. }
  52287. });
  52288. return lineData;
  52289. },
  52290. formatTooltip: function (dataIndex) {
  52291. var data = this.getData();
  52292. var itemModel = data.getItemModel(dataIndex);
  52293. var name = itemModel.get('name');
  52294. if (name) {
  52295. return name;
  52296. }
  52297. var fromName = itemModel.get('fromName');
  52298. var toName = itemModel.get('toName');
  52299. var html = [];
  52300. fromName != null && html.push(fromName);
  52301. toName != null && html.push(toName);
  52302. return encodeHTML(html.join(' > '));
  52303. },
  52304. preventIncremental: function () {
  52305. return !!this.get('effect.show');
  52306. },
  52307. getProgressive: function () {
  52308. var progressive = this.option.progressive;
  52309. if (progressive == null) {
  52310. return this.option.large ? 1e4 : this.get('progressive');
  52311. }
  52312. return progressive;
  52313. },
  52314. getProgressiveThreshold: function () {
  52315. var progressiveThreshold = this.option.progressiveThreshold;
  52316. if (progressiveThreshold == null) {
  52317. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  52318. }
  52319. return progressiveThreshold;
  52320. },
  52321. defaultOption: {
  52322. coordinateSystem: 'geo',
  52323. zlevel: 0,
  52324. z: 2,
  52325. legendHoverLink: true,
  52326. hoverAnimation: true,
  52327. // Cartesian coordinate system
  52328. xAxisIndex: 0,
  52329. yAxisIndex: 0,
  52330. symbol: ['none', 'none'],
  52331. symbolSize: [10, 10],
  52332. // Geo coordinate system
  52333. geoIndex: 0,
  52334. effect: {
  52335. show: false,
  52336. period: 4,
  52337. // Animation delay. support callback
  52338. // delay: 0,
  52339. // If move with constant speed px/sec
  52340. // period will be ignored if this property is > 0,
  52341. constantSpeed: 0,
  52342. symbol: 'circle',
  52343. symbolSize: 3,
  52344. loop: true,
  52345. // Length of trail, 0 - 1
  52346. trailLength: 0.2
  52347. // Same with lineStyle.color
  52348. // color
  52349. },
  52350. large: false,
  52351. // Available when large is true
  52352. largeThreshold: 2000,
  52353. // If lines are polyline
  52354. // polyline not support curveness, label, animation
  52355. polyline: false,
  52356. label: {
  52357. show: false,
  52358. position: 'end'
  52359. // distance: 5,
  52360. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  52361. },
  52362. lineStyle: {
  52363. opacity: 0.5
  52364. }
  52365. }
  52366. });
  52367. /*
  52368. * Licensed to the Apache Software Foundation (ASF) under one
  52369. * or more contributor license agreements. See the NOTICE file
  52370. * distributed with this work for additional information
  52371. * regarding copyright ownership. The ASF licenses this file
  52372. * to you under the Apache License, Version 2.0 (the
  52373. * "License"); you may not use this file except in compliance
  52374. * with the License. You may obtain a copy of the License at
  52375. *
  52376. * http://www.apache.org/licenses/LICENSE-2.0
  52377. *
  52378. * Unless required by applicable law or agreed to in writing,
  52379. * software distributed under the License is distributed on an
  52380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52381. * KIND, either express or implied. See the License for the
  52382. * specific language governing permissions and limitations
  52383. * under the License.
  52384. */
  52385. /**
  52386. * Provide effect for line
  52387. * @module echarts/chart/helper/EffectLine
  52388. */
  52389. /**
  52390. * @constructor
  52391. * @extends {module:zrender/graphic/Group}
  52392. * @alias {module:echarts/chart/helper/Line}
  52393. */
  52394. function EffectLine(lineData, idx, seriesScope) {
  52395. Group.call(this);
  52396. this.add(this.createLine(lineData, idx, seriesScope));
  52397. this._updateEffectSymbol(lineData, idx);
  52398. }
  52399. var effectLineProto = EffectLine.prototype;
  52400. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  52401. return new Line$1(lineData, idx, seriesScope);
  52402. };
  52403. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  52404. var itemModel = lineData.getItemModel(idx);
  52405. var effectModel = itemModel.getModel('effect');
  52406. var size = effectModel.get('symbolSize');
  52407. var symbolType = effectModel.get('symbol');
  52408. if (!isArray(size)) {
  52409. size = [size, size];
  52410. }
  52411. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  52412. var symbol = this.childAt(1);
  52413. if (this._symbolType !== symbolType) {
  52414. // Remove previous
  52415. this.remove(symbol);
  52416. symbol = createSymbol(
  52417. symbolType, -0.5, -0.5, 1, 1, color
  52418. );
  52419. symbol.z2 = 100;
  52420. symbol.culling = true;
  52421. this.add(symbol);
  52422. }
  52423. // Symbol may be removed if loop is false
  52424. if (!symbol) {
  52425. return;
  52426. }
  52427. // Shadow color is same with color in default
  52428. symbol.setStyle('shadowColor', color);
  52429. symbol.setStyle(effectModel.getItemStyle(['color']));
  52430. symbol.attr('scale', size);
  52431. symbol.setColor(color);
  52432. symbol.attr('scale', size);
  52433. this._symbolType = symbolType;
  52434. this._updateEffectAnimation(lineData, effectModel, idx);
  52435. };
  52436. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  52437. var symbol = this.childAt(1);
  52438. if (!symbol) {
  52439. return;
  52440. }
  52441. var self = this;
  52442. var points = lineData.getItemLayout(idx);
  52443. var period = effectModel.get('period') * 1000;
  52444. var loop = effectModel.get('loop');
  52445. var constantSpeed = effectModel.get('constantSpeed');
  52446. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  52447. return idx / lineData.count() * period / 3;
  52448. });
  52449. var isDelayFunc = typeof delayExpr === 'function';
  52450. // Ignore when updating
  52451. symbol.ignore = true;
  52452. this.updateAnimationPoints(symbol, points);
  52453. if (constantSpeed > 0) {
  52454. period = this.getLineLength(symbol) / constantSpeed * 1000;
  52455. }
  52456. if (period !== this._period || loop !== this._loop) {
  52457. symbol.stopAnimation();
  52458. var delay = delayExpr;
  52459. if (isDelayFunc) {
  52460. delay = delayExpr(idx);
  52461. }
  52462. if (symbol.__t > 0) {
  52463. delay = -period * symbol.__t;
  52464. }
  52465. symbol.__t = 0;
  52466. var animator = symbol.animate('', loop)
  52467. .when(period, {
  52468. __t: 1
  52469. })
  52470. .delay(delay)
  52471. .during(function () {
  52472. self.updateSymbolPosition(symbol);
  52473. });
  52474. if (!loop) {
  52475. animator.done(function () {
  52476. self.remove(symbol);
  52477. });
  52478. }
  52479. animator.start();
  52480. }
  52481. this._period = period;
  52482. this._loop = loop;
  52483. };
  52484. effectLineProto.getLineLength = function (symbol) {
  52485. // Not so accurate
  52486. return (dist(symbol.__p1, symbol.__cp1)
  52487. + dist(symbol.__cp1, symbol.__p2));
  52488. };
  52489. effectLineProto.updateAnimationPoints = function (symbol, points) {
  52490. symbol.__p1 = points[0];
  52491. symbol.__p2 = points[1];
  52492. symbol.__cp1 = points[2] || [
  52493. (points[0][0] + points[1][0]) / 2,
  52494. (points[0][1] + points[1][1]) / 2
  52495. ];
  52496. };
  52497. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  52498. this.childAt(0).updateData(lineData, idx, seriesScope);
  52499. this._updateEffectSymbol(lineData, idx);
  52500. };
  52501. effectLineProto.updateSymbolPosition = function (symbol) {
  52502. var p1 = symbol.__p1;
  52503. var p2 = symbol.__p2;
  52504. var cp1 = symbol.__cp1;
  52505. var t = symbol.__t;
  52506. var pos = symbol.position;
  52507. var quadraticAt$$1 = quadraticAt;
  52508. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  52509. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  52510. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  52511. // Tangent
  52512. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  52513. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  52514. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  52515. symbol.ignore = false;
  52516. };
  52517. effectLineProto.updateLayout = function (lineData, idx) {
  52518. this.childAt(0).updateLayout(lineData, idx);
  52519. var effectModel = lineData.getItemModel(idx).getModel('effect');
  52520. this._updateEffectAnimation(lineData, effectModel, idx);
  52521. };
  52522. inherits(EffectLine, Group);
  52523. /*
  52524. * Licensed to the Apache Software Foundation (ASF) under one
  52525. * or more contributor license agreements. See the NOTICE file
  52526. * distributed with this work for additional information
  52527. * regarding copyright ownership. The ASF licenses this file
  52528. * to you under the Apache License, Version 2.0 (the
  52529. * "License"); you may not use this file except in compliance
  52530. * with the License. You may obtain a copy of the License at
  52531. *
  52532. * http://www.apache.org/licenses/LICENSE-2.0
  52533. *
  52534. * Unless required by applicable law or agreed to in writing,
  52535. * software distributed under the License is distributed on an
  52536. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52537. * KIND, either express or implied. See the License for the
  52538. * specific language governing permissions and limitations
  52539. * under the License.
  52540. */
  52541. /**
  52542. * @module echarts/chart/helper/Line
  52543. */
  52544. /**
  52545. * @constructor
  52546. * @extends {module:zrender/graphic/Group}
  52547. * @alias {module:echarts/chart/helper/Polyline}
  52548. */
  52549. function Polyline$2(lineData, idx, seriesScope) {
  52550. Group.call(this);
  52551. this._createPolyline(lineData, idx, seriesScope);
  52552. }
  52553. var polylineProto = Polyline$2.prototype;
  52554. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  52555. // var seriesModel = lineData.hostModel;
  52556. var points = lineData.getItemLayout(idx);
  52557. var line = new Polyline({
  52558. shape: {
  52559. points: points
  52560. }
  52561. });
  52562. this.add(line);
  52563. this._updateCommonStl(lineData, idx, seriesScope);
  52564. };
  52565. polylineProto.updateData = function (lineData, idx, seriesScope) {
  52566. var seriesModel = lineData.hostModel;
  52567. var line = this.childAt(0);
  52568. var target = {
  52569. shape: {
  52570. points: lineData.getItemLayout(idx)
  52571. }
  52572. };
  52573. updateProps(line, target, seriesModel, idx);
  52574. this._updateCommonStl(lineData, idx, seriesScope);
  52575. };
  52576. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  52577. var line = this.childAt(0);
  52578. var itemModel = lineData.getItemModel(idx);
  52579. var visualColor = lineData.getItemVisual(idx, 'color');
  52580. var lineStyle = seriesScope && seriesScope.lineStyle;
  52581. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  52582. if (!seriesScope || lineData.hasItemOption) {
  52583. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  52584. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  52585. }
  52586. line.useStyle(defaults(
  52587. {
  52588. strokeNoScale: true,
  52589. fill: 'none',
  52590. stroke: visualColor
  52591. },
  52592. lineStyle
  52593. ));
  52594. line.hoverStyle = hoverLineStyle;
  52595. setHoverStyle(this);
  52596. };
  52597. polylineProto.updateLayout = function (lineData, idx) {
  52598. var polyline = this.childAt(0);
  52599. polyline.setShape('points', lineData.getItemLayout(idx));
  52600. };
  52601. inherits(Polyline$2, Group);
  52602. /*
  52603. * Licensed to the Apache Software Foundation (ASF) under one
  52604. * or more contributor license agreements. See the NOTICE file
  52605. * distributed with this work for additional information
  52606. * regarding copyright ownership. The ASF licenses this file
  52607. * to you under the Apache License, Version 2.0 (the
  52608. * "License"); you may not use this file except in compliance
  52609. * with the License. You may obtain a copy of the License at
  52610. *
  52611. * http://www.apache.org/licenses/LICENSE-2.0
  52612. *
  52613. * Unless required by applicable law or agreed to in writing,
  52614. * software distributed under the License is distributed on an
  52615. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52616. * KIND, either express or implied. See the License for the
  52617. * specific language governing permissions and limitations
  52618. * under the License.
  52619. */
  52620. /**
  52621. * Provide effect for line
  52622. * @module echarts/chart/helper/EffectLine
  52623. */
  52624. /**
  52625. * @constructor
  52626. * @extends {module:echarts/chart/helper/EffectLine}
  52627. * @alias {module:echarts/chart/helper/Polyline}
  52628. */
  52629. function EffectPolyline(lineData, idx, seriesScope) {
  52630. EffectLine.call(this, lineData, idx, seriesScope);
  52631. this._lastFrame = 0;
  52632. this._lastFramePercent = 0;
  52633. }
  52634. var effectPolylineProto = EffectPolyline.prototype;
  52635. // Overwrite
  52636. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  52637. return new Polyline$2(lineData, idx, seriesScope);
  52638. };
  52639. // Overwrite
  52640. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  52641. this._points = points;
  52642. var accLenArr = [0];
  52643. var len$$1 = 0;
  52644. for (var i = 1; i < points.length; i++) {
  52645. var p1 = points[i - 1];
  52646. var p2 = points[i];
  52647. len$$1 += dist(p1, p2);
  52648. accLenArr.push(len$$1);
  52649. }
  52650. if (len$$1 === 0) {
  52651. return;
  52652. }
  52653. for (var i = 0; i < accLenArr.length; i++) {
  52654. accLenArr[i] /= len$$1;
  52655. }
  52656. this._offsets = accLenArr;
  52657. this._length = len$$1;
  52658. };
  52659. // Overwrite
  52660. effectPolylineProto.getLineLength = function (symbol) {
  52661. return this._length;
  52662. };
  52663. // Overwrite
  52664. effectPolylineProto.updateSymbolPosition = function (symbol) {
  52665. var t = symbol.__t;
  52666. var points = this._points;
  52667. var offsets = this._offsets;
  52668. var len$$1 = points.length;
  52669. if (!offsets) {
  52670. // Has length 0
  52671. return;
  52672. }
  52673. var lastFrame = this._lastFrame;
  52674. var frame;
  52675. if (t < this._lastFramePercent) {
  52676. // Start from the next frame
  52677. // PENDING start from lastFrame ?
  52678. var start = Math.min(lastFrame + 1, len$$1 - 1);
  52679. for (frame = start; frame >= 0; frame--) {
  52680. if (offsets[frame] <= t) {
  52681. break;
  52682. }
  52683. }
  52684. // PENDING really need to do this ?
  52685. frame = Math.min(frame, len$$1 - 2);
  52686. }
  52687. else {
  52688. for (var frame = lastFrame; frame < len$$1; frame++) {
  52689. if (offsets[frame] > t) {
  52690. break;
  52691. }
  52692. }
  52693. frame = Math.min(frame - 1, len$$1 - 2);
  52694. }
  52695. lerp(
  52696. symbol.position, points[frame], points[frame + 1],
  52697. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  52698. );
  52699. var tx = points[frame + 1][0] - points[frame][0];
  52700. var ty = points[frame + 1][1] - points[frame][1];
  52701. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  52702. this._lastFrame = frame;
  52703. this._lastFramePercent = t;
  52704. symbol.ignore = false;
  52705. };
  52706. inherits(EffectPolyline, EffectLine);
  52707. /*
  52708. * Licensed to the Apache Software Foundation (ASF) under one
  52709. * or more contributor license agreements. See the NOTICE file
  52710. * distributed with this work for additional information
  52711. * regarding copyright ownership. The ASF licenses this file
  52712. * to you under the Apache License, Version 2.0 (the
  52713. * "License"); you may not use this file except in compliance
  52714. * with the License. You may obtain a copy of the License at
  52715. *
  52716. * http://www.apache.org/licenses/LICENSE-2.0
  52717. *
  52718. * Unless required by applicable law or agreed to in writing,
  52719. * software distributed under the License is distributed on an
  52720. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52721. * KIND, either express or implied. See the License for the
  52722. * specific language governing permissions and limitations
  52723. * under the License.
  52724. */
  52725. // TODO Batch by color
  52726. var LargeLineShape = extendShape({
  52727. shape: {
  52728. polyline: false,
  52729. curveness: 0,
  52730. segs: []
  52731. },
  52732. buildPath: function (path, shape) {
  52733. var segs = shape.segs;
  52734. var curveness = shape.curveness;
  52735. if (shape.polyline) {
  52736. for (var i = 0; i < segs.length;) {
  52737. var count = segs[i++];
  52738. if (count > 0) {
  52739. path.moveTo(segs[i++], segs[i++]);
  52740. for (var k = 1; k < count; k++) {
  52741. path.lineTo(segs[i++], segs[i++]);
  52742. }
  52743. }
  52744. }
  52745. }
  52746. else {
  52747. for (var i = 0; i < segs.length;) {
  52748. var x0 = segs[i++];
  52749. var y0 = segs[i++];
  52750. var x1 = segs[i++];
  52751. var y1 = segs[i++];
  52752. path.moveTo(x0, y0);
  52753. if (curveness > 0) {
  52754. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  52755. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  52756. path.quadraticCurveTo(x2, y2, x1, y1);
  52757. }
  52758. else {
  52759. path.lineTo(x1, y1);
  52760. }
  52761. }
  52762. }
  52763. },
  52764. findDataIndex: function (x, y) {
  52765. var shape = this.shape;
  52766. var segs = shape.segs;
  52767. var curveness = shape.curveness;
  52768. if (shape.polyline) {
  52769. var dataIndex = 0;
  52770. for (var i = 0; i < segs.length;) {
  52771. var count = segs[i++];
  52772. if (count > 0) {
  52773. var x0 = segs[i++];
  52774. var y0 = segs[i++];
  52775. for (var k = 1; k < count; k++) {
  52776. var x1 = segs[i++];
  52777. var y1 = segs[i++];
  52778. if (containStroke$1(x0, y0, x1, y1)) {
  52779. return dataIndex;
  52780. }
  52781. }
  52782. }
  52783. dataIndex++;
  52784. }
  52785. }
  52786. else {
  52787. var dataIndex = 0;
  52788. for (var i = 0; i < segs.length;) {
  52789. var x0 = segs[i++];
  52790. var y0 = segs[i++];
  52791. var x1 = segs[i++];
  52792. var y1 = segs[i++];
  52793. if (curveness > 0) {
  52794. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  52795. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  52796. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  52797. return dataIndex;
  52798. }
  52799. }
  52800. else {
  52801. if (containStroke$1(x0, y0, x1, y1)) {
  52802. return dataIndex;
  52803. }
  52804. }
  52805. dataIndex++;
  52806. }
  52807. }
  52808. return -1;
  52809. }
  52810. });
  52811. function LargeLineDraw() {
  52812. this.group = new Group();
  52813. }
  52814. var largeLineProto = LargeLineDraw.prototype;
  52815. largeLineProto.isPersistent = function () {
  52816. return !this._incremental;
  52817. };
  52818. /**
  52819. * Update symbols draw by new data
  52820. * @param {module:echarts/data/List} data
  52821. */
  52822. largeLineProto.updateData = function (data) {
  52823. this.group.removeAll();
  52824. var lineEl = new LargeLineShape({
  52825. rectHover: true,
  52826. cursor: 'default'
  52827. });
  52828. lineEl.setShape({
  52829. segs: data.getLayout('linesPoints')
  52830. });
  52831. this._setCommon(lineEl, data);
  52832. // Add back
  52833. this.group.add(lineEl);
  52834. this._incremental = null;
  52835. };
  52836. /**
  52837. * @override
  52838. */
  52839. largeLineProto.incrementalPrepareUpdate = function (data) {
  52840. this.group.removeAll();
  52841. this._clearIncremental();
  52842. if (data.count() > 5e5) {
  52843. if (!this._incremental) {
  52844. this._incremental = new IncrementalDisplayble({
  52845. silent: true
  52846. });
  52847. }
  52848. this.group.add(this._incremental);
  52849. }
  52850. else {
  52851. this._incremental = null;
  52852. }
  52853. };
  52854. /**
  52855. * @override
  52856. */
  52857. largeLineProto.incrementalUpdate = function (taskParams, data) {
  52858. var lineEl = new LargeLineShape();
  52859. lineEl.setShape({
  52860. segs: data.getLayout('linesPoints')
  52861. });
  52862. this._setCommon(lineEl, data, !!this._incremental);
  52863. if (!this._incremental) {
  52864. lineEl.rectHover = true;
  52865. lineEl.cursor = 'default';
  52866. lineEl.__startIndex = taskParams.start;
  52867. this.group.add(lineEl);
  52868. }
  52869. else {
  52870. this._incremental.addDisplayable(lineEl, true);
  52871. }
  52872. };
  52873. /**
  52874. * @override
  52875. */
  52876. largeLineProto.remove = function () {
  52877. this._clearIncremental();
  52878. this._incremental = null;
  52879. this.group.removeAll();
  52880. };
  52881. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  52882. var hostModel = data.hostModel;
  52883. lineEl.setShape({
  52884. polyline: hostModel.get('polyline'),
  52885. curveness: hostModel.get('lineStyle.curveness')
  52886. });
  52887. lineEl.useStyle(
  52888. hostModel.getModel('lineStyle').getLineStyle()
  52889. );
  52890. lineEl.style.strokeNoScale = true;
  52891. var visualColor = data.getVisual('color');
  52892. if (visualColor) {
  52893. lineEl.setStyle('stroke', visualColor);
  52894. }
  52895. lineEl.setStyle('fill');
  52896. if (!isIncremental) {
  52897. // Enable tooltip
  52898. // PENDING May have performance issue when path is extremely large
  52899. lineEl.seriesIndex = hostModel.seriesIndex;
  52900. lineEl.on('mousemove', function (e) {
  52901. lineEl.dataIndex = null;
  52902. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  52903. if (dataIndex > 0) {
  52904. // Provide dataIndex for tooltip
  52905. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  52906. }
  52907. });
  52908. }
  52909. };
  52910. largeLineProto._clearIncremental = function () {
  52911. var incremental = this._incremental;
  52912. if (incremental) {
  52913. incremental.clearDisplaybles();
  52914. }
  52915. };
  52916. /*
  52917. * Licensed to the Apache Software Foundation (ASF) under one
  52918. * or more contributor license agreements. See the NOTICE file
  52919. * distributed with this work for additional information
  52920. * regarding copyright ownership. The ASF licenses this file
  52921. * to you under the Apache License, Version 2.0 (the
  52922. * "License"); you may not use this file except in compliance
  52923. * with the License. You may obtain a copy of the License at
  52924. *
  52925. * http://www.apache.org/licenses/LICENSE-2.0
  52926. *
  52927. * Unless required by applicable law or agreed to in writing,
  52928. * software distributed under the License is distributed on an
  52929. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52930. * KIND, either express or implied. See the License for the
  52931. * specific language governing permissions and limitations
  52932. * under the License.
  52933. */
  52934. var linesLayout = {
  52935. seriesType: 'lines',
  52936. plan: createRenderPlanner(),
  52937. reset: function (seriesModel) {
  52938. var coordSys = seriesModel.coordinateSystem;
  52939. var isPolyline = seriesModel.get('polyline');
  52940. var isLarge = seriesModel.pipelineContext.large;
  52941. function progress(params, lineData) {
  52942. var lineCoords = [];
  52943. if (isLarge) {
  52944. var points;
  52945. var segCount = params.end - params.start;
  52946. if (isPolyline) {
  52947. var totalCoordsCount = 0;
  52948. for (var i = params.start; i < params.end; i++) {
  52949. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  52950. }
  52951. points = new Float32Array(segCount + totalCoordsCount * 2);
  52952. }
  52953. else {
  52954. points = new Float32Array(segCount * 4);
  52955. }
  52956. var offset = 0;
  52957. var pt = [];
  52958. for (var i = params.start; i < params.end; i++) {
  52959. var len = seriesModel.getLineCoords(i, lineCoords);
  52960. if (isPolyline) {
  52961. points[offset++] = len;
  52962. }
  52963. for (var k = 0; k < len; k++) {
  52964. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  52965. points[offset++] = pt[0];
  52966. points[offset++] = pt[1];
  52967. }
  52968. }
  52969. lineData.setLayout('linesPoints', points);
  52970. }
  52971. else {
  52972. for (var i = params.start; i < params.end; i++) {
  52973. var itemModel = lineData.getItemModel(i);
  52974. var len = seriesModel.getLineCoords(i, lineCoords);
  52975. var pts = [];
  52976. if (isPolyline) {
  52977. for (var j = 0; j < len; j++) {
  52978. pts.push(coordSys.dataToPoint(lineCoords[j]));
  52979. }
  52980. }
  52981. else {
  52982. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  52983. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  52984. var curveness = itemModel.get('lineStyle.curveness');
  52985. if (+curveness) {
  52986. pts[2] = [
  52987. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  52988. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  52989. ];
  52990. }
  52991. }
  52992. lineData.setItemLayout(i, pts);
  52993. }
  52994. }
  52995. }
  52996. return { progress: progress };
  52997. }
  52998. };
  52999. /*
  53000. * Licensed to the Apache Software Foundation (ASF) under one
  53001. * or more contributor license agreements. See the NOTICE file
  53002. * distributed with this work for additional information
  53003. * regarding copyright ownership. The ASF licenses this file
  53004. * to you under the Apache License, Version 2.0 (the
  53005. * "License"); you may not use this file except in compliance
  53006. * with the License. You may obtain a copy of the License at
  53007. *
  53008. * http://www.apache.org/licenses/LICENSE-2.0
  53009. *
  53010. * Unless required by applicable law or agreed to in writing,
  53011. * software distributed under the License is distributed on an
  53012. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53013. * KIND, either express or implied. See the License for the
  53014. * specific language governing permissions and limitations
  53015. * under the License.
  53016. */
  53017. extendChartView({
  53018. type: 'lines',
  53019. init: function () {},
  53020. render: function (seriesModel, ecModel, api) {
  53021. var data = seriesModel.getData();
  53022. var lineDraw = this._updateLineDraw(data, seriesModel);
  53023. var zlevel = seriesModel.get('zlevel');
  53024. var trailLength = seriesModel.get('effect.trailLength');
  53025. var zr = api.getZr();
  53026. // Avoid the drag cause ghost shadow
  53027. // FIXME Better way ?
  53028. // SVG doesn't support
  53029. var isSvg = zr.painter.getType() === 'svg';
  53030. if (!isSvg) {
  53031. zr.painter.getLayer(zlevel).clear(true);
  53032. }
  53033. // Config layer with motion blur
  53034. if (this._lastZlevel != null && !isSvg) {
  53035. zr.configLayer(this._lastZlevel, {
  53036. motionBlur: false
  53037. });
  53038. }
  53039. if (this._showEffect(seriesModel) && trailLength) {
  53040. if (__DEV__) {
  53041. var notInIndividual = false;
  53042. ecModel.eachSeries(function (otherSeriesModel) {
  53043. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  53044. notInIndividual = true;
  53045. }
  53046. });
  53047. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  53048. }
  53049. if (!isSvg) {
  53050. zr.configLayer(zlevel, {
  53051. motionBlur: true,
  53052. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  53053. });
  53054. }
  53055. }
  53056. lineDraw.updateData(data);
  53057. this._lastZlevel = zlevel;
  53058. this._finished = true;
  53059. },
  53060. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53061. var data = seriesModel.getData();
  53062. var lineDraw = this._updateLineDraw(data, seriesModel);
  53063. lineDraw.incrementalPrepareUpdate(data);
  53064. this._clearLayer(api);
  53065. this._finished = false;
  53066. },
  53067. incrementalRender: function (taskParams, seriesModel, ecModel) {
  53068. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  53069. this._finished = taskParams.end === seriesModel.getData().count();
  53070. },
  53071. updateTransform: function (seriesModel, ecModel, api) {
  53072. var data = seriesModel.getData();
  53073. var pipelineContext = seriesModel.pipelineContext;
  53074. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  53075. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  53076. return {
  53077. update: true
  53078. };
  53079. }
  53080. else {
  53081. // TODO Use same logic with ScatterView.
  53082. // Manually update layout
  53083. var res = linesLayout.reset(seriesModel);
  53084. if (res.progress) {
  53085. res.progress({ start: 0, end: data.count() }, data);
  53086. }
  53087. this._lineDraw.updateLayout();
  53088. this._clearLayer(api);
  53089. }
  53090. },
  53091. _updateLineDraw: function (data, seriesModel) {
  53092. var lineDraw = this._lineDraw;
  53093. var hasEffect = this._showEffect(seriesModel);
  53094. var isPolyline = !!seriesModel.get('polyline');
  53095. var pipelineContext = seriesModel.pipelineContext;
  53096. var isLargeDraw = pipelineContext.large;
  53097. if (__DEV__) {
  53098. if (hasEffect && isLargeDraw) {
  53099. console.warn('Large lines not support effect');
  53100. }
  53101. }
  53102. if (!lineDraw
  53103. || hasEffect !== this._hasEffet
  53104. || isPolyline !== this._isPolyline
  53105. || isLargeDraw !== this._isLargeDraw
  53106. ) {
  53107. if (lineDraw) {
  53108. lineDraw.remove();
  53109. }
  53110. lineDraw = this._lineDraw = isLargeDraw
  53111. ? new LargeLineDraw()
  53112. : new LineDraw(
  53113. isPolyline
  53114. ? (hasEffect ? EffectPolyline : Polyline$2)
  53115. : (hasEffect ? EffectLine : Line$1)
  53116. );
  53117. this._hasEffet = hasEffect;
  53118. this._isPolyline = isPolyline;
  53119. this._isLargeDraw = isLargeDraw;
  53120. this.group.removeAll();
  53121. }
  53122. this.group.add(lineDraw.group);
  53123. return lineDraw;
  53124. },
  53125. _showEffect: function (seriesModel) {
  53126. return !!seriesModel.get('effect.show');
  53127. },
  53128. _clearLayer: function (api) {
  53129. // Not use motion when dragging or zooming
  53130. var zr = api.getZr();
  53131. var isSvg = zr.painter.getType() === 'svg';
  53132. if (!isSvg && this._lastZlevel != null) {
  53133. zr.painter.getLayer(this._lastZlevel).clear(true);
  53134. }
  53135. },
  53136. remove: function (ecModel, api) {
  53137. this._lineDraw && this._lineDraw.remove();
  53138. this._lineDraw = null;
  53139. // Clear motion when lineDraw is removed
  53140. this._clearLayer(api);
  53141. },
  53142. dispose: function () {}
  53143. });
  53144. /*
  53145. * Licensed to the Apache Software Foundation (ASF) under one
  53146. * or more contributor license agreements. See the NOTICE file
  53147. * distributed with this work for additional information
  53148. * regarding copyright ownership. The ASF licenses this file
  53149. * to you under the Apache License, Version 2.0 (the
  53150. * "License"); you may not use this file except in compliance
  53151. * with the License. You may obtain a copy of the License at
  53152. *
  53153. * http://www.apache.org/licenses/LICENSE-2.0
  53154. *
  53155. * Unless required by applicable law or agreed to in writing,
  53156. * software distributed under the License is distributed on an
  53157. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53158. * KIND, either express or implied. See the License for the
  53159. * specific language governing permissions and limitations
  53160. * under the License.
  53161. */
  53162. function normalize$2(a) {
  53163. if (!(a instanceof Array)) {
  53164. a = [a, a];
  53165. }
  53166. return a;
  53167. }
  53168. var opacityQuery = 'lineStyle.opacity'.split('.');
  53169. var linesVisual = {
  53170. seriesType: 'lines',
  53171. reset: function (seriesModel, ecModel, api) {
  53172. var symbolType = normalize$2(seriesModel.get('symbol'));
  53173. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  53174. var data = seriesModel.getData();
  53175. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  53176. data.setVisual('toSymbol', symbolType && symbolType[1]);
  53177. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  53178. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  53179. data.setVisual('opacity', seriesModel.get(opacityQuery));
  53180. function dataEach(data, idx) {
  53181. var itemModel = data.getItemModel(idx);
  53182. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  53183. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  53184. var opacity = itemModel.get(opacityQuery);
  53185. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  53186. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  53187. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  53188. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  53189. data.setItemVisual(idx, 'opacity', opacity);
  53190. }
  53191. return {dataEach: data.hasItemOption ? dataEach : null};
  53192. }
  53193. };
  53194. /*
  53195. * Licensed to the Apache Software Foundation (ASF) under one
  53196. * or more contributor license agreements. See the NOTICE file
  53197. * distributed with this work for additional information
  53198. * regarding copyright ownership. The ASF licenses this file
  53199. * to you under the Apache License, Version 2.0 (the
  53200. * "License"); you may not use this file except in compliance
  53201. * with the License. You may obtain a copy of the License at
  53202. *
  53203. * http://www.apache.org/licenses/LICENSE-2.0
  53204. *
  53205. * Unless required by applicable law or agreed to in writing,
  53206. * software distributed under the License is distributed on an
  53207. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53208. * KIND, either express or implied. See the License for the
  53209. * specific language governing permissions and limitations
  53210. * under the License.
  53211. */
  53212. registerLayout(linesLayout);
  53213. registerVisual(linesVisual);
  53214. /*
  53215. * Licensed to the Apache Software Foundation (ASF) under one
  53216. * or more contributor license agreements. See the NOTICE file
  53217. * distributed with this work for additional information
  53218. * regarding copyright ownership. The ASF licenses this file
  53219. * to you under the Apache License, Version 2.0 (the
  53220. * "License"); you may not use this file except in compliance
  53221. * with the License. You may obtain a copy of the License at
  53222. *
  53223. * http://www.apache.org/licenses/LICENSE-2.0
  53224. *
  53225. * Unless required by applicable law or agreed to in writing,
  53226. * software distributed under the License is distributed on an
  53227. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53228. * KIND, either express or implied. See the License for the
  53229. * specific language governing permissions and limitations
  53230. * under the License.
  53231. */
  53232. SeriesModel.extend({
  53233. type: 'series.heatmap',
  53234. getInitialData: function (option, ecModel) {
  53235. return createListFromArray(this.getSource(), this, {
  53236. generateCoord: 'value'
  53237. });
  53238. },
  53239. preventIncremental: function () {
  53240. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  53241. if (coordSysCreator && coordSysCreator.dimensions) {
  53242. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  53243. }
  53244. },
  53245. defaultOption: {
  53246. // Cartesian2D or geo
  53247. coordinateSystem: 'cartesian2d',
  53248. zlevel: 0,
  53249. z: 2,
  53250. // Cartesian coordinate system
  53251. // xAxisIndex: 0,
  53252. // yAxisIndex: 0,
  53253. // Geo coordinate system
  53254. geoIndex: 0,
  53255. blurSize: 30,
  53256. pointSize: 20,
  53257. maxOpacity: 1,
  53258. minOpacity: 0
  53259. }
  53260. });
  53261. /*
  53262. * Licensed to the Apache Software Foundation (ASF) under one
  53263. * or more contributor license agreements. See the NOTICE file
  53264. * distributed with this work for additional information
  53265. * regarding copyright ownership. The ASF licenses this file
  53266. * to you under the Apache License, Version 2.0 (the
  53267. * "License"); you may not use this file except in compliance
  53268. * with the License. You may obtain a copy of the License at
  53269. *
  53270. * http://www.apache.org/licenses/LICENSE-2.0
  53271. *
  53272. * Unless required by applicable law or agreed to in writing,
  53273. * software distributed under the License is distributed on an
  53274. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53275. * KIND, either express or implied. See the License for the
  53276. * specific language governing permissions and limitations
  53277. * under the License.
  53278. */
  53279. /**
  53280. * @file defines echarts Heatmap Chart
  53281. * @author Ovilia (me@zhangwenli.com)
  53282. * Inspired by https://github.com/mourner/simpleheat
  53283. *
  53284. * @module
  53285. */
  53286. var GRADIENT_LEVELS = 256;
  53287. /**
  53288. * Heatmap Chart
  53289. *
  53290. * @class
  53291. */
  53292. function Heatmap() {
  53293. var canvas = createCanvas();
  53294. this.canvas = canvas;
  53295. this.blurSize = 30;
  53296. this.pointSize = 20;
  53297. this.maxOpacity = 1;
  53298. this.minOpacity = 0;
  53299. this._gradientPixels = {};
  53300. }
  53301. Heatmap.prototype = {
  53302. /**
  53303. * Renders Heatmap and returns the rendered canvas
  53304. * @param {Array} data array of data, each has x, y, value
  53305. * @param {number} width canvas width
  53306. * @param {number} height canvas height
  53307. */
  53308. update: function(data, width, height, normalize, colorFunc, isInRange) {
  53309. var brush = this._getBrush();
  53310. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  53311. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  53312. var r = this.pointSize + this.blurSize;
  53313. var canvas = this.canvas;
  53314. var ctx = canvas.getContext('2d');
  53315. var len = data.length;
  53316. canvas.width = width;
  53317. canvas.height = height;
  53318. for (var i = 0; i < len; ++i) {
  53319. var p = data[i];
  53320. var x = p[0];
  53321. var y = p[1];
  53322. var value = p[2];
  53323. // calculate alpha using value
  53324. var alpha = normalize(value);
  53325. // draw with the circle brush with alpha
  53326. ctx.globalAlpha = alpha;
  53327. ctx.drawImage(brush, x - r, y - r);
  53328. }
  53329. if (!canvas.width || !canvas.height) {
  53330. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  53331. // 'CanvasRenderingContext2D': The source height is 0."
  53332. return canvas;
  53333. }
  53334. // colorize the canvas using alpha value and set with gradient
  53335. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  53336. var pixels = imageData.data;
  53337. var offset = 0;
  53338. var pixelLen = pixels.length;
  53339. var minOpacity = this.minOpacity;
  53340. var maxOpacity = this.maxOpacity;
  53341. var diffOpacity = maxOpacity - minOpacity;
  53342. while(offset < pixelLen) {
  53343. var alpha = pixels[offset + 3] / 256;
  53344. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  53345. // Simple optimize to ignore the empty data
  53346. if (alpha > 0) {
  53347. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  53348. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  53349. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  53350. pixels[offset++] = gradient[gradientOffset];
  53351. pixels[offset++] = gradient[gradientOffset + 1];
  53352. pixels[offset++] = gradient[gradientOffset + 2];
  53353. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  53354. }
  53355. else {
  53356. offset += 4;
  53357. }
  53358. }
  53359. ctx.putImageData(imageData, 0, 0);
  53360. return canvas;
  53361. },
  53362. /**
  53363. * get canvas of a black circle brush used for canvas to draw later
  53364. * @private
  53365. * @returns {Object} circle brush canvas
  53366. */
  53367. _getBrush: function() {
  53368. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  53369. // set brush size
  53370. var r = this.pointSize + this.blurSize;
  53371. var d = r * 2;
  53372. brushCanvas.width = d;
  53373. brushCanvas.height = d;
  53374. var ctx = brushCanvas.getContext('2d');
  53375. ctx.clearRect(0, 0, d, d);
  53376. // in order to render shadow without the distinct circle,
  53377. // draw the distinct circle in an invisible place,
  53378. // and use shadowOffset to draw shadow in the center of the canvas
  53379. ctx.shadowOffsetX = d;
  53380. ctx.shadowBlur = this.blurSize;
  53381. // draw the shadow in black, and use alpha and shadow blur to generate
  53382. // color in color map
  53383. ctx.shadowColor = '#000';
  53384. // draw circle in the left to the canvas
  53385. ctx.beginPath();
  53386. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  53387. ctx.closePath();
  53388. ctx.fill();
  53389. return brushCanvas;
  53390. },
  53391. /**
  53392. * get gradient color map
  53393. * @private
  53394. */
  53395. _getGradient: function (data, colorFunc, state) {
  53396. var gradientPixels = this._gradientPixels;
  53397. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  53398. var color = [0, 0, 0, 0];
  53399. var off = 0;
  53400. for (var i = 0; i < 256; i++) {
  53401. colorFunc[state](i / 255, true, color);
  53402. pixelsSingleState[off++] = color[0];
  53403. pixelsSingleState[off++] = color[1];
  53404. pixelsSingleState[off++] = color[2];
  53405. pixelsSingleState[off++] = color[3];
  53406. }
  53407. return pixelsSingleState;
  53408. }
  53409. };
  53410. /*
  53411. * Licensed to the Apache Software Foundation (ASF) under one
  53412. * or more contributor license agreements. See the NOTICE file
  53413. * distributed with this work for additional information
  53414. * regarding copyright ownership. The ASF licenses this file
  53415. * to you under the Apache License, Version 2.0 (the
  53416. * "License"); you may not use this file except in compliance
  53417. * with the License. You may obtain a copy of the License at
  53418. *
  53419. * http://www.apache.org/licenses/LICENSE-2.0
  53420. *
  53421. * Unless required by applicable law or agreed to in writing,
  53422. * software distributed under the License is distributed on an
  53423. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53424. * KIND, either express or implied. See the License for the
  53425. * specific language governing permissions and limitations
  53426. * under the License.
  53427. */
  53428. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  53429. var dataSpan = dataExtent[1] - dataExtent[0];
  53430. pieceList = map(pieceList, function (piece) {
  53431. return {
  53432. interval: [
  53433. (piece.interval[0] - dataExtent[0]) / dataSpan,
  53434. (piece.interval[1] - dataExtent[0]) / dataSpan
  53435. ]
  53436. };
  53437. });
  53438. var len = pieceList.length;
  53439. var lastIndex = 0;
  53440. return function (val) {
  53441. // Try to find in the location of the last found
  53442. for (var i = lastIndex; i < len; i++) {
  53443. var interval = pieceList[i].interval;
  53444. if (interval[0] <= val && val <= interval[1]) {
  53445. lastIndex = i;
  53446. break;
  53447. }
  53448. }
  53449. if (i === len) { // Not found, back interation
  53450. for (var i = lastIndex - 1; i >= 0; i--) {
  53451. var interval = pieceList[i].interval;
  53452. if (interval[0] <= val && val <= interval[1]) {
  53453. lastIndex = i;
  53454. break;
  53455. }
  53456. }
  53457. }
  53458. return i >= 0 && i < len && selected[i];
  53459. };
  53460. }
  53461. function getIsInContinuousRange(dataExtent, range) {
  53462. var dataSpan = dataExtent[1] - dataExtent[0];
  53463. range = [
  53464. (range[0] - dataExtent[0]) / dataSpan,
  53465. (range[1] - dataExtent[0]) / dataSpan
  53466. ];
  53467. return function (val) {
  53468. return val >= range[0] && val <= range[1];
  53469. };
  53470. }
  53471. function isGeoCoordSys(coordSys) {
  53472. var dimensions = coordSys.dimensions;
  53473. // Not use coorSys.type === 'geo' because coordSys maybe extended
  53474. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  53475. }
  53476. extendChartView({
  53477. type: 'heatmap',
  53478. render: function (seriesModel, ecModel, api) {
  53479. var visualMapOfThisSeries;
  53480. ecModel.eachComponent('visualMap', function (visualMap) {
  53481. visualMap.eachTargetSeries(function (targetSeries) {
  53482. if (targetSeries === seriesModel) {
  53483. visualMapOfThisSeries = visualMap;
  53484. }
  53485. });
  53486. });
  53487. if (__DEV__) {
  53488. if (!visualMapOfThisSeries) {
  53489. throw new Error('Heatmap must use with visualMap');
  53490. }
  53491. }
  53492. this.group.removeAll();
  53493. this._incrementalDisplayable = null;
  53494. var coordSys = seriesModel.coordinateSystem;
  53495. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  53496. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  53497. }
  53498. else if (isGeoCoordSys(coordSys)) {
  53499. this._renderOnGeo(
  53500. coordSys, seriesModel, visualMapOfThisSeries, api
  53501. );
  53502. }
  53503. },
  53504. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53505. this.group.removeAll();
  53506. },
  53507. incrementalRender: function (params, seriesModel, ecModel, api) {
  53508. var coordSys = seriesModel.coordinateSystem;
  53509. if (coordSys) {
  53510. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  53511. }
  53512. },
  53513. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  53514. var coordSys = seriesModel.coordinateSystem;
  53515. var width;
  53516. var height;
  53517. if (coordSys.type === 'cartesian2d') {
  53518. var xAxis = coordSys.getAxis('x');
  53519. var yAxis = coordSys.getAxis('y');
  53520. if (__DEV__) {
  53521. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  53522. throw new Error('Heatmap on cartesian must have two category axes');
  53523. }
  53524. if (!(xAxis.onBand && yAxis.onBand)) {
  53525. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  53526. }
  53527. }
  53528. width = xAxis.getBandWidth();
  53529. height = yAxis.getBandWidth();
  53530. }
  53531. var group = this.group;
  53532. var data = seriesModel.getData();
  53533. var itemStyleQuery = 'itemStyle';
  53534. var hoverItemStyleQuery = 'emphasis.itemStyle';
  53535. var labelQuery = 'label';
  53536. var hoverLabelQuery = 'emphasis.label';
  53537. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  53538. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  53539. var labelModel = seriesModel.getModel(labelQuery);
  53540. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  53541. var coordSysType = coordSys.type;
  53542. var dataDims = coordSysType === 'cartesian2d'
  53543. ? [
  53544. data.mapDimension('x'),
  53545. data.mapDimension('y'),
  53546. data.mapDimension('value')
  53547. ]
  53548. : [
  53549. data.mapDimension('time'),
  53550. data.mapDimension('value')
  53551. ];
  53552. for (var idx = start; idx < end; idx++) {
  53553. var rect;
  53554. if (coordSysType === 'cartesian2d') {
  53555. // Ignore empty data
  53556. if (isNaN(data.get(dataDims[2], idx))) {
  53557. continue;
  53558. }
  53559. var point = coordSys.dataToPoint([
  53560. data.get(dataDims[0], idx),
  53561. data.get(dataDims[1], idx)
  53562. ]);
  53563. rect = new Rect({
  53564. shape: {
  53565. x: point[0] - width / 2,
  53566. y: point[1] - height / 2,
  53567. width: width,
  53568. height: height
  53569. },
  53570. style: {
  53571. fill: data.getItemVisual(idx, 'color'),
  53572. opacity: data.getItemVisual(idx, 'opacity')
  53573. }
  53574. });
  53575. }
  53576. else {
  53577. // Ignore empty data
  53578. if (isNaN(data.get(dataDims[1], idx))) {
  53579. continue;
  53580. }
  53581. rect = new Rect({
  53582. z2: 1,
  53583. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  53584. style: {
  53585. fill: data.getItemVisual(idx, 'color'),
  53586. opacity: data.getItemVisual(idx, 'opacity')
  53587. }
  53588. });
  53589. }
  53590. var itemModel = data.getItemModel(idx);
  53591. // Optimization for large datset
  53592. if (data.hasItemOption) {
  53593. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  53594. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  53595. labelModel = itemModel.getModel(labelQuery);
  53596. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  53597. }
  53598. var rawValue = seriesModel.getRawValue(idx);
  53599. var defaultText = '-';
  53600. if (rawValue && rawValue[2] != null) {
  53601. defaultText = rawValue[2];
  53602. }
  53603. setLabelStyle(
  53604. style, hoverStl, labelModel, hoverLabelModel,
  53605. {
  53606. labelFetcher: seriesModel,
  53607. labelDataIndex: idx,
  53608. defaultText: defaultText,
  53609. isRectText: true
  53610. }
  53611. );
  53612. rect.setStyle(style);
  53613. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  53614. rect.incremental = incremental;
  53615. // PENDING
  53616. if (incremental) {
  53617. // Rect must use hover layer if it's incremental.
  53618. rect.useHoverLayer = true;
  53619. }
  53620. group.add(rect);
  53621. data.setItemGraphicEl(idx, rect);
  53622. }
  53623. },
  53624. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  53625. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  53626. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  53627. // if (!visualMapping) {
  53628. // throw new Error('Data range must have color visuals');
  53629. // }
  53630. var data = seriesModel.getData();
  53631. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  53632. hmLayer.blurSize = seriesModel.get('blurSize');
  53633. hmLayer.pointSize = seriesModel.get('pointSize');
  53634. hmLayer.minOpacity = seriesModel.get('minOpacity');
  53635. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  53636. var rect = geo.getViewRect().clone();
  53637. var roamTransform = geo.getRoamTransform();
  53638. rect.applyTransform(roamTransform);
  53639. // Clamp on viewport
  53640. var x = Math.max(rect.x, 0);
  53641. var y = Math.max(rect.y, 0);
  53642. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  53643. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  53644. var width = x2 - x;
  53645. var height = y2 - y;
  53646. var dims = [
  53647. data.mapDimension('lng'),
  53648. data.mapDimension('lat'),
  53649. data.mapDimension('value')
  53650. ];
  53651. var points = data.mapArray(dims, function (lng, lat, value) {
  53652. var pt = geo.dataToPoint([lng, lat]);
  53653. pt[0] -= x;
  53654. pt[1] -= y;
  53655. pt.push(value);
  53656. return pt;
  53657. });
  53658. var dataExtent = visualMapModel.getExtent();
  53659. var isInRange = visualMapModel.type === 'visualMap.continuous'
  53660. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  53661. : getIsInPiecewiseRange(
  53662. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  53663. );
  53664. hmLayer.update(
  53665. points, width, height,
  53666. inRangeVisuals.color.getNormalizer(),
  53667. {
  53668. inRange: inRangeVisuals.color.getColorMapper(),
  53669. outOfRange: outOfRangeVisuals.color.getColorMapper()
  53670. },
  53671. isInRange
  53672. );
  53673. var img = new ZImage({
  53674. style: {
  53675. width: width,
  53676. height: height,
  53677. x: x,
  53678. y: y,
  53679. image: hmLayer.canvas
  53680. },
  53681. silent: true
  53682. });
  53683. this.group.add(img);
  53684. },
  53685. dispose: function () {}
  53686. });
  53687. /*
  53688. * Licensed to the Apache Software Foundation (ASF) under one
  53689. * or more contributor license agreements. See the NOTICE file
  53690. * distributed with this work for additional information
  53691. * regarding copyright ownership. The ASF licenses this file
  53692. * to you under the Apache License, Version 2.0 (the
  53693. * "License"); you may not use this file except in compliance
  53694. * with the License. You may obtain a copy of the License at
  53695. *
  53696. * http://www.apache.org/licenses/LICENSE-2.0
  53697. *
  53698. * Unless required by applicable law or agreed to in writing,
  53699. * software distributed under the License is distributed on an
  53700. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53701. * KIND, either express or implied. See the License for the
  53702. * specific language governing permissions and limitations
  53703. * under the License.
  53704. */
  53705. /*
  53706. * Licensed to the Apache Software Foundation (ASF) under one
  53707. * or more contributor license agreements. See the NOTICE file
  53708. * distributed with this work for additional information
  53709. * regarding copyright ownership. The ASF licenses this file
  53710. * to you under the Apache License, Version 2.0 (the
  53711. * "License"); you may not use this file except in compliance
  53712. * with the License. You may obtain a copy of the License at
  53713. *
  53714. * http://www.apache.org/licenses/LICENSE-2.0
  53715. *
  53716. * Unless required by applicable law or agreed to in writing,
  53717. * software distributed under the License is distributed on an
  53718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53719. * KIND, either express or implied. See the License for the
  53720. * specific language governing permissions and limitations
  53721. * under the License.
  53722. */
  53723. var PictorialBarSeries = BaseBarSeries.extend({
  53724. type: 'series.pictorialBar',
  53725. dependencies: ['grid'],
  53726. defaultOption: {
  53727. symbol: 'circle', // Customized bar shape
  53728. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  53729. symbolRotate: null,
  53730. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  53731. symbolOffset: null,
  53732. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  53733. // Auto margin by defualt.
  53734. symbolRepeat: false, // false/null/undefined, means no repeat.
  53735. // Can be true, means auto calculate repeat times and cut by data.
  53736. // Can be a number, specifies repeat times, and do not cut by data.
  53737. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  53738. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  53739. symbolClip: false,
  53740. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  53741. symbolPatternSize: 400, // 400 * 400 px
  53742. barGap: '-100%', // In most case, overlap is needed.
  53743. // z can be set in data item, which is z2 actually.
  53744. // Disable progressive
  53745. progressive: 0,
  53746. hoverAnimation: false // Open only when needed.
  53747. },
  53748. getInitialData: function (option) {
  53749. // Disable stack.
  53750. option.stack = null;
  53751. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  53752. }
  53753. });
  53754. /*
  53755. * Licensed to the Apache Software Foundation (ASF) under one
  53756. * or more contributor license agreements. See the NOTICE file
  53757. * distributed with this work for additional information
  53758. * regarding copyright ownership. The ASF licenses this file
  53759. * to you under the Apache License, Version 2.0 (the
  53760. * "License"); you may not use this file except in compliance
  53761. * with the License. You may obtain a copy of the License at
  53762. *
  53763. * http://www.apache.org/licenses/LICENSE-2.0
  53764. *
  53765. * Unless required by applicable law or agreed to in writing,
  53766. * software distributed under the License is distributed on an
  53767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53768. * KIND, either express or implied. See the License for the
  53769. * specific language governing permissions and limitations
  53770. * under the License.
  53771. */
  53772. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  53773. // index: +isHorizontal
  53774. var LAYOUT_ATTRS = [
  53775. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  53776. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  53777. ];
  53778. var pathForLineWidth = new Circle();
  53779. var BarView$1 = extendChartView({
  53780. type: 'pictorialBar',
  53781. render: function (seriesModel, ecModel, api) {
  53782. var group = this.group;
  53783. var data = seriesModel.getData();
  53784. var oldData = this._data;
  53785. var cartesian = seriesModel.coordinateSystem;
  53786. var baseAxis = cartesian.getBaseAxis();
  53787. var isHorizontal = !!baseAxis.isHorizontal();
  53788. var coordSysRect = cartesian.grid.getRect();
  53789. var opt = {
  53790. ecSize: {width: api.getWidth(), height: api.getHeight()},
  53791. seriesModel: seriesModel,
  53792. coordSys: cartesian,
  53793. coordSysExtent: [
  53794. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  53795. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  53796. ],
  53797. isHorizontal: isHorizontal,
  53798. valueDim: LAYOUT_ATTRS[+isHorizontal],
  53799. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  53800. };
  53801. data.diff(oldData)
  53802. .add(function (dataIndex) {
  53803. if (!data.hasValue(dataIndex)) {
  53804. return;
  53805. }
  53806. var itemModel = getItemModel(data, dataIndex);
  53807. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  53808. var bar = createBar(data, opt, symbolMeta);
  53809. data.setItemGraphicEl(dataIndex, bar);
  53810. group.add(bar);
  53811. updateCommon$1(bar, opt, symbolMeta);
  53812. })
  53813. .update(function (newIndex, oldIndex) {
  53814. var bar = oldData.getItemGraphicEl(oldIndex);
  53815. if (!data.hasValue(newIndex)) {
  53816. group.remove(bar);
  53817. return;
  53818. }
  53819. var itemModel = getItemModel(data, newIndex);
  53820. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  53821. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  53822. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  53823. group.remove(bar);
  53824. data.setItemGraphicEl(newIndex, null);
  53825. bar = null;
  53826. }
  53827. if (bar) {
  53828. updateBar(bar, opt, symbolMeta);
  53829. }
  53830. else {
  53831. bar = createBar(data, opt, symbolMeta, true);
  53832. }
  53833. data.setItemGraphicEl(newIndex, bar);
  53834. bar.__pictorialSymbolMeta = symbolMeta;
  53835. // Add back
  53836. group.add(bar);
  53837. updateCommon$1(bar, opt, symbolMeta);
  53838. })
  53839. .remove(function (dataIndex) {
  53840. var bar = oldData.getItemGraphicEl(dataIndex);
  53841. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  53842. })
  53843. .execute();
  53844. this._data = data;
  53845. return this.group;
  53846. },
  53847. dispose: noop,
  53848. remove: function (ecModel, api) {
  53849. var group = this.group;
  53850. var data = this._data;
  53851. if (ecModel.get('animation')) {
  53852. if (data) {
  53853. data.eachItemGraphicEl(function (bar) {
  53854. removeBar(data, bar.dataIndex, ecModel, bar);
  53855. });
  53856. }
  53857. }
  53858. else {
  53859. group.removeAll();
  53860. }
  53861. }
  53862. });
  53863. // Set or calculate default value about symbol, and calculate layout info.
  53864. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  53865. var layout = data.getItemLayout(dataIndex);
  53866. var symbolRepeat = itemModel.get('symbolRepeat');
  53867. var symbolClip = itemModel.get('symbolClip');
  53868. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  53869. var symbolRotate = itemModel.get('symbolRotate');
  53870. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  53871. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  53872. var isAnimationEnabled = itemModel.isAnimationEnabled();
  53873. var symbolMeta = {
  53874. dataIndex: dataIndex,
  53875. layout: layout,
  53876. itemModel: itemModel,
  53877. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  53878. color: data.getItemVisual(dataIndex, 'color'),
  53879. symbolClip: symbolClip,
  53880. symbolRepeat: symbolRepeat,
  53881. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  53882. symbolPatternSize: symbolPatternSize,
  53883. rotation: rotation,
  53884. animationModel: isAnimationEnabled ? itemModel : null,
  53885. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  53886. z2: itemModel.getShallow('z', true) || 0
  53887. };
  53888. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  53889. prepareSymbolSize(
  53890. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  53891. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  53892. );
  53893. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  53894. var symbolSize = symbolMeta.symbolSize;
  53895. var symbolOffset = itemModel.get('symbolOffset');
  53896. if (isArray(symbolOffset)) {
  53897. symbolOffset = [
  53898. parsePercent$1(symbolOffset[0], symbolSize[0]),
  53899. parsePercent$1(symbolOffset[1], symbolSize[1])
  53900. ];
  53901. }
  53902. prepareLayoutInfo(
  53903. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  53904. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  53905. opt, symbolMeta
  53906. );
  53907. return symbolMeta;
  53908. }
  53909. // bar length can be negative.
  53910. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  53911. var valueDim = opt.valueDim;
  53912. var symbolBoundingData = itemModel.get('symbolBoundingData');
  53913. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  53914. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  53915. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  53916. var boundingLength;
  53917. if (isArray(symbolBoundingData)) {
  53918. var symbolBoundingExtent = [
  53919. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  53920. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  53921. ];
  53922. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  53923. boundingLength = symbolBoundingExtent[pxSignIdx];
  53924. }
  53925. else if (symbolBoundingData != null) {
  53926. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  53927. }
  53928. else if (symbolRepeat) {
  53929. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  53930. }
  53931. else {
  53932. boundingLength = layout[valueDim.wh];
  53933. }
  53934. output.boundingLength = boundingLength;
  53935. if (symbolRepeat) {
  53936. output.repeatCutLength = layout[valueDim.wh];
  53937. }
  53938. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  53939. }
  53940. function convertToCoordOnAxis(axis, value) {
  53941. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  53942. }
  53943. // Support ['100%', '100%']
  53944. function prepareSymbolSize(
  53945. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  53946. pxSign, symbolPatternSize, opt, output
  53947. ) {
  53948. var valueDim = opt.valueDim;
  53949. var categoryDim = opt.categoryDim;
  53950. var categorySize = Math.abs(layout[categoryDim.wh]);
  53951. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  53952. if (isArray(symbolSize)) {
  53953. symbolSize = symbolSize.slice();
  53954. }
  53955. else {
  53956. if (symbolSize == null) {
  53957. symbolSize = '100%';
  53958. }
  53959. symbolSize = [symbolSize, symbolSize];
  53960. }
  53961. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  53962. // to complicated to calculate real percent value if considering scaled lineWidth.
  53963. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  53964. // which can be tolerated in pictorial chart.
  53965. symbolSize[categoryDim.index] = parsePercent$1(
  53966. symbolSize[categoryDim.index],
  53967. categorySize
  53968. );
  53969. symbolSize[valueDim.index] = parsePercent$1(
  53970. symbolSize[valueDim.index],
  53971. symbolRepeat ? categorySize : Math.abs(boundingLength)
  53972. );
  53973. output.symbolSize = symbolSize;
  53974. // If x or y is less than zero, show reversed shape.
  53975. var symbolScale = output.symbolScale = [
  53976. symbolSize[0] / symbolPatternSize,
  53977. symbolSize[1] / symbolPatternSize
  53978. ];
  53979. // Follow convention, 'right' and 'top' is the normal scale.
  53980. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  53981. }
  53982. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  53983. // In symbols are drawn with scale, so do not need to care about the case that width
  53984. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  53985. // be calculated.
  53986. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  53987. if (valueLineWidth) {
  53988. pathForLineWidth.attr({
  53989. scale: symbolScale.slice(),
  53990. rotation: rotation
  53991. });
  53992. pathForLineWidth.updateTransform();
  53993. valueLineWidth /= pathForLineWidth.getLineScale();
  53994. valueLineWidth *= symbolScale[opt.valueDim.index];
  53995. }
  53996. output.valueLineWidth = valueLineWidth;
  53997. }
  53998. function prepareLayoutInfo(
  53999. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  54000. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  54001. ) {
  54002. var categoryDim = opt.categoryDim;
  54003. var valueDim = opt.valueDim;
  54004. var pxSign = output.pxSign;
  54005. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  54006. var pathLen = unitLength;
  54007. // Note: rotation will not effect the layout of symbols, because user may
  54008. // want symbols to rotate on its center, which should not be translated
  54009. // when rotating.
  54010. if (symbolRepeat) {
  54011. var absBoundingLength = Math.abs(boundingLength);
  54012. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  54013. var hasEndGap = false;
  54014. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  54015. hasEndGap = true;
  54016. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  54017. }
  54018. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  54019. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  54020. // When symbol margin is less than 0, margin at both ends will be subtracted
  54021. // to ensure that all of the symbols will not be overflow the given area.
  54022. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  54023. // Both final repeatTimes and final symbolMargin area calculated based on
  54024. // boundingLength.
  54025. var repeatSpecified = isNumeric(symbolRepeat);
  54026. var repeatTimes = repeatSpecified
  54027. ? symbolRepeat
  54028. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  54029. // Adjust calculate margin, to ensure each symbol is displayed
  54030. // entirely in the given layout area.
  54031. var mDiff = absBoundingLength - repeatTimes * unitLength;
  54032. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  54033. uLenWithMargin = unitLength + symbolMargin * 2;
  54034. endFix = hasEndGap ? 0 : symbolMargin * 2;
  54035. // Update repeatTimes when not all symbol will be shown.
  54036. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  54037. repeatTimes = repeatCutLength
  54038. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  54039. : 0;
  54040. }
  54041. pathLen = repeatTimes * uLenWithMargin - endFix;
  54042. output.repeatTimes = repeatTimes;
  54043. output.symbolMargin = symbolMargin;
  54044. }
  54045. var sizeFix = pxSign * (pathLen / 2);
  54046. var pathPosition = output.pathPosition = [];
  54047. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  54048. pathPosition[valueDim.index] = symbolPosition === 'start'
  54049. ? sizeFix
  54050. : symbolPosition === 'end'
  54051. ? boundingLength - sizeFix
  54052. : boundingLength / 2; // 'center'
  54053. if (symbolOffset) {
  54054. pathPosition[0] += symbolOffset[0];
  54055. pathPosition[1] += symbolOffset[1];
  54056. }
  54057. var bundlePosition = output.bundlePosition = [];
  54058. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  54059. bundlePosition[valueDim.index] = layout[valueDim.xy];
  54060. var barRectShape = output.barRectShape = extend({}, layout);
  54061. barRectShape[valueDim.wh] = pxSign * Math.max(
  54062. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  54063. );
  54064. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  54065. var clipShape = output.clipShape = {};
  54066. // Consider that symbol may be overflow layout rect.
  54067. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  54068. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  54069. clipShape[valueDim.xy] = 0;
  54070. clipShape[valueDim.wh] = layout[valueDim.wh];
  54071. }
  54072. function createPath(symbolMeta) {
  54073. var symbolPatternSize = symbolMeta.symbolPatternSize;
  54074. var path = createSymbol(
  54075. // Consider texture img, make a big size.
  54076. symbolMeta.symbolType,
  54077. -symbolPatternSize / 2,
  54078. -symbolPatternSize / 2,
  54079. symbolPatternSize,
  54080. symbolPatternSize,
  54081. symbolMeta.color
  54082. );
  54083. path.attr({
  54084. culling: true
  54085. });
  54086. path.type !== 'image' && path.setStyle({
  54087. strokeNoScale: true
  54088. });
  54089. return path;
  54090. }
  54091. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  54092. var bundle = bar.__pictorialBundle;
  54093. var symbolSize = symbolMeta.symbolSize;
  54094. var valueLineWidth = symbolMeta.valueLineWidth;
  54095. var pathPosition = symbolMeta.pathPosition;
  54096. var valueDim = opt.valueDim;
  54097. var repeatTimes = symbolMeta.repeatTimes || 0;
  54098. var index = 0;
  54099. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  54100. eachPath(bar, function (path) {
  54101. path.__pictorialAnimationIndex = index;
  54102. path.__pictorialRepeatTimes = repeatTimes;
  54103. if (index < repeatTimes) {
  54104. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  54105. }
  54106. else {
  54107. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  54108. bundle.remove(path);
  54109. });
  54110. }
  54111. updateHoverAnimation(path, symbolMeta);
  54112. index++;
  54113. });
  54114. for (; index < repeatTimes; index++) {
  54115. var path = createPath(symbolMeta);
  54116. path.__pictorialAnimationIndex = index;
  54117. path.__pictorialRepeatTimes = repeatTimes;
  54118. bundle.add(path);
  54119. var target = makeTarget(index);
  54120. updateAttr(
  54121. path,
  54122. {
  54123. position: target.position,
  54124. scale: [0, 0]
  54125. },
  54126. {
  54127. scale: target.scale,
  54128. rotation: target.rotation
  54129. },
  54130. symbolMeta,
  54131. isUpdate
  54132. );
  54133. // FIXME
  54134. // If all emphasis/normal through action.
  54135. path
  54136. .on('mouseover', onMouseOver)
  54137. .on('mouseout', onMouseOut);
  54138. updateHoverAnimation(path, symbolMeta);
  54139. }
  54140. function makeTarget(index) {
  54141. var position = pathPosition.slice();
  54142. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  54143. // Otherwise: i = index;
  54144. var pxSign = symbolMeta.pxSign;
  54145. var i = index;
  54146. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  54147. i = repeatTimes - 1 - index;
  54148. }
  54149. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  54150. return {
  54151. position: position,
  54152. scale: symbolMeta.symbolScale.slice(),
  54153. rotation: symbolMeta.rotation
  54154. };
  54155. }
  54156. function onMouseOver() {
  54157. eachPath(bar, function (path) {
  54158. path.trigger('emphasis');
  54159. });
  54160. }
  54161. function onMouseOut() {
  54162. eachPath(bar, function (path) {
  54163. path.trigger('normal');
  54164. });
  54165. }
  54166. }
  54167. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  54168. var bundle = bar.__pictorialBundle;
  54169. var mainPath = bar.__pictorialMainPath;
  54170. if (!mainPath) {
  54171. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  54172. bundle.add(mainPath);
  54173. updateAttr(
  54174. mainPath,
  54175. {
  54176. position: symbolMeta.pathPosition.slice(),
  54177. scale: [0, 0],
  54178. rotation: symbolMeta.rotation
  54179. },
  54180. {
  54181. scale: symbolMeta.symbolScale.slice()
  54182. },
  54183. symbolMeta,
  54184. isUpdate
  54185. );
  54186. mainPath
  54187. .on('mouseover', onMouseOver)
  54188. .on('mouseout', onMouseOut);
  54189. }
  54190. else {
  54191. updateAttr(
  54192. mainPath,
  54193. null,
  54194. {
  54195. position: symbolMeta.pathPosition.slice(),
  54196. scale: symbolMeta.symbolScale.slice(),
  54197. rotation: symbolMeta.rotation
  54198. },
  54199. symbolMeta,
  54200. isUpdate
  54201. );
  54202. }
  54203. updateHoverAnimation(mainPath, symbolMeta);
  54204. function onMouseOver() {
  54205. this.trigger('emphasis');
  54206. }
  54207. function onMouseOut() {
  54208. this.trigger('normal');
  54209. }
  54210. }
  54211. // bar rect is used for label.
  54212. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  54213. var rectShape = extend({}, symbolMeta.barRectShape);
  54214. var barRect = bar.__pictorialBarRect;
  54215. if (!barRect) {
  54216. barRect = bar.__pictorialBarRect = new Rect({
  54217. z2: 2,
  54218. shape: rectShape,
  54219. silent: true,
  54220. style: {
  54221. stroke: 'transparent',
  54222. fill: 'transparent',
  54223. lineWidth: 0
  54224. }
  54225. });
  54226. bar.add(barRect);
  54227. }
  54228. else {
  54229. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  54230. }
  54231. }
  54232. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  54233. // If not clip, symbol will be remove and rebuilt.
  54234. if (symbolMeta.symbolClip) {
  54235. var clipPath = bar.__pictorialClipPath;
  54236. var clipShape = extend({}, symbolMeta.clipShape);
  54237. var valueDim = opt.valueDim;
  54238. var animationModel = symbolMeta.animationModel;
  54239. var dataIndex = symbolMeta.dataIndex;
  54240. if (clipPath) {
  54241. updateProps(
  54242. clipPath, {shape: clipShape}, animationModel, dataIndex
  54243. );
  54244. }
  54245. else {
  54246. clipShape[valueDim.wh] = 0;
  54247. clipPath = new Rect({shape: clipShape});
  54248. bar.__pictorialBundle.setClipPath(clipPath);
  54249. bar.__pictorialClipPath = clipPath;
  54250. var target = {};
  54251. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  54252. graphic[isUpdate ? 'updateProps' : 'initProps'](
  54253. clipPath, {shape: target}, animationModel, dataIndex
  54254. );
  54255. }
  54256. }
  54257. }
  54258. function getItemModel(data, dataIndex) {
  54259. var itemModel = data.getItemModel(dataIndex);
  54260. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  54261. itemModel.isAnimationEnabled = isAnimationEnabled;
  54262. return itemModel;
  54263. }
  54264. function getAnimationDelayParams(path) {
  54265. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  54266. return {
  54267. index: path.__pictorialAnimationIndex,
  54268. count: path.__pictorialRepeatTimes
  54269. };
  54270. }
  54271. function isAnimationEnabled() {
  54272. // `animation` prop can be set on itemModel in pictorial bar chart.
  54273. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  54274. }
  54275. function updateHoverAnimation(path, symbolMeta) {
  54276. path.off('emphasis').off('normal');
  54277. var scale = symbolMeta.symbolScale.slice();
  54278. symbolMeta.hoverAnimation && path
  54279. .on('emphasis', function() {
  54280. this.animateTo({
  54281. scale: [scale[0] * 1.1, scale[1] * 1.1]
  54282. }, 400, 'elasticOut');
  54283. })
  54284. .on('normal', function() {
  54285. this.animateTo({
  54286. scale: scale.slice()
  54287. }, 400, 'elasticOut');
  54288. });
  54289. }
  54290. function createBar(data, opt, symbolMeta, isUpdate) {
  54291. // bar is the main element for each data.
  54292. var bar = new Group();
  54293. // bundle is used for location and clip.
  54294. var bundle = new Group();
  54295. bar.add(bundle);
  54296. bar.__pictorialBundle = bundle;
  54297. bundle.attr('position', symbolMeta.bundlePosition.slice());
  54298. if (symbolMeta.symbolRepeat) {
  54299. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  54300. }
  54301. else {
  54302. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  54303. }
  54304. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  54305. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  54306. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  54307. bar.__pictorialSymbolMeta = symbolMeta;
  54308. return bar;
  54309. }
  54310. function updateBar(bar, opt, symbolMeta) {
  54311. var animationModel = symbolMeta.animationModel;
  54312. var dataIndex = symbolMeta.dataIndex;
  54313. var bundle = bar.__pictorialBundle;
  54314. updateProps(
  54315. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  54316. );
  54317. if (symbolMeta.symbolRepeat) {
  54318. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  54319. }
  54320. else {
  54321. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  54322. }
  54323. createOrUpdateBarRect(bar, symbolMeta, true);
  54324. createOrUpdateClip(bar, opt, symbolMeta, true);
  54325. }
  54326. function removeBar(data, dataIndex, animationModel, bar) {
  54327. // Not show text when animating
  54328. var labelRect = bar.__pictorialBarRect;
  54329. labelRect && (labelRect.style.text = null);
  54330. var pathes = [];
  54331. eachPath(bar, function (path) {
  54332. pathes.push(path);
  54333. });
  54334. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  54335. // I do not find proper remove animation for clip yet.
  54336. bar.__pictorialClipPath && (animationModel = null);
  54337. each$1(pathes, function (path) {
  54338. updateProps(
  54339. path, {scale: [0, 0]}, animationModel, dataIndex,
  54340. function () {
  54341. bar.parent && bar.parent.remove(bar);
  54342. }
  54343. );
  54344. });
  54345. data.setItemGraphicEl(dataIndex, null);
  54346. }
  54347. function getShapeStr(data, symbolMeta) {
  54348. return [
  54349. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  54350. !!symbolMeta.symbolRepeat,
  54351. !!symbolMeta.symbolClip
  54352. ].join(':');
  54353. }
  54354. function eachPath(bar, cb, context) {
  54355. // Do not use Group#eachChild, because it do not support remove.
  54356. each$1(bar.__pictorialBundle.children(), function (el) {
  54357. el !== bar.__pictorialBarRect && cb.call(context, el);
  54358. });
  54359. }
  54360. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  54361. immediateAttrs && el.attr(immediateAttrs);
  54362. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  54363. if (symbolMeta.symbolClip && !isUpdate) {
  54364. animationAttrs && el.attr(animationAttrs);
  54365. }
  54366. else {
  54367. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  54368. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  54369. );
  54370. }
  54371. }
  54372. function updateCommon$1(bar, opt, symbolMeta) {
  54373. var color = symbolMeta.color;
  54374. var dataIndex = symbolMeta.dataIndex;
  54375. var itemModel = symbolMeta.itemModel;
  54376. // Color must be excluded.
  54377. // Because symbol provide setColor individually to set fill and stroke
  54378. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  54379. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  54380. var cursorStyle = itemModel.getShallow('cursor');
  54381. eachPath(bar, function (path) {
  54382. // PENDING setColor should be before setStyle!!!
  54383. path.setColor(color);
  54384. path.setStyle(defaults(
  54385. {
  54386. fill: color,
  54387. opacity: symbolMeta.opacity
  54388. },
  54389. normalStyle
  54390. ));
  54391. setHoverStyle(path, hoverStyle);
  54392. cursorStyle && (path.cursor = cursorStyle);
  54393. path.z2 = symbolMeta.z2;
  54394. });
  54395. var barRectHoverStyle = {};
  54396. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  54397. var barRect = bar.__pictorialBarRect;
  54398. setLabel(
  54399. barRect.style, barRectHoverStyle, itemModel,
  54400. color, opt.seriesModel, dataIndex, barPositionOutside
  54401. );
  54402. setHoverStyle(barRect, barRectHoverStyle);
  54403. }
  54404. function toIntTimes(times) {
  54405. var roundedTimes = Math.round(times);
  54406. // Escapse accurate error
  54407. return Math.abs(times - roundedTimes) < 1e-4
  54408. ? roundedTimes
  54409. : Math.ceil(times);
  54410. }
  54411. /*
  54412. * Licensed to the Apache Software Foundation (ASF) under one
  54413. * or more contributor license agreements. See the NOTICE file
  54414. * distributed with this work for additional information
  54415. * regarding copyright ownership. The ASF licenses this file
  54416. * to you under the Apache License, Version 2.0 (the
  54417. * "License"); you may not use this file except in compliance
  54418. * with the License. You may obtain a copy of the License at
  54419. *
  54420. * http://www.apache.org/licenses/LICENSE-2.0
  54421. *
  54422. * Unless required by applicable law or agreed to in writing,
  54423. * software distributed under the License is distributed on an
  54424. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54425. * KIND, either express or implied. See the License for the
  54426. * specific language governing permissions and limitations
  54427. * under the License.
  54428. */
  54429. // In case developer forget to include grid component
  54430. registerLayout(curry(
  54431. layout, 'pictorialBar'
  54432. ));
  54433. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  54434. /*
  54435. * Licensed to the Apache Software Foundation (ASF) under one
  54436. * or more contributor license agreements. See the NOTICE file
  54437. * distributed with this work for additional information
  54438. * regarding copyright ownership. The ASF licenses this file
  54439. * to you under the Apache License, Version 2.0 (the
  54440. * "License"); you may not use this file except in compliance
  54441. * with the License. You may obtain a copy of the License at
  54442. *
  54443. * http://www.apache.org/licenses/LICENSE-2.0
  54444. *
  54445. * Unless required by applicable law or agreed to in writing,
  54446. * software distributed under the License is distributed on an
  54447. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54448. * KIND, either express or implied. See the License for the
  54449. * specific language governing permissions and limitations
  54450. * under the License.
  54451. */
  54452. /**
  54453. * @constructor module:echarts/coord/single/SingleAxis
  54454. * @extends {module:echarts/coord/Axis}
  54455. * @param {string} dim
  54456. * @param {*} scale
  54457. * @param {Array.<number>} coordExtent
  54458. * @param {string} axisType
  54459. * @param {string} position
  54460. */
  54461. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  54462. Axis.call(this, dim, scale, coordExtent);
  54463. /**
  54464. * Axis type
  54465. * - 'category'
  54466. * - 'value'
  54467. * - 'time'
  54468. * - 'log'
  54469. * @type {string}
  54470. */
  54471. this.type = axisType || 'value';
  54472. /**
  54473. * Axis position
  54474. * - 'top'
  54475. * - 'bottom'
  54476. * - 'left'
  54477. * - 'right'
  54478. * @type {string}
  54479. */
  54480. this.position = position || 'bottom';
  54481. /**
  54482. * Axis orient
  54483. * - 'horizontal'
  54484. * - 'vertical'
  54485. * @type {[type]}
  54486. */
  54487. this.orient = null;
  54488. };
  54489. SingleAxis.prototype = {
  54490. constructor: SingleAxis,
  54491. /**
  54492. * Axis model
  54493. * @type {module:echarts/coord/single/AxisModel}
  54494. */
  54495. model: null,
  54496. /**
  54497. * Judge the orient of the axis.
  54498. * @return {boolean}
  54499. */
  54500. isHorizontal: function () {
  54501. var position = this.position;
  54502. return position === 'top' || position === 'bottom';
  54503. },
  54504. /**
  54505. * @override
  54506. */
  54507. pointToData: function (point, clamp) {
  54508. return this.coordinateSystem.pointToData(point, clamp)[0];
  54509. },
  54510. /**
  54511. * Convert the local coord(processed by dataToCoord())
  54512. * to global coord(concrete pixel coord).
  54513. * designated by module:echarts/coord/single/Single.
  54514. * @type {Function}
  54515. */
  54516. toGlobalCoord: null,
  54517. /**
  54518. * Convert the global coord to local coord.
  54519. * designated by module:echarts/coord/single/Single.
  54520. * @type {Function}
  54521. */
  54522. toLocalCoord: null
  54523. };
  54524. inherits(SingleAxis, Axis);
  54525. /*
  54526. * Licensed to the Apache Software Foundation (ASF) under one
  54527. * or more contributor license agreements. See the NOTICE file
  54528. * distributed with this work for additional information
  54529. * regarding copyright ownership. The ASF licenses this file
  54530. * to you under the Apache License, Version 2.0 (the
  54531. * "License"); you may not use this file except in compliance
  54532. * with the License. You may obtain a copy of the License at
  54533. *
  54534. * http://www.apache.org/licenses/LICENSE-2.0
  54535. *
  54536. * Unless required by applicable law or agreed to in writing,
  54537. * software distributed under the License is distributed on an
  54538. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54539. * KIND, either express or implied. See the License for the
  54540. * specific language governing permissions and limitations
  54541. * under the License.
  54542. */
  54543. /**
  54544. * Single coordinates system.
  54545. */
  54546. /**
  54547. * Create a single coordinates system.
  54548. *
  54549. * @param {module:echarts/coord/single/AxisModel} axisModel
  54550. * @param {module:echarts/model/Global} ecModel
  54551. * @param {module:echarts/ExtensionAPI} api
  54552. */
  54553. function Single(axisModel, ecModel, api) {
  54554. /**
  54555. * @type {string}
  54556. * @readOnly
  54557. */
  54558. this.dimension = 'single';
  54559. /**
  54560. * Add it just for draw tooltip.
  54561. *
  54562. * @type {Array.<string>}
  54563. * @readOnly
  54564. */
  54565. this.dimensions = ['single'];
  54566. /**
  54567. * @private
  54568. * @type {module:echarts/coord/single/SingleAxis}.
  54569. */
  54570. this._axis = null;
  54571. /**
  54572. * @private
  54573. * @type {module:zrender/core/BoundingRect}
  54574. */
  54575. this._rect;
  54576. this._init(axisModel, ecModel, api);
  54577. /**
  54578. * @type {module:echarts/coord/single/AxisModel}
  54579. */
  54580. this.model = axisModel;
  54581. }
  54582. Single.prototype = {
  54583. type: 'singleAxis',
  54584. axisPointerEnabled: true,
  54585. constructor: Single,
  54586. /**
  54587. * Initialize single coordinate system.
  54588. *
  54589. * @param {module:echarts/coord/single/AxisModel} axisModel
  54590. * @param {module:echarts/model/Global} ecModel
  54591. * @param {module:echarts/ExtensionAPI} api
  54592. * @private
  54593. */
  54594. _init: function (axisModel, ecModel, api) {
  54595. var dim = this.dimension;
  54596. var axis = new SingleAxis(
  54597. dim,
  54598. createScaleByModel(axisModel),
  54599. [0, 0],
  54600. axisModel.get('type'),
  54601. axisModel.get('position')
  54602. );
  54603. var isCategory = axis.type === 'category';
  54604. axis.onBand = isCategory && axisModel.get('boundaryGap');
  54605. axis.inverse = axisModel.get('inverse');
  54606. axis.orient = axisModel.get('orient');
  54607. axisModel.axis = axis;
  54608. axis.model = axisModel;
  54609. axis.coordinateSystem = this;
  54610. this._axis = axis;
  54611. },
  54612. /**
  54613. * Update axis scale after data processed
  54614. * @param {module:echarts/model/Global} ecModel
  54615. * @param {module:echarts/ExtensionAPI} api
  54616. */
  54617. update: function (ecModel, api) {
  54618. ecModel.eachSeries(function (seriesModel) {
  54619. if (seriesModel.coordinateSystem === this) {
  54620. var data = seriesModel.getData();
  54621. each$1(data.mapDimension(this.dimension, true), function (dim) {
  54622. this._axis.scale.unionExtentFromData(data, dim);
  54623. }, this);
  54624. niceScaleExtent(this._axis.scale, this._axis.model);
  54625. }
  54626. }, this);
  54627. },
  54628. /**
  54629. * Resize the single coordinate system.
  54630. *
  54631. * @param {module:echarts/coord/single/AxisModel} axisModel
  54632. * @param {module:echarts/ExtensionAPI} api
  54633. */
  54634. resize: function (axisModel, api) {
  54635. this._rect = getLayoutRect(
  54636. {
  54637. left: axisModel.get('left'),
  54638. top: axisModel.get('top'),
  54639. right: axisModel.get('right'),
  54640. bottom: axisModel.get('bottom'),
  54641. width: axisModel.get('width'),
  54642. height: axisModel.get('height')
  54643. },
  54644. {
  54645. width: api.getWidth(),
  54646. height: api.getHeight()
  54647. }
  54648. );
  54649. this._adjustAxis();
  54650. },
  54651. /**
  54652. * @return {module:zrender/core/BoundingRect}
  54653. */
  54654. getRect: function () {
  54655. return this._rect;
  54656. },
  54657. /**
  54658. * @private
  54659. */
  54660. _adjustAxis: function () {
  54661. var rect = this._rect;
  54662. var axis = this._axis;
  54663. var isHorizontal = axis.isHorizontal();
  54664. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  54665. var idx = axis.reverse ? 1 : 0;
  54666. axis.setExtent(extent[idx], extent[1 - idx]);
  54667. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  54668. },
  54669. /**
  54670. * @param {module:echarts/coord/single/SingleAxis} axis
  54671. * @param {number} coordBase
  54672. */
  54673. _updateAxisTransform: function (axis, coordBase) {
  54674. var axisExtent = axis.getExtent();
  54675. var extentSum = axisExtent[0] + axisExtent[1];
  54676. var isHorizontal = axis.isHorizontal();
  54677. axis.toGlobalCoord = isHorizontal
  54678. ? function (coord) {
  54679. return coord + coordBase;
  54680. }
  54681. : function (coord) {
  54682. return extentSum - coord + coordBase;
  54683. };
  54684. axis.toLocalCoord = isHorizontal
  54685. ? function (coord) {
  54686. return coord - coordBase;
  54687. }
  54688. : function (coord) {
  54689. return extentSum - coord + coordBase;
  54690. };
  54691. },
  54692. /**
  54693. * Get axis.
  54694. *
  54695. * @return {module:echarts/coord/single/SingleAxis}
  54696. */
  54697. getAxis: function () {
  54698. return this._axis;
  54699. },
  54700. /**
  54701. * Get axis, add it just for draw tooltip.
  54702. *
  54703. * @return {[type]} [description]
  54704. */
  54705. getBaseAxis: function () {
  54706. return this._axis;
  54707. },
  54708. /**
  54709. * @return {Array.<module:echarts/coord/Axis>}
  54710. */
  54711. getAxes: function () {
  54712. return [this._axis];
  54713. },
  54714. /**
  54715. * @return {Object} {baseAxes: [], otherAxes: []}
  54716. */
  54717. getTooltipAxes: function () {
  54718. return {baseAxes: [this.getAxis()]};
  54719. },
  54720. /**
  54721. * If contain point.
  54722. *
  54723. * @param {Array.<number>} point
  54724. * @return {boolean}
  54725. */
  54726. containPoint: function (point) {
  54727. var rect = this.getRect();
  54728. var axis = this.getAxis();
  54729. var orient = axis.orient;
  54730. if (orient === 'horizontal') {
  54731. return axis.contain(axis.toLocalCoord(point[0]))
  54732. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  54733. }
  54734. else {
  54735. return axis.contain(axis.toLocalCoord(point[1]))
  54736. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  54737. }
  54738. },
  54739. /**
  54740. * @param {Array.<number>} point
  54741. * @return {Array.<number>}
  54742. */
  54743. pointToData: function (point) {
  54744. var axis = this.getAxis();
  54745. return [axis.coordToData(axis.toLocalCoord(
  54746. point[axis.orient === 'horizontal' ? 0 : 1]
  54747. ))];
  54748. },
  54749. /**
  54750. * Convert the series data to concrete point.
  54751. *
  54752. * @param {number|Array.<number>} val
  54753. * @return {Array.<number>}
  54754. */
  54755. dataToPoint: function (val) {
  54756. var axis = this.getAxis();
  54757. var rect = this.getRect();
  54758. var pt = [];
  54759. var idx = axis.orient === 'horizontal' ? 0 : 1;
  54760. if (val instanceof Array) {
  54761. val = val[0];
  54762. }
  54763. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  54764. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  54765. return pt;
  54766. }
  54767. };
  54768. /*
  54769. * Licensed to the Apache Software Foundation (ASF) under one
  54770. * or more contributor license agreements. See the NOTICE file
  54771. * distributed with this work for additional information
  54772. * regarding copyright ownership. The ASF licenses this file
  54773. * to you under the Apache License, Version 2.0 (the
  54774. * "License"); you may not use this file except in compliance
  54775. * with the License. You may obtain a copy of the License at
  54776. *
  54777. * http://www.apache.org/licenses/LICENSE-2.0
  54778. *
  54779. * Unless required by applicable law or agreed to in writing,
  54780. * software distributed under the License is distributed on an
  54781. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54782. * KIND, either express or implied. See the License for the
  54783. * specific language governing permissions and limitations
  54784. * under the License.
  54785. */
  54786. /**
  54787. * Single coordinate system creator.
  54788. */
  54789. /**
  54790. * Create single coordinate system and inject it into seriesModel.
  54791. *
  54792. * @param {module:echarts/model/Global} ecModel
  54793. * @param {module:echarts/ExtensionAPI} api
  54794. * @return {Array.<module:echarts/coord/single/Single>}
  54795. */
  54796. function create$3(ecModel, api) {
  54797. var singles = [];
  54798. ecModel.eachComponent('singleAxis', function(axisModel, idx) {
  54799. var single = new Single(axisModel, ecModel, api);
  54800. single.name = 'single_' + idx;
  54801. single.resize(axisModel, api);
  54802. axisModel.coordinateSystem = single;
  54803. singles.push(single);
  54804. });
  54805. ecModel.eachSeries(function (seriesModel) {
  54806. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  54807. var singleAxisModel = ecModel.queryComponents({
  54808. mainType: 'singleAxis',
  54809. index: seriesModel.get('singleAxisIndex'),
  54810. id: seriesModel.get('singleAxisId')
  54811. })[0];
  54812. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  54813. }
  54814. });
  54815. return singles;
  54816. }
  54817. CoordinateSystemManager.register('single', {
  54818. create: create$3,
  54819. dimensions: Single.prototype.dimensions
  54820. });
  54821. /*
  54822. * Licensed to the Apache Software Foundation (ASF) under one
  54823. * or more contributor license agreements. See the NOTICE file
  54824. * distributed with this work for additional information
  54825. * regarding copyright ownership. The ASF licenses this file
  54826. * to you under the Apache License, Version 2.0 (the
  54827. * "License"); you may not use this file except in compliance
  54828. * with the License. You may obtain a copy of the License at
  54829. *
  54830. * http://www.apache.org/licenses/LICENSE-2.0
  54831. *
  54832. * Unless required by applicable law or agreed to in writing,
  54833. * software distributed under the License is distributed on an
  54834. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54835. * KIND, either express or implied. See the License for the
  54836. * specific language governing permissions and limitations
  54837. * under the License.
  54838. */
  54839. /**
  54840. * @param {Object} opt {labelInside}
  54841. * @return {Object} {
  54842. * position, rotation, labelDirection, labelOffset,
  54843. * tickDirection, labelRotate, z2
  54844. * }
  54845. */
  54846. function layout$2(axisModel, opt) {
  54847. opt = opt || {};
  54848. var single = axisModel.coordinateSystem;
  54849. var axis = axisModel.axis;
  54850. var layout = {};
  54851. var axisPosition = axis.position;
  54852. var orient = axis.orient;
  54853. var rect = single.getRect();
  54854. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  54855. var positionMap = {
  54856. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  54857. vertical: {left: rectBound[0], right: rectBound[1]}
  54858. };
  54859. layout.position = [
  54860. orient === 'vertical'
  54861. ? positionMap.vertical[axisPosition]
  54862. : rectBound[0],
  54863. orient === 'horizontal'
  54864. ? positionMap.horizontal[axisPosition]
  54865. : rectBound[3]
  54866. ];
  54867. var r = {horizontal: 0, vertical: 1};
  54868. layout.rotation = Math.PI / 2 * r[orient];
  54869. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  54870. layout.labelDirection = layout.tickDirection
  54871. = layout.nameDirection
  54872. = directionMap[axisPosition];
  54873. if (axisModel.get('axisTick.inside')) {
  54874. layout.tickDirection = -layout.tickDirection;
  54875. }
  54876. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  54877. layout.labelDirection = -layout.labelDirection;
  54878. }
  54879. var labelRotation = opt.rotate;
  54880. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  54881. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  54882. layout.z2 = 1;
  54883. return layout;
  54884. }
  54885. /*
  54886. * Licensed to the Apache Software Foundation (ASF) under one
  54887. * or more contributor license agreements. See the NOTICE file
  54888. * distributed with this work for additional information
  54889. * regarding copyright ownership. The ASF licenses this file
  54890. * to you under the Apache License, Version 2.0 (the
  54891. * "License"); you may not use this file except in compliance
  54892. * with the License. You may obtain a copy of the License at
  54893. *
  54894. * http://www.apache.org/licenses/LICENSE-2.0
  54895. *
  54896. * Unless required by applicable law or agreed to in writing,
  54897. * software distributed under the License is distributed on an
  54898. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54899. * KIND, either express or implied. See the License for the
  54900. * specific language governing permissions and limitations
  54901. * under the License.
  54902. */
  54903. var axisBuilderAttrs$2 = [
  54904. 'axisLine', 'axisTickLabel', 'axisName'
  54905. ];
  54906. var selfBuilderAttr = 'splitLine';
  54907. var SingleAxisView = AxisView.extend({
  54908. type: 'singleAxis',
  54909. axisPointerClass: 'SingleAxisPointer',
  54910. render: function (axisModel, ecModel, api, payload) {
  54911. var group = this.group;
  54912. group.removeAll();
  54913. var layout = layout$2(axisModel);
  54914. var axisBuilder = new AxisBuilder(axisModel, layout);
  54915. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  54916. group.add(axisBuilder.getGroup());
  54917. if (axisModel.get(selfBuilderAttr + '.show')) {
  54918. this['_' + selfBuilderAttr](axisModel);
  54919. }
  54920. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  54921. },
  54922. _splitLine: function(axisModel) {
  54923. var axis = axisModel.axis;
  54924. if (axis.scale.isBlank()) {
  54925. return;
  54926. }
  54927. var splitLineModel = axisModel.getModel('splitLine');
  54928. var lineStyleModel = splitLineModel.getModel('lineStyle');
  54929. var lineWidth = lineStyleModel.get('width');
  54930. var lineColors = lineStyleModel.get('color');
  54931. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  54932. var gridRect = axisModel.coordinateSystem.getRect();
  54933. var isHorizontal = axis.isHorizontal();
  54934. var splitLines = [];
  54935. var lineCount = 0;
  54936. var ticksCoords = axis.getTicksCoords({
  54937. tickModel: splitLineModel
  54938. });
  54939. var p1 = [];
  54940. var p2 = [];
  54941. for (var i = 0; i < ticksCoords.length; ++i) {
  54942. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  54943. if (isHorizontal) {
  54944. p1[0] = tickCoord;
  54945. p1[1] = gridRect.y;
  54946. p2[0] = tickCoord;
  54947. p2[1] = gridRect.y + gridRect.height;
  54948. }
  54949. else {
  54950. p1[0] = gridRect.x;
  54951. p1[1] = tickCoord;
  54952. p2[0] = gridRect.x + gridRect.width;
  54953. p2[1] = tickCoord;
  54954. }
  54955. var colorIndex = (lineCount++) % lineColors.length;
  54956. splitLines[colorIndex] = splitLines[colorIndex] || [];
  54957. splitLines[colorIndex].push(new Line(
  54958. subPixelOptimizeLine({
  54959. shape: {
  54960. x1: p1[0],
  54961. y1: p1[1],
  54962. x2: p2[0],
  54963. y2: p2[1]
  54964. },
  54965. style: {
  54966. lineWidth: lineWidth
  54967. },
  54968. silent: true
  54969. })));
  54970. }
  54971. for (var i = 0; i < splitLines.length; ++i) {
  54972. this.group.add(mergePath(splitLines[i], {
  54973. style: {
  54974. stroke: lineColors[i % lineColors.length],
  54975. lineDash: lineStyleModel.getLineDash(lineWidth),
  54976. lineWidth: lineWidth
  54977. },
  54978. silent: true
  54979. }));
  54980. }
  54981. }
  54982. });
  54983. /*
  54984. * Licensed to the Apache Software Foundation (ASF) under one
  54985. * or more contributor license agreements. See the NOTICE file
  54986. * distributed with this work for additional information
  54987. * regarding copyright ownership. The ASF licenses this file
  54988. * to you under the Apache License, Version 2.0 (the
  54989. * "License"); you may not use this file except in compliance
  54990. * with the License. You may obtain a copy of the License at
  54991. *
  54992. * http://www.apache.org/licenses/LICENSE-2.0
  54993. *
  54994. * Unless required by applicable law or agreed to in writing,
  54995. * software distributed under the License is distributed on an
  54996. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54997. * KIND, either express or implied. See the License for the
  54998. * specific language governing permissions and limitations
  54999. * under the License.
  55000. */
  55001. var AxisModel$4 = ComponentModel.extend({
  55002. type: 'singleAxis',
  55003. layoutMode: 'box',
  55004. /**
  55005. * @type {module:echarts/coord/single/SingleAxis}
  55006. */
  55007. axis: null,
  55008. /**
  55009. * @type {module:echarts/coord/single/Single}
  55010. */
  55011. coordinateSystem: null,
  55012. /**
  55013. * @override
  55014. */
  55015. getCoordSysModel: function () {
  55016. return this;
  55017. }
  55018. });
  55019. var defaultOption$2 = {
  55020. left: '5%',
  55021. top: '5%',
  55022. right: '5%',
  55023. bottom: '5%',
  55024. type: 'value',
  55025. position: 'bottom',
  55026. orient: 'horizontal',
  55027. axisLine: {
  55028. show: true,
  55029. lineStyle: {
  55030. width: 2,
  55031. type: 'solid'
  55032. }
  55033. },
  55034. // Single coordinate system and single axis is the,
  55035. // which is used as the parent tooltip model.
  55036. // same model, so we set default tooltip show as true.
  55037. tooltip: {
  55038. show: true
  55039. },
  55040. axisTick: {
  55041. show: true,
  55042. length: 6,
  55043. lineStyle: {
  55044. width: 2
  55045. }
  55046. },
  55047. axisLabel: {
  55048. show: true,
  55049. interval: 'auto'
  55050. },
  55051. splitLine: {
  55052. show: true,
  55053. lineStyle: {
  55054. type: 'dashed',
  55055. opacity: 0.2
  55056. }
  55057. }
  55058. };
  55059. function getAxisType$2(axisName, option) {
  55060. return option.type || (option.data ? 'category' : 'value');
  55061. }
  55062. merge(AxisModel$4.prototype, axisModelCommonMixin);
  55063. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  55064. /*
  55065. * Licensed to the Apache Software Foundation (ASF) under one
  55066. * or more contributor license agreements. See the NOTICE file
  55067. * distributed with this work for additional information
  55068. * regarding copyright ownership. The ASF licenses this file
  55069. * to you under the Apache License, Version 2.0 (the
  55070. * "License"); you may not use this file except in compliance
  55071. * with the License. You may obtain a copy of the License at
  55072. *
  55073. * http://www.apache.org/licenses/LICENSE-2.0
  55074. *
  55075. * Unless required by applicable law or agreed to in writing,
  55076. * software distributed under the License is distributed on an
  55077. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55078. * KIND, either express or implied. See the License for the
  55079. * specific language governing permissions and limitations
  55080. * under the License.
  55081. */
  55082. /**
  55083. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  55084. * @param {module:echarts/model/Global} ecModel
  55085. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  55086. */
  55087. var findPointFromSeries = function (finder, ecModel) {
  55088. var point = [];
  55089. var seriesIndex = finder.seriesIndex;
  55090. var seriesModel;
  55091. if (seriesIndex == null || !(
  55092. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  55093. )) {
  55094. return {point: []};
  55095. }
  55096. var data = seriesModel.getData();
  55097. var dataIndex = queryDataIndex(data, finder);
  55098. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  55099. return {point: []};
  55100. }
  55101. var el = data.getItemGraphicEl(dataIndex);
  55102. var coordSys = seriesModel.coordinateSystem;
  55103. if (seriesModel.getTooltipPosition) {
  55104. point = seriesModel.getTooltipPosition(dataIndex) || [];
  55105. }
  55106. else if (coordSys && coordSys.dataToPoint) {
  55107. point = coordSys.dataToPoint(
  55108. data.getValues(
  55109. map(coordSys.dimensions, function (dim) {
  55110. return data.mapDimension(dim);
  55111. }), dataIndex, true
  55112. )
  55113. ) || [];
  55114. }
  55115. else if (el) {
  55116. // Use graphic bounding rect
  55117. var rect = el.getBoundingRect().clone();
  55118. rect.applyTransform(el.transform);
  55119. point = [
  55120. rect.x + rect.width / 2,
  55121. rect.y + rect.height / 2
  55122. ];
  55123. }
  55124. return {point: point, el: el};
  55125. };
  55126. /*
  55127. * Licensed to the Apache Software Foundation (ASF) under one
  55128. * or more contributor license agreements. See the NOTICE file
  55129. * distributed with this work for additional information
  55130. * regarding copyright ownership. The ASF licenses this file
  55131. * to you under the Apache License, Version 2.0 (the
  55132. * "License"); you may not use this file except in compliance
  55133. * with the License. You may obtain a copy of the License at
  55134. *
  55135. * http://www.apache.org/licenses/LICENSE-2.0
  55136. *
  55137. * Unless required by applicable law or agreed to in writing,
  55138. * software distributed under the License is distributed on an
  55139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55140. * KIND, either express or implied. See the License for the
  55141. * specific language governing permissions and limitations
  55142. * under the License.
  55143. */
  55144. var each$14 = each$1;
  55145. var curry$3 = curry;
  55146. var inner$7 = makeInner();
  55147. /**
  55148. * Basic logic: check all axis, if they do not demand show/highlight,
  55149. * then hide/downplay them.
  55150. *
  55151. * @param {Object} coordSysAxesInfo
  55152. * @param {Object} payload
  55153. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  55154. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  55155. * trigger axisPointer and tooltip.
  55156. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  55157. * trigger axisPointer and tooltip.
  55158. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  55159. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  55160. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  55161. * [{
  55162. * axisDim: 'x'|'y'|'angle'|...,
  55163. * axisIndex: ...,
  55164. * value: ...
  55165. * }, ...]
  55166. * @param {Function} [payload.dispatchAction]
  55167. * @param {Object} [payload.tooltipOption]
  55168. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  55169. * which can be specified in dispatchAction
  55170. * @param {module:echarts/model/Global} ecModel
  55171. * @param {module:echarts/ExtensionAPI} api
  55172. * @return {Object} content of event obj for echarts.connect.
  55173. */
  55174. var axisTrigger = function (payload, ecModel, api) {
  55175. var currTrigger = payload.currTrigger;
  55176. var point = [payload.x, payload.y];
  55177. var finder = payload;
  55178. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  55179. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  55180. // Pending
  55181. // See #6121. But we are not able to reproduce it yet.
  55182. if (!coordSysAxesInfo) {
  55183. return;
  55184. }
  55185. if (illegalPoint(point)) {
  55186. // Used in the default behavior of `connection`: use the sample seriesIndex
  55187. // and dataIndex. And also used in the tooltipView trigger.
  55188. point = findPointFromSeries({
  55189. seriesIndex: finder.seriesIndex,
  55190. // Do not use dataIndexInside from other ec instance.
  55191. // FIXME: auto detect it?
  55192. dataIndex: finder.dataIndex
  55193. }, ecModel).point;
  55194. }
  55195. var isIllegalPoint = illegalPoint(point);
  55196. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  55197. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  55198. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  55199. // and dataIndex.
  55200. var inputAxesInfo = finder.axesInfo;
  55201. var axesInfo = coordSysAxesInfo.axesInfo;
  55202. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  55203. var outputFinder = {};
  55204. var showValueMap = {};
  55205. var dataByCoordSys = {list: [], map: {}};
  55206. var updaters = {
  55207. showPointer: curry$3(showPointer, showValueMap),
  55208. showTooltip: curry$3(showTooltip, dataByCoordSys)
  55209. };
  55210. // Process for triggered axes.
  55211. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  55212. // If a point given, it must be contained by the coordinate system.
  55213. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  55214. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  55215. var axis = axisInfo.axis;
  55216. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  55217. // If no inputAxesInfo, no axis is restricted.
  55218. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  55219. var val = inputAxisInfo && inputAxisInfo.value;
  55220. if (val == null && !isIllegalPoint) {
  55221. val = axis.pointToData(point);
  55222. }
  55223. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  55224. }
  55225. });
  55226. });
  55227. // Process for linked axes.
  55228. var linkTriggers = {};
  55229. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  55230. var linkGroup = tarAxisInfo.linkGroup;
  55231. // If axis has been triggered in the previous stage, it should not be triggered by link.
  55232. if (linkGroup && !showValueMap[tarKey]) {
  55233. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  55234. var srcValItem = showValueMap[srcKey];
  55235. // If srcValItem exist, source axis is triggered, so link to target axis.
  55236. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  55237. var val = srcValItem.value;
  55238. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  55239. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  55240. )));
  55241. linkTriggers[tarAxisInfo.key] = val;
  55242. }
  55243. });
  55244. }
  55245. });
  55246. each$14(linkTriggers, function (val, tarKey) {
  55247. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  55248. });
  55249. updateModelActually(showValueMap, axesInfo, outputFinder);
  55250. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  55251. dispatchHighDownActually(axesInfo, dispatchAction, api);
  55252. return outputFinder;
  55253. };
  55254. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  55255. var axis = axisInfo.axis;
  55256. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  55257. return;
  55258. }
  55259. if (!axisInfo.involveSeries) {
  55260. updaters.showPointer(axisInfo, newValue);
  55261. return;
  55262. }
  55263. // Heavy calculation. So put it after axis.containData checking.
  55264. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  55265. var payloadBatch = payloadInfo.payloadBatch;
  55266. var snapToValue = payloadInfo.snapToValue;
  55267. // Fill content of event obj for echarts.connect.
  55268. // By defualt use the first involved series data as a sample to connect.
  55269. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  55270. extend(outputFinder, payloadBatch[0]);
  55271. }
  55272. // If no linkSource input, this process is for collecting link
  55273. // target, where snap should not be accepted.
  55274. if (!dontSnap && axisInfo.snap) {
  55275. if (axis.containData(snapToValue) && snapToValue != null) {
  55276. newValue = snapToValue;
  55277. }
  55278. }
  55279. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  55280. // Tooltip should always be snapToValue, otherwise there will be
  55281. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  55282. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  55283. }
  55284. function buildPayloadsBySeries(value, axisInfo) {
  55285. var axis = axisInfo.axis;
  55286. var dim = axis.dim;
  55287. var snapToValue = value;
  55288. var payloadBatch = [];
  55289. var minDist = Number.MAX_VALUE;
  55290. var minDiff = -1;
  55291. each$14(axisInfo.seriesModels, function (series, idx) {
  55292. var dataDim = series.getData().mapDimension(dim, true);
  55293. var seriesNestestValue;
  55294. var dataIndices;
  55295. if (series.getAxisTooltipData) {
  55296. var result = series.getAxisTooltipData(dataDim, value, axis);
  55297. dataIndices = result.dataIndices;
  55298. seriesNestestValue = result.nestestValue;
  55299. }
  55300. else {
  55301. dataIndices = series.getData().indicesOfNearest(
  55302. dataDim[0],
  55303. value,
  55304. // Add a threshold to avoid find the wrong dataIndex
  55305. // when data length is not same.
  55306. // false,
  55307. axis.type === 'category' ? 0.5 : null
  55308. );
  55309. if (!dataIndices.length) {
  55310. return;
  55311. }
  55312. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  55313. }
  55314. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  55315. return;
  55316. }
  55317. var diff = value - seriesNestestValue;
  55318. var dist = Math.abs(diff);
  55319. // Consider category case
  55320. if (dist <= minDist) {
  55321. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  55322. minDist = dist;
  55323. minDiff = diff;
  55324. snapToValue = seriesNestestValue;
  55325. payloadBatch.length = 0;
  55326. }
  55327. each$14(dataIndices, function (dataIndex) {
  55328. payloadBatch.push({
  55329. seriesIndex: series.seriesIndex,
  55330. dataIndexInside: dataIndex,
  55331. dataIndex: series.getData().getRawIndex(dataIndex)
  55332. });
  55333. });
  55334. }
  55335. });
  55336. return {
  55337. payloadBatch: payloadBatch,
  55338. snapToValue: snapToValue
  55339. };
  55340. }
  55341. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  55342. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  55343. }
  55344. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  55345. var payloadBatch = payloadInfo.payloadBatch;
  55346. var axis = axisInfo.axis;
  55347. var axisModel = axis.model;
  55348. var axisPointerModel = axisInfo.axisPointerModel;
  55349. // If no data, do not create anything in dataByCoordSys,
  55350. // whose length will be used to judge whether dispatch action.
  55351. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  55352. return;
  55353. }
  55354. var coordSysModel = axisInfo.coordSys.model;
  55355. var coordSysKey = makeKey(coordSysModel);
  55356. var coordSysItem = dataByCoordSys.map[coordSysKey];
  55357. if (!coordSysItem) {
  55358. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  55359. coordSysId: coordSysModel.id,
  55360. coordSysIndex: coordSysModel.componentIndex,
  55361. coordSysType: coordSysModel.type,
  55362. coordSysMainType: coordSysModel.mainType,
  55363. dataByAxis: []
  55364. };
  55365. dataByCoordSys.list.push(coordSysItem);
  55366. }
  55367. coordSysItem.dataByAxis.push({
  55368. axisDim: axis.dim,
  55369. axisIndex: axisModel.componentIndex,
  55370. axisType: axisModel.type,
  55371. axisId: axisModel.id,
  55372. value: value,
  55373. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  55374. // depends that all models have been updated. So it should not be performed
  55375. // here. Considering axisPointerModel used here is volatile, which is hard
  55376. // to be retrieve in TooltipView, we prepare parameters here.
  55377. valueLabelOpt: {
  55378. precision: axisPointerModel.get('label.precision'),
  55379. formatter: axisPointerModel.get('label.formatter')
  55380. },
  55381. seriesDataIndices: payloadBatch.slice()
  55382. });
  55383. }
  55384. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  55385. var outputAxesInfo = outputFinder.axesInfo = [];
  55386. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  55387. each$14(axesInfo, function (axisInfo, key) {
  55388. var option = axisInfo.axisPointerModel.option;
  55389. var valItem = showValueMap[key];
  55390. if (valItem) {
  55391. !axisInfo.useHandle && (option.status = 'show');
  55392. option.value = valItem.value;
  55393. // For label formatter param and highlight.
  55394. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  55395. }
  55396. // When always show (e.g., handle used), remain
  55397. // original value and status.
  55398. else {
  55399. // If hide, value still need to be set, consider
  55400. // click legend to toggle axis blank.
  55401. !axisInfo.useHandle && (option.status = 'hide');
  55402. }
  55403. // If status is 'hide', should be no info in payload.
  55404. option.status === 'show' && outputAxesInfo.push({
  55405. axisDim: axisInfo.axis.dim,
  55406. axisIndex: axisInfo.axis.model.componentIndex,
  55407. value: option.value
  55408. });
  55409. });
  55410. }
  55411. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  55412. // Basic logic: If no showTip required, hideTip will be dispatched.
  55413. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  55414. dispatchAction({type: 'hideTip'});
  55415. return;
  55416. }
  55417. // In most case only one axis (or event one series is used). It is
  55418. // convinient to fetch payload.seriesIndex and payload.dataIndex
  55419. // dirtectly. So put the first seriesIndex and dataIndex of the first
  55420. // axis on the payload.
  55421. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  55422. dispatchAction({
  55423. type: 'showTip',
  55424. escapeConnect: true,
  55425. x: point[0],
  55426. y: point[1],
  55427. tooltipOption: payload.tooltipOption,
  55428. position: payload.position,
  55429. dataIndexInside: sampleItem.dataIndexInside,
  55430. dataIndex: sampleItem.dataIndex,
  55431. seriesIndex: sampleItem.seriesIndex,
  55432. dataByCoordSys: dataByCoordSys.list
  55433. });
  55434. }
  55435. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  55436. // FIXME
  55437. // highlight status modification shoule be a stage of main process?
  55438. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  55439. var zr = api.getZr();
  55440. var highDownKey = 'axisPointerLastHighlights';
  55441. var lastHighlights = inner$7(zr)[highDownKey] || {};
  55442. var newHighlights = inner$7(zr)[highDownKey] = {};
  55443. // Update highlight/downplay status according to axisPointer model.
  55444. // Build hash map and remove duplicate incidentally.
  55445. each$14(axesInfo, function (axisInfo, key) {
  55446. var option = axisInfo.axisPointerModel.option;
  55447. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  55448. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  55449. newHighlights[key] = batchItem;
  55450. });
  55451. });
  55452. // Diff.
  55453. var toHighlight = [];
  55454. var toDownplay = [];
  55455. each$1(lastHighlights, function (batchItem, key) {
  55456. !newHighlights[key] && toDownplay.push(batchItem);
  55457. });
  55458. each$1(newHighlights, function (batchItem, key) {
  55459. !lastHighlights[key] && toHighlight.push(batchItem);
  55460. });
  55461. toDownplay.length && api.dispatchAction({
  55462. type: 'downplay', escapeConnect: true, batch: toDownplay
  55463. });
  55464. toHighlight.length && api.dispatchAction({
  55465. type: 'highlight', escapeConnect: true, batch: toHighlight
  55466. });
  55467. }
  55468. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  55469. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  55470. var inputAxisInfo = inputAxesInfo[i];
  55471. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  55472. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  55473. ) {
  55474. return inputAxisInfo;
  55475. }
  55476. }
  55477. }
  55478. function makeMapperParam(axisInfo) {
  55479. var axisModel = axisInfo.axis.model;
  55480. var item = {};
  55481. var dim = item.axisDim = axisInfo.axis.dim;
  55482. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  55483. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  55484. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  55485. return item;
  55486. }
  55487. function illegalPoint(point) {
  55488. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  55489. }
  55490. /*
  55491. * Licensed to the Apache Software Foundation (ASF) under one
  55492. * or more contributor license agreements. See the NOTICE file
  55493. * distributed with this work for additional information
  55494. * regarding copyright ownership. The ASF licenses this file
  55495. * to you under the Apache License, Version 2.0 (the
  55496. * "License"); you may not use this file except in compliance
  55497. * with the License. You may obtain a copy of the License at
  55498. *
  55499. * http://www.apache.org/licenses/LICENSE-2.0
  55500. *
  55501. * Unless required by applicable law or agreed to in writing,
  55502. * software distributed under the License is distributed on an
  55503. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55504. * KIND, either express or implied. See the License for the
  55505. * specific language governing permissions and limitations
  55506. * under the License.
  55507. */
  55508. var AxisPointerModel = extendComponentModel({
  55509. type: 'axisPointer',
  55510. coordSysAxesInfo: null,
  55511. defaultOption: {
  55512. // 'auto' means that show when triggered by tooltip or handle.
  55513. show: 'auto',
  55514. // 'click' | 'mousemove' | 'none'
  55515. triggerOn: null, // set default in AxisPonterView.js
  55516. zlevel: 0,
  55517. z: 50,
  55518. type: 'line',
  55519. // axispointer triggered by tootip determine snap automatically,
  55520. // see `modelHelper`.
  55521. snap: false,
  55522. triggerTooltip: true,
  55523. value: null,
  55524. status: null, // Init value depends on whether handle is used.
  55525. // [group0, group1, ...]
  55526. // Each group can be: {
  55527. // mapper: function () {},
  55528. // singleTooltip: 'multiple', // 'multiple' or 'single'
  55529. // xAxisId: ...,
  55530. // yAxisName: ...,
  55531. // angleAxisIndex: ...
  55532. // }
  55533. // mapper: can be ignored.
  55534. // input: {axisInfo, value}
  55535. // output: {axisInfo, value}
  55536. link: [],
  55537. // Do not set 'auto' here, otherwise global animation: false
  55538. // will not effect at this axispointer.
  55539. animation: null,
  55540. animationDurationUpdate: 200,
  55541. lineStyle: {
  55542. color: '#aaa',
  55543. width: 1,
  55544. type: 'solid'
  55545. },
  55546. shadowStyle: {
  55547. color: 'rgba(150,150,150,0.3)'
  55548. },
  55549. label: {
  55550. show: true,
  55551. formatter: null, // string | Function
  55552. precision: 'auto', // Or a number like 0, 1, 2 ...
  55553. margin: 3,
  55554. color: '#fff',
  55555. padding: [5, 7, 5, 7],
  55556. backgroundColor: 'auto', // default: axis line color
  55557. borderColor: null,
  55558. borderWidth: 0,
  55559. shadowBlur: 3,
  55560. shadowColor: '#aaa'
  55561. // Considering applicability, common style should
  55562. // better not have shadowOffset.
  55563. // shadowOffsetX: 0,
  55564. // shadowOffsetY: 2
  55565. },
  55566. handle: {
  55567. show: false,
  55568. 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
  55569. size: 45,
  55570. // handle margin is from symbol center to axis, which is stable when circular move.
  55571. margin: 50,
  55572. // color: '#1b8bbd'
  55573. // color: '#2f4554'
  55574. color: '#333',
  55575. shadowBlur: 3,
  55576. shadowColor: '#aaa',
  55577. shadowOffsetX: 0,
  55578. shadowOffsetY: 2,
  55579. // For mobile performance
  55580. throttle: 40
  55581. }
  55582. }
  55583. });
  55584. /*
  55585. * Licensed to the Apache Software Foundation (ASF) under one
  55586. * or more contributor license agreements. See the NOTICE file
  55587. * distributed with this work for additional information
  55588. * regarding copyright ownership. The ASF licenses this file
  55589. * to you under the Apache License, Version 2.0 (the
  55590. * "License"); you may not use this file except in compliance
  55591. * with the License. You may obtain a copy of the License at
  55592. *
  55593. * http://www.apache.org/licenses/LICENSE-2.0
  55594. *
  55595. * Unless required by applicable law or agreed to in writing,
  55596. * software distributed under the License is distributed on an
  55597. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55598. * KIND, either express or implied. See the License for the
  55599. * specific language governing permissions and limitations
  55600. * under the License.
  55601. */
  55602. var inner$8 = makeInner();
  55603. var each$15 = each$1;
  55604. /**
  55605. * @param {string} key
  55606. * @param {module:echarts/ExtensionAPI} api
  55607. * @param {Function} handler
  55608. * param: {string} currTrigger
  55609. * param: {Array.<number>} point
  55610. */
  55611. function register(key, api, handler) {
  55612. if (env$1.node) {
  55613. return;
  55614. }
  55615. var zr = api.getZr();
  55616. inner$8(zr).records || (inner$8(zr).records = {});
  55617. initGlobalListeners(zr, api);
  55618. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  55619. record.handler = handler;
  55620. }
  55621. function initGlobalListeners(zr, api) {
  55622. if (inner$8(zr).initialized) {
  55623. return;
  55624. }
  55625. inner$8(zr).initialized = true;
  55626. useHandler('click', curry(doEnter, 'click'));
  55627. useHandler('mousemove', curry(doEnter, 'mousemove'));
  55628. // useHandler('mouseout', onLeave);
  55629. useHandler('globalout', onLeave);
  55630. function useHandler(eventType, cb) {
  55631. zr.on(eventType, function (e) {
  55632. var dis = makeDispatchAction(api);
  55633. each$15(inner$8(zr).records, function (record) {
  55634. record && cb(record, e, dis.dispatchAction);
  55635. });
  55636. dispatchTooltipFinally(dis.pendings, api);
  55637. });
  55638. }
  55639. }
  55640. function dispatchTooltipFinally(pendings, api) {
  55641. var showLen = pendings.showTip.length;
  55642. var hideLen = pendings.hideTip.length;
  55643. var actuallyPayload;
  55644. if (showLen) {
  55645. actuallyPayload = pendings.showTip[showLen - 1];
  55646. }
  55647. else if (hideLen) {
  55648. actuallyPayload = pendings.hideTip[hideLen - 1];
  55649. }
  55650. if (actuallyPayload) {
  55651. actuallyPayload.dispatchAction = null;
  55652. api.dispatchAction(actuallyPayload);
  55653. }
  55654. }
  55655. function onLeave(record, e, dispatchAction) {
  55656. record.handler('leave', null, dispatchAction);
  55657. }
  55658. function doEnter(currTrigger, record, e, dispatchAction) {
  55659. record.handler(currTrigger, e, dispatchAction);
  55660. }
  55661. function makeDispatchAction(api) {
  55662. var pendings = {
  55663. showTip: [],
  55664. hideTip: []
  55665. };
  55666. // FIXME
  55667. // better approach?
  55668. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  55669. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  55670. // So we have to add "final stage" to merge those dispatched actions.
  55671. var dispatchAction = function (payload) {
  55672. var pendingList = pendings[payload.type];
  55673. if (pendingList) {
  55674. pendingList.push(payload);
  55675. }
  55676. else {
  55677. payload.dispatchAction = dispatchAction;
  55678. api.dispatchAction(payload);
  55679. }
  55680. };
  55681. return {
  55682. dispatchAction: dispatchAction,
  55683. pendings: pendings
  55684. };
  55685. }
  55686. /**
  55687. * @param {string} key
  55688. * @param {module:echarts/ExtensionAPI} api
  55689. */
  55690. function unregister(key, api) {
  55691. if (env$1.node) {
  55692. return;
  55693. }
  55694. var zr = api.getZr();
  55695. var record = (inner$8(zr).records || {})[key];
  55696. if (record) {
  55697. inner$8(zr).records[key] = null;
  55698. }
  55699. }
  55700. /*
  55701. * Licensed to the Apache Software Foundation (ASF) under one
  55702. * or more contributor license agreements. See the NOTICE file
  55703. * distributed with this work for additional information
  55704. * regarding copyright ownership. The ASF licenses this file
  55705. * to you under the Apache License, Version 2.0 (the
  55706. * "License"); you may not use this file except in compliance
  55707. * with the License. You may obtain a copy of the License at
  55708. *
  55709. * http://www.apache.org/licenses/LICENSE-2.0
  55710. *
  55711. * Unless required by applicable law or agreed to in writing,
  55712. * software distributed under the License is distributed on an
  55713. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55714. * KIND, either express or implied. See the License for the
  55715. * specific language governing permissions and limitations
  55716. * under the License.
  55717. */
  55718. var AxisPointerView = extendComponentView({
  55719. type: 'axisPointer',
  55720. render: function (globalAxisPointerModel, ecModel, api) {
  55721. var globalTooltipModel = ecModel.getComponent('tooltip');
  55722. var triggerOn = globalAxisPointerModel.get('triggerOn')
  55723. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  55724. // Register global listener in AxisPointerView to enable
  55725. // AxisPointerView to be independent to Tooltip.
  55726. register(
  55727. 'axisPointer',
  55728. api,
  55729. function (currTrigger, e, dispatchAction) {
  55730. // If 'none', it is not controlled by mouse totally.
  55731. if (triggerOn !== 'none'
  55732. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  55733. ) {
  55734. dispatchAction({
  55735. type: 'updateAxisPointer',
  55736. currTrigger: currTrigger,
  55737. x: e && e.offsetX,
  55738. y: e && e.offsetY
  55739. });
  55740. }
  55741. }
  55742. );
  55743. },
  55744. /**
  55745. * @override
  55746. */
  55747. remove: function (ecModel, api) {
  55748. unregister(api.getZr(), 'axisPointer');
  55749. AxisPointerView.superApply(this._model, 'remove', arguments);
  55750. },
  55751. /**
  55752. * @override
  55753. */
  55754. dispose: function (ecModel, api) {
  55755. unregister('axisPointer', api);
  55756. AxisPointerView.superApply(this._model, 'dispose', arguments);
  55757. }
  55758. });
  55759. /*
  55760. * Licensed to the Apache Software Foundation (ASF) under one
  55761. * or more contributor license agreements. See the NOTICE file
  55762. * distributed with this work for additional information
  55763. * regarding copyright ownership. The ASF licenses this file
  55764. * to you under the Apache License, Version 2.0 (the
  55765. * "License"); you may not use this file except in compliance
  55766. * with the License. You may obtain a copy of the License at
  55767. *
  55768. * http://www.apache.org/licenses/LICENSE-2.0
  55769. *
  55770. * Unless required by applicable law or agreed to in writing,
  55771. * software distributed under the License is distributed on an
  55772. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55773. * KIND, either express or implied. See the License for the
  55774. * specific language governing permissions and limitations
  55775. * under the License.
  55776. */
  55777. var inner$9 = makeInner();
  55778. var clone$4 = clone;
  55779. var bind$2 = bind;
  55780. /**
  55781. * Base axis pointer class in 2D.
  55782. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  55783. */
  55784. function BaseAxisPointer () {
  55785. }
  55786. BaseAxisPointer.prototype = {
  55787. /**
  55788. * @private
  55789. */
  55790. _group: null,
  55791. /**
  55792. * @private
  55793. */
  55794. _lastGraphicKey: null,
  55795. /**
  55796. * @private
  55797. */
  55798. _handle: null,
  55799. /**
  55800. * @private
  55801. */
  55802. _dragging: false,
  55803. /**
  55804. * @private
  55805. */
  55806. _lastValue: null,
  55807. /**
  55808. * @private
  55809. */
  55810. _lastStatus: null,
  55811. /**
  55812. * @private
  55813. */
  55814. _payloadInfo: null,
  55815. /**
  55816. * In px, arbitrary value. Do not set too small,
  55817. * no animation is ok for most cases.
  55818. * @protected
  55819. */
  55820. animationThreshold: 15,
  55821. /**
  55822. * @implement
  55823. */
  55824. render: function (axisModel, axisPointerModel, api, forceRender) {
  55825. var value = axisPointerModel.get('value');
  55826. var status = axisPointerModel.get('status');
  55827. // Bind them to `this`, not in closure, otherwise they will not
  55828. // be replaced when user calling setOption in not merge mode.
  55829. this._axisModel = axisModel;
  55830. this._axisPointerModel = axisPointerModel;
  55831. this._api = api;
  55832. // Optimize: `render` will be called repeatly during mouse move.
  55833. // So it is power consuming if performing `render` each time,
  55834. // especially on mobile device.
  55835. if (!forceRender
  55836. && this._lastValue === value
  55837. && this._lastStatus === status
  55838. ) {
  55839. return;
  55840. }
  55841. this._lastValue = value;
  55842. this._lastStatus = status;
  55843. var group = this._group;
  55844. var handle = this._handle;
  55845. if (!status || status === 'hide') {
  55846. // Do not clear here, for animation better.
  55847. group && group.hide();
  55848. handle && handle.hide();
  55849. return;
  55850. }
  55851. group && group.show();
  55852. handle && handle.show();
  55853. // Otherwise status is 'show'
  55854. var elOption = {};
  55855. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  55856. // Enable change axis pointer type.
  55857. var graphicKey = elOption.graphicKey;
  55858. if (graphicKey !== this._lastGraphicKey) {
  55859. this.clear(api);
  55860. }
  55861. this._lastGraphicKey = graphicKey;
  55862. var moveAnimation = this._moveAnimation =
  55863. this.determineAnimation(axisModel, axisPointerModel);
  55864. if (!group) {
  55865. group = this._group = new Group();
  55866. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  55867. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  55868. api.getZr().add(group);
  55869. }
  55870. else {
  55871. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  55872. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  55873. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  55874. }
  55875. updateMandatoryProps(group, axisPointerModel, true);
  55876. this._renderHandle(value);
  55877. },
  55878. /**
  55879. * @implement
  55880. */
  55881. remove: function (api) {
  55882. this.clear(api);
  55883. },
  55884. /**
  55885. * @implement
  55886. */
  55887. dispose: function (api) {
  55888. this.clear(api);
  55889. },
  55890. /**
  55891. * @protected
  55892. */
  55893. determineAnimation: function (axisModel, axisPointerModel) {
  55894. var animation = axisPointerModel.get('animation');
  55895. var axis = axisModel.axis;
  55896. var isCategoryAxis = axis.type === 'category';
  55897. var useSnap = axisPointerModel.get('snap');
  55898. // Value axis without snap always do not snap.
  55899. if (!useSnap && !isCategoryAxis) {
  55900. return false;
  55901. }
  55902. if (animation === 'auto' || animation == null) {
  55903. var animationThreshold = this.animationThreshold;
  55904. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  55905. return true;
  55906. }
  55907. // It is important to auto animation when snap used. Consider if there is
  55908. // a dataZoom, animation will be disabled when too many points exist, while
  55909. // it will be enabled for better visual effect when little points exist.
  55910. if (useSnap) {
  55911. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  55912. var axisExtent = axis.getExtent();
  55913. // Approximate band width
  55914. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  55915. }
  55916. return false;
  55917. }
  55918. return animation === true;
  55919. },
  55920. /**
  55921. * add {pointer, label, graphicKey} to elOption
  55922. * @protected
  55923. */
  55924. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  55925. // Shoule be implemenented by sub-class.
  55926. },
  55927. /**
  55928. * @protected
  55929. */
  55930. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  55931. var pointerOption = elOption.pointer;
  55932. if (pointerOption) {
  55933. var pointerEl = inner$9(group).pointerEl = new graphic[pointerOption.type](
  55934. clone$4(elOption.pointer)
  55935. );
  55936. group.add(pointerEl);
  55937. }
  55938. },
  55939. /**
  55940. * @protected
  55941. */
  55942. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  55943. if (elOption.label) {
  55944. var labelEl = inner$9(group).labelEl = new Rect(
  55945. clone$4(elOption.label)
  55946. );
  55947. group.add(labelEl);
  55948. updateLabelShowHide(labelEl, axisPointerModel);
  55949. }
  55950. },
  55951. /**
  55952. * @protected
  55953. */
  55954. updatePointerEl: function (group, elOption, updateProps$$1) {
  55955. var pointerEl = inner$9(group).pointerEl;
  55956. if (pointerEl) {
  55957. pointerEl.setStyle(elOption.pointer.style);
  55958. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  55959. }
  55960. },
  55961. /**
  55962. * @protected
  55963. */
  55964. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  55965. var labelEl = inner$9(group).labelEl;
  55966. if (labelEl) {
  55967. labelEl.setStyle(elOption.label.style);
  55968. updateProps$$1(labelEl, {
  55969. // Consider text length change in vertical axis, animation should
  55970. // be used on shape, otherwise the effect will be weird.
  55971. shape: elOption.label.shape,
  55972. position: elOption.label.position
  55973. });
  55974. updateLabelShowHide(labelEl, axisPointerModel);
  55975. }
  55976. },
  55977. /**
  55978. * @private
  55979. */
  55980. _renderHandle: function (value) {
  55981. if (this._dragging || !this.updateHandleTransform) {
  55982. return;
  55983. }
  55984. var axisPointerModel = this._axisPointerModel;
  55985. var zr = this._api.getZr();
  55986. var handle = this._handle;
  55987. var handleModel = axisPointerModel.getModel('handle');
  55988. var status = axisPointerModel.get('status');
  55989. if (!handleModel.get('show') || !status || status === 'hide') {
  55990. handle && zr.remove(handle);
  55991. this._handle = null;
  55992. return;
  55993. }
  55994. var isInit;
  55995. if (!this._handle) {
  55996. isInit = true;
  55997. handle = this._handle = createIcon(
  55998. handleModel.get('icon'),
  55999. {
  56000. cursor: 'move',
  56001. draggable: true,
  56002. onmousemove: function (e) {
  56003. // Fot mobile devicem, prevent screen slider on the button.
  56004. stop(e.event);
  56005. },
  56006. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  56007. drift: bind$2(this._onHandleDragMove, this),
  56008. ondragend: bind$2(this._onHandleDragEnd, this)
  56009. }
  56010. );
  56011. zr.add(handle);
  56012. }
  56013. updateMandatoryProps(handle, axisPointerModel, false);
  56014. // update style
  56015. var includeStyles = [
  56016. 'color', 'borderColor', 'borderWidth', 'opacity',
  56017. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  56018. ];
  56019. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  56020. // update position
  56021. var handleSize = handleModel.get('size');
  56022. if (!isArray(handleSize)) {
  56023. handleSize = [handleSize, handleSize];
  56024. }
  56025. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  56026. createOrUpdate(
  56027. this,
  56028. '_doDispatchAxisPointer',
  56029. handleModel.get('throttle') || 0,
  56030. 'fixRate'
  56031. );
  56032. this._moveHandleToValue(value, isInit);
  56033. },
  56034. /**
  56035. * @private
  56036. */
  56037. _moveHandleToValue: function (value, isInit) {
  56038. updateProps$1(
  56039. this._axisPointerModel,
  56040. !isInit && this._moveAnimation,
  56041. this._handle,
  56042. getHandleTransProps(this.getHandleTransform(
  56043. value, this._axisModel, this._axisPointerModel
  56044. ))
  56045. );
  56046. },
  56047. /**
  56048. * @private
  56049. */
  56050. _onHandleDragMove: function (dx, dy) {
  56051. var handle = this._handle;
  56052. if (!handle) {
  56053. return;
  56054. }
  56055. this._dragging = true;
  56056. // Persistent for throttle.
  56057. var trans = this.updateHandleTransform(
  56058. getHandleTransProps(handle),
  56059. [dx, dy],
  56060. this._axisModel,
  56061. this._axisPointerModel
  56062. );
  56063. this._payloadInfo = trans;
  56064. handle.stopAnimation();
  56065. handle.attr(getHandleTransProps(trans));
  56066. inner$9(handle).lastProp = null;
  56067. this._doDispatchAxisPointer();
  56068. },
  56069. /**
  56070. * Throttled method.
  56071. * @private
  56072. */
  56073. _doDispatchAxisPointer: function () {
  56074. var handle = this._handle;
  56075. if (!handle) {
  56076. return;
  56077. }
  56078. var payloadInfo = this._payloadInfo;
  56079. var axisModel = this._axisModel;
  56080. this._api.dispatchAction({
  56081. type: 'updateAxisPointer',
  56082. x: payloadInfo.cursorPoint[0],
  56083. y: payloadInfo.cursorPoint[1],
  56084. tooltipOption: payloadInfo.tooltipOption,
  56085. axesInfo: [{
  56086. axisDim: axisModel.axis.dim,
  56087. axisIndex: axisModel.componentIndex
  56088. }]
  56089. });
  56090. },
  56091. /**
  56092. * @private
  56093. */
  56094. _onHandleDragEnd: function (moveAnimation) {
  56095. this._dragging = false;
  56096. var handle = this._handle;
  56097. if (!handle) {
  56098. return;
  56099. }
  56100. var value = this._axisPointerModel.get('value');
  56101. // Consider snap or categroy axis, handle may be not consistent with
  56102. // axisPointer. So move handle to align the exact value position when
  56103. // drag ended.
  56104. this._moveHandleToValue(value);
  56105. // For the effect: tooltip will be shown when finger holding on handle
  56106. // button, and will be hidden after finger left handle button.
  56107. this._api.dispatchAction({
  56108. type: 'hideTip'
  56109. });
  56110. },
  56111. /**
  56112. * Should be implemenented by sub-class if support `handle`.
  56113. * @protected
  56114. * @param {number} value
  56115. * @param {module:echarts/model/Model} axisModel
  56116. * @param {module:echarts/model/Model} axisPointerModel
  56117. * @return {Object} {position: [x, y], rotation: 0}
  56118. */
  56119. getHandleTransform: null,
  56120. /**
  56121. * * Should be implemenented by sub-class if support `handle`.
  56122. * @protected
  56123. * @param {Object} transform {position, rotation}
  56124. * @param {Array.<number>} delta [dx, dy]
  56125. * @param {module:echarts/model/Model} axisModel
  56126. * @param {module:echarts/model/Model} axisPointerModel
  56127. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  56128. */
  56129. updateHandleTransform: null,
  56130. /**
  56131. * @private
  56132. */
  56133. clear: function (api) {
  56134. this._lastValue = null;
  56135. this._lastStatus = null;
  56136. var zr = api.getZr();
  56137. var group = this._group;
  56138. var handle = this._handle;
  56139. if (zr && group) {
  56140. this._lastGraphicKey = null;
  56141. group && zr.remove(group);
  56142. handle && zr.remove(handle);
  56143. this._group = null;
  56144. this._handle = null;
  56145. this._payloadInfo = null;
  56146. }
  56147. },
  56148. /**
  56149. * @protected
  56150. */
  56151. doClear: function () {
  56152. // Implemented by sub-class if necessary.
  56153. },
  56154. /**
  56155. * @protected
  56156. * @param {Array.<number>} xy
  56157. * @param {Array.<number>} wh
  56158. * @param {number} [xDimIndex=0] or 1
  56159. */
  56160. buildLabel: function (xy, wh, xDimIndex) {
  56161. xDimIndex = xDimIndex || 0;
  56162. return {
  56163. x: xy[xDimIndex],
  56164. y: xy[1 - xDimIndex],
  56165. width: wh[xDimIndex],
  56166. height: wh[1 - xDimIndex]
  56167. };
  56168. }
  56169. };
  56170. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  56171. function updateProps$1(animationModel, moveAnimation, el, props) {
  56172. // Animation optimize.
  56173. if (!propsEqual(inner$9(el).lastProp, props)) {
  56174. inner$9(el).lastProp = props;
  56175. moveAnimation
  56176. ? updateProps(el, props, animationModel)
  56177. : (el.stopAnimation(), el.attr(props));
  56178. }
  56179. }
  56180. function propsEqual(lastProps, newProps) {
  56181. if (isObject$1(lastProps) && isObject$1(newProps)) {
  56182. var equals = true;
  56183. each$1(newProps, function (item, key) {
  56184. equals = equals && propsEqual(lastProps[key], item);
  56185. });
  56186. return !!equals;
  56187. }
  56188. else {
  56189. return lastProps === newProps;
  56190. }
  56191. }
  56192. function updateLabelShowHide(labelEl, axisPointerModel) {
  56193. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  56194. }
  56195. function getHandleTransProps(trans) {
  56196. return {
  56197. position: trans.position.slice(),
  56198. rotation: trans.rotation || 0
  56199. };
  56200. }
  56201. function updateMandatoryProps(group, axisPointerModel, silent) {
  56202. var z = axisPointerModel.get('z');
  56203. var zlevel = axisPointerModel.get('zlevel');
  56204. group && group.traverse(function (el) {
  56205. if (el.type !== 'group') {
  56206. z != null && (el.z = z);
  56207. zlevel != null && (el.zlevel = zlevel);
  56208. el.silent = silent;
  56209. }
  56210. });
  56211. }
  56212. enableClassExtend(BaseAxisPointer);
  56213. /*
  56214. * Licensed to the Apache Software Foundation (ASF) under one
  56215. * or more contributor license agreements. See the NOTICE file
  56216. * distributed with this work for additional information
  56217. * regarding copyright ownership. The ASF licenses this file
  56218. * to you under the Apache License, Version 2.0 (the
  56219. * "License"); you may not use this file except in compliance
  56220. * with the License. You may obtain a copy of the License at
  56221. *
  56222. * http://www.apache.org/licenses/LICENSE-2.0
  56223. *
  56224. * Unless required by applicable law or agreed to in writing,
  56225. * software distributed under the License is distributed on an
  56226. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56227. * KIND, either express or implied. See the License for the
  56228. * specific language governing permissions and limitations
  56229. * under the License.
  56230. */
  56231. /**
  56232. * @param {module:echarts/model/Model} axisPointerModel
  56233. */
  56234. function buildElStyle(axisPointerModel) {
  56235. var axisPointerType = axisPointerModel.get('type');
  56236. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  56237. var style;
  56238. if (axisPointerType === 'line') {
  56239. style = styleModel.getLineStyle();
  56240. style.fill = null;
  56241. }
  56242. else if (axisPointerType === 'shadow') {
  56243. style = styleModel.getAreaStyle();
  56244. style.stroke = null;
  56245. }
  56246. return style;
  56247. }
  56248. /**
  56249. * @param {Function} labelPos {align, verticalAlign, position}
  56250. */
  56251. function buildLabelElOption(
  56252. elOption, axisModel, axisPointerModel, api, labelPos
  56253. ) {
  56254. var value = axisPointerModel.get('value');
  56255. var text = getValueLabel(
  56256. value, axisModel.axis, axisModel.ecModel,
  56257. axisPointerModel.get('seriesDataIndices'),
  56258. {
  56259. precision: axisPointerModel.get('label.precision'),
  56260. formatter: axisPointerModel.get('label.formatter')
  56261. }
  56262. );
  56263. var labelModel = axisPointerModel.getModel('label');
  56264. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  56265. var font = labelModel.getFont();
  56266. var textRect = getBoundingRect(text, font);
  56267. var position = labelPos.position;
  56268. var width = textRect.width + paddings[1] + paddings[3];
  56269. var height = textRect.height + paddings[0] + paddings[2];
  56270. // Adjust by align.
  56271. var align = labelPos.align;
  56272. align === 'right' && (position[0] -= width);
  56273. align === 'center' && (position[0] -= width / 2);
  56274. var verticalAlign = labelPos.verticalAlign;
  56275. verticalAlign === 'bottom' && (position[1] -= height);
  56276. verticalAlign === 'middle' && (position[1] -= height / 2);
  56277. // Not overflow ec container
  56278. confineInContainer(position, width, height, api);
  56279. var bgColor = labelModel.get('backgroundColor');
  56280. if (!bgColor || bgColor === 'auto') {
  56281. bgColor = axisModel.get('axisLine.lineStyle.color');
  56282. }
  56283. elOption.label = {
  56284. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  56285. position: position.slice(),
  56286. // TODO: rich
  56287. style: {
  56288. text: text,
  56289. textFont: font,
  56290. textFill: labelModel.getTextColor(),
  56291. textPosition: 'inside',
  56292. fill: bgColor,
  56293. stroke: labelModel.get('borderColor') || 'transparent',
  56294. lineWidth: labelModel.get('borderWidth') || 0,
  56295. shadowBlur: labelModel.get('shadowBlur'),
  56296. shadowColor: labelModel.get('shadowColor'),
  56297. shadowOffsetX: labelModel.get('shadowOffsetX'),
  56298. shadowOffsetY: labelModel.get('shadowOffsetY')
  56299. },
  56300. // Lable should be over axisPointer.
  56301. z2: 10
  56302. };
  56303. }
  56304. // Do not overflow ec container
  56305. function confineInContainer(position, width, height, api) {
  56306. var viewWidth = api.getWidth();
  56307. var viewHeight = api.getHeight();
  56308. position[0] = Math.min(position[0] + width, viewWidth) - width;
  56309. position[1] = Math.min(position[1] + height, viewHeight) - height;
  56310. position[0] = Math.max(position[0], 0);
  56311. position[1] = Math.max(position[1], 0);
  56312. }
  56313. /**
  56314. * @param {number} value
  56315. * @param {module:echarts/coord/Axis} axis
  56316. * @param {module:echarts/model/Global} ecModel
  56317. * @param {Object} opt
  56318. * @param {Array.<Object>} seriesDataIndices
  56319. * @param {number|string} opt.precision 'auto' or a number
  56320. * @param {string|Function} opt.formatter label formatter
  56321. */
  56322. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  56323. value = axis.scale.parse(value);
  56324. var text = axis.scale.getLabel(
  56325. // If `precision` is set, width can be fixed (like '12.00500'), which
  56326. // helps to debounce when when moving label.
  56327. value, {precision: opt.precision}
  56328. );
  56329. var formatter = opt.formatter;
  56330. if (formatter) {
  56331. var params = {
  56332. value: getAxisRawValue(axis, value),
  56333. seriesData: []
  56334. };
  56335. each$1(seriesDataIndices, function (idxItem) {
  56336. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  56337. var dataIndex = idxItem.dataIndexInside;
  56338. var dataParams = series && series.getDataParams(dataIndex);
  56339. dataParams && params.seriesData.push(dataParams);
  56340. });
  56341. if (isString(formatter)) {
  56342. text = formatter.replace('{value}', text);
  56343. }
  56344. else if (isFunction$1(formatter)) {
  56345. text = formatter(params);
  56346. }
  56347. }
  56348. return text;
  56349. }
  56350. /**
  56351. * @param {module:echarts/coord/Axis} axis
  56352. * @param {number} value
  56353. * @param {Object} layoutInfo {
  56354. * rotation, position, labelOffset, labelDirection, labelMargin
  56355. * }
  56356. */
  56357. function getTransformedPosition (axis, value, layoutInfo) {
  56358. var transform = create$1();
  56359. rotate(transform, transform, layoutInfo.rotation);
  56360. translate(transform, transform, layoutInfo.position);
  56361. return applyTransform$1([
  56362. axis.dataToCoord(value),
  56363. (layoutInfo.labelOffset || 0)
  56364. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  56365. ], transform);
  56366. }
  56367. function buildCartesianSingleLabelElOption(
  56368. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  56369. ) {
  56370. var textLayout = AxisBuilder.innerTextLayout(
  56371. layoutInfo.rotation, 0, layoutInfo.labelDirection
  56372. );
  56373. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  56374. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  56375. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  56376. align: textLayout.textAlign,
  56377. verticalAlign: textLayout.textVerticalAlign
  56378. });
  56379. }
  56380. /**
  56381. * @param {Array.<number>} p1
  56382. * @param {Array.<number>} p2
  56383. * @param {number} [xDimIndex=0] or 1
  56384. */
  56385. function makeLineShape(p1, p2, xDimIndex) {
  56386. xDimIndex = xDimIndex || 0;
  56387. return {
  56388. x1: p1[xDimIndex],
  56389. y1: p1[1 - xDimIndex],
  56390. x2: p2[xDimIndex],
  56391. y2: p2[1 - xDimIndex]
  56392. };
  56393. }
  56394. /**
  56395. * @param {Array.<number>} xy
  56396. * @param {Array.<number>} wh
  56397. * @param {number} [xDimIndex=0] or 1
  56398. */
  56399. function makeRectShape(xy, wh, xDimIndex) {
  56400. xDimIndex = xDimIndex || 0;
  56401. return {
  56402. x: xy[xDimIndex],
  56403. y: xy[1 - xDimIndex],
  56404. width: wh[xDimIndex],
  56405. height: wh[1 - xDimIndex]
  56406. };
  56407. }
  56408. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  56409. return {
  56410. cx: cx,
  56411. cy: cy,
  56412. r0: r0,
  56413. r: r,
  56414. startAngle: startAngle,
  56415. endAngle: endAngle,
  56416. clockwise: true
  56417. };
  56418. }
  56419. /*
  56420. * Licensed to the Apache Software Foundation (ASF) under one
  56421. * or more contributor license agreements. See the NOTICE file
  56422. * distributed with this work for additional information
  56423. * regarding copyright ownership. The ASF licenses this file
  56424. * to you under the Apache License, Version 2.0 (the
  56425. * "License"); you may not use this file except in compliance
  56426. * with the License. You may obtain a copy of the License at
  56427. *
  56428. * http://www.apache.org/licenses/LICENSE-2.0
  56429. *
  56430. * Unless required by applicable law or agreed to in writing,
  56431. * software distributed under the License is distributed on an
  56432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56433. * KIND, either express or implied. See the License for the
  56434. * specific language governing permissions and limitations
  56435. * under the License.
  56436. */
  56437. var CartesianAxisPointer = BaseAxisPointer.extend({
  56438. /**
  56439. * @override
  56440. */
  56441. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  56442. var axis = axisModel.axis;
  56443. var grid = axis.grid;
  56444. var axisPointerType = axisPointerModel.get('type');
  56445. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  56446. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  56447. if (axisPointerType && axisPointerType !== 'none') {
  56448. var elStyle = buildElStyle(axisPointerModel);
  56449. var pointerOption = pointerShapeBuilder[axisPointerType](
  56450. axis, pixelValue, otherExtent, elStyle
  56451. );
  56452. pointerOption.style = elStyle;
  56453. elOption.graphicKey = pointerOption.type;
  56454. elOption.pointer = pointerOption;
  56455. }
  56456. var layoutInfo = layout$1(grid.model, axisModel);
  56457. buildCartesianSingleLabelElOption(
  56458. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  56459. );
  56460. },
  56461. /**
  56462. * @override
  56463. */
  56464. getHandleTransform: function (value, axisModel, axisPointerModel) {
  56465. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  56466. labelInside: false
  56467. });
  56468. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  56469. return {
  56470. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  56471. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  56472. };
  56473. },
  56474. /**
  56475. * @override
  56476. */
  56477. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  56478. var axis = axisModel.axis;
  56479. var grid = axis.grid;
  56480. var axisExtent = axis.getGlobalExtent(true);
  56481. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  56482. var dimIndex = axis.dim === 'x' ? 0 : 1;
  56483. var currPosition = transform.position;
  56484. currPosition[dimIndex] += delta[dimIndex];
  56485. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  56486. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  56487. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  56488. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  56489. cursorPoint[dimIndex] = currPosition[dimIndex];
  56490. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  56491. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  56492. return {
  56493. position: currPosition,
  56494. rotation: transform.rotation,
  56495. cursorPoint: cursorPoint,
  56496. tooltipOption: tooltipOptions[dimIndex]
  56497. };
  56498. }
  56499. });
  56500. function getCartesian(grid, axis) {
  56501. var opt = {};
  56502. opt[axis.dim + 'AxisIndex'] = axis.index;
  56503. return grid.getCartesian(opt);
  56504. }
  56505. var pointerShapeBuilder = {
  56506. line: function (axis, pixelValue, otherExtent, elStyle) {
  56507. var targetShape = makeLineShape(
  56508. [pixelValue, otherExtent[0]],
  56509. [pixelValue, otherExtent[1]],
  56510. getAxisDimIndex(axis)
  56511. );
  56512. subPixelOptimizeLine({
  56513. shape: targetShape,
  56514. style: elStyle
  56515. });
  56516. return {
  56517. type: 'Line',
  56518. shape: targetShape
  56519. };
  56520. },
  56521. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  56522. var bandWidth = Math.max(1, axis.getBandWidth());
  56523. var span = otherExtent[1] - otherExtent[0];
  56524. return {
  56525. type: 'Rect',
  56526. shape: makeRectShape(
  56527. [pixelValue - bandWidth / 2, otherExtent[0]],
  56528. [bandWidth, span],
  56529. getAxisDimIndex(axis)
  56530. )
  56531. };
  56532. }
  56533. };
  56534. function getAxisDimIndex(axis) {
  56535. return axis.dim === 'x' ? 0 : 1;
  56536. }
  56537. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  56538. /*
  56539. * Licensed to the Apache Software Foundation (ASF) under one
  56540. * or more contributor license agreements. See the NOTICE file
  56541. * distributed with this work for additional information
  56542. * regarding copyright ownership. The ASF licenses this file
  56543. * to you under the Apache License, Version 2.0 (the
  56544. * "License"); you may not use this file except in compliance
  56545. * with the License. You may obtain a copy of the License at
  56546. *
  56547. * http://www.apache.org/licenses/LICENSE-2.0
  56548. *
  56549. * Unless required by applicable law or agreed to in writing,
  56550. * software distributed under the License is distributed on an
  56551. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56552. * KIND, either express or implied. See the License for the
  56553. * specific language governing permissions and limitations
  56554. * under the License.
  56555. */
  56556. // CartesianAxisPointer is not supposed to be required here. But consider
  56557. // echarts.simple.js and online build tooltip, which only require gridSimple,
  56558. // CartesianAxisPointer should be able to required somewhere.
  56559. registerPreprocessor(function (option) {
  56560. // Always has a global axisPointerModel for default setting.
  56561. if (option) {
  56562. (!option.axisPointer || option.axisPointer.length === 0)
  56563. && (option.axisPointer = {});
  56564. var link = option.axisPointer.link;
  56565. // Normalize to array to avoid object mergin. But if link
  56566. // is not set, remain null/undefined, otherwise it will
  56567. // override existent link setting.
  56568. if (link && !isArray(link)) {
  56569. option.axisPointer.link = [link];
  56570. }
  56571. }
  56572. });
  56573. // This process should proformed after coordinate systems created
  56574. // and series data processed. So put it on statistic processing stage.
  56575. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  56576. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  56577. // allAxesInfo should be updated when setOption performed.
  56578. ecModel.getComponent('axisPointer').coordSysAxesInfo
  56579. = collect(ecModel, api);
  56580. });
  56581. // Broadcast to all views.
  56582. registerAction({
  56583. type: 'updateAxisPointer',
  56584. event: 'updateAxisPointer',
  56585. update: ':updateAxisPointer'
  56586. }, axisTrigger);
  56587. /*
  56588. * Licensed to the Apache Software Foundation (ASF) under one
  56589. * or more contributor license agreements. See the NOTICE file
  56590. * distributed with this work for additional information
  56591. * regarding copyright ownership. The ASF licenses this file
  56592. * to you under the Apache License, Version 2.0 (the
  56593. * "License"); you may not use this file except in compliance
  56594. * with the License. You may obtain a copy of the License at
  56595. *
  56596. * http://www.apache.org/licenses/LICENSE-2.0
  56597. *
  56598. * Unless required by applicable law or agreed to in writing,
  56599. * software distributed under the License is distributed on an
  56600. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56601. * KIND, either express or implied. See the License for the
  56602. * specific language governing permissions and limitations
  56603. * under the License.
  56604. */
  56605. var XY = ['x', 'y'];
  56606. var WH = ['width', 'height'];
  56607. var SingleAxisPointer = BaseAxisPointer.extend({
  56608. /**
  56609. * @override
  56610. */
  56611. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  56612. var axis = axisModel.axis;
  56613. var coordSys = axis.coordinateSystem;
  56614. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  56615. var pixelValue = coordSys.dataToPoint(value)[0];
  56616. var axisPointerType = axisPointerModel.get('type');
  56617. if (axisPointerType && axisPointerType !== 'none') {
  56618. var elStyle = buildElStyle(axisPointerModel);
  56619. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  56620. axis, pixelValue, otherExtent, elStyle
  56621. );
  56622. pointerOption.style = elStyle;
  56623. elOption.graphicKey = pointerOption.type;
  56624. elOption.pointer = pointerOption;
  56625. }
  56626. var layoutInfo = layout$2(axisModel);
  56627. buildCartesianSingleLabelElOption(
  56628. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  56629. );
  56630. },
  56631. /**
  56632. * @override
  56633. */
  56634. getHandleTransform: function (value, axisModel, axisPointerModel) {
  56635. var layoutInfo = layout$2(axisModel, {labelInside: false});
  56636. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  56637. return {
  56638. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  56639. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  56640. };
  56641. },
  56642. /**
  56643. * @override
  56644. */
  56645. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  56646. var axis = axisModel.axis;
  56647. var coordSys = axis.coordinateSystem;
  56648. var dimIndex = getPointDimIndex(axis);
  56649. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  56650. var currPosition = transform.position;
  56651. currPosition[dimIndex] += delta[dimIndex];
  56652. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  56653. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  56654. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  56655. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  56656. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  56657. cursorPoint[dimIndex] = currPosition[dimIndex];
  56658. return {
  56659. position: currPosition,
  56660. rotation: transform.rotation,
  56661. cursorPoint: cursorPoint,
  56662. tooltipOption: {
  56663. verticalAlign: 'middle'
  56664. }
  56665. };
  56666. }
  56667. });
  56668. var pointerShapeBuilder$1 = {
  56669. line: function (axis, pixelValue, otherExtent, elStyle) {
  56670. var targetShape = makeLineShape(
  56671. [pixelValue, otherExtent[0]],
  56672. [pixelValue, otherExtent[1]],
  56673. getPointDimIndex(axis)
  56674. );
  56675. subPixelOptimizeLine({
  56676. shape: targetShape,
  56677. style: elStyle
  56678. });
  56679. return {
  56680. type: 'Line',
  56681. shape: targetShape
  56682. };
  56683. },
  56684. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  56685. var bandWidth = axis.getBandWidth();
  56686. var span = otherExtent[1] - otherExtent[0];
  56687. return {
  56688. type: 'Rect',
  56689. shape: makeRectShape(
  56690. [pixelValue - bandWidth / 2, otherExtent[0]],
  56691. [bandWidth, span],
  56692. getPointDimIndex(axis)
  56693. )
  56694. };
  56695. }
  56696. };
  56697. function getPointDimIndex(axis) {
  56698. return axis.isHorizontal() ? 0 : 1;
  56699. }
  56700. function getGlobalExtent(coordSys, dimIndex) {
  56701. var rect = coordSys.getRect();
  56702. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  56703. }
  56704. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  56705. /*
  56706. * Licensed to the Apache Software Foundation (ASF) under one
  56707. * or more contributor license agreements. See the NOTICE file
  56708. * distributed with this work for additional information
  56709. * regarding copyright ownership. The ASF licenses this file
  56710. * to you under the Apache License, Version 2.0 (the
  56711. * "License"); you may not use this file except in compliance
  56712. * with the License. You may obtain a copy of the License at
  56713. *
  56714. * http://www.apache.org/licenses/LICENSE-2.0
  56715. *
  56716. * Unless required by applicable law or agreed to in writing,
  56717. * software distributed under the License is distributed on an
  56718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56719. * KIND, either express or implied. See the License for the
  56720. * specific language governing permissions and limitations
  56721. * under the License.
  56722. */
  56723. extendComponentView({
  56724. type: 'single'
  56725. });
  56726. /*
  56727. * Licensed to the Apache Software Foundation (ASF) under one
  56728. * or more contributor license agreements. See the NOTICE file
  56729. * distributed with this work for additional information
  56730. * regarding copyright ownership. The ASF licenses this file
  56731. * to you under the Apache License, Version 2.0 (the
  56732. * "License"); you may not use this file except in compliance
  56733. * with the License. You may obtain a copy of the License at
  56734. *
  56735. * http://www.apache.org/licenses/LICENSE-2.0
  56736. *
  56737. * Unless required by applicable law or agreed to in writing,
  56738. * software distributed under the License is distributed on an
  56739. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56740. * KIND, either express or implied. See the License for the
  56741. * specific language governing permissions and limitations
  56742. * under the License.
  56743. */
  56744. /**
  56745. * @file Define the themeRiver view's series model
  56746. * @author Deqing Li(annong035@gmail.com)
  56747. */
  56748. var DATA_NAME_INDEX = 2;
  56749. var ThemeRiverSeries = SeriesModel.extend({
  56750. type: 'series.themeRiver',
  56751. dependencies: ['singleAxis'],
  56752. /**
  56753. * @readOnly
  56754. * @type {module:zrender/core/util#HashMap}
  56755. */
  56756. nameMap: null,
  56757. /**
  56758. * @override
  56759. */
  56760. init: function (option) {
  56761. ThemeRiverSeries.superApply(this, 'init', arguments);
  56762. // Put this function here is for the sake of consistency of code style.
  56763. // Enable legend selection for each data item
  56764. // Use a function instead of direct access because data reference may changed
  56765. this.legendDataProvider = function () {
  56766. return this.getRawData();
  56767. };
  56768. },
  56769. /**
  56770. * If there is no value of a certain point in the time for some event,set it value to 0.
  56771. *
  56772. * @param {Array} data initial data in the option
  56773. * @return {Array}
  56774. */
  56775. fixData: function (data) {
  56776. var rawDataLength = data.length;
  56777. // grouped data by name
  56778. var dataByName = nest()
  56779. .key(function (dataItem) {
  56780. return dataItem[2];
  56781. })
  56782. .entries(data);
  56783. // data group in each layer
  56784. var layData = map(dataByName, function (d) {
  56785. return {
  56786. name: d.key,
  56787. dataList: d.values
  56788. };
  56789. });
  56790. var layerNum = layData.length;
  56791. var largestLayer = -1;
  56792. var index = -1;
  56793. for (var i = 0; i < layerNum; ++i) {
  56794. var len = layData[i].dataList.length;
  56795. if (len > largestLayer) {
  56796. largestLayer = len;
  56797. index = i;
  56798. }
  56799. }
  56800. for (var k = 0; k < layerNum; ++k) {
  56801. if (k === index) {
  56802. continue;
  56803. }
  56804. var name = layData[k].name;
  56805. for (var j = 0; j < largestLayer; ++j) {
  56806. var timeValue = layData[index].dataList[j][0];
  56807. var length = layData[k].dataList.length;
  56808. var keyIndex = -1;
  56809. for (var l = 0; l < length; ++l) {
  56810. var value = layData[k].dataList[l][0];
  56811. if (value === timeValue) {
  56812. keyIndex = l;
  56813. break;
  56814. }
  56815. }
  56816. if (keyIndex === -1) {
  56817. data[rawDataLength] = [];
  56818. data[rawDataLength][0] = timeValue;
  56819. data[rawDataLength][1] = 0;
  56820. data[rawDataLength][2] = name;
  56821. rawDataLength++;
  56822. }
  56823. }
  56824. }
  56825. return data;
  56826. },
  56827. /**
  56828. * @override
  56829. * @param {Object} option the initial option that user gived
  56830. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  56831. * @return {module:echarts/data/List}
  56832. */
  56833. getInitialData: function (option, ecModel) {
  56834. var singleAxisModel = ecModel.queryComponents({
  56835. mainType: 'singleAxis',
  56836. index: this.get('singleAxisIndex'),
  56837. id: this.get('singleAxisId')
  56838. })[0];
  56839. var axisType = singleAxisModel.get('type');
  56840. // filter the data item with the value of label is undefined
  56841. var filterData = filter(option.data, function (dataItem) {
  56842. return dataItem[2] !== undefined;
  56843. });
  56844. // ??? TODO design a stage to transfer data for themeRiver and lines?
  56845. var data = this.fixData(filterData || []);
  56846. var nameList = [];
  56847. var nameMap = this.nameMap = createHashMap();
  56848. var count = 0;
  56849. for (var i = 0; i < data.length; ++i) {
  56850. nameList.push(data[i][DATA_NAME_INDEX]);
  56851. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  56852. nameMap.set(data[i][DATA_NAME_INDEX], count);
  56853. count++;
  56854. }
  56855. }
  56856. var dimensionsInfo = createDimensions(data, {
  56857. coordDimensions: ['single'],
  56858. dimensionsDefine: [
  56859. {
  56860. name: 'time',
  56861. type: getDimensionTypeByAxis(axisType)
  56862. },
  56863. {
  56864. name: 'value',
  56865. type: 'float'
  56866. },
  56867. {
  56868. name: 'name',
  56869. type: 'ordinal'
  56870. }
  56871. ],
  56872. encodeDefine: {
  56873. single: 0,
  56874. value: 1,
  56875. itemName: 2
  56876. }
  56877. });
  56878. var list = new List(dimensionsInfo, this);
  56879. list.initData(data);
  56880. return list;
  56881. },
  56882. /**
  56883. * The raw data is divided into multiple layers and each layer
  56884. * has same name.
  56885. *
  56886. * @return {Array.<Array.<number>>}
  56887. */
  56888. getLayerSeries: function () {
  56889. var data = this.getData();
  56890. var lenCount = data.count();
  56891. var indexArr = [];
  56892. for (var i = 0; i < lenCount; ++i) {
  56893. indexArr[i] = i;
  56894. }
  56895. // data group by name
  56896. var dataByName = nest()
  56897. .key(function (index) {
  56898. return data.get('name', index);
  56899. })
  56900. .entries(indexArr);
  56901. var layerSeries = map(dataByName, function (d) {
  56902. return {
  56903. name: d.key,
  56904. indices: d.values
  56905. };
  56906. });
  56907. var timeDim = data.mapDimension('single');
  56908. for (var j = 0; j < layerSeries.length; ++j) {
  56909. layerSeries[j].indices.sort(comparer);
  56910. }
  56911. function comparer(index1, index2) {
  56912. return data.get(timeDim, index1) - data.get(timeDim, index2);
  56913. }
  56914. return layerSeries;
  56915. },
  56916. /**
  56917. * Get data indices for show tooltip content
  56918. *
  56919. * @param {Array.<string>|string} dim single coordinate dimension
  56920. * @param {number} value axis value
  56921. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  56922. * the themeRiver.
  56923. * @return {Object} {dataIndices, nestestValue}
  56924. */
  56925. getAxisTooltipData: function (dim, value, baseAxis) {
  56926. if (!isArray(dim)) {
  56927. dim = dim ? [dim] : [];
  56928. }
  56929. var data = this.getData();
  56930. var layerSeries = this.getLayerSeries();
  56931. var indices = [];
  56932. var layerNum = layerSeries.length;
  56933. var nestestValue;
  56934. for (var i = 0; i < layerNum; ++i) {
  56935. var minDist = Number.MAX_VALUE;
  56936. var nearestIdx = -1;
  56937. var pointNum = layerSeries[i].indices.length;
  56938. for (var j = 0; j < pointNum; ++j) {
  56939. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  56940. var dist = Math.abs(theValue - value);
  56941. if (dist <= minDist) {
  56942. nestestValue = theValue;
  56943. minDist = dist;
  56944. nearestIdx = layerSeries[i].indices[j];
  56945. }
  56946. }
  56947. indices.push(nearestIdx);
  56948. }
  56949. return {dataIndices: indices, nestestValue: nestestValue};
  56950. },
  56951. /**
  56952. * @override
  56953. * @param {number} dataIndex index of data
  56954. */
  56955. formatTooltip: function (dataIndex) {
  56956. var data = this.getData();
  56957. var htmlName = data.getName(dataIndex);
  56958. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  56959. if (isNaN(htmlValue) || htmlValue == null) {
  56960. htmlValue = '-';
  56961. }
  56962. return encodeHTML(htmlName + ' : ' + htmlValue);
  56963. },
  56964. defaultOption: {
  56965. zlevel: 0,
  56966. z: 2,
  56967. coordinateSystem: 'singleAxis',
  56968. // gap in axis's orthogonal orientation
  56969. boundaryGap: ['10%', '10%'],
  56970. // legendHoverLink: true,
  56971. singleAxisIndex: 0,
  56972. animationEasing: 'linear',
  56973. label: {
  56974. margin: 4,
  56975. show: true,
  56976. position: 'left',
  56977. color: '#000',
  56978. fontSize: 11
  56979. },
  56980. emphasis: {
  56981. label: {
  56982. show: true
  56983. }
  56984. }
  56985. }
  56986. });
  56987. /*
  56988. * Licensed to the Apache Software Foundation (ASF) under one
  56989. * or more contributor license agreements. See the NOTICE file
  56990. * distributed with this work for additional information
  56991. * regarding copyright ownership. The ASF licenses this file
  56992. * to you under the Apache License, Version 2.0 (the
  56993. * "License"); you may not use this file except in compliance
  56994. * with the License. You may obtain a copy of the License at
  56995. *
  56996. * http://www.apache.org/licenses/LICENSE-2.0
  56997. *
  56998. * Unless required by applicable law or agreed to in writing,
  56999. * software distributed under the License is distributed on an
  57000. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57001. * KIND, either express or implied. See the License for the
  57002. * specific language governing permissions and limitations
  57003. * under the License.
  57004. */
  57005. /**
  57006. * @file The file used to draw themeRiver view
  57007. * @author Deqing Li(annong035@gmail.com)
  57008. */
  57009. extendChartView({
  57010. type: 'themeRiver',
  57011. init: function () {
  57012. this._layers = [];
  57013. },
  57014. render: function (seriesModel, ecModel, api) {
  57015. var data = seriesModel.getData();
  57016. var group = this.group;
  57017. var layerSeries = seriesModel.getLayerSeries();
  57018. var layoutInfo = data.getLayout('layoutInfo');
  57019. var rect = layoutInfo.rect;
  57020. var boundaryGap = layoutInfo.boundaryGap;
  57021. group.attr('position', [0, rect.y + boundaryGap[0]]);
  57022. function keyGetter(item) {
  57023. return item.name;
  57024. }
  57025. var dataDiffer = new DataDiffer(
  57026. this._layersSeries || [], layerSeries,
  57027. keyGetter, keyGetter
  57028. );
  57029. var newLayersGroups = {};
  57030. dataDiffer
  57031. .add(bind(process, this, 'add'))
  57032. .update(bind(process, this, 'update'))
  57033. .remove(bind(process, this, 'remove'))
  57034. .execute();
  57035. function process(status, idx, oldIdx) {
  57036. var oldLayersGroups = this._layers;
  57037. if (status === 'remove') {
  57038. group.remove(oldLayersGroups[idx]);
  57039. return;
  57040. }
  57041. var points0 = [];
  57042. var points1 = [];
  57043. var color;
  57044. var indices = layerSeries[idx].indices;
  57045. for (var j = 0; j < indices.length; j++) {
  57046. var layout = data.getItemLayout(indices[j]);
  57047. var x = layout.x;
  57048. var y0 = layout.y0;
  57049. var y = layout.y;
  57050. points0.push([x, y0]);
  57051. points1.push([x, y0 + y]);
  57052. color = data.getItemVisual(indices[j], 'color');
  57053. }
  57054. var polygon;
  57055. var text;
  57056. var textLayout = data.getItemLayout(indices[0]);
  57057. var itemModel = data.getItemModel(indices[j - 1]);
  57058. var labelModel = itemModel.getModel('label');
  57059. var margin = labelModel.get('margin');
  57060. if (status === 'add') {
  57061. var layerGroup = newLayersGroups[idx] = new Group();
  57062. polygon = new Polygon$1({
  57063. shape: {
  57064. points: points0,
  57065. stackedOnPoints: points1,
  57066. smooth: 0.4,
  57067. stackedOnSmooth: 0.4,
  57068. smoothConstraint: false
  57069. },
  57070. z2: 0
  57071. });
  57072. text = new Text({
  57073. style: {
  57074. x: textLayout.x - margin,
  57075. y: textLayout.y0 + textLayout.y / 2
  57076. }
  57077. });
  57078. layerGroup.add(polygon);
  57079. layerGroup.add(text);
  57080. group.add(layerGroup);
  57081. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  57082. polygon.removeClipPath();
  57083. }));
  57084. }
  57085. else {
  57086. var layerGroup = oldLayersGroups[oldIdx];
  57087. polygon = layerGroup.childAt(0);
  57088. text = layerGroup.childAt(1);
  57089. group.add(layerGroup);
  57090. newLayersGroups[idx] = layerGroup;
  57091. updateProps(polygon, {
  57092. shape: {
  57093. points: points0,
  57094. stackedOnPoints: points1
  57095. }
  57096. }, seriesModel);
  57097. updateProps(text, {
  57098. style: {
  57099. x: textLayout.x - margin,
  57100. y: textLayout.y0 + textLayout.y / 2
  57101. }
  57102. }, seriesModel);
  57103. }
  57104. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  57105. var itemStyleModel = itemModel.getModel('itemStyle');
  57106. setTextStyle(text.style, labelModel, {
  57107. text: labelModel.get('show')
  57108. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  57109. || data.getName(indices[j - 1])
  57110. : null,
  57111. textVerticalAlign: 'middle'
  57112. });
  57113. polygon.setStyle(extend({
  57114. fill: color
  57115. }, itemStyleModel.getItemStyle(['color'])));
  57116. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  57117. }
  57118. this._layersSeries = layerSeries;
  57119. this._layers = newLayersGroups;
  57120. },
  57121. dispose: function () {}
  57122. });
  57123. // add animation to the view
  57124. function createGridClipShape$3(rect, seriesModel, cb) {
  57125. var rectEl = new Rect({
  57126. shape: {
  57127. x: rect.x - 10,
  57128. y: rect.y - 10,
  57129. width: 0,
  57130. height: rect.height + 20
  57131. }
  57132. });
  57133. initProps(rectEl, {
  57134. shape: {
  57135. width: rect.width + 20,
  57136. height: rect.height + 20
  57137. }
  57138. }, seriesModel, cb);
  57139. return rectEl;
  57140. }
  57141. /*
  57142. * Licensed to the Apache Software Foundation (ASF) under one
  57143. * or more contributor license agreements. See the NOTICE file
  57144. * distributed with this work for additional information
  57145. * regarding copyright ownership. The ASF licenses this file
  57146. * to you under the Apache License, Version 2.0 (the
  57147. * "License"); you may not use this file except in compliance
  57148. * with the License. You may obtain a copy of the License at
  57149. *
  57150. * http://www.apache.org/licenses/LICENSE-2.0
  57151. *
  57152. * Unless required by applicable law or agreed to in writing,
  57153. * software distributed under the License is distributed on an
  57154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57155. * KIND, either express or implied. See the License for the
  57156. * specific language governing permissions and limitations
  57157. * under the License.
  57158. */
  57159. /**
  57160. * @file Using layout algorithm transform the raw data to layout information.
  57161. * @author Deqing Li(annong035@gmail.com)
  57162. */
  57163. var themeRiverLayout = function (ecModel, api) {
  57164. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  57165. var data = seriesModel.getData();
  57166. var single = seriesModel.coordinateSystem;
  57167. var layoutInfo = {};
  57168. // use the axis boundingRect for view
  57169. var rect = single.getRect();
  57170. layoutInfo.rect = rect;
  57171. var boundaryGap = seriesModel.get('boundaryGap');
  57172. var axis = single.getAxis();
  57173. layoutInfo.boundaryGap = boundaryGap;
  57174. if (axis.orient === 'horizontal') {
  57175. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  57176. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  57177. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  57178. themeRiverLayout$1(data, seriesModel, height);
  57179. }
  57180. else {
  57181. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  57182. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  57183. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  57184. themeRiverLayout$1(data, seriesModel, width);
  57185. }
  57186. data.setLayout('layoutInfo', layoutInfo);
  57187. });
  57188. };
  57189. /**
  57190. * The layout information about themeriver
  57191. *
  57192. * @param {module:echarts/data/List} data data in the series
  57193. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  57194. * @param {number} height value used to compute every series height
  57195. */
  57196. function themeRiverLayout$1(data, seriesModel, height) {
  57197. if (!data.count()) {
  57198. return;
  57199. }
  57200. var coordSys = seriesModel.coordinateSystem;
  57201. // the data in each layer are organized into a series.
  57202. var layerSeries = seriesModel.getLayerSeries();
  57203. // the points in each layer.
  57204. var timeDim = data.mapDimension('single');
  57205. var valueDim = data.mapDimension('value');
  57206. var layerPoints = map(layerSeries, function (singleLayer) {
  57207. return map(singleLayer.indices, function (idx) {
  57208. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  57209. pt[1] = data.get(valueDim, idx);
  57210. return pt;
  57211. });
  57212. });
  57213. var base = computeBaseline(layerPoints);
  57214. var baseLine = base.y0;
  57215. var ky = height / base.max;
  57216. // set layout information for each item.
  57217. var n = layerSeries.length;
  57218. var m = layerSeries[0].indices.length;
  57219. var baseY0;
  57220. for (var j = 0; j < m; ++j) {
  57221. baseY0 = baseLine[j] * ky;
  57222. data.setItemLayout(layerSeries[0].indices[j], {
  57223. layerIndex: 0,
  57224. x: layerPoints[0][j][0],
  57225. y0: baseY0,
  57226. y: layerPoints[0][j][1] * ky
  57227. });
  57228. for (var i = 1; i < n; ++i) {
  57229. baseY0 += layerPoints[i - 1][j][1] * ky;
  57230. data.setItemLayout(layerSeries[i].indices[j], {
  57231. layerIndex: i,
  57232. x: layerPoints[i][j][0],
  57233. y0: baseY0,
  57234. y: layerPoints[i][j][1] * ky
  57235. });
  57236. }
  57237. }
  57238. }
  57239. /**
  57240. * Compute the baseLine of the rawdata
  57241. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  57242. *
  57243. * @param {Array.<Array>} data the points in each layer
  57244. * @return {Object}
  57245. */
  57246. function computeBaseline(data) {
  57247. var layerNum = data.length;
  57248. var pointNum = data[0].length;
  57249. var sums = [];
  57250. var y0 = [];
  57251. var max = 0;
  57252. var temp;
  57253. var base = {};
  57254. for (var i = 0; i < pointNum; ++i) {
  57255. for (var j = 0, temp = 0; j < layerNum; ++j) {
  57256. temp += data[j][i][1];
  57257. }
  57258. if (temp > max) {
  57259. max = temp;
  57260. }
  57261. sums.push(temp);
  57262. }
  57263. for (var k = 0; k < pointNum; ++k) {
  57264. y0[k] = (max - sums[k]) / 2;
  57265. }
  57266. max = 0;
  57267. for (var l = 0; l < pointNum; ++l) {
  57268. var sum = sums[l] + y0[l];
  57269. if (sum > max) {
  57270. max = sum;
  57271. }
  57272. }
  57273. base.y0 = y0;
  57274. base.max = max;
  57275. return base;
  57276. }
  57277. /*
  57278. * Licensed to the Apache Software Foundation (ASF) under one
  57279. * or more contributor license agreements. See the NOTICE file
  57280. * distributed with this work for additional information
  57281. * regarding copyright ownership. The ASF licenses this file
  57282. * to you under the Apache License, Version 2.0 (the
  57283. * "License"); you may not use this file except in compliance
  57284. * with the License. You may obtain a copy of the License at
  57285. *
  57286. * http://www.apache.org/licenses/LICENSE-2.0
  57287. *
  57288. * Unless required by applicable law or agreed to in writing,
  57289. * software distributed under the License is distributed on an
  57290. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57291. * KIND, either express or implied. See the License for the
  57292. * specific language governing permissions and limitations
  57293. * under the License.
  57294. */
  57295. /**
  57296. * @file Visual encoding for themeRiver view
  57297. * @author Deqing Li(annong035@gmail.com)
  57298. */
  57299. var themeRiverVisual = function (ecModel) {
  57300. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  57301. var data = seriesModel.getData();
  57302. var rawData = seriesModel.getRawData();
  57303. var colorList = seriesModel.get('color');
  57304. var idxMap = createHashMap();
  57305. data.each(function (idx) {
  57306. idxMap.set(data.getRawIndex(idx), idx);
  57307. });
  57308. rawData.each(function (rawIndex) {
  57309. var name = rawData.getName(rawIndex);
  57310. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  57311. rawData.setItemVisual(rawIndex, 'color', color);
  57312. var idx = idxMap.get(rawIndex);
  57313. if (idx != null) {
  57314. data.setItemVisual(idx, 'color', color);
  57315. }
  57316. });
  57317. });
  57318. };
  57319. /*
  57320. * Licensed to the Apache Software Foundation (ASF) under one
  57321. * or more contributor license agreements. See the NOTICE file
  57322. * distributed with this work for additional information
  57323. * regarding copyright ownership. The ASF licenses this file
  57324. * to you under the Apache License, Version 2.0 (the
  57325. * "License"); you may not use this file except in compliance
  57326. * with the License. You may obtain a copy of the License at
  57327. *
  57328. * http://www.apache.org/licenses/LICENSE-2.0
  57329. *
  57330. * Unless required by applicable law or agreed to in writing,
  57331. * software distributed under the License is distributed on an
  57332. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57333. * KIND, either express or implied. See the License for the
  57334. * specific language governing permissions and limitations
  57335. * under the License.
  57336. */
  57337. registerLayout(themeRiverLayout);
  57338. registerVisual(themeRiverVisual);
  57339. registerProcessor(dataFilter('themeRiver'));
  57340. /*
  57341. * Licensed to the Apache Software Foundation (ASF) under one
  57342. * or more contributor license agreements. See the NOTICE file
  57343. * distributed with this work for additional information
  57344. * regarding copyright ownership. The ASF licenses this file
  57345. * to you under the Apache License, Version 2.0 (the
  57346. * "License"); you may not use this file except in compliance
  57347. * with the License. You may obtain a copy of the License at
  57348. *
  57349. * http://www.apache.org/licenses/LICENSE-2.0
  57350. *
  57351. * Unless required by applicable law or agreed to in writing,
  57352. * software distributed under the License is distributed on an
  57353. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57354. * KIND, either express or implied. See the License for the
  57355. * specific language governing permissions and limitations
  57356. * under the License.
  57357. */
  57358. SeriesModel.extend({
  57359. type: 'series.sunburst',
  57360. /**
  57361. * @type {module:echarts/data/Tree~Node}
  57362. */
  57363. _viewRoot: null,
  57364. getInitialData: function (option, ecModel) {
  57365. // Create a virtual root.
  57366. var root = { name: option.name, children: option.data };
  57367. completeTreeValue$1(root);
  57368. var levels = option.levels || [];
  57369. // levels = option.levels = setDefault(levels, ecModel);
  57370. var treeOption = {};
  57371. treeOption.levels = levels;
  57372. // Make sure always a new tree is created when setOption,
  57373. // in TreemapView, we check whether oldTree === newTree
  57374. // to choose mappings approach among old shapes and new shapes.
  57375. return Tree.createTree(root, this, treeOption).data;
  57376. },
  57377. optionUpdated: function () {
  57378. this.resetViewRoot();
  57379. },
  57380. /*
  57381. * @override
  57382. */
  57383. getDataParams: function (dataIndex) {
  57384. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  57385. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  57386. params.treePathInfo = wrapTreePathInfo(node, this);
  57387. return params;
  57388. },
  57389. defaultOption: {
  57390. zlevel: 0,
  57391. z: 2,
  57392. // 默认全局居中
  57393. center: ['50%', '50%'],
  57394. radius: [0, '75%'],
  57395. // 默认顺时针
  57396. clockwise: true,
  57397. startAngle: 90,
  57398. // 最小角度改为0
  57399. minAngle: 0,
  57400. percentPrecision: 2,
  57401. // If still show when all data zero.
  57402. stillShowZeroSum: true,
  57403. // Policy of highlighting pieces when hover on one
  57404. // Valid values: 'none' (for not downplay others), 'descendant',
  57405. // 'ancestor', 'self'
  57406. highlightPolicy: 'descendant',
  57407. // 'rootToNode', 'link', or false
  57408. nodeClick: 'rootToNode',
  57409. renderLabelForZeroData: false,
  57410. label: {
  57411. // could be: 'radial', 'tangential', or 'none'
  57412. rotate: 'radial',
  57413. show: true,
  57414. opacity: 1,
  57415. // 'left' is for inner side of inside, and 'right' is for outter
  57416. // side for inside
  57417. align: 'center',
  57418. position: 'inside',
  57419. distance: 5,
  57420. silent: true,
  57421. emphasis: {}
  57422. },
  57423. itemStyle: {
  57424. borderWidth: 1,
  57425. borderColor: 'white',
  57426. opacity: 1,
  57427. emphasis: {},
  57428. highlight: {
  57429. opacity: 1
  57430. },
  57431. downplay: {
  57432. opacity: 0.9
  57433. }
  57434. },
  57435. // Animation type canbe expansion, scale
  57436. animationType: 'expansion',
  57437. animationDuration: 1000,
  57438. animationDurationUpdate: 500,
  57439. animationEasing: 'cubicOut',
  57440. data: [],
  57441. levels: [],
  57442. /**
  57443. * Sort order.
  57444. *
  57445. * Valid values: 'desc', 'asc', null, or callback function.
  57446. * 'desc' and 'asc' for descend and ascendant order;
  57447. * null for not sorting;
  57448. * example of callback function:
  57449. * function(nodeA, nodeB) {
  57450. * return nodeA.getValue() - nodeB.getValue();
  57451. * }
  57452. */
  57453. sort: 'desc'
  57454. },
  57455. getViewRoot: function () {
  57456. return this._viewRoot;
  57457. },
  57458. /**
  57459. * @param {module:echarts/data/Tree~Node} [viewRoot]
  57460. */
  57461. resetViewRoot: function (viewRoot) {
  57462. viewRoot
  57463. ? (this._viewRoot = viewRoot)
  57464. : (viewRoot = this._viewRoot);
  57465. var root = this.getRawData().tree.root;
  57466. if (!viewRoot
  57467. || (viewRoot !== root && !root.contains(viewRoot))
  57468. ) {
  57469. this._viewRoot = root;
  57470. }
  57471. }
  57472. });
  57473. /**
  57474. * @param {Object} dataNode
  57475. */
  57476. function completeTreeValue$1(dataNode) {
  57477. // Postorder travel tree.
  57478. // If value of none-leaf node is not set,
  57479. // calculate it by suming up the value of all children.
  57480. var sum = 0;
  57481. each$1(dataNode.children, function (child) {
  57482. completeTreeValue$1(child);
  57483. var childValue = child.value;
  57484. isArray(childValue) && (childValue = childValue[0]);
  57485. sum += childValue;
  57486. });
  57487. var thisValue = dataNode.value;
  57488. if (isArray(thisValue)) {
  57489. thisValue = thisValue[0];
  57490. }
  57491. if (thisValue == null || isNaN(thisValue)) {
  57492. thisValue = sum;
  57493. }
  57494. // Value should not less than 0.
  57495. if (thisValue < 0) {
  57496. thisValue = 0;
  57497. }
  57498. isArray(dataNode.value)
  57499. ? (dataNode.value[0] = thisValue)
  57500. : (dataNode.value = thisValue);
  57501. }
  57502. /*
  57503. * Licensed to the Apache Software Foundation (ASF) under one
  57504. * or more contributor license agreements. See the NOTICE file
  57505. * distributed with this work for additional information
  57506. * regarding copyright ownership. The ASF licenses this file
  57507. * to you under the Apache License, Version 2.0 (the
  57508. * "License"); you may not use this file except in compliance
  57509. * with the License. You may obtain a copy of the License at
  57510. *
  57511. * http://www.apache.org/licenses/LICENSE-2.0
  57512. *
  57513. * Unless required by applicable law or agreed to in writing,
  57514. * software distributed under the License is distributed on an
  57515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57516. * KIND, either express or implied. See the License for the
  57517. * specific language governing permissions and limitations
  57518. * under the License.
  57519. */
  57520. var NodeHighlightPolicy = {
  57521. NONE: 'none', // not downplay others
  57522. DESCENDANT: 'descendant',
  57523. ANCESTOR: 'ancestor',
  57524. SELF: 'self'
  57525. };
  57526. var DEFAULT_SECTOR_Z = 2;
  57527. var DEFAULT_TEXT_Z = 4;
  57528. /**
  57529. * Sunburstce of Sunburst including Sector, Label, LabelLine
  57530. * @constructor
  57531. * @extends {module:zrender/graphic/Group}
  57532. */
  57533. function SunburstPiece(node, seriesModel, ecModel) {
  57534. Group.call(this);
  57535. var sector = new Sector({
  57536. z2: DEFAULT_SECTOR_Z
  57537. });
  57538. sector.seriesIndex = seriesModel.seriesIndex;
  57539. var text = new Text({
  57540. z2: DEFAULT_TEXT_Z,
  57541. silent: node.getModel('label').get('silent')
  57542. });
  57543. this.add(sector);
  57544. this.add(text);
  57545. this.updateData(true, node, 'normal', seriesModel, ecModel);
  57546. // Hover to change label and labelLine
  57547. function onEmphasis() {
  57548. text.ignore = text.hoverIgnore;
  57549. }
  57550. function onNormal() {
  57551. text.ignore = text.normalIgnore;
  57552. }
  57553. this.on('emphasis', onEmphasis)
  57554. .on('normal', onNormal)
  57555. .on('mouseover', onEmphasis)
  57556. .on('mouseout', onNormal);
  57557. }
  57558. var SunburstPieceProto = SunburstPiece.prototype;
  57559. SunburstPieceProto.updateData = function (
  57560. firstCreate,
  57561. node,
  57562. state,
  57563. seriesModel,
  57564. ecModel
  57565. ) {
  57566. this.node = node;
  57567. node.piece = this;
  57568. seriesModel = seriesModel || this._seriesModel;
  57569. ecModel = ecModel || this._ecModel;
  57570. var sector = this.childAt(0);
  57571. sector.dataIndex = node.dataIndex;
  57572. var itemModel = node.getModel();
  57573. var layout = node.getLayout();
  57574. if (!layout) {
  57575. console.log(node.getLayout());
  57576. }
  57577. var sectorShape = extend({}, layout);
  57578. sectorShape.label = null;
  57579. var visualColor = getNodeColor(node, seriesModel, ecModel);
  57580. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  57581. var style;
  57582. if (state === 'normal') {
  57583. style = normalStyle;
  57584. }
  57585. else {
  57586. var stateStyle = itemModel.getModel(state + '.itemStyle')
  57587. .getItemStyle();
  57588. style = merge(stateStyle, normalStyle);
  57589. }
  57590. style = defaults(
  57591. {
  57592. lineJoin: 'bevel',
  57593. fill: style.fill || visualColor
  57594. },
  57595. style
  57596. );
  57597. if (firstCreate) {
  57598. sector.setShape(sectorShape);
  57599. sector.shape.r = layout.r0;
  57600. updateProps(
  57601. sector,
  57602. {
  57603. shape: {
  57604. r: layout.r
  57605. }
  57606. },
  57607. seriesModel,
  57608. node.dataIndex
  57609. );
  57610. sector.useStyle(style);
  57611. }
  57612. else if (typeof style.fill === 'object' && style.fill.type
  57613. || typeof sector.style.fill === 'object' && sector.style.fill.type
  57614. ) {
  57615. // Disable animation for gradient since no interpolation method
  57616. // is supported for gradient
  57617. updateProps(sector, {
  57618. shape: sectorShape
  57619. }, seriesModel);
  57620. sector.useStyle(style);
  57621. }
  57622. else {
  57623. updateProps(sector, {
  57624. shape: sectorShape,
  57625. style: style
  57626. }, seriesModel);
  57627. }
  57628. this._updateLabel(seriesModel, visualColor, state);
  57629. var cursorStyle = itemModel.getShallow('cursor');
  57630. cursorStyle && sector.attr('cursor', cursorStyle);
  57631. if (firstCreate) {
  57632. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  57633. this._initEvents(sector, node, seriesModel, highlightPolicy);
  57634. }
  57635. this._seriesModel = seriesModel || this._seriesModel;
  57636. this._ecModel = ecModel || this._ecModel;
  57637. };
  57638. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  57639. var that = this;
  57640. this.node.hostTree.root.eachNode(function (n) {
  57641. if (n.piece) {
  57642. if (that.node === n) {
  57643. n.piece.updateData(false, n, 'emphasis');
  57644. }
  57645. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  57646. n.piece.childAt(0).trigger('highlight');
  57647. }
  57648. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  57649. n.piece.childAt(0).trigger('downplay');
  57650. }
  57651. }
  57652. });
  57653. };
  57654. SunburstPieceProto.onNormal = function () {
  57655. this.node.hostTree.root.eachNode(function (n) {
  57656. if (n.piece) {
  57657. n.piece.updateData(false, n, 'normal');
  57658. }
  57659. });
  57660. };
  57661. SunburstPieceProto.onHighlight = function () {
  57662. this.updateData(false, this.node, 'highlight');
  57663. };
  57664. SunburstPieceProto.onDownplay = function () {
  57665. this.updateData(false, this.node, 'downplay');
  57666. };
  57667. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  57668. var itemModel = this.node.getModel();
  57669. var normalModel = itemModel.getModel('label');
  57670. var labelModel = state === 'normal' || state === 'emphasis'
  57671. ? normalModel
  57672. : itemModel.getModel(state + '.label');
  57673. var labelHoverModel = itemModel.getModel('emphasis.label');
  57674. var text = retrieve(
  57675. seriesModel.getFormattedLabel(
  57676. this.node.dataIndex, 'normal', null, null, 'label'
  57677. ),
  57678. this.node.name
  57679. );
  57680. if (getLabelAttr('show') === false) {
  57681. text = '';
  57682. }
  57683. var layout = this.node.getLayout();
  57684. var labelMinAngle = labelModel.get('minAngle');
  57685. if (labelMinAngle == null) {
  57686. labelMinAngle = normalModel.get('minAngle');
  57687. }
  57688. labelMinAngle = labelMinAngle / 180 * Math.PI;
  57689. var angle = layout.endAngle - layout.startAngle;
  57690. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  57691. // Not displaying text when angle is too small
  57692. text = '';
  57693. }
  57694. var label = this.childAt(1);
  57695. setLabelStyle(
  57696. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  57697. {
  57698. defaultText: labelModel.getShallow('show') ? text : null,
  57699. autoColor: visualColor,
  57700. useInsideStyle: true
  57701. }
  57702. );
  57703. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  57704. var dx = Math.cos(midAngle);
  57705. var dy = Math.sin(midAngle);
  57706. var r;
  57707. var labelPosition = getLabelAttr('position');
  57708. var labelPadding = getLabelAttr('distance') || 0;
  57709. var textAlign = getLabelAttr('align');
  57710. if (labelPosition === 'outside') {
  57711. r = layout.r + labelPadding;
  57712. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  57713. }
  57714. else {
  57715. if (!textAlign || textAlign === 'center') {
  57716. r = (layout.r + layout.r0) / 2;
  57717. textAlign = 'center';
  57718. }
  57719. else if (textAlign === 'left') {
  57720. r = layout.r0 + labelPadding;
  57721. if (midAngle > Math.PI / 2) {
  57722. textAlign = 'right';
  57723. }
  57724. }
  57725. else if (textAlign === 'right') {
  57726. r = layout.r - labelPadding;
  57727. if (midAngle > Math.PI / 2) {
  57728. textAlign = 'left';
  57729. }
  57730. }
  57731. }
  57732. label.attr('style', {
  57733. text: text,
  57734. textAlign: textAlign,
  57735. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  57736. opacity: getLabelAttr('opacity')
  57737. });
  57738. var textX = r * dx + layout.cx;
  57739. var textY = r * dy + layout.cy;
  57740. label.attr('position', [textX, textY]);
  57741. var rotateType = getLabelAttr('rotate');
  57742. var rotate = 0;
  57743. if (rotateType === 'radial') {
  57744. rotate = -midAngle;
  57745. if (rotate < -Math.PI / 2) {
  57746. rotate += Math.PI;
  57747. }
  57748. }
  57749. else if (rotateType === 'tangential') {
  57750. rotate = Math.PI / 2 - midAngle;
  57751. if (rotate > Math.PI / 2) {
  57752. rotate -= Math.PI;
  57753. }
  57754. else if (rotate < -Math.PI / 2) {
  57755. rotate += Math.PI;
  57756. }
  57757. } else if (typeof rotateType === 'number') {
  57758. rotate = rotateType * Math.PI / 180;
  57759. }
  57760. label.attr('rotation', rotate);
  57761. function getLabelAttr(name) {
  57762. var stateAttr = labelModel.get(name);
  57763. if (stateAttr == null) {
  57764. return normalModel.get(name);
  57765. }
  57766. else {
  57767. return stateAttr;
  57768. }
  57769. }
  57770. };
  57771. SunburstPieceProto._initEvents = function (
  57772. sector,
  57773. node,
  57774. seriesModel,
  57775. highlightPolicy
  57776. ) {
  57777. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  57778. var that = this;
  57779. var onEmphasis = function () {
  57780. that.onEmphasis(highlightPolicy);
  57781. };
  57782. var onNormal = function () {
  57783. that.onNormal();
  57784. };
  57785. var onDownplay = function () {
  57786. that.onDownplay();
  57787. };
  57788. var onHighlight = function () {
  57789. that.onHighlight();
  57790. };
  57791. if (seriesModel.isAnimationEnabled()) {
  57792. sector
  57793. .on('mouseover', onEmphasis)
  57794. .on('mouseout', onNormal)
  57795. .on('emphasis', onEmphasis)
  57796. .on('normal', onNormal)
  57797. .on('downplay', onDownplay)
  57798. .on('highlight', onHighlight);
  57799. }
  57800. };
  57801. inherits(SunburstPiece, Group);
  57802. /**
  57803. * Get node color
  57804. *
  57805. * @param {TreeNode} node the node to get color
  57806. * @param {module:echarts/model/Series} seriesModel series
  57807. * @param {module:echarts/model/Global} ecModel echarts defaults
  57808. */
  57809. function getNodeColor(node, seriesModel, ecModel) {
  57810. // Color from visualMap
  57811. var visualColor = node.getVisual('color');
  57812. var visualMetaList = node.getVisual('visualMeta');
  57813. if (!visualMetaList || visualMetaList.length === 0) {
  57814. // Use first-generation color if has no visualMap
  57815. visualColor = null;
  57816. }
  57817. // Self color or level color
  57818. var color = node.getModel('itemStyle').get('color');
  57819. if (color) {
  57820. return color;
  57821. }
  57822. else if (visualColor) {
  57823. // Color mapping
  57824. return visualColor;
  57825. }
  57826. else if (node.depth === 0) {
  57827. // Virtual root node
  57828. return ecModel.option.color[0];
  57829. }
  57830. else {
  57831. // First-generation color
  57832. var length = ecModel.option.color.length;
  57833. color = ecModel.option.color[getRootId(node) % length];
  57834. }
  57835. return color;
  57836. }
  57837. /**
  57838. * Get index of root in sorted order
  57839. *
  57840. * @param {TreeNode} node current node
  57841. * @return {number} index in root
  57842. */
  57843. function getRootId(node) {
  57844. var ancestor = node;
  57845. while (ancestor.depth > 1) {
  57846. ancestor = ancestor.parentNode;
  57847. }
  57848. var virtualRoot = node.getAncestors()[0];
  57849. return indexOf(virtualRoot.children, ancestor);
  57850. }
  57851. function isNodeHighlighted(node, activeNode, policy) {
  57852. if (policy === NodeHighlightPolicy.NONE) {
  57853. return false;
  57854. }
  57855. else if (policy === NodeHighlightPolicy.SELF) {
  57856. return node === activeNode;
  57857. }
  57858. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  57859. return node === activeNode || node.isAncestorOf(activeNode);
  57860. }
  57861. else {
  57862. return node === activeNode || node.isDescendantOf(activeNode);
  57863. }
  57864. }
  57865. /*
  57866. * Licensed to the Apache Software Foundation (ASF) under one
  57867. * or more contributor license agreements. See the NOTICE file
  57868. * distributed with this work for additional information
  57869. * regarding copyright ownership. The ASF licenses this file
  57870. * to you under the Apache License, Version 2.0 (the
  57871. * "License"); you may not use this file except in compliance
  57872. * with the License. You may obtain a copy of the License at
  57873. *
  57874. * http://www.apache.org/licenses/LICENSE-2.0
  57875. *
  57876. * Unless required by applicable law or agreed to in writing,
  57877. * software distributed under the License is distributed on an
  57878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57879. * KIND, either express or implied. See the License for the
  57880. * specific language governing permissions and limitations
  57881. * under the License.
  57882. */
  57883. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  57884. var SunburstView = Chart.extend({
  57885. type: 'sunburst',
  57886. init: function () {
  57887. },
  57888. render: function (seriesModel, ecModel, api, payload) {
  57889. var that = this;
  57890. this.seriesModel = seriesModel;
  57891. this.api = api;
  57892. this.ecModel = ecModel;
  57893. var data = seriesModel.getData();
  57894. var virtualRoot = data.tree.root;
  57895. var newRoot = seriesModel.getViewRoot();
  57896. var group = this.group;
  57897. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  57898. var newChildren = [];
  57899. newRoot.eachNode(function (node) {
  57900. newChildren.push(node);
  57901. });
  57902. var oldChildren = this._oldChildren || [];
  57903. dualTravel(newChildren, oldChildren);
  57904. renderRollUp(virtualRoot, newRoot);
  57905. if (payload && payload.highlight && payload.highlight.piece) {
  57906. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  57907. payload.highlight.piece.onEmphasis(highlightPolicy);
  57908. }
  57909. else if (payload && payload.unhighlight) {
  57910. var piece = this.virtualPiece;
  57911. if (!piece && virtualRoot.children.length) {
  57912. piece = virtualRoot.children[0].piece;
  57913. }
  57914. if (piece) {
  57915. piece.onNormal();
  57916. }
  57917. }
  57918. this._initEvents();
  57919. this._oldChildren = newChildren;
  57920. function dualTravel(newChildren, oldChildren) {
  57921. if (newChildren.length === 0 && oldChildren.length === 0) {
  57922. return;
  57923. }
  57924. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  57925. .add(processNode)
  57926. .update(processNode)
  57927. .remove(curry(processNode, null))
  57928. .execute();
  57929. function getKey(node) {
  57930. return node.getId();
  57931. }
  57932. function processNode(newId, oldId) {
  57933. var newNode = newId == null ? null : newChildren[newId];
  57934. var oldNode = oldId == null ? null : oldChildren[oldId];
  57935. doRenderNode(newNode, oldNode);
  57936. }
  57937. }
  57938. function doRenderNode(newNode, oldNode) {
  57939. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  57940. // Not render data with value 0
  57941. newNode = null;
  57942. }
  57943. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  57944. if (oldNode && oldNode.piece) {
  57945. if (newNode) {
  57946. // Update
  57947. oldNode.piece.updateData(
  57948. false, newNode, 'normal', seriesModel, ecModel);
  57949. // For tooltip
  57950. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  57951. }
  57952. else {
  57953. // Remove
  57954. removeNode(oldNode);
  57955. }
  57956. }
  57957. else if (newNode) {
  57958. // Add
  57959. var piece = new SunburstPiece(
  57960. newNode,
  57961. seriesModel,
  57962. ecModel
  57963. );
  57964. group.add(piece);
  57965. // For tooltip
  57966. data.setItemGraphicEl(newNode.dataIndex, piece);
  57967. }
  57968. }
  57969. }
  57970. function removeNode(node) {
  57971. if (!node) {
  57972. return;
  57973. }
  57974. if (node.piece) {
  57975. group.remove(node.piece);
  57976. node.piece = null;
  57977. }
  57978. }
  57979. function renderRollUp(virtualRoot, viewRoot) {
  57980. if (viewRoot.depth > 0) {
  57981. // Render
  57982. if (that.virtualPiece) {
  57983. // Update
  57984. that.virtualPiece.updateData(
  57985. false, virtualRoot, 'normal', seriesModel, ecModel);
  57986. }
  57987. else {
  57988. // Add
  57989. that.virtualPiece = new SunburstPiece(
  57990. virtualRoot,
  57991. seriesModel,
  57992. ecModel
  57993. );
  57994. group.add(that.virtualPiece);
  57995. }
  57996. if (viewRoot.piece._onclickEvent) {
  57997. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  57998. }
  57999. var event = function (e) {
  58000. that._rootToNode(viewRoot.parentNode);
  58001. };
  58002. viewRoot.piece._onclickEvent = event;
  58003. that.virtualPiece.on('click', event);
  58004. }
  58005. else if (that.virtualPiece) {
  58006. // Remove
  58007. group.remove(that.virtualPiece);
  58008. that.virtualPiece = null;
  58009. }
  58010. }
  58011. },
  58012. dispose: function () {
  58013. },
  58014. /**
  58015. * @private
  58016. */
  58017. _initEvents: function () {
  58018. var that = this;
  58019. var event = function (e) {
  58020. var targetFound = false;
  58021. var viewRoot = that.seriesModel.getViewRoot();
  58022. viewRoot.eachNode(function (node) {
  58023. if (!targetFound
  58024. && node.piece && node.piece.childAt(0) === e.target
  58025. ) {
  58026. var nodeClick = node.getModel().get('nodeClick');
  58027. if (nodeClick === 'rootToNode') {
  58028. that._rootToNode(node);
  58029. }
  58030. else if (nodeClick === 'link') {
  58031. var itemModel = node.getModel();
  58032. var link = itemModel.get('link');
  58033. if (link) {
  58034. var linkTarget = itemModel.get('target', true)
  58035. || '_blank';
  58036. window.open(link, linkTarget);
  58037. }
  58038. }
  58039. targetFound = true;
  58040. }
  58041. });
  58042. };
  58043. if (this.group._onclickEvent) {
  58044. this.group.off('click', this.group._onclickEvent);
  58045. }
  58046. this.group.on('click', event);
  58047. this.group._onclickEvent = event;
  58048. },
  58049. /**
  58050. * @private
  58051. */
  58052. _rootToNode: function (node) {
  58053. if (node !== this.seriesModel.getViewRoot()) {
  58054. this.api.dispatchAction({
  58055. type: ROOT_TO_NODE_ACTION,
  58056. from: this.uid,
  58057. seriesId: this.seriesModel.id,
  58058. targetNode: node
  58059. });
  58060. }
  58061. },
  58062. /**
  58063. * @implement
  58064. */
  58065. containPoint: function (point, seriesModel) {
  58066. var treeRoot = seriesModel.getData();
  58067. var itemLayout = treeRoot.getItemLayout(0);
  58068. if (itemLayout) {
  58069. var dx = point[0] - itemLayout.cx;
  58070. var dy = point[1] - itemLayout.cy;
  58071. var radius = Math.sqrt(dx * dx + dy * dy);
  58072. return radius <= itemLayout.r && radius >= itemLayout.r0;
  58073. }
  58074. }
  58075. });
  58076. /*
  58077. * Licensed to the Apache Software Foundation (ASF) under one
  58078. * or more contributor license agreements. See the NOTICE file
  58079. * distributed with this work for additional information
  58080. * regarding copyright ownership. The ASF licenses this file
  58081. * to you under the Apache License, Version 2.0 (the
  58082. * "License"); you may not use this file except in compliance
  58083. * with the License. You may obtain a copy of the License at
  58084. *
  58085. * http://www.apache.org/licenses/LICENSE-2.0
  58086. *
  58087. * Unless required by applicable law or agreed to in writing,
  58088. * software distributed under the License is distributed on an
  58089. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58090. * KIND, either express or implied. See the License for the
  58091. * specific language governing permissions and limitations
  58092. * under the License.
  58093. */
  58094. /**
  58095. * @file Sunburst action
  58096. */
  58097. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  58098. registerAction(
  58099. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  58100. function (payload, ecModel) {
  58101. ecModel.eachComponent(
  58102. {mainType: 'series', subType: 'sunburst', query: payload},
  58103. handleRootToNode
  58104. );
  58105. function handleRootToNode(model, index) {
  58106. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  58107. if (targetInfo) {
  58108. var originViewRoot = model.getViewRoot();
  58109. if (originViewRoot) {
  58110. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  58111. ? 'rollUp' : 'drillDown';
  58112. }
  58113. model.resetViewRoot(targetInfo.node);
  58114. }
  58115. }
  58116. }
  58117. );
  58118. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  58119. registerAction(
  58120. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  58121. function (payload, ecModel) {
  58122. ecModel.eachComponent(
  58123. {mainType: 'series', subType: 'sunburst', query: payload},
  58124. handleHighlight
  58125. );
  58126. function handleHighlight(model, index) {
  58127. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  58128. if (targetInfo) {
  58129. payload.highlight = targetInfo.node;
  58130. }
  58131. }
  58132. }
  58133. );
  58134. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  58135. registerAction(
  58136. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  58137. function (payload, ecModel) {
  58138. ecModel.eachComponent(
  58139. {mainType: 'series', subType: 'sunburst', query: payload},
  58140. handleUnhighlight
  58141. );
  58142. function handleUnhighlight(model, index) {
  58143. payload.unhighlight = true;
  58144. }
  58145. }
  58146. );
  58147. /*
  58148. * Licensed to the Apache Software Foundation (ASF) under one
  58149. * or more contributor license agreements. See the NOTICE file
  58150. * distributed with this work for additional information
  58151. * regarding copyright ownership. The ASF licenses this file
  58152. * to you under the Apache License, Version 2.0 (the
  58153. * "License"); you may not use this file except in compliance
  58154. * with the License. You may obtain a copy of the License at
  58155. *
  58156. * http://www.apache.org/licenses/LICENSE-2.0
  58157. *
  58158. * Unless required by applicable law or agreed to in writing,
  58159. * software distributed under the License is distributed on an
  58160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58161. * KIND, either express or implied. See the License for the
  58162. * specific language governing permissions and limitations
  58163. * under the License.
  58164. */
  58165. var RADIAN$1 = Math.PI / 180;
  58166. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  58167. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  58168. var center = seriesModel.get('center');
  58169. var radius = seriesModel.get('radius');
  58170. if (!isArray(radius)) {
  58171. radius = [0, radius];
  58172. }
  58173. if (!isArray(center)) {
  58174. center = [center, center];
  58175. }
  58176. var width = api.getWidth();
  58177. var height = api.getHeight();
  58178. var size = Math.min(width, height);
  58179. var cx = parsePercent$1(center[0], width);
  58180. var cy = parsePercent$1(center[1], height);
  58181. var r0 = parsePercent$1(radius[0], size / 2);
  58182. var r = parsePercent$1(radius[1], size / 2);
  58183. var startAngle = -seriesModel.get('startAngle') * RADIAN$1;
  58184. var minAngle = seriesModel.get('minAngle') * RADIAN$1;
  58185. var virtualRoot = seriesModel.getData().tree.root;
  58186. var treeRoot = seriesModel.getViewRoot();
  58187. var rootDepth = treeRoot.depth;
  58188. var sort = seriesModel.get('sort');
  58189. if (sort != null) {
  58190. initChildren$1(treeRoot, sort);
  58191. }
  58192. var validDataCount = 0;
  58193. each$1(treeRoot.children, function (child) {
  58194. !isNaN(child.getValue()) && validDataCount++;
  58195. });
  58196. var sum = treeRoot.getValue();
  58197. // Sum may be 0
  58198. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  58199. var renderRollupNode = treeRoot.depth > 0;
  58200. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  58201. var rPerLevel = (r - r0) / (levels || 1);
  58202. var clockwise = seriesModel.get('clockwise');
  58203. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  58204. // In the case some sector angle is smaller than minAngle
  58205. var dir = clockwise ? 1 : -1;
  58206. /**
  58207. * Render a tree
  58208. * @return increased angle
  58209. */
  58210. var renderNode = function (node, startAngle) {
  58211. if (!node) {
  58212. return;
  58213. }
  58214. var endAngle = startAngle;
  58215. // Render self
  58216. if (node !== virtualRoot) {
  58217. // Tree node is virtual, so it doesn't need to be drawn
  58218. var value = node.getValue();
  58219. var angle = (sum === 0 && stillShowZeroSum)
  58220. ? unitRadian : (value * unitRadian);
  58221. if (angle < minAngle) {
  58222. angle = minAngle;
  58223. }
  58224. else {
  58225. }
  58226. endAngle = startAngle + dir * angle;
  58227. var depth = node.depth - rootDepth
  58228. - (renderRollupNode ? -1 : 1);
  58229. var rStart = r0 + rPerLevel * depth;
  58230. var rEnd = r0 + rPerLevel * (depth + 1);
  58231. var itemModel = node.getModel();
  58232. if (itemModel.get('r0') != null) {
  58233. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  58234. }
  58235. if (itemModel.get('r') != null) {
  58236. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  58237. }
  58238. node.setLayout({
  58239. angle: angle,
  58240. startAngle: startAngle,
  58241. endAngle: endAngle,
  58242. clockwise: clockwise,
  58243. cx: cx,
  58244. cy: cy,
  58245. r0: rStart,
  58246. r: rEnd
  58247. });
  58248. }
  58249. // Render children
  58250. if (node.children && node.children.length) {
  58251. // currentAngle = startAngle;
  58252. var siblingAngle = 0;
  58253. each$1(node.children, function (node) {
  58254. siblingAngle += renderNode(node, startAngle + siblingAngle);
  58255. });
  58256. }
  58257. return endAngle - startAngle;
  58258. };
  58259. // Virtual root node for roll up
  58260. if (renderRollupNode) {
  58261. var rStart = r0;
  58262. var rEnd = r0 + rPerLevel;
  58263. var angle = Math.PI * 2;
  58264. virtualRoot.setLayout({
  58265. angle: angle,
  58266. startAngle: startAngle,
  58267. endAngle: startAngle + angle,
  58268. clockwise: clockwise,
  58269. cx: cx,
  58270. cy: cy,
  58271. r0: rStart,
  58272. r: rEnd
  58273. });
  58274. }
  58275. renderNode(treeRoot, startAngle);
  58276. });
  58277. };
  58278. /**
  58279. * Init node children by order and update visual
  58280. *
  58281. * @param {TreeNode} node root node
  58282. * @param {boolean} isAsc if is in ascendant order
  58283. */
  58284. function initChildren$1(node, isAsc) {
  58285. var children = node.children || [];
  58286. node.children = sort$2(children, isAsc);
  58287. // Init children recursively
  58288. if (children.length) {
  58289. each$1(node.children, function (child) {
  58290. initChildren$1(child, isAsc);
  58291. });
  58292. }
  58293. }
  58294. /**
  58295. * Sort children nodes
  58296. *
  58297. * @param {TreeNode[]} children children of node to be sorted
  58298. * @param {string | function | null} sort sort method
  58299. * See SunburstSeries.js for details.
  58300. */
  58301. function sort$2(children, sortOrder) {
  58302. if (typeof sortOrder === 'function') {
  58303. return children.sort(sortOrder);
  58304. }
  58305. else {
  58306. var isAsc = sortOrder === 'asc';
  58307. return children.sort(function (a, b) {
  58308. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  58309. return diff === 0
  58310. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  58311. : diff;
  58312. });
  58313. }
  58314. }
  58315. /*
  58316. * Licensed to the Apache Software Foundation (ASF) under one
  58317. * or more contributor license agreements. See the NOTICE file
  58318. * distributed with this work for additional information
  58319. * regarding copyright ownership. The ASF licenses this file
  58320. * to you under the Apache License, Version 2.0 (the
  58321. * "License"); you may not use this file except in compliance
  58322. * with the License. You may obtain a copy of the License at
  58323. *
  58324. * http://www.apache.org/licenses/LICENSE-2.0
  58325. *
  58326. * Unless required by applicable law or agreed to in writing,
  58327. * software distributed under the License is distributed on an
  58328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58329. * KIND, either express or implied. See the License for the
  58330. * specific language governing permissions and limitations
  58331. * under the License.
  58332. */
  58333. registerVisual(curry(dataColor, 'sunburst'));
  58334. registerLayout(curry(sunburstLayout, 'sunburst'));
  58335. registerProcessor(curry(dataFilter, 'sunburst'));
  58336. /*
  58337. * Licensed to the Apache Software Foundation (ASF) under one
  58338. * or more contributor license agreements. See the NOTICE file
  58339. * distributed with this work for additional information
  58340. * regarding copyright ownership. The ASF licenses this file
  58341. * to you under the Apache License, Version 2.0 (the
  58342. * "License"); you may not use this file except in compliance
  58343. * with the License. You may obtain a copy of the License at
  58344. *
  58345. * http://www.apache.org/licenses/LICENSE-2.0
  58346. *
  58347. * Unless required by applicable law or agreed to in writing,
  58348. * software distributed under the License is distributed on an
  58349. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58350. * KIND, either express or implied. See the License for the
  58351. * specific language governing permissions and limitations
  58352. * under the License.
  58353. */
  58354. function dataToCoordSize(dataSize, dataItem) {
  58355. // dataItem is necessary in log axis.
  58356. dataItem = dataItem || [0, 0];
  58357. return map(['x', 'y'], function (dim, dimIdx) {
  58358. var axis = this.getAxis(dim);
  58359. var val = dataItem[dimIdx];
  58360. var halfSize = dataSize[dimIdx] / 2;
  58361. return axis.type === 'category'
  58362. ? axis.getBandWidth()
  58363. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  58364. }, this);
  58365. }
  58366. var prepareCartesian2d = function (coordSys) {
  58367. var rect = coordSys.grid.getRect();
  58368. return {
  58369. coordSys: {
  58370. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  58371. type: 'cartesian2d',
  58372. x: rect.x,
  58373. y: rect.y,
  58374. width: rect.width,
  58375. height: rect.height
  58376. },
  58377. api: {
  58378. coord: function (data) {
  58379. // do not provide "out" param
  58380. return coordSys.dataToPoint(data);
  58381. },
  58382. size: bind(dataToCoordSize, coordSys)
  58383. }
  58384. };
  58385. };
  58386. /*
  58387. * Licensed to the Apache Software Foundation (ASF) under one
  58388. * or more contributor license agreements. See the NOTICE file
  58389. * distributed with this work for additional information
  58390. * regarding copyright ownership. The ASF licenses this file
  58391. * to you under the Apache License, Version 2.0 (the
  58392. * "License"); you may not use this file except in compliance
  58393. * with the License. You may obtain a copy of the License at
  58394. *
  58395. * http://www.apache.org/licenses/LICENSE-2.0
  58396. *
  58397. * Unless required by applicable law or agreed to in writing,
  58398. * software distributed under the License is distributed on an
  58399. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58400. * KIND, either express or implied. See the License for the
  58401. * specific language governing permissions and limitations
  58402. * under the License.
  58403. */
  58404. function dataToCoordSize$1(dataSize, dataItem) {
  58405. dataItem = dataItem || [0, 0];
  58406. return map([0, 1], function (dimIdx) {
  58407. var val = dataItem[dimIdx];
  58408. var halfSize = dataSize[dimIdx] / 2;
  58409. var p1 = [];
  58410. var p2 = [];
  58411. p1[dimIdx] = val - halfSize;
  58412. p2[dimIdx] = val + halfSize;
  58413. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  58414. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  58415. }, this);
  58416. }
  58417. var prepareGeo = function (coordSys) {
  58418. var rect = coordSys.getBoundingRect();
  58419. return {
  58420. coordSys: {
  58421. type: 'geo',
  58422. x: rect.x,
  58423. y: rect.y,
  58424. width: rect.width,
  58425. height: rect.height
  58426. },
  58427. api: {
  58428. coord: function (data) {
  58429. // do not provide "out" and noRoam param,
  58430. // Compatible with this usage:
  58431. // echarts.util.map(item.points, api.coord)
  58432. return coordSys.dataToPoint(data);
  58433. },
  58434. size: bind(dataToCoordSize$1, coordSys)
  58435. }
  58436. };
  58437. };
  58438. /*
  58439. * Licensed to the Apache Software Foundation (ASF) under one
  58440. * or more contributor license agreements. See the NOTICE file
  58441. * distributed with this work for additional information
  58442. * regarding copyright ownership. The ASF licenses this file
  58443. * to you under the Apache License, Version 2.0 (the
  58444. * "License"); you may not use this file except in compliance
  58445. * with the License. You may obtain a copy of the License at
  58446. *
  58447. * http://www.apache.org/licenses/LICENSE-2.0
  58448. *
  58449. * Unless required by applicable law or agreed to in writing,
  58450. * software distributed under the License is distributed on an
  58451. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58452. * KIND, either express or implied. See the License for the
  58453. * specific language governing permissions and limitations
  58454. * under the License.
  58455. */
  58456. function dataToCoordSize$2(dataSize, dataItem) {
  58457. // dataItem is necessary in log axis.
  58458. var axis = this.getAxis();
  58459. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  58460. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  58461. return axis.type === 'category'
  58462. ? axis.getBandWidth()
  58463. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  58464. }
  58465. var prepareSingleAxis = function (coordSys) {
  58466. var rect = coordSys.getRect();
  58467. return {
  58468. coordSys: {
  58469. type: 'singleAxis',
  58470. x: rect.x,
  58471. y: rect.y,
  58472. width: rect.width,
  58473. height: rect.height
  58474. },
  58475. api: {
  58476. coord: function (val) {
  58477. // do not provide "out" param
  58478. return coordSys.dataToPoint(val);
  58479. },
  58480. size: bind(dataToCoordSize$2, coordSys)
  58481. }
  58482. };
  58483. };
  58484. /*
  58485. * Licensed to the Apache Software Foundation (ASF) under one
  58486. * or more contributor license agreements. See the NOTICE file
  58487. * distributed with this work for additional information
  58488. * regarding copyright ownership. The ASF licenses this file
  58489. * to you under the Apache License, Version 2.0 (the
  58490. * "License"); you may not use this file except in compliance
  58491. * with the License. You may obtain a copy of the License at
  58492. *
  58493. * http://www.apache.org/licenses/LICENSE-2.0
  58494. *
  58495. * Unless required by applicable law or agreed to in writing,
  58496. * software distributed under the License is distributed on an
  58497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58498. * KIND, either express or implied. See the License for the
  58499. * specific language governing permissions and limitations
  58500. * under the License.
  58501. */
  58502. function dataToCoordSize$3(dataSize, dataItem) {
  58503. // dataItem is necessary in log axis.
  58504. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  58505. var axis = this['get' + dim + 'Axis']();
  58506. var val = dataItem[dimIdx];
  58507. var halfSize = dataSize[dimIdx] / 2;
  58508. var method = 'dataTo' + dim;
  58509. var result = axis.type === 'category'
  58510. ? axis.getBandWidth()
  58511. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  58512. if (dim === 'Angle') {
  58513. result = result * Math.PI / 180;
  58514. }
  58515. return result;
  58516. }, this);
  58517. }
  58518. var preparePolar = function (coordSys) {
  58519. var radiusAxis = coordSys.getRadiusAxis();
  58520. var angleAxis = coordSys.getAngleAxis();
  58521. var radius = radiusAxis.getExtent();
  58522. radius[0] > radius[1] && radius.reverse();
  58523. return {
  58524. coordSys: {
  58525. type: 'polar',
  58526. cx: coordSys.cx,
  58527. cy: coordSys.cy,
  58528. r: radius[1],
  58529. r0: radius[0]
  58530. },
  58531. api: {
  58532. coord: bind(function (data) {
  58533. var radius = radiusAxis.dataToRadius(data[0]);
  58534. var angle = angleAxis.dataToAngle(data[1]);
  58535. var coord = coordSys.coordToPoint([radius, angle]);
  58536. coord.push(radius, angle * Math.PI / 180);
  58537. return coord;
  58538. }),
  58539. size: bind(dataToCoordSize$3, coordSys)
  58540. }
  58541. };
  58542. };
  58543. /*
  58544. * Licensed to the Apache Software Foundation (ASF) under one
  58545. * or more contributor license agreements. See the NOTICE file
  58546. * distributed with this work for additional information
  58547. * regarding copyright ownership. The ASF licenses this file
  58548. * to you under the Apache License, Version 2.0 (the
  58549. * "License"); you may not use this file except in compliance
  58550. * with the License. You may obtain a copy of the License at
  58551. *
  58552. * http://www.apache.org/licenses/LICENSE-2.0
  58553. *
  58554. * Unless required by applicable law or agreed to in writing,
  58555. * software distributed under the License is distributed on an
  58556. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58557. * KIND, either express or implied. See the License for the
  58558. * specific language governing permissions and limitations
  58559. * under the License.
  58560. */
  58561. var prepareCalendar = function (coordSys) {
  58562. var rect = coordSys.getRect();
  58563. var rangeInfo = coordSys.getRangeInfo();
  58564. return {
  58565. coordSys: {
  58566. type: 'calendar',
  58567. x: rect.x,
  58568. y: rect.y,
  58569. width: rect.width,
  58570. height: rect.height,
  58571. cellWidth: coordSys.getCellWidth(),
  58572. cellHeight: coordSys.getCellHeight(),
  58573. rangeInfo: {
  58574. start: rangeInfo.start,
  58575. end: rangeInfo.end,
  58576. weeks: rangeInfo.weeks,
  58577. dayCount: rangeInfo.allDay
  58578. }
  58579. },
  58580. api: {
  58581. coord: function (data, clamp) {
  58582. return coordSys.dataToPoint(data, clamp);
  58583. }
  58584. }
  58585. };
  58586. };
  58587. /*
  58588. * Licensed to the Apache Software Foundation (ASF) under one
  58589. * or more contributor license agreements. See the NOTICE file
  58590. * distributed with this work for additional information
  58591. * regarding copyright ownership. The ASF licenses this file
  58592. * to you under the Apache License, Version 2.0 (the
  58593. * "License"); you may not use this file except in compliance
  58594. * with the License. You may obtain a copy of the License at
  58595. *
  58596. * http://www.apache.org/licenses/LICENSE-2.0
  58597. *
  58598. * Unless required by applicable law or agreed to in writing,
  58599. * software distributed under the License is distributed on an
  58600. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58601. * KIND, either express or implied. See the License for the
  58602. * specific language governing permissions and limitations
  58603. * under the License.
  58604. */
  58605. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  58606. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  58607. var LABEL_NORMAL = ['label'];
  58608. var LABEL_EMPHASIS = ['emphasis', 'label'];
  58609. // Use prefix to avoid index to be the same as el.name,
  58610. // which will cause weird udpate animation.
  58611. var GROUP_DIFF_PREFIX = 'e\0\0';
  58612. /**
  58613. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  58614. * of each coordinate systems are not required by each coordinate systems directly, but
  58615. * required by the module `custom`.
  58616. *
  58617. * prepareInfoForCustomSeries {Function}: optional
  58618. * @return {Object} {coordSys: {...}, api: {
  58619. * coord: function (data, clamp) {}, // return point in global.
  58620. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  58621. * }}
  58622. */
  58623. var prepareCustoms = {
  58624. cartesian2d: prepareCartesian2d,
  58625. geo: prepareGeo,
  58626. singleAxis: prepareSingleAxis,
  58627. polar: preparePolar,
  58628. calendar: prepareCalendar
  58629. };
  58630. // ------
  58631. // Model
  58632. // ------
  58633. extendSeriesModel({
  58634. type: 'series.custom',
  58635. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  58636. defaultOption: {
  58637. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  58638. zlevel: 0,
  58639. z: 2,
  58640. legendHoverLink: true
  58641. // Cartesian coordinate system
  58642. // xAxisIndex: 0,
  58643. // yAxisIndex: 0,
  58644. // Polar coordinate system
  58645. // polarIndex: 0,
  58646. // Geo coordinate system
  58647. // geoIndex: 0,
  58648. // label: {}
  58649. // itemStyle: {}
  58650. },
  58651. getInitialData: function (option, ecModel) {
  58652. return createListFromArray(this.getSource(), this);
  58653. }
  58654. });
  58655. // -----
  58656. // View
  58657. // -----
  58658. extendChartView({
  58659. type: 'custom',
  58660. /**
  58661. * @private
  58662. * @type {module:echarts/data/List}
  58663. */
  58664. _data: null,
  58665. /**
  58666. * @override
  58667. */
  58668. render: function (customSeries, ecModel, api) {
  58669. var oldData = this._data;
  58670. var data = customSeries.getData();
  58671. var group = this.group;
  58672. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  58673. this.group.removeAll();
  58674. data.diff(oldData)
  58675. .add(function (newIdx) {
  58676. createOrUpdate$1(
  58677. null, newIdx, renderItem(newIdx), customSeries, group, data
  58678. );
  58679. })
  58680. .update(function (newIdx, oldIdx) {
  58681. var el = oldData.getItemGraphicEl(oldIdx);
  58682. createOrUpdate$1(
  58683. el, newIdx, renderItem(newIdx), customSeries, group, data
  58684. );
  58685. })
  58686. .remove(function (oldIdx) {
  58687. var el = oldData.getItemGraphicEl(oldIdx);
  58688. el && group.remove(el);
  58689. })
  58690. .execute();
  58691. this._data = data;
  58692. },
  58693. incrementalPrepareRender: function (customSeries, ecModel, api) {
  58694. this.group.removeAll();
  58695. this._data = null;
  58696. },
  58697. incrementalRender: function (params, customSeries, ecModel, api) {
  58698. var data = customSeries.getData();
  58699. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  58700. function setIncrementalAndHoverLayer(el) {
  58701. if (!el.isGroup) {
  58702. el.incremental = true;
  58703. el.useHoverLayer = true;
  58704. }
  58705. }
  58706. for (var idx = params.start; idx < params.end; idx++) {
  58707. var el = createOrUpdate$1(null, idx, renderItem(idx), customSeries, this.group, data);
  58708. el.traverse(setIncrementalAndHoverLayer);
  58709. }
  58710. },
  58711. /**
  58712. * @override
  58713. */
  58714. dispose: noop
  58715. });
  58716. function createEl(elOption) {
  58717. var graphicType = elOption.type;
  58718. var el;
  58719. if (graphicType === 'path') {
  58720. var shape = elOption.shape;
  58721. el = makePath(
  58722. shape.pathData,
  58723. null,
  58724. {
  58725. x: shape.x || 0,
  58726. y: shape.y || 0,
  58727. width: shape.width || 0,
  58728. height: shape.height || 0
  58729. },
  58730. 'center'
  58731. );
  58732. el.__customPathData = elOption.pathData;
  58733. }
  58734. else if (graphicType === 'image') {
  58735. el = new ZImage({
  58736. });
  58737. el.__customImagePath = elOption.style.image;
  58738. }
  58739. else if (graphicType === 'text') {
  58740. el = new Text({
  58741. });
  58742. el.__customText = elOption.style.text;
  58743. }
  58744. else {
  58745. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  58746. if (__DEV__) {
  58747. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  58748. }
  58749. el = new Clz();
  58750. }
  58751. el.__customGraphicType = graphicType;
  58752. el.name = elOption.name;
  58753. return el;
  58754. }
  58755. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
  58756. var targetProps = {};
  58757. var elOptionStyle = elOption.style || {};
  58758. elOption.shape && (targetProps.shape = clone(elOption.shape));
  58759. elOption.position && (targetProps.position = elOption.position.slice());
  58760. elOption.scale && (targetProps.scale = elOption.scale.slice());
  58761. elOption.origin && (targetProps.origin = elOption.origin.slice());
  58762. elOption.rotation && (targetProps.rotation = elOption.rotation);
  58763. if (el.type === 'image' && elOption.style) {
  58764. var targetStyle = targetProps.style = {};
  58765. each$1(['x', 'y', 'width', 'height'], function (prop) {
  58766. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  58767. });
  58768. }
  58769. if (el.type === 'text' && elOption.style) {
  58770. var targetStyle = targetProps.style = {};
  58771. each$1(['x', 'y'], function (prop) {
  58772. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  58773. });
  58774. // Compatible with previous: both support
  58775. // textFill and fill, textStroke and stroke in 'text' element.
  58776. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  58777. elOptionStyle.textFill = elOptionStyle.fill
  58778. );
  58779. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  58780. elOptionStyle.textStroke = elOptionStyle.stroke
  58781. );
  58782. }
  58783. if (el.type !== 'group') {
  58784. el.useStyle(elOptionStyle);
  58785. // Init animation.
  58786. if (isInit) {
  58787. el.style.opacity = 0;
  58788. var targetOpacity = elOptionStyle.opacity;
  58789. targetOpacity == null && (targetOpacity = 1);
  58790. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  58791. }
  58792. }
  58793. if (isInit) {
  58794. el.attr(targetProps);
  58795. }
  58796. else {
  58797. updateProps(el, targetProps, animatableModel, dataIndex);
  58798. }
  58799. // z2 must not be null/undefined, otherwise sort error may occur.
  58800. el.attr({z2: elOption.z2 || 0, silent: elOption.silent});
  58801. elOption.styleEmphasis !== false && setHoverStyle(el, elOption.styleEmphasis);
  58802. }
  58803. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  58804. if (elOptionStyle[prop] != null && !isInit) {
  58805. targetStyle[prop] = elOptionStyle[prop];
  58806. elOptionStyle[prop] = oldElStyle[prop];
  58807. }
  58808. }
  58809. function makeRenderItem(customSeries, data, ecModel, api) {
  58810. var renderItem = customSeries.get('renderItem');
  58811. var coordSys = customSeries.coordinateSystem;
  58812. var prepareResult = {};
  58813. if (coordSys) {
  58814. if (__DEV__) {
  58815. assert$1(renderItem, 'series.render is required.');
  58816. assert$1(
  58817. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  58818. 'This coordSys does not support custom series.'
  58819. );
  58820. }
  58821. prepareResult = coordSys.prepareCustoms
  58822. ? coordSys.prepareCustoms()
  58823. : prepareCustoms[coordSys.type](coordSys);
  58824. }
  58825. var userAPI = defaults({
  58826. getWidth: api.getWidth,
  58827. getHeight: api.getHeight,
  58828. getZr: api.getZr,
  58829. getDevicePixelRatio: api.getDevicePixelRatio,
  58830. value: value,
  58831. style: style,
  58832. styleEmphasis: styleEmphasis,
  58833. visual: visual,
  58834. barLayout: barLayout,
  58835. currentSeriesIndices: currentSeriesIndices,
  58836. font: font
  58837. }, prepareResult.api || {});
  58838. var userParams = {
  58839. context: {},
  58840. seriesId: customSeries.id,
  58841. seriesName: customSeries.name,
  58842. seriesIndex: customSeries.seriesIndex,
  58843. coordSys: prepareResult.coordSys,
  58844. dataInsideLength: data.count(),
  58845. encode: wrapEncodeDef(customSeries.getData())
  58846. };
  58847. // Do not support call `api` asynchronously without dataIndexInside input.
  58848. var currDataIndexInside;
  58849. var currDirty = true;
  58850. var currItemModel;
  58851. var currLabelNormalModel;
  58852. var currLabelEmphasisModel;
  58853. var currVisualColor;
  58854. return function (dataIndexInside) {
  58855. currDataIndexInside = dataIndexInside;
  58856. currDirty = true;
  58857. return renderItem && renderItem(
  58858. defaults({
  58859. dataIndexInside: dataIndexInside,
  58860. dataIndex: data.getRawIndex(dataIndexInside)
  58861. }, userParams),
  58862. userAPI
  58863. ) || {};
  58864. };
  58865. // Do not update cache until api called.
  58866. function updateCache(dataIndexInside) {
  58867. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58868. if (currDirty) {
  58869. currItemModel = data.getItemModel(dataIndexInside);
  58870. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  58871. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  58872. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  58873. currDirty = false;
  58874. }
  58875. }
  58876. /**
  58877. * @public
  58878. * @param {number|string} dim
  58879. * @param {number} [dataIndexInside=currDataIndexInside]
  58880. * @return {number|string} value
  58881. */
  58882. function value(dim, dataIndexInside) {
  58883. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58884. return data.get(data.getDimension(dim || 0), dataIndexInside);
  58885. }
  58886. /**
  58887. * By default, `visual` is applied to style (to support visualMap).
  58888. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  58889. * it can be implemented as:
  58890. * `api.style({stroke: api.visual('color'), fill: null})`;
  58891. * @public
  58892. * @param {Object} [extra]
  58893. * @param {number} [dataIndexInside=currDataIndexInside]
  58894. */
  58895. function style(extra, dataIndexInside) {
  58896. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58897. updateCache(dataIndexInside);
  58898. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  58899. currVisualColor != null && (itemStyle.fill = currVisualColor);
  58900. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  58901. opacity != null && (itemStyle.opacity = opacity);
  58902. setTextStyle(itemStyle, currLabelNormalModel, null, {
  58903. autoColor: currVisualColor,
  58904. isRectText: true
  58905. });
  58906. itemStyle.text = currLabelNormalModel.getShallow('show')
  58907. ? retrieve2(
  58908. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  58909. getDefaultLabel(data, dataIndexInside)
  58910. )
  58911. : null;
  58912. extra && extend(itemStyle, extra);
  58913. return itemStyle;
  58914. }
  58915. /**
  58916. * @public
  58917. * @param {Object} [extra]
  58918. * @param {number} [dataIndexInside=currDataIndexInside]
  58919. */
  58920. function styleEmphasis(extra, dataIndexInside) {
  58921. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58922. updateCache(dataIndexInside);
  58923. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  58924. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  58925. isRectText: true
  58926. }, true);
  58927. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  58928. ? retrieve3(
  58929. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  58930. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  58931. getDefaultLabel(data, dataIndexInside)
  58932. )
  58933. : null;
  58934. extra && extend(itemStyle, extra);
  58935. return itemStyle;
  58936. }
  58937. /**
  58938. * @public
  58939. * @param {string} visualType
  58940. * @param {number} [dataIndexInside=currDataIndexInside]
  58941. */
  58942. function visual(visualType, dataIndexInside) {
  58943. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58944. return data.getItemVisual(dataIndexInside, visualType);
  58945. }
  58946. /**
  58947. * @public
  58948. * @param {number} opt.count Positive interger.
  58949. * @param {number} [opt.barWidth]
  58950. * @param {number} [opt.barMaxWidth]
  58951. * @param {number} [opt.barGap]
  58952. * @param {number} [opt.barCategoryGap]
  58953. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  58954. */
  58955. function barLayout(opt) {
  58956. if (coordSys.getBaseAxis) {
  58957. var baseAxis = coordSys.getBaseAxis();
  58958. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  58959. }
  58960. }
  58961. /**
  58962. * @public
  58963. * @return {Array.<number>}
  58964. */
  58965. function currentSeriesIndices() {
  58966. return ecModel.getCurrentSeriesIndices();
  58967. }
  58968. /**
  58969. * @public
  58970. * @param {Object} opt
  58971. * @param {string} [opt.fontStyle]
  58972. * @param {number} [opt.fontWeight]
  58973. * @param {number} [opt.fontSize]
  58974. * @param {string} [opt.fontFamily]
  58975. * @return {string} font string
  58976. */
  58977. function font(opt) {
  58978. return getFont(opt, ecModel);
  58979. }
  58980. }
  58981. function wrapEncodeDef(data) {
  58982. var encodeDef = {};
  58983. each$1(data.dimensions, function (dimName, dataDimIndex) {
  58984. var dimInfo = data.getDimensionInfo(dimName);
  58985. if (!dimInfo.isExtraCoord) {
  58986. var coordDim = dimInfo.coordDim;
  58987. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  58988. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  58989. }
  58990. });
  58991. return encodeDef;
  58992. }
  58993. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  58994. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
  58995. el && data.setItemGraphicEl(dataIndex, el);
  58996. return el;
  58997. }
  58998. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
  58999. var elOptionType = elOption.type;
  59000. if (el
  59001. && elOptionType !== el.__customGraphicType
  59002. && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
  59003. && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
  59004. && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
  59005. ) {
  59006. group.remove(el);
  59007. el = null;
  59008. }
  59009. // `elOption.type` is undefined when `renderItem` returns nothing.
  59010. if (elOptionType == null) {
  59011. return;
  59012. }
  59013. var isInit = !el;
  59014. !el && (el = createEl(elOption));
  59015. updateEl(el, dataIndex, elOption, animatableModel, data, isInit);
  59016. if (elOptionType === 'group') {
  59017. var oldChildren = el.children() || [];
  59018. var newChildren = elOption.children || [];
  59019. if (elOption.diffChildrenByName) {
  59020. // lower performance.
  59021. diffGroupChildren({
  59022. oldChildren: oldChildren,
  59023. newChildren: newChildren,
  59024. dataIndex: dataIndex,
  59025. animatableModel: animatableModel,
  59026. group: el,
  59027. data: data
  59028. });
  59029. }
  59030. else {
  59031. // better performance.
  59032. var index = 0;
  59033. for (; index < newChildren.length; index++) {
  59034. doCreateOrUpdate(
  59035. el.childAt(index),
  59036. dataIndex,
  59037. newChildren[index],
  59038. animatableModel,
  59039. el,
  59040. data
  59041. );
  59042. }
  59043. for (; index < oldChildren.length; index++) {
  59044. oldChildren[index] && el.remove(oldChildren[index]);
  59045. }
  59046. }
  59047. }
  59048. group.add(el);
  59049. return el;
  59050. }
  59051. function diffGroupChildren(context) {
  59052. (new DataDiffer(
  59053. context.oldChildren,
  59054. context.newChildren,
  59055. getKey,
  59056. getKey,
  59057. context
  59058. ))
  59059. .add(processAddUpdate)
  59060. .update(processAddUpdate)
  59061. .remove(processRemove)
  59062. .execute();
  59063. }
  59064. function getKey(item, idx) {
  59065. var name = item && item.name;
  59066. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  59067. }
  59068. function processAddUpdate(newIndex, oldIndex) {
  59069. var context = this.context;
  59070. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  59071. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  59072. doCreateOrUpdate(
  59073. child,
  59074. context.dataIndex,
  59075. childOption,
  59076. context.animatableModel,
  59077. context.group,
  59078. context.data
  59079. );
  59080. }
  59081. function processRemove(oldIndex) {
  59082. var context = this.context;
  59083. var child = context.oldChildren[oldIndex];
  59084. child && context.group.remove(child);
  59085. }
  59086. /*
  59087. * Licensed to the Apache Software Foundation (ASF) under one
  59088. * or more contributor license agreements. See the NOTICE file
  59089. * distributed with this work for additional information
  59090. * regarding copyright ownership. The ASF licenses this file
  59091. * to you under the Apache License, Version 2.0 (the
  59092. * "License"); you may not use this file except in compliance
  59093. * with the License. You may obtain a copy of the License at
  59094. *
  59095. * http://www.apache.org/licenses/LICENSE-2.0
  59096. *
  59097. * Unless required by applicable law or agreed to in writing,
  59098. * software distributed under the License is distributed on an
  59099. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59100. * KIND, either express or implied. See the License for the
  59101. * specific language governing permissions and limitations
  59102. * under the License.
  59103. */
  59104. // -------------
  59105. // Preprocessor
  59106. // -------------
  59107. registerPreprocessor(function (option) {
  59108. var graphicOption = option.graphic;
  59109. // Convert
  59110. // {graphic: [{left: 10, type: 'circle'}, ...]}
  59111. // or
  59112. // {graphic: {left: 10, type: 'circle'}}
  59113. // to
  59114. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  59115. if (isArray(graphicOption)) {
  59116. if (!graphicOption[0] || !graphicOption[0].elements) {
  59117. option.graphic = [{elements: graphicOption}];
  59118. }
  59119. else {
  59120. // Only one graphic instance can be instantiated. (We dont
  59121. // want that too many views are created in echarts._viewMap)
  59122. option.graphic = [option.graphic[0]];
  59123. }
  59124. }
  59125. else if (graphicOption && !graphicOption.elements) {
  59126. option.graphic = [{elements: [graphicOption]}];
  59127. }
  59128. });
  59129. // ------
  59130. // Model
  59131. // ------
  59132. var GraphicModel = extendComponentModel({
  59133. type: 'graphic',
  59134. defaultOption: {
  59135. // Extra properties for each elements:
  59136. //
  59137. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  59138. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  59139. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  59140. // This mechanism is useful when you want to position a group/element
  59141. // against the right side or the center of this container.
  59142. //
  59143. // width/height: (can only be pixel value, default 0)
  59144. // Only be used to specify contianer(group) size, if needed. And
  59145. // can not be percentage value (like '33%'). See the reason in the
  59146. // layout algorithm below.
  59147. //
  59148. // bounding: (enum: 'all' (default) | 'raw')
  59149. // Specify how to calculate boundingRect when locating.
  59150. // 'all': Get uioned and transformed boundingRect
  59151. // from both itself and its descendants.
  59152. // This mode simplies confining a group of elements in the bounding
  59153. // of their ancester container (e.g., using 'right: 0').
  59154. // 'raw': Only use the boundingRect of itself and before transformed.
  59155. // This mode is similar to css behavior, which is useful when you
  59156. // want an element to be able to overflow its container. (Consider
  59157. // a rotated circle needs to be located in a corner.)
  59158. // Note: elements is always behind its ancestors in this elements array.
  59159. elements: [],
  59160. parentId: null
  59161. },
  59162. /**
  59163. * Save el options for the sake of the performance (only update modified graphics).
  59164. * The order is the same as those in option. (ancesters -> descendants)
  59165. *
  59166. * @private
  59167. * @type {Array.<Object>}
  59168. */
  59169. _elOptionsToUpdate: null,
  59170. /**
  59171. * @override
  59172. */
  59173. mergeOption: function (option) {
  59174. // Prevent default merge to elements
  59175. var elements = this.option.elements;
  59176. this.option.elements = null;
  59177. GraphicModel.superApply(this, 'mergeOption', arguments);
  59178. this.option.elements = elements;
  59179. },
  59180. /**
  59181. * @override
  59182. */
  59183. optionUpdated: function (newOption, isInit) {
  59184. var thisOption = this.option;
  59185. var newList = (isInit ? thisOption : newOption).elements;
  59186. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  59187. var flattenedList = [];
  59188. this._flatten(newList, flattenedList);
  59189. var mappingResult = mappingToExists(existList, flattenedList);
  59190. makeIdAndName(mappingResult);
  59191. // Clear elOptionsToUpdate
  59192. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  59193. each$1(mappingResult, function (resultItem, index) {
  59194. var newElOption = resultItem.option;
  59195. if (__DEV__) {
  59196. assert$1(
  59197. isObject$1(newElOption) || resultItem.exist,
  59198. 'Empty graphic option definition'
  59199. );
  59200. }
  59201. if (!newElOption) {
  59202. return;
  59203. }
  59204. elOptionsToUpdate.push(newElOption);
  59205. setKeyInfoToNewElOption(resultItem, newElOption);
  59206. mergeNewElOptionToExist(existList, index, newElOption);
  59207. setLayoutInfoToExist(existList[index], newElOption);
  59208. }, this);
  59209. // Clean
  59210. for (var i = existList.length - 1; i >= 0; i--) {
  59211. if (existList[i] == null) {
  59212. existList.splice(i, 1);
  59213. }
  59214. else {
  59215. // $action should be volatile, otherwise option gotten from
  59216. // `getOption` will contain unexpected $action.
  59217. delete existList[i].$action;
  59218. }
  59219. }
  59220. },
  59221. /**
  59222. * Convert
  59223. * [{
  59224. * type: 'group',
  59225. * id: 'xx',
  59226. * children: [{type: 'circle'}, {type: 'polygon'}]
  59227. * }]
  59228. * to
  59229. * [
  59230. * {type: 'group', id: 'xx'},
  59231. * {type: 'circle', parentId: 'xx'},
  59232. * {type: 'polygon', parentId: 'xx'}
  59233. * ]
  59234. *
  59235. * @private
  59236. * @param {Array.<Object>} optionList option list
  59237. * @param {Array.<Object>} result result of flatten
  59238. * @param {Object} parentOption parent option
  59239. */
  59240. _flatten: function (optionList, result, parentOption) {
  59241. each$1(optionList, function (option) {
  59242. if (!option) {
  59243. return;
  59244. }
  59245. if (parentOption) {
  59246. option.parentOption = parentOption;
  59247. }
  59248. result.push(option);
  59249. var children = option.children;
  59250. if (option.type === 'group' && children) {
  59251. this._flatten(children, result, option);
  59252. }
  59253. // Deleting for JSON output, and for not affecting group creation.
  59254. delete option.children;
  59255. }, this);
  59256. },
  59257. // FIXME
  59258. // Pass to view using payload? setOption has a payload?
  59259. useElOptionsToUpdate: function () {
  59260. var els = this._elOptionsToUpdate;
  59261. // Clear to avoid render duplicately when zooming.
  59262. this._elOptionsToUpdate = null;
  59263. return els;
  59264. }
  59265. });
  59266. // -----
  59267. // View
  59268. // -----
  59269. extendComponentView({
  59270. type: 'graphic',
  59271. /**
  59272. * @override
  59273. */
  59274. init: function (ecModel, api) {
  59275. /**
  59276. * @private
  59277. * @type {module:zrender/core/util.HashMap}
  59278. */
  59279. this._elMap = createHashMap();
  59280. /**
  59281. * @private
  59282. * @type {module:echarts/graphic/GraphicModel}
  59283. */
  59284. this._lastGraphicModel;
  59285. },
  59286. /**
  59287. * @override
  59288. */
  59289. render: function (graphicModel, ecModel, api) {
  59290. // Having leveraged between use cases and algorithm complexity, a very
  59291. // simple layout mechanism is used:
  59292. // The size(width/height) can be determined by itself or its parent (not
  59293. // implemented yet), but can not by its children. (Top-down travel)
  59294. // The location(x/y) can be determined by the bounding rect of itself
  59295. // (can including its descendants or not) and the size of its parent.
  59296. // (Bottom-up travel)
  59297. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  59298. // view will be reused.
  59299. if (graphicModel !== this._lastGraphicModel) {
  59300. this._clear();
  59301. }
  59302. this._lastGraphicModel = graphicModel;
  59303. this._updateElements(graphicModel, api);
  59304. this._relocate(graphicModel, api);
  59305. },
  59306. /**
  59307. * Update graphic elements.
  59308. *
  59309. * @private
  59310. * @param {Object} graphicModel graphic model
  59311. * @param {module:echarts/ExtensionAPI} api extension API
  59312. */
  59313. _updateElements: function (graphicModel, api) {
  59314. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  59315. if (!elOptionsToUpdate) {
  59316. return;
  59317. }
  59318. var elMap = this._elMap;
  59319. var rootGroup = this.group;
  59320. // Top-down tranverse to assign graphic settings to each elements.
  59321. each$1(elOptionsToUpdate, function (elOption) {
  59322. var $action = elOption.$action;
  59323. var id = elOption.id;
  59324. var existEl = elMap.get(id);
  59325. var parentId = elOption.parentId;
  59326. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  59327. if (elOption.type === 'text') {
  59328. var elOptionStyle = elOption.style;
  59329. // In top/bottom mode, textVerticalAlign should not be used, which cause
  59330. // inaccurately locating.
  59331. if (elOption.hv && elOption.hv[1]) {
  59332. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  59333. }
  59334. // Compatible with previous setting: both support fill and textFill,
  59335. // stroke and textStroke.
  59336. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  59337. elOptionStyle.textFill = elOptionStyle.fill
  59338. );
  59339. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  59340. elOptionStyle.textStroke = elOptionStyle.stroke
  59341. );
  59342. }
  59343. // Remove unnecessary props to avoid potential problems.
  59344. var elOptionCleaned = getCleanedElOption(elOption);
  59345. // For simple, do not support parent change, otherwise reorder is needed.
  59346. if (__DEV__) {
  59347. existEl && assert$1(
  59348. targetElParent === existEl.parent,
  59349. 'Changing parent is not supported.'
  59350. );
  59351. }
  59352. if (!$action || $action === 'merge') {
  59353. existEl
  59354. ? existEl.attr(elOptionCleaned)
  59355. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  59356. }
  59357. else if ($action === 'replace') {
  59358. removeEl(existEl, elMap);
  59359. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  59360. }
  59361. else if ($action === 'remove') {
  59362. removeEl(existEl, elMap);
  59363. }
  59364. var el = elMap.get(id);
  59365. if (el) {
  59366. el.__ecGraphicWidth = elOption.width;
  59367. el.__ecGraphicHeight = elOption.height;
  59368. }
  59369. });
  59370. },
  59371. /**
  59372. * Locate graphic elements.
  59373. *
  59374. * @private
  59375. * @param {Object} graphicModel graphic model
  59376. * @param {module:echarts/ExtensionAPI} api extension API
  59377. */
  59378. _relocate: function (graphicModel, api) {
  59379. var elOptions = graphicModel.option.elements;
  59380. var rootGroup = this.group;
  59381. var elMap = this._elMap;
  59382. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  59383. for (var i = elOptions.length - 1; i >= 0; i--) {
  59384. var elOption = elOptions[i];
  59385. var el = elMap.get(elOption.id);
  59386. if (!el) {
  59387. continue;
  59388. }
  59389. var parentEl = el.parent;
  59390. var containerInfo = parentEl === rootGroup
  59391. ? {
  59392. width: api.getWidth(),
  59393. height: api.getHeight()
  59394. }
  59395. : { // Like 'position:absolut' in css, default 0.
  59396. width: parentEl.__ecGraphicWidth || 0,
  59397. height: parentEl.__ecGraphicHeight || 0
  59398. };
  59399. positionElement(
  59400. el, elOption, containerInfo, null,
  59401. {hv: elOption.hv, boundingMode: elOption.bounding}
  59402. );
  59403. }
  59404. },
  59405. /**
  59406. * Clear all elements.
  59407. *
  59408. * @private
  59409. */
  59410. _clear: function () {
  59411. var elMap = this._elMap;
  59412. elMap.each(function (el) {
  59413. removeEl(el, elMap);
  59414. });
  59415. this._elMap = createHashMap();
  59416. },
  59417. /**
  59418. * @override
  59419. */
  59420. dispose: function () {
  59421. this._clear();
  59422. }
  59423. });
  59424. function createEl$1(id, targetElParent, elOption, elMap) {
  59425. var graphicType = elOption.type;
  59426. if (__DEV__) {
  59427. assert$1(graphicType, 'graphic type MUST be set');
  59428. }
  59429. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  59430. if (__DEV__) {
  59431. assert$1(Clz, 'graphic type can not be found');
  59432. }
  59433. var el = new Clz(elOption);
  59434. targetElParent.add(el);
  59435. elMap.set(id, el);
  59436. el.__ecGraphicId = id;
  59437. }
  59438. function removeEl(existEl, elMap) {
  59439. var existElParent = existEl && existEl.parent;
  59440. if (existElParent) {
  59441. existEl.type === 'group' && existEl.traverse(function (el) {
  59442. removeEl(el, elMap);
  59443. });
  59444. elMap.removeKey(existEl.__ecGraphicId);
  59445. existElParent.remove(existEl);
  59446. }
  59447. }
  59448. // Remove unnecessary props to avoid potential problems.
  59449. function getCleanedElOption(elOption) {
  59450. elOption = extend({}, elOption);
  59451. each$1(
  59452. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  59453. function (name) {
  59454. delete elOption[name];
  59455. }
  59456. );
  59457. return elOption;
  59458. }
  59459. function isSetLoc(obj, props) {
  59460. var isSet;
  59461. each$1(props, function (prop) {
  59462. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  59463. });
  59464. return isSet;
  59465. }
  59466. function setKeyInfoToNewElOption(resultItem, newElOption) {
  59467. var existElOption = resultItem.exist;
  59468. // Set id and type after id assigned.
  59469. newElOption.id = resultItem.keyInfo.id;
  59470. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  59471. // Set parent id if not specified
  59472. if (newElOption.parentId == null) {
  59473. var newElParentOption = newElOption.parentOption;
  59474. if (newElParentOption) {
  59475. newElOption.parentId = newElParentOption.id;
  59476. }
  59477. else if (existElOption) {
  59478. newElOption.parentId = existElOption.parentId;
  59479. }
  59480. }
  59481. // Clear
  59482. newElOption.parentOption = null;
  59483. }
  59484. function mergeNewElOptionToExist(existList, index, newElOption) {
  59485. // Update existing options, for `getOption` feature.
  59486. var newElOptCopy = extend({}, newElOption);
  59487. var existElOption = existList[index];
  59488. var $action = newElOption.$action || 'merge';
  59489. if ($action === 'merge') {
  59490. if (existElOption) {
  59491. if (__DEV__) {
  59492. var newType = newElOption.type;
  59493. assert$1(
  59494. !newType || existElOption.type === newType,
  59495. 'Please set $action: "replace" to change `type`'
  59496. );
  59497. }
  59498. // We can ensure that newElOptCopy and existElOption are not
  59499. // the same object, so `merge` will not change newElOptCopy.
  59500. merge(existElOption, newElOptCopy, true);
  59501. // Rigid body, use ignoreSize.
  59502. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  59503. // Will be used in render.
  59504. copyLayoutParams(newElOption, existElOption);
  59505. }
  59506. else {
  59507. existList[index] = newElOptCopy;
  59508. }
  59509. }
  59510. else if ($action === 'replace') {
  59511. existList[index] = newElOptCopy;
  59512. }
  59513. else if ($action === 'remove') {
  59514. // null will be cleaned later.
  59515. existElOption && (existList[index] = null);
  59516. }
  59517. }
  59518. function setLayoutInfoToExist(existItem, newElOption) {
  59519. if (!existItem) {
  59520. return;
  59521. }
  59522. existItem.hv = newElOption.hv = [
  59523. // Rigid body, dont care `width`.
  59524. isSetLoc(newElOption, ['left', 'right']),
  59525. // Rigid body, dont care `height`.
  59526. isSetLoc(newElOption, ['top', 'bottom'])
  59527. ];
  59528. // Give default group size. Otherwise layout error may occur.
  59529. if (existItem.type === 'group') {
  59530. existItem.width == null && (existItem.width = newElOption.width = 0);
  59531. existItem.height == null && (existItem.height = newElOption.height = 0);
  59532. }
  59533. }
  59534. /*
  59535. * Licensed to the Apache Software Foundation (ASF) under one
  59536. * or more contributor license agreements. See the NOTICE file
  59537. * distributed with this work for additional information
  59538. * regarding copyright ownership. The ASF licenses this file
  59539. * to you under the Apache License, Version 2.0 (the
  59540. * "License"); you may not use this file except in compliance
  59541. * with the License. You may obtain a copy of the License at
  59542. *
  59543. * http://www.apache.org/licenses/LICENSE-2.0
  59544. *
  59545. * Unless required by applicable law or agreed to in writing,
  59546. * software distributed under the License is distributed on an
  59547. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59548. * KIND, either express or implied. See the License for the
  59549. * specific language governing permissions and limitations
  59550. * under the License.
  59551. */
  59552. /*
  59553. * Licensed to the Apache Software Foundation (ASF) under one
  59554. * or more contributor license agreements. See the NOTICE file
  59555. * distributed with this work for additional information
  59556. * regarding copyright ownership. The ASF licenses this file
  59557. * to you under the Apache License, Version 2.0 (the
  59558. * "License"); you may not use this file except in compliance
  59559. * with the License. You may obtain a copy of the License at
  59560. *
  59561. * http://www.apache.org/licenses/LICENSE-2.0
  59562. *
  59563. * Unless required by applicable law or agreed to in writing,
  59564. * software distributed under the License is distributed on an
  59565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59566. * KIND, either express or implied. See the License for the
  59567. * specific language governing permissions and limitations
  59568. * under the License.
  59569. */
  59570. var LegendModel = extendComponentModel({
  59571. type: 'legend.plain',
  59572. dependencies: ['series'],
  59573. layoutMode: {
  59574. type: 'box',
  59575. // legend.width/height are maxWidth/maxHeight actually,
  59576. // whereas realy width/height is calculated by its content.
  59577. // (Setting {left: 10, right: 10} does not make sense).
  59578. // So consider the case:
  59579. // `setOption({legend: {left: 10});`
  59580. // then `setOption({legend: {right: 10});`
  59581. // The previous `left` should be cleared by setting `ignoreSize`.
  59582. ignoreSize: true
  59583. },
  59584. init: function (option, parentModel, ecModel) {
  59585. this.mergeDefaultAndTheme(option, ecModel);
  59586. option.selected = option.selected || {};
  59587. },
  59588. mergeOption: function (option) {
  59589. LegendModel.superCall(this, 'mergeOption', option);
  59590. },
  59591. optionUpdated: function () {
  59592. this._updateData(this.ecModel);
  59593. var legendData = this._data;
  59594. // If selectedMode is single, try to select one
  59595. if (legendData[0] && this.get('selectedMode') === 'single') {
  59596. var hasSelected = false;
  59597. // If has any selected in option.selected
  59598. for (var i = 0; i < legendData.length; i++) {
  59599. var name = legendData[i].get('name');
  59600. if (this.isSelected(name)) {
  59601. // Force to unselect others
  59602. this.select(name);
  59603. hasSelected = true;
  59604. break;
  59605. }
  59606. }
  59607. // Try select the first if selectedMode is single
  59608. !hasSelected && this.select(legendData[0].get('name'));
  59609. }
  59610. },
  59611. _updateData: function (ecModel) {
  59612. var potentialData = [];
  59613. var availableNames = [];
  59614. ecModel.eachRawSeries(function (seriesModel) {
  59615. var seriesName = seriesModel.name;
  59616. availableNames.push(seriesName);
  59617. var isPotential;
  59618. if (seriesModel.legendDataProvider) {
  59619. var data = seriesModel.legendDataProvider();
  59620. var names = data.mapArray(data.getName);
  59621. if (!ecModel.isSeriesFiltered(seriesModel)) {
  59622. availableNames = availableNames.concat(names);
  59623. }
  59624. if (names.length) {
  59625. potentialData = potentialData.concat(names);
  59626. }
  59627. else {
  59628. isPotential = true;
  59629. }
  59630. }
  59631. else {
  59632. isPotential = true;
  59633. }
  59634. if (isPotential && isNameSpecified(seriesModel)) {
  59635. potentialData.push(seriesModel.name);
  59636. }
  59637. });
  59638. /**
  59639. * @type {Array.<string>}
  59640. * @private
  59641. */
  59642. this._availableNames = availableNames;
  59643. // If legend.data not specified in option, use availableNames as data,
  59644. // which is convinient for user preparing option.
  59645. var rawData = this.get('data') || potentialData;
  59646. var legendData = map(rawData, function (dataItem) {
  59647. // Can be string or number
  59648. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  59649. dataItem = {
  59650. name: dataItem
  59651. };
  59652. }
  59653. return new Model(dataItem, this, this.ecModel);
  59654. }, this);
  59655. /**
  59656. * @type {Array.<module:echarts/model/Model>}
  59657. * @private
  59658. */
  59659. this._data = legendData;
  59660. },
  59661. /**
  59662. * @return {Array.<module:echarts/model/Model>}
  59663. */
  59664. getData: function () {
  59665. return this._data;
  59666. },
  59667. /**
  59668. * @param {string} name
  59669. */
  59670. select: function (name) {
  59671. var selected = this.option.selected;
  59672. var selectedMode = this.get('selectedMode');
  59673. if (selectedMode === 'single') {
  59674. var data = this._data;
  59675. each$1(data, function (dataItem) {
  59676. selected[dataItem.get('name')] = false;
  59677. });
  59678. }
  59679. selected[name] = true;
  59680. },
  59681. /**
  59682. * @param {string} name
  59683. */
  59684. unSelect: function (name) {
  59685. if (this.get('selectedMode') !== 'single') {
  59686. this.option.selected[name] = false;
  59687. }
  59688. },
  59689. /**
  59690. * @param {string} name
  59691. */
  59692. toggleSelected: function (name) {
  59693. var selected = this.option.selected;
  59694. // Default is true
  59695. if (!selected.hasOwnProperty(name)) {
  59696. selected[name] = true;
  59697. }
  59698. this[selected[name] ? 'unSelect' : 'select'](name);
  59699. },
  59700. /**
  59701. * @param {string} name
  59702. */
  59703. isSelected: function (name) {
  59704. var selected = this.option.selected;
  59705. return !(selected.hasOwnProperty(name) && !selected[name])
  59706. && indexOf(this._availableNames, name) >= 0;
  59707. },
  59708. defaultOption: {
  59709. // 一级层叠
  59710. zlevel: 0,
  59711. // 二级层叠
  59712. z: 4,
  59713. show: true,
  59714. // 布局方式,默认为水平布局,可选为:
  59715. // 'horizontal' | 'vertical'
  59716. orient: 'horizontal',
  59717. left: 'center',
  59718. // right: 'center',
  59719. top: 0,
  59720. // bottom: null,
  59721. // 水平对齐
  59722. // 'auto' | 'left' | 'right'
  59723. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  59724. align: 'auto',
  59725. backgroundColor: 'rgba(0,0,0,0)',
  59726. // 图例边框颜色
  59727. borderColor: '#ccc',
  59728. borderRadius: 0,
  59729. // 图例边框线宽,单位px,默认为0(无边框)
  59730. borderWidth: 0,
  59731. // 图例内边距,单位px,默认各方向内边距为5,
  59732. // 接受数组分别设定上右下左边距,同css
  59733. padding: 5,
  59734. // 各个item之间的间隔,单位px,默认为10,
  59735. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  59736. itemGap: 10,
  59737. // 图例图形宽度
  59738. itemWidth: 25,
  59739. // 图例图形高度
  59740. itemHeight: 14,
  59741. // 图例关闭时候的颜色
  59742. inactiveColor: '#ccc',
  59743. textStyle: {
  59744. // 图例文字颜色
  59745. color: '#333'
  59746. },
  59747. // formatter: '',
  59748. // 选择模式,默认开启图例开关
  59749. selectedMode: true,
  59750. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  59751. // selected: null,
  59752. // 图例内容(详见legend.data,数组中每一项代表一个item
  59753. // data: [],
  59754. // Tooltip 相关配置
  59755. tooltip: {
  59756. show: false
  59757. }
  59758. }
  59759. });
  59760. /*
  59761. * Licensed to the Apache Software Foundation (ASF) under one
  59762. * or more contributor license agreements. See the NOTICE file
  59763. * distributed with this work for additional information
  59764. * regarding copyright ownership. The ASF licenses this file
  59765. * to you under the Apache License, Version 2.0 (the
  59766. * "License"); you may not use this file except in compliance
  59767. * with the License. You may obtain a copy of the License at
  59768. *
  59769. * http://www.apache.org/licenses/LICENSE-2.0
  59770. *
  59771. * Unless required by applicable law or agreed to in writing,
  59772. * software distributed under the License is distributed on an
  59773. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59774. * KIND, either express or implied. See the License for the
  59775. * specific language governing permissions and limitations
  59776. * under the License.
  59777. */
  59778. function legendSelectActionHandler(methodName, payload, ecModel) {
  59779. var selectedMap = {};
  59780. var isToggleSelect = methodName === 'toggleSelected';
  59781. var isSelected;
  59782. // Update all legend components
  59783. ecModel.eachComponent('legend', function (legendModel) {
  59784. if (isToggleSelect && isSelected != null) {
  59785. // Force other legend has same selected status
  59786. // Or the first is toggled to true and other are toggled to false
  59787. // In the case one legend has some item unSelected in option. And if other legend
  59788. // doesn't has the item, they will assume it is selected.
  59789. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  59790. }
  59791. else {
  59792. legendModel[methodName](payload.name);
  59793. isSelected = legendModel.isSelected(payload.name);
  59794. }
  59795. var legendData = legendModel.getData();
  59796. each$1(legendData, function (model) {
  59797. var name = model.get('name');
  59798. // Wrap element
  59799. if (name === '\n' || name === '') {
  59800. return;
  59801. }
  59802. var isItemSelected = legendModel.isSelected(name);
  59803. if (selectedMap.hasOwnProperty(name)) {
  59804. // Unselected if any legend is unselected
  59805. selectedMap[name] = selectedMap[name] && isItemSelected;
  59806. }
  59807. else {
  59808. selectedMap[name] = isItemSelected;
  59809. }
  59810. });
  59811. });
  59812. // Return the event explicitly
  59813. return {
  59814. name: payload.name,
  59815. selected: selectedMap
  59816. };
  59817. }
  59818. /**
  59819. * @event legendToggleSelect
  59820. * @type {Object}
  59821. * @property {string} type 'legendToggleSelect'
  59822. * @property {string} [from]
  59823. * @property {string} name Series name or data item name
  59824. */
  59825. registerAction(
  59826. 'legendToggleSelect', 'legendselectchanged',
  59827. curry(legendSelectActionHandler, 'toggleSelected')
  59828. );
  59829. /**
  59830. * @event legendSelect
  59831. * @type {Object}
  59832. * @property {string} type 'legendSelect'
  59833. * @property {string} name Series name or data item name
  59834. */
  59835. registerAction(
  59836. 'legendSelect', 'legendselected',
  59837. curry(legendSelectActionHandler, 'select')
  59838. );
  59839. /**
  59840. * @event legendUnSelect
  59841. * @type {Object}
  59842. * @property {string} type 'legendUnSelect'
  59843. * @property {string} name Series name or data item name
  59844. */
  59845. registerAction(
  59846. 'legendUnSelect', 'legendunselected',
  59847. curry(legendSelectActionHandler, 'unSelect')
  59848. );
  59849. /*
  59850. * Licensed to the Apache Software Foundation (ASF) under one
  59851. * or more contributor license agreements. See the NOTICE file
  59852. * distributed with this work for additional information
  59853. * regarding copyright ownership. The ASF licenses this file
  59854. * to you under the Apache License, Version 2.0 (the
  59855. * "License"); you may not use this file except in compliance
  59856. * with the License. You may obtain a copy of the License at
  59857. *
  59858. * http://www.apache.org/licenses/LICENSE-2.0
  59859. *
  59860. * Unless required by applicable law or agreed to in writing,
  59861. * software distributed under the License is distributed on an
  59862. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59863. * KIND, either express or implied. See the License for the
  59864. * specific language governing permissions and limitations
  59865. * under the License.
  59866. */
  59867. /**
  59868. * Layout list like component.
  59869. * It will box layout each items in group of component and then position the whole group in the viewport
  59870. * @param {module:zrender/group/Group} group
  59871. * @param {module:echarts/model/Component} componentModel
  59872. * @param {module:echarts/ExtensionAPI}
  59873. */
  59874. function layout$3(group, componentModel, api) {
  59875. var boxLayoutParams = componentModel.getBoxLayoutParams();
  59876. var padding = componentModel.get('padding');
  59877. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  59878. var rect = getLayoutRect(
  59879. boxLayoutParams,
  59880. viewportSize,
  59881. padding
  59882. );
  59883. box(
  59884. componentModel.get('orient'),
  59885. group,
  59886. componentModel.get('itemGap'),
  59887. rect.width,
  59888. rect.height
  59889. );
  59890. positionElement(
  59891. group,
  59892. boxLayoutParams,
  59893. viewportSize,
  59894. padding
  59895. );
  59896. }
  59897. function makeBackground(rect, componentModel) {
  59898. var padding = normalizeCssArray$1(
  59899. componentModel.get('padding')
  59900. );
  59901. var style = componentModel.getItemStyle(['color', 'opacity']);
  59902. style.fill = componentModel.get('backgroundColor');
  59903. var rect = new Rect({
  59904. shape: {
  59905. x: rect.x - padding[3],
  59906. y: rect.y - padding[0],
  59907. width: rect.width + padding[1] + padding[3],
  59908. height: rect.height + padding[0] + padding[2],
  59909. r: componentModel.get('borderRadius')
  59910. },
  59911. style: style,
  59912. silent: true,
  59913. z2: -1
  59914. });
  59915. // FIXME
  59916. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  59917. // and background rect when setting like `left: 0`, `top: 0`.
  59918. // graphic.subPixelOptimizeRect(rect);
  59919. return rect;
  59920. }
  59921. /*
  59922. * Licensed to the Apache Software Foundation (ASF) under one
  59923. * or more contributor license agreements. See the NOTICE file
  59924. * distributed with this work for additional information
  59925. * regarding copyright ownership. The ASF licenses this file
  59926. * to you under the Apache License, Version 2.0 (the
  59927. * "License"); you may not use this file except in compliance
  59928. * with the License. You may obtain a copy of the License at
  59929. *
  59930. * http://www.apache.org/licenses/LICENSE-2.0
  59931. *
  59932. * Unless required by applicable law or agreed to in writing,
  59933. * software distributed under the License is distributed on an
  59934. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59935. * KIND, either express or implied. See the License for the
  59936. * specific language governing permissions and limitations
  59937. * under the License.
  59938. */
  59939. var curry$4 = curry;
  59940. var each$16 = each$1;
  59941. var Group$3 = Group;
  59942. var LegendView = extendComponentView({
  59943. type: 'legend.plain',
  59944. newlineDisabled: false,
  59945. /**
  59946. * @override
  59947. */
  59948. init: function () {
  59949. /**
  59950. * @private
  59951. * @type {module:zrender/container/Group}
  59952. */
  59953. this.group.add(this._contentGroup = new Group$3());
  59954. /**
  59955. * @private
  59956. * @type {module:zrender/Element}
  59957. */
  59958. this._backgroundEl;
  59959. },
  59960. /**
  59961. * @protected
  59962. */
  59963. getContentGroup: function () {
  59964. return this._contentGroup;
  59965. },
  59966. /**
  59967. * @override
  59968. */
  59969. render: function (legendModel, ecModel, api) {
  59970. this.resetInner();
  59971. if (!legendModel.get('show', true)) {
  59972. return;
  59973. }
  59974. var itemAlign = legendModel.get('align');
  59975. if (!itemAlign || itemAlign === 'auto') {
  59976. itemAlign = (
  59977. legendModel.get('left') === 'right'
  59978. && legendModel.get('orient') === 'vertical'
  59979. ) ? 'right' : 'left';
  59980. }
  59981. this.renderInner(itemAlign, legendModel, ecModel, api);
  59982. // Perform layout.
  59983. var positionInfo = legendModel.getBoxLayoutParams();
  59984. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  59985. var padding = legendModel.get('padding');
  59986. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  59987. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  59988. // Place mainGroup, based on the calculated `mainRect`.
  59989. var layoutRect = getLayoutRect(
  59990. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  59991. viewportSize,
  59992. padding
  59993. );
  59994. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  59995. // Render background after group is layout.
  59996. this.group.add(
  59997. this._backgroundEl = makeBackground(mainRect, legendModel)
  59998. );
  59999. },
  60000. /**
  60001. * @protected
  60002. */
  60003. resetInner: function () {
  60004. this.getContentGroup().removeAll();
  60005. this._backgroundEl && this.group.remove(this._backgroundEl);
  60006. },
  60007. /**
  60008. * @protected
  60009. */
  60010. renderInner: function (itemAlign, legendModel, ecModel, api) {
  60011. var contentGroup = this.getContentGroup();
  60012. var legendDrawnMap = createHashMap();
  60013. var selectMode = legendModel.get('selectedMode');
  60014. var excludeSeriesId = [];
  60015. ecModel.eachRawSeries(function (seriesModel) {
  60016. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  60017. });
  60018. each$16(legendModel.getData(), function (itemModel, dataIndex) {
  60019. var name = itemModel.get('name');
  60020. // Use empty string or \n as a newline string
  60021. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  60022. contentGroup.add(new Group$3({
  60023. newline: true
  60024. }));
  60025. return;
  60026. }
  60027. // Representitive series.
  60028. var seriesModel = ecModel.getSeriesByName(name)[0];
  60029. if (legendDrawnMap.get(name)) {
  60030. // Have been drawed
  60031. return;
  60032. }
  60033. // Series legend
  60034. if (seriesModel) {
  60035. var data = seriesModel.getData();
  60036. var color = data.getVisual('color');
  60037. // If color is a callback function
  60038. if (typeof color === 'function') {
  60039. // Use the first data
  60040. color = color(seriesModel.getDataParams(0));
  60041. }
  60042. // Using rect symbol defaultly
  60043. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  60044. var symbolType = data.getVisual('symbol');
  60045. var itemGroup = this._createItem(
  60046. name, dataIndex, itemModel, legendModel,
  60047. legendSymbolType, symbolType,
  60048. itemAlign, color,
  60049. selectMode
  60050. );
  60051. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  60052. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, null, api, excludeSeriesId))
  60053. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, null, api, excludeSeriesId));
  60054. legendDrawnMap.set(name, true);
  60055. }
  60056. else {
  60057. // Data legend of pie, funnel
  60058. ecModel.eachRawSeries(function (seriesModel) {
  60059. // In case multiple series has same data name
  60060. if (legendDrawnMap.get(name)) {
  60061. return;
  60062. }
  60063. if (seriesModel.legendDataProvider) {
  60064. var data = seriesModel.legendDataProvider();
  60065. var idx = data.indexOfName(name);
  60066. if (idx < 0) {
  60067. return;
  60068. }
  60069. var color = data.getItemVisual(idx, 'color');
  60070. var legendSymbolType = 'roundRect';
  60071. var itemGroup = this._createItem(
  60072. name, dataIndex, itemModel, legendModel,
  60073. legendSymbolType, null,
  60074. itemAlign, color,
  60075. selectMode
  60076. );
  60077. // FIXME: consider different series has items with the same name.
  60078. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  60079. // FIXME Should not specify the series name
  60080. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, name, api, excludeSeriesId))
  60081. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, name, api, excludeSeriesId));
  60082. legendDrawnMap.set(name, true);
  60083. }
  60084. }, this);
  60085. }
  60086. if (__DEV__) {
  60087. if (!legendDrawnMap.get(name)) {
  60088. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  60089. }
  60090. }
  60091. }, this);
  60092. },
  60093. _createItem: function (
  60094. name, dataIndex, itemModel, legendModel,
  60095. legendSymbolType, symbolType,
  60096. itemAlign, color, selectMode
  60097. ) {
  60098. var itemWidth = legendModel.get('itemWidth');
  60099. var itemHeight = legendModel.get('itemHeight');
  60100. var inactiveColor = legendModel.get('inactiveColor');
  60101. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  60102. var isSelected = legendModel.isSelected(name);
  60103. var itemGroup = new Group$3();
  60104. var textStyleModel = itemModel.getModel('textStyle');
  60105. var itemIcon = itemModel.get('icon');
  60106. var tooltipModel = itemModel.getModel('tooltip');
  60107. var legendGlobalTooltipModel = tooltipModel.parentModel;
  60108. // Use user given icon first
  60109. legendSymbolType = itemIcon || legendSymbolType;
  60110. itemGroup.add(createSymbol(
  60111. legendSymbolType,
  60112. 0,
  60113. 0,
  60114. itemWidth,
  60115. itemHeight,
  60116. isSelected ? color : inactiveColor,
  60117. // symbolKeepAspect default true for legend
  60118. symbolKeepAspect == null ? true : symbolKeepAspect
  60119. ));
  60120. // Compose symbols
  60121. // PENDING
  60122. if (!itemIcon && symbolType
  60123. // At least show one symbol, can't be all none
  60124. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  60125. ) {
  60126. var size = itemHeight * 0.8;
  60127. if (symbolType === 'none') {
  60128. symbolType = 'circle';
  60129. }
  60130. // Put symbol in the center
  60131. itemGroup.add(createSymbol(
  60132. symbolType,
  60133. (itemWidth - size) / 2,
  60134. (itemHeight - size) / 2,
  60135. size,
  60136. size,
  60137. isSelected ? color : inactiveColor,
  60138. // symbolKeepAspect default true for legend
  60139. symbolKeepAspect == null ? true : symbolKeepAspect
  60140. ));
  60141. }
  60142. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  60143. var textAlign = itemAlign;
  60144. var formatter = legendModel.get('formatter');
  60145. var content = name;
  60146. if (typeof formatter === 'string' && formatter) {
  60147. content = formatter.replace('{name}', name != null ? name : '');
  60148. }
  60149. else if (typeof formatter === 'function') {
  60150. content = formatter(name);
  60151. }
  60152. itemGroup.add(new Text({
  60153. style: setTextStyle({}, textStyleModel, {
  60154. text: content,
  60155. x: textX,
  60156. y: itemHeight / 2,
  60157. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  60158. textAlign: textAlign,
  60159. textVerticalAlign: 'middle'
  60160. })
  60161. }));
  60162. // Add a invisible rect to increase the area of mouse hover
  60163. var hitRect = new Rect({
  60164. shape: itemGroup.getBoundingRect(),
  60165. invisible: true,
  60166. tooltip: tooltipModel.get('show') ? extend({
  60167. content: name,
  60168. // Defaul formatter
  60169. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  60170. return name;
  60171. },
  60172. formatterParams: {
  60173. componentType: 'legend',
  60174. legendIndex: legendModel.componentIndex,
  60175. name: name,
  60176. $vars: ['name']
  60177. }
  60178. }, tooltipModel.option) : null
  60179. });
  60180. itemGroup.add(hitRect);
  60181. itemGroup.eachChild(function (child) {
  60182. child.silent = true;
  60183. });
  60184. hitRect.silent = !selectMode;
  60185. this.getContentGroup().add(itemGroup);
  60186. setHoverStyle(itemGroup);
  60187. itemGroup.__legendDataIndex = dataIndex;
  60188. return itemGroup;
  60189. },
  60190. /**
  60191. * @protected
  60192. */
  60193. layoutInner: function (legendModel, itemAlign, maxSize) {
  60194. var contentGroup = this.getContentGroup();
  60195. // Place items in contentGroup.
  60196. box(
  60197. legendModel.get('orient'),
  60198. contentGroup,
  60199. legendModel.get('itemGap'),
  60200. maxSize.width,
  60201. maxSize.height
  60202. );
  60203. var contentRect = contentGroup.getBoundingRect();
  60204. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  60205. return this.group.getBoundingRect();
  60206. }
  60207. });
  60208. function dispatchSelectAction(name, api) {
  60209. api.dispatchAction({
  60210. type: 'legendToggleSelect',
  60211. name: name
  60212. });
  60213. }
  60214. function dispatchHighlightAction(seriesModel, dataName, api, excludeSeriesId) {
  60215. // If element hover will move to a hoverLayer.
  60216. var el = api.getZr().storage.getDisplayList()[0];
  60217. if (!(el && el.useHoverLayer)) {
  60218. api.dispatchAction({
  60219. type: 'highlight',
  60220. seriesName: seriesModel.name,
  60221. name: dataName,
  60222. excludeSeriesId: excludeSeriesId
  60223. });
  60224. }
  60225. }
  60226. function dispatchDownplayAction(seriesModel, dataName, api, excludeSeriesId) {
  60227. // If element hover will move to a hoverLayer.
  60228. var el = api.getZr().storage.getDisplayList()[0];
  60229. if (!(el && el.useHoverLayer)) {
  60230. api.dispatchAction({
  60231. type: 'downplay',
  60232. seriesName: seriesModel.name,
  60233. name: dataName,
  60234. excludeSeriesId: excludeSeriesId
  60235. });
  60236. }
  60237. }
  60238. /*
  60239. * Licensed to the Apache Software Foundation (ASF) under one
  60240. * or more contributor license agreements. See the NOTICE file
  60241. * distributed with this work for additional information
  60242. * regarding copyright ownership. The ASF licenses this file
  60243. * to you under the Apache License, Version 2.0 (the
  60244. * "License"); you may not use this file except in compliance
  60245. * with the License. You may obtain a copy of the License at
  60246. *
  60247. * http://www.apache.org/licenses/LICENSE-2.0
  60248. *
  60249. * Unless required by applicable law or agreed to in writing,
  60250. * software distributed under the License is distributed on an
  60251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60252. * KIND, either express or implied. See the License for the
  60253. * specific language governing permissions and limitations
  60254. * under the License.
  60255. */
  60256. var legendFilter = function (ecModel) {
  60257. var legendModels = ecModel.findComponents({
  60258. mainType: 'legend'
  60259. });
  60260. if (legendModels && legendModels.length) {
  60261. ecModel.filterSeries(function (series) {
  60262. // If in any legend component the status is not selected.
  60263. // Because in legend series is assumed selected when it is not in the legend data.
  60264. for (var i = 0; i < legendModels.length; i++) {
  60265. if (!legendModels[i].isSelected(series.name)) {
  60266. return false;
  60267. }
  60268. }
  60269. return true;
  60270. });
  60271. }
  60272. };
  60273. /*
  60274. * Licensed to the Apache Software Foundation (ASF) under one
  60275. * or more contributor license agreements. See the NOTICE file
  60276. * distributed with this work for additional information
  60277. * regarding copyright ownership. The ASF licenses this file
  60278. * to you under the Apache License, Version 2.0 (the
  60279. * "License"); you may not use this file except in compliance
  60280. * with the License. You may obtain a copy of the License at
  60281. *
  60282. * http://www.apache.org/licenses/LICENSE-2.0
  60283. *
  60284. * Unless required by applicable law or agreed to in writing,
  60285. * software distributed under the License is distributed on an
  60286. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60287. * KIND, either express or implied. See the License for the
  60288. * specific language governing permissions and limitations
  60289. * under the License.
  60290. */
  60291. // Do not contain scrollable legend, for sake of file size.
  60292. // Series Filter
  60293. registerProcessor(legendFilter);
  60294. ComponentModel.registerSubTypeDefaulter('legend', function () {
  60295. // Default 'plain' when no type specified.
  60296. return 'plain';
  60297. });
  60298. /*
  60299. * Licensed to the Apache Software Foundation (ASF) under one
  60300. * or more contributor license agreements. See the NOTICE file
  60301. * distributed with this work for additional information
  60302. * regarding copyright ownership. The ASF licenses this file
  60303. * to you under the Apache License, Version 2.0 (the
  60304. * "License"); you may not use this file except in compliance
  60305. * with the License. You may obtain a copy of the License at
  60306. *
  60307. * http://www.apache.org/licenses/LICENSE-2.0
  60308. *
  60309. * Unless required by applicable law or agreed to in writing,
  60310. * software distributed under the License is distributed on an
  60311. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60312. * KIND, either express or implied. See the License for the
  60313. * specific language governing permissions and limitations
  60314. * under the License.
  60315. */
  60316. var ScrollableLegendModel = LegendModel.extend({
  60317. type: 'legend.scroll',
  60318. /**
  60319. * @param {number} scrollDataIndex
  60320. */
  60321. setScrollDataIndex: function (scrollDataIndex) {
  60322. this.option.scrollDataIndex = scrollDataIndex;
  60323. },
  60324. defaultOption: {
  60325. scrollDataIndex: 0,
  60326. pageButtonItemGap: 5,
  60327. pageButtonGap: null,
  60328. pageButtonPosition: 'end', // 'start' or 'end'
  60329. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  60330. pageIcons: {
  60331. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  60332. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  60333. },
  60334. pageIconColor: '#2f4554',
  60335. pageIconInactiveColor: '#aaa',
  60336. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  60337. pageTextStyle: {
  60338. color: '#333'
  60339. },
  60340. animationDurationUpdate: 800
  60341. },
  60342. /**
  60343. * @override
  60344. */
  60345. init: function (option, parentModel, ecModel, extraOpt) {
  60346. var inputPositionParams = getLayoutParams(option);
  60347. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  60348. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  60349. },
  60350. /**
  60351. * @override
  60352. */
  60353. mergeOption: function (option, extraOpt) {
  60354. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  60355. mergeAndNormalizeLayoutParams(this, this.option, option);
  60356. },
  60357. getOrient: function () {
  60358. return this.get('orient') === 'vertical'
  60359. ? {index: 1, name: 'vertical'}
  60360. : {index: 0, name: 'horizontal'};
  60361. }
  60362. });
  60363. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  60364. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  60365. var orient = legendModel.getOrient();
  60366. var ignoreSize = [1, 1];
  60367. ignoreSize[orient.index] = 0;
  60368. mergeLayoutParam(target, raw, {
  60369. type: 'box', ignoreSize: ignoreSize
  60370. });
  60371. }
  60372. /*
  60373. * Licensed to the Apache Software Foundation (ASF) under one
  60374. * or more contributor license agreements. See the NOTICE file
  60375. * distributed with this work for additional information
  60376. * regarding copyright ownership. The ASF licenses this file
  60377. * to you under the Apache License, Version 2.0 (the
  60378. * "License"); you may not use this file except in compliance
  60379. * with the License. You may obtain a copy of the License at
  60380. *
  60381. * http://www.apache.org/licenses/LICENSE-2.0
  60382. *
  60383. * Unless required by applicable law or agreed to in writing,
  60384. * software distributed under the License is distributed on an
  60385. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60386. * KIND, either express or implied. See the License for the
  60387. * specific language governing permissions and limitations
  60388. * under the License.
  60389. */
  60390. /**
  60391. * Separate legend and scrollable legend to reduce package size.
  60392. */
  60393. var Group$4 = Group;
  60394. var WH$1 = ['width', 'height'];
  60395. var XY$1 = ['x', 'y'];
  60396. var ScrollableLegendView = LegendView.extend({
  60397. type: 'legend.scroll',
  60398. newlineDisabled: true,
  60399. init: function () {
  60400. ScrollableLegendView.superCall(this, 'init');
  60401. /**
  60402. * @private
  60403. * @type {number} For `scroll`.
  60404. */
  60405. this._currentIndex = 0;
  60406. /**
  60407. * @private
  60408. * @type {module:zrender/container/Group}
  60409. */
  60410. this.group.add(this._containerGroup = new Group$4());
  60411. this._containerGroup.add(this.getContentGroup());
  60412. /**
  60413. * @private
  60414. * @type {module:zrender/container/Group}
  60415. */
  60416. this.group.add(this._controllerGroup = new Group$4());
  60417. /**
  60418. *
  60419. * @private
  60420. */
  60421. this._showController;
  60422. },
  60423. /**
  60424. * @override
  60425. */
  60426. resetInner: function () {
  60427. ScrollableLegendView.superCall(this, 'resetInner');
  60428. this._controllerGroup.removeAll();
  60429. this._containerGroup.removeClipPath();
  60430. this._containerGroup.__rectSize = null;
  60431. },
  60432. /**
  60433. * @override
  60434. */
  60435. renderInner: function (itemAlign, legendModel, ecModel, api) {
  60436. var me = this;
  60437. // Render content items.
  60438. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  60439. var controllerGroup = this._controllerGroup;
  60440. var pageIconSize = legendModel.get('pageIconSize', true);
  60441. if (!isArray(pageIconSize)) {
  60442. pageIconSize = [pageIconSize, pageIconSize];
  60443. }
  60444. createPageButton('pagePrev', 0);
  60445. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  60446. controllerGroup.add(new Text({
  60447. name: 'pageText',
  60448. style: {
  60449. textFill: pageTextStyleModel.getTextColor(),
  60450. font: pageTextStyleModel.getFont(),
  60451. textVerticalAlign: 'middle',
  60452. textAlign: 'center'
  60453. },
  60454. silent: true
  60455. }));
  60456. createPageButton('pageNext', 1);
  60457. function createPageButton(name, iconIdx) {
  60458. var pageDataIndexName = name + 'DataIndex';
  60459. var icon = createIcon(
  60460. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  60461. {
  60462. // Buttons will be created in each render, so we do not need
  60463. // to worry about avoiding using legendModel kept in scope.
  60464. onclick: bind(
  60465. me._pageGo, me, pageDataIndexName, legendModel, api
  60466. )
  60467. },
  60468. {
  60469. x: -pageIconSize[0] / 2,
  60470. y: -pageIconSize[1] / 2,
  60471. width: pageIconSize[0],
  60472. height: pageIconSize[1]
  60473. }
  60474. );
  60475. icon.name = name;
  60476. controllerGroup.add(icon);
  60477. }
  60478. },
  60479. /**
  60480. * @override
  60481. */
  60482. layoutInner: function (legendModel, itemAlign, maxSize) {
  60483. var contentGroup = this.getContentGroup();
  60484. var containerGroup = this._containerGroup;
  60485. var controllerGroup = this._controllerGroup;
  60486. var orientIdx = legendModel.getOrient().index;
  60487. var wh = WH$1[orientIdx];
  60488. var hw = WH$1[1 - orientIdx];
  60489. var yx = XY$1[1 - orientIdx];
  60490. // Place items in contentGroup.
  60491. box(
  60492. legendModel.get('orient'),
  60493. contentGroup,
  60494. legendModel.get('itemGap'),
  60495. !orientIdx ? null : maxSize.width,
  60496. orientIdx ? null : maxSize.height
  60497. );
  60498. box(
  60499. // Buttons in controller are layout always horizontally.
  60500. 'horizontal',
  60501. controllerGroup,
  60502. legendModel.get('pageButtonItemGap', true)
  60503. );
  60504. var contentRect = contentGroup.getBoundingRect();
  60505. var controllerRect = controllerGroup.getBoundingRect();
  60506. var showController = this._showController = contentRect[wh] > maxSize[wh];
  60507. var contentPos = [-contentRect.x, -contentRect.y];
  60508. // Remain contentPos when scroll animation perfroming.
  60509. contentPos[orientIdx] = contentGroup.position[orientIdx];
  60510. // Layout container group based on 0.
  60511. var containerPos = [0, 0];
  60512. var controllerPos = [-controllerRect.x, -controllerRect.y];
  60513. var pageButtonGap = retrieve2(
  60514. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  60515. );
  60516. // Place containerGroup and controllerGroup and contentGroup.
  60517. if (showController) {
  60518. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  60519. // controller is on the right / bottom.
  60520. if (pageButtonPosition === 'end') {
  60521. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  60522. }
  60523. // controller is on the left / top.
  60524. else {
  60525. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  60526. }
  60527. }
  60528. // Always align controller to content as 'middle'.
  60529. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  60530. contentGroup.attr('position', contentPos);
  60531. containerGroup.attr('position', containerPos);
  60532. controllerGroup.attr('position', controllerPos);
  60533. // Calculate `mainRect` and set `clipPath`.
  60534. // mainRect should not be calculated by `this.group.getBoundingRect()`
  60535. // for sake of the overflow.
  60536. var mainRect = this.group.getBoundingRect();
  60537. var mainRect = {x: 0, y: 0};
  60538. // Consider content may be overflow (should be clipped).
  60539. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  60540. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  60541. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  60542. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  60543. containerGroup.__rectSize = maxSize[wh];
  60544. if (showController) {
  60545. var clipShape = {x: 0, y: 0};
  60546. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  60547. clipShape[hw] = mainRect[hw];
  60548. containerGroup.setClipPath(new Rect({shape: clipShape}));
  60549. // Consider content may be larger than container, container rect
  60550. // can not be obtained from `containerGroup.getBoundingRect()`.
  60551. containerGroup.__rectSize = clipShape[wh];
  60552. }
  60553. else {
  60554. // Do not remove or ignore controller. Keep them set as place holders.
  60555. controllerGroup.eachChild(function (child) {
  60556. child.attr({invisible: true, silent: true});
  60557. });
  60558. }
  60559. // Content translate animation.
  60560. var pageInfo = this._getPageInfo(legendModel);
  60561. pageInfo.pageIndex != null && updateProps(
  60562. contentGroup,
  60563. {position: pageInfo.contentPosition},
  60564. // When switch from "show controller" to "not show controller", view should be
  60565. // updated immediately without animation, otherwise causes weird efffect.
  60566. showController ? legendModel : false
  60567. );
  60568. this._updatePageInfoView(legendModel, pageInfo);
  60569. return mainRect;
  60570. },
  60571. _pageGo: function (to, legendModel, api) {
  60572. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  60573. scrollDataIndex != null && api.dispatchAction({
  60574. type: 'legendScroll',
  60575. scrollDataIndex: scrollDataIndex,
  60576. legendId: legendModel.id
  60577. });
  60578. },
  60579. _updatePageInfoView: function (legendModel, pageInfo) {
  60580. var controllerGroup = this._controllerGroup;
  60581. each$1(['pagePrev', 'pageNext'], function (name) {
  60582. var canJump = pageInfo[name + 'DataIndex'] != null;
  60583. var icon = controllerGroup.childOfName(name);
  60584. if (icon) {
  60585. icon.setStyle(
  60586. 'fill',
  60587. canJump
  60588. ? legendModel.get('pageIconColor', true)
  60589. : legendModel.get('pageIconInactiveColor', true)
  60590. );
  60591. icon.cursor = canJump ? 'pointer' : 'default';
  60592. }
  60593. });
  60594. var pageText = controllerGroup.childOfName('pageText');
  60595. var pageFormatter = legendModel.get('pageFormatter');
  60596. var pageIndex = pageInfo.pageIndex;
  60597. var current = pageIndex != null ? pageIndex + 1 : 0;
  60598. var total = pageInfo.pageCount;
  60599. pageText && pageFormatter && pageText.setStyle(
  60600. 'text',
  60601. isString(pageFormatter)
  60602. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  60603. : pageFormatter({current: current, total: total})
  60604. );
  60605. },
  60606. /**
  60607. * @param {module:echarts/model/Model} legendModel
  60608. * @return {Object} {
  60609. * contentPosition: Array.<number>, null when data item not found.
  60610. * pageIndex: number, null when data item not found.
  60611. * pageCount: number, always be a number, can be 0.
  60612. * pagePrevDataIndex: number, null when no next page.
  60613. * pageNextDataIndex: number, null when no previous page.
  60614. * }
  60615. */
  60616. _getPageInfo: function (legendModel) {
  60617. // Align left or top by the current dataIndex.
  60618. var currDataIndex = legendModel.get('scrollDataIndex', true);
  60619. var contentGroup = this.getContentGroup();
  60620. var contentRect = contentGroup.getBoundingRect();
  60621. var containerRectSize = this._containerGroup.__rectSize;
  60622. var orientIdx = legendModel.getOrient().index;
  60623. var wh = WH$1[orientIdx];
  60624. var hw = WH$1[1 - orientIdx];
  60625. var xy = XY$1[orientIdx];
  60626. var contentPos = contentGroup.position.slice();
  60627. var pageIndex;
  60628. var pagePrevDataIndex;
  60629. var pageNextDataIndex;
  60630. var targetItemGroup;
  60631. if (this._showController) {
  60632. contentGroup.eachChild(function (child) {
  60633. if (child.__legendDataIndex === currDataIndex) {
  60634. targetItemGroup = child;
  60635. }
  60636. });
  60637. }
  60638. else {
  60639. targetItemGroup = contentGroup.childAt(0);
  60640. }
  60641. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  60642. if (targetItemGroup) {
  60643. var itemRect = targetItemGroup.getBoundingRect();
  60644. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  60645. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  60646. pageIndex = Math.floor(
  60647. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  60648. );
  60649. pageIndex = (contentRect[wh] && pageCount)
  60650. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  60651. : -1;
  60652. var winRect = {x: 0, y: 0};
  60653. winRect[wh] = containerRectSize;
  60654. winRect[hw] = contentRect[hw];
  60655. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  60656. var startIdx;
  60657. var children = contentGroup.children();
  60658. contentGroup.eachChild(function (child, index) {
  60659. var itemRect = getItemRect(child);
  60660. if (itemRect.intersect(winRect)) {
  60661. startIdx == null && (startIdx = index);
  60662. // It is user-friendly that the last item shown in the
  60663. // current window is shown at the begining of next window.
  60664. pageNextDataIndex = child.__legendDataIndex;
  60665. }
  60666. // If the last item is shown entirely, no next page.
  60667. if (index === children.length - 1
  60668. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  60669. ) {
  60670. pageNextDataIndex = null;
  60671. }
  60672. });
  60673. // Always align based on the left/top most item, so the left/top most
  60674. // item in the previous window is needed to be found here.
  60675. if (startIdx != null) {
  60676. var startItem = children[startIdx];
  60677. var startRect = getItemRect(startItem);
  60678. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  60679. // If the first item is shown entirely, no previous page.
  60680. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  60681. pagePrevDataIndex = null;
  60682. }
  60683. else {
  60684. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  60685. startIdx--;
  60686. }
  60687. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  60688. }
  60689. }
  60690. }
  60691. return {
  60692. contentPosition: contentPos,
  60693. pageIndex: pageIndex,
  60694. pageCount: pageCount,
  60695. pagePrevDataIndex: pagePrevDataIndex,
  60696. pageNextDataIndex: pageNextDataIndex
  60697. };
  60698. function getItemRect(el) {
  60699. var itemRect = el.getBoundingRect().clone();
  60700. itemRect[xy] += el.position[orientIdx];
  60701. return itemRect;
  60702. }
  60703. }
  60704. });
  60705. /*
  60706. * Licensed to the Apache Software Foundation (ASF) under one
  60707. * or more contributor license agreements. See the NOTICE file
  60708. * distributed with this work for additional information
  60709. * regarding copyright ownership. The ASF licenses this file
  60710. * to you under the Apache License, Version 2.0 (the
  60711. * "License"); you may not use this file except in compliance
  60712. * with the License. You may obtain a copy of the License at
  60713. *
  60714. * http://www.apache.org/licenses/LICENSE-2.0
  60715. *
  60716. * Unless required by applicable law or agreed to in writing,
  60717. * software distributed under the License is distributed on an
  60718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60719. * KIND, either express or implied. See the License for the
  60720. * specific language governing permissions and limitations
  60721. * under the License.
  60722. */
  60723. /**
  60724. * @event legendScroll
  60725. * @type {Object}
  60726. * @property {string} type 'legendScroll'
  60727. * @property {string} scrollDataIndex
  60728. */
  60729. registerAction(
  60730. 'legendScroll', 'legendscroll',
  60731. function (payload, ecModel) {
  60732. var scrollDataIndex = payload.scrollDataIndex;
  60733. scrollDataIndex != null && ecModel.eachComponent(
  60734. {mainType: 'legend', subType: 'scroll', query: payload},
  60735. function (legendModel) {
  60736. legendModel.setScrollDataIndex(scrollDataIndex);
  60737. }
  60738. );
  60739. }
  60740. );
  60741. /*
  60742. * Licensed to the Apache Software Foundation (ASF) under one
  60743. * or more contributor license agreements. See the NOTICE file
  60744. * distributed with this work for additional information
  60745. * regarding copyright ownership. The ASF licenses this file
  60746. * to you under the Apache License, Version 2.0 (the
  60747. * "License"); you may not use this file except in compliance
  60748. * with the License. You may obtain a copy of the License at
  60749. *
  60750. * http://www.apache.org/licenses/LICENSE-2.0
  60751. *
  60752. * Unless required by applicable law or agreed to in writing,
  60753. * software distributed under the License is distributed on an
  60754. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60755. * KIND, either express or implied. See the License for the
  60756. * specific language governing permissions and limitations
  60757. * under the License.
  60758. */
  60759. /**
  60760. * Legend component entry file8
  60761. */
  60762. /*
  60763. * Licensed to the Apache Software Foundation (ASF) under one
  60764. * or more contributor license agreements. See the NOTICE file
  60765. * distributed with this work for additional information
  60766. * regarding copyright ownership. The ASF licenses this file
  60767. * to you under the Apache License, Version 2.0 (the
  60768. * "License"); you may not use this file except in compliance
  60769. * with the License. You may obtain a copy of the License at
  60770. *
  60771. * http://www.apache.org/licenses/LICENSE-2.0
  60772. *
  60773. * Unless required by applicable law or agreed to in writing,
  60774. * software distributed under the License is distributed on an
  60775. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60776. * KIND, either express or implied. See the License for the
  60777. * specific language governing permissions and limitations
  60778. * under the License.
  60779. */
  60780. extendComponentModel({
  60781. type: 'tooltip',
  60782. dependencies: ['axisPointer'],
  60783. defaultOption: {
  60784. zlevel: 0,
  60785. z: 8,
  60786. show: true,
  60787. // tooltip主体内容
  60788. showContent: true,
  60789. // 'trigger' only works on coordinate system.
  60790. // 'item' | 'axis' | 'none'
  60791. trigger: 'item',
  60792. // 'click' | 'mousemove' | 'none'
  60793. triggerOn: 'mousemove|click',
  60794. alwaysShowContent: false,
  60795. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  60796. // 位置 {Array} | {Function}
  60797. // position: null
  60798. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  60799. // align: null,
  60800. // verticalAlign: null,
  60801. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  60802. confine: false,
  60803. // 内容格式器:{string}(Template) ¦ {Function}
  60804. // formatter: null
  60805. showDelay: 0,
  60806. // 隐藏延迟,单位ms
  60807. hideDelay: 100,
  60808. // 动画变换时间,单位s
  60809. transitionDuration: 0.4,
  60810. enterable: false,
  60811. // 提示背景颜色,默认为透明度为0.7的黑色
  60812. backgroundColor: 'rgba(50,50,50,0.7)',
  60813. // 提示边框颜色
  60814. borderColor: '#333',
  60815. // 提示边框圆角,单位px,默认为4
  60816. borderRadius: 4,
  60817. // 提示边框线宽,单位px,默认为0(无边框)
  60818. borderWidth: 0,
  60819. // 提示内边距,单位px,默认各方向内边距为5,
  60820. // 接受数组分别设定上右下左边距,同css
  60821. padding: 5,
  60822. // Extra css text
  60823. extraCssText: '',
  60824. // 坐标轴指示器,坐标轴触发有效
  60825. axisPointer: {
  60826. // 默认为直线
  60827. // 可选为:'line' | 'shadow' | 'cross'
  60828. type: 'line',
  60829. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  60830. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  60831. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  60832. // 极坐标系会默认选择 angle 轴
  60833. axis: 'auto',
  60834. animation: 'auto',
  60835. animationDurationUpdate: 200,
  60836. animationEasingUpdate: 'exponentialOut',
  60837. crossStyle: {
  60838. color: '#999',
  60839. width: 1,
  60840. type: 'dashed',
  60841. // TODO formatter
  60842. textStyle: {}
  60843. }
  60844. // lineStyle and shadowStyle should not be specified here,
  60845. // otherwise it will always override those styles on option.axisPointer.
  60846. },
  60847. textStyle: {
  60848. color: '#fff',
  60849. fontSize: 14
  60850. }
  60851. }
  60852. });
  60853. /*
  60854. * Licensed to the Apache Software Foundation (ASF) under one
  60855. * or more contributor license agreements. See the NOTICE file
  60856. * distributed with this work for additional information
  60857. * regarding copyright ownership. The ASF licenses this file
  60858. * to you under the Apache License, Version 2.0 (the
  60859. * "License"); you may not use this file except in compliance
  60860. * with the License. You may obtain a copy of the License at
  60861. *
  60862. * http://www.apache.org/licenses/LICENSE-2.0
  60863. *
  60864. * Unless required by applicable law or agreed to in writing,
  60865. * software distributed under the License is distributed on an
  60866. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60867. * KIND, either express or implied. See the License for the
  60868. * specific language governing permissions and limitations
  60869. * under the License.
  60870. */
  60871. var each$18 = each$1;
  60872. var toCamelCase$1 = toCamelCase;
  60873. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  60874. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  60875. /**
  60876. * @param {number} duration
  60877. * @return {string}
  60878. * @inner
  60879. */
  60880. function assembleTransition(duration) {
  60881. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  60882. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  60883. + 'top ' + duration + 's ' + transitionCurve;
  60884. return map(vendors, function (vendorPrefix) {
  60885. return vendorPrefix + 'transition:' + transitionText;
  60886. }).join(';');
  60887. }
  60888. /**
  60889. * @param {Object} textStyle
  60890. * @return {string}
  60891. * @inner
  60892. */
  60893. function assembleFont(textStyleModel) {
  60894. var cssText = [];
  60895. var fontSize = textStyleModel.get('fontSize');
  60896. var color = textStyleModel.getTextColor();
  60897. color && cssText.push('color:' + color);
  60898. cssText.push('font:' + textStyleModel.getFont());
  60899. fontSize &&
  60900. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  60901. each$18(['decoration', 'align'], function (name) {
  60902. var val = textStyleModel.get(name);
  60903. val && cssText.push('text-' + name + ':' + val);
  60904. });
  60905. return cssText.join(';');
  60906. }
  60907. /**
  60908. * @param {Object} tooltipModel
  60909. * @return {string}
  60910. * @inner
  60911. */
  60912. function assembleCssText(tooltipModel) {
  60913. var cssText = [];
  60914. var transitionDuration = tooltipModel.get('transitionDuration');
  60915. var backgroundColor = tooltipModel.get('backgroundColor');
  60916. var textStyleModel = tooltipModel.getModel('textStyle');
  60917. var padding = tooltipModel.get('padding');
  60918. // Animation transition. Do not animate when transitionDuration is 0.
  60919. transitionDuration &&
  60920. cssText.push(assembleTransition(transitionDuration));
  60921. if (backgroundColor) {
  60922. if (env$1.canvasSupported) {
  60923. cssText.push('background-Color:' + backgroundColor);
  60924. }
  60925. else {
  60926. // for ie
  60927. cssText.push(
  60928. 'background-Color:#' + toHex(backgroundColor)
  60929. );
  60930. cssText.push('filter:alpha(opacity=70)');
  60931. }
  60932. }
  60933. // Border style
  60934. each$18(['width', 'color', 'radius'], function (name) {
  60935. var borderName = 'border-' + name;
  60936. var camelCase = toCamelCase$1(borderName);
  60937. var val = tooltipModel.get(camelCase);
  60938. val != null &&
  60939. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  60940. });
  60941. // Text style
  60942. cssText.push(assembleFont(textStyleModel));
  60943. // Padding
  60944. if (padding != null) {
  60945. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  60946. }
  60947. return cssText.join(';') + ';';
  60948. }
  60949. /**
  60950. * @alias module:echarts/component/tooltip/TooltipContent
  60951. * @constructor
  60952. */
  60953. function TooltipContent(container, api) {
  60954. if (env$1.wxa) {
  60955. return null;
  60956. }
  60957. var el = document.createElement('div');
  60958. var zr = this._zr = api.getZr();
  60959. this.el = el;
  60960. this._x = api.getWidth() / 2;
  60961. this._y = api.getHeight() / 2;
  60962. container.appendChild(el);
  60963. this._container = container;
  60964. this._show = false;
  60965. /**
  60966. * @private
  60967. */
  60968. this._hideTimeout;
  60969. var self = this;
  60970. el.onmouseenter = function () {
  60971. // clear the timeout in hideLater and keep showing tooltip
  60972. if (self._enterable) {
  60973. clearTimeout(self._hideTimeout);
  60974. self._show = true;
  60975. }
  60976. self._inContent = true;
  60977. };
  60978. el.onmousemove = function (e) {
  60979. e = e || window.event;
  60980. if (!self._enterable) {
  60981. // Try trigger zrender event to avoid mouse
  60982. // in and out shape too frequently
  60983. var handler = zr.handler;
  60984. normalizeEvent(container, e, true);
  60985. handler.dispatch('mousemove', e);
  60986. }
  60987. };
  60988. el.onmouseleave = function () {
  60989. if (self._enterable) {
  60990. if (self._show) {
  60991. self.hideLater(self._hideDelay);
  60992. }
  60993. }
  60994. self._inContent = false;
  60995. };
  60996. }
  60997. TooltipContent.prototype = {
  60998. constructor: TooltipContent,
  60999. /**
  61000. * @private
  61001. * @type {boolean}
  61002. */
  61003. _enterable: true,
  61004. /**
  61005. * Update when tooltip is rendered
  61006. */
  61007. update: function () {
  61008. // FIXME
  61009. // Move this logic to ec main?
  61010. var container = this._container;
  61011. var stl = container.currentStyle
  61012. || document.defaultView.getComputedStyle(container);
  61013. var domStyle = container.style;
  61014. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  61015. domStyle.position = 'relative';
  61016. }
  61017. // Hide the tooltip
  61018. // PENDING
  61019. // this.hide();
  61020. },
  61021. show: function (tooltipModel) {
  61022. clearTimeout(this._hideTimeout);
  61023. var el = this.el;
  61024. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  61025. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  61026. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  61027. + (tooltipModel.get('extraCssText') || '');
  61028. el.style.display = el.innerHTML ? 'block' : 'none';
  61029. this._show = true;
  61030. },
  61031. setContent: function (content) {
  61032. this.el.innerHTML = content == null ? '' : content;
  61033. },
  61034. setEnterable: function (enterable) {
  61035. this._enterable = enterable;
  61036. },
  61037. getSize: function () {
  61038. var el = this.el;
  61039. return [el.clientWidth, el.clientHeight];
  61040. },
  61041. moveTo: function (x, y) {
  61042. // xy should be based on canvas root. But tooltipContent is
  61043. // the sibling of canvas root. So padding of ec container
  61044. // should be considered here.
  61045. var zr = this._zr;
  61046. var viewportRootOffset;
  61047. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  61048. x += viewportRootOffset.offsetLeft;
  61049. y += viewportRootOffset.offsetTop;
  61050. }
  61051. var style = this.el.style;
  61052. style.left = x + 'px';
  61053. style.top = y + 'px';
  61054. this._x = x;
  61055. this._y = y;
  61056. },
  61057. hide: function () {
  61058. this.el.style.display = 'none';
  61059. this._show = false;
  61060. },
  61061. hideLater: function (time) {
  61062. if (this._show && !(this._inContent && this._enterable)) {
  61063. if (time) {
  61064. this._hideDelay = time;
  61065. // Set show false to avoid invoke hideLater mutiple times
  61066. this._show = false;
  61067. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  61068. }
  61069. else {
  61070. this.hide();
  61071. }
  61072. }
  61073. },
  61074. isShow: function () {
  61075. return this._show;
  61076. }
  61077. };
  61078. /*
  61079. * Licensed to the Apache Software Foundation (ASF) under one
  61080. * or more contributor license agreements. See the NOTICE file
  61081. * distributed with this work for additional information
  61082. * regarding copyright ownership. The ASF licenses this file
  61083. * to you under the Apache License, Version 2.0 (the
  61084. * "License"); you may not use this file except in compliance
  61085. * with the License. You may obtain a copy of the License at
  61086. *
  61087. * http://www.apache.org/licenses/LICENSE-2.0
  61088. *
  61089. * Unless required by applicable law or agreed to in writing,
  61090. * software distributed under the License is distributed on an
  61091. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61092. * KIND, either express or implied. See the License for the
  61093. * specific language governing permissions and limitations
  61094. * under the License.
  61095. */
  61096. var bind$3 = bind;
  61097. var each$17 = each$1;
  61098. var parsePercent$2 = parsePercent$1;
  61099. var proxyRect = new Rect({
  61100. shape: {x: -1, y: -1, width: 2, height: 2}
  61101. });
  61102. extendComponentView({
  61103. type: 'tooltip',
  61104. init: function (ecModel, api) {
  61105. if (env$1.node) {
  61106. return;
  61107. }
  61108. var tooltipContent = new TooltipContent(api.getDom(), api);
  61109. this._tooltipContent = tooltipContent;
  61110. },
  61111. render: function (tooltipModel, ecModel, api) {
  61112. if (env$1.node || env$1.wxa) {
  61113. return;
  61114. }
  61115. // Reset
  61116. this.group.removeAll();
  61117. /**
  61118. * @private
  61119. * @type {module:echarts/component/tooltip/TooltipModel}
  61120. */
  61121. this._tooltipModel = tooltipModel;
  61122. /**
  61123. * @private
  61124. * @type {module:echarts/model/Global}
  61125. */
  61126. this._ecModel = ecModel;
  61127. /**
  61128. * @private
  61129. * @type {module:echarts/ExtensionAPI}
  61130. */
  61131. this._api = api;
  61132. /**
  61133. * Should be cleaned when render.
  61134. * @private
  61135. * @type {Array.<Array.<Object>>}
  61136. */
  61137. this._lastDataByCoordSys = null;
  61138. /**
  61139. * @private
  61140. * @type {boolean}
  61141. */
  61142. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  61143. var tooltipContent = this._tooltipContent;
  61144. tooltipContent.update();
  61145. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  61146. this._initGlobalListener();
  61147. this._keepShow();
  61148. },
  61149. _initGlobalListener: function () {
  61150. var tooltipModel = this._tooltipModel;
  61151. var triggerOn = tooltipModel.get('triggerOn');
  61152. register(
  61153. 'itemTooltip',
  61154. this._api,
  61155. bind$3(function (currTrigger, e, dispatchAction) {
  61156. // If 'none', it is not controlled by mouse totally.
  61157. if (triggerOn !== 'none') {
  61158. if (triggerOn.indexOf(currTrigger) >= 0) {
  61159. this._tryShow(e, dispatchAction);
  61160. }
  61161. else if (currTrigger === 'leave') {
  61162. this._hide(dispatchAction);
  61163. }
  61164. }
  61165. }, this)
  61166. );
  61167. },
  61168. _keepShow: function () {
  61169. var tooltipModel = this._tooltipModel;
  61170. var ecModel = this._ecModel;
  61171. var api = this._api;
  61172. // Try to keep the tooltip show when refreshing
  61173. if (this._lastX != null
  61174. && this._lastY != null
  61175. // When user is willing to control tooltip totally using API,
  61176. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  61177. // which is not expected.
  61178. && tooltipModel.get('triggerOn') !== 'none'
  61179. ) {
  61180. var self = this;
  61181. clearTimeout(this._refreshUpdateTimeout);
  61182. this._refreshUpdateTimeout = setTimeout(function () {
  61183. // Show tip next tick after other charts are rendered
  61184. // In case highlight action has wrong result
  61185. // FIXME
  61186. self.manuallyShowTip(tooltipModel, ecModel, api, {
  61187. x: self._lastX,
  61188. y: self._lastY
  61189. });
  61190. });
  61191. }
  61192. },
  61193. /**
  61194. * Show tip manually by
  61195. * dispatchAction({
  61196. * type: 'showTip',
  61197. * x: 10,
  61198. * y: 10
  61199. * });
  61200. * Or
  61201. * dispatchAction({
  61202. * type: 'showTip',
  61203. * seriesIndex: 0,
  61204. * dataIndex or dataIndexInside or name
  61205. * });
  61206. *
  61207. * TODO Batch
  61208. */
  61209. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  61210. if (payload.from === this.uid || env$1.node) {
  61211. return;
  61212. }
  61213. var dispatchAction = makeDispatchAction$1(payload, api);
  61214. // Reset ticket
  61215. this._ticket = '';
  61216. // When triggered from axisPointer.
  61217. var dataByCoordSys = payload.dataByCoordSys;
  61218. if (payload.tooltip && payload.x != null && payload.y != null) {
  61219. var el = proxyRect;
  61220. el.position = [payload.x, payload.y];
  61221. el.update();
  61222. el.tooltip = payload.tooltip;
  61223. // Manually show tooltip while view is not using zrender elements.
  61224. this._tryShow({
  61225. offsetX: payload.x,
  61226. offsetY: payload.y,
  61227. target: el
  61228. }, dispatchAction);
  61229. }
  61230. else if (dataByCoordSys) {
  61231. this._tryShow({
  61232. offsetX: payload.x,
  61233. offsetY: payload.y,
  61234. position: payload.position,
  61235. event: {},
  61236. dataByCoordSys: payload.dataByCoordSys,
  61237. tooltipOption: payload.tooltipOption
  61238. }, dispatchAction);
  61239. }
  61240. else if (payload.seriesIndex != null) {
  61241. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  61242. return;
  61243. }
  61244. var pointInfo = findPointFromSeries(payload, ecModel);
  61245. var cx = pointInfo.point[0];
  61246. var cy = pointInfo.point[1];
  61247. if (cx != null && cy != null) {
  61248. this._tryShow({
  61249. offsetX: cx,
  61250. offsetY: cy,
  61251. position: payload.position,
  61252. target: pointInfo.el,
  61253. event: {}
  61254. }, dispatchAction);
  61255. }
  61256. }
  61257. else if (payload.x != null && payload.y != null) {
  61258. // FIXME
  61259. // should wrap dispatchAction like `axisPointer/globalListener` ?
  61260. api.dispatchAction({
  61261. type: 'updateAxisPointer',
  61262. x: payload.x,
  61263. y: payload.y
  61264. });
  61265. this._tryShow({
  61266. offsetX: payload.x,
  61267. offsetY: payload.y,
  61268. position: payload.position,
  61269. target: api.getZr().findHover(payload.x, payload.y).target,
  61270. event: {}
  61271. }, dispatchAction);
  61272. }
  61273. },
  61274. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  61275. var tooltipContent = this._tooltipContent;
  61276. if (!this._alwaysShowContent && this._tooltipModel) {
  61277. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  61278. }
  61279. this._lastX = this._lastY = null;
  61280. if (payload.from !== this.uid) {
  61281. this._hide(makeDispatchAction$1(payload, api));
  61282. }
  61283. },
  61284. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  61285. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  61286. // and tooltip.
  61287. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  61288. var seriesIndex = payload.seriesIndex;
  61289. var dataIndex = payload.dataIndex;
  61290. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  61291. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  61292. return;
  61293. }
  61294. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  61295. if (!seriesModel) {
  61296. return;
  61297. }
  61298. var data = seriesModel.getData();
  61299. var tooltipModel = buildTooltipModel([
  61300. data.getItemModel(dataIndex),
  61301. seriesModel,
  61302. (seriesModel.coordinateSystem || {}).model,
  61303. tooltipModel
  61304. ]);
  61305. if (tooltipModel.get('trigger') !== 'axis') {
  61306. return;
  61307. }
  61308. api.dispatchAction({
  61309. type: 'updateAxisPointer',
  61310. seriesIndex: seriesIndex,
  61311. dataIndex: dataIndex,
  61312. position: payload.position
  61313. });
  61314. return true;
  61315. },
  61316. _tryShow: function (e, dispatchAction) {
  61317. var el = e.target;
  61318. var tooltipModel = this._tooltipModel;
  61319. if (!tooltipModel) {
  61320. return;
  61321. }
  61322. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  61323. this._lastX = e.offsetX;
  61324. this._lastY = e.offsetY;
  61325. var dataByCoordSys = e.dataByCoordSys;
  61326. if (dataByCoordSys && dataByCoordSys.length) {
  61327. this._showAxisTooltip(dataByCoordSys, e);
  61328. }
  61329. // Always show item tooltip if mouse is on the element with dataIndex
  61330. else if (el && el.dataIndex != null) {
  61331. this._lastDataByCoordSys = null;
  61332. this._showSeriesItemTooltip(e, el, dispatchAction);
  61333. }
  61334. // Tooltip provided directly. Like legend.
  61335. else if (el && el.tooltip) {
  61336. this._lastDataByCoordSys = null;
  61337. this._showComponentItemTooltip(e, el, dispatchAction);
  61338. }
  61339. else {
  61340. this._lastDataByCoordSys = null;
  61341. this._hide(dispatchAction);
  61342. }
  61343. },
  61344. _showOrMove: function (tooltipModel, cb) {
  61345. // showDelay is used in this case: tooltip.enterable is set
  61346. // as true. User intent to move mouse into tooltip and click
  61347. // something. `showDelay` makes it easyer to enter the content
  61348. // but tooltip do not move immediately.
  61349. var delay = tooltipModel.get('showDelay');
  61350. cb = bind(cb, this);
  61351. clearTimeout(this._showTimout);
  61352. delay > 0
  61353. ? (this._showTimout = setTimeout(cb, delay))
  61354. : cb();
  61355. },
  61356. _showAxisTooltip: function (dataByCoordSys, e) {
  61357. var ecModel = this._ecModel;
  61358. var globalTooltipModel = this._tooltipModel;
  61359. var point = [e.offsetX, e.offsetY];
  61360. var singleDefaultHTML = [];
  61361. var singleParamsList = [];
  61362. var singleTooltipModel = buildTooltipModel([
  61363. e.tooltipOption,
  61364. globalTooltipModel
  61365. ]);
  61366. each$17(dataByCoordSys, function (itemCoordSys) {
  61367. // var coordParamList = [];
  61368. // var coordDefaultHTML = [];
  61369. // var coordTooltipModel = buildTooltipModel([
  61370. // e.tooltipOption,
  61371. // itemCoordSys.tooltipOption,
  61372. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  61373. // globalTooltipModel
  61374. // ]);
  61375. // var displayMode = coordTooltipModel.get('displayMode');
  61376. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  61377. each$17(itemCoordSys.dataByAxis, function (item) {
  61378. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  61379. var axisValue = item.value;
  61380. var seriesDefaultHTML = [];
  61381. if (!axisModel || axisValue == null) {
  61382. return;
  61383. }
  61384. var valueLabel = getValueLabel(
  61385. axisValue, axisModel.axis, ecModel,
  61386. item.seriesDataIndices,
  61387. item.valueLabelOpt
  61388. );
  61389. each$1(item.seriesDataIndices, function (idxItem) {
  61390. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  61391. var dataIndex = idxItem.dataIndexInside;
  61392. var dataParams = series && series.getDataParams(dataIndex);
  61393. dataParams.axisDim = item.axisDim;
  61394. dataParams.axisIndex = item.axisIndex;
  61395. dataParams.axisType = item.axisType;
  61396. dataParams.axisId = item.axisId;
  61397. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  61398. dataParams.axisValueLabel = valueLabel;
  61399. if (dataParams) {
  61400. singleParamsList.push(dataParams);
  61401. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  61402. }
  61403. });
  61404. // Default tooltip content
  61405. // FIXME
  61406. // (1) shold be the first data which has name?
  61407. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  61408. var firstLine = valueLabel;
  61409. singleDefaultHTML.push(
  61410. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  61411. + seriesDefaultHTML.join('<br />')
  61412. );
  61413. });
  61414. }, this);
  61415. // In most case, the second axis is shown upper than the first one.
  61416. singleDefaultHTML.reverse();
  61417. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  61418. var positionExpr = e.position;
  61419. this._showOrMove(singleTooltipModel, function () {
  61420. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  61421. this._updatePosition(
  61422. singleTooltipModel,
  61423. positionExpr,
  61424. point[0], point[1],
  61425. this._tooltipContent,
  61426. singleParamsList
  61427. );
  61428. }
  61429. else {
  61430. this._showTooltipContent(
  61431. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  61432. point[0], point[1], positionExpr
  61433. );
  61434. }
  61435. });
  61436. // Do not trigger events here, because this branch only be entered
  61437. // from dispatchAction.
  61438. },
  61439. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  61440. var ecModel = this._ecModel;
  61441. // Use dataModel in element if possible
  61442. // Used when mouseover on a element like markPoint or edge
  61443. // In which case, the data is not main data in series.
  61444. var seriesIndex = el.seriesIndex;
  61445. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  61446. // For example, graph link.
  61447. var dataModel = el.dataModel || seriesModel;
  61448. var dataIndex = el.dataIndex;
  61449. var dataType = el.dataType;
  61450. var data = dataModel.getData();
  61451. var tooltipModel = buildTooltipModel([
  61452. data.getItemModel(dataIndex),
  61453. dataModel,
  61454. seriesModel && (seriesModel.coordinateSystem || {}).model,
  61455. this._tooltipModel
  61456. ]);
  61457. var tooltipTrigger = tooltipModel.get('trigger');
  61458. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  61459. return;
  61460. }
  61461. var params = dataModel.getDataParams(dataIndex, dataType);
  61462. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  61463. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  61464. this._showOrMove(tooltipModel, function () {
  61465. this._showTooltipContent(
  61466. tooltipModel, defaultHtml, params, asyncTicket,
  61467. e.offsetX, e.offsetY, e.position, e.target
  61468. );
  61469. });
  61470. // FIXME
  61471. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  61472. dispatchAction({
  61473. type: 'showTip',
  61474. dataIndexInside: dataIndex,
  61475. dataIndex: data.getRawIndex(dataIndex),
  61476. seriesIndex: seriesIndex,
  61477. from: this.uid
  61478. });
  61479. },
  61480. _showComponentItemTooltip: function (e, el, dispatchAction) {
  61481. var tooltipOpt = el.tooltip;
  61482. if (typeof tooltipOpt === 'string') {
  61483. var content = tooltipOpt;
  61484. tooltipOpt = {
  61485. content: content,
  61486. // Fixed formatter
  61487. formatter: content
  61488. };
  61489. }
  61490. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  61491. var defaultHtml = subTooltipModel.get('content');
  61492. var asyncTicket = Math.random();
  61493. // Do not check whether `trigger` is 'none' here, because `trigger`
  61494. // only works on cooridinate system. In fact, we have not found case
  61495. // that requires setting `trigger` nothing on component yet.
  61496. this._showOrMove(subTooltipModel, function () {
  61497. this._showTooltipContent(
  61498. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  61499. asyncTicket, e.offsetX, e.offsetY, e.position, el
  61500. );
  61501. });
  61502. // If not dispatch showTip, tip may be hide triggered by axis.
  61503. dispatchAction({
  61504. type: 'showTip',
  61505. from: this.uid
  61506. });
  61507. },
  61508. _showTooltipContent: function (
  61509. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  61510. ) {
  61511. // Reset ticket
  61512. this._ticket = '';
  61513. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  61514. return;
  61515. }
  61516. var tooltipContent = this._tooltipContent;
  61517. var formatter = tooltipModel.get('formatter');
  61518. positionExpr = positionExpr || tooltipModel.get('position');
  61519. var html = defaultHtml;
  61520. if (formatter && typeof formatter === 'string') {
  61521. html = formatTpl(formatter, params, true);
  61522. }
  61523. else if (typeof formatter === 'function') {
  61524. var callback = bind$3(function (cbTicket, html) {
  61525. if (cbTicket === this._ticket) {
  61526. tooltipContent.setContent(html);
  61527. this._updatePosition(
  61528. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  61529. );
  61530. }
  61531. }, this);
  61532. this._ticket = asyncTicket;
  61533. html = formatter(params, asyncTicket, callback);
  61534. }
  61535. tooltipContent.setContent(html);
  61536. tooltipContent.show(tooltipModel);
  61537. this._updatePosition(
  61538. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  61539. );
  61540. },
  61541. /**
  61542. * @param {string|Function|Array.<number>|Object} positionExpr
  61543. * @param {number} x Mouse x
  61544. * @param {number} y Mouse y
  61545. * @param {boolean} confine Whether confine tooltip content in view rect.
  61546. * @param {Object|<Array.<Object>} params
  61547. * @param {module:zrender/Element} el target element
  61548. * @param {module:echarts/ExtensionAPI} api
  61549. * @return {Array.<number>}
  61550. */
  61551. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  61552. var viewWidth = this._api.getWidth();
  61553. var viewHeight = this._api.getHeight();
  61554. positionExpr = positionExpr || tooltipModel.get('position');
  61555. var contentSize = content.getSize();
  61556. var align = tooltipModel.get('align');
  61557. var vAlign = tooltipModel.get('verticalAlign');
  61558. var rect = el && el.getBoundingRect().clone();
  61559. el && rect.applyTransform(el.transform);
  61560. if (typeof positionExpr === 'function') {
  61561. // Callback of position can be an array or a string specify the position
  61562. positionExpr = positionExpr([x, y], params, content.el, rect, {
  61563. viewSize: [viewWidth, viewHeight],
  61564. contentSize: contentSize.slice()
  61565. });
  61566. }
  61567. if (isArray(positionExpr)) {
  61568. x = parsePercent$2(positionExpr[0], viewWidth);
  61569. y = parsePercent$2(positionExpr[1], viewHeight);
  61570. }
  61571. else if (isObject$1(positionExpr)) {
  61572. positionExpr.width = contentSize[0];
  61573. positionExpr.height = contentSize[1];
  61574. var layoutRect = getLayoutRect(
  61575. positionExpr, {width: viewWidth, height: viewHeight}
  61576. );
  61577. x = layoutRect.x;
  61578. y = layoutRect.y;
  61579. align = null;
  61580. // When positionExpr is left/top/right/bottom,
  61581. // align and verticalAlign will not work.
  61582. vAlign = null;
  61583. }
  61584. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  61585. else if (typeof positionExpr === 'string' && el) {
  61586. var pos = calcTooltipPosition(
  61587. positionExpr, rect, contentSize
  61588. );
  61589. x = pos[0];
  61590. y = pos[1];
  61591. }
  61592. else {
  61593. var pos = refixTooltipPosition(
  61594. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  61595. );
  61596. x = pos[0];
  61597. y = pos[1];
  61598. }
  61599. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  61600. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  61601. if (tooltipModel.get('confine')) {
  61602. var pos = confineTooltipPosition(
  61603. x, y, content.el, viewWidth, viewHeight
  61604. );
  61605. x = pos[0];
  61606. y = pos[1];
  61607. }
  61608. content.moveTo(x, y);
  61609. },
  61610. // FIXME
  61611. // Should we remove this but leave this to user?
  61612. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  61613. var lastCoordSys = this._lastDataByCoordSys;
  61614. var contentNotChanged = !!lastCoordSys
  61615. && lastCoordSys.length === dataByCoordSys.length;
  61616. contentNotChanged && each$17(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  61617. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  61618. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  61619. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  61620. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  61621. contentNotChanged && each$17(lastDataByAxis, function (lastItem, indexAxis) {
  61622. var thisItem = thisDataByAxis[indexAxis] || {};
  61623. var lastIndices = lastItem.seriesDataIndices || [];
  61624. var newIndices = thisItem.seriesDataIndices || [];
  61625. contentNotChanged &=
  61626. lastItem.value === thisItem.value
  61627. && lastItem.axisType === thisItem.axisType
  61628. && lastItem.axisId === thisItem.axisId
  61629. && lastIndices.length === newIndices.length;
  61630. contentNotChanged && each$17(lastIndices, function (lastIdxItem, j) {
  61631. var newIdxItem = newIndices[j];
  61632. contentNotChanged &=
  61633. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  61634. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  61635. });
  61636. });
  61637. });
  61638. this._lastDataByCoordSys = dataByCoordSys;
  61639. return !!contentNotChanged;
  61640. },
  61641. _hide: function (dispatchAction) {
  61642. // Do not directly hideLater here, because this behavior may be prevented
  61643. // in dispatchAction when showTip is dispatched.
  61644. // FIXME
  61645. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  61646. this._lastDataByCoordSys = null;
  61647. dispatchAction({
  61648. type: 'hideTip',
  61649. from: this.uid
  61650. });
  61651. },
  61652. dispose: function (ecModel, api) {
  61653. if (env$1.node || env$1.wxa) {
  61654. return;
  61655. }
  61656. this._tooltipContent.hide();
  61657. unregister('itemTooltip', api);
  61658. }
  61659. });
  61660. /**
  61661. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  61662. * From top to bottom. (the last one should be globalTooltipModel);
  61663. */
  61664. function buildTooltipModel(modelCascade) {
  61665. var resultModel = modelCascade.pop();
  61666. while (modelCascade.length) {
  61667. var tooltipOpt = modelCascade.pop();
  61668. if (tooltipOpt) {
  61669. if (Model.isInstance(tooltipOpt)) {
  61670. tooltipOpt = tooltipOpt.get('tooltip', true);
  61671. }
  61672. // In each data item tooltip can be simply write:
  61673. // {
  61674. // value: 10,
  61675. // tooltip: 'Something you need to know'
  61676. // }
  61677. if (typeof tooltipOpt === 'string') {
  61678. tooltipOpt = {formatter: tooltipOpt};
  61679. }
  61680. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  61681. }
  61682. }
  61683. return resultModel;
  61684. }
  61685. function makeDispatchAction$1(payload, api) {
  61686. return payload.dispatchAction || bind(api.dispatchAction, api);
  61687. }
  61688. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  61689. var size = getOuterSize(el);
  61690. var width = size.width;
  61691. var height = size.height;
  61692. if (gapH != null) {
  61693. if (x + width + gapH > viewWidth) {
  61694. x -= width + gapH;
  61695. }
  61696. else {
  61697. x += gapH;
  61698. }
  61699. }
  61700. if (gapV != null) {
  61701. if (y + height + gapV > viewHeight) {
  61702. y -= height + gapV;
  61703. }
  61704. else {
  61705. y += gapV;
  61706. }
  61707. }
  61708. return [x, y];
  61709. }
  61710. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  61711. var size = getOuterSize(el);
  61712. var width = size.width;
  61713. var height = size.height;
  61714. x = Math.min(x + width, viewWidth) - width;
  61715. y = Math.min(y + height, viewHeight) - height;
  61716. x = Math.max(x, 0);
  61717. y = Math.max(y, 0);
  61718. return [x, y];
  61719. }
  61720. function getOuterSize(el) {
  61721. var width = el.clientWidth;
  61722. var height = el.clientHeight;
  61723. // Consider browser compatibility.
  61724. // IE8 does not support getComputedStyle.
  61725. if (document.defaultView && document.defaultView.getComputedStyle) {
  61726. var stl = document.defaultView.getComputedStyle(el);
  61727. if (stl) {
  61728. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  61729. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  61730. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  61731. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  61732. }
  61733. }
  61734. return {width: width, height: height};
  61735. }
  61736. function calcTooltipPosition(position, rect, contentSize) {
  61737. var domWidth = contentSize[0];
  61738. var domHeight = contentSize[1];
  61739. var gap = 5;
  61740. var x = 0;
  61741. var y = 0;
  61742. var rectWidth = rect.width;
  61743. var rectHeight = rect.height;
  61744. switch (position) {
  61745. case 'inside':
  61746. x = rect.x + rectWidth / 2 - domWidth / 2;
  61747. y = rect.y + rectHeight / 2 - domHeight / 2;
  61748. break;
  61749. case 'top':
  61750. x = rect.x + rectWidth / 2 - domWidth / 2;
  61751. y = rect.y - domHeight - gap;
  61752. break;
  61753. case 'bottom':
  61754. x = rect.x + rectWidth / 2 - domWidth / 2;
  61755. y = rect.y + rectHeight + gap;
  61756. break;
  61757. case 'left':
  61758. x = rect.x - domWidth - gap;
  61759. y = rect.y + rectHeight / 2 - domHeight / 2;
  61760. break;
  61761. case 'right':
  61762. x = rect.x + rectWidth + gap;
  61763. y = rect.y + rectHeight / 2 - domHeight / 2;
  61764. }
  61765. return [x, y];
  61766. }
  61767. function isCenterAlign(align) {
  61768. return align === 'center' || align === 'middle';
  61769. }
  61770. /*
  61771. * Licensed to the Apache Software Foundation (ASF) under one
  61772. * or more contributor license agreements. See the NOTICE file
  61773. * distributed with this work for additional information
  61774. * regarding copyright ownership. The ASF licenses this file
  61775. * to you under the Apache License, Version 2.0 (the
  61776. * "License"); you may not use this file except in compliance
  61777. * with the License. You may obtain a copy of the License at
  61778. *
  61779. * http://www.apache.org/licenses/LICENSE-2.0
  61780. *
  61781. * Unless required by applicable law or agreed to in writing,
  61782. * software distributed under the License is distributed on an
  61783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61784. * KIND, either express or implied. See the License for the
  61785. * specific language governing permissions and limitations
  61786. * under the License.
  61787. */
  61788. // FIXME Better way to pack data in graphic element
  61789. /**
  61790. * @action
  61791. * @property {string} type
  61792. * @property {number} seriesIndex
  61793. * @property {number} dataIndex
  61794. * @property {number} [x]
  61795. * @property {number} [y]
  61796. */
  61797. registerAction(
  61798. {
  61799. type: 'showTip',
  61800. event: 'showTip',
  61801. update: 'tooltip:manuallyShowTip'
  61802. },
  61803. // noop
  61804. function () {}
  61805. );
  61806. registerAction(
  61807. {
  61808. type: 'hideTip',
  61809. event: 'hideTip',
  61810. update: 'tooltip:manuallyHideTip'
  61811. },
  61812. // noop
  61813. function () {}
  61814. );
  61815. /*
  61816. * Licensed to the Apache Software Foundation (ASF) under one
  61817. * or more contributor license agreements. See the NOTICE file
  61818. * distributed with this work for additional information
  61819. * regarding copyright ownership. The ASF licenses this file
  61820. * to you under the Apache License, Version 2.0 (the
  61821. * "License"); you may not use this file except in compliance
  61822. * with the License. You may obtain a copy of the License at
  61823. *
  61824. * http://www.apache.org/licenses/LICENSE-2.0
  61825. *
  61826. * Unless required by applicable law or agreed to in writing,
  61827. * software distributed under the License is distributed on an
  61828. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61829. * KIND, either express or implied. See the License for the
  61830. * specific language governing permissions and limitations
  61831. * under the License.
  61832. */
  61833. function getSeriesStackId$1(seriesModel) {
  61834. return seriesModel.get('stack')
  61835. || '__ec_stack_' + seriesModel.seriesIndex;
  61836. }
  61837. function getAxisKey$1(axis) {
  61838. return axis.dim;
  61839. }
  61840. /**
  61841. * @param {string} seriesType
  61842. * @param {module:echarts/model/Global} ecModel
  61843. * @param {module:echarts/ExtensionAPI} api
  61844. */
  61845. function barLayoutPolar(seriesType, ecModel, api) {
  61846. var width = api.getWidth();
  61847. var height = api.getHeight();
  61848. var lastStackCoords = {};
  61849. var barWidthAndOffset = calRadialBar(
  61850. filter(
  61851. ecModel.getSeriesByType(seriesType),
  61852. function (seriesModel) {
  61853. return !ecModel.isSeriesFiltered(seriesModel)
  61854. && seriesModel.coordinateSystem
  61855. && seriesModel.coordinateSystem.type === 'polar';
  61856. }
  61857. )
  61858. );
  61859. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  61860. // Check series coordinate, do layout for polar only
  61861. if (seriesModel.coordinateSystem.type !== 'polar') {
  61862. return;
  61863. }
  61864. var data = seriesModel.getData();
  61865. var polar = seriesModel.coordinateSystem;
  61866. var baseAxis = polar.getBaseAxis();
  61867. var stackId = getSeriesStackId$1(seriesModel);
  61868. var columnLayoutInfo
  61869. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  61870. var columnOffset = columnLayoutInfo.offset;
  61871. var columnWidth = columnLayoutInfo.width;
  61872. var valueAxis = polar.getOtherAxis(baseAxis);
  61873. var center = seriesModel.get('center') || ['50%', '50%'];
  61874. var cx = parsePercent$1(center[0], width);
  61875. var cy = parsePercent$1(center[1], height);
  61876. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  61877. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  61878. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  61879. var valueDim = data.mapDimension(valueAxis.dim);
  61880. var baseDim = data.mapDimension(baseAxis.dim);
  61881. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  61882. var valueAxisStart = valueAxis.getExtent()[0];
  61883. for (var idx = 0, len = data.count(); idx < len; idx++) {
  61884. var value = data.get(valueDim, idx);
  61885. var baseValue = data.get(baseDim, idx);
  61886. if (isNaN(value)) {
  61887. continue;
  61888. }
  61889. var sign = value >= 0 ? 'p' : 'n';
  61890. var baseCoord = valueAxisStart;
  61891. // Because of the barMinHeight, we can not use the value in
  61892. // stackResultDimension directly.
  61893. // Only ordinal axis can be stacked.
  61894. if (stacked) {
  61895. if (!lastStackCoords[stackId][baseValue]) {
  61896. lastStackCoords[stackId][baseValue] = {
  61897. p: valueAxisStart, // Positive stack
  61898. n: valueAxisStart // Negative stack
  61899. };
  61900. }
  61901. // Should also consider #4243
  61902. baseCoord = lastStackCoords[stackId][baseValue][sign];
  61903. }
  61904. var r0;
  61905. var r;
  61906. var startAngle;
  61907. var endAngle;
  61908. // radial sector
  61909. if (valueAxis.dim === 'radius') {
  61910. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  61911. var angle = baseAxis.dataToAngle(baseValue);
  61912. if (Math.abs(radiusSpan) < barMinHeight) {
  61913. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  61914. }
  61915. r0 = baseCoord;
  61916. r = baseCoord + radiusSpan;
  61917. startAngle = angle - columnOffset;
  61918. endAngle = startAngle - columnWidth;
  61919. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  61920. }
  61921. // tangential sector
  61922. else {
  61923. // angleAxis must be clamped.
  61924. var angleSpan = valueAxis.dataToAngle(value, true) - valueAxisStart;
  61925. var radius = baseAxis.dataToRadius(baseValue);
  61926. if (Math.abs(angleSpan) < barMinAngle) {
  61927. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  61928. }
  61929. r0 = radius + columnOffset;
  61930. r = r0 + columnWidth;
  61931. startAngle = baseCoord;
  61932. endAngle = baseCoord + angleSpan;
  61933. // if the previous stack is at the end of the ring,
  61934. // add a round to differentiate it from origin
  61935. // var extent = angleAxis.getExtent();
  61936. // var stackCoord = angle;
  61937. // if (stackCoord === extent[0] && value > 0) {
  61938. // stackCoord = extent[1];
  61939. // }
  61940. // else if (stackCoord === extent[1] && value < 0) {
  61941. // stackCoord = extent[0];
  61942. // }
  61943. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  61944. }
  61945. data.setItemLayout(idx, {
  61946. cx: cx,
  61947. cy: cy,
  61948. r0: r0,
  61949. r: r,
  61950. // Consider that positive angle is anti-clockwise,
  61951. // while positive radian of sector is clockwise
  61952. startAngle: -startAngle * Math.PI / 180,
  61953. endAngle: -endAngle * Math.PI / 180
  61954. });
  61955. }
  61956. }, this);
  61957. }
  61958. /**
  61959. * Calculate bar width and offset for radial bar charts
  61960. */
  61961. function calRadialBar(barSeries, api) {
  61962. // Columns info on each category axis. Key is polar name
  61963. var columnsMap = {};
  61964. each$1(barSeries, function (seriesModel, idx) {
  61965. var data = seriesModel.getData();
  61966. var polar = seriesModel.coordinateSystem;
  61967. var baseAxis = polar.getBaseAxis();
  61968. var axisExtent = baseAxis.getExtent();
  61969. var bandWidth = baseAxis.type === 'category'
  61970. ? baseAxis.getBandWidth()
  61971. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  61972. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  61973. bandWidth: bandWidth,
  61974. remainedWidth: bandWidth,
  61975. autoWidthCount: 0,
  61976. categoryGap: '20%',
  61977. gap: '30%',
  61978. stacks: {}
  61979. };
  61980. var stacks = columnsOnAxis.stacks;
  61981. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  61982. var stackId = getSeriesStackId$1(seriesModel);
  61983. if (!stacks[stackId]) {
  61984. columnsOnAxis.autoWidthCount++;
  61985. }
  61986. stacks[stackId] = stacks[stackId] || {
  61987. width: 0,
  61988. maxWidth: 0
  61989. };
  61990. var barWidth = parsePercent$1(
  61991. seriesModel.get('barWidth'),
  61992. bandWidth
  61993. );
  61994. var barMaxWidth = parsePercent$1(
  61995. seriesModel.get('barMaxWidth'),
  61996. bandWidth
  61997. );
  61998. var barGap = seriesModel.get('barGap');
  61999. var barCategoryGap = seriesModel.get('barCategoryGap');
  62000. if (barWidth && !stacks[stackId].width) {
  62001. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  62002. stacks[stackId].width = barWidth;
  62003. columnsOnAxis.remainedWidth -= barWidth;
  62004. }
  62005. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  62006. (barGap != null) && (columnsOnAxis.gap = barGap);
  62007. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  62008. });
  62009. var result = {};
  62010. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  62011. result[coordSysName] = {};
  62012. var stacks = columnsOnAxis.stacks;
  62013. var bandWidth = columnsOnAxis.bandWidth;
  62014. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  62015. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  62016. var remainedWidth = columnsOnAxis.remainedWidth;
  62017. var autoWidthCount = columnsOnAxis.autoWidthCount;
  62018. var autoWidth = (remainedWidth - categoryGap)
  62019. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  62020. autoWidth = Math.max(autoWidth, 0);
  62021. // Find if any auto calculated bar exceeded maxBarWidth
  62022. each$1(stacks, function (column, stack) {
  62023. var maxWidth = column.maxWidth;
  62024. if (maxWidth && maxWidth < autoWidth) {
  62025. maxWidth = Math.min(maxWidth, remainedWidth);
  62026. if (column.width) {
  62027. maxWidth = Math.min(maxWidth, column.width);
  62028. }
  62029. remainedWidth -= maxWidth;
  62030. column.width = maxWidth;
  62031. autoWidthCount--;
  62032. }
  62033. });
  62034. // Recalculate width again
  62035. autoWidth = (remainedWidth - categoryGap)
  62036. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  62037. autoWidth = Math.max(autoWidth, 0);
  62038. var widthSum = 0;
  62039. var lastColumn;
  62040. each$1(stacks, function (column, idx) {
  62041. if (!column.width) {
  62042. column.width = autoWidth;
  62043. }
  62044. lastColumn = column;
  62045. widthSum += column.width * (1 + barGapPercent);
  62046. });
  62047. if (lastColumn) {
  62048. widthSum -= lastColumn.width * barGapPercent;
  62049. }
  62050. var offset = -widthSum / 2;
  62051. each$1(stacks, function (column, stackId) {
  62052. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  62053. offset: offset,
  62054. width: column.width
  62055. };
  62056. offset += column.width * (1 + barGapPercent);
  62057. });
  62058. });
  62059. return result;
  62060. }
  62061. /*
  62062. * Licensed to the Apache Software Foundation (ASF) under one
  62063. * or more contributor license agreements. See the NOTICE file
  62064. * distributed with this work for additional information
  62065. * regarding copyright ownership. The ASF licenses this file
  62066. * to you under the Apache License, Version 2.0 (the
  62067. * "License"); you may not use this file except in compliance
  62068. * with the License. You may obtain a copy of the License at
  62069. *
  62070. * http://www.apache.org/licenses/LICENSE-2.0
  62071. *
  62072. * Unless required by applicable law or agreed to in writing,
  62073. * software distributed under the License is distributed on an
  62074. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62075. * KIND, either express or implied. See the License for the
  62076. * specific language governing permissions and limitations
  62077. * under the License.
  62078. */
  62079. function RadiusAxis(scale, radiusExtent) {
  62080. Axis.call(this, 'radius', scale, radiusExtent);
  62081. /**
  62082. * Axis type
  62083. * - 'category'
  62084. * - 'value'
  62085. * - 'time'
  62086. * - 'log'
  62087. * @type {string}
  62088. */
  62089. this.type = 'category';
  62090. }
  62091. RadiusAxis.prototype = {
  62092. constructor: RadiusAxis,
  62093. /**
  62094. * @override
  62095. */
  62096. pointToData: function (point, clamp) {
  62097. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  62098. },
  62099. dataToRadius: Axis.prototype.dataToCoord,
  62100. radiusToData: Axis.prototype.coordToData
  62101. };
  62102. inherits(RadiusAxis, Axis);
  62103. /*
  62104. * Licensed to the Apache Software Foundation (ASF) under one
  62105. * or more contributor license agreements. See the NOTICE file
  62106. * distributed with this work for additional information
  62107. * regarding copyright ownership. The ASF licenses this file
  62108. * to you under the Apache License, Version 2.0 (the
  62109. * "License"); you may not use this file except in compliance
  62110. * with the License. You may obtain a copy of the License at
  62111. *
  62112. * http://www.apache.org/licenses/LICENSE-2.0
  62113. *
  62114. * Unless required by applicable law or agreed to in writing,
  62115. * software distributed under the License is distributed on an
  62116. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62117. * KIND, either express or implied. See the License for the
  62118. * specific language governing permissions and limitations
  62119. * under the License.
  62120. */
  62121. function AngleAxis(scale, angleExtent) {
  62122. angleExtent = angleExtent || [0, 360];
  62123. Axis.call(this, 'angle', scale, angleExtent);
  62124. /**
  62125. * Axis type
  62126. * - 'category'
  62127. * - 'value'
  62128. * - 'time'
  62129. * - 'log'
  62130. * @type {string}
  62131. */
  62132. this.type = 'category';
  62133. }
  62134. AngleAxis.prototype = {
  62135. constructor: AngleAxis,
  62136. /**
  62137. * @override
  62138. */
  62139. pointToData: function (point, clamp) {
  62140. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  62141. },
  62142. dataToAngle: Axis.prototype.dataToCoord,
  62143. angleToData: Axis.prototype.coordToData
  62144. };
  62145. inherits(AngleAxis, Axis);
  62146. /*
  62147. * Licensed to the Apache Software Foundation (ASF) under one
  62148. * or more contributor license agreements. See the NOTICE file
  62149. * distributed with this work for additional information
  62150. * regarding copyright ownership. The ASF licenses this file
  62151. * to you under the Apache License, Version 2.0 (the
  62152. * "License"); you may not use this file except in compliance
  62153. * with the License. You may obtain a copy of the License at
  62154. *
  62155. * http://www.apache.org/licenses/LICENSE-2.0
  62156. *
  62157. * Unless required by applicable law or agreed to in writing,
  62158. * software distributed under the License is distributed on an
  62159. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62160. * KIND, either express or implied. See the License for the
  62161. * specific language governing permissions and limitations
  62162. * under the License.
  62163. */
  62164. /**
  62165. * @module echarts/coord/polar/Polar
  62166. */
  62167. /**
  62168. * @alias {module:echarts/coord/polar/Polar}
  62169. * @constructor
  62170. * @param {string} name
  62171. */
  62172. var Polar = function (name) {
  62173. /**
  62174. * @type {string}
  62175. */
  62176. this.name = name || '';
  62177. /**
  62178. * x of polar center
  62179. * @type {number}
  62180. */
  62181. this.cx = 0;
  62182. /**
  62183. * y of polar center
  62184. * @type {number}
  62185. */
  62186. this.cy = 0;
  62187. /**
  62188. * @type {module:echarts/coord/polar/RadiusAxis}
  62189. * @private
  62190. */
  62191. this._radiusAxis = new RadiusAxis();
  62192. /**
  62193. * @type {module:echarts/coord/polar/AngleAxis}
  62194. * @private
  62195. */
  62196. this._angleAxis = new AngleAxis();
  62197. this._radiusAxis.polar = this._angleAxis.polar = this;
  62198. };
  62199. Polar.prototype = {
  62200. type: 'polar',
  62201. axisPointerEnabled: true,
  62202. constructor: Polar,
  62203. /**
  62204. * @param {Array.<string>}
  62205. * @readOnly
  62206. */
  62207. dimensions: ['radius', 'angle'],
  62208. /**
  62209. * @type {module:echarts/coord/PolarModel}
  62210. */
  62211. model: null,
  62212. /**
  62213. * If contain coord
  62214. * @param {Array.<number>} point
  62215. * @return {boolean}
  62216. */
  62217. containPoint: function (point) {
  62218. var coord = this.pointToCoord(point);
  62219. return this._radiusAxis.contain(coord[0])
  62220. && this._angleAxis.contain(coord[1]);
  62221. },
  62222. /**
  62223. * If contain data
  62224. * @param {Array.<number>} data
  62225. * @return {boolean}
  62226. */
  62227. containData: function (data) {
  62228. return this._radiusAxis.containData(data[0])
  62229. && this._angleAxis.containData(data[1]);
  62230. },
  62231. /**
  62232. * @param {string} dim
  62233. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62234. */
  62235. getAxis: function (dim) {
  62236. return this['_' + dim + 'Axis'];
  62237. },
  62238. /**
  62239. * @return {Array.<module:echarts/coord/Axis>}
  62240. */
  62241. getAxes: function () {
  62242. return [this._radiusAxis, this._angleAxis];
  62243. },
  62244. /**
  62245. * Get axes by type of scale
  62246. * @param {string} scaleType
  62247. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62248. */
  62249. getAxesByScale: function (scaleType) {
  62250. var axes = [];
  62251. var angleAxis = this._angleAxis;
  62252. var radiusAxis = this._radiusAxis;
  62253. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  62254. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  62255. return axes;
  62256. },
  62257. /**
  62258. * @return {module:echarts/coord/polar/AngleAxis}
  62259. */
  62260. getAngleAxis: function () {
  62261. return this._angleAxis;
  62262. },
  62263. /**
  62264. * @return {module:echarts/coord/polar/RadiusAxis}
  62265. */
  62266. getRadiusAxis: function () {
  62267. return this._radiusAxis;
  62268. },
  62269. /**
  62270. * @param {module:echarts/coord/polar/Axis}
  62271. * @return {module:echarts/coord/polar/Axis}
  62272. */
  62273. getOtherAxis: function (axis) {
  62274. var angleAxis = this._angleAxis;
  62275. return axis === angleAxis ? this._radiusAxis : angleAxis;
  62276. },
  62277. /**
  62278. * Base axis will be used on stacking.
  62279. *
  62280. * @return {module:echarts/coord/polar/Axis}
  62281. */
  62282. getBaseAxis: function () {
  62283. return this.getAxesByScale('ordinal')[0]
  62284. || this.getAxesByScale('time')[0]
  62285. || this.getAngleAxis();
  62286. },
  62287. /**
  62288. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  62289. * @return {Object} {baseAxes: [], otherAxes: []}
  62290. */
  62291. getTooltipAxes: function (dim) {
  62292. var baseAxis = (dim != null && dim !== 'auto')
  62293. ? this.getAxis(dim) : this.getBaseAxis();
  62294. return {
  62295. baseAxes: [baseAxis],
  62296. otherAxes: [this.getOtherAxis(baseAxis)]
  62297. };
  62298. },
  62299. /**
  62300. * Convert a single data item to (x, y) point.
  62301. * Parameter data is an array which the first element is radius and the second is angle
  62302. * @param {Array.<number>} data
  62303. * @param {boolean} [clamp=false]
  62304. * @return {Array.<number>}
  62305. */
  62306. dataToPoint: function (data, clamp) {
  62307. return this.coordToPoint([
  62308. this._radiusAxis.dataToRadius(data[0], clamp),
  62309. this._angleAxis.dataToAngle(data[1], clamp)
  62310. ]);
  62311. },
  62312. /**
  62313. * Convert a (x, y) point to data
  62314. * @param {Array.<number>} point
  62315. * @param {boolean} [clamp=false]
  62316. * @return {Array.<number>}
  62317. */
  62318. pointToData: function (point, clamp) {
  62319. var coord = this.pointToCoord(point);
  62320. return [
  62321. this._radiusAxis.radiusToData(coord[0], clamp),
  62322. this._angleAxis.angleToData(coord[1], clamp)
  62323. ];
  62324. },
  62325. /**
  62326. * Convert a (x, y) point to (radius, angle) coord
  62327. * @param {Array.<number>} point
  62328. * @return {Array.<number>}
  62329. */
  62330. pointToCoord: function (point) {
  62331. var dx = point[0] - this.cx;
  62332. var dy = point[1] - this.cy;
  62333. var angleAxis = this.getAngleAxis();
  62334. var extent = angleAxis.getExtent();
  62335. var minAngle = Math.min(extent[0], extent[1]);
  62336. var maxAngle = Math.max(extent[0], extent[1]);
  62337. // Fix fixed extent in polarCreator
  62338. // FIXME
  62339. angleAxis.inverse
  62340. ? (minAngle = maxAngle - 360)
  62341. : (maxAngle = minAngle + 360);
  62342. var radius = Math.sqrt(dx * dx + dy * dy);
  62343. dx /= radius;
  62344. dy /= radius;
  62345. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  62346. // move to angleExtent
  62347. var dir = radian < minAngle ? 1 : -1;
  62348. while (radian < minAngle || radian > maxAngle) {
  62349. radian += dir * 360;
  62350. }
  62351. return [radius, radian];
  62352. },
  62353. /**
  62354. * Convert a (radius, angle) coord to (x, y) point
  62355. * @param {Array.<number>} coord
  62356. * @return {Array.<number>}
  62357. */
  62358. coordToPoint: function (coord) {
  62359. var radius = coord[0];
  62360. var radian = coord[1] / 180 * Math.PI;
  62361. var x = Math.cos(radian) * radius + this.cx;
  62362. // Inverse the y
  62363. var y = -Math.sin(radian) * radius + this.cy;
  62364. return [x, y];
  62365. }
  62366. };
  62367. /*
  62368. * Licensed to the Apache Software Foundation (ASF) under one
  62369. * or more contributor license agreements. See the NOTICE file
  62370. * distributed with this work for additional information
  62371. * regarding copyright ownership. The ASF licenses this file
  62372. * to you under the Apache License, Version 2.0 (the
  62373. * "License"); you may not use this file except in compliance
  62374. * with the License. You may obtain a copy of the License at
  62375. *
  62376. * http://www.apache.org/licenses/LICENSE-2.0
  62377. *
  62378. * Unless required by applicable law or agreed to in writing,
  62379. * software distributed under the License is distributed on an
  62380. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62381. * KIND, either express or implied. See the License for the
  62382. * specific language governing permissions and limitations
  62383. * under the License.
  62384. */
  62385. var PolarAxisModel = ComponentModel.extend({
  62386. type: 'polarAxis',
  62387. /**
  62388. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62389. */
  62390. axis: null,
  62391. /**
  62392. * @override
  62393. */
  62394. getCoordSysModel: function () {
  62395. return this.ecModel.queryComponents({
  62396. mainType: 'polar',
  62397. index: this.option.polarIndex,
  62398. id: this.option.polarId
  62399. })[0];
  62400. }
  62401. });
  62402. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  62403. var polarAxisDefaultExtendedOption = {
  62404. angle: {
  62405. // polarIndex: 0,
  62406. // polarId: '',
  62407. startAngle: 90,
  62408. clockwise: true,
  62409. splitNumber: 12,
  62410. axisLabel: {
  62411. rotate: false
  62412. }
  62413. },
  62414. radius: {
  62415. // polarIndex: 0,
  62416. // polarId: '',
  62417. splitNumber: 5
  62418. }
  62419. };
  62420. function getAxisType$3(axisDim, option) {
  62421. // Default axis with data is category axis
  62422. return option.type || (option.data ? 'category' : 'value');
  62423. }
  62424. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  62425. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  62426. /*
  62427. * Licensed to the Apache Software Foundation (ASF) under one
  62428. * or more contributor license agreements. See the NOTICE file
  62429. * distributed with this work for additional information
  62430. * regarding copyright ownership. The ASF licenses this file
  62431. * to you under the Apache License, Version 2.0 (the
  62432. * "License"); you may not use this file except in compliance
  62433. * with the License. You may obtain a copy of the License at
  62434. *
  62435. * http://www.apache.org/licenses/LICENSE-2.0
  62436. *
  62437. * Unless required by applicable law or agreed to in writing,
  62438. * software distributed under the License is distributed on an
  62439. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62440. * KIND, either express or implied. See the License for the
  62441. * specific language governing permissions and limitations
  62442. * under the License.
  62443. */
  62444. extendComponentModel({
  62445. type: 'polar',
  62446. dependencies: ['polarAxis', 'angleAxis'],
  62447. /**
  62448. * @type {module:echarts/coord/polar/Polar}
  62449. */
  62450. coordinateSystem: null,
  62451. /**
  62452. * @param {string} axisType
  62453. * @return {module:echarts/coord/polar/AxisModel}
  62454. */
  62455. findAxisModel: function (axisType) {
  62456. var foundAxisModel;
  62457. var ecModel = this.ecModel;
  62458. ecModel.eachComponent(axisType, function (axisModel) {
  62459. if (axisModel.getCoordSysModel() === this) {
  62460. foundAxisModel = axisModel;
  62461. }
  62462. }, this);
  62463. return foundAxisModel;
  62464. },
  62465. defaultOption: {
  62466. zlevel: 0,
  62467. z: 0,
  62468. center: ['50%', '50%'],
  62469. radius: '80%'
  62470. }
  62471. });
  62472. /*
  62473. * Licensed to the Apache Software Foundation (ASF) under one
  62474. * or more contributor license agreements. See the NOTICE file
  62475. * distributed with this work for additional information
  62476. * regarding copyright ownership. The ASF licenses this file
  62477. * to you under the Apache License, Version 2.0 (the
  62478. * "License"); you may not use this file except in compliance
  62479. * with the License. You may obtain a copy of the License at
  62480. *
  62481. * http://www.apache.org/licenses/LICENSE-2.0
  62482. *
  62483. * Unless required by applicable law or agreed to in writing,
  62484. * software distributed under the License is distributed on an
  62485. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62486. * KIND, either express or implied. See the License for the
  62487. * specific language governing permissions and limitations
  62488. * under the License.
  62489. */
  62490. // TODO Axis scale
  62491. /**
  62492. * Resize method bound to the polar
  62493. * @param {module:echarts/coord/polar/PolarModel} polarModel
  62494. * @param {module:echarts/ExtensionAPI} api
  62495. */
  62496. function resizePolar(polar, polarModel, api) {
  62497. var center = polarModel.get('center');
  62498. var width = api.getWidth();
  62499. var height = api.getHeight();
  62500. polar.cx = parsePercent$1(center[0], width);
  62501. polar.cy = parsePercent$1(center[1], height);
  62502. var radiusAxis = polar.getRadiusAxis();
  62503. var size = Math.min(width, height) / 2;
  62504. var radius = parsePercent$1(polarModel.get('radius'), size);
  62505. radiusAxis.inverse
  62506. ? radiusAxis.setExtent(radius, 0)
  62507. : radiusAxis.setExtent(0, radius);
  62508. }
  62509. /**
  62510. * Update polar
  62511. */
  62512. function updatePolarScale(ecModel, api) {
  62513. var polar = this;
  62514. var angleAxis = polar.getAngleAxis();
  62515. var radiusAxis = polar.getRadiusAxis();
  62516. // Reset scale
  62517. angleAxis.scale.setExtent(Infinity, -Infinity);
  62518. radiusAxis.scale.setExtent(Infinity, -Infinity);
  62519. ecModel.eachSeries(function (seriesModel) {
  62520. if (seriesModel.coordinateSystem === polar) {
  62521. var data = seriesModel.getData();
  62522. each$1(data.mapDimension('radius', true), function (dim) {
  62523. radiusAxis.scale.unionExtentFromData(
  62524. data, getStackedDimension(data, dim)
  62525. );
  62526. });
  62527. each$1(data.mapDimension('angle', true), function (dim) {
  62528. angleAxis.scale.unionExtentFromData(
  62529. data, getStackedDimension(data, dim)
  62530. );
  62531. });
  62532. }
  62533. });
  62534. niceScaleExtent(angleAxis.scale, angleAxis.model);
  62535. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  62536. // Fix extent of category angle axis
  62537. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  62538. var extent = angleAxis.getExtent();
  62539. var diff = 360 / angleAxis.scale.count();
  62540. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  62541. angleAxis.setExtent(extent[0], extent[1]);
  62542. }
  62543. }
  62544. /**
  62545. * Set common axis properties
  62546. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62547. * @param {module:echarts/coord/polar/AxisModel}
  62548. * @inner
  62549. */
  62550. function setAxis(axis, axisModel) {
  62551. axis.type = axisModel.get('type');
  62552. axis.scale = createScaleByModel(axisModel);
  62553. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  62554. axis.inverse = axisModel.get('inverse');
  62555. if (axisModel.mainType === 'angleAxis') {
  62556. axis.inverse ^= axisModel.get('clockwise');
  62557. var startAngle = axisModel.get('startAngle');
  62558. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  62559. }
  62560. // Inject axis instance
  62561. axisModel.axis = axis;
  62562. axis.model = axisModel;
  62563. }
  62564. var polarCreator = {
  62565. dimensions: Polar.prototype.dimensions,
  62566. create: function (ecModel, api) {
  62567. var polarList = [];
  62568. ecModel.eachComponent('polar', function (polarModel, idx) {
  62569. var polar = new Polar(idx);
  62570. // Inject resize and update method
  62571. polar.update = updatePolarScale;
  62572. var radiusAxis = polar.getRadiusAxis();
  62573. var angleAxis = polar.getAngleAxis();
  62574. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  62575. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  62576. setAxis(radiusAxis, radiusAxisModel);
  62577. setAxis(angleAxis, angleAxisModel);
  62578. resizePolar(polar, polarModel, api);
  62579. polarList.push(polar);
  62580. polarModel.coordinateSystem = polar;
  62581. polar.model = polarModel;
  62582. });
  62583. // Inject coordinateSystem to series
  62584. ecModel.eachSeries(function (seriesModel) {
  62585. if (seriesModel.get('coordinateSystem') === 'polar') {
  62586. var polarModel = ecModel.queryComponents({
  62587. mainType: 'polar',
  62588. index: seriesModel.get('polarIndex'),
  62589. id: seriesModel.get('polarId')
  62590. })[0];
  62591. if (__DEV__) {
  62592. if (!polarModel) {
  62593. throw new Error(
  62594. 'Polar "' + retrieve(
  62595. seriesModel.get('polarIndex'),
  62596. seriesModel.get('polarId'),
  62597. 0
  62598. ) + '" not found'
  62599. );
  62600. }
  62601. }
  62602. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  62603. }
  62604. });
  62605. return polarList;
  62606. }
  62607. };
  62608. CoordinateSystemManager.register('polar', polarCreator);
  62609. /*
  62610. * Licensed to the Apache Software Foundation (ASF) under one
  62611. * or more contributor license agreements. See the NOTICE file
  62612. * distributed with this work for additional information
  62613. * regarding copyright ownership. The ASF licenses this file
  62614. * to you under the Apache License, Version 2.0 (the
  62615. * "License"); you may not use this file except in compliance
  62616. * with the License. You may obtain a copy of the License at
  62617. *
  62618. * http://www.apache.org/licenses/LICENSE-2.0
  62619. *
  62620. * Unless required by applicable law or agreed to in writing,
  62621. * software distributed under the License is distributed on an
  62622. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62623. * KIND, either express or implied. See the License for the
  62624. * specific language governing permissions and limitations
  62625. * under the License.
  62626. */
  62627. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  62628. function getAxisLineShape(polar, rExtent, angle) {
  62629. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  62630. var start = polar.coordToPoint([rExtent[0], angle]);
  62631. var end = polar.coordToPoint([rExtent[1], angle]);
  62632. return {
  62633. x1: start[0],
  62634. y1: start[1],
  62635. x2: end[0],
  62636. y2: end[1]
  62637. };
  62638. }
  62639. function getRadiusIdx(polar) {
  62640. var radiusAxis = polar.getRadiusAxis();
  62641. return radiusAxis.inverse ? 0 : 1;
  62642. }
  62643. // Remove the last tick which will overlap the first tick
  62644. function fixAngleOverlap(list) {
  62645. var firstItem = list[0];
  62646. var lastItem = list[list.length - 1];
  62647. if (firstItem
  62648. && lastItem
  62649. && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
  62650. ) {
  62651. list.pop();
  62652. }
  62653. }
  62654. AxisView.extend({
  62655. type: 'angleAxis',
  62656. axisPointerClass: 'PolarAxisPointer',
  62657. render: function (angleAxisModel, ecModel) {
  62658. this.group.removeAll();
  62659. if (!angleAxisModel.get('show')) {
  62660. return;
  62661. }
  62662. var angleAxis = angleAxisModel.axis;
  62663. var polar = angleAxis.polar;
  62664. var radiusExtent = polar.getRadiusAxis().getExtent();
  62665. var ticksAngles = angleAxis.getTicksCoords();
  62666. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  62667. var labelItem = clone(labelItem);
  62668. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  62669. return labelItem;
  62670. });
  62671. fixAngleOverlap(labels);
  62672. fixAngleOverlap(ticksAngles);
  62673. each$1(elementList$1, function (name) {
  62674. if (angleAxisModel.get(name +'.show')
  62675. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  62676. ) {
  62677. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent, labels);
  62678. }
  62679. }, this);
  62680. },
  62681. /**
  62682. * @private
  62683. */
  62684. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62685. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  62686. var circle = new Circle({
  62687. shape: {
  62688. cx: polar.cx,
  62689. cy: polar.cy,
  62690. r: radiusExtent[getRadiusIdx(polar)]
  62691. },
  62692. style: lineStyleModel.getLineStyle(),
  62693. z2: 1,
  62694. silent: true
  62695. });
  62696. circle.style.fill = null;
  62697. this.group.add(circle);
  62698. },
  62699. /**
  62700. * @private
  62701. */
  62702. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62703. var tickModel = angleAxisModel.getModel('axisTick');
  62704. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  62705. var radius = radiusExtent[getRadiusIdx(polar)];
  62706. var lines = map(ticksAngles, function (tickAngleItem) {
  62707. return new Line({
  62708. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  62709. });
  62710. });
  62711. this.group.add(mergePath(
  62712. lines, {
  62713. style: defaults(
  62714. tickModel.getModel('lineStyle').getLineStyle(),
  62715. {
  62716. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  62717. }
  62718. )
  62719. }
  62720. ));
  62721. },
  62722. /**
  62723. * @private
  62724. */
  62725. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent, labels) {
  62726. var rawCategoryData = angleAxisModel.getCategories(true);
  62727. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  62728. var labelMargin = commonLabelModel.get('margin');
  62729. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  62730. each$1(labels, function (labelItem, idx) {
  62731. var labelModel = commonLabelModel;
  62732. var tickValue = labelItem.tickValue;
  62733. var r = radiusExtent[getRadiusIdx(polar)];
  62734. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  62735. var cx = polar.cx;
  62736. var cy = polar.cy;
  62737. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  62738. ? 'center' : (p[0] > cx ? 'left' : 'right');
  62739. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  62740. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  62741. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  62742. labelModel = new Model(rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel);
  62743. }
  62744. var textEl = new Text({silent: true});
  62745. this.group.add(textEl);
  62746. setTextStyle(textEl.style, labelModel, {
  62747. x: p[0],
  62748. y: p[1],
  62749. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  62750. text: labelItem.formattedLabel,
  62751. textAlign: labelTextAlign,
  62752. textVerticalAlign: labelTextVerticalAlign
  62753. });
  62754. }, this);
  62755. },
  62756. /**
  62757. * @private
  62758. */
  62759. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62760. var splitLineModel = angleAxisModel.getModel('splitLine');
  62761. var lineStyleModel = splitLineModel.getModel('lineStyle');
  62762. var lineColors = lineStyleModel.get('color');
  62763. var lineCount = 0;
  62764. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  62765. var splitLines = [];
  62766. for (var i = 0; i < ticksAngles.length; i++) {
  62767. var colorIndex = (lineCount++) % lineColors.length;
  62768. splitLines[colorIndex] = splitLines[colorIndex] || [];
  62769. splitLines[colorIndex].push(new Line({
  62770. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  62771. }));
  62772. }
  62773. // Simple optimization
  62774. // Batching the lines if color are the same
  62775. for (var i = 0; i < splitLines.length; i++) {
  62776. this.group.add(mergePath(splitLines[i], {
  62777. style: defaults({
  62778. stroke: lineColors[i % lineColors.length]
  62779. }, lineStyleModel.getLineStyle()),
  62780. silent: true,
  62781. z: angleAxisModel.get('z')
  62782. }));
  62783. }
  62784. },
  62785. /**
  62786. * @private
  62787. */
  62788. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62789. if (!ticksAngles.length) {
  62790. return;
  62791. }
  62792. var splitAreaModel = angleAxisModel.getModel('splitArea');
  62793. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  62794. var areaColors = areaStyleModel.get('color');
  62795. var lineCount = 0;
  62796. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  62797. var splitAreas = [];
  62798. var RADIAN = Math.PI / 180;
  62799. var prevAngle = -ticksAngles[0].coord * RADIAN;
  62800. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  62801. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  62802. var clockwise = angleAxisModel.get('clockwise');
  62803. for (var i = 1; i < ticksAngles.length; i++) {
  62804. var colorIndex = (lineCount++) % areaColors.length;
  62805. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  62806. splitAreas[colorIndex].push(new Sector({
  62807. shape: {
  62808. cx: polar.cx,
  62809. cy: polar.cy,
  62810. r0: r0,
  62811. r: r1,
  62812. startAngle: prevAngle,
  62813. endAngle: -ticksAngles[i].coord * RADIAN,
  62814. clockwise: clockwise
  62815. },
  62816. silent: true
  62817. }));
  62818. prevAngle = -ticksAngles[i].coord * RADIAN;
  62819. }
  62820. // Simple optimization
  62821. // Batching the lines if color are the same
  62822. for (var i = 0; i < splitAreas.length; i++) {
  62823. this.group.add(mergePath(splitAreas[i], {
  62824. style: defaults({
  62825. fill: areaColors[i % areaColors.length]
  62826. }, areaStyleModel.getAreaStyle()),
  62827. silent: true
  62828. }));
  62829. }
  62830. }
  62831. });
  62832. /*
  62833. * Licensed to the Apache Software Foundation (ASF) under one
  62834. * or more contributor license agreements. See the NOTICE file
  62835. * distributed with this work for additional information
  62836. * regarding copyright ownership. The ASF licenses this file
  62837. * to you under the Apache License, Version 2.0 (the
  62838. * "License"); you may not use this file except in compliance
  62839. * with the License. You may obtain a copy of the License at
  62840. *
  62841. * http://www.apache.org/licenses/LICENSE-2.0
  62842. *
  62843. * Unless required by applicable law or agreed to in writing,
  62844. * software distributed under the License is distributed on an
  62845. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62846. * KIND, either express or implied. See the License for the
  62847. * specific language governing permissions and limitations
  62848. * under the License.
  62849. */
  62850. /*
  62851. * Licensed to the Apache Software Foundation (ASF) under one
  62852. * or more contributor license agreements. See the NOTICE file
  62853. * distributed with this work for additional information
  62854. * regarding copyright ownership. The ASF licenses this file
  62855. * to you under the Apache License, Version 2.0 (the
  62856. * "License"); you may not use this file except in compliance
  62857. * with the License. You may obtain a copy of the License at
  62858. *
  62859. * http://www.apache.org/licenses/LICENSE-2.0
  62860. *
  62861. * Unless required by applicable law or agreed to in writing,
  62862. * software distributed under the License is distributed on an
  62863. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62864. * KIND, either express or implied. See the License for the
  62865. * specific language governing permissions and limitations
  62866. * under the License.
  62867. */
  62868. var axisBuilderAttrs$3 = [
  62869. 'axisLine', 'axisTickLabel', 'axisName'
  62870. ];
  62871. var selfBuilderAttrs$1 = [
  62872. 'splitLine', 'splitArea'
  62873. ];
  62874. AxisView.extend({
  62875. type: 'radiusAxis',
  62876. axisPointerClass: 'PolarAxisPointer',
  62877. render: function (radiusAxisModel, ecModel) {
  62878. this.group.removeAll();
  62879. if (!radiusAxisModel.get('show')) {
  62880. return;
  62881. }
  62882. var radiusAxis = radiusAxisModel.axis;
  62883. var polar = radiusAxis.polar;
  62884. var angleAxis = polar.getAngleAxis();
  62885. var ticksCoords = radiusAxis.getTicksCoords();
  62886. var axisAngle = angleAxis.getExtent()[0];
  62887. var radiusExtent = radiusAxis.getExtent();
  62888. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  62889. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  62890. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  62891. this.group.add(axisBuilder.getGroup());
  62892. each$1(selfBuilderAttrs$1, function (name) {
  62893. if (radiusAxisModel.get(name +'.show') && !radiusAxis.scale.isBlank()) {
  62894. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  62895. }
  62896. }, this);
  62897. },
  62898. /**
  62899. * @private
  62900. */
  62901. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  62902. var splitLineModel = radiusAxisModel.getModel('splitLine');
  62903. var lineStyleModel = splitLineModel.getModel('lineStyle');
  62904. var lineColors = lineStyleModel.get('color');
  62905. var lineCount = 0;
  62906. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  62907. var splitLines = [];
  62908. for (var i = 0; i < ticksCoords.length; i++) {
  62909. var colorIndex = (lineCount++) % lineColors.length;
  62910. splitLines[colorIndex] = splitLines[colorIndex] || [];
  62911. splitLines[colorIndex].push(new Circle({
  62912. shape: {
  62913. cx: polar.cx,
  62914. cy: polar.cy,
  62915. r: ticksCoords[i].coord
  62916. },
  62917. silent: true
  62918. }));
  62919. }
  62920. // Simple optimization
  62921. // Batching the lines if color are the same
  62922. for (var i = 0; i < splitLines.length; i++) {
  62923. this.group.add(mergePath(splitLines[i], {
  62924. style: defaults({
  62925. stroke: lineColors[i % lineColors.length],
  62926. fill: null
  62927. }, lineStyleModel.getLineStyle()),
  62928. silent: true
  62929. }));
  62930. }
  62931. },
  62932. /**
  62933. * @private
  62934. */
  62935. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  62936. if (!ticksCoords.length) {
  62937. return;
  62938. }
  62939. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  62940. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  62941. var areaColors = areaStyleModel.get('color');
  62942. var lineCount = 0;
  62943. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  62944. var splitAreas = [];
  62945. var prevRadius = ticksCoords[0].coord;
  62946. for (var i = 1; i < ticksCoords.length; i++) {
  62947. var colorIndex = (lineCount++) % areaColors.length;
  62948. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  62949. splitAreas[colorIndex].push(new Sector({
  62950. shape: {
  62951. cx: polar.cx,
  62952. cy: polar.cy,
  62953. r0: prevRadius,
  62954. r: ticksCoords[i].coord,
  62955. startAngle: 0,
  62956. endAngle: Math.PI * 2
  62957. },
  62958. silent: true
  62959. }));
  62960. prevRadius = ticksCoords[i].coord;
  62961. }
  62962. // Simple optimization
  62963. // Batching the lines if color are the same
  62964. for (var i = 0; i < splitAreas.length; i++) {
  62965. this.group.add(mergePath(splitAreas[i], {
  62966. style: defaults({
  62967. fill: areaColors[i % areaColors.length]
  62968. }, areaStyleModel.getAreaStyle()),
  62969. silent: true
  62970. }));
  62971. }
  62972. }
  62973. });
  62974. /**
  62975. * @inner
  62976. */
  62977. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  62978. return {
  62979. position: [polar.cx, polar.cy],
  62980. rotation: axisAngle / 180 * Math.PI,
  62981. labelDirection: -1,
  62982. tickDirection: -1,
  62983. nameDirection: 1,
  62984. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  62985. // Over splitLine and splitArea
  62986. z2: 1
  62987. };
  62988. }
  62989. /*
  62990. * Licensed to the Apache Software Foundation (ASF) under one
  62991. * or more contributor license agreements. See the NOTICE file
  62992. * distributed with this work for additional information
  62993. * regarding copyright ownership. The ASF licenses this file
  62994. * to you under the Apache License, Version 2.0 (the
  62995. * "License"); you may not use this file except in compliance
  62996. * with the License. You may obtain a copy of the License at
  62997. *
  62998. * http://www.apache.org/licenses/LICENSE-2.0
  62999. *
  63000. * Unless required by applicable law or agreed to in writing,
  63001. * software distributed under the License is distributed on an
  63002. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63003. * KIND, either express or implied. See the License for the
  63004. * specific language governing permissions and limitations
  63005. * under the License.
  63006. */
  63007. /*
  63008. * Licensed to the Apache Software Foundation (ASF) under one
  63009. * or more contributor license agreements. See the NOTICE file
  63010. * distributed with this work for additional information
  63011. * regarding copyright ownership. The ASF licenses this file
  63012. * to you under the Apache License, Version 2.0 (the
  63013. * "License"); you may not use this file except in compliance
  63014. * with the License. You may obtain a copy of the License at
  63015. *
  63016. * http://www.apache.org/licenses/LICENSE-2.0
  63017. *
  63018. * Unless required by applicable law or agreed to in writing,
  63019. * software distributed under the License is distributed on an
  63020. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63021. * KIND, either express or implied. See the License for the
  63022. * specific language governing permissions and limitations
  63023. * under the License.
  63024. */
  63025. var PolarAxisPointer = BaseAxisPointer.extend({
  63026. /**
  63027. * @override
  63028. */
  63029. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  63030. var axis = axisModel.axis;
  63031. if (axis.dim === 'angle') {
  63032. this.animationThreshold = Math.PI / 18;
  63033. }
  63034. var polar = axis.polar;
  63035. var otherAxis = polar.getOtherAxis(axis);
  63036. var otherExtent = otherAxis.getExtent();
  63037. var coordValue;
  63038. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  63039. var axisPointerType = axisPointerModel.get('type');
  63040. if (axisPointerType && axisPointerType !== 'none') {
  63041. var elStyle = buildElStyle(axisPointerModel);
  63042. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  63043. axis, polar, coordValue, otherExtent, elStyle
  63044. );
  63045. pointerOption.style = elStyle;
  63046. elOption.graphicKey = pointerOption.type;
  63047. elOption.pointer = pointerOption;
  63048. }
  63049. var labelMargin = axisPointerModel.get('label.margin');
  63050. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  63051. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  63052. }
  63053. // Do not support handle, utill any user requires it.
  63054. });
  63055. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  63056. var axis = axisModel.axis;
  63057. var coord = axis.dataToCoord(value);
  63058. var axisAngle = polar.getAngleAxis().getExtent()[0];
  63059. axisAngle = axisAngle / 180 * Math.PI;
  63060. var radiusExtent = polar.getRadiusAxis().getExtent();
  63061. var position;
  63062. var align;
  63063. var verticalAlign;
  63064. if (axis.dim === 'radius') {
  63065. var transform = create$1();
  63066. rotate(transform, transform, axisAngle);
  63067. translate(transform, transform, [polar.cx, polar.cy]);
  63068. position = applyTransform$1([coord, -labelMargin], transform);
  63069. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  63070. var labelLayout = AxisBuilder.innerTextLayout(
  63071. axisAngle, labelRotation * Math.PI / 180, -1
  63072. );
  63073. align = labelLayout.textAlign;
  63074. verticalAlign = labelLayout.textVerticalAlign;
  63075. }
  63076. else { // angle axis
  63077. var r = radiusExtent[1];
  63078. position = polar.coordToPoint([r + labelMargin, coord]);
  63079. var cx = polar.cx;
  63080. var cy = polar.cy;
  63081. align = Math.abs(position[0] - cx) / r < 0.3
  63082. ? 'center' : (position[0] > cx ? 'left' : 'right');
  63083. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  63084. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  63085. }
  63086. return {
  63087. position: position,
  63088. align: align,
  63089. verticalAlign: verticalAlign
  63090. };
  63091. }
  63092. var pointerShapeBuilder$2 = {
  63093. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  63094. return axis.dim === 'angle'
  63095. ? {
  63096. type: 'Line',
  63097. shape: makeLineShape(
  63098. polar.coordToPoint([otherExtent[0], coordValue]),
  63099. polar.coordToPoint([otherExtent[1], coordValue])
  63100. )
  63101. }
  63102. : {
  63103. type: 'Circle',
  63104. shape: {
  63105. cx: polar.cx,
  63106. cy: polar.cy,
  63107. r: coordValue
  63108. }
  63109. };
  63110. },
  63111. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  63112. var bandWidth = Math.max(1, axis.getBandWidth());
  63113. var radian = Math.PI / 180;
  63114. return axis.dim === 'angle'
  63115. ? {
  63116. type: 'Sector',
  63117. shape: makeSectorShape(
  63118. polar.cx, polar.cy,
  63119. otherExtent[0], otherExtent[1],
  63120. // In ECharts y is negative if angle is positive
  63121. (-coordValue - bandWidth / 2) * radian,
  63122. (-coordValue + bandWidth / 2) * radian
  63123. )
  63124. }
  63125. : {
  63126. type: 'Sector',
  63127. shape: makeSectorShape(
  63128. polar.cx, polar.cy,
  63129. coordValue - bandWidth / 2,
  63130. coordValue + bandWidth / 2,
  63131. 0, Math.PI * 2
  63132. )
  63133. };
  63134. }
  63135. };
  63136. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  63137. /*
  63138. * Licensed to the Apache Software Foundation (ASF) under one
  63139. * or more contributor license agreements. See the NOTICE file
  63140. * distributed with this work for additional information
  63141. * regarding copyright ownership. The ASF licenses this file
  63142. * to you under the Apache License, Version 2.0 (the
  63143. * "License"); you may not use this file except in compliance
  63144. * with the License. You may obtain a copy of the License at
  63145. *
  63146. * http://www.apache.org/licenses/LICENSE-2.0
  63147. *
  63148. * Unless required by applicable law or agreed to in writing,
  63149. * software distributed under the License is distributed on an
  63150. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63151. * KIND, either express or implied. See the License for the
  63152. * specific language governing permissions and limitations
  63153. * under the License.
  63154. */
  63155. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  63156. registerLayout(curry(barLayoutPolar, 'bar'));
  63157. // Polar view
  63158. extendComponentView({
  63159. type: 'polar'
  63160. });
  63161. /*
  63162. * Licensed to the Apache Software Foundation (ASF) under one
  63163. * or more contributor license agreements. See the NOTICE file
  63164. * distributed with this work for additional information
  63165. * regarding copyright ownership. The ASF licenses this file
  63166. * to you under the Apache License, Version 2.0 (the
  63167. * "License"); you may not use this file except in compliance
  63168. * with the License. You may obtain a copy of the License at
  63169. *
  63170. * http://www.apache.org/licenses/LICENSE-2.0
  63171. *
  63172. * Unless required by applicable law or agreed to in writing,
  63173. * software distributed under the License is distributed on an
  63174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63175. * KIND, either express or implied. See the License for the
  63176. * specific language governing permissions and limitations
  63177. * under the License.
  63178. */
  63179. var GeoModel = ComponentModel.extend({
  63180. type: 'geo',
  63181. /**
  63182. * @type {module:echarts/coord/geo/Geo}
  63183. */
  63184. coordinateSystem: null,
  63185. layoutMode: 'box',
  63186. init: function (option) {
  63187. ComponentModel.prototype.init.apply(this, arguments);
  63188. // Default label emphasis `show`
  63189. defaultEmphasis(option, 'label', ['show']);
  63190. },
  63191. optionUpdated: function () {
  63192. var option = this.option;
  63193. var self = this;
  63194. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  63195. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  63196. if (regionOpt.name) {
  63197. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  63198. }
  63199. return optionModelMap;
  63200. }, createHashMap());
  63201. this.updateSelectedMap(option.regions);
  63202. },
  63203. defaultOption: {
  63204. zlevel: 0,
  63205. z: 0,
  63206. show: true,
  63207. left: 'center',
  63208. top: 'center',
  63209. // width:,
  63210. // height:,
  63211. // right
  63212. // bottom
  63213. // Aspect is width / height. Inited to be geoJson bbox aspect
  63214. // This parameter is used for scale this aspect
  63215. aspectScale: 0.75,
  63216. ///// Layout with center and size
  63217. // If you wan't to put map in a fixed size box with right aspect ratio
  63218. // This two properties may more conveninet
  63219. // layoutCenter: [50%, 50%]
  63220. // layoutSize: 100
  63221. silent: false,
  63222. // Map type
  63223. map: '',
  63224. // Define left-top, right-bottom coords to control view
  63225. // For example, [ [180, 90], [-180, -90] ]
  63226. boundingCoords: null,
  63227. // Default on center of map
  63228. center: null,
  63229. zoom: 1,
  63230. scaleLimit: null,
  63231. // selectedMode: false
  63232. label: {
  63233. show: false,
  63234. color: '#000'
  63235. },
  63236. itemStyle: {
  63237. // color: 各异,
  63238. borderWidth: 0.5,
  63239. borderColor: '#444',
  63240. color: '#eee'
  63241. },
  63242. emphasis: {
  63243. label: {
  63244. show: true,
  63245. color: 'rgb(100,0,0)'
  63246. },
  63247. itemStyle: {
  63248. color: 'rgba(255,215,0,0.8)'
  63249. }
  63250. },
  63251. regions: []
  63252. },
  63253. /**
  63254. * Get model of region
  63255. * @param {string} name
  63256. * @return {module:echarts/model/Model}
  63257. */
  63258. getRegionModel: function (name) {
  63259. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  63260. },
  63261. /**
  63262. * Format label
  63263. * @param {string} name Region name
  63264. * @param {string} [status='normal'] 'normal' or 'emphasis'
  63265. * @return {string}
  63266. */
  63267. getFormattedLabel: function (name, status) {
  63268. var regionModel = this.getRegionModel(name);
  63269. var formatter = regionModel.get('label.' + status + '.formatter');
  63270. var params = {
  63271. name: name
  63272. };
  63273. if (typeof formatter === 'function') {
  63274. params.status = status;
  63275. return formatter(params);
  63276. }
  63277. else if (typeof formatter === 'string') {
  63278. return formatter.replace('{a}', name != null ? name : '');
  63279. }
  63280. },
  63281. setZoom: function (zoom) {
  63282. this.option.zoom = zoom;
  63283. },
  63284. setCenter: function (center) {
  63285. this.option.center = center;
  63286. }
  63287. });
  63288. mixin(GeoModel, selectableMixin);
  63289. /*
  63290. * Licensed to the Apache Software Foundation (ASF) under one
  63291. * or more contributor license agreements. See the NOTICE file
  63292. * distributed with this work for additional information
  63293. * regarding copyright ownership. The ASF licenses this file
  63294. * to you under the Apache License, Version 2.0 (the
  63295. * "License"); you may not use this file except in compliance
  63296. * with the License. You may obtain a copy of the License at
  63297. *
  63298. * http://www.apache.org/licenses/LICENSE-2.0
  63299. *
  63300. * Unless required by applicable law or agreed to in writing,
  63301. * software distributed under the License is distributed on an
  63302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63303. * KIND, either express or implied. See the License for the
  63304. * specific language governing permissions and limitations
  63305. * under the License.
  63306. */
  63307. extendComponentView({
  63308. type: 'geo',
  63309. init: function (ecModel, api) {
  63310. var mapDraw = new MapDraw(api, true);
  63311. this._mapDraw = mapDraw;
  63312. this.group.add(mapDraw.group);
  63313. },
  63314. render: function (geoModel, ecModel, api, payload) {
  63315. // Not render if it is an toggleSelect action from self
  63316. if (payload && payload.type === 'geoToggleSelect'
  63317. && payload.from === this.uid
  63318. ) {
  63319. return;
  63320. }
  63321. var mapDraw = this._mapDraw;
  63322. if (geoModel.get('show')) {
  63323. mapDraw.draw(geoModel, ecModel, api, this, payload);
  63324. }
  63325. else {
  63326. this._mapDraw.group.removeAll();
  63327. }
  63328. this.group.silent = geoModel.get('silent');
  63329. },
  63330. dispose: function () {
  63331. this._mapDraw && this._mapDraw.remove();
  63332. }
  63333. });
  63334. /*
  63335. * Licensed to the Apache Software Foundation (ASF) under one
  63336. * or more contributor license agreements. See the NOTICE file
  63337. * distributed with this work for additional information
  63338. * regarding copyright ownership. The ASF licenses this file
  63339. * to you under the Apache License, Version 2.0 (the
  63340. * "License"); you may not use this file except in compliance
  63341. * with the License. You may obtain a copy of the License at
  63342. *
  63343. * http://www.apache.org/licenses/LICENSE-2.0
  63344. *
  63345. * Unless required by applicable law or agreed to in writing,
  63346. * software distributed under the License is distributed on an
  63347. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63348. * KIND, either express or implied. See the License for the
  63349. * specific language governing permissions and limitations
  63350. * under the License.
  63351. */
  63352. function makeAction(method, actionInfo) {
  63353. actionInfo.update = 'updateView';
  63354. registerAction(actionInfo, function (payload, ecModel) {
  63355. var selected = {};
  63356. ecModel.eachComponent(
  63357. { mainType: 'geo', query: payload},
  63358. function (geoModel) {
  63359. geoModel[method](payload.name);
  63360. var geo = geoModel.coordinateSystem;
  63361. each$1(geo.regions, function (region) {
  63362. selected[region.name] = geoModel.isSelected(region.name) || false;
  63363. });
  63364. }
  63365. );
  63366. return {
  63367. selected: selected,
  63368. name: payload.name
  63369. };
  63370. });
  63371. }
  63372. makeAction('toggleSelected', {
  63373. type: 'geoToggleSelect',
  63374. event: 'geoselectchanged'
  63375. });
  63376. makeAction('select', {
  63377. type: 'geoSelect',
  63378. event: 'geoselected'
  63379. });
  63380. makeAction('unSelect', {
  63381. type: 'geoUnSelect',
  63382. event: 'geounselected'
  63383. });
  63384. /*
  63385. * Licensed to the Apache Software Foundation (ASF) under one
  63386. * or more contributor license agreements. See the NOTICE file
  63387. * distributed with this work for additional information
  63388. * regarding copyright ownership. The ASF licenses this file
  63389. * to you under the Apache License, Version 2.0 (the
  63390. * "License"); you may not use this file except in compliance
  63391. * with the License. You may obtain a copy of the License at
  63392. *
  63393. * http://www.apache.org/licenses/LICENSE-2.0
  63394. *
  63395. * Unless required by applicable law or agreed to in writing,
  63396. * software distributed under the License is distributed on an
  63397. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63398. * KIND, either express or implied. See the License for the
  63399. * specific language governing permissions and limitations
  63400. * under the License.
  63401. */
  63402. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  63403. var preprocessor$1 = function (option, isNew) {
  63404. var brushComponents = option && option.brush;
  63405. if (!isArray(brushComponents)) {
  63406. brushComponents = brushComponents ? [brushComponents] : [];
  63407. }
  63408. if (!brushComponents.length) {
  63409. return;
  63410. }
  63411. var brushComponentSpecifiedBtns = [];
  63412. each$1(brushComponents, function (brushOpt) {
  63413. var tbs = brushOpt.hasOwnProperty('toolbox')
  63414. ? brushOpt.toolbox : [];
  63415. if (tbs instanceof Array) {
  63416. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  63417. }
  63418. });
  63419. var toolbox = option && option.toolbox;
  63420. if (isArray(toolbox)) {
  63421. toolbox = toolbox[0];
  63422. }
  63423. if (!toolbox) {
  63424. toolbox = {feature: {}};
  63425. option.toolbox = [toolbox];
  63426. }
  63427. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  63428. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  63429. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  63430. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  63431. removeDuplicate(brushTypes);
  63432. if (isNew && !brushTypes.length) {
  63433. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  63434. }
  63435. };
  63436. function removeDuplicate(arr) {
  63437. var map$$1 = {};
  63438. each$1(arr, function (val) {
  63439. map$$1[val] = 1;
  63440. });
  63441. arr.length = 0;
  63442. each$1(map$$1, function (flag, val) {
  63443. arr.push(val);
  63444. });
  63445. }
  63446. /*
  63447. * Licensed to the Apache Software Foundation (ASF) under one
  63448. * or more contributor license agreements. See the NOTICE file
  63449. * distributed with this work for additional information
  63450. * regarding copyright ownership. The ASF licenses this file
  63451. * to you under the Apache License, Version 2.0 (the
  63452. * "License"); you may not use this file except in compliance
  63453. * with the License. You may obtain a copy of the License at
  63454. *
  63455. * http://www.apache.org/licenses/LICENSE-2.0
  63456. *
  63457. * Unless required by applicable law or agreed to in writing,
  63458. * software distributed under the License is distributed on an
  63459. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63460. * KIND, either express or implied. See the License for the
  63461. * specific language governing permissions and limitations
  63462. * under the License.
  63463. */
  63464. /**
  63465. * @file Visual solution, for consistent option specification.
  63466. */
  63467. var each$19 = each$1;
  63468. function hasKeys(obj) {
  63469. if (obj) {
  63470. for (var name in obj){
  63471. if (obj.hasOwnProperty(name)) {
  63472. return true;
  63473. }
  63474. }
  63475. }
  63476. }
  63477. /**
  63478. * @param {Object} option
  63479. * @param {Array.<string>} stateList
  63480. * @param {Function} [supplementVisualOption]
  63481. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  63482. */
  63483. function createVisualMappings(option, stateList, supplementVisualOption) {
  63484. var visualMappings = {};
  63485. each$19(stateList, function (state) {
  63486. var mappings = visualMappings[state] = createMappings();
  63487. each$19(option[state], function (visualData, visualType) {
  63488. if (!VisualMapping.isValidType(visualType)) {
  63489. return;
  63490. }
  63491. var mappingOption = {
  63492. type: visualType,
  63493. visual: visualData
  63494. };
  63495. supplementVisualOption && supplementVisualOption(mappingOption, state);
  63496. mappings[visualType] = new VisualMapping(mappingOption);
  63497. // Prepare a alpha for opacity, for some case that opacity
  63498. // is not supported, such as rendering using gradient color.
  63499. if (visualType === 'opacity') {
  63500. mappingOption = clone(mappingOption);
  63501. mappingOption.type = 'colorAlpha';
  63502. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  63503. }
  63504. });
  63505. });
  63506. return visualMappings;
  63507. function createMappings() {
  63508. var Creater = function () {};
  63509. // Make sure hidden fields will not be visited by
  63510. // object iteration (with hasOwnProperty checking).
  63511. Creater.prototype.__hidden = Creater.prototype;
  63512. var obj = new Creater();
  63513. return obj;
  63514. }
  63515. }
  63516. /**
  63517. * @param {Object} thisOption
  63518. * @param {Object} newOption
  63519. * @param {Array.<string>} keys
  63520. */
  63521. function replaceVisualOption(thisOption, newOption, keys) {
  63522. // Visual attributes merge is not supported, otherwise it
  63523. // brings overcomplicated merge logic. See #2853. So if
  63524. // newOption has anyone of these keys, all of these keys
  63525. // will be reset. Otherwise, all keys remain.
  63526. var has;
  63527. each$1(keys, function (key) {
  63528. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  63529. has = true;
  63530. }
  63531. });
  63532. has && each$1(keys, function (key) {
  63533. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  63534. thisOption[key] = clone(newOption[key]);
  63535. }
  63536. else {
  63537. delete thisOption[key];
  63538. }
  63539. });
  63540. }
  63541. /**
  63542. * @param {Array.<string>} stateList
  63543. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  63544. * @param {module:echarts/data/List} list
  63545. * @param {Function} getValueState param: valueOrIndex, return: state.
  63546. * @param {object} [scope] Scope for getValueState
  63547. * @param {string} [dimension] Concrete dimension, if used.
  63548. */
  63549. // ???! handle brush?
  63550. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  63551. var visualTypesMap = {};
  63552. each$1(stateList, function (state) {
  63553. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  63554. visualTypesMap[state] = visualTypes;
  63555. });
  63556. var dataIndex;
  63557. function getVisual(key) {
  63558. return data.getItemVisual(dataIndex, key);
  63559. }
  63560. function setVisual(key, value) {
  63561. data.setItemVisual(dataIndex, key, value);
  63562. }
  63563. if (dimension == null) {
  63564. data.each(eachItem);
  63565. }
  63566. else {
  63567. data.each([dimension], eachItem);
  63568. }
  63569. function eachItem(valueOrIndex, index) {
  63570. dataIndex = dimension == null ? valueOrIndex : index;
  63571. var rawDataItem = data.getRawDataItem(dataIndex);
  63572. // Consider performance
  63573. if (rawDataItem && rawDataItem.visualMap === false) {
  63574. return;
  63575. }
  63576. var valueState = getValueState.call(scope, valueOrIndex);
  63577. var mappings = visualMappings[valueState];
  63578. var visualTypes = visualTypesMap[valueState];
  63579. for (var i = 0, len = visualTypes.length; i < len; i++) {
  63580. var type = visualTypes[i];
  63581. mappings[type] && mappings[type].applyVisual(
  63582. valueOrIndex, getVisual, setVisual
  63583. );
  63584. }
  63585. }
  63586. }
  63587. /**
  63588. * @param {module:echarts/data/List} data
  63589. * @param {Array.<string>} stateList
  63590. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  63591. * @param {Function} getValueState param: valueOrIndex, return: state.
  63592. * @param {number} [dim] dimension or dimension index.
  63593. */
  63594. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  63595. var visualTypesMap = {};
  63596. each$1(stateList, function (state) {
  63597. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  63598. visualTypesMap[state] = visualTypes;
  63599. });
  63600. function progress(params, data) {
  63601. if (dim != null) {
  63602. dim = data.getDimension(dim);
  63603. }
  63604. function getVisual(key) {
  63605. return data.getItemVisual(dataIndex, key);
  63606. }
  63607. function setVisual(key, value) {
  63608. data.setItemVisual(dataIndex, key, value);
  63609. }
  63610. var dataIndex;
  63611. while ((dataIndex = params.next()) != null) {
  63612. var rawDataItem = data.getRawDataItem(dataIndex);
  63613. // Consider performance
  63614. if (rawDataItem && rawDataItem.visualMap === false) {
  63615. return;
  63616. }
  63617. var value = dim != null
  63618. ? data.get(dim, dataIndex, true)
  63619. : dataIndex;
  63620. var valueState = getValueState(value);
  63621. var mappings = visualMappings[valueState];
  63622. var visualTypes = visualTypesMap[valueState];
  63623. for (var i = 0, len = visualTypes.length; i < len; i++) {
  63624. var type = visualTypes[i];
  63625. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  63626. }
  63627. }
  63628. }
  63629. return {progress: progress};
  63630. }
  63631. /*
  63632. * Licensed to the Apache Software Foundation (ASF) under one
  63633. * or more contributor license agreements. See the NOTICE file
  63634. * distributed with this work for additional information
  63635. * regarding copyright ownership. The ASF licenses this file
  63636. * to you under the Apache License, Version 2.0 (the
  63637. * "License"); you may not use this file except in compliance
  63638. * with the License. You may obtain a copy of the License at
  63639. *
  63640. * http://www.apache.org/licenses/LICENSE-2.0
  63641. *
  63642. * Unless required by applicable law or agreed to in writing,
  63643. * software distributed under the License is distributed on an
  63644. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63645. * KIND, either express or implied. See the License for the
  63646. * specific language governing permissions and limitations
  63647. * under the License.
  63648. */
  63649. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  63650. // Key of the second level is chart element type: `point`, `rect`.
  63651. // See moudule:echarts/component/helper/BrushController
  63652. // function param:
  63653. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  63654. // {Object} selectors {point: selector, rect: selector, ...}
  63655. // {Object} area {range: [[], [], ..], boudingRect}
  63656. // function return:
  63657. // {boolean} Whether in the given brush.
  63658. var selector = {
  63659. lineX: getLineSelectors(0),
  63660. lineY: getLineSelectors(1),
  63661. rect: {
  63662. point: function (itemLayout, selectors, area) {
  63663. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  63664. },
  63665. rect: function (itemLayout, selectors, area) {
  63666. return itemLayout && area.boundingRect.intersect(itemLayout);
  63667. }
  63668. },
  63669. polygon: {
  63670. point: function (itemLayout, selectors, area) {
  63671. return itemLayout
  63672. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  63673. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  63674. },
  63675. rect: function (itemLayout, selectors, area) {
  63676. var points = area.range;
  63677. if (!itemLayout || points.length <= 1) {
  63678. return false;
  63679. }
  63680. var x = itemLayout.x;
  63681. var y = itemLayout.y;
  63682. var width = itemLayout.width;
  63683. var height = itemLayout.height;
  63684. var p = points[0];
  63685. if (contain$1(points, x, y)
  63686. || contain$1(points, x + width, y)
  63687. || contain$1(points, x, y + height)
  63688. || contain$1(points, x + width, y + height)
  63689. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  63690. || lineIntersectPolygon(x, y, x + width, y, points)
  63691. || lineIntersectPolygon(x, y, x, y + height, points)
  63692. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  63693. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  63694. ) {
  63695. return true;
  63696. }
  63697. }
  63698. }
  63699. };
  63700. function getLineSelectors(xyIndex) {
  63701. var xy = ['x', 'y'];
  63702. var wh = ['width', 'height'];
  63703. return {
  63704. point: function (itemLayout, selectors, area) {
  63705. if (itemLayout) {
  63706. var range = area.range;
  63707. var p = itemLayout[xyIndex];
  63708. return inLineRange(p, range);
  63709. }
  63710. },
  63711. rect: function (itemLayout, selectors, area) {
  63712. if (itemLayout) {
  63713. var range = area.range;
  63714. var layoutRange = [
  63715. itemLayout[xy[xyIndex]],
  63716. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  63717. ];
  63718. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  63719. return inLineRange(layoutRange[0], range)
  63720. || inLineRange(layoutRange[1], range)
  63721. || inLineRange(range[0], layoutRange)
  63722. || inLineRange(range[1], layoutRange);
  63723. }
  63724. }
  63725. };
  63726. }
  63727. function inLineRange(p, range) {
  63728. return range[0] <= p && p <= range[1];
  63729. }
  63730. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  63731. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  63732. var p = points[i];
  63733. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  63734. return true;
  63735. }
  63736. p2 = p;
  63737. }
  63738. }
  63739. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  63740. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  63741. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  63742. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  63743. if (nearZero(delta)) { // parallel
  63744. return false;
  63745. }
  63746. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  63747. if (namenda < 0 || namenda > 1) {
  63748. return false;
  63749. }
  63750. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  63751. if (miu < 0 || miu > 1) {
  63752. return false;
  63753. }
  63754. return true;
  63755. }
  63756. function nearZero(val) {
  63757. return val <= (1e-6) && val >= -(1e-6);
  63758. }
  63759. function determinant(v1, v2, v3, v4) {
  63760. return v1 * v4 - v2 * v3;
  63761. }
  63762. /*
  63763. * Licensed to the Apache Software Foundation (ASF) under one
  63764. * or more contributor license agreements. See the NOTICE file
  63765. * distributed with this work for additional information
  63766. * regarding copyright ownership. The ASF licenses this file
  63767. * to you under the Apache License, Version 2.0 (the
  63768. * "License"); you may not use this file except in compliance
  63769. * with the License. You may obtain a copy of the License at
  63770. *
  63771. * http://www.apache.org/licenses/LICENSE-2.0
  63772. *
  63773. * Unless required by applicable law or agreed to in writing,
  63774. * software distributed under the License is distributed on an
  63775. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63776. * KIND, either express or implied. See the License for the
  63777. * specific language governing permissions and limitations
  63778. * under the License.
  63779. */
  63780. var each$20 = each$1;
  63781. var indexOf$1 = indexOf;
  63782. var curry$5 = curry;
  63783. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  63784. // FIXME
  63785. // how to genarialize to more coordinate systems.
  63786. var INCLUDE_FINDER_MAIN_TYPES = [
  63787. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  63788. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  63789. ];
  63790. /**
  63791. * [option in constructor]:
  63792. * {
  63793. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  63794. * }
  63795. *
  63796. *
  63797. * [targetInfo]:
  63798. *
  63799. * There can be multiple axes in a single targetInfo. Consider the case
  63800. * of `grid` component, a targetInfo represents a grid which contains one or more
  63801. * cartesian and one or more axes. And consider the case of parallel system,
  63802. * which has multiple axes in a coordinate system.
  63803. * Can be {
  63804. * panelId: ...,
  63805. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  63806. * coordSyses: all cartesians.
  63807. * gridModel: <grid component>
  63808. * xAxes: correspond to coordSyses on index
  63809. * yAxes: correspond to coordSyses on index
  63810. * }
  63811. * or {
  63812. * panelId: ...,
  63813. * coordSys: <geo coord sys>
  63814. * coordSyses: [<geo coord sys>]
  63815. * geoModel: <geo component>
  63816. * }
  63817. *
  63818. *
  63819. * [panelOpt]:
  63820. *
  63821. * Make from targetInfo. Input to BrushController.
  63822. * {
  63823. * panelId: ...,
  63824. * rect: ...
  63825. * }
  63826. *
  63827. *
  63828. * [area]:
  63829. *
  63830. * Generated by BrushController or user input.
  63831. * {
  63832. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  63833. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  63834. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  63835. * range: pixel range.
  63836. * coordRange: representitive coord range (the first one of coordRanges).
  63837. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  63838. * }
  63839. */
  63840. /**
  63841. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  63842. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  63843. * @param {module:echarts/model/Global} ecModel
  63844. * @param {Object} [opt]
  63845. * @param {Array.<string>} [opt.include] include coordinate system types.
  63846. */
  63847. function BrushTargetManager(option, ecModel, opt) {
  63848. /**
  63849. * @private
  63850. * @type {Array.<Object>}
  63851. */
  63852. var targetInfoList = this._targetInfoList = [];
  63853. var info = {};
  63854. var foundCpts = parseFinder$1(ecModel, option);
  63855. each$20(targetInfoBuilders, function (builder, type) {
  63856. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  63857. builder(foundCpts, targetInfoList, info);
  63858. }
  63859. });
  63860. }
  63861. var proto$2 = BrushTargetManager.prototype;
  63862. proto$2.setOutputRanges = function (areas, ecModel) {
  63863. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  63864. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  63865. // area.coordRange is the first of area.coordRanges
  63866. if (!area.coordRange) {
  63867. area.coordRange = coordRange;
  63868. // In 'category' axis, coord to pixel is not reversible, so we can not
  63869. // rebuild range by coordRange accrately, which may bring trouble when
  63870. // brushing only one item. So we use __rangeOffset to rebuilding range
  63871. // by coordRange. And this it only used in brush component so it is no
  63872. // need to be adapted to coordRanges.
  63873. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  63874. area.__rangeOffset = {
  63875. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  63876. xyMinMax: result.xyMinMax
  63877. };
  63878. }
  63879. });
  63880. };
  63881. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  63882. each$20(areas, function (area) {
  63883. var targetInfo = this.findTargetInfo(area, ecModel);
  63884. if (targetInfo && targetInfo !== true) {
  63885. each$1(
  63886. targetInfo.coordSyses,
  63887. function (coordSys) {
  63888. var result = coordConvert[area.brushType](1, coordSys, area.range);
  63889. cb(area, result.values, coordSys, ecModel);
  63890. }
  63891. );
  63892. }
  63893. }, this);
  63894. };
  63895. proto$2.setInputRanges = function (areas, ecModel) {
  63896. each$20(areas, function (area) {
  63897. var targetInfo = this.findTargetInfo(area, ecModel);
  63898. if (__DEV__) {
  63899. assert$1(
  63900. !targetInfo || targetInfo === true || area.coordRange,
  63901. 'coordRange must be specified when coord index specified.'
  63902. );
  63903. assert$1(
  63904. !targetInfo || targetInfo !== true || area.range,
  63905. 'range must be specified in global brush.'
  63906. );
  63907. }
  63908. area.range = area.range || [];
  63909. // convert coordRange to global range and set panelId.
  63910. if (targetInfo && targetInfo !== true) {
  63911. area.panelId = targetInfo.panelId;
  63912. // (1) area.range shoule always be calculate from coordRange but does
  63913. // not keep its original value, for the sake of the dataZoom scenario,
  63914. // where area.coordRange remains unchanged but area.range may be changed.
  63915. // (2) Only support converting one coordRange to pixel range in brush
  63916. // component. So do not consider `coordRanges`.
  63917. // (3) About __rangeOffset, see comment above.
  63918. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  63919. var rangeOffset = area.__rangeOffset;
  63920. area.range = rangeOffset
  63921. ? diffProcessor[area.brushType](
  63922. result.values,
  63923. rangeOffset.offset,
  63924. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  63925. )
  63926. : result.values;
  63927. }
  63928. }, this);
  63929. };
  63930. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  63931. return map(this._targetInfoList, function (targetInfo) {
  63932. var rect = targetInfo.getPanelRect();
  63933. return {
  63934. panelId: targetInfo.panelId,
  63935. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  63936. clipPath: makeRectPanelClipPath(rect),
  63937. isTargetByCursor: makeRectIsTargetByCursor(
  63938. rect, api, targetInfo.coordSysModel
  63939. ),
  63940. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  63941. };
  63942. });
  63943. };
  63944. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  63945. // Check whether area is bound in coord, and series do not belong to that coord.
  63946. // If do not do this check, some brush (like lineX) will controll all axes.
  63947. var targetInfo = this.findTargetInfo(area, ecModel);
  63948. return targetInfo === true || (
  63949. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  63950. );
  63951. };
  63952. /**
  63953. * If return Object, a coord found.
  63954. * If reutrn true, global found.
  63955. * Otherwise nothing found.
  63956. *
  63957. * @param {Object} area
  63958. * @param {Array} targetInfoList
  63959. * @return {Object|boolean}
  63960. */
  63961. proto$2.findTargetInfo = function (area, ecModel) {
  63962. var targetInfoList = this._targetInfoList;
  63963. var foundCpts = parseFinder$1(ecModel, area);
  63964. for (var i = 0; i < targetInfoList.length; i++) {
  63965. var targetInfo = targetInfoList[i];
  63966. var areaPanelId = area.panelId;
  63967. if (areaPanelId) {
  63968. if (targetInfo.panelId === areaPanelId) {
  63969. return targetInfo;
  63970. }
  63971. }
  63972. else {
  63973. for (var i = 0; i < targetInfoMatchers.length; i++) {
  63974. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  63975. return targetInfo;
  63976. }
  63977. }
  63978. }
  63979. }
  63980. return true;
  63981. };
  63982. function formatMinMax(minMax) {
  63983. minMax[0] > minMax[1] && minMax.reverse();
  63984. return minMax;
  63985. }
  63986. function parseFinder$1(ecModel, option) {
  63987. return parseFinder(
  63988. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  63989. );
  63990. }
  63991. var targetInfoBuilders = {
  63992. grid: function (foundCpts, targetInfoList) {
  63993. var xAxisModels = foundCpts.xAxisModels;
  63994. var yAxisModels = foundCpts.yAxisModels;
  63995. var gridModels = foundCpts.gridModels;
  63996. // Remove duplicated.
  63997. var gridModelMap = createHashMap();
  63998. var xAxesHas = {};
  63999. var yAxesHas = {};
  64000. if (!xAxisModels && !yAxisModels && !gridModels) {
  64001. return;
  64002. }
  64003. each$20(xAxisModels, function (axisModel) {
  64004. var gridModel = axisModel.axis.grid.model;
  64005. gridModelMap.set(gridModel.id, gridModel);
  64006. xAxesHas[gridModel.id] = true;
  64007. });
  64008. each$20(yAxisModels, function (axisModel) {
  64009. var gridModel = axisModel.axis.grid.model;
  64010. gridModelMap.set(gridModel.id, gridModel);
  64011. yAxesHas[gridModel.id] = true;
  64012. });
  64013. each$20(gridModels, function (gridModel) {
  64014. gridModelMap.set(gridModel.id, gridModel);
  64015. xAxesHas[gridModel.id] = true;
  64016. yAxesHas[gridModel.id] = true;
  64017. });
  64018. gridModelMap.each(function (gridModel) {
  64019. var grid = gridModel.coordinateSystem;
  64020. var cartesians = [];
  64021. each$20(grid.getCartesians(), function (cartesian, index) {
  64022. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  64023. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  64024. ) {
  64025. cartesians.push(cartesian);
  64026. }
  64027. });
  64028. targetInfoList.push({
  64029. panelId: 'grid--' + gridModel.id,
  64030. gridModel: gridModel,
  64031. coordSysModel: gridModel,
  64032. // Use the first one as the representitive coordSys.
  64033. coordSys: cartesians[0],
  64034. coordSyses: cartesians,
  64035. getPanelRect: panelRectBuilder.grid,
  64036. xAxisDeclared: xAxesHas[gridModel.id],
  64037. yAxisDeclared: yAxesHas[gridModel.id]
  64038. });
  64039. });
  64040. },
  64041. geo: function (foundCpts, targetInfoList) {
  64042. each$20(foundCpts.geoModels, function (geoModel) {
  64043. var coordSys = geoModel.coordinateSystem;
  64044. targetInfoList.push({
  64045. panelId: 'geo--' + geoModel.id,
  64046. geoModel: geoModel,
  64047. coordSysModel: geoModel,
  64048. coordSys: coordSys,
  64049. coordSyses: [coordSys],
  64050. getPanelRect: panelRectBuilder.geo
  64051. });
  64052. });
  64053. }
  64054. };
  64055. var targetInfoMatchers = [
  64056. // grid
  64057. function (foundCpts, targetInfo) {
  64058. var xAxisModel = foundCpts.xAxisModel;
  64059. var yAxisModel = foundCpts.yAxisModel;
  64060. var gridModel = foundCpts.gridModel;
  64061. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  64062. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  64063. return gridModel && gridModel === targetInfo.gridModel;
  64064. },
  64065. // geo
  64066. function (foundCpts, targetInfo) {
  64067. var geoModel = foundCpts.geoModel;
  64068. return geoModel && geoModel === targetInfo.geoModel;
  64069. }
  64070. ];
  64071. var panelRectBuilder = {
  64072. grid: function () {
  64073. // grid is not Transformable.
  64074. return this.coordSys.grid.getRect().clone();
  64075. },
  64076. geo: function () {
  64077. var coordSys = this.coordSys;
  64078. var rect = coordSys.getBoundingRect().clone();
  64079. // geo roam and zoom transform
  64080. rect.applyTransform(getTransform(coordSys));
  64081. return rect;
  64082. }
  64083. };
  64084. var coordConvert = {
  64085. lineX: curry$5(axisConvert, 0),
  64086. lineY: curry$5(axisConvert, 1),
  64087. rect: function (to, coordSys, rangeOrCoordRange) {
  64088. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  64089. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  64090. var values = [
  64091. formatMinMax([xminymin[0], xmaxymax[0]]),
  64092. formatMinMax([xminymin[1], xmaxymax[1]])
  64093. ];
  64094. return {values: values, xyMinMax: values};
  64095. },
  64096. polygon: function (to, coordSys, rangeOrCoordRange) {
  64097. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  64098. var values = map(rangeOrCoordRange, function (item) {
  64099. var p = coordSys[COORD_CONVERTS[to]](item);
  64100. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  64101. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  64102. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  64103. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  64104. return p;
  64105. });
  64106. return {values: values, xyMinMax: xyMinMax};
  64107. }
  64108. };
  64109. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  64110. if (__DEV__) {
  64111. assert$1(
  64112. coordSys.type === 'cartesian2d',
  64113. 'lineX/lineY brush is available only in cartesian2d.'
  64114. );
  64115. }
  64116. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  64117. var values = formatMinMax(map([0, 1], function (i) {
  64118. return to
  64119. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  64120. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  64121. }));
  64122. var xyMinMax = [];
  64123. xyMinMax[axisNameIndex] = values;
  64124. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  64125. return {values: values, xyMinMax: xyMinMax};
  64126. }
  64127. var diffProcessor = {
  64128. lineX: curry$5(axisDiffProcessor, 0),
  64129. lineY: curry$5(axisDiffProcessor, 1),
  64130. rect: function (values, refer, scales) {
  64131. return [
  64132. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  64133. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  64134. ];
  64135. },
  64136. polygon: function (values, refer, scales) {
  64137. return map(values, function (item, idx) {
  64138. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  64139. });
  64140. }
  64141. };
  64142. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  64143. return [
  64144. values[0] - scales[axisNameIndex] * refer[0],
  64145. values[1] - scales[axisNameIndex] * refer[1]
  64146. ];
  64147. }
  64148. // We have to process scale caused by dataZoom manually,
  64149. // although it might be not accurate.
  64150. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  64151. var sizeCurr = getSize(xyMinMaxCurr);
  64152. var sizeOrigin = getSize(xyMinMaxOrigin);
  64153. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  64154. isNaN(scales[0]) && (scales[0] = 1);
  64155. isNaN(scales[1]) && (scales[1] = 1);
  64156. return scales;
  64157. }
  64158. function getSize(xyMinMax) {
  64159. return xyMinMax
  64160. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  64161. : [NaN, NaN];
  64162. }
  64163. /*
  64164. * Licensed to the Apache Software Foundation (ASF) under one
  64165. * or more contributor license agreements. See the NOTICE file
  64166. * distributed with this work for additional information
  64167. * regarding copyright ownership. The ASF licenses this file
  64168. * to you under the Apache License, Version 2.0 (the
  64169. * "License"); you may not use this file except in compliance
  64170. * with the License. You may obtain a copy of the License at
  64171. *
  64172. * http://www.apache.org/licenses/LICENSE-2.0
  64173. *
  64174. * Unless required by applicable law or agreed to in writing,
  64175. * software distributed under the License is distributed on an
  64176. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64177. * KIND, either express or implied. See the License for the
  64178. * specific language governing permissions and limitations
  64179. * under the License.
  64180. */
  64181. var STATE_LIST = ['inBrush', 'outOfBrush'];
  64182. var DISPATCH_METHOD = '__ecBrushSelect';
  64183. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  64184. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  64185. /**
  64186. * Layout for visual, the priority higher than other layout, and before brush visual.
  64187. */
  64188. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  64189. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  64190. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  64191. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  64192. );
  64193. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  64194. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  64195. });
  64196. });
  64197. /**
  64198. * Register the visual encoding if this modules required.
  64199. */
  64200. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  64201. var brushSelected = [];
  64202. var throttleType;
  64203. var throttleDelay;
  64204. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  64205. var thisBrushSelected = {
  64206. brushId: brushModel.id,
  64207. brushIndex: brushIndex,
  64208. brushName: brushModel.name,
  64209. areas: clone(brushModel.areas),
  64210. selected: []
  64211. };
  64212. // Every brush component exists in event params, convenient
  64213. // for user to find by index.
  64214. brushSelected.push(thisBrushSelected);
  64215. var brushOption = brushModel.option;
  64216. var brushLink = brushOption.brushLink;
  64217. var linkedSeriesMap = [];
  64218. var selectedDataIndexForLink = [];
  64219. var rangeInfoBySeries = [];
  64220. var hasBrushExists = 0;
  64221. if (!brushIndex) { // Only the first throttle setting works.
  64222. throttleType = brushOption.throttleType;
  64223. throttleDelay = brushOption.throttleDelay;
  64224. }
  64225. // Add boundingRect and selectors to range.
  64226. var areas = map(brushModel.areas, function (area) {
  64227. return bindSelector(
  64228. defaults(
  64229. {boundingRect: boundingRectBuilders[area.brushType](area)},
  64230. area
  64231. )
  64232. );
  64233. });
  64234. var visualMappings = createVisualMappings(
  64235. brushModel.option, STATE_LIST, function (mappingOption) {
  64236. mappingOption.mappingMethod = 'fixed';
  64237. }
  64238. );
  64239. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  64240. linkedSeriesMap[seriesIndex] = 1;
  64241. });
  64242. function linkOthers(seriesIndex) {
  64243. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  64244. }
  64245. // If no supported brush or no brush on the series,
  64246. // all visuals should be in original state.
  64247. function brushed(rangeInfoList) {
  64248. return !!rangeInfoList.length;
  64249. }
  64250. /**
  64251. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  64252. *
  64253. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  64254. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  64255. * └!hasBrushExist┘ └nothing.
  64256. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  64257. * └!hasBrushExist┘ └nothing.
  64258. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  64259. * !brushed┘ └nothing.
  64260. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  64261. */
  64262. // Step A
  64263. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  64264. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  64265. seriesModel.subType === 'parallel'
  64266. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  64267. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  64268. });
  64269. function stepAParallel(seriesModel, seriesIndex) {
  64270. var coordSys = seriesModel.coordinateSystem;
  64271. hasBrushExists |= coordSys.hasAxisBrushed();
  64272. linkOthers(seriesIndex) && coordSys.eachActiveState(
  64273. seriesModel.getData(),
  64274. function (activeState, dataIndex) {
  64275. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  64276. }
  64277. );
  64278. }
  64279. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  64280. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  64281. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  64282. return;
  64283. }
  64284. each$1(areas, function (area) {
  64285. selectorsByBrushType[area.brushType]
  64286. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  64287. && rangeInfoList.push(area);
  64288. hasBrushExists |= brushed(rangeInfoList);
  64289. });
  64290. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  64291. var data = seriesModel.getData();
  64292. data.each(function (dataIndex) {
  64293. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  64294. selectedDataIndexForLink[dataIndex] = 1;
  64295. }
  64296. });
  64297. }
  64298. }
  64299. // Step B
  64300. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  64301. var seriesBrushSelected = {
  64302. seriesId: seriesModel.id,
  64303. seriesIndex: seriesIndex,
  64304. seriesName: seriesModel.name,
  64305. dataIndex: []
  64306. };
  64307. // Every series exists in event params, convenient
  64308. // for user to find series by seriesIndex.
  64309. thisBrushSelected.selected.push(seriesBrushSelected);
  64310. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  64311. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  64312. var data = seriesModel.getData();
  64313. var getValueState = linkOthers(seriesIndex)
  64314. ? function (dataIndex) {
  64315. return selectedDataIndexForLink[dataIndex]
  64316. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  64317. : 'outOfBrush';
  64318. }
  64319. : function (dataIndex) {
  64320. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  64321. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  64322. : 'outOfBrush';
  64323. };
  64324. // If no supported brush or no brush, all visuals are in original state.
  64325. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  64326. && applyVisual(
  64327. STATE_LIST, visualMappings, data, getValueState
  64328. );
  64329. });
  64330. });
  64331. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  64332. });
  64333. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  64334. // This event will not be triggered when `setOpion`, otherwise dead lock may
  64335. // triggered when do `setOption` in event listener, which we do not find
  64336. // satisfactory way to solve yet. Some considered resolutions:
  64337. // (a) Diff with prevoius selected data ant only trigger event when changed.
  64338. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  64339. // also detect value changes in selected data) might bring complexity or fragility.
  64340. // (b) Use spectial param like `silent` to suppress event triggering.
  64341. // But such kind of volatile param may be weird in `setOption`.
  64342. if (!payload) {
  64343. return;
  64344. }
  64345. var zr = api.getZr();
  64346. if (zr[DISPATCH_FLAG]) {
  64347. return;
  64348. }
  64349. if (!zr[DISPATCH_METHOD]) {
  64350. zr[DISPATCH_METHOD] = doDispatch;
  64351. }
  64352. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  64353. fn(api, brushSelected);
  64354. }
  64355. function doDispatch(api, brushSelected) {
  64356. if (!api.isDisposed()) {
  64357. var zr = api.getZr();
  64358. zr[DISPATCH_FLAG] = true;
  64359. api.dispatchAction({
  64360. type: 'brushSelect',
  64361. batch: brushSelected
  64362. });
  64363. zr[DISPATCH_FLAG] = false;
  64364. }
  64365. }
  64366. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  64367. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  64368. var area = rangeInfoList[i];
  64369. if (selectorsByBrushType[area.brushType](
  64370. dataIndex, data, area.selectors, area
  64371. )) {
  64372. return true;
  64373. }
  64374. }
  64375. }
  64376. function getSelectorsByBrushType(seriesModel) {
  64377. var brushSelector = seriesModel.brushSelector;
  64378. if (isString(brushSelector)) {
  64379. var sels = [];
  64380. each$1(selector, function (selectorsByElementType, brushType) {
  64381. sels[brushType] = function (dataIndex, data, selectors, area) {
  64382. var itemLayout = data.getItemLayout(dataIndex);
  64383. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  64384. };
  64385. });
  64386. return sels;
  64387. }
  64388. else if (isFunction$1(brushSelector)) {
  64389. var bSelector = {};
  64390. each$1(selector, function (sel, brushType) {
  64391. bSelector[brushType] = brushSelector;
  64392. });
  64393. return bSelector;
  64394. }
  64395. return brushSelector;
  64396. }
  64397. function brushModelNotControll(brushModel, seriesIndex) {
  64398. var seriesIndices = brushModel.option.seriesIndex;
  64399. return seriesIndices != null
  64400. && seriesIndices !== 'all'
  64401. && (
  64402. isArray(seriesIndices)
  64403. ? indexOf(seriesIndices, seriesIndex) < 0
  64404. : seriesIndex !== seriesIndices
  64405. );
  64406. }
  64407. function bindSelector(area) {
  64408. var selectors = area.selectors = {};
  64409. each$1(selector[area.brushType], function (selFn, elType) {
  64410. // Do not use function binding or curry for performance.
  64411. selectors[elType] = function (itemLayout) {
  64412. return selFn(itemLayout, selectors, area);
  64413. };
  64414. });
  64415. return area;
  64416. }
  64417. var boundingRectBuilders = {
  64418. lineX: noop,
  64419. lineY: noop,
  64420. rect: function (area) {
  64421. return getBoundingRectFromMinMax(area.range);
  64422. },
  64423. polygon: function (area) {
  64424. var minMax;
  64425. var range = area.range;
  64426. for (var i = 0, len = range.length; i < len; i++) {
  64427. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  64428. var rg = range[i];
  64429. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  64430. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  64431. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  64432. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  64433. }
  64434. return minMax && getBoundingRectFromMinMax(minMax);
  64435. }
  64436. };
  64437. function getBoundingRectFromMinMax(minMax) {
  64438. return new BoundingRect(
  64439. minMax[0][0],
  64440. minMax[1][0],
  64441. minMax[0][1] - minMax[0][0],
  64442. minMax[1][1] - minMax[1][0]
  64443. );
  64444. }
  64445. /*
  64446. * Licensed to the Apache Software Foundation (ASF) under one
  64447. * or more contributor license agreements. See the NOTICE file
  64448. * distributed with this work for additional information
  64449. * regarding copyright ownership. The ASF licenses this file
  64450. * to you under the Apache License, Version 2.0 (the
  64451. * "License"); you may not use this file except in compliance
  64452. * with the License. You may obtain a copy of the License at
  64453. *
  64454. * http://www.apache.org/licenses/LICENSE-2.0
  64455. *
  64456. * Unless required by applicable law or agreed to in writing,
  64457. * software distributed under the License is distributed on an
  64458. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64459. * KIND, either express or implied. See the License for the
  64460. * specific language governing permissions and limitations
  64461. * under the License.
  64462. */
  64463. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  64464. var BrushModel = extendComponentModel({
  64465. type: 'brush',
  64466. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  64467. /**
  64468. * @protected
  64469. */
  64470. defaultOption: {
  64471. // inBrush: null,
  64472. // outOfBrush: null,
  64473. toolbox: null, // Default value see preprocessor.
  64474. brushLink: null, // Series indices array, broadcast using dataIndex.
  64475. // or 'all', which means all series. 'none' or null means no series.
  64476. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  64477. geoIndex: null, //
  64478. xAxisIndex: null,
  64479. yAxisIndex: null,
  64480. brushType: 'rect', // Default brushType, see BrushController.
  64481. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  64482. transformable: true, // Default transformable.
  64483. brushStyle: { // Default brushStyle
  64484. borderWidth: 1,
  64485. color: 'rgba(120,140,180,0.3)',
  64486. borderColor: 'rgba(120,140,180,0.8)'
  64487. },
  64488. throttleType: 'fixRate',// Throttle in brushSelected event. 'fixRate' or 'debounce'.
  64489. // If null, no throttle. Valid only in the first brush component
  64490. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  64491. // FIXME
  64492. // 试验效果
  64493. removeOnClick: true,
  64494. z: 10000
  64495. },
  64496. /**
  64497. * @readOnly
  64498. * @type {Array.<Object>}
  64499. */
  64500. areas: [],
  64501. /**
  64502. * Current activated brush type.
  64503. * If null, brush is inactived.
  64504. * see module:echarts/component/helper/BrushController
  64505. * @readOnly
  64506. * @type {string}
  64507. */
  64508. brushType: null,
  64509. /**
  64510. * Current brush opt.
  64511. * see module:echarts/component/helper/BrushController
  64512. * @readOnly
  64513. * @type {Object}
  64514. */
  64515. brushOption: {},
  64516. /**
  64517. * @readOnly
  64518. * @type {Array.<Object>}
  64519. */
  64520. coordInfoList: [],
  64521. optionUpdated: function (newOption, isInit) {
  64522. var thisOption = this.option;
  64523. !isInit && replaceVisualOption(
  64524. thisOption, newOption, ['inBrush', 'outOfBrush']
  64525. );
  64526. var inBrush = thisOption.inBrush = thisOption.inBrush || {};
  64527. // Always give default visual, consider setOption at the second time.
  64528. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  64529. if (!inBrush.hasOwnProperty('liftZ')) {
  64530. // Bigger than the highlight z lift, otherwise it will
  64531. // be effected by the highlight z when brush.
  64532. inBrush.liftZ = 5;
  64533. }
  64534. },
  64535. /**
  64536. * If ranges is null/undefined, range state remain.
  64537. *
  64538. * @param {Array.<Object>} [ranges]
  64539. */
  64540. setAreas: function (areas) {
  64541. if (__DEV__) {
  64542. assert$1(isArray(areas));
  64543. each$1(areas, function (area) {
  64544. assert$1(area.brushType, 'Illegal areas');
  64545. });
  64546. }
  64547. // If ranges is null/undefined, range state remain.
  64548. // This helps user to dispatchAction({type: 'brush'}) with no areas
  64549. // set but just want to get the current brush select info from a `brush` event.
  64550. if (!areas) {
  64551. return;
  64552. }
  64553. this.areas = map(areas, function (area) {
  64554. return generateBrushOption(this.option, area);
  64555. }, this);
  64556. },
  64557. /**
  64558. * see module:echarts/component/helper/BrushController
  64559. * @param {Object} brushOption
  64560. */
  64561. setBrushOption: function (brushOption) {
  64562. this.brushOption = generateBrushOption(this.option, brushOption);
  64563. this.brushType = this.brushOption.brushType;
  64564. }
  64565. });
  64566. function generateBrushOption(option, brushOption) {
  64567. return merge(
  64568. {
  64569. brushType: option.brushType,
  64570. brushMode: option.brushMode,
  64571. transformable: option.transformable,
  64572. brushStyle: new Model(option.brushStyle).getItemStyle(),
  64573. removeOnClick: option.removeOnClick,
  64574. z: option.z
  64575. },
  64576. brushOption,
  64577. true
  64578. );
  64579. }
  64580. /*
  64581. * Licensed to the Apache Software Foundation (ASF) under one
  64582. * or more contributor license agreements. See the NOTICE file
  64583. * distributed with this work for additional information
  64584. * regarding copyright ownership. The ASF licenses this file
  64585. * to you under the Apache License, Version 2.0 (the
  64586. * "License"); you may not use this file except in compliance
  64587. * with the License. You may obtain a copy of the License at
  64588. *
  64589. * http://www.apache.org/licenses/LICENSE-2.0
  64590. *
  64591. * Unless required by applicable law or agreed to in writing,
  64592. * software distributed under the License is distributed on an
  64593. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64594. * KIND, either express or implied. See the License for the
  64595. * specific language governing permissions and limitations
  64596. * under the License.
  64597. */
  64598. extendComponentView({
  64599. type: 'brush',
  64600. init: function (ecModel, api) {
  64601. /**
  64602. * @readOnly
  64603. * @type {module:echarts/model/Global}
  64604. */
  64605. this.ecModel = ecModel;
  64606. /**
  64607. * @readOnly
  64608. * @type {module:echarts/ExtensionAPI}
  64609. */
  64610. this.api = api;
  64611. /**
  64612. * @readOnly
  64613. * @type {module:echarts/component/brush/BrushModel}
  64614. */
  64615. this.model;
  64616. /**
  64617. * @private
  64618. * @type {module:echarts/component/helper/BrushController}
  64619. */
  64620. (this._brushController = new BrushController(api.getZr()))
  64621. .on('brush', bind(this._onBrush, this))
  64622. .mount();
  64623. },
  64624. /**
  64625. * @override
  64626. */
  64627. render: function (brushModel) {
  64628. this.model = brushModel;
  64629. return updateController.apply(this, arguments);
  64630. },
  64631. /**
  64632. * @override
  64633. */
  64634. updateTransform: updateController,
  64635. /**
  64636. * @override
  64637. */
  64638. updateView: updateController,
  64639. // /**
  64640. // * @override
  64641. // */
  64642. // updateLayout: updateController,
  64643. // /**
  64644. // * @override
  64645. // */
  64646. // updateVisual: updateController,
  64647. /**
  64648. * @override
  64649. */
  64650. dispose: function () {
  64651. this._brushController.dispose();
  64652. },
  64653. /**
  64654. * @private
  64655. */
  64656. _onBrush: function (areas, opt) {
  64657. var modelId = this.model.id;
  64658. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  64659. // Action is not dispatched on drag end, because the drag end
  64660. // emits the same params with the last drag move event, and
  64661. // may have some delay when using touch pad, which makes
  64662. // animation not smooth (when using debounce).
  64663. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  64664. type: 'brush',
  64665. brushId: modelId,
  64666. areas: clone(areas),
  64667. $from: modelId
  64668. });
  64669. }
  64670. });
  64671. function updateController(brushModel, ecModel, api, payload) {
  64672. // Do not update controller when drawing.
  64673. (!payload || payload.$from !== brushModel.id) && this._brushController
  64674. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  64675. .enableBrush(brushModel.brushOption)
  64676. .updateCovers(brushModel.areas.slice());
  64677. }
  64678. /*
  64679. * Licensed to the Apache Software Foundation (ASF) under one
  64680. * or more contributor license agreements. See the NOTICE file
  64681. * distributed with this work for additional information
  64682. * regarding copyright ownership. The ASF licenses this file
  64683. * to you under the Apache License, Version 2.0 (the
  64684. * "License"); you may not use this file except in compliance
  64685. * with the License. You may obtain a copy of the License at
  64686. *
  64687. * http://www.apache.org/licenses/LICENSE-2.0
  64688. *
  64689. * Unless required by applicable law or agreed to in writing,
  64690. * software distributed under the License is distributed on an
  64691. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64692. * KIND, either express or implied. See the License for the
  64693. * specific language governing permissions and limitations
  64694. * under the License.
  64695. */
  64696. /**
  64697. * payload: {
  64698. * brushIndex: number, or,
  64699. * brushId: string, or,
  64700. * brushName: string,
  64701. * globalRanges: Array
  64702. * }
  64703. */
  64704. registerAction(
  64705. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  64706. function (payload, ecModel) {
  64707. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  64708. brushModel.setAreas(payload.areas);
  64709. });
  64710. }
  64711. );
  64712. /**
  64713. * payload: {
  64714. * brushComponents: [
  64715. * {
  64716. * brushId,
  64717. * brushIndex,
  64718. * brushName,
  64719. * series: [
  64720. * {
  64721. * seriesId,
  64722. * seriesIndex,
  64723. * seriesName,
  64724. * rawIndices: [21, 34, ...]
  64725. * },
  64726. * ...
  64727. * ]
  64728. * },
  64729. * ...
  64730. * ]
  64731. * }
  64732. */
  64733. registerAction(
  64734. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  64735. function () {}
  64736. );
  64737. /*
  64738. * Licensed to the Apache Software Foundation (ASF) under one
  64739. * or more contributor license agreements. See the NOTICE file
  64740. * distributed with this work for additional information
  64741. * regarding copyright ownership. The ASF licenses this file
  64742. * to you under the Apache License, Version 2.0 (the
  64743. * "License"); you may not use this file except in compliance
  64744. * with the License. You may obtain a copy of the License at
  64745. *
  64746. * http://www.apache.org/licenses/LICENSE-2.0
  64747. *
  64748. * Unless required by applicable law or agreed to in writing,
  64749. * software distributed under the License is distributed on an
  64750. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64751. * KIND, either express or implied. See the License for the
  64752. * specific language governing permissions and limitations
  64753. * under the License.
  64754. */
  64755. var features = {};
  64756. function register$1(name, ctor) {
  64757. features[name] = ctor;
  64758. }
  64759. function get$1(name) {
  64760. return features[name];
  64761. }
  64762. /*
  64763. * Licensed to the Apache Software Foundation (ASF) under one
  64764. * or more contributor license agreements. See the NOTICE file
  64765. * distributed with this work for additional information
  64766. * regarding copyright ownership. The ASF licenses this file
  64767. * to you under the Apache License, Version 2.0 (the
  64768. * "License"); you may not use this file except in compliance
  64769. * with the License. You may obtain a copy of the License at
  64770. *
  64771. * http://www.apache.org/licenses/LICENSE-2.0
  64772. *
  64773. * Unless required by applicable law or agreed to in writing,
  64774. * software distributed under the License is distributed on an
  64775. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64776. * KIND, either express or implied. See the License for the
  64777. * specific language governing permissions and limitations
  64778. * under the License.
  64779. */
  64780. var brushLang = lang.toolbox.brush;
  64781. function Brush(model, ecModel, api) {
  64782. this.model = model;
  64783. this.ecModel = ecModel;
  64784. this.api = api;
  64785. /**
  64786. * @private
  64787. * @type {string}
  64788. */
  64789. this._brushType;
  64790. /**
  64791. * @private
  64792. * @type {string}
  64793. */
  64794. this._brushMode;
  64795. }
  64796. Brush.defaultOption = {
  64797. show: true,
  64798. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  64799. icon: {
  64800. 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
  64801. 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
  64802. 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
  64803. 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
  64804. 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
  64805. 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
  64806. },
  64807. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  64808. title: clone(brushLang.title)
  64809. };
  64810. var proto$3 = Brush.prototype;
  64811. // proto.updateLayout = function (featureModel, ecModel, api) {
  64812. proto$3.render =
  64813. proto$3.updateView = function (featureModel, ecModel, api) {
  64814. var brushType;
  64815. var brushMode;
  64816. var isBrushed;
  64817. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  64818. brushType = brushModel.brushType;
  64819. brushMode = brushModel.brushOption.brushMode || 'single';
  64820. isBrushed |= brushModel.areas.length;
  64821. });
  64822. this._brushType = brushType;
  64823. this._brushMode = brushMode;
  64824. each$1(featureModel.get('type', true), function (type) {
  64825. featureModel.setIconStatus(
  64826. type,
  64827. (
  64828. type === 'keep'
  64829. ? brushMode === 'multiple'
  64830. : type === 'clear'
  64831. ? isBrushed
  64832. : type === brushType
  64833. ) ? 'emphasis' : 'normal'
  64834. );
  64835. });
  64836. };
  64837. proto$3.getIcons = function () {
  64838. var model = this.model;
  64839. var availableIcons = model.get('icon', true);
  64840. var icons = {};
  64841. each$1(model.get('type', true), function (type) {
  64842. if (availableIcons[type]) {
  64843. icons[type] = availableIcons[type];
  64844. }
  64845. });
  64846. return icons;
  64847. };
  64848. proto$3.onclick = function (ecModel, api, type) {
  64849. var brushType = this._brushType;
  64850. var brushMode = this._brushMode;
  64851. if (type === 'clear') {
  64852. // Trigger parallel action firstly
  64853. api.dispatchAction({
  64854. type: 'axisAreaSelect',
  64855. intervals: []
  64856. });
  64857. api.dispatchAction({
  64858. type: 'brush',
  64859. command: 'clear',
  64860. // Clear all areas of all brush components.
  64861. areas: []
  64862. });
  64863. }
  64864. else {
  64865. api.dispatchAction({
  64866. type: 'takeGlobalCursor',
  64867. key: 'brush',
  64868. brushOption: {
  64869. brushType: type === 'keep'
  64870. ? brushType
  64871. : (brushType === type ? false : type),
  64872. brushMode: type === 'keep'
  64873. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  64874. : brushMode
  64875. }
  64876. });
  64877. }
  64878. };
  64879. register$1('brush', Brush);
  64880. /*
  64881. * Licensed to the Apache Software Foundation (ASF) under one
  64882. * or more contributor license agreements. See the NOTICE file
  64883. * distributed with this work for additional information
  64884. * regarding copyright ownership. The ASF licenses this file
  64885. * to you under the Apache License, Version 2.0 (the
  64886. * "License"); you may not use this file except in compliance
  64887. * with the License. You may obtain a copy of the License at
  64888. *
  64889. * http://www.apache.org/licenses/LICENSE-2.0
  64890. *
  64891. * Unless required by applicable law or agreed to in writing,
  64892. * software distributed under the License is distributed on an
  64893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64894. * KIND, either express or implied. See the License for the
  64895. * specific language governing permissions and limitations
  64896. * under the License.
  64897. */
  64898. /**
  64899. * Brush component entry
  64900. */
  64901. registerPreprocessor(preprocessor$1);
  64902. /*
  64903. * Licensed to the Apache Software Foundation (ASF) under one
  64904. * or more contributor license agreements. See the NOTICE file
  64905. * distributed with this work for additional information
  64906. * regarding copyright ownership. The ASF licenses this file
  64907. * to you under the Apache License, Version 2.0 (the
  64908. * "License"); you may not use this file except in compliance
  64909. * with the License. You may obtain a copy of the License at
  64910. *
  64911. * http://www.apache.org/licenses/LICENSE-2.0
  64912. *
  64913. * Unless required by applicable law or agreed to in writing,
  64914. * software distributed under the License is distributed on an
  64915. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64916. * KIND, either express or implied. See the License for the
  64917. * specific language governing permissions and limitations
  64918. * under the License.
  64919. */
  64920. // (24*60*60*1000)
  64921. var PROXIMATE_ONE_DAY = 86400000;
  64922. /**
  64923. * Calendar
  64924. *
  64925. * @constructor
  64926. *
  64927. * @param {Object} calendarModel calendarModel
  64928. * @param {Object} ecModel ecModel
  64929. * @param {Object} api api
  64930. */
  64931. function Calendar(calendarModel, ecModel, api) {
  64932. this._model = calendarModel;
  64933. }
  64934. Calendar.prototype = {
  64935. constructor: Calendar,
  64936. type: 'calendar',
  64937. dimensions: ['time', 'value'],
  64938. // Required in createListFromData
  64939. getDimensionsInfo: function () {
  64940. return [{name: 'time', type: 'time'}, 'value'];
  64941. },
  64942. getRangeInfo: function () {
  64943. return this._rangeInfo;
  64944. },
  64945. getModel: function () {
  64946. return this._model;
  64947. },
  64948. getRect: function () {
  64949. return this._rect;
  64950. },
  64951. getCellWidth: function () {
  64952. return this._sw;
  64953. },
  64954. getCellHeight: function () {
  64955. return this._sh;
  64956. },
  64957. getOrient: function () {
  64958. return this._orient;
  64959. },
  64960. /**
  64961. * getFirstDayOfWeek
  64962. *
  64963. * @example
  64964. * 0 : start at Sunday
  64965. * 1 : start at Monday
  64966. *
  64967. * @return {number}
  64968. */
  64969. getFirstDayOfWeek: function () {
  64970. return this._firstDayOfWeek;
  64971. },
  64972. /**
  64973. * get date info
  64974. *
  64975. * @param {string|number} date date
  64976. * @return {Object}
  64977. * {
  64978. * y: string, local full year, eg., '1940',
  64979. * m: string, local month, from '01' ot '12',
  64980. * d: string, local date, from '01' to '31' (if exists),
  64981. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  64982. * time: timestamp,
  64983. * formatedDate: string, yyyy-MM-dd,
  64984. * date: original date object.
  64985. * }
  64986. */
  64987. getDateInfo: function (date) {
  64988. date = parseDate(date);
  64989. var y = date.getFullYear();
  64990. var m = date.getMonth() + 1;
  64991. m = m < 10 ? '0' + m : m;
  64992. var d = date.getDate();
  64993. d = d < 10 ? '0' + d : d;
  64994. var day = date.getDay();
  64995. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  64996. return {
  64997. y: y,
  64998. m: m,
  64999. d: d,
  65000. day: day,
  65001. time: date.getTime(),
  65002. formatedDate: y + '-' + m + '-' + d,
  65003. date: date
  65004. };
  65005. },
  65006. getNextNDay: function (date, n) {
  65007. n = n || 0;
  65008. if (n === 0) {
  65009. return this.getDateInfo(date);
  65010. }
  65011. date = new Date(this.getDateInfo(date).time);
  65012. date.setDate(date.getDate() + n);
  65013. return this.getDateInfo(date);
  65014. },
  65015. update: function (ecModel, api) {
  65016. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  65017. this._orient = this._model.get('orient');
  65018. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  65019. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  65020. var weeks = this._rangeInfo.weeks || 1;
  65021. var whNames = ['width', 'height'];
  65022. var cellSize = this._model.get('cellSize').slice();
  65023. var layoutParams = this._model.getBoxLayoutParams();
  65024. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  65025. each$1([0, 1], function (idx) {
  65026. if (cellSizeSpecified(cellSize, idx)) {
  65027. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  65028. }
  65029. });
  65030. var whGlobal = {
  65031. width: api.getWidth(),
  65032. height: api.getHeight()
  65033. };
  65034. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  65035. each$1([0, 1], function (idx) {
  65036. if (!cellSizeSpecified(cellSize, idx)) {
  65037. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  65038. }
  65039. });
  65040. function cellSizeSpecified(cellSize, idx) {
  65041. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  65042. }
  65043. this._sw = cellSize[0];
  65044. this._sh = cellSize[1];
  65045. },
  65046. /**
  65047. * Convert a time data(time, value) item to (x, y) point.
  65048. *
  65049. * @override
  65050. * @param {Array|number} data data
  65051. * @param {boolean} [clamp=true] out of range
  65052. * @return {Array} point
  65053. */
  65054. dataToPoint: function (data, clamp) {
  65055. isArray(data) && (data = data[0]);
  65056. clamp == null && (clamp = true);
  65057. var dayInfo = this.getDateInfo(data);
  65058. var range = this._rangeInfo;
  65059. var date = dayInfo.formatedDate;
  65060. // if not in range return [NaN, NaN]
  65061. if (clamp && !(
  65062. dayInfo.time >= range.start.time
  65063. && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY
  65064. )) {
  65065. return [NaN, NaN];
  65066. }
  65067. var week = dayInfo.day;
  65068. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  65069. if (this._orient === 'vertical') {
  65070. return [
  65071. this._rect.x + week * this._sw + this._sw / 2,
  65072. this._rect.y + nthWeek * this._sh + this._sh / 2
  65073. ];
  65074. }
  65075. return [
  65076. this._rect.x + nthWeek * this._sw + this._sw / 2,
  65077. this._rect.y + week * this._sh + this._sh / 2
  65078. ];
  65079. },
  65080. /**
  65081. * Convert a (x, y) point to time data
  65082. *
  65083. * @override
  65084. * @param {string} point point
  65085. * @return {string} data
  65086. */
  65087. pointToData: function (point) {
  65088. var date = this.pointToDate(point);
  65089. return date && date.time;
  65090. },
  65091. /**
  65092. * Convert a time date item to (x, y) four point.
  65093. *
  65094. * @param {Array} data date[0] is date
  65095. * @param {boolean} [clamp=true] out of range
  65096. * @return {Object} point
  65097. */
  65098. dataToRect: function (data, clamp) {
  65099. var point = this.dataToPoint(data, clamp);
  65100. return {
  65101. contentShape: {
  65102. x: point[0] - (this._sw - this._lineWidth) / 2,
  65103. y: point[1] - (this._sh - this._lineWidth) / 2,
  65104. width: this._sw - this._lineWidth,
  65105. height: this._sh - this._lineWidth
  65106. },
  65107. center: point,
  65108. tl: [
  65109. point[0] - this._sw / 2,
  65110. point[1] - this._sh / 2
  65111. ],
  65112. tr: [
  65113. point[0] + this._sw / 2,
  65114. point[1] - this._sh / 2
  65115. ],
  65116. br: [
  65117. point[0] + this._sw / 2,
  65118. point[1] + this._sh / 2
  65119. ],
  65120. bl: [
  65121. point[0] - this._sw / 2,
  65122. point[1] + this._sh / 2
  65123. ]
  65124. };
  65125. },
  65126. /**
  65127. * Convert a (x, y) point to time date
  65128. *
  65129. * @param {Array} point point
  65130. * @return {Object} date
  65131. */
  65132. pointToDate: function (point) {
  65133. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  65134. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  65135. var range = this._rangeInfo.range;
  65136. if (this._orient === 'vertical') {
  65137. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  65138. }
  65139. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  65140. },
  65141. /**
  65142. * @inheritDoc
  65143. */
  65144. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  65145. /**
  65146. * @inheritDoc
  65147. */
  65148. convertFromPixel: curry(doConvert$2, 'pointToData'),
  65149. /**
  65150. * initRange
  65151. *
  65152. * @private
  65153. * @return {Array} [start, end]
  65154. */
  65155. _initRangeOption: function () {
  65156. var range = this._model.get('range');
  65157. var rg = range;
  65158. if (isArray(rg) && rg.length === 1) {
  65159. rg = rg[0];
  65160. }
  65161. if (/^\d{4}$/.test(rg)) {
  65162. range = [rg + '-01-01', rg + '-12-31'];
  65163. }
  65164. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  65165. var start = this.getDateInfo(rg);
  65166. var firstDay = start.date;
  65167. firstDay.setMonth(firstDay.getMonth() + 1);
  65168. var end = this.getNextNDay(firstDay, -1);
  65169. range = [start.formatedDate, end.formatedDate];
  65170. }
  65171. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  65172. range = [rg, rg];
  65173. }
  65174. var tmp = this._getRangeInfo(range);
  65175. if (tmp.start.time > tmp.end.time) {
  65176. range.reverse();
  65177. }
  65178. return range;
  65179. },
  65180. /**
  65181. * range info
  65182. *
  65183. * @private
  65184. * @param {Array} range range ['2017-01-01', '2017-07-08']
  65185. * If range[0] > range[1], they will not be reversed.
  65186. * @return {Object} obj
  65187. */
  65188. _getRangeInfo: function (range) {
  65189. range = [
  65190. this.getDateInfo(range[0]),
  65191. this.getDateInfo(range[1])
  65192. ];
  65193. var reversed;
  65194. if (range[0].time > range[1].time) {
  65195. reversed = true;
  65196. range.reverse();
  65197. }
  65198. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  65199. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  65200. // Consider case:
  65201. // Firstly set system timezone as "Time Zone: America/Toronto",
  65202. // ```
  65203. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  65204. // var second = new Date(1478412000000);
  65205. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  65206. // ```
  65207. // will get wrong result because of DST. So we should fix it.
  65208. var date = new Date(range[0].time);
  65209. var startDateNum = date.getDate();
  65210. var endDateNum = range[1].date.getDate();
  65211. date.setDate(startDateNum + allDay - 1);
  65212. // The bias can not over a month, so just compare date.
  65213. if (date.getDate() !== endDateNum) {
  65214. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  65215. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  65216. allDay -= sign;
  65217. date.setDate(startDateNum + allDay - 1);
  65218. }
  65219. }
  65220. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  65221. var nthWeek = reversed ? -weeks + 1: weeks - 1;
  65222. reversed && range.reverse();
  65223. return {
  65224. range: [range[0].formatedDate, range[1].formatedDate],
  65225. start: range[0],
  65226. end: range[1],
  65227. allDay: allDay,
  65228. weeks: weeks,
  65229. // From 0.
  65230. nthWeek: nthWeek,
  65231. fweek: range[0].day,
  65232. lweek: range[1].day
  65233. };
  65234. },
  65235. /**
  65236. * get date by nthWeeks and week day in range
  65237. *
  65238. * @private
  65239. * @param {number} nthWeek the week
  65240. * @param {number} day the week day
  65241. * @param {Array} range [d1, d2]
  65242. * @return {Object}
  65243. */
  65244. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  65245. var rangeInfo = this._getRangeInfo(range);
  65246. if (nthWeek > rangeInfo.weeks
  65247. || (nthWeek === 0 && day < rangeInfo.fweek)
  65248. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  65249. ) {
  65250. return false;
  65251. }
  65252. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  65253. var date = new Date(rangeInfo.start.time);
  65254. date.setDate(rangeInfo.start.d + nthDay);
  65255. return this.getDateInfo(date);
  65256. }
  65257. };
  65258. Calendar.dimensions = Calendar.prototype.dimensions;
  65259. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  65260. Calendar.create = function (ecModel, api) {
  65261. var calendarList = [];
  65262. ecModel.eachComponent('calendar', function (calendarModel) {
  65263. var calendar = new Calendar(calendarModel, ecModel, api);
  65264. calendarList.push(calendar);
  65265. calendarModel.coordinateSystem = calendar;
  65266. });
  65267. ecModel.eachSeries(function (calendarSeries) {
  65268. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  65269. // Inject coordinate system
  65270. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  65271. }
  65272. });
  65273. return calendarList;
  65274. };
  65275. function doConvert$2(methodName, ecModel, finder, value) {
  65276. var calendarModel = finder.calendarModel;
  65277. var seriesModel = finder.seriesModel;
  65278. var coordSys = calendarModel
  65279. ? calendarModel.coordinateSystem
  65280. : seriesModel
  65281. ? seriesModel.coordinateSystem
  65282. : null;
  65283. return coordSys === this ? coordSys[methodName](value) : null;
  65284. }
  65285. CoordinateSystemManager.register('calendar', Calendar);
  65286. /*
  65287. * Licensed to the Apache Software Foundation (ASF) under one
  65288. * or more contributor license agreements. See the NOTICE file
  65289. * distributed with this work for additional information
  65290. * regarding copyright ownership. The ASF licenses this file
  65291. * to you under the Apache License, Version 2.0 (the
  65292. * "License"); you may not use this file except in compliance
  65293. * with the License. You may obtain a copy of the License at
  65294. *
  65295. * http://www.apache.org/licenses/LICENSE-2.0
  65296. *
  65297. * Unless required by applicable law or agreed to in writing,
  65298. * software distributed under the License is distributed on an
  65299. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65300. * KIND, either express or implied. See the License for the
  65301. * specific language governing permissions and limitations
  65302. * under the License.
  65303. */
  65304. var CalendarModel = ComponentModel.extend({
  65305. type: 'calendar',
  65306. /**
  65307. * @type {module:echarts/coord/calendar/Calendar}
  65308. */
  65309. coordinateSystem: null,
  65310. defaultOption: {
  65311. zlevel: 0,
  65312. z: 2,
  65313. left: 80,
  65314. top: 60,
  65315. cellSize: 20,
  65316. // horizontal vertical
  65317. orient: 'horizontal',
  65318. // month separate line style
  65319. splitLine: {
  65320. show: true,
  65321. lineStyle: {
  65322. color: '#000',
  65323. width: 1,
  65324. type: 'solid'
  65325. }
  65326. },
  65327. // rect style temporarily unused emphasis
  65328. itemStyle: {
  65329. color: '#fff',
  65330. borderWidth: 1,
  65331. borderColor: '#ccc'
  65332. },
  65333. // week text style
  65334. dayLabel: {
  65335. show: true,
  65336. // a week first day
  65337. firstDay: 0,
  65338. // start end
  65339. position: 'start',
  65340. margin: '50%', // 50% of cellSize
  65341. nameMap: 'en',
  65342. color: '#000'
  65343. },
  65344. // month text style
  65345. monthLabel: {
  65346. show: true,
  65347. // start end
  65348. position: 'start',
  65349. margin: 5,
  65350. // center or left
  65351. align: 'center',
  65352. // cn en []
  65353. nameMap: 'en',
  65354. formatter: null,
  65355. color: '#000'
  65356. },
  65357. // year text style
  65358. yearLabel: {
  65359. show: true,
  65360. // top bottom left right
  65361. position: null,
  65362. margin: 30,
  65363. formatter: null,
  65364. color: '#ccc',
  65365. fontFamily: 'sans-serif',
  65366. fontWeight: 'bolder',
  65367. fontSize: 20
  65368. }
  65369. },
  65370. /**
  65371. * @override
  65372. */
  65373. init: function (option, parentModel, ecModel, extraOpt) {
  65374. var inputPositionParams = getLayoutParams(option);
  65375. CalendarModel.superApply(this, 'init', arguments);
  65376. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  65377. },
  65378. /**
  65379. * @override
  65380. */
  65381. mergeOption: function (option, extraOpt) {
  65382. CalendarModel.superApply(this, 'mergeOption', arguments);
  65383. mergeAndNormalizeLayoutParams$1(this.option, option);
  65384. }
  65385. });
  65386. function mergeAndNormalizeLayoutParams$1(target, raw) {
  65387. // Normalize cellSize
  65388. var cellSize = target.cellSize;
  65389. if (!isArray(cellSize)) {
  65390. cellSize = target.cellSize = [cellSize, cellSize];
  65391. }
  65392. else if (cellSize.length === 1) {
  65393. cellSize[1] = cellSize[0];
  65394. }
  65395. var ignoreSize = map([0, 1], function (hvIdx) {
  65396. // If user have set `width` or both `left` and `right`, cellSize
  65397. // will be automatically set to 'auto', otherwise the default
  65398. // setting of cellSize will make `width` setting not work.
  65399. if (sizeCalculable(raw, hvIdx)) {
  65400. cellSize[hvIdx] = 'auto';
  65401. }
  65402. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  65403. });
  65404. mergeLayoutParam(target, raw, {
  65405. type: 'box', ignoreSize: ignoreSize
  65406. });
  65407. }
  65408. /*
  65409. * Licensed to the Apache Software Foundation (ASF) under one
  65410. * or more contributor license agreements. See the NOTICE file
  65411. * distributed with this work for additional information
  65412. * regarding copyright ownership. The ASF licenses this file
  65413. * to you under the Apache License, Version 2.0 (the
  65414. * "License"); you may not use this file except in compliance
  65415. * with the License. You may obtain a copy of the License at
  65416. *
  65417. * http://www.apache.org/licenses/LICENSE-2.0
  65418. *
  65419. * Unless required by applicable law or agreed to in writing,
  65420. * software distributed under the License is distributed on an
  65421. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65422. * KIND, either express or implied. See the License for the
  65423. * specific language governing permissions and limitations
  65424. * under the License.
  65425. */
  65426. var MONTH_TEXT = {
  65427. EN: [
  65428. 'Jan', 'Feb', 'Mar',
  65429. 'Apr', 'May', 'Jun',
  65430. 'Jul', 'Aug', 'Sep',
  65431. 'Oct', 'Nov', 'Dec'
  65432. ],
  65433. CN: [
  65434. '一月', '二月', '三月',
  65435. '四月', '五月', '六月',
  65436. '七月', '八月', '九月',
  65437. '十月', '十一月', '十二月'
  65438. ]
  65439. };
  65440. var WEEK_TEXT = {
  65441. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  65442. CN: ['日', '一', '二', '三', '四', '五', '六']
  65443. };
  65444. extendComponentView({
  65445. type: 'calendar',
  65446. /**
  65447. * top/left line points
  65448. * @private
  65449. */
  65450. _tlpoints: null,
  65451. /**
  65452. * bottom/right line points
  65453. * @private
  65454. */
  65455. _blpoints: null,
  65456. /**
  65457. * first day of month
  65458. * @private
  65459. */
  65460. _firstDayOfMonth: null,
  65461. /**
  65462. * first day point of month
  65463. * @private
  65464. */
  65465. _firstDayPoints: null,
  65466. render: function (calendarModel, ecModel, api) {
  65467. var group = this.group;
  65468. group.removeAll();
  65469. var coordSys = calendarModel.coordinateSystem;
  65470. // range info
  65471. var rangeData = coordSys.getRangeInfo();
  65472. var orient = coordSys.getOrient();
  65473. this._renderDayRect(calendarModel, rangeData, group);
  65474. // _renderLines must be called prior to following function
  65475. this._renderLines(calendarModel, rangeData, orient, group);
  65476. this._renderYearText(calendarModel, rangeData, orient, group);
  65477. this._renderMonthText(calendarModel, orient, group);
  65478. this._renderWeekText(calendarModel, rangeData, orient, group);
  65479. },
  65480. // render day rect
  65481. _renderDayRect: function (calendarModel, rangeData, group) {
  65482. var coordSys = calendarModel.coordinateSystem;
  65483. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  65484. var sw = coordSys.getCellWidth();
  65485. var sh = coordSys.getCellHeight();
  65486. for (var i = rangeData.start.time;
  65487. i <= rangeData.end.time;
  65488. i = coordSys.getNextNDay(i, 1).time
  65489. ) {
  65490. var point = coordSys.dataToRect([i], false).tl;
  65491. // every rect
  65492. var rect = new Rect({
  65493. shape: {
  65494. x: point[0],
  65495. y: point[1],
  65496. width: sw,
  65497. height: sh
  65498. },
  65499. cursor: 'default',
  65500. style: itemRectStyleModel
  65501. });
  65502. group.add(rect);
  65503. }
  65504. },
  65505. // render separate line
  65506. _renderLines: function (calendarModel, rangeData, orient, group) {
  65507. var self = this;
  65508. var coordSys = calendarModel.coordinateSystem;
  65509. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  65510. var show = calendarModel.get('splitLine.show');
  65511. var lineWidth = lineStyleModel.lineWidth;
  65512. this._tlpoints = [];
  65513. this._blpoints = [];
  65514. this._firstDayOfMonth = [];
  65515. this._firstDayPoints = [];
  65516. var firstDay = rangeData.start;
  65517. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  65518. addPoints(firstDay.formatedDate);
  65519. if (i === 0) {
  65520. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  65521. }
  65522. var date = firstDay.date;
  65523. date.setMonth(date.getMonth() + 1);
  65524. firstDay = coordSys.getDateInfo(date);
  65525. }
  65526. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  65527. function addPoints(date) {
  65528. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  65529. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  65530. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  65531. self._tlpoints.push(points[0]);
  65532. self._blpoints.push(points[points.length - 1]);
  65533. show && self._drawSplitline(points, lineStyleModel, group);
  65534. }
  65535. // render top/left line
  65536. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  65537. // render bottom/right line
  65538. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  65539. },
  65540. // get points at both ends
  65541. _getEdgesPoints: function (points, lineWidth, orient) {
  65542. var rs = [points[0].slice(), points[points.length - 1].slice()];
  65543. var idx = orient === 'horizontal' ? 0 : 1;
  65544. // both ends of the line are extend half lineWidth
  65545. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  65546. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  65547. return rs;
  65548. },
  65549. // render split line
  65550. _drawSplitline: function (points, lineStyleModel, group) {
  65551. var poyline = new Polyline({
  65552. z2: 20,
  65553. shape: {
  65554. points: points
  65555. },
  65556. style: lineStyleModel
  65557. });
  65558. group.add(poyline);
  65559. },
  65560. // render month line of one week points
  65561. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  65562. var coordSys = calendarModel.coordinateSystem;
  65563. date = coordSys.getDateInfo(date);
  65564. var points = [];
  65565. for (var i = 0; i < 7; i++) {
  65566. var tmpD = coordSys.getNextNDay(date.time, i);
  65567. var point = coordSys.dataToRect([tmpD.time], false);
  65568. points[2 * tmpD.day] = point.tl;
  65569. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  65570. }
  65571. return points;
  65572. },
  65573. _formatterLabel: function (formatter, params) {
  65574. if (typeof formatter === 'string' && formatter) {
  65575. return formatTplSimple(formatter, params);
  65576. }
  65577. if (typeof formatter === 'function') {
  65578. return formatter(params);
  65579. }
  65580. return params.nameMap;
  65581. },
  65582. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  65583. point = point.slice();
  65584. var aligns = ['center', 'bottom'];
  65585. if (position === 'bottom') {
  65586. point[1] += margin;
  65587. aligns = ['center', 'top'];
  65588. }
  65589. else if (position === 'left') {
  65590. point[0] -= margin;
  65591. }
  65592. else if (position === 'right') {
  65593. point[0] += margin;
  65594. aligns = ['center', 'top'];
  65595. }
  65596. else { // top
  65597. point[1] -= margin;
  65598. }
  65599. var rotate = 0;
  65600. if (position === 'left' || position === 'right') {
  65601. rotate = Math.PI / 2;
  65602. }
  65603. return {
  65604. rotation: rotate,
  65605. position: point,
  65606. style: {
  65607. textAlign: aligns[0],
  65608. textVerticalAlign: aligns[1]
  65609. }
  65610. };
  65611. },
  65612. // render year
  65613. _renderYearText: function (calendarModel, rangeData, orient, group) {
  65614. var yearLabel = calendarModel.getModel('yearLabel');
  65615. if (!yearLabel.get('show')) {
  65616. return;
  65617. }
  65618. var margin = yearLabel.get('margin');
  65619. var pos = yearLabel.get('position');
  65620. if (!pos) {
  65621. pos = orient !== 'horizontal' ? 'top' : 'left';
  65622. }
  65623. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  65624. var xc = (points[0][0] + points[1][0]) / 2;
  65625. var yc = (points[0][1] + points[1][1]) / 2;
  65626. var idx = orient === 'horizontal' ? 0 : 1;
  65627. var posPoints = {
  65628. top: [xc, points[idx][1]],
  65629. bottom: [xc, points[1 - idx][1]],
  65630. left: [points[1 - idx][0], yc],
  65631. right: [points[idx][0], yc]
  65632. };
  65633. var name = rangeData.start.y;
  65634. if (+rangeData.end.y > +rangeData.start.y) {
  65635. name = name + '-' + rangeData.end.y;
  65636. }
  65637. var formatter = yearLabel.get('formatter');
  65638. var params = {
  65639. start: rangeData.start.y,
  65640. end: rangeData.end.y,
  65641. nameMap: name
  65642. };
  65643. var content = this._formatterLabel(formatter, params);
  65644. var yearText = new Text({z2: 30});
  65645. setTextStyle(yearText.style, yearLabel, {text: content}),
  65646. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  65647. group.add(yearText);
  65648. },
  65649. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  65650. var align = 'left';
  65651. var vAlign = 'top';
  65652. var x = point[0];
  65653. var y = point[1];
  65654. if (orient === 'horizontal') {
  65655. y = y + margin;
  65656. if (isCenter) {
  65657. align = 'center';
  65658. }
  65659. if (position === 'start') {
  65660. vAlign = 'bottom';
  65661. }
  65662. }
  65663. else {
  65664. x = x + margin;
  65665. if (isCenter) {
  65666. vAlign = 'middle';
  65667. }
  65668. if (position === 'start') {
  65669. align = 'right';
  65670. }
  65671. }
  65672. return {
  65673. x: x,
  65674. y: y,
  65675. textAlign: align,
  65676. textVerticalAlign: vAlign
  65677. };
  65678. },
  65679. // render month and year text
  65680. _renderMonthText: function (calendarModel, orient, group) {
  65681. var monthLabel = calendarModel.getModel('monthLabel');
  65682. if (!monthLabel.get('show')) {
  65683. return;
  65684. }
  65685. var nameMap = monthLabel.get('nameMap');
  65686. var margin = monthLabel.get('margin');
  65687. var pos = monthLabel.get('position');
  65688. var align = monthLabel.get('align');
  65689. var termPoints = [this._tlpoints, this._blpoints];
  65690. if (isString(nameMap)) {
  65691. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  65692. }
  65693. var idx = pos === 'start' ? 0 : 1;
  65694. var axis = orient === 'horizontal' ? 0 : 1;
  65695. margin = pos === 'start' ? -margin : margin;
  65696. var isCenter = (align === 'center');
  65697. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  65698. var tmp = termPoints[idx][i].slice();
  65699. var firstDay = this._firstDayOfMonth[i];
  65700. if (isCenter) {
  65701. var firstDayPoints = this._firstDayPoints[i];
  65702. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  65703. }
  65704. var formatter = monthLabel.get('formatter');
  65705. var name = nameMap[+firstDay.m - 1];
  65706. var params = {
  65707. yyyy: firstDay.y,
  65708. yy: (firstDay.y + '').slice(2),
  65709. MM: firstDay.m,
  65710. M: +firstDay.m,
  65711. nameMap: name
  65712. };
  65713. var content = this._formatterLabel(formatter, params);
  65714. var monthText = new Text({z2: 30});
  65715. extend(
  65716. setTextStyle(monthText.style, monthLabel, {text: content}),
  65717. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  65718. );
  65719. group.add(monthText);
  65720. }
  65721. },
  65722. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  65723. var align = 'center';
  65724. var vAlign = 'middle';
  65725. var x = point[0];
  65726. var y = point[1];
  65727. var isStart = position === 'start';
  65728. if (orient === 'horizontal') {
  65729. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  65730. align = isStart ? 'right' : 'left';
  65731. }
  65732. else {
  65733. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  65734. vAlign = isStart ? 'bottom' : 'top';
  65735. }
  65736. return {
  65737. x: x,
  65738. y: y,
  65739. textAlign: align,
  65740. textVerticalAlign: vAlign
  65741. };
  65742. },
  65743. // render weeks
  65744. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  65745. var dayLabel = calendarModel.getModel('dayLabel');
  65746. if (!dayLabel.get('show')) {
  65747. return;
  65748. }
  65749. var coordSys = calendarModel.coordinateSystem;
  65750. var pos = dayLabel.get('position');
  65751. var nameMap = dayLabel.get('nameMap');
  65752. var margin = dayLabel.get('margin');
  65753. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  65754. if (isString(nameMap)) {
  65755. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  65756. }
  65757. var start = coordSys.getNextNDay(
  65758. rangeData.end.time, (7 - rangeData.lweek)
  65759. ).time;
  65760. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  65761. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  65762. if (pos === 'start') {
  65763. start = coordSys.getNextNDay(
  65764. rangeData.start.time, -(7 + rangeData.fweek)
  65765. ).time;
  65766. margin = -margin;
  65767. }
  65768. for (var i = 0; i < 7; i++) {
  65769. var tmpD = coordSys.getNextNDay(start, i);
  65770. var point = coordSys.dataToRect([tmpD.time], false).center;
  65771. var day = i;
  65772. day = Math.abs((i + firstDayOfWeek) % 7);
  65773. var weekText = new Text({z2: 30});
  65774. extend(
  65775. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  65776. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  65777. );
  65778. group.add(weekText);
  65779. }
  65780. }
  65781. });
  65782. /*
  65783. * Licensed to the Apache Software Foundation (ASF) under one
  65784. * or more contributor license agreements. See the NOTICE file
  65785. * distributed with this work for additional information
  65786. * regarding copyright ownership. The ASF licenses this file
  65787. * to you under the Apache License, Version 2.0 (the
  65788. * "License"); you may not use this file except in compliance
  65789. * with the License. You may obtain a copy of the License at
  65790. *
  65791. * http://www.apache.org/licenses/LICENSE-2.0
  65792. *
  65793. * Unless required by applicable law or agreed to in writing,
  65794. * software distributed under the License is distributed on an
  65795. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65796. * KIND, either express or implied. See the License for the
  65797. * specific language governing permissions and limitations
  65798. * under the License.
  65799. */
  65800. /**
  65801. * @file calendar.js
  65802. * @author dxh
  65803. */
  65804. /*
  65805. * Licensed to the Apache Software Foundation (ASF) under one
  65806. * or more contributor license agreements. See the NOTICE file
  65807. * distributed with this work for additional information
  65808. * regarding copyright ownership. The ASF licenses this file
  65809. * to you under the Apache License, Version 2.0 (the
  65810. * "License"); you may not use this file except in compliance
  65811. * with the License. You may obtain a copy of the License at
  65812. *
  65813. * http://www.apache.org/licenses/LICENSE-2.0
  65814. *
  65815. * Unless required by applicable law or agreed to in writing,
  65816. * software distributed under the License is distributed on an
  65817. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65818. * KIND, either express or implied. See the License for the
  65819. * specific language governing permissions and limitations
  65820. * under the License.
  65821. */
  65822. // Model
  65823. extendComponentModel({
  65824. type: 'title',
  65825. layoutMode: {type: 'box', ignoreSize: true},
  65826. defaultOption: {
  65827. // 一级层叠
  65828. zlevel: 0,
  65829. // 二级层叠
  65830. z: 6,
  65831. show: true,
  65832. text: '',
  65833. // 超链接跳转
  65834. // link: null,
  65835. // 仅支持self | blank
  65836. target: 'blank',
  65837. subtext: '',
  65838. // 超链接跳转
  65839. // sublink: null,
  65840. // 仅支持self | blank
  65841. subtarget: 'blank',
  65842. // 'center' ¦ 'left' ¦ 'right'
  65843. // ¦ {number}(x坐标,单位px)
  65844. left: 0,
  65845. // 'top' ¦ 'bottom' ¦ 'center'
  65846. // ¦ {number}(y坐标,单位px)
  65847. top: 0,
  65848. // 水平对齐
  65849. // 'auto' | 'left' | 'right' | 'center'
  65850. // 默认根据 left 的位置判断是左对齐还是右对齐
  65851. // textAlign: null
  65852. //
  65853. // 垂直对齐
  65854. // 'auto' | 'top' | 'bottom' | 'middle'
  65855. // 默认根据 top 位置判断是上对齐还是下对齐
  65856. // textBaseline: null
  65857. backgroundColor: 'rgba(0,0,0,0)',
  65858. // 标题边框颜色
  65859. borderColor: '#ccc',
  65860. // 标题边框线宽,单位px,默认为0(无边框)
  65861. borderWidth: 0,
  65862. // 标题内边距,单位px,默认各方向内边距为5,
  65863. // 接受数组分别设定上右下左边距,同css
  65864. padding: 5,
  65865. // 主副标题纵向间隔,单位px,默认为10,
  65866. itemGap: 10,
  65867. textStyle: {
  65868. fontSize: 18,
  65869. fontWeight: 'bolder',
  65870. color: '#333'
  65871. },
  65872. subtextStyle: {
  65873. color: '#aaa'
  65874. }
  65875. }
  65876. });
  65877. // View
  65878. extendComponentView({
  65879. type: 'title',
  65880. render: function (titleModel, ecModel, api) {
  65881. this.group.removeAll();
  65882. if (!titleModel.get('show')) {
  65883. return;
  65884. }
  65885. var group = this.group;
  65886. var textStyleModel = titleModel.getModel('textStyle');
  65887. var subtextStyleModel = titleModel.getModel('subtextStyle');
  65888. var textAlign = titleModel.get('textAlign');
  65889. var textBaseline = titleModel.get('textBaseline');
  65890. var textEl = new Text({
  65891. style: setTextStyle({}, textStyleModel, {
  65892. text: titleModel.get('text'),
  65893. textFill: textStyleModel.getTextColor()
  65894. }, {disableBox: true}),
  65895. z2: 10
  65896. });
  65897. var textRect = textEl.getBoundingRect();
  65898. var subText = titleModel.get('subtext');
  65899. var subTextEl = new Text({
  65900. style: setTextStyle({}, subtextStyleModel, {
  65901. text: subText,
  65902. textFill: subtextStyleModel.getTextColor(),
  65903. y: textRect.height + titleModel.get('itemGap'),
  65904. textVerticalAlign: 'top'
  65905. }, {disableBox: true}),
  65906. z2: 10
  65907. });
  65908. var link = titleModel.get('link');
  65909. var sublink = titleModel.get('sublink');
  65910. textEl.silent = !link;
  65911. subTextEl.silent = !sublink;
  65912. if (link) {
  65913. textEl.on('click', function () {
  65914. window.open(link, '_' + titleModel.get('target'));
  65915. });
  65916. }
  65917. if (sublink) {
  65918. subTextEl.on('click', function () {
  65919. window.open(sublink, '_' + titleModel.get('subtarget'));
  65920. });
  65921. }
  65922. group.add(textEl);
  65923. subText && group.add(subTextEl);
  65924. // If no subText, but add subTextEl, there will be an empty line.
  65925. var groupRect = group.getBoundingRect();
  65926. var layoutOption = titleModel.getBoxLayoutParams();
  65927. layoutOption.width = groupRect.width;
  65928. layoutOption.height = groupRect.height;
  65929. var layoutRect = getLayoutRect(
  65930. layoutOption, {
  65931. width: api.getWidth(),
  65932. height: api.getHeight()
  65933. }, titleModel.get('padding')
  65934. );
  65935. // Adjust text align based on position
  65936. if (!textAlign) {
  65937. // Align left if title is on the left. center and right is same
  65938. textAlign = titleModel.get('left') || titleModel.get('right');
  65939. if (textAlign === 'middle') {
  65940. textAlign = 'center';
  65941. }
  65942. // Adjust layout by text align
  65943. if (textAlign === 'right') {
  65944. layoutRect.x += layoutRect.width;
  65945. }
  65946. else if (textAlign === 'center') {
  65947. layoutRect.x += layoutRect.width / 2;
  65948. }
  65949. }
  65950. if (!textBaseline) {
  65951. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  65952. if (textBaseline === 'center') {
  65953. textBaseline = 'middle';
  65954. }
  65955. if (textBaseline === 'bottom') {
  65956. layoutRect.y += layoutRect.height;
  65957. }
  65958. else if (textBaseline === 'middle') {
  65959. layoutRect.y += layoutRect.height / 2;
  65960. }
  65961. textBaseline = textBaseline || 'top';
  65962. }
  65963. group.attr('position', [layoutRect.x, layoutRect.y]);
  65964. var alignStyle = {
  65965. textAlign: textAlign,
  65966. textVerticalAlign: textBaseline
  65967. };
  65968. textEl.setStyle(alignStyle);
  65969. subTextEl.setStyle(alignStyle);
  65970. // Render background
  65971. // Get groupRect again because textAlign has been changed
  65972. groupRect = group.getBoundingRect();
  65973. var padding = layoutRect.margin;
  65974. var style = titleModel.getItemStyle(['color', 'opacity']);
  65975. style.fill = titleModel.get('backgroundColor');
  65976. var rect = new Rect({
  65977. shape: {
  65978. x: groupRect.x - padding[3],
  65979. y: groupRect.y - padding[0],
  65980. width: groupRect.width + padding[1] + padding[3],
  65981. height: groupRect.height + padding[0] + padding[2],
  65982. r: titleModel.get('borderRadius')
  65983. },
  65984. style: style,
  65985. silent: true
  65986. });
  65987. subPixelOptimizeRect(rect);
  65988. group.add(rect);
  65989. }
  65990. });
  65991. /*
  65992. * Licensed to the Apache Software Foundation (ASF) under one
  65993. * or more contributor license agreements. See the NOTICE file
  65994. * distributed with this work for additional information
  65995. * regarding copyright ownership. The ASF licenses this file
  65996. * to you under the Apache License, Version 2.0 (the
  65997. * "License"); you may not use this file except in compliance
  65998. * with the License. You may obtain a copy of the License at
  65999. *
  66000. * http://www.apache.org/licenses/LICENSE-2.0
  66001. *
  66002. * Unless required by applicable law or agreed to in writing,
  66003. * software distributed under the License is distributed on an
  66004. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66005. * KIND, either express or implied. See the License for the
  66006. * specific language governing permissions and limitations
  66007. * under the License.
  66008. */
  66009. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  66010. // Default 'slider' when no type specified.
  66011. return 'slider';
  66012. });
  66013. /*
  66014. * Licensed to the Apache Software Foundation (ASF) under one
  66015. * or more contributor license agreements. See the NOTICE file
  66016. * distributed with this work for additional information
  66017. * regarding copyright ownership. The ASF licenses this file
  66018. * to you under the Apache License, Version 2.0 (the
  66019. * "License"); you may not use this file except in compliance
  66020. * with the License. You may obtain a copy of the License at
  66021. *
  66022. * http://www.apache.org/licenses/LICENSE-2.0
  66023. *
  66024. * Unless required by applicable law or agreed to in writing,
  66025. * software distributed under the License is distributed on an
  66026. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66027. * KIND, either express or implied. See the License for the
  66028. * specific language governing permissions and limitations
  66029. * under the License.
  66030. */
  66031. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  66032. // Supported coords.
  66033. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  66034. /**
  66035. * @param {string} coordType
  66036. * @return {boolean}
  66037. */
  66038. function isCoordSupported(coordType) {
  66039. return indexOf(COORDS, coordType) >= 0;
  66040. }
  66041. /**
  66042. * Create "each" method to iterate names.
  66043. *
  66044. * @pubilc
  66045. * @param {Array.<string>} names
  66046. * @param {Array.<string>=} attrs
  66047. * @return {Function}
  66048. */
  66049. function createNameEach(names, attrs) {
  66050. names = names.slice();
  66051. var capitalNames = map(names, capitalFirst);
  66052. attrs = (attrs || []).slice();
  66053. var capitalAttrs = map(attrs, capitalFirst);
  66054. return function (callback, context) {
  66055. each$1(names, function (name, index) {
  66056. var nameObj = {name: name, capital: capitalNames[index]};
  66057. for (var j = 0; j < attrs.length; j++) {
  66058. nameObj[attrs[j]] = name + capitalAttrs[j];
  66059. }
  66060. callback.call(context, nameObj);
  66061. });
  66062. };
  66063. }
  66064. /**
  66065. * Iterate each dimension name.
  66066. *
  66067. * @public
  66068. * @param {Function} callback The parameter is like:
  66069. * {
  66070. * name: 'angle',
  66071. * capital: 'Angle',
  66072. * axis: 'angleAxis',
  66073. * axisIndex: 'angleAixs',
  66074. * index: 'angleIndex'
  66075. * }
  66076. * @param {Object} context
  66077. */
  66078. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  66079. /**
  66080. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  66081. * dataZoomModels and 'links' make up one or more graphics.
  66082. * This function finds the graphic where the source dataZoomModel is in.
  66083. *
  66084. * @public
  66085. * @param {Function} forEachNode Node iterator.
  66086. * @param {Function} forEachEdgeType edgeType iterator
  66087. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  66088. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  66089. */
  66090. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  66091. return function (sourceNode) {
  66092. var result = {
  66093. nodes: [],
  66094. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  66095. };
  66096. forEachEdgeType(function (edgeType) {
  66097. result.records[edgeType.name] = {};
  66098. });
  66099. if (!sourceNode) {
  66100. return result;
  66101. }
  66102. absorb(sourceNode, result);
  66103. var existsLink;
  66104. do {
  66105. existsLink = false;
  66106. forEachNode(processSingleNode);
  66107. }
  66108. while (existsLink);
  66109. function processSingleNode(node) {
  66110. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  66111. absorb(node, result);
  66112. existsLink = true;
  66113. }
  66114. }
  66115. return result;
  66116. };
  66117. function isNodeAbsorded(node, result) {
  66118. return indexOf(result.nodes, node) >= 0;
  66119. }
  66120. function isLinked(node, result) {
  66121. var hasLink = false;
  66122. forEachEdgeType(function (edgeType) {
  66123. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  66124. result.records[edgeType.name][edgeId] && (hasLink = true);
  66125. });
  66126. });
  66127. return hasLink;
  66128. }
  66129. function absorb(node, result) {
  66130. result.nodes.push(node);
  66131. forEachEdgeType(function (edgeType) {
  66132. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  66133. result.records[edgeType.name][edgeId] = true;
  66134. });
  66135. });
  66136. }
  66137. }
  66138. /*
  66139. * Licensed to the Apache Software Foundation (ASF) under one
  66140. * or more contributor license agreements. See the NOTICE file
  66141. * distributed with this work for additional information
  66142. * regarding copyright ownership. The ASF licenses this file
  66143. * to you under the Apache License, Version 2.0 (the
  66144. * "License"); you may not use this file except in compliance
  66145. * with the License. You may obtain a copy of the License at
  66146. *
  66147. * http://www.apache.org/licenses/LICENSE-2.0
  66148. *
  66149. * Unless required by applicable law or agreed to in writing,
  66150. * software distributed under the License is distributed on an
  66151. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66152. * KIND, either express or implied. See the License for the
  66153. * specific language governing permissions and limitations
  66154. * under the License.
  66155. */
  66156. var each$22 = each$1;
  66157. var asc$1 = asc;
  66158. /**
  66159. * Operate single axis.
  66160. * One axis can only operated by one axis operator.
  66161. * Different dataZoomModels may be defined to operate the same axis.
  66162. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  66163. * So dataZoomModels share one axisProxy in that case.
  66164. *
  66165. * @class
  66166. */
  66167. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  66168. /**
  66169. * @private
  66170. * @type {string}
  66171. */
  66172. this._dimName = dimName;
  66173. /**
  66174. * @private
  66175. */
  66176. this._axisIndex = axisIndex;
  66177. /**
  66178. * @private
  66179. * @type {Array.<number>}
  66180. */
  66181. this._valueWindow;
  66182. /**
  66183. * @private
  66184. * @type {Array.<number>}
  66185. */
  66186. this._percentWindow;
  66187. /**
  66188. * @private
  66189. * @type {Array.<number>}
  66190. */
  66191. this._dataExtent;
  66192. /**
  66193. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  66194. * @private
  66195. * @type {Object}
  66196. */
  66197. this._minMaxSpan;
  66198. /**
  66199. * @readOnly
  66200. * @type {module: echarts/model/Global}
  66201. */
  66202. this.ecModel = ecModel;
  66203. /**
  66204. * @private
  66205. * @type {module: echarts/component/dataZoom/DataZoomModel}
  66206. */
  66207. this._dataZoomModel = dataZoomModel;
  66208. // /**
  66209. // * @readOnly
  66210. // * @private
  66211. // */
  66212. // this.hasSeriesStacked;
  66213. };
  66214. AxisProxy.prototype = {
  66215. constructor: AxisProxy,
  66216. /**
  66217. * Whether the axisProxy is hosted by dataZoomModel.
  66218. *
  66219. * @public
  66220. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66221. * @return {boolean}
  66222. */
  66223. hostedBy: function (dataZoomModel) {
  66224. return this._dataZoomModel === dataZoomModel;
  66225. },
  66226. /**
  66227. * @return {Array.<number>} Value can only be NaN or finite value.
  66228. */
  66229. getDataValueWindow: function () {
  66230. return this._valueWindow.slice();
  66231. },
  66232. /**
  66233. * @return {Array.<number>}
  66234. */
  66235. getDataPercentWindow: function () {
  66236. return this._percentWindow.slice();
  66237. },
  66238. /**
  66239. * @public
  66240. * @param {number} axisIndex
  66241. * @return {Array} seriesModels
  66242. */
  66243. getTargetSeriesModels: function () {
  66244. var seriesModels = [];
  66245. var ecModel = this.ecModel;
  66246. ecModel.eachSeries(function (seriesModel) {
  66247. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  66248. var dimName = this._dimName;
  66249. var axisModel = ecModel.queryComponents({
  66250. mainType: dimName + 'Axis',
  66251. index: seriesModel.get(dimName + 'AxisIndex'),
  66252. id: seriesModel.get(dimName + 'AxisId')
  66253. })[0];
  66254. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  66255. seriesModels.push(seriesModel);
  66256. }
  66257. }
  66258. }, this);
  66259. return seriesModels;
  66260. },
  66261. getAxisModel: function () {
  66262. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  66263. },
  66264. getOtherAxisModel: function () {
  66265. var axisDim = this._dimName;
  66266. var ecModel = this.ecModel;
  66267. var axisModel = this.getAxisModel();
  66268. var isCartesian = axisDim === 'x' || axisDim === 'y';
  66269. var otherAxisDim;
  66270. var coordSysIndexName;
  66271. if (isCartesian) {
  66272. coordSysIndexName = 'gridIndex';
  66273. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  66274. }
  66275. else {
  66276. coordSysIndexName = 'polarIndex';
  66277. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  66278. }
  66279. var foundOtherAxisModel;
  66280. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  66281. if ((otherAxisModel.get(coordSysIndexName) || 0)
  66282. === (axisModel.get(coordSysIndexName) || 0)
  66283. ) {
  66284. foundOtherAxisModel = otherAxisModel;
  66285. }
  66286. });
  66287. return foundOtherAxisModel;
  66288. },
  66289. getMinMaxSpan: function () {
  66290. return clone(this._minMaxSpan);
  66291. },
  66292. /**
  66293. * Only calculate by given range and this._dataExtent, do not change anything.
  66294. *
  66295. * @param {Object} opt
  66296. * @param {number} [opt.start]
  66297. * @param {number} [opt.end]
  66298. * @param {number} [opt.startValue]
  66299. * @param {number} [opt.endValue]
  66300. */
  66301. calculateDataWindow: function (opt) {
  66302. var dataExtent = this._dataExtent;
  66303. var axisModel = this.getAxisModel();
  66304. var scale = axisModel.axis.scale;
  66305. var rangePropMode = this._dataZoomModel.getRangePropMode();
  66306. var percentExtent = [0, 100];
  66307. var percentWindow = [
  66308. opt.start,
  66309. opt.end
  66310. ];
  66311. var valueWindow = [];
  66312. each$22(['startValue', 'endValue'], function (prop) {
  66313. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  66314. });
  66315. // Normalize bound.
  66316. each$22([0, 1], function (idx) {
  66317. var boundValue = valueWindow[idx];
  66318. var boundPercent = percentWindow[idx];
  66319. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  66320. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  66321. // for cases that a dataZoom component controls multiple axes with different
  66322. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  66323. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  66324. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  66325. // accurately (because all of values that are overflow the `dataExtent` will
  66326. // be calculated to percent '100%'). So we have to use
  66327. // `dataZoom.getRangePropMode()` to mark which prop is used.
  66328. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  66329. // it remains its original value.
  66330. if (rangePropMode[idx] === 'percent') {
  66331. if (boundPercent == null) {
  66332. boundPercent = percentExtent[idx];
  66333. }
  66334. // Use scale.parse to math round for category or time axis.
  66335. boundValue = scale.parse(linearMap(
  66336. boundPercent, percentExtent, dataExtent, true
  66337. ));
  66338. }
  66339. else {
  66340. // Calculating `percent` from `value` may be not accurate, because
  66341. // This calculation can not be inversed, because all of values that
  66342. // are overflow the `dataExtent` will be calculated to percent '100%'
  66343. boundPercent = linearMap(
  66344. boundValue, dataExtent, percentExtent, true
  66345. );
  66346. }
  66347. // valueWindow[idx] = round(boundValue);
  66348. // percentWindow[idx] = round(boundPercent);
  66349. valueWindow[idx] = boundValue;
  66350. percentWindow[idx] = boundPercent;
  66351. });
  66352. return {
  66353. valueWindow: asc$1(valueWindow),
  66354. percentWindow: asc$1(percentWindow)
  66355. };
  66356. },
  66357. /**
  66358. * Notice: reset should not be called before series.restoreData() called,
  66359. * so it is recommanded to be called in "process stage" but not "model init
  66360. * stage".
  66361. *
  66362. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66363. */
  66364. reset: function (dataZoomModel) {
  66365. if (dataZoomModel !== this._dataZoomModel) {
  66366. return;
  66367. }
  66368. var targetSeries = this.getTargetSeriesModels();
  66369. // Culculate data window and data extent, and record them.
  66370. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  66371. // this.hasSeriesStacked = false;
  66372. // each(targetSeries, function (series) {
  66373. // var data = series.getData();
  66374. // var dataDim = data.mapDimension(this._dimName);
  66375. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  66376. // if (stackedDimension && stackedDimension === dataDim) {
  66377. // this.hasSeriesStacked = true;
  66378. // }
  66379. // }, this);
  66380. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  66381. this._valueWindow = dataWindow.valueWindow;
  66382. this._percentWindow = dataWindow.percentWindow;
  66383. setMinMaxSpan(this);
  66384. // Update axis setting then.
  66385. setAxisModel(this);
  66386. },
  66387. /**
  66388. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66389. */
  66390. restore: function (dataZoomModel) {
  66391. if (dataZoomModel !== this._dataZoomModel) {
  66392. return;
  66393. }
  66394. this._valueWindow = this._percentWindow = null;
  66395. setAxisModel(this, true);
  66396. },
  66397. /**
  66398. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66399. */
  66400. filterData: function (dataZoomModel, api) {
  66401. if (dataZoomModel !== this._dataZoomModel) {
  66402. return;
  66403. }
  66404. var axisDim = this._dimName;
  66405. var seriesModels = this.getTargetSeriesModels();
  66406. var filterMode = dataZoomModel.get('filterMode');
  66407. var valueWindow = this._valueWindow;
  66408. if (filterMode === 'none') {
  66409. return;
  66410. }
  66411. // FIXME
  66412. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  66413. // with NaN data, NaN will be filtered and stack will be wrong.
  66414. // So we need to force the mode to be set empty.
  66415. // In fect, it is not a big deal that do not support filterMode-'filter'
  66416. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  66417. // selection" some day, which might need "adapt to data extent on the
  66418. // otherAxis", which is disabled by filterMode-'empty'.
  66419. // But currently, stack has been fixed to based on value but not index,
  66420. // so this is not an issue any more.
  66421. // var otherAxisModel = this.getOtherAxisModel();
  66422. // if (dataZoomModel.get('$fromToolbox')
  66423. // && otherAxisModel
  66424. // && otherAxisModel.hasSeriesStacked
  66425. // ) {
  66426. // filterMode = 'empty';
  66427. // }
  66428. // TODO
  66429. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  66430. // Process series data
  66431. each$22(seriesModels, function (seriesModel) {
  66432. var seriesData = seriesModel.getData();
  66433. var dataDims = seriesData.mapDimension(axisDim, true);
  66434. if (filterMode === 'weakFilter') {
  66435. seriesData.filterSelf(function (dataIndex) {
  66436. var leftOut;
  66437. var rightOut;
  66438. var hasValue;
  66439. for (var i = 0; i < dataDims.length; i++) {
  66440. var value = seriesData.get(dataDims[i], dataIndex);
  66441. var thisHasValue = !isNaN(value);
  66442. var thisLeftOut = value < valueWindow[0];
  66443. var thisRightOut = value > valueWindow[1];
  66444. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  66445. return true;
  66446. }
  66447. thisHasValue && (hasValue = true);
  66448. thisLeftOut && (leftOut = true);
  66449. thisRightOut && (rightOut = true);
  66450. }
  66451. // If both left out and right out, do not filter.
  66452. return hasValue && leftOut && rightOut;
  66453. });
  66454. }
  66455. else {
  66456. each$22(dataDims, function (dim) {
  66457. if (filterMode === 'empty') {
  66458. seriesModel.setData(
  66459. seriesData.map(dim, function (value) {
  66460. return !isInWindow(value) ? NaN : value;
  66461. })
  66462. );
  66463. }
  66464. else {
  66465. var range = {};
  66466. range[dim] = valueWindow;
  66467. // console.time('select');
  66468. seriesData.selectRange(range);
  66469. // console.timeEnd('select');
  66470. }
  66471. });
  66472. }
  66473. each$22(dataDims, function (dim) {
  66474. seriesData.setApproximateExtent(valueWindow, dim);
  66475. });
  66476. });
  66477. function isInWindow(value) {
  66478. return value >= valueWindow[0] && value <= valueWindow[1];
  66479. }
  66480. }
  66481. };
  66482. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  66483. var dataExtent = [Infinity, -Infinity];
  66484. each$22(seriesModels, function (seriesModel) {
  66485. var seriesData = seriesModel.getData();
  66486. if (seriesData) {
  66487. each$22(seriesData.mapDimension(axisDim, true), function (dim) {
  66488. var seriesExtent = seriesData.getApproximateExtent(dim);
  66489. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  66490. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  66491. });
  66492. }
  66493. });
  66494. if (dataExtent[1] < dataExtent[0]) {
  66495. dataExtent = [NaN, NaN];
  66496. }
  66497. // It is important to get "consistent" extent when more then one axes is
  66498. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  66499. // when zooming. But it is difficult to know what is "consistent", considering
  66500. // axes have different type or even different meanings (For example, two
  66501. // time axes are used to compare data of the same date in different years).
  66502. // So basically dataZoom just obtains extent by series.data (in category axis
  66503. // extent can be obtained from axis.data).
  66504. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  66505. // consistent.
  66506. fixExtentByAxis(axisProxy, dataExtent);
  66507. return dataExtent;
  66508. }
  66509. function fixExtentByAxis(axisProxy, dataExtent) {
  66510. var axisModel = axisProxy.getAxisModel();
  66511. var min = axisModel.getMin(true);
  66512. // For category axis, if min/max/scale are not set, extent is determined
  66513. // by axis.data by default.
  66514. var isCategoryAxis = axisModel.get('type') === 'category';
  66515. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  66516. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  66517. dataExtent[0] = min;
  66518. }
  66519. else if (isCategoryAxis) {
  66520. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  66521. }
  66522. var max = axisModel.getMax(true);
  66523. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  66524. dataExtent[1] = max;
  66525. }
  66526. else if (isCategoryAxis) {
  66527. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  66528. }
  66529. if (!axisModel.get('scale', true)) {
  66530. dataExtent[0] > 0 && (dataExtent[0] = 0);
  66531. dataExtent[1] < 0 && (dataExtent[1] = 0);
  66532. }
  66533. // For value axis, if min/max/scale are not set, we just use the extent obtained
  66534. // by series data, which may be a little different from the extent calculated by
  66535. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  66536. // little when zooming. So it will not be fixed until some users require it strongly.
  66537. return dataExtent;
  66538. }
  66539. function setAxisModel(axisProxy, isRestore) {
  66540. var axisModel = axisProxy.getAxisModel();
  66541. var percentWindow = axisProxy._percentWindow;
  66542. var valueWindow = axisProxy._valueWindow;
  66543. if (!percentWindow) {
  66544. return;
  66545. }
  66546. // [0, 500]: arbitrary value, guess axis extent.
  66547. var precision = getPixelPrecision(valueWindow, [0, 500]);
  66548. precision = Math.min(precision, 20);
  66549. // isRestore or isFull
  66550. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  66551. axisModel.setRange(
  66552. useOrigin ? null : +valueWindow[0].toFixed(precision),
  66553. useOrigin ? null : +valueWindow[1].toFixed(precision)
  66554. );
  66555. }
  66556. function setMinMaxSpan(axisProxy) {
  66557. var minMaxSpan = axisProxy._minMaxSpan = {};
  66558. var dataZoomModel = axisProxy._dataZoomModel;
  66559. each$22(['min', 'max'], function (minMax) {
  66560. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  66561. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  66562. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  66563. if (valueSpan != null) {
  66564. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  66565. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  66566. if (valueSpan != null) {
  66567. var dataExtent = axisProxy._dataExtent;
  66568. minMaxSpan[minMax + 'Span'] = linearMap(
  66569. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  66570. );
  66571. }
  66572. }
  66573. });
  66574. }
  66575. /*
  66576. * Licensed to the Apache Software Foundation (ASF) under one
  66577. * or more contributor license agreements. See the NOTICE file
  66578. * distributed with this work for additional information
  66579. * regarding copyright ownership. The ASF licenses this file
  66580. * to you under the Apache License, Version 2.0 (the
  66581. * "License"); you may not use this file except in compliance
  66582. * with the License. You may obtain a copy of the License at
  66583. *
  66584. * http://www.apache.org/licenses/LICENSE-2.0
  66585. *
  66586. * Unless required by applicable law or agreed to in writing,
  66587. * software distributed under the License is distributed on an
  66588. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66589. * KIND, either express or implied. See the License for the
  66590. * specific language governing permissions and limitations
  66591. * under the License.
  66592. */
  66593. var each$21 = each$1;
  66594. var eachAxisDim = eachAxisDim$1;
  66595. var DataZoomModel = extendComponentModel({
  66596. type: 'dataZoom',
  66597. dependencies: [
  66598. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  66599. ],
  66600. /**
  66601. * @protected
  66602. */
  66603. defaultOption: {
  66604. zlevel: 0,
  66605. z: 4, // Higher than normal component (z: 2).
  66606. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  66607. xAxisIndex: null, // Default the first horizontal category axis.
  66608. yAxisIndex: null, // Default the first vertical category axis.
  66609. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  66610. // 'filter': data items which are out of window will be removed. This option is
  66611. // applicable when filtering outliers. For each data item, it will be
  66612. // filtered if one of the relevant dimensions is out of the window.
  66613. // 'weakFilter': data items which are out of window will be removed. This option
  66614. // is applicable when filtering outliers. For each data item, it will be
  66615. // filtered only if all of the relevant dimensions are out of the same
  66616. // side of the window.
  66617. // 'empty': data items which are out of window will be set to empty.
  66618. // This option is applicable when user should not neglect
  66619. // that there are some data items out of window.
  66620. // 'none': Do not filter.
  66621. // Taking line chart as an example, line will be broken in
  66622. // the filtered points when filterModel is set to 'empty', but
  66623. // be connected when set to 'filter'.
  66624. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  66625. // default 100. Do not throttle when use null/undefined.
  66626. // If animation === true and animationDurationUpdate > 0,
  66627. // default value is 100, otherwise 20.
  66628. start: 0, // Start percent. 0 ~ 100
  66629. end: 100, // End percent. 0 ~ 100
  66630. startValue: null, // Start value. If startValue specified, start is ignored.
  66631. endValue: null, // End value. If endValue specified, end is ignored.
  66632. minSpan: null, // 0 ~ 100
  66633. maxSpan: null, // 0 ~ 100
  66634. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  66635. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  66636. rangeMode: null // Array, can be 'value' or 'percent'.
  66637. },
  66638. /**
  66639. * @override
  66640. */
  66641. init: function (option, parentModel, ecModel) {
  66642. /**
  66643. * key like x_0, y_1
  66644. * @private
  66645. * @type {Object}
  66646. */
  66647. this._dataIntervalByAxis = {};
  66648. /**
  66649. * @private
  66650. */
  66651. this._dataInfo = {};
  66652. /**
  66653. * key like x_0, y_1
  66654. * @private
  66655. */
  66656. this._axisProxies = {};
  66657. /**
  66658. * @readOnly
  66659. */
  66660. this.textStyleModel;
  66661. /**
  66662. * @private
  66663. */
  66664. this._autoThrottle = true;
  66665. /**
  66666. * 'percent' or 'value'
  66667. * @private
  66668. */
  66669. this._rangePropMode = ['percent', 'percent'];
  66670. var rawOption = retrieveRaw(option);
  66671. this.mergeDefaultAndTheme(option, ecModel);
  66672. this.doInit(rawOption);
  66673. },
  66674. /**
  66675. * @override
  66676. */
  66677. mergeOption: function (newOption) {
  66678. var rawOption = retrieveRaw(newOption);
  66679. //FIX #2591
  66680. merge(this.option, newOption, true);
  66681. this.doInit(rawOption);
  66682. },
  66683. /**
  66684. * @protected
  66685. */
  66686. doInit: function (rawOption) {
  66687. var thisOption = this.option;
  66688. // Disable realtime view update if canvas is not supported.
  66689. if (!env$1.canvasSupported) {
  66690. thisOption.realtime = false;
  66691. }
  66692. this._setDefaultThrottle(rawOption);
  66693. updateRangeUse(this, rawOption);
  66694. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  66695. // start/end has higher priority over startValue/endValue if they
  66696. // both set, but we should make chart.setOption({endValue: 1000})
  66697. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  66698. if (this._rangePropMode[index] === 'value') {
  66699. thisOption[names[0]] = null;
  66700. }
  66701. // Otherwise do nothing and use the merge result.
  66702. }, this);
  66703. this.textStyleModel = this.getModel('textStyle');
  66704. this._resetTarget();
  66705. this._giveAxisProxies();
  66706. },
  66707. /**
  66708. * @private
  66709. */
  66710. _giveAxisProxies: function () {
  66711. var axisProxies = this._axisProxies;
  66712. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  66713. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  66714. // If exists, share axisProxy with other dataZoomModels.
  66715. var axisProxy = axisModel.__dzAxisProxy || (
  66716. // Use the first dataZoomModel as the main model of axisProxy.
  66717. axisModel.__dzAxisProxy = new AxisProxy(
  66718. dimNames.name, axisIndex, this, ecModel
  66719. )
  66720. );
  66721. // FIXME
  66722. // dispose __dzAxisProxy
  66723. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  66724. }, this);
  66725. },
  66726. /**
  66727. * @private
  66728. */
  66729. _resetTarget: function () {
  66730. var thisOption = this.option;
  66731. var autoMode = this._judgeAutoMode();
  66732. eachAxisDim(function (dimNames) {
  66733. var axisIndexName = dimNames.axisIndex;
  66734. thisOption[axisIndexName] = normalizeToArray(
  66735. thisOption[axisIndexName]
  66736. );
  66737. }, this);
  66738. if (autoMode === 'axisIndex') {
  66739. this._autoSetAxisIndex();
  66740. }
  66741. else if (autoMode === 'orient') {
  66742. this._autoSetOrient();
  66743. }
  66744. },
  66745. /**
  66746. * @private
  66747. */
  66748. _judgeAutoMode: function () {
  66749. // Auto set only works for setOption at the first time.
  66750. // The following is user's reponsibility. So using merged
  66751. // option is OK.
  66752. var thisOption = this.option;
  66753. var hasIndexSpecified = false;
  66754. eachAxisDim(function (dimNames) {
  66755. // When user set axisIndex as a empty array, we think that user specify axisIndex
  66756. // but do not want use auto mode. Because empty array may be encountered when
  66757. // some error occured.
  66758. if (thisOption[dimNames.axisIndex] != null) {
  66759. hasIndexSpecified = true;
  66760. }
  66761. }, this);
  66762. var orient = thisOption.orient;
  66763. if (orient == null && hasIndexSpecified) {
  66764. return 'orient';
  66765. }
  66766. else if (!hasIndexSpecified) {
  66767. if (orient == null) {
  66768. thisOption.orient = 'horizontal';
  66769. }
  66770. return 'axisIndex';
  66771. }
  66772. },
  66773. /**
  66774. * @private
  66775. */
  66776. _autoSetAxisIndex: function () {
  66777. var autoAxisIndex = true;
  66778. var orient = this.get('orient', true);
  66779. var thisOption = this.option;
  66780. var dependentModels = this.dependentModels;
  66781. if (autoAxisIndex) {
  66782. // Find axis that parallel to dataZoom as default.
  66783. var dimName = orient === 'vertical' ? 'y' : 'x';
  66784. if (dependentModels[dimName + 'Axis'].length) {
  66785. thisOption[dimName + 'AxisIndex'] = [0];
  66786. autoAxisIndex = false;
  66787. }
  66788. else {
  66789. each$21(dependentModels.singleAxis, function (singleAxisModel) {
  66790. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  66791. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  66792. autoAxisIndex = false;
  66793. }
  66794. });
  66795. }
  66796. }
  66797. if (autoAxisIndex) {
  66798. // Find the first category axis as default. (consider polar)
  66799. eachAxisDim(function (dimNames) {
  66800. if (!autoAxisIndex) {
  66801. return;
  66802. }
  66803. var axisIndices = [];
  66804. var axisModels = this.dependentModels[dimNames.axis];
  66805. if (axisModels.length && !axisIndices.length) {
  66806. for (var i = 0, len = axisModels.length; i < len; i++) {
  66807. if (axisModels[i].get('type') === 'category') {
  66808. axisIndices.push(i);
  66809. }
  66810. }
  66811. }
  66812. thisOption[dimNames.axisIndex] = axisIndices;
  66813. if (axisIndices.length) {
  66814. autoAxisIndex = false;
  66815. }
  66816. }, this);
  66817. }
  66818. if (autoAxisIndex) {
  66819. // FIXME
  66820. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  66821. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  66822. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  66823. // dataZoom component auto adopts series that reference to
  66824. // both xAxis and yAxis which type is 'value'.
  66825. this.ecModel.eachSeries(function (seriesModel) {
  66826. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  66827. eachAxisDim(function (dimNames) {
  66828. var axisIndices = thisOption[dimNames.axisIndex];
  66829. var axisIndex = seriesModel.get(dimNames.axisIndex);
  66830. var axisId = seriesModel.get(dimNames.axisId);
  66831. var axisModel = seriesModel.ecModel.queryComponents({
  66832. mainType: dimNames.axis,
  66833. index: axisIndex,
  66834. id: axisId
  66835. })[0];
  66836. if (__DEV__) {
  66837. if (!axisModel) {
  66838. throw new Error(
  66839. dimNames.axis + ' "' + retrieve(
  66840. axisIndex,
  66841. axisId,
  66842. 0
  66843. ) + '" not found'
  66844. );
  66845. }
  66846. }
  66847. axisIndex = axisModel.componentIndex;
  66848. if (indexOf(axisIndices, axisIndex) < 0) {
  66849. axisIndices.push(axisIndex);
  66850. }
  66851. });
  66852. }
  66853. }, this);
  66854. }
  66855. },
  66856. /**
  66857. * @private
  66858. */
  66859. _autoSetOrient: function () {
  66860. var dim;
  66861. // Find the first axis
  66862. this.eachTargetAxis(function (dimNames) {
  66863. !dim && (dim = dimNames.name);
  66864. }, this);
  66865. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  66866. },
  66867. /**
  66868. * @private
  66869. */
  66870. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  66871. // FIXME
  66872. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  66873. // 例如series.type === scatter时。
  66874. var is = true;
  66875. eachAxisDim(function (dimNames) {
  66876. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  66877. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  66878. if (!axisModel || axisModel.get('type') !== axisType) {
  66879. is = false;
  66880. }
  66881. }, this);
  66882. return is;
  66883. },
  66884. /**
  66885. * @private
  66886. */
  66887. _setDefaultThrottle: function (rawOption) {
  66888. // When first time user set throttle, auto throttle ends.
  66889. if (rawOption.hasOwnProperty('throttle')) {
  66890. this._autoThrottle = false;
  66891. }
  66892. if (this._autoThrottle) {
  66893. var globalOption = this.ecModel.option;
  66894. this.option.throttle =
  66895. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  66896. ? 100 : 20;
  66897. }
  66898. },
  66899. /**
  66900. * @public
  66901. */
  66902. getFirstTargetAxisModel: function () {
  66903. var firstAxisModel;
  66904. eachAxisDim(function (dimNames) {
  66905. if (firstAxisModel == null) {
  66906. var indices = this.get(dimNames.axisIndex);
  66907. if (indices.length) {
  66908. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  66909. }
  66910. }
  66911. }, this);
  66912. return firstAxisModel;
  66913. },
  66914. /**
  66915. * @public
  66916. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  66917. */
  66918. eachTargetAxis: function (callback, context) {
  66919. var ecModel = this.ecModel;
  66920. eachAxisDim(function (dimNames) {
  66921. each$21(
  66922. this.get(dimNames.axisIndex),
  66923. function (axisIndex) {
  66924. callback.call(context, dimNames, axisIndex, this, ecModel);
  66925. },
  66926. this
  66927. );
  66928. }, this);
  66929. },
  66930. /**
  66931. * @param {string} dimName
  66932. * @param {number} axisIndex
  66933. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  66934. */
  66935. getAxisProxy: function (dimName, axisIndex) {
  66936. return this._axisProxies[dimName + '_' + axisIndex];
  66937. },
  66938. /**
  66939. * @param {string} dimName
  66940. * @param {number} axisIndex
  66941. * @return {module:echarts/model/Model} If not found, return null/undefined.
  66942. */
  66943. getAxisModel: function (dimName, axisIndex) {
  66944. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  66945. return axisProxy && axisProxy.getAxisModel();
  66946. },
  66947. /**
  66948. * If not specified, set to undefined.
  66949. *
  66950. * @public
  66951. * @param {Object} opt
  66952. * @param {number} [opt.start]
  66953. * @param {number} [opt.end]
  66954. * @param {number} [opt.startValue]
  66955. * @param {number} [opt.endValue]
  66956. * @param {boolean} [ignoreUpdateRangeUsg=false]
  66957. */
  66958. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  66959. var option = this.option;
  66960. each$21([['start', 'startValue'], ['end', 'endValue']], function (names) {
  66961. // If only one of 'start' and 'startValue' is not null/undefined, the other
  66962. // should be cleared, which enable clear the option.
  66963. // If both of them are not set, keep option with the original value, which
  66964. // enable use only set start but not set end when calling `dispatchAction`.
  66965. // The same as 'end' and 'endValue'.
  66966. if (opt[names[0]] != null || opt[names[1]] != null) {
  66967. option[names[0]] = opt[names[0]];
  66968. option[names[1]] = opt[names[1]];
  66969. }
  66970. }, this);
  66971. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  66972. },
  66973. /**
  66974. * @public
  66975. * @return {Array.<number>} [startPercent, endPercent]
  66976. */
  66977. getPercentRange: function () {
  66978. var axisProxy = this.findRepresentativeAxisProxy();
  66979. if (axisProxy) {
  66980. return axisProxy.getDataPercentWindow();
  66981. }
  66982. },
  66983. /**
  66984. * @public
  66985. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  66986. *
  66987. * @param {string} [axisDimName]
  66988. * @param {number} [axisIndex]
  66989. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  66990. */
  66991. getValueRange: function (axisDimName, axisIndex) {
  66992. if (axisDimName == null && axisIndex == null) {
  66993. var axisProxy = this.findRepresentativeAxisProxy();
  66994. if (axisProxy) {
  66995. return axisProxy.getDataValueWindow();
  66996. }
  66997. }
  66998. else {
  66999. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  67000. }
  67001. },
  67002. /**
  67003. * @public
  67004. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  67005. * corresponding to the axisModel
  67006. * @return {module:echarts/component/dataZoom/AxisProxy}
  67007. */
  67008. findRepresentativeAxisProxy: function (axisModel) {
  67009. if (axisModel) {
  67010. return axisModel.__dzAxisProxy;
  67011. }
  67012. // Find the first hosted axisProxy
  67013. var axisProxies = this._axisProxies;
  67014. for (var key in axisProxies) {
  67015. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  67016. return axisProxies[key];
  67017. }
  67018. }
  67019. // If no hosted axis find not hosted axisProxy.
  67020. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  67021. // and the option.start or option.end settings are different. The percentRange
  67022. // should follow axisProxy.
  67023. // (We encounter this problem in toolbox data zoom.)
  67024. for (var key in axisProxies) {
  67025. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  67026. return axisProxies[key];
  67027. }
  67028. }
  67029. },
  67030. /**
  67031. * @return {Array.<string>}
  67032. */
  67033. getRangePropMode: function () {
  67034. return this._rangePropMode.slice();
  67035. }
  67036. });
  67037. function retrieveRaw(option) {
  67038. var ret = {};
  67039. each$21(
  67040. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  67041. function (name) {
  67042. option.hasOwnProperty(name) && (ret[name] = option[name]);
  67043. }
  67044. );
  67045. return ret;
  67046. }
  67047. function updateRangeUse(dataZoomModel, rawOption) {
  67048. var rangePropMode = dataZoomModel._rangePropMode;
  67049. var rangeModeInOption = dataZoomModel.get('rangeMode');
  67050. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  67051. var percentSpecified = rawOption[names[0]] != null;
  67052. var valueSpecified = rawOption[names[1]] != null;
  67053. if (percentSpecified && !valueSpecified) {
  67054. rangePropMode[index] = 'percent';
  67055. }
  67056. else if (!percentSpecified && valueSpecified) {
  67057. rangePropMode[index] = 'value';
  67058. }
  67059. else if (rangeModeInOption) {
  67060. rangePropMode[index] = rangeModeInOption[index];
  67061. }
  67062. else if (percentSpecified) { // percentSpecified && valueSpecified
  67063. rangePropMode[index] = 'percent';
  67064. }
  67065. // else remain its original setting.
  67066. });
  67067. }
  67068. /*
  67069. * Licensed to the Apache Software Foundation (ASF) under one
  67070. * or more contributor license agreements. See the NOTICE file
  67071. * distributed with this work for additional information
  67072. * regarding copyright ownership. The ASF licenses this file
  67073. * to you under the Apache License, Version 2.0 (the
  67074. * "License"); you may not use this file except in compliance
  67075. * with the License. You may obtain a copy of the License at
  67076. *
  67077. * http://www.apache.org/licenses/LICENSE-2.0
  67078. *
  67079. * Unless required by applicable law or agreed to in writing,
  67080. * software distributed under the License is distributed on an
  67081. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67082. * KIND, either express or implied. See the License for the
  67083. * specific language governing permissions and limitations
  67084. * under the License.
  67085. */
  67086. var DataZoomView = Component.extend({
  67087. type: 'dataZoom',
  67088. render: function (dataZoomModel, ecModel, api, payload) {
  67089. this.dataZoomModel = dataZoomModel;
  67090. this.ecModel = ecModel;
  67091. this.api = api;
  67092. },
  67093. /**
  67094. * Find the first target coordinate system.
  67095. *
  67096. * @protected
  67097. * @return {Object} {
  67098. * grid: [
  67099. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  67100. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  67101. * ...
  67102. * ], // cartesians must not be null/undefined.
  67103. * polar: [
  67104. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  67105. * ...
  67106. * ], // polars must not be null/undefined.
  67107. * singleAxis: [
  67108. * {model: coord0, axisModels: [], coordIndex: 0}
  67109. * ]
  67110. */
  67111. getTargetCoordInfo: function () {
  67112. var dataZoomModel = this.dataZoomModel;
  67113. var ecModel = this.ecModel;
  67114. var coordSysLists = {};
  67115. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  67116. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  67117. if (axisModel) {
  67118. var coordModel = axisModel.getCoordSysModel();
  67119. coordModel && save(
  67120. coordModel,
  67121. axisModel,
  67122. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  67123. coordModel.componentIndex
  67124. );
  67125. }
  67126. }, this);
  67127. function save(coordModel, axisModel, store, coordIndex) {
  67128. var item;
  67129. for (var i = 0; i < store.length; i++) {
  67130. if (store[i].model === coordModel) {
  67131. item = store[i];
  67132. break;
  67133. }
  67134. }
  67135. if (!item) {
  67136. store.push(item = {
  67137. model: coordModel, axisModels: [], coordIndex: coordIndex
  67138. });
  67139. }
  67140. item.axisModels.push(axisModel);
  67141. }
  67142. return coordSysLists;
  67143. }
  67144. });
  67145. /*
  67146. * Licensed to the Apache Software Foundation (ASF) under one
  67147. * or more contributor license agreements. See the NOTICE file
  67148. * distributed with this work for additional information
  67149. * regarding copyright ownership. The ASF licenses this file
  67150. * to you under the Apache License, Version 2.0 (the
  67151. * "License"); you may not use this file except in compliance
  67152. * with the License. You may obtain a copy of the License at
  67153. *
  67154. * http://www.apache.org/licenses/LICENSE-2.0
  67155. *
  67156. * Unless required by applicable law or agreed to in writing,
  67157. * software distributed under the License is distributed on an
  67158. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67159. * KIND, either express or implied. See the License for the
  67160. * specific language governing permissions and limitations
  67161. * under the License.
  67162. */
  67163. var SliderZoomModel = DataZoomModel.extend({
  67164. type: 'dataZoom.slider',
  67165. layoutMode: 'box',
  67166. /**
  67167. * @protected
  67168. */
  67169. defaultOption: {
  67170. show: true,
  67171. // ph => placeholder. Using placehoder here because
  67172. // deault value can only be drived in view stage.
  67173. right: 'ph', // Default align to grid rect.
  67174. top: 'ph', // Default align to grid rect.
  67175. width: 'ph', // Default align to grid rect.
  67176. height: 'ph', // Default align to grid rect.
  67177. left: null, // Default align to grid rect.
  67178. bottom: null, // Default align to grid rect.
  67179. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  67180. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  67181. // highest priority, remain for compatibility of
  67182. // previous version, but not recommended any more.
  67183. dataBackground: {
  67184. lineStyle: {
  67185. color: '#2f4554',
  67186. width: 0.5,
  67187. opacity: 0.3
  67188. },
  67189. areaStyle: {
  67190. color: 'rgba(47,69,84,0.3)',
  67191. opacity: 0.3
  67192. }
  67193. },
  67194. borderColor: '#ddd', // border color of the box. For compatibility,
  67195. // if dataBackgroundColor is set, borderColor
  67196. // is ignored.
  67197. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  67198. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  67199. // 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',
  67200. 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',
  67201. // Percent of the slider height
  67202. handleSize: '100%',
  67203. handleStyle: {
  67204. color: '#a7b7cc'
  67205. },
  67206. labelPrecision: null,
  67207. labelFormatter: null,
  67208. showDetail: true,
  67209. showDataShadow: 'auto', // Default auto decision.
  67210. realtime: true,
  67211. zoomLock: false, // Whether disable zoom.
  67212. textStyle: {
  67213. color: '#333'
  67214. }
  67215. }
  67216. });
  67217. /*
  67218. * Licensed to the Apache Software Foundation (ASF) under one
  67219. * or more contributor license agreements. See the NOTICE file
  67220. * distributed with this work for additional information
  67221. * regarding copyright ownership. The ASF licenses this file
  67222. * to you under the Apache License, Version 2.0 (the
  67223. * "License"); you may not use this file except in compliance
  67224. * with the License. You may obtain a copy of the License at
  67225. *
  67226. * http://www.apache.org/licenses/LICENSE-2.0
  67227. *
  67228. * Unless required by applicable law or agreed to in writing,
  67229. * software distributed under the License is distributed on an
  67230. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67231. * KIND, either express or implied. See the License for the
  67232. * specific language governing permissions and limitations
  67233. * under the License.
  67234. */
  67235. var Rect$2 = Rect;
  67236. var linearMap$1 = linearMap;
  67237. var asc$2 = asc;
  67238. var bind$4 = bind;
  67239. var each$23 = each$1;
  67240. // Constants
  67241. var DEFAULT_LOCATION_EDGE_GAP = 7;
  67242. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  67243. var DEFAULT_FILLER_SIZE = 30;
  67244. var HORIZONTAL = 'horizontal';
  67245. var VERTICAL = 'vertical';
  67246. var LABEL_GAP = 5;
  67247. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  67248. var SliderZoomView = DataZoomView.extend({
  67249. type: 'dataZoom.slider',
  67250. init: function (ecModel, api) {
  67251. /**
  67252. * @private
  67253. * @type {Object}
  67254. */
  67255. this._displayables = {};
  67256. /**
  67257. * @private
  67258. * @type {string}
  67259. */
  67260. this._orient;
  67261. /**
  67262. * [0, 100]
  67263. * @private
  67264. */
  67265. this._range;
  67266. /**
  67267. * [coord of the first handle, coord of the second handle]
  67268. * @private
  67269. */
  67270. this._handleEnds;
  67271. /**
  67272. * [length, thick]
  67273. * @private
  67274. * @type {Array.<number>}
  67275. */
  67276. this._size;
  67277. /**
  67278. * @private
  67279. * @type {number}
  67280. */
  67281. this._handleWidth;
  67282. /**
  67283. * @private
  67284. * @type {number}
  67285. */
  67286. this._handleHeight;
  67287. /**
  67288. * @private
  67289. */
  67290. this._location;
  67291. /**
  67292. * @private
  67293. */
  67294. this._dragging;
  67295. /**
  67296. * @private
  67297. */
  67298. this._dataShadowInfo;
  67299. this.api = api;
  67300. },
  67301. /**
  67302. * @override
  67303. */
  67304. render: function (dataZoomModel, ecModel, api, payload) {
  67305. SliderZoomView.superApply(this, 'render', arguments);
  67306. createOrUpdate(
  67307. this,
  67308. '_dispatchZoomAction',
  67309. this.dataZoomModel.get('throttle'),
  67310. 'fixRate'
  67311. );
  67312. this._orient = dataZoomModel.get('orient');
  67313. if (this.dataZoomModel.get('show') === false) {
  67314. this.group.removeAll();
  67315. return;
  67316. }
  67317. // Notice: this._resetInterval() should not be executed when payload.type
  67318. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  67319. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  67320. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  67321. this._buildView();
  67322. }
  67323. this._updateView();
  67324. },
  67325. /**
  67326. * @override
  67327. */
  67328. remove: function () {
  67329. SliderZoomView.superApply(this, 'remove', arguments);
  67330. clear(this, '_dispatchZoomAction');
  67331. },
  67332. /**
  67333. * @override
  67334. */
  67335. dispose: function () {
  67336. SliderZoomView.superApply(this, 'dispose', arguments);
  67337. clear(this, '_dispatchZoomAction');
  67338. },
  67339. _buildView: function () {
  67340. var thisGroup = this.group;
  67341. thisGroup.removeAll();
  67342. this._resetLocation();
  67343. this._resetInterval();
  67344. var barGroup = this._displayables.barGroup = new Group();
  67345. this._renderBackground();
  67346. this._renderHandle();
  67347. this._renderDataShadow();
  67348. thisGroup.add(barGroup);
  67349. this._positionGroup();
  67350. },
  67351. /**
  67352. * @private
  67353. */
  67354. _resetLocation: function () {
  67355. var dataZoomModel = this.dataZoomModel;
  67356. var api = this.api;
  67357. // If some of x/y/width/height are not specified,
  67358. // auto-adapt according to target grid.
  67359. var coordRect = this._findCoordRect();
  67360. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  67361. // Default align by coordinate system rect.
  67362. var positionInfo = this._orient === HORIZONTAL
  67363. ? {
  67364. // Why using 'right', because right should be used in vertical,
  67365. // and it is better to be consistent for dealing with position param merge.
  67366. right: ecSize.width - coordRect.x - coordRect.width,
  67367. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  67368. width: coordRect.width,
  67369. height: DEFAULT_FILLER_SIZE
  67370. }
  67371. : { // vertical
  67372. right: DEFAULT_LOCATION_EDGE_GAP,
  67373. top: coordRect.y,
  67374. width: DEFAULT_FILLER_SIZE,
  67375. height: coordRect.height
  67376. };
  67377. // Do not write back to option and replace value 'ph', because
  67378. // the 'ph' value should be recalculated when resize.
  67379. var layoutParams = getLayoutParams(dataZoomModel.option);
  67380. // Replace the placeholder value.
  67381. each$1(['right', 'top', 'width', 'height'], function (name) {
  67382. if (layoutParams[name] === 'ph') {
  67383. layoutParams[name] = positionInfo[name];
  67384. }
  67385. });
  67386. var layoutRect = getLayoutRect(
  67387. layoutParams,
  67388. ecSize,
  67389. dataZoomModel.padding
  67390. );
  67391. this._location = {x: layoutRect.x, y: layoutRect.y};
  67392. this._size = [layoutRect.width, layoutRect.height];
  67393. this._orient === VERTICAL && this._size.reverse();
  67394. },
  67395. /**
  67396. * @private
  67397. */
  67398. _positionGroup: function () {
  67399. var thisGroup = this.group;
  67400. var location = this._location;
  67401. var orient = this._orient;
  67402. // Just use the first axis to determine mapping.
  67403. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  67404. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  67405. var barGroup = this._displayables.barGroup;
  67406. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  67407. // Transform barGroup.
  67408. barGroup.attr(
  67409. (orient === HORIZONTAL && !inverse)
  67410. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  67411. : (orient === HORIZONTAL && inverse)
  67412. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  67413. : (orient === VERTICAL && !inverse)
  67414. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  67415. // Dont use Math.PI, considering shadow direction.
  67416. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  67417. );
  67418. // Position barGroup
  67419. var rect = thisGroup.getBoundingRect([barGroup]);
  67420. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  67421. },
  67422. /**
  67423. * @private
  67424. */
  67425. _getViewExtent: function () {
  67426. return [0, this._size[0]];
  67427. },
  67428. _renderBackground: function () {
  67429. var dataZoomModel = this.dataZoomModel;
  67430. var size = this._size;
  67431. var barGroup = this._displayables.barGroup;
  67432. barGroup.add(new Rect$2({
  67433. silent: true,
  67434. shape: {
  67435. x: 0, y: 0, width: size[0], height: size[1]
  67436. },
  67437. style: {
  67438. fill: dataZoomModel.get('backgroundColor')
  67439. },
  67440. z2: -40
  67441. }));
  67442. // Click panel, over shadow, below handles.
  67443. barGroup.add(new Rect$2({
  67444. shape: {
  67445. x: 0, y: 0, width: size[0], height: size[1]
  67446. },
  67447. style: {
  67448. fill: 'transparent'
  67449. },
  67450. z2: 0,
  67451. onclick: bind(this._onClickPanelClick, this)
  67452. }));
  67453. },
  67454. _renderDataShadow: function () {
  67455. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  67456. if (!info) {
  67457. return;
  67458. }
  67459. var size = this._size;
  67460. var seriesModel = info.series;
  67461. var data = seriesModel.getRawData();
  67462. var otherDim = seriesModel.getShadowDim
  67463. ? seriesModel.getShadowDim() // @see candlestick
  67464. : info.otherDim;
  67465. if (otherDim == null) {
  67466. return;
  67467. }
  67468. var otherDataExtent = data.getDataExtent(otherDim);
  67469. // Nice extent.
  67470. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  67471. otherDataExtent = [
  67472. otherDataExtent[0] - otherOffset,
  67473. otherDataExtent[1] + otherOffset
  67474. ];
  67475. var otherShadowExtent = [0, size[1]];
  67476. var thisShadowExtent = [0, size[0]];
  67477. var areaPoints = [[size[0], 0], [0, 0]];
  67478. var linePoints = [];
  67479. var step = thisShadowExtent[1] / (data.count() - 1);
  67480. var thisCoord = 0;
  67481. // Optimize for large data shadow
  67482. var stride = Math.round(data.count() / size[0]);
  67483. var lastIsEmpty;
  67484. data.each([otherDim], function (value, index) {
  67485. if (stride > 0 && (index % stride)) {
  67486. thisCoord += step;
  67487. return;
  67488. }
  67489. // FIXME
  67490. // Should consider axis.min/axis.max when drawing dataShadow.
  67491. // FIXME
  67492. // 应该使用统一的空判断?还是在list里进行空判断?
  67493. var isEmpty = value == null || isNaN(value) || value === '';
  67494. // See #4235.
  67495. var otherCoord = isEmpty
  67496. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  67497. // Attempt to draw data shadow precisely when there are empty value.
  67498. if (isEmpty && !lastIsEmpty && index) {
  67499. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  67500. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  67501. }
  67502. else if (!isEmpty && lastIsEmpty) {
  67503. areaPoints.push([thisCoord, 0]);
  67504. linePoints.push([thisCoord, 0]);
  67505. }
  67506. areaPoints.push([thisCoord, otherCoord]);
  67507. linePoints.push([thisCoord, otherCoord]);
  67508. thisCoord += step;
  67509. lastIsEmpty = isEmpty;
  67510. });
  67511. var dataZoomModel = this.dataZoomModel;
  67512. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  67513. this._displayables.barGroup.add(new Polygon({
  67514. shape: {points: areaPoints},
  67515. style: defaults(
  67516. {fill: dataZoomModel.get('dataBackgroundColor')},
  67517. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  67518. ),
  67519. silent: true,
  67520. z2: -20
  67521. }));
  67522. this._displayables.barGroup.add(new Polyline({
  67523. shape: {points: linePoints},
  67524. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  67525. silent: true,
  67526. z2: -19
  67527. }));
  67528. },
  67529. _prepareDataShadowInfo: function () {
  67530. var dataZoomModel = this.dataZoomModel;
  67531. var showDataShadow = dataZoomModel.get('showDataShadow');
  67532. if (showDataShadow === false) {
  67533. return;
  67534. }
  67535. // Find a representative series.
  67536. var result;
  67537. var ecModel = this.ecModel;
  67538. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  67539. var seriesModels = dataZoomModel
  67540. .getAxisProxy(dimNames.name, axisIndex)
  67541. .getTargetSeriesModels();
  67542. each$1(seriesModels, function (seriesModel) {
  67543. if (result) {
  67544. return;
  67545. }
  67546. if (showDataShadow !== true && indexOf(
  67547. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  67548. ) < 0
  67549. ) {
  67550. return;
  67551. }
  67552. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  67553. var otherDim = getOtherDim(dimNames.name);
  67554. var otherAxisInverse;
  67555. var coordSys = seriesModel.coordinateSystem;
  67556. if (otherDim != null && coordSys.getOtherAxis) {
  67557. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  67558. }
  67559. otherDim = seriesModel.getData().mapDimension(otherDim);
  67560. result = {
  67561. thisAxis: thisAxis,
  67562. series: seriesModel,
  67563. thisDim: dimNames.name,
  67564. otherDim: otherDim,
  67565. otherAxisInverse: otherAxisInverse
  67566. };
  67567. }, this);
  67568. }, this);
  67569. return result;
  67570. },
  67571. _renderHandle: function () {
  67572. var displaybles = this._displayables;
  67573. var handles = displaybles.handles = [];
  67574. var handleLabels = displaybles.handleLabels = [];
  67575. var barGroup = this._displayables.barGroup;
  67576. var size = this._size;
  67577. var dataZoomModel = this.dataZoomModel;
  67578. barGroup.add(displaybles.filler = new Rect$2({
  67579. draggable: true,
  67580. cursor: getCursor(this._orient),
  67581. drift: bind$4(this._onDragMove, this, 'all'),
  67582. onmousemove: function (e) {
  67583. // Fot mobile devicem, prevent screen slider on the button.
  67584. stop(e.event);
  67585. },
  67586. ondragstart: bind$4(this._showDataInfo, this, true),
  67587. ondragend: bind$4(this._onDragEnd, this),
  67588. onmouseover: bind$4(this._showDataInfo, this, true),
  67589. onmouseout: bind$4(this._showDataInfo, this, false),
  67590. style: {
  67591. fill: dataZoomModel.get('fillerColor'),
  67592. textPosition : 'inside'
  67593. }
  67594. }));
  67595. // Frame border.
  67596. barGroup.add(new Rect$2(subPixelOptimizeRect({
  67597. silent: true,
  67598. shape: {
  67599. x: 0,
  67600. y: 0,
  67601. width: size[0],
  67602. height: size[1]
  67603. },
  67604. style: {
  67605. stroke: dataZoomModel.get('dataBackgroundColor')
  67606. || dataZoomModel.get('borderColor'),
  67607. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  67608. fill: 'rgba(0,0,0,0)'
  67609. }
  67610. })));
  67611. each$23([0, 1], function (handleIndex) {
  67612. var path = createIcon(
  67613. dataZoomModel.get('handleIcon'),
  67614. {
  67615. cursor: getCursor(this._orient),
  67616. draggable: true,
  67617. drift: bind$4(this._onDragMove, this, handleIndex),
  67618. onmousemove: function (e) {
  67619. // Fot mobile devicem, prevent screen slider on the button.
  67620. stop(e.event);
  67621. },
  67622. ondragend: bind$4(this._onDragEnd, this),
  67623. onmouseover: bind$4(this._showDataInfo, this, true),
  67624. onmouseout: bind$4(this._showDataInfo, this, false)
  67625. },
  67626. {x: -1, y: 0, width: 2, height: 2}
  67627. );
  67628. var bRect = path.getBoundingRect();
  67629. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  67630. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  67631. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  67632. var handleColor = dataZoomModel.get('handleColor');
  67633. // Compatitable with previous version
  67634. if (handleColor != null) {
  67635. path.style.fill = handleColor;
  67636. }
  67637. barGroup.add(handles[handleIndex] = path);
  67638. var textStyleModel = dataZoomModel.textStyleModel;
  67639. this.group.add(
  67640. handleLabels[handleIndex] = new Text({
  67641. silent: true,
  67642. invisible: true,
  67643. style: {
  67644. x: 0, y: 0, text: '',
  67645. textVerticalAlign: 'middle',
  67646. textAlign: 'center',
  67647. textFill: textStyleModel.getTextColor(),
  67648. textFont: textStyleModel.getFont()
  67649. },
  67650. z2: 10
  67651. }));
  67652. }, this);
  67653. },
  67654. /**
  67655. * @private
  67656. */
  67657. _resetInterval: function () {
  67658. var range = this._range = this.dataZoomModel.getPercentRange();
  67659. var viewExtent = this._getViewExtent();
  67660. this._handleEnds = [
  67661. linearMap$1(range[0], [0, 100], viewExtent, true),
  67662. linearMap$1(range[1], [0, 100], viewExtent, true)
  67663. ];
  67664. },
  67665. /**
  67666. * @private
  67667. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  67668. * @param {number} delta
  67669. * @return {boolean} changed
  67670. */
  67671. _updateInterval: function (handleIndex, delta) {
  67672. var dataZoomModel = this.dataZoomModel;
  67673. var handleEnds = this._handleEnds;
  67674. var viewExtend = this._getViewExtent();
  67675. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  67676. var percentExtent = [0, 100];
  67677. sliderMove(
  67678. delta,
  67679. handleEnds,
  67680. viewExtend,
  67681. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  67682. minMaxSpan.minSpan != null
  67683. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  67684. minMaxSpan.maxSpan != null
  67685. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  67686. );
  67687. var lastRange = this._range;
  67688. var range = this._range = asc$2([
  67689. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  67690. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  67691. ]);
  67692. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  67693. },
  67694. /**
  67695. * @private
  67696. */
  67697. _updateView: function (nonRealtime) {
  67698. var displaybles = this._displayables;
  67699. var handleEnds = this._handleEnds;
  67700. var handleInterval = asc$2(handleEnds.slice());
  67701. var size = this._size;
  67702. each$23([0, 1], function (handleIndex) {
  67703. // Handles
  67704. var handle = displaybles.handles[handleIndex];
  67705. var handleHeight = this._handleHeight;
  67706. handle.attr({
  67707. scale: [handleHeight / 2, handleHeight / 2],
  67708. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  67709. });
  67710. }, this);
  67711. // Filler
  67712. displaybles.filler.setShape({
  67713. x: handleInterval[0],
  67714. y: 0,
  67715. width: handleInterval[1] - handleInterval[0],
  67716. height: size[1]
  67717. });
  67718. this._updateDataInfo(nonRealtime);
  67719. },
  67720. /**
  67721. * @private
  67722. */
  67723. _updateDataInfo: function (nonRealtime) {
  67724. var dataZoomModel = this.dataZoomModel;
  67725. var displaybles = this._displayables;
  67726. var handleLabels = displaybles.handleLabels;
  67727. var orient = this._orient;
  67728. var labelTexts = ['', ''];
  67729. // FIXME
  67730. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  67731. if (dataZoomModel.get('showDetail')) {
  67732. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  67733. if (axisProxy) {
  67734. var axis = axisProxy.getAxisModel().axis;
  67735. var range = this._range;
  67736. var dataInterval = nonRealtime
  67737. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  67738. ? axisProxy.calculateDataWindow({
  67739. start: range[0], end: range[1]
  67740. }).valueWindow
  67741. : axisProxy.getDataValueWindow();
  67742. labelTexts = [
  67743. this._formatLabel(dataInterval[0], axis),
  67744. this._formatLabel(dataInterval[1], axis)
  67745. ];
  67746. }
  67747. }
  67748. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  67749. setLabel.call(this, 0);
  67750. setLabel.call(this, 1);
  67751. function setLabel(handleIndex) {
  67752. // Label
  67753. // Text should not transform by barGroup.
  67754. // Ignore handlers transform
  67755. var barTransform = getTransform(
  67756. displaybles.handles[handleIndex].parent, this.group
  67757. );
  67758. var direction = transformDirection(
  67759. handleIndex === 0 ? 'right' : 'left', barTransform
  67760. );
  67761. var offset = this._handleWidth / 2 + LABEL_GAP;
  67762. var textPoint = applyTransform$1(
  67763. [
  67764. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  67765. this._size[1] / 2
  67766. ],
  67767. barTransform
  67768. );
  67769. handleLabels[handleIndex].setStyle({
  67770. x: textPoint[0],
  67771. y: textPoint[1],
  67772. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  67773. textAlign: orient === HORIZONTAL ? direction : 'center',
  67774. text: labelTexts[handleIndex]
  67775. });
  67776. }
  67777. },
  67778. /**
  67779. * @private
  67780. */
  67781. _formatLabel: function (value, axis) {
  67782. var dataZoomModel = this.dataZoomModel;
  67783. var labelFormatter = dataZoomModel.get('labelFormatter');
  67784. var labelPrecision = dataZoomModel.get('labelPrecision');
  67785. if (labelPrecision == null || labelPrecision === 'auto') {
  67786. labelPrecision = axis.getPixelPrecision();
  67787. }
  67788. var valueStr = (value == null || isNaN(value))
  67789. ? ''
  67790. // FIXME Glue code
  67791. : (axis.type === 'category' || axis.type === 'time')
  67792. ? axis.scale.getLabel(Math.round(value))
  67793. // param of toFixed should less then 20.
  67794. : value.toFixed(Math.min(labelPrecision, 20));
  67795. return isFunction$1(labelFormatter)
  67796. ? labelFormatter(value, valueStr)
  67797. : isString(labelFormatter)
  67798. ? labelFormatter.replace('{value}', valueStr)
  67799. : valueStr;
  67800. },
  67801. /**
  67802. * @private
  67803. * @param {boolean} showOrHide true: show, false: hide
  67804. */
  67805. _showDataInfo: function (showOrHide) {
  67806. // Always show when drgging.
  67807. showOrHide = this._dragging || showOrHide;
  67808. var handleLabels = this._displayables.handleLabels;
  67809. handleLabels[0].attr('invisible', !showOrHide);
  67810. handleLabels[1].attr('invisible', !showOrHide);
  67811. },
  67812. _onDragMove: function (handleIndex, dx, dy) {
  67813. this._dragging = true;
  67814. // Transform dx, dy to bar coordination.
  67815. var barTransform = this._displayables.barGroup.getLocalTransform();
  67816. var vertex = applyTransform$1([dx, dy], barTransform, true);
  67817. var changed = this._updateInterval(handleIndex, vertex[0]);
  67818. var realtime = this.dataZoomModel.get('realtime');
  67819. this._updateView(!realtime);
  67820. // Avoid dispatch dataZoom repeatly but range not changed,
  67821. // which cause bad visual effect when progressive enabled.
  67822. changed && realtime && this._dispatchZoomAction();
  67823. },
  67824. _onDragEnd: function () {
  67825. this._dragging = false;
  67826. this._showDataInfo(false);
  67827. // While in realtime mode and stream mode, dispatch action when
  67828. // drag end will cause the whole view rerender, which is unnecessary.
  67829. var realtime = this.dataZoomModel.get('realtime');
  67830. !realtime && this._dispatchZoomAction();
  67831. },
  67832. _onClickPanelClick: function (e) {
  67833. var size = this._size;
  67834. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  67835. if (localPoint[0] < 0 || localPoint[0] > size[0]
  67836. || localPoint[1] < 0 || localPoint[1] > size[1]
  67837. ) {
  67838. return;
  67839. }
  67840. var handleEnds = this._handleEnds;
  67841. var center = (handleEnds[0] + handleEnds[1]) / 2;
  67842. var changed = this._updateInterval('all', localPoint[0] - center);
  67843. this._updateView();
  67844. changed && this._dispatchZoomAction();
  67845. },
  67846. /**
  67847. * This action will be throttled.
  67848. * @private
  67849. */
  67850. _dispatchZoomAction: function () {
  67851. var range = this._range;
  67852. this.api.dispatchAction({
  67853. type: 'dataZoom',
  67854. from: this.uid,
  67855. dataZoomId: this.dataZoomModel.id,
  67856. start: range[0],
  67857. end: range[1]
  67858. });
  67859. },
  67860. /**
  67861. * @private
  67862. */
  67863. _findCoordRect: function () {
  67864. // Find the grid coresponding to the first axis referred by dataZoom.
  67865. var rect;
  67866. each$23(this.getTargetCoordInfo(), function (coordInfoList) {
  67867. if (!rect && coordInfoList.length) {
  67868. var coordSys = coordInfoList[0].model.coordinateSystem;
  67869. rect = coordSys.getRect && coordSys.getRect();
  67870. }
  67871. });
  67872. if (!rect) {
  67873. var width = this.api.getWidth();
  67874. var height = this.api.getHeight();
  67875. rect = {
  67876. x: width * 0.2,
  67877. y: height * 0.2,
  67878. width: width * 0.6,
  67879. height: height * 0.6
  67880. };
  67881. }
  67882. return rect;
  67883. }
  67884. });
  67885. function getOtherDim(thisDim) {
  67886. // FIXME
  67887. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  67888. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  67889. return map$$1[thisDim];
  67890. }
  67891. function getCursor(orient) {
  67892. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  67893. }
  67894. /*
  67895. * Licensed to the Apache Software Foundation (ASF) under one
  67896. * or more contributor license agreements. See the NOTICE file
  67897. * distributed with this work for additional information
  67898. * regarding copyright ownership. The ASF licenses this file
  67899. * to you under the Apache License, Version 2.0 (the
  67900. * "License"); you may not use this file except in compliance
  67901. * with the License. You may obtain a copy of the License at
  67902. *
  67903. * http://www.apache.org/licenses/LICENSE-2.0
  67904. *
  67905. * Unless required by applicable law or agreed to in writing,
  67906. * software distributed under the License is distributed on an
  67907. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67908. * KIND, either express or implied. See the License for the
  67909. * specific language governing permissions and limitations
  67910. * under the License.
  67911. */
  67912. DataZoomModel.extend({
  67913. type: 'dataZoom.inside',
  67914. /**
  67915. * @protected
  67916. */
  67917. defaultOption: {
  67918. disabled: false, // Whether disable this inside zoom.
  67919. zoomLock: false, // Whether disable zoom but only pan.
  67920. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  67921. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  67922. preventDefaultMouseMove: true
  67923. }
  67924. });
  67925. /*
  67926. * Licensed to the Apache Software Foundation (ASF) under one
  67927. * or more contributor license agreements. See the NOTICE file
  67928. * distributed with this work for additional information
  67929. * regarding copyright ownership. The ASF licenses this file
  67930. * to you under the Apache License, Version 2.0 (the
  67931. * "License"); you may not use this file except in compliance
  67932. * with the License. You may obtain a copy of the License at
  67933. *
  67934. * http://www.apache.org/licenses/LICENSE-2.0
  67935. *
  67936. * Unless required by applicable law or agreed to in writing,
  67937. * software distributed under the License is distributed on an
  67938. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67939. * KIND, either express or implied. See the License for the
  67940. * specific language governing permissions and limitations
  67941. * under the License.
  67942. */
  67943. // Only create one roam controller for each coordinate system.
  67944. // one roam controller might be refered by two inside data zoom
  67945. // components (for example, one for x and one for y). When user
  67946. // pan or zoom, only dispatch one action for those data zoom
  67947. // components.
  67948. var curry$6 = curry;
  67949. var ATTR$1 = '\0_ec_dataZoom_roams';
  67950. /**
  67951. * @public
  67952. * @param {module:echarts/ExtensionAPI} api
  67953. * @param {Object} dataZoomInfo
  67954. * @param {string} dataZoomInfo.coordId
  67955. * @param {Function} dataZoomInfo.containsPoint
  67956. * @param {Array.<string>} dataZoomInfo.allCoordIds
  67957. * @param {string} dataZoomInfo.dataZoomId
  67958. * @param {number} dataZoomInfo.throttleRate
  67959. * @param {Function} dataZoomInfo.panGetRange
  67960. * @param {Function} dataZoomInfo.zoomGetRange
  67961. * @param {boolean} [dataZoomInfo.zoomLock]
  67962. * @param {boolean} [dataZoomInfo.disabled]
  67963. */
  67964. function register$2(api, dataZoomInfo) {
  67965. var store = giveStore(api);
  67966. var theDataZoomId = dataZoomInfo.dataZoomId;
  67967. var theCoordId = dataZoomInfo.coordId;
  67968. // Do clean when a dataZoom changes its target coordnate system.
  67969. // Avoid memory leak, dispose all not-used-registered.
  67970. each$1(store, function (record, coordId) {
  67971. var dataZoomInfos = record.dataZoomInfos;
  67972. if (dataZoomInfos[theDataZoomId]
  67973. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  67974. ) {
  67975. delete dataZoomInfos[theDataZoomId];
  67976. record.count--;
  67977. }
  67978. });
  67979. cleanStore(store);
  67980. var record = store[theCoordId];
  67981. // Create if needed.
  67982. if (!record) {
  67983. record = store[theCoordId] = {
  67984. coordId: theCoordId,
  67985. dataZoomInfos: {},
  67986. count: 0
  67987. };
  67988. record.controller = createController(api, record);
  67989. record.dispatchAction = curry(dispatchAction$1, api);
  67990. }
  67991. // Update reference of dataZoom.
  67992. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  67993. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  67994. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  67995. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  67996. // Consider resize, area should be always updated.
  67997. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  67998. // Update throttle.
  67999. createOrUpdate(
  68000. record,
  68001. 'dispatchAction',
  68002. dataZoomInfo.throttleRate,
  68003. 'fixRate'
  68004. );
  68005. }
  68006. /**
  68007. * @public
  68008. * @param {module:echarts/ExtensionAPI} api
  68009. * @param {string} dataZoomId
  68010. */
  68011. function unregister$1(api, dataZoomId) {
  68012. var store = giveStore(api);
  68013. each$1(store, function (record) {
  68014. record.controller.dispose();
  68015. var dataZoomInfos = record.dataZoomInfos;
  68016. if (dataZoomInfos[dataZoomId]) {
  68017. delete dataZoomInfos[dataZoomId];
  68018. record.count--;
  68019. }
  68020. });
  68021. cleanStore(store);
  68022. }
  68023. /**
  68024. * @public
  68025. */
  68026. function generateCoordId(coordModel) {
  68027. return coordModel.type + '\0_' + coordModel.id;
  68028. }
  68029. /**
  68030. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  68031. * @type {Array.<Object>}
  68032. */
  68033. function giveStore(api) {
  68034. // Mount store on zrender instance, so that we do not
  68035. // need to worry about dispose.
  68036. var zr = api.getZr();
  68037. return zr[ATTR$1] || (zr[ATTR$1] = {});
  68038. }
  68039. function createController(api, newRecord) {
  68040. var controller = new RoamController(api.getZr());
  68041. controller.on('pan', curry$6(onPan, newRecord));
  68042. controller.on('zoom', curry$6(onZoom, newRecord));
  68043. return controller;
  68044. }
  68045. function cleanStore(store) {
  68046. each$1(store, function (record, coordId) {
  68047. if (!record.count) {
  68048. record.controller.dispose();
  68049. delete store[coordId];
  68050. }
  68051. });
  68052. }
  68053. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  68054. wrapAndDispatch(record, function (info) {
  68055. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  68056. });
  68057. }
  68058. function onZoom(record, scale, mouseX, mouseY) {
  68059. wrapAndDispatch(record, function (info) {
  68060. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  68061. });
  68062. }
  68063. function wrapAndDispatch(record, getRange) {
  68064. var batch = [];
  68065. each$1(record.dataZoomInfos, function (info) {
  68066. var range = getRange(info);
  68067. !info.disabled && range && batch.push({
  68068. dataZoomId: info.dataZoomId,
  68069. start: range[0],
  68070. end: range[1]
  68071. });
  68072. });
  68073. batch.length && record.dispatchAction(batch);
  68074. }
  68075. /**
  68076. * This action will be throttled.
  68077. */
  68078. function dispatchAction$1(api, batch) {
  68079. api.dispatchAction({
  68080. type: 'dataZoom',
  68081. batch: batch
  68082. });
  68083. }
  68084. /**
  68085. * Merge roamController settings when multiple dataZooms share one roamController.
  68086. */
  68087. function mergeControllerParams(dataZoomInfos) {
  68088. var controlType;
  68089. var opt = {};
  68090. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  68091. // as string, it is probably revert to reserved word by compress tool. See #7411.
  68092. var prefix = 'type_';
  68093. var typePriority = {
  68094. 'type_true': 2,
  68095. 'type_move': 1,
  68096. 'type_false': 0,
  68097. 'type_undefined': -1
  68098. };
  68099. each$1(dataZoomInfos, function (dataZoomInfo) {
  68100. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  68101. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  68102. controlType = oneType;
  68103. }
  68104. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  68105. extend(opt, dataZoomInfo.roamControllerOpt);
  68106. });
  68107. return {
  68108. controlType: controlType,
  68109. opt: opt
  68110. };
  68111. }
  68112. /*
  68113. * Licensed to the Apache Software Foundation (ASF) under one
  68114. * or more contributor license agreements. See the NOTICE file
  68115. * distributed with this work for additional information
  68116. * regarding copyright ownership. The ASF licenses this file
  68117. * to you under the Apache License, Version 2.0 (the
  68118. * "License"); you may not use this file except in compliance
  68119. * with the License. You may obtain a copy of the License at
  68120. *
  68121. * http://www.apache.org/licenses/LICENSE-2.0
  68122. *
  68123. * Unless required by applicable law or agreed to in writing,
  68124. * software distributed under the License is distributed on an
  68125. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68126. * KIND, either express or implied. See the License for the
  68127. * specific language governing permissions and limitations
  68128. * under the License.
  68129. */
  68130. var bind$5 = bind;
  68131. var InsideZoomView = DataZoomView.extend({
  68132. type: 'dataZoom.inside',
  68133. /**
  68134. * @override
  68135. */
  68136. init: function (ecModel, api) {
  68137. /**
  68138. * 'throttle' is used in this.dispatchAction, so we save range
  68139. * to avoid missing some 'pan' info.
  68140. * @private
  68141. * @type {Array.<number>}
  68142. */
  68143. this._range;
  68144. },
  68145. /**
  68146. * @override
  68147. */
  68148. render: function (dataZoomModel, ecModel, api, payload) {
  68149. InsideZoomView.superApply(this, 'render', arguments);
  68150. // Hance the `throttle` util ensures to preserve command order,
  68151. // here simply updating range all the time will not cause missing
  68152. // any of the the roam change.
  68153. this._range = dataZoomModel.getPercentRange();
  68154. // Reset controllers.
  68155. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  68156. var allCoordIds = map(coordInfoList, function (coordInfo) {
  68157. return generateCoordId(coordInfo.model);
  68158. });
  68159. each$1(coordInfoList, function (coordInfo) {
  68160. var coordModel = coordInfo.model;
  68161. var dataZoomOption = dataZoomModel.option;
  68162. register$2(
  68163. api,
  68164. {
  68165. coordId: generateCoordId(coordModel),
  68166. allCoordIds: allCoordIds,
  68167. containsPoint: function (e, x, y) {
  68168. return coordModel.coordinateSystem.containPoint([x, y]);
  68169. },
  68170. dataZoomId: dataZoomModel.id,
  68171. throttleRate: dataZoomModel.get('throttle', true),
  68172. panGetRange: bind$5(this._onPan, this, coordInfo, coordSysName),
  68173. zoomGetRange: bind$5(this._onZoom, this, coordInfo, coordSysName),
  68174. zoomLock: dataZoomOption.zoomLock,
  68175. disabled: dataZoomOption.disabled,
  68176. roamControllerOpt: {
  68177. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  68178. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  68179. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  68180. }
  68181. }
  68182. );
  68183. }, this);
  68184. }, this);
  68185. },
  68186. /**
  68187. * @override
  68188. */
  68189. dispose: function () {
  68190. unregister$1(this.api, this.dataZoomModel.id);
  68191. InsideZoomView.superApply(this, 'dispose', arguments);
  68192. this._range = null;
  68193. },
  68194. /**
  68195. * @private
  68196. */
  68197. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  68198. var lastRange = this._range;
  68199. var range = lastRange.slice();
  68200. // Calculate transform by the first axis.
  68201. var axisModel = coordInfo.axisModels[0];
  68202. if (!axisModel) {
  68203. return;
  68204. }
  68205. var directionInfo = getDirectionInfo[coordSysName](
  68206. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  68207. );
  68208. var percentDelta = directionInfo.signal
  68209. * (range[1] - range[0])
  68210. * directionInfo.pixel / directionInfo.pixelLength;
  68211. sliderMove(percentDelta, range, [0, 100], 'all');
  68212. this._range = range;
  68213. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  68214. return range;
  68215. }
  68216. },
  68217. /**
  68218. * @private
  68219. */
  68220. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  68221. var lastRange = this._range;
  68222. var range = lastRange.slice();
  68223. // Calculate transform by the first axis.
  68224. var axisModel = coordInfo.axisModels[0];
  68225. if (!axisModel) {
  68226. return;
  68227. }
  68228. var directionInfo = getDirectionInfo[coordSysName](
  68229. null, [mouseX, mouseY], axisModel, controller, coordInfo
  68230. );
  68231. var percentPoint = (
  68232. directionInfo.signal > 0
  68233. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  68234. : (directionInfo.pixel - directionInfo.pixelStart)
  68235. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  68236. scale = Math.max(1 / scale, 0);
  68237. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  68238. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  68239. // Restrict range.
  68240. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  68241. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  68242. this._range = range;
  68243. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  68244. return range;
  68245. }
  68246. }
  68247. });
  68248. var getDirectionInfo = {
  68249. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  68250. var axis = axisModel.axis;
  68251. var ret = {};
  68252. var rect = coordInfo.model.coordinateSystem.getRect();
  68253. oldPoint = oldPoint || [0, 0];
  68254. if (axis.dim === 'x') {
  68255. ret.pixel = newPoint[0] - oldPoint[0];
  68256. ret.pixelLength = rect.width;
  68257. ret.pixelStart = rect.x;
  68258. ret.signal = axis.inverse ? 1 : -1;
  68259. }
  68260. else { // axis.dim === 'y'
  68261. ret.pixel = newPoint[1] - oldPoint[1];
  68262. ret.pixelLength = rect.height;
  68263. ret.pixelStart = rect.y;
  68264. ret.signal = axis.inverse ? -1 : 1;
  68265. }
  68266. return ret;
  68267. },
  68268. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  68269. var axis = axisModel.axis;
  68270. var ret = {};
  68271. var polar = coordInfo.model.coordinateSystem;
  68272. var radiusExtent = polar.getRadiusAxis().getExtent();
  68273. var angleExtent = polar.getAngleAxis().getExtent();
  68274. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  68275. newPoint = polar.pointToCoord(newPoint);
  68276. if (axisModel.mainType === 'radiusAxis') {
  68277. ret.pixel = newPoint[0] - oldPoint[0];
  68278. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  68279. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  68280. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  68281. ret.pixelStart = radiusExtent[0];
  68282. ret.signal = axis.inverse ? 1 : -1;
  68283. }
  68284. else { // 'angleAxis'
  68285. ret.pixel = newPoint[1] - oldPoint[1];
  68286. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  68287. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  68288. ret.pixelLength = angleExtent[1] - angleExtent[0];
  68289. ret.pixelStart = angleExtent[0];
  68290. ret.signal = axis.inverse ? -1 : 1;
  68291. }
  68292. return ret;
  68293. },
  68294. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  68295. var axis = axisModel.axis;
  68296. var rect = coordInfo.model.coordinateSystem.getRect();
  68297. var ret = {};
  68298. oldPoint = oldPoint || [0, 0];
  68299. if (axis.orient === 'horizontal') {
  68300. ret.pixel = newPoint[0] - oldPoint[0];
  68301. ret.pixelLength = rect.width;
  68302. ret.pixelStart = rect.x;
  68303. ret.signal = axis.inverse ? 1 : -1;
  68304. }
  68305. else { // 'vertical'
  68306. ret.pixel = newPoint[1] - oldPoint[1];
  68307. ret.pixelLength = rect.height;
  68308. ret.pixelStart = rect.y;
  68309. ret.signal = axis.inverse ? -1 : 1;
  68310. }
  68311. return ret;
  68312. }
  68313. };
  68314. /*
  68315. * Licensed to the Apache Software Foundation (ASF) under one
  68316. * or more contributor license agreements. See the NOTICE file
  68317. * distributed with this work for additional information
  68318. * regarding copyright ownership. The ASF licenses this file
  68319. * to you under the Apache License, Version 2.0 (the
  68320. * "License"); you may not use this file except in compliance
  68321. * with the License. You may obtain a copy of the License at
  68322. *
  68323. * http://www.apache.org/licenses/LICENSE-2.0
  68324. *
  68325. * Unless required by applicable law or agreed to in writing,
  68326. * software distributed under the License is distributed on an
  68327. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68328. * KIND, either express or implied. See the License for the
  68329. * specific language governing permissions and limitations
  68330. * under the License.
  68331. */
  68332. registerProcessor({
  68333. // `dataZoomProcessor` will only be performed in needed series. Consider if
  68334. // there is a line series and a pie series, it is better not to update the
  68335. // line series if only pie series is needed to be updated.
  68336. getTargetSeries: function (ecModel) {
  68337. var seriesModelMap = createHashMap();
  68338. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68339. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  68340. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  68341. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  68342. seriesModelMap.set(seriesModel.uid, seriesModel);
  68343. });
  68344. });
  68345. });
  68346. return seriesModelMap;
  68347. },
  68348. modifyOutputEnd: true,
  68349. // Consider appendData, where filter should be performed. Because data process is
  68350. // in block mode currently, it is not need to worry about that the overallProgress
  68351. // execute every frame.
  68352. overallReset: function (ecModel, api) {
  68353. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68354. // We calculate window and reset axis here but not in model
  68355. // init stage and not after action dispatch handler, because
  68356. // reset should be called after seriesData.restoreData.
  68357. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  68358. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  68359. });
  68360. // Caution: data zoom filtering is order sensitive when using
  68361. // percent range and no min/max/scale set on axis.
  68362. // For example, we have dataZoom definition:
  68363. // [
  68364. // {xAxisIndex: 0, start: 30, end: 70},
  68365. // {yAxisIndex: 0, start: 20, end: 80}
  68366. // ]
  68367. // In this case, [20, 80] of y-dataZoom should be based on data
  68368. // that have filtered by x-dataZoom using range of [30, 70],
  68369. // but should not be based on full raw data. Thus sliding
  68370. // x-dataZoom will change both ranges of xAxis and yAxis,
  68371. // while sliding y-dataZoom will only change the range of yAxis.
  68372. // So we should filter x-axis after reset x-axis immediately,
  68373. // and then reset y-axis and filter y-axis.
  68374. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  68375. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  68376. });
  68377. });
  68378. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68379. // Fullfill all of the range props so that user
  68380. // is able to get them from chart.getOption().
  68381. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  68382. var percentRange = axisProxy.getDataPercentWindow();
  68383. var valueRange = axisProxy.getDataValueWindow();
  68384. dataZoomModel.setRawRange({
  68385. start: percentRange[0],
  68386. end: percentRange[1],
  68387. startValue: valueRange[0],
  68388. endValue: valueRange[1]
  68389. }, true);
  68390. });
  68391. }
  68392. });
  68393. /*
  68394. * Licensed to the Apache Software Foundation (ASF) under one
  68395. * or more contributor license agreements. See the NOTICE file
  68396. * distributed with this work for additional information
  68397. * regarding copyright ownership. The ASF licenses this file
  68398. * to you under the Apache License, Version 2.0 (the
  68399. * "License"); you may not use this file except in compliance
  68400. * with the License. You may obtain a copy of the License at
  68401. *
  68402. * http://www.apache.org/licenses/LICENSE-2.0
  68403. *
  68404. * Unless required by applicable law or agreed to in writing,
  68405. * software distributed under the License is distributed on an
  68406. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68407. * KIND, either express or implied. See the License for the
  68408. * specific language governing permissions and limitations
  68409. * under the License.
  68410. */
  68411. registerAction('dataZoom', function (payload, ecModel) {
  68412. var linkedNodesFinder = createLinkedNodesFinder(
  68413. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  68414. eachAxisDim$1,
  68415. function (model, dimNames) {
  68416. return model.get(dimNames.axisIndex);
  68417. }
  68418. );
  68419. var effectedModels = [];
  68420. ecModel.eachComponent(
  68421. {mainType: 'dataZoom', query: payload},
  68422. function (model, index) {
  68423. effectedModels.push.apply(
  68424. effectedModels, linkedNodesFinder(model).nodes
  68425. );
  68426. }
  68427. );
  68428. each$1(effectedModels, function (dataZoomModel, index) {
  68429. dataZoomModel.setRawRange({
  68430. start: payload.start,
  68431. end: payload.end,
  68432. startValue: payload.startValue,
  68433. endValue: payload.endValue
  68434. });
  68435. });
  68436. });
  68437. /*
  68438. * Licensed to the Apache Software Foundation (ASF) under one
  68439. * or more contributor license agreements. See the NOTICE file
  68440. * distributed with this work for additional information
  68441. * regarding copyright ownership. The ASF licenses this file
  68442. * to you under the Apache License, Version 2.0 (the
  68443. * "License"); you may not use this file except in compliance
  68444. * with the License. You may obtain a copy of the License at
  68445. *
  68446. * http://www.apache.org/licenses/LICENSE-2.0
  68447. *
  68448. * Unless required by applicable law or agreed to in writing,
  68449. * software distributed under the License is distributed on an
  68450. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68451. * KIND, either express or implied. See the License for the
  68452. * specific language governing permissions and limitations
  68453. * under the License.
  68454. */
  68455. /**
  68456. * DataZoom component entry
  68457. */
  68458. /*
  68459. * Licensed to the Apache Software Foundation (ASF) under one
  68460. * or more contributor license agreements. See the NOTICE file
  68461. * distributed with this work for additional information
  68462. * regarding copyright ownership. The ASF licenses this file
  68463. * to you under the Apache License, Version 2.0 (the
  68464. * "License"); you may not use this file except in compliance
  68465. * with the License. You may obtain a copy of the License at
  68466. *
  68467. * http://www.apache.org/licenses/LICENSE-2.0
  68468. *
  68469. * Unless required by applicable law or agreed to in writing,
  68470. * software distributed under the License is distributed on an
  68471. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68472. * KIND, either express or implied. See the License for the
  68473. * specific language governing permissions and limitations
  68474. * under the License.
  68475. */
  68476. var each$24 = each$1;
  68477. var preprocessor$2 = function (option) {
  68478. var visualMap = option && option.visualMap;
  68479. if (!isArray(visualMap)) {
  68480. visualMap = visualMap ? [visualMap] : [];
  68481. }
  68482. each$24(visualMap, function (opt) {
  68483. if (!opt) {
  68484. return;
  68485. }
  68486. // rename splitList to pieces
  68487. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  68488. opt.pieces = opt.splitList;
  68489. delete opt.splitList;
  68490. }
  68491. var pieces = opt.pieces;
  68492. if (pieces && isArray(pieces)) {
  68493. each$24(pieces, function (piece) {
  68494. if (isObject$1(piece)) {
  68495. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  68496. piece.min = piece.start;
  68497. }
  68498. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  68499. piece.max = piece.end;
  68500. }
  68501. }
  68502. });
  68503. }
  68504. });
  68505. };
  68506. function has$1(obj, name) {
  68507. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  68508. }
  68509. /*
  68510. * Licensed to the Apache Software Foundation (ASF) under one
  68511. * or more contributor license agreements. See the NOTICE file
  68512. * distributed with this work for additional information
  68513. * regarding copyright ownership. The ASF licenses this file
  68514. * to you under the Apache License, Version 2.0 (the
  68515. * "License"); you may not use this file except in compliance
  68516. * with the License. You may obtain a copy of the License at
  68517. *
  68518. * http://www.apache.org/licenses/LICENSE-2.0
  68519. *
  68520. * Unless required by applicable law or agreed to in writing,
  68521. * software distributed under the License is distributed on an
  68522. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68523. * KIND, either express or implied. See the License for the
  68524. * specific language governing permissions and limitations
  68525. * under the License.
  68526. */
  68527. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  68528. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  68529. return (
  68530. !option.categories
  68531. && (
  68532. !(
  68533. option.pieces
  68534. ? option.pieces.length > 0
  68535. : option.splitNumber > 0
  68536. )
  68537. || option.calculable
  68538. )
  68539. )
  68540. ? 'continuous' : 'piecewise';
  68541. });
  68542. /*
  68543. * Licensed to the Apache Software Foundation (ASF) under one
  68544. * or more contributor license agreements. See the NOTICE file
  68545. * distributed with this work for additional information
  68546. * regarding copyright ownership. The ASF licenses this file
  68547. * to you under the Apache License, Version 2.0 (the
  68548. * "License"); you may not use this file except in compliance
  68549. * with the License. You may obtain a copy of the License at
  68550. *
  68551. * http://www.apache.org/licenses/LICENSE-2.0
  68552. *
  68553. * Unless required by applicable law or agreed to in writing,
  68554. * software distributed under the License is distributed on an
  68555. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68556. * KIND, either express or implied. See the License for the
  68557. * specific language governing permissions and limitations
  68558. * under the License.
  68559. */
  68560. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  68561. registerVisual(VISUAL_PRIORITY, {
  68562. createOnAllSeries: true,
  68563. reset: function (seriesModel, ecModel) {
  68564. var resetDefines = [];
  68565. ecModel.eachComponent('visualMap', function (visualMapModel) {
  68566. var pipelineContext = seriesModel.pipelineContext;
  68567. if (!visualMapModel.isTargetSeries(seriesModel)
  68568. || (pipelineContext && pipelineContext.large)
  68569. ) {
  68570. return;
  68571. }
  68572. resetDefines.push(incrementalApplyVisual(
  68573. visualMapModel.stateList,
  68574. visualMapModel.targetVisuals,
  68575. bind(visualMapModel.getValueState, visualMapModel),
  68576. visualMapModel.getDataDimension(seriesModel.getData())
  68577. ));
  68578. });
  68579. return resetDefines;
  68580. }
  68581. });
  68582. // Only support color.
  68583. registerVisual(VISUAL_PRIORITY, {
  68584. createOnAllSeries: true,
  68585. reset: function (seriesModel, ecModel) {
  68586. var data = seriesModel.getData();
  68587. var visualMetaList = [];
  68588. ecModel.eachComponent('visualMap', function (visualMapModel) {
  68589. if (visualMapModel.isTargetSeries(seriesModel)) {
  68590. var visualMeta = visualMapModel.getVisualMeta(
  68591. bind(getColorVisual, null, seriesModel, visualMapModel)
  68592. ) || {stops: [], outerColors: []};
  68593. var concreteDim = visualMapModel.getDataDimension(data);
  68594. var dimInfo = data.getDimensionInfo(concreteDim);
  68595. if (dimInfo != null) {
  68596. // visualMeta.dimension should be dimension index, but not concrete dimension.
  68597. visualMeta.dimension = dimInfo.index;
  68598. visualMetaList.push(visualMeta);
  68599. }
  68600. }
  68601. });
  68602. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  68603. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  68604. }
  68605. });
  68606. // FIXME
  68607. // performance and export for heatmap?
  68608. // value can be Infinity or -Infinity
  68609. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  68610. var mappings = visualMapModel.targetVisuals[valueState];
  68611. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  68612. var resultVisual = {
  68613. color: seriesModel.getData().getVisual('color') // default color.
  68614. };
  68615. for (var i = 0, len = visualTypes.length; i < len; i++) {
  68616. var type = visualTypes[i];
  68617. var mapping = mappings[
  68618. type === 'opacity' ? '__alphaForOpacity' : type
  68619. ];
  68620. mapping && mapping.applyVisual(value, getVisual, setVisual);
  68621. }
  68622. return resultVisual.color;
  68623. function getVisual(key) {
  68624. return resultVisual[key];
  68625. }
  68626. function setVisual(key, value) {
  68627. resultVisual[key] = value;
  68628. }
  68629. }
  68630. /*
  68631. * Licensed to the Apache Software Foundation (ASF) under one
  68632. * or more contributor license agreements. See the NOTICE file
  68633. * distributed with this work for additional information
  68634. * regarding copyright ownership. The ASF licenses this file
  68635. * to you under the Apache License, Version 2.0 (the
  68636. * "License"); you may not use this file except in compliance
  68637. * with the License. You may obtain a copy of the License at
  68638. *
  68639. * http://www.apache.org/licenses/LICENSE-2.0
  68640. *
  68641. * Unless required by applicable law or agreed to in writing,
  68642. * software distributed under the License is distributed on an
  68643. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68644. * KIND, either express or implied. See the License for the
  68645. * specific language governing permissions and limitations
  68646. * under the License.
  68647. */
  68648. /**
  68649. * @file Visual mapping.
  68650. */
  68651. var visualDefault = {
  68652. /**
  68653. * @public
  68654. */
  68655. get: function (visualType, key, isCategory) {
  68656. var value = clone(
  68657. (defaultOption$3[visualType] || {})[key]
  68658. );
  68659. return isCategory
  68660. ? (isArray(value) ? value[value.length - 1] : value)
  68661. : value;
  68662. }
  68663. };
  68664. var defaultOption$3 = {
  68665. color: {
  68666. active: ['#006edd', '#e0ffff'],
  68667. inactive: ['rgba(0,0,0,0)']
  68668. },
  68669. colorHue: {
  68670. active: [0, 360],
  68671. inactive: [0, 0]
  68672. },
  68673. colorSaturation: {
  68674. active: [0.3, 1],
  68675. inactive: [0, 0]
  68676. },
  68677. colorLightness: {
  68678. active: [0.9, 0.5],
  68679. inactive: [0, 0]
  68680. },
  68681. colorAlpha: {
  68682. active: [0.3, 1],
  68683. inactive: [0, 0]
  68684. },
  68685. opacity: {
  68686. active: [0.3, 1],
  68687. inactive: [0, 0]
  68688. },
  68689. symbol: {
  68690. active: ['circle', 'roundRect', 'diamond'],
  68691. inactive: ['none']
  68692. },
  68693. symbolSize: {
  68694. active: [10, 50],
  68695. inactive: [0, 0]
  68696. }
  68697. };
  68698. /*
  68699. * Licensed to the Apache Software Foundation (ASF) under one
  68700. * or more contributor license agreements. See the NOTICE file
  68701. * distributed with this work for additional information
  68702. * regarding copyright ownership. The ASF licenses this file
  68703. * to you under the Apache License, Version 2.0 (the
  68704. * "License"); you may not use this file except in compliance
  68705. * with the License. You may obtain a copy of the License at
  68706. *
  68707. * http://www.apache.org/licenses/LICENSE-2.0
  68708. *
  68709. * Unless required by applicable law or agreed to in writing,
  68710. * software distributed under the License is distributed on an
  68711. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68712. * KIND, either express or implied. See the License for the
  68713. * specific language governing permissions and limitations
  68714. * under the License.
  68715. */
  68716. var mapVisual$2 = VisualMapping.mapVisual;
  68717. var eachVisual = VisualMapping.eachVisual;
  68718. var isArray$3 = isArray;
  68719. var each$25 = each$1;
  68720. var asc$3 = asc;
  68721. var linearMap$2 = linearMap;
  68722. var noop$2 = noop;
  68723. var VisualMapModel = extendComponentModel({
  68724. type: 'visualMap',
  68725. dependencies: ['series'],
  68726. /**
  68727. * @readOnly
  68728. * @type {Array.<string>}
  68729. */
  68730. stateList: ['inRange', 'outOfRange'],
  68731. /**
  68732. * @readOnly
  68733. * @type {Array.<string>}
  68734. */
  68735. replacableOptionKeys: [
  68736. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  68737. ],
  68738. /**
  68739. * [lowerBound, upperBound]
  68740. *
  68741. * @readOnly
  68742. * @type {Array.<number>}
  68743. */
  68744. dataBound: [-Infinity, Infinity],
  68745. /**
  68746. * @readOnly
  68747. * @type {string|Object}
  68748. */
  68749. layoutMode: {type: 'box', ignoreSize: true},
  68750. /**
  68751. * @protected
  68752. */
  68753. defaultOption: {
  68754. show: true,
  68755. zlevel: 0,
  68756. z: 4,
  68757. seriesIndex: 'all', // 'all' or null/undefined: all series.
  68758. // A number or an array of number: the specified series.
  68759. // set min: 0, max: 200, only for campatible with ec2.
  68760. // In fact min max should not have default value.
  68761. min: 0, // min value, must specified if pieces is not specified.
  68762. max: 200, // max value, must specified if pieces is not specified.
  68763. dimension: null,
  68764. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  68765. // 'symbol', 'symbolSize'
  68766. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  68767. // 'colorLightness', 'colorAlpha',
  68768. // 'symbol', 'symbolSize'
  68769. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  68770. right: null, // The same as left.
  68771. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  68772. bottom: 0, // The same as top.
  68773. itemWidth: null,
  68774. itemHeight: null,
  68775. inverse: false,
  68776. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  68777. backgroundColor: 'rgba(0,0,0,0)',
  68778. borderColor: '#ccc', // 值域边框颜色
  68779. contentColor: '#5793f3',
  68780. inactiveColor: '#aaa',
  68781. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  68782. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  68783. // 接受数组分别设定上右下左边距,同css
  68784. textGap: 10, //
  68785. precision: 0, // 小数精度,默认为0,无小数点
  68786. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  68787. formatter: null,
  68788. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  68789. textStyle: {
  68790. color: '#333' // 值域文字颜色
  68791. }
  68792. },
  68793. /**
  68794. * @protected
  68795. */
  68796. init: function (option, parentModel, ecModel) {
  68797. /**
  68798. * @private
  68799. * @type {Array.<number>}
  68800. */
  68801. this._dataExtent;
  68802. /**
  68803. * @readOnly
  68804. */
  68805. this.targetVisuals = {};
  68806. /**
  68807. * @readOnly
  68808. */
  68809. this.controllerVisuals = {};
  68810. /**
  68811. * @readOnly
  68812. */
  68813. this.textStyleModel;
  68814. /**
  68815. * [width, height]
  68816. * @readOnly
  68817. * @type {Array.<number>}
  68818. */
  68819. this.itemSize;
  68820. this.mergeDefaultAndTheme(option, ecModel);
  68821. },
  68822. /**
  68823. * @protected
  68824. */
  68825. optionUpdated: function (newOption, isInit) {
  68826. var thisOption = this.option;
  68827. // FIXME
  68828. // necessary?
  68829. // Disable realtime view update if canvas is not supported.
  68830. if (!env$1.canvasSupported) {
  68831. thisOption.realtime = false;
  68832. }
  68833. !isInit && replaceVisualOption(
  68834. thisOption, newOption, this.replacableOptionKeys
  68835. );
  68836. this.textStyleModel = this.getModel('textStyle');
  68837. this.resetItemSize();
  68838. this.completeVisualOption();
  68839. },
  68840. /**
  68841. * @protected
  68842. */
  68843. resetVisual: function (supplementVisualOption) {
  68844. var stateList = this.stateList;
  68845. supplementVisualOption = bind(supplementVisualOption, this);
  68846. this.controllerVisuals = createVisualMappings(
  68847. this.option.controller, stateList, supplementVisualOption
  68848. );
  68849. this.targetVisuals = createVisualMappings(
  68850. this.option.target, stateList, supplementVisualOption
  68851. );
  68852. },
  68853. /**
  68854. * @protected
  68855. * @return {Array.<number>} An array of series indices.
  68856. */
  68857. getTargetSeriesIndices: function () {
  68858. var optionSeriesIndex = this.option.seriesIndex;
  68859. var seriesIndices = [];
  68860. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  68861. this.ecModel.eachSeries(function (seriesModel, index) {
  68862. seriesIndices.push(index);
  68863. });
  68864. }
  68865. else {
  68866. seriesIndices = normalizeToArray(optionSeriesIndex);
  68867. }
  68868. return seriesIndices;
  68869. },
  68870. /**
  68871. * @public
  68872. */
  68873. eachTargetSeries: function (callback, context) {
  68874. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  68875. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  68876. }, this);
  68877. },
  68878. /**
  68879. * @pubilc
  68880. */
  68881. isTargetSeries: function (seriesModel) {
  68882. var is = false;
  68883. this.eachTargetSeries(function (model) {
  68884. model === seriesModel && (is = true);
  68885. });
  68886. return is;
  68887. },
  68888. /**
  68889. * @example
  68890. * this.formatValueText(someVal); // format single numeric value to text.
  68891. * this.formatValueText(someVal, true); // format single category value to text.
  68892. * this.formatValueText([min, max]); // format numeric min-max to text.
  68893. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  68894. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  68895. *
  68896. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  68897. * @param {boolean} [isCategory=false] Only available when value is number.
  68898. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  68899. * @return {string}
  68900. * @protected
  68901. */
  68902. formatValueText: function(value, isCategory, edgeSymbols) {
  68903. var option = this.option;
  68904. var precision = option.precision;
  68905. var dataBound = this.dataBound;
  68906. var formatter = option.formatter;
  68907. var isMinMax;
  68908. var textValue;
  68909. edgeSymbols = edgeSymbols || ['<', '>'];
  68910. if (isArray(value)) {
  68911. value = value.slice();
  68912. isMinMax = true;
  68913. }
  68914. textValue = isCategory
  68915. ? value
  68916. : (isMinMax
  68917. ? [toFixed(value[0]), toFixed(value[1])]
  68918. : toFixed(value)
  68919. );
  68920. if (isString(formatter)) {
  68921. return formatter
  68922. .replace('{value}', isMinMax ? textValue[0] : textValue)
  68923. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  68924. }
  68925. else if (isFunction$1(formatter)) {
  68926. return isMinMax
  68927. ? formatter(value[0], value[1])
  68928. : formatter(value);
  68929. }
  68930. if (isMinMax) {
  68931. if (value[0] === dataBound[0]) {
  68932. return edgeSymbols[0] + ' ' + textValue[1];
  68933. }
  68934. else if (value[1] === dataBound[1]) {
  68935. return edgeSymbols[1] + ' ' + textValue[0];
  68936. }
  68937. else {
  68938. return textValue[0] + ' - ' + textValue[1];
  68939. }
  68940. }
  68941. else { // Format single value (includes category case).
  68942. return textValue;
  68943. }
  68944. function toFixed(val) {
  68945. return val === dataBound[0]
  68946. ? 'min'
  68947. : val === dataBound[1]
  68948. ? 'max'
  68949. : (+val).toFixed(Math.min(precision, 20));
  68950. }
  68951. },
  68952. /**
  68953. * @protected
  68954. */
  68955. resetExtent: function () {
  68956. var thisOption = this.option;
  68957. // Can not calculate data extent by data here.
  68958. // Because series and data may be modified in processing stage.
  68959. // So we do not support the feature "auto min/max".
  68960. var extent = asc$3([thisOption.min, thisOption.max]);
  68961. this._dataExtent = extent;
  68962. },
  68963. /**
  68964. * @public
  68965. * @param {module:echarts/data/List} list
  68966. * @return {string} Concrete dimention. If return null/undefined,
  68967. * no dimension used.
  68968. */
  68969. getDataDimension: function (list) {
  68970. var optDim = this.option.dimension;
  68971. var listDimensions = list.dimensions;
  68972. if (optDim == null && !listDimensions.length) {
  68973. return;
  68974. }
  68975. if (optDim != null) {
  68976. return list.getDimension(optDim);
  68977. }
  68978. var dimNames = list.dimensions;
  68979. for (var i = dimNames.length - 1; i >= 0; i--) {
  68980. var dimName = dimNames[i];
  68981. var dimInfo = list.getDimensionInfo(dimName);
  68982. if (!dimInfo.isCalculationCoord) {
  68983. return dimName;
  68984. }
  68985. }
  68986. },
  68987. /**
  68988. * @public
  68989. * @override
  68990. */
  68991. getExtent: function () {
  68992. return this._dataExtent.slice();
  68993. },
  68994. /**
  68995. * @protected
  68996. */
  68997. completeVisualOption: function () {
  68998. var ecModel = this.ecModel;
  68999. var thisOption = this.option;
  69000. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  69001. var target = thisOption.target || (thisOption.target = {});
  69002. var controller = thisOption.controller || (thisOption.controller = {});
  69003. merge(target, base); // Do not override
  69004. merge(controller, base); // Do not override
  69005. var isCategory = this.isCategory();
  69006. completeSingle.call(this, target);
  69007. completeSingle.call(this, controller);
  69008. completeInactive.call(this, target, 'inRange', 'outOfRange');
  69009. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  69010. completeController.call(this, controller);
  69011. function completeSingle(base) {
  69012. // Compatible with ec2 dataRange.color.
  69013. // The mapping order of dataRange.color is: [high value, ..., low value]
  69014. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  69015. // Notice: ec2 has no inverse.
  69016. if (isArray$3(thisOption.color)
  69017. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  69018. // So adding color only when no inRange defined.
  69019. && !base.inRange
  69020. ) {
  69021. base.inRange = {color: thisOption.color.slice().reverse()};
  69022. }
  69023. // Compatible with previous logic, always give a defautl color, otherwise
  69024. // simple config with no inRange and outOfRange will not work.
  69025. // Originally we use visualMap.color as the default color, but setOption at
  69026. // the second time the default color will be erased. So we change to use
  69027. // constant DEFAULT_COLOR.
  69028. // If user do not want the defualt color, set inRange: {color: null}.
  69029. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  69030. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  69031. each$25(this.stateList, function (state) {
  69032. var visualType = base[state];
  69033. if (isString(visualType)) {
  69034. var defa = visualDefault.get(visualType, 'active', isCategory);
  69035. if (defa) {
  69036. base[state] = {};
  69037. base[state][visualType] = defa;
  69038. }
  69039. else {
  69040. // Mark as not specified.
  69041. delete base[state];
  69042. }
  69043. }
  69044. }, this);
  69045. }
  69046. function completeInactive(base, stateExist, stateAbsent) {
  69047. var optExist = base[stateExist];
  69048. var optAbsent = base[stateAbsent];
  69049. if (optExist && !optAbsent) {
  69050. optAbsent = base[stateAbsent] = {};
  69051. each$25(optExist, function (visualData, visualType) {
  69052. if (!VisualMapping.isValidType(visualType)) {
  69053. return;
  69054. }
  69055. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  69056. if (defa != null) {
  69057. optAbsent[visualType] = defa;
  69058. // Compatibable with ec2:
  69059. // Only inactive color to rgba(0,0,0,0) can not
  69060. // make label transparent, so use opacity also.
  69061. if (visualType === 'color'
  69062. && !optAbsent.hasOwnProperty('opacity')
  69063. && !optAbsent.hasOwnProperty('colorAlpha')
  69064. ) {
  69065. optAbsent.opacity = [0, 0];
  69066. }
  69067. }
  69068. });
  69069. }
  69070. }
  69071. function completeController(controller) {
  69072. var symbolExists = (controller.inRange || {}).symbol
  69073. || (controller.outOfRange || {}).symbol;
  69074. var symbolSizeExists = (controller.inRange || {}).symbolSize
  69075. || (controller.outOfRange || {}).symbolSize;
  69076. var inactiveColor = this.get('inactiveColor');
  69077. each$25(this.stateList, function (state) {
  69078. var itemSize = this.itemSize;
  69079. var visuals = controller[state];
  69080. // Set inactive color for controller if no other color
  69081. // attr (like colorAlpha) specified.
  69082. if (!visuals) {
  69083. visuals = controller[state] = {
  69084. color: isCategory ? inactiveColor : [inactiveColor]
  69085. };
  69086. }
  69087. // Consistent symbol and symbolSize if not specified.
  69088. if (visuals.symbol == null) {
  69089. visuals.symbol = symbolExists
  69090. && clone(symbolExists)
  69091. || (isCategory ? 'roundRect' : ['roundRect']);
  69092. }
  69093. if (visuals.symbolSize == null) {
  69094. visuals.symbolSize = symbolSizeExists
  69095. && clone(symbolSizeExists)
  69096. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  69097. }
  69098. // Filter square and none.
  69099. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  69100. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  69101. });
  69102. // Normalize symbolSize
  69103. var symbolSize = visuals.symbolSize;
  69104. if (symbolSize != null) {
  69105. var max = -Infinity;
  69106. // symbolSize can be object when categories defined.
  69107. eachVisual(symbolSize, function (value) {
  69108. value > max && (max = value);
  69109. });
  69110. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  69111. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  69112. });
  69113. }
  69114. }, this);
  69115. }
  69116. },
  69117. /**
  69118. * @protected
  69119. */
  69120. resetItemSize: function () {
  69121. this.itemSize = [
  69122. parseFloat(this.get('itemWidth')),
  69123. parseFloat(this.get('itemHeight'))
  69124. ];
  69125. },
  69126. /**
  69127. * @public
  69128. */
  69129. isCategory: function () {
  69130. return !!this.option.categories;
  69131. },
  69132. /**
  69133. * @public
  69134. * @abstract
  69135. */
  69136. setSelected: noop$2,
  69137. /**
  69138. * @public
  69139. * @abstract
  69140. * @param {*|module:echarts/data/List} valueOrData
  69141. * @param {number} dataIndex
  69142. * @return {string} state See this.stateList
  69143. */
  69144. getValueState: noop$2,
  69145. /**
  69146. * FIXME
  69147. * Do not publish to thirt-part-dev temporarily
  69148. * util the interface is stable. (Should it return
  69149. * a function but not visual meta?)
  69150. *
  69151. * @pubilc
  69152. * @abstract
  69153. * @param {Function} getColorVisual
  69154. * params: value, valueState
  69155. * return: color
  69156. * @return {Object} visualMeta
  69157. * should includes {stops, outerColors}
  69158. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  69159. */
  69160. getVisualMeta: noop$2
  69161. });
  69162. /*
  69163. * Licensed to the Apache Software Foundation (ASF) under one
  69164. * or more contributor license agreements. See the NOTICE file
  69165. * distributed with this work for additional information
  69166. * regarding copyright ownership. The ASF licenses this file
  69167. * to you under the Apache License, Version 2.0 (the
  69168. * "License"); you may not use this file except in compliance
  69169. * with the License. You may obtain a copy of the License at
  69170. *
  69171. * http://www.apache.org/licenses/LICENSE-2.0
  69172. *
  69173. * Unless required by applicable law or agreed to in writing,
  69174. * software distributed under the License is distributed on an
  69175. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69176. * KIND, either express or implied. See the License for the
  69177. * specific language governing permissions and limitations
  69178. * under the License.
  69179. */
  69180. // Constant
  69181. var DEFAULT_BAR_BOUND = [20, 140];
  69182. var ContinuousModel = VisualMapModel.extend({
  69183. type: 'visualMap.continuous',
  69184. /**
  69185. * @protected
  69186. */
  69187. defaultOption: {
  69188. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  69189. calculable: false, // This prop effect default component type determine,
  69190. // See echarts/component/visualMap/typeDefaulter.
  69191. range: null, // selected range. In default case `range` is [min, max]
  69192. // and can auto change along with modification of min max,
  69193. // util use specifid a range.
  69194. realtime: true, // Whether realtime update.
  69195. itemHeight: null, // The length of the range control edge.
  69196. itemWidth: null, // The length of the other side.
  69197. hoverLink: true, // Enable hover highlight.
  69198. hoverLinkDataSize: null,// The size of hovered data.
  69199. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  69200. // If not specified, follow the value of `realtime`.
  69201. },
  69202. /**
  69203. * @override
  69204. */
  69205. optionUpdated: function (newOption, isInit) {
  69206. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  69207. this.resetExtent();
  69208. this.resetVisual(function (mappingOption) {
  69209. mappingOption.mappingMethod = 'linear';
  69210. mappingOption.dataExtent = this.getExtent();
  69211. });
  69212. this._resetRange();
  69213. },
  69214. /**
  69215. * @protected
  69216. * @override
  69217. */
  69218. resetItemSize: function () {
  69219. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  69220. var itemSize = this.itemSize;
  69221. this._orient === 'horizontal' && itemSize.reverse();
  69222. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  69223. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  69224. },
  69225. /**
  69226. * @private
  69227. */
  69228. _resetRange: function () {
  69229. var dataExtent = this.getExtent();
  69230. var range = this.option.range;
  69231. if (!range || range.auto) {
  69232. // `range` should always be array (so we dont use other
  69233. // value like 'auto') for user-friend. (consider getOption).
  69234. dataExtent.auto = 1;
  69235. this.option.range = dataExtent;
  69236. }
  69237. else if (isArray(range)) {
  69238. if (range[0] > range[1]) {
  69239. range.reverse();
  69240. }
  69241. range[0] = Math.max(range[0], dataExtent[0]);
  69242. range[1] = Math.min(range[1], dataExtent[1]);
  69243. }
  69244. },
  69245. /**
  69246. * @protected
  69247. * @override
  69248. */
  69249. completeVisualOption: function () {
  69250. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  69251. each$1(this.stateList, function (state) {
  69252. var symbolSize = this.option.controller[state].symbolSize;
  69253. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  69254. symbolSize[0] = 0; // For good looking.
  69255. }
  69256. }, this);
  69257. },
  69258. /**
  69259. * @override
  69260. */
  69261. setSelected: function (selected) {
  69262. this.option.range = selected.slice();
  69263. this._resetRange();
  69264. },
  69265. /**
  69266. * @public
  69267. */
  69268. getSelected: function () {
  69269. var dataExtent = this.getExtent();
  69270. var dataInterval = asc(
  69271. (this.get('range') || []).slice()
  69272. );
  69273. // Clamp
  69274. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  69275. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  69276. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  69277. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  69278. return dataInterval;
  69279. },
  69280. /**
  69281. * @override
  69282. */
  69283. getValueState: function (value) {
  69284. var range = this.option.range;
  69285. var dataExtent = this.getExtent();
  69286. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  69287. // range[1] is processed likewise.
  69288. return (
  69289. (range[0] <= dataExtent[0] || range[0] <= value)
  69290. && (range[1] >= dataExtent[1] || value <= range[1])
  69291. ) ? 'inRange' : 'outOfRange';
  69292. },
  69293. /**
  69294. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  69295. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  69296. */
  69297. findTargetDataIndices: function (range) {
  69298. var result = [];
  69299. this.eachTargetSeries(function (seriesModel) {
  69300. var dataIndices = [];
  69301. var data = seriesModel.getData();
  69302. data.each(this.getDataDimension(data), function (value, dataIndex) {
  69303. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  69304. }, this);
  69305. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  69306. }, this);
  69307. return result;
  69308. },
  69309. /**
  69310. * @implement
  69311. */
  69312. getVisualMeta: function (getColorVisual) {
  69313. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  69314. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  69315. var stops = [];
  69316. function setStop(value, valueState) {
  69317. stops.push({
  69318. value: value,
  69319. color: getColorVisual(value, valueState)
  69320. });
  69321. }
  69322. // Format to: outOfRange -- inRange -- outOfRange.
  69323. var iIdx = 0;
  69324. var oIdx = 0;
  69325. var iLen = iVals.length;
  69326. var oLen = oVals.length;
  69327. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  69328. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  69329. if (oVals[oIdx] < iVals[iIdx]) {
  69330. setStop(oVals[oIdx], 'outOfRange');
  69331. }
  69332. }
  69333. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  69334. // If range is full, value beyond min, max will be clamped.
  69335. // make a singularity
  69336. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  69337. setStop(iVals[iIdx], 'inRange');
  69338. }
  69339. for (var first = 1; oIdx < oLen; oIdx++) {
  69340. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  69341. // make a singularity
  69342. if (first) {
  69343. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  69344. first = 0;
  69345. }
  69346. setStop(oVals[oIdx], 'outOfRange');
  69347. }
  69348. }
  69349. var stopsLen = stops.length;
  69350. return {
  69351. stops: stops,
  69352. outerColors: [
  69353. stopsLen ? stops[0].color : 'transparent',
  69354. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  69355. ]
  69356. };
  69357. }
  69358. });
  69359. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  69360. if (dataExtent[0] === dataExtent[1]) {
  69361. return dataExtent.slice();
  69362. }
  69363. // When using colorHue mapping, it is not linear color any more.
  69364. // Moreover, canvas gradient seems not to be accurate linear.
  69365. // FIXME
  69366. // Should be arbitrary value 100? or based on pixel size?
  69367. var count = 200;
  69368. var step = (dataExtent[1] - dataExtent[0]) / count;
  69369. var value = dataExtent[0];
  69370. var stopValues = [];
  69371. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  69372. stopValues.push(value);
  69373. value += step;
  69374. }
  69375. stopValues.push(dataExtent[1]);
  69376. return stopValues;
  69377. }
  69378. /*
  69379. * Licensed to the Apache Software Foundation (ASF) under one
  69380. * or more contributor license agreements. See the NOTICE file
  69381. * distributed with this work for additional information
  69382. * regarding copyright ownership. The ASF licenses this file
  69383. * to you under the Apache License, Version 2.0 (the
  69384. * "License"); you may not use this file except in compliance
  69385. * with the License. You may obtain a copy of the License at
  69386. *
  69387. * http://www.apache.org/licenses/LICENSE-2.0
  69388. *
  69389. * Unless required by applicable law or agreed to in writing,
  69390. * software distributed under the License is distributed on an
  69391. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69392. * KIND, either express or implied. See the License for the
  69393. * specific language governing permissions and limitations
  69394. * under the License.
  69395. */
  69396. var VisualMapView = extendComponentView({
  69397. type: 'visualMap',
  69398. /**
  69399. * @readOnly
  69400. * @type {Object}
  69401. */
  69402. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  69403. init: function (ecModel, api) {
  69404. /**
  69405. * @readOnly
  69406. * @type {module:echarts/model/Global}
  69407. */
  69408. this.ecModel = ecModel;
  69409. /**
  69410. * @readOnly
  69411. * @type {module:echarts/ExtensionAPI}
  69412. */
  69413. this.api = api;
  69414. /**
  69415. * @readOnly
  69416. * @type {module:echarts/component/visualMap/visualMapModel}
  69417. */
  69418. this.visualMapModel;
  69419. },
  69420. /**
  69421. * @protected
  69422. */
  69423. render: function (visualMapModel, ecModel, api, payload) {
  69424. this.visualMapModel = visualMapModel;
  69425. if (visualMapModel.get('show') === false) {
  69426. this.group.removeAll();
  69427. return;
  69428. }
  69429. this.doRender.apply(this, arguments);
  69430. },
  69431. /**
  69432. * @protected
  69433. */
  69434. renderBackground: function (group) {
  69435. var visualMapModel = this.visualMapModel;
  69436. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  69437. var rect = group.getBoundingRect();
  69438. group.add(new Rect({
  69439. z2: -1, // Lay background rect on the lowest layer.
  69440. silent: true,
  69441. shape: {
  69442. x: rect.x - padding[3],
  69443. y: rect.y - padding[0],
  69444. width: rect.width + padding[3] + padding[1],
  69445. height: rect.height + padding[0] + padding[2]
  69446. },
  69447. style: {
  69448. fill: visualMapModel.get('backgroundColor'),
  69449. stroke: visualMapModel.get('borderColor'),
  69450. lineWidth: visualMapModel.get('borderWidth')
  69451. }
  69452. }));
  69453. },
  69454. /**
  69455. * @protected
  69456. * @param {number} targetValue can be Infinity or -Infinity
  69457. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  69458. * @param {Object} [opts]
  69459. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  69460. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  69461. * @return {*} Visual value.
  69462. */
  69463. getControllerVisual: function (targetValue, visualCluster, opts) {
  69464. opts = opts || {};
  69465. var forceState = opts.forceState;
  69466. var visualMapModel = this.visualMapModel;
  69467. var visualObj = {};
  69468. // Default values.
  69469. if (visualCluster === 'symbol') {
  69470. visualObj.symbol = visualMapModel.get('itemSymbol');
  69471. }
  69472. if (visualCluster === 'color') {
  69473. var defaultColor = visualMapModel.get('contentColor');
  69474. visualObj.color = defaultColor;
  69475. }
  69476. function getter(key) {
  69477. return visualObj[key];
  69478. }
  69479. function setter(key, value) {
  69480. visualObj[key] = value;
  69481. }
  69482. var mappings = visualMapModel.controllerVisuals[
  69483. forceState || visualMapModel.getValueState(targetValue)
  69484. ];
  69485. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  69486. each$1(visualTypes, function (type) {
  69487. var visualMapping = mappings[type];
  69488. if (opts.convertOpacityToAlpha && type === 'opacity') {
  69489. type = 'colorAlpha';
  69490. visualMapping = mappings.__alphaForOpacity;
  69491. }
  69492. if (VisualMapping.dependsOn(type, visualCluster)) {
  69493. visualMapping && visualMapping.applyVisual(
  69494. targetValue, getter, setter
  69495. );
  69496. }
  69497. });
  69498. return visualObj[visualCluster];
  69499. },
  69500. /**
  69501. * @protected
  69502. */
  69503. positionGroup: function (group) {
  69504. var model = this.visualMapModel;
  69505. var api = this.api;
  69506. positionElement(
  69507. group,
  69508. model.getBoxLayoutParams(),
  69509. {width: api.getWidth(), height: api.getHeight()}
  69510. );
  69511. },
  69512. /**
  69513. * @protected
  69514. * @abstract
  69515. */
  69516. doRender: noop
  69517. });
  69518. /*
  69519. * Licensed to the Apache Software Foundation (ASF) under one
  69520. * or more contributor license agreements. See the NOTICE file
  69521. * distributed with this work for additional information
  69522. * regarding copyright ownership. The ASF licenses this file
  69523. * to you under the Apache License, Version 2.0 (the
  69524. * "License"); you may not use this file except in compliance
  69525. * with the License. You may obtain a copy of the License at
  69526. *
  69527. * http://www.apache.org/licenses/LICENSE-2.0
  69528. *
  69529. * Unless required by applicable law or agreed to in writing,
  69530. * software distributed under the License is distributed on an
  69531. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69532. * KIND, either express or implied. See the License for the
  69533. * specific language governing permissions and limitations
  69534. * under the License.
  69535. */
  69536. /**
  69537. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  69538. * @param {module:echarts/ExtensionAPI} api
  69539. * @param {Array.<number>} itemSize always [short, long]
  69540. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  69541. */
  69542. function getItemAlign(visualMapModel, api, itemSize) {
  69543. var modelOption = visualMapModel.option;
  69544. var itemAlign = modelOption.align;
  69545. if (itemAlign != null && itemAlign !== 'auto') {
  69546. return itemAlign;
  69547. }
  69548. // Auto decision align.
  69549. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  69550. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  69551. var paramsSet = [
  69552. ['left', 'right', 'width'],
  69553. ['top', 'bottom', 'height']
  69554. ];
  69555. var reals = paramsSet[realIndex];
  69556. var fakeValue = [0, null, 10];
  69557. var layoutInput = {};
  69558. for (var i = 0; i < 3; i++) {
  69559. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  69560. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  69561. }
  69562. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  69563. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  69564. return reals[
  69565. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  69566. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  69567. ];
  69568. }
  69569. /**
  69570. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  69571. * dataIndexInside means filtered index.
  69572. */
  69573. function convertDataIndex(batch) {
  69574. each$1(batch || [], function (batchItem) {
  69575. if (batch.dataIndex != null) {
  69576. batch.dataIndexInside = batch.dataIndex;
  69577. batch.dataIndex = null;
  69578. }
  69579. });
  69580. return batch;
  69581. }
  69582. /*
  69583. * Licensed to the Apache Software Foundation (ASF) under one
  69584. * or more contributor license agreements. See the NOTICE file
  69585. * distributed with this work for additional information
  69586. * regarding copyright ownership. The ASF licenses this file
  69587. * to you under the Apache License, Version 2.0 (the
  69588. * "License"); you may not use this file except in compliance
  69589. * with the License. You may obtain a copy of the License at
  69590. *
  69591. * http://www.apache.org/licenses/LICENSE-2.0
  69592. *
  69593. * Unless required by applicable law or agreed to in writing,
  69594. * software distributed under the License is distributed on an
  69595. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69596. * KIND, either express or implied. See the License for the
  69597. * specific language governing permissions and limitations
  69598. * under the License.
  69599. */
  69600. var linearMap$3 = linearMap;
  69601. var each$26 = each$1;
  69602. var mathMin$7 = Math.min;
  69603. var mathMax$7 = Math.max;
  69604. // Arbitrary value
  69605. var HOVER_LINK_SIZE = 12;
  69606. var HOVER_LINK_OUT = 6;
  69607. // Notice:
  69608. // Any "interval" should be by the order of [low, high].
  69609. // "handle0" (handleIndex === 0) maps to
  69610. // low data value: this._dataInterval[0] and has low coord.
  69611. // "handle1" (handleIndex === 1) maps to
  69612. // high data value: this._dataInterval[1] and has high coord.
  69613. // The logic of transform is implemented in this._createBarGroup.
  69614. var ContinuousView = VisualMapView.extend({
  69615. type: 'visualMap.continuous',
  69616. /**
  69617. * @override
  69618. */
  69619. init: function () {
  69620. ContinuousView.superApply(this, 'init', arguments);
  69621. /**
  69622. * @private
  69623. */
  69624. this._shapes = {};
  69625. /**
  69626. * @private
  69627. */
  69628. this._dataInterval = [];
  69629. /**
  69630. * @private
  69631. */
  69632. this._handleEnds = [];
  69633. /**
  69634. * @private
  69635. */
  69636. this._orient;
  69637. /**
  69638. * @private
  69639. */
  69640. this._useHandle;
  69641. /**
  69642. * @private
  69643. */
  69644. this._hoverLinkDataIndices = [];
  69645. /**
  69646. * @private
  69647. */
  69648. this._dragging;
  69649. /**
  69650. * @private
  69651. */
  69652. this._hovering;
  69653. },
  69654. /**
  69655. * @protected
  69656. * @override
  69657. */
  69658. doRender: function (visualMapModel, ecModel, api, payload) {
  69659. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  69660. this._buildView();
  69661. }
  69662. },
  69663. /**
  69664. * @private
  69665. */
  69666. _buildView: function () {
  69667. this.group.removeAll();
  69668. var visualMapModel = this.visualMapModel;
  69669. var thisGroup = this.group;
  69670. this._orient = visualMapModel.get('orient');
  69671. this._useHandle = visualMapModel.get('calculable');
  69672. this._resetInterval();
  69673. this._renderBar(thisGroup);
  69674. var dataRangeText = visualMapModel.get('text');
  69675. this._renderEndsText(thisGroup, dataRangeText, 0);
  69676. this._renderEndsText(thisGroup, dataRangeText, 1);
  69677. // Do this for background size calculation.
  69678. this._updateView(true);
  69679. // After updating view, inner shapes is built completely,
  69680. // and then background can be rendered.
  69681. this.renderBackground(thisGroup);
  69682. // Real update view
  69683. this._updateView();
  69684. this._enableHoverLinkToSeries();
  69685. this._enableHoverLinkFromSeries();
  69686. this.positionGroup(thisGroup);
  69687. },
  69688. /**
  69689. * @private
  69690. */
  69691. _renderEndsText: function (group, dataRangeText, endsIndex) {
  69692. if (!dataRangeText) {
  69693. return;
  69694. }
  69695. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  69696. var text = dataRangeText[1 - endsIndex];
  69697. text = text != null ? text + '' : '';
  69698. var visualMapModel = this.visualMapModel;
  69699. var textGap = visualMapModel.get('textGap');
  69700. var itemSize = visualMapModel.itemSize;
  69701. var barGroup = this._shapes.barGroup;
  69702. var position = this._applyTransform(
  69703. [
  69704. itemSize[0] / 2,
  69705. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  69706. ],
  69707. barGroup
  69708. );
  69709. var align = this._applyTransform(
  69710. endsIndex === 0 ? 'bottom' : 'top',
  69711. barGroup
  69712. );
  69713. var orient = this._orient;
  69714. var textStyleModel = this.visualMapModel.textStyleModel;
  69715. this.group.add(new Text({
  69716. style: {
  69717. x: position[0],
  69718. y: position[1],
  69719. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  69720. textAlign: orient === 'horizontal' ? align : 'center',
  69721. text: text,
  69722. textFont: textStyleModel.getFont(),
  69723. textFill: textStyleModel.getTextColor()
  69724. }
  69725. }));
  69726. },
  69727. /**
  69728. * @private
  69729. */
  69730. _renderBar: function (targetGroup) {
  69731. var visualMapModel = this.visualMapModel;
  69732. var shapes = this._shapes;
  69733. var itemSize = visualMapModel.itemSize;
  69734. var orient = this._orient;
  69735. var useHandle = this._useHandle;
  69736. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  69737. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  69738. // Bar
  69739. barGroup.add(shapes.outOfRange = createPolygon());
  69740. barGroup.add(shapes.inRange = createPolygon(
  69741. null,
  69742. useHandle ? getCursor$1(this._orient) : null,
  69743. bind(this._dragHandle, this, 'all', false),
  69744. bind(this._dragHandle, this, 'all', true)
  69745. ));
  69746. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  69747. var textSize = mathMax$7(textRect.width, textRect.height);
  69748. // Handle
  69749. if (useHandle) {
  69750. shapes.handleThumbs = [];
  69751. shapes.handleLabels = [];
  69752. shapes.handleLabelPoints = [];
  69753. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  69754. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  69755. }
  69756. this._createIndicator(barGroup, itemSize, textSize, orient);
  69757. targetGroup.add(barGroup);
  69758. },
  69759. /**
  69760. * @private
  69761. */
  69762. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  69763. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  69764. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  69765. var handleThumb = createPolygon(
  69766. createHandlePoints(handleIndex, textSize),
  69767. getCursor$1(this._orient),
  69768. onDrift,
  69769. onDragEnd
  69770. );
  69771. handleThumb.position[0] = itemSize[0];
  69772. barGroup.add(handleThumb);
  69773. // Text is always horizontal layout but should not be effected by
  69774. // transform (orient/inverse). So label is built separately but not
  69775. // use zrender/graphic/helper/RectText, and is located based on view
  69776. // group (according to handleLabelPoint) but not barGroup.
  69777. var textStyleModel = this.visualMapModel.textStyleModel;
  69778. var handleLabel = new Text({
  69779. draggable: true,
  69780. drift: onDrift,
  69781. onmousemove: function (e) {
  69782. // Fot mobile devicem, prevent screen slider on the button.
  69783. stop(e.event);
  69784. },
  69785. ondragend: onDragEnd,
  69786. style: {
  69787. x: 0, y: 0, text: '',
  69788. textFont: textStyleModel.getFont(),
  69789. textFill: textStyleModel.getTextColor()
  69790. }
  69791. });
  69792. this.group.add(handleLabel);
  69793. var handleLabelPoint = [
  69794. orient === 'horizontal'
  69795. ? textSize / 2
  69796. : textSize * 1.5,
  69797. orient === 'horizontal'
  69798. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  69799. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  69800. ];
  69801. var shapes = this._shapes;
  69802. shapes.handleThumbs[handleIndex] = handleThumb;
  69803. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  69804. shapes.handleLabels[handleIndex] = handleLabel;
  69805. },
  69806. /**
  69807. * @private
  69808. */
  69809. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  69810. var indicator = createPolygon([[0, 0]], 'move');
  69811. indicator.position[0] = itemSize[0];
  69812. indicator.attr({invisible: true, silent: true});
  69813. barGroup.add(indicator);
  69814. var textStyleModel = this.visualMapModel.textStyleModel;
  69815. var indicatorLabel = new Text({
  69816. silent: true,
  69817. invisible: true,
  69818. style: {
  69819. x: 0, y: 0, text: '',
  69820. textFont: textStyleModel.getFont(),
  69821. textFill: textStyleModel.getTextColor()
  69822. }
  69823. });
  69824. this.group.add(indicatorLabel);
  69825. var indicatorLabelPoint = [
  69826. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  69827. 0
  69828. ];
  69829. var shapes = this._shapes;
  69830. shapes.indicator = indicator;
  69831. shapes.indicatorLabel = indicatorLabel;
  69832. shapes.indicatorLabelPoint = indicatorLabelPoint;
  69833. },
  69834. /**
  69835. * @private
  69836. */
  69837. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  69838. if (!this._useHandle) {
  69839. return;
  69840. }
  69841. this._dragging = !isEnd;
  69842. if (!isEnd) {
  69843. // Transform dx, dy to bar coordination.
  69844. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  69845. this._updateInterval(handleIndex, vertex[1]);
  69846. // Considering realtime, update view should be executed
  69847. // before dispatch action.
  69848. this._updateView();
  69849. }
  69850. // dragEnd do not dispatch action when realtime.
  69851. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  69852. this.api.dispatchAction({
  69853. type: 'selectDataRange',
  69854. from: this.uid,
  69855. visualMapId: this.visualMapModel.id,
  69856. selected: this._dataInterval.slice()
  69857. });
  69858. }
  69859. if (isEnd) {
  69860. !this._hovering && this._clearHoverLinkToSeries();
  69861. }
  69862. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  69863. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  69864. }
  69865. },
  69866. /**
  69867. * @private
  69868. */
  69869. _resetInterval: function () {
  69870. var visualMapModel = this.visualMapModel;
  69871. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  69872. var dataExtent = visualMapModel.getExtent();
  69873. var sizeExtent = [0, visualMapModel.itemSize[1]];
  69874. this._handleEnds = [
  69875. linearMap$3(dataInterval[0], dataExtent, sizeExtent, true),
  69876. linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)
  69877. ];
  69878. },
  69879. /**
  69880. * @private
  69881. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  69882. * @param {number} dx
  69883. * @param {number} dy
  69884. */
  69885. _updateInterval: function (handleIndex, delta) {
  69886. delta = delta || 0;
  69887. var visualMapModel = this.visualMapModel;
  69888. var handleEnds = this._handleEnds;
  69889. var sizeExtent = [0, visualMapModel.itemSize[1]];
  69890. sliderMove(
  69891. delta,
  69892. handleEnds,
  69893. sizeExtent,
  69894. handleIndex,
  69895. // cross is forbiden
  69896. 0
  69897. );
  69898. var dataExtent = visualMapModel.getExtent();
  69899. // Update data interval.
  69900. this._dataInterval = [
  69901. linearMap$3(handleEnds[0], sizeExtent, dataExtent, true),
  69902. linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)
  69903. ];
  69904. },
  69905. /**
  69906. * @private
  69907. */
  69908. _updateView: function (forSketch) {
  69909. var visualMapModel = this.visualMapModel;
  69910. var dataExtent = visualMapModel.getExtent();
  69911. var shapes = this._shapes;
  69912. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  69913. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  69914. var visualInRange = this._createBarVisual(
  69915. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  69916. );
  69917. var visualOutOfRange = this._createBarVisual(
  69918. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  69919. );
  69920. shapes.inRange
  69921. .setStyle({
  69922. fill: visualInRange.barColor,
  69923. opacity: visualInRange.opacity
  69924. })
  69925. .setShape('points', visualInRange.barPoints);
  69926. shapes.outOfRange
  69927. .setStyle({
  69928. fill: visualOutOfRange.barColor,
  69929. opacity: visualOutOfRange.opacity
  69930. })
  69931. .setShape('points', visualOutOfRange.barPoints);
  69932. this._updateHandle(inRangeHandleEnds, visualInRange);
  69933. },
  69934. /**
  69935. * @private
  69936. */
  69937. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  69938. var opts = {
  69939. forceState: forceState,
  69940. convertOpacityToAlpha: true
  69941. };
  69942. var colorStops = this._makeColorGradient(dataInterval, opts);
  69943. var symbolSizes = [
  69944. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  69945. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  69946. ];
  69947. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  69948. return {
  69949. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  69950. barPoints: barPoints,
  69951. handlesColor: [
  69952. colorStops[0].color,
  69953. colorStops[colorStops.length - 1].color
  69954. ]
  69955. };
  69956. },
  69957. /**
  69958. * @private
  69959. */
  69960. _makeColorGradient: function (dataInterval, opts) {
  69961. // Considering colorHue, which is not linear, so we have to sample
  69962. // to calculate gradient color stops, but not only caculate head
  69963. // and tail.
  69964. var sampleNumber = 100; // Arbitrary value.
  69965. var colorStops = [];
  69966. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  69967. colorStops.push({
  69968. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  69969. offset: 0
  69970. });
  69971. for (var i = 1; i < sampleNumber; i++) {
  69972. var currValue = dataInterval[0] + step * i;
  69973. if (currValue > dataInterval[1]) {
  69974. break;
  69975. }
  69976. colorStops.push({
  69977. color: this.getControllerVisual(currValue, 'color', opts),
  69978. offset: i / sampleNumber
  69979. });
  69980. }
  69981. colorStops.push({
  69982. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  69983. offset: 1
  69984. });
  69985. return colorStops;
  69986. },
  69987. /**
  69988. * @private
  69989. */
  69990. _createBarPoints: function (handleEnds, symbolSizes) {
  69991. var itemSize = this.visualMapModel.itemSize;
  69992. return [
  69993. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  69994. [itemSize[0], handleEnds[0]],
  69995. [itemSize[0], handleEnds[1]],
  69996. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  69997. ];
  69998. },
  69999. /**
  70000. * @private
  70001. */
  70002. _createBarGroup: function (itemAlign) {
  70003. var orient = this._orient;
  70004. var inverse = this.visualMapModel.get('inverse');
  70005. return new Group(
  70006. (orient === 'horizontal' && !inverse)
  70007. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  70008. : (orient === 'horizontal' && inverse)
  70009. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  70010. : (orient === 'vertical' && !inverse)
  70011. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  70012. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  70013. );
  70014. },
  70015. /**
  70016. * @private
  70017. */
  70018. _updateHandle: function (handleEnds, visualInRange) {
  70019. if (!this._useHandle) {
  70020. return;
  70021. }
  70022. var shapes = this._shapes;
  70023. var visualMapModel = this.visualMapModel;
  70024. var handleThumbs = shapes.handleThumbs;
  70025. var handleLabels = shapes.handleLabels;
  70026. each$26([0, 1], function (handleIndex) {
  70027. var handleThumb = handleThumbs[handleIndex];
  70028. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  70029. handleThumb.position[1] = handleEnds[handleIndex];
  70030. // Update handle label position.
  70031. var textPoint = applyTransform$1(
  70032. shapes.handleLabelPoints[handleIndex],
  70033. getTransform(handleThumb, this.group)
  70034. );
  70035. handleLabels[handleIndex].setStyle({
  70036. x: textPoint[0],
  70037. y: textPoint[1],
  70038. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  70039. textVerticalAlign: 'middle',
  70040. textAlign: this._applyTransform(
  70041. this._orient === 'horizontal'
  70042. ? (handleIndex === 0 ? 'bottom' : 'top')
  70043. : 'left',
  70044. shapes.barGroup
  70045. )
  70046. });
  70047. }, this);
  70048. },
  70049. /**
  70050. * @private
  70051. * @param {number} cursorValue
  70052. * @param {number} textValue
  70053. * @param {string} [rangeSymbol]
  70054. * @param {number} [halfHoverLinkSize]
  70055. */
  70056. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  70057. var visualMapModel = this.visualMapModel;
  70058. var dataExtent = visualMapModel.getExtent();
  70059. var itemSize = visualMapModel.itemSize;
  70060. var sizeExtent = [0, itemSize[1]];
  70061. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  70062. var shapes = this._shapes;
  70063. var indicator = shapes.indicator;
  70064. if (!indicator) {
  70065. return;
  70066. }
  70067. indicator.position[1] = pos;
  70068. indicator.attr('invisible', false);
  70069. indicator.setShape('points', createIndicatorPoints(
  70070. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  70071. ));
  70072. var opts = {convertOpacityToAlpha: true};
  70073. var color = this.getControllerVisual(cursorValue, 'color', opts);
  70074. indicator.setStyle('fill', color);
  70075. // Update handle label position.
  70076. var textPoint = applyTransform$1(
  70077. shapes.indicatorLabelPoint,
  70078. getTransform(indicator, this.group)
  70079. );
  70080. var indicatorLabel = shapes.indicatorLabel;
  70081. indicatorLabel.attr('invisible', false);
  70082. var align = this._applyTransform('left', shapes.barGroup);
  70083. var orient = this._orient;
  70084. indicatorLabel.setStyle({
  70085. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  70086. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  70087. textAlign: orient === 'horizontal' ? 'center' : align,
  70088. x: textPoint[0],
  70089. y: textPoint[1]
  70090. });
  70091. },
  70092. /**
  70093. * @private
  70094. */
  70095. _enableHoverLinkToSeries: function () {
  70096. var self = this;
  70097. this._shapes.barGroup
  70098. .on('mousemove', function (e) {
  70099. self._hovering = true;
  70100. if (!self._dragging) {
  70101. var itemSize = self.visualMapModel.itemSize;
  70102. var pos = self._applyTransform(
  70103. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  70104. );
  70105. // For hover link show when hover handle, which might be
  70106. // below or upper than sizeExtent.
  70107. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  70108. self._doHoverLinkToSeries(
  70109. pos[1],
  70110. 0 <= pos[0] && pos[0] <= itemSize[0]
  70111. );
  70112. }
  70113. })
  70114. .on('mouseout', function () {
  70115. // When mouse is out of handle, hoverLink still need
  70116. // to be displayed when realtime is set as false.
  70117. self._hovering = false;
  70118. !self._dragging && self._clearHoverLinkToSeries();
  70119. });
  70120. },
  70121. /**
  70122. * @private
  70123. */
  70124. _enableHoverLinkFromSeries: function () {
  70125. var zr = this.api.getZr();
  70126. if (this.visualMapModel.option.hoverLink) {
  70127. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  70128. zr.on('mouseout', this._hideIndicator, this);
  70129. }
  70130. else {
  70131. this._clearHoverLinkFromSeries();
  70132. }
  70133. },
  70134. /**
  70135. * @private
  70136. */
  70137. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  70138. var visualMapModel = this.visualMapModel;
  70139. var itemSize = visualMapModel.itemSize;
  70140. if (!visualMapModel.option.hoverLink) {
  70141. return;
  70142. }
  70143. var sizeExtent = [0, itemSize[1]];
  70144. var dataExtent = visualMapModel.getExtent();
  70145. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  70146. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  70147. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  70148. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  70149. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  70150. var valueRange = [
  70151. linearMap$3(hoverRange[0], sizeExtent, dataExtent, true),
  70152. linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)
  70153. ];
  70154. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  70155. // where china and india has very large population.
  70156. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  70157. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  70158. // Do not show indicator when mouse is over handle,
  70159. // otherwise labels overlap, especially when dragging.
  70160. if (hoverOnBar) {
  70161. if (valueRange[0] === -Infinity) {
  70162. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  70163. }
  70164. else if (valueRange[1] === Infinity) {
  70165. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  70166. }
  70167. else {
  70168. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  70169. }
  70170. }
  70171. // When realtime is set as false, handles, which are in barGroup,
  70172. // also trigger hoverLink, which help user to realize where they
  70173. // focus on when dragging. (see test/heatmap-large.html)
  70174. // When realtime is set as true, highlight will not show when hover
  70175. // handle, because the label on handle, which displays a exact value
  70176. // but not range, might mislead users.
  70177. var oldBatch = this._hoverLinkDataIndices;
  70178. var newBatch = [];
  70179. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  70180. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  70181. }
  70182. var resultBatches = compressBatches(oldBatch, newBatch);
  70183. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  70184. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  70185. },
  70186. /**
  70187. * @private
  70188. */
  70189. _hoverLinkFromSeriesMouseOver: function (e) {
  70190. var el = e.target;
  70191. var visualMapModel = this.visualMapModel;
  70192. if (!el || el.dataIndex == null) {
  70193. return;
  70194. }
  70195. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  70196. if (!visualMapModel.isTargetSeries(dataModel)) {
  70197. return;
  70198. }
  70199. var data = dataModel.getData(el.dataType);
  70200. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  70201. if (!isNaN(value)) {
  70202. this._showIndicator(value, value);
  70203. }
  70204. },
  70205. /**
  70206. * @private
  70207. */
  70208. _hideIndicator: function () {
  70209. var shapes = this._shapes;
  70210. shapes.indicator && shapes.indicator.attr('invisible', true);
  70211. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  70212. },
  70213. /**
  70214. * @private
  70215. */
  70216. _clearHoverLinkToSeries: function () {
  70217. this._hideIndicator();
  70218. var indices = this._hoverLinkDataIndices;
  70219. this._dispatchHighDown('downplay', convertDataIndex(indices));
  70220. indices.length = 0;
  70221. },
  70222. /**
  70223. * @private
  70224. */
  70225. _clearHoverLinkFromSeries: function () {
  70226. this._hideIndicator();
  70227. var zr = this.api.getZr();
  70228. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  70229. zr.off('mouseout', this._hideIndicator);
  70230. },
  70231. /**
  70232. * @private
  70233. */
  70234. _applyTransform: function (vertex, element, inverse, global) {
  70235. var transform = getTransform(element, global ? null : this.group);
  70236. return graphic[
  70237. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  70238. ](vertex, transform, inverse);
  70239. },
  70240. /**
  70241. * @private
  70242. */
  70243. _dispatchHighDown: function (type, batch) {
  70244. batch && batch.length && this.api.dispatchAction({
  70245. type: type,
  70246. batch: batch
  70247. });
  70248. },
  70249. /**
  70250. * @override
  70251. */
  70252. dispose: function () {
  70253. this._clearHoverLinkFromSeries();
  70254. this._clearHoverLinkToSeries();
  70255. },
  70256. /**
  70257. * @override
  70258. */
  70259. remove: function () {
  70260. this._clearHoverLinkFromSeries();
  70261. this._clearHoverLinkToSeries();
  70262. }
  70263. });
  70264. function createPolygon(points, cursor, onDrift, onDragEnd) {
  70265. return new Polygon({
  70266. shape: {points: points},
  70267. draggable: !!onDrift,
  70268. cursor: cursor,
  70269. drift: onDrift,
  70270. onmousemove: function (e) {
  70271. // Fot mobile devicem, prevent screen slider on the button.
  70272. stop(e.event);
  70273. },
  70274. ondragend: onDragEnd
  70275. });
  70276. }
  70277. function createHandlePoints(handleIndex, textSize) {
  70278. return handleIndex === 0
  70279. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  70280. : [[0, 0], [textSize, 0], [textSize, textSize]];
  70281. }
  70282. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  70283. return isRange
  70284. ? [ // indicate range
  70285. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  70286. [HOVER_LINK_OUT, 0],
  70287. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  70288. ]
  70289. : [ // indicate single value
  70290. [0, 0], [5, -5], [5, 5]
  70291. ];
  70292. }
  70293. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  70294. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  70295. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  70296. if (hoverLinkDataSize) {
  70297. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  70298. }
  70299. return halfHoverLinkSize;
  70300. }
  70301. function useHoverLinkOnHandle(visualMapModel) {
  70302. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  70303. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  70304. }
  70305. function getCursor$1(orient) {
  70306. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  70307. }
  70308. /*
  70309. * Licensed to the Apache Software Foundation (ASF) under one
  70310. * or more contributor license agreements. See the NOTICE file
  70311. * distributed with this work for additional information
  70312. * regarding copyright ownership. The ASF licenses this file
  70313. * to you under the Apache License, Version 2.0 (the
  70314. * "License"); you may not use this file except in compliance
  70315. * with the License. You may obtain a copy of the License at
  70316. *
  70317. * http://www.apache.org/licenses/LICENSE-2.0
  70318. *
  70319. * Unless required by applicable law or agreed to in writing,
  70320. * software distributed under the License is distributed on an
  70321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70322. * KIND, either express or implied. See the License for the
  70323. * specific language governing permissions and limitations
  70324. * under the License.
  70325. */
  70326. var actionInfo$2 = {
  70327. type: 'selectDataRange',
  70328. event: 'dataRangeSelected',
  70329. // FIXME use updateView appears wrong
  70330. update: 'update'
  70331. };
  70332. registerAction(actionInfo$2, function (payload, ecModel) {
  70333. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  70334. model.setSelected(payload.selected);
  70335. });
  70336. });
  70337. /*
  70338. * Licensed to the Apache Software Foundation (ASF) under one
  70339. * or more contributor license agreements. See the NOTICE file
  70340. * distributed with this work for additional information
  70341. * regarding copyright ownership. The ASF licenses this file
  70342. * to you under the Apache License, Version 2.0 (the
  70343. * "License"); you may not use this file except in compliance
  70344. * with the License. You may obtain a copy of the License at
  70345. *
  70346. * http://www.apache.org/licenses/LICENSE-2.0
  70347. *
  70348. * Unless required by applicable law or agreed to in writing,
  70349. * software distributed under the License is distributed on an
  70350. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70351. * KIND, either express or implied. See the License for the
  70352. * specific language governing permissions and limitations
  70353. * under the License.
  70354. */
  70355. /**
  70356. * DataZoom component entry
  70357. */
  70358. registerPreprocessor(preprocessor$2);
  70359. /*
  70360. * Licensed to the Apache Software Foundation (ASF) under one
  70361. * or more contributor license agreements. See the NOTICE file
  70362. * distributed with this work for additional information
  70363. * regarding copyright ownership. The ASF licenses this file
  70364. * to you under the Apache License, Version 2.0 (the
  70365. * "License"); you may not use this file except in compliance
  70366. * with the License. You may obtain a copy of the License at
  70367. *
  70368. * http://www.apache.org/licenses/LICENSE-2.0
  70369. *
  70370. * Unless required by applicable law or agreed to in writing,
  70371. * software distributed under the License is distributed on an
  70372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70373. * KIND, either express or implied. See the License for the
  70374. * specific language governing permissions and limitations
  70375. * under the License.
  70376. */
  70377. var PiecewiseModel = VisualMapModel.extend({
  70378. type: 'visualMap.piecewise',
  70379. /**
  70380. * Order Rule:
  70381. *
  70382. * option.categories / option.pieces / option.text / option.selected:
  70383. * If !option.inverse,
  70384. * Order when vertical: ['top', ..., 'bottom'].
  70385. * Order when horizontal: ['left', ..., 'right'].
  70386. * If option.inverse, the meaning of
  70387. * the order should be reversed.
  70388. *
  70389. * this._pieceList:
  70390. * The order is always [low, ..., high].
  70391. *
  70392. * Mapping from location to low-high:
  70393. * If !option.inverse
  70394. * When vertical, top is high.
  70395. * When horizontal, right is high.
  70396. * If option.inverse, reverse.
  70397. */
  70398. /**
  70399. * @protected
  70400. */
  70401. defaultOption: {
  70402. selected: null, // Object. If not specified, means selected.
  70403. // When pieces and splitNumber: {'0': true, '5': true}
  70404. // When categories: {'cate1': false, 'cate3': true}
  70405. // When selected === false, means all unselected.
  70406. minOpen: false, // Whether include values that smaller than `min`.
  70407. maxOpen: false, // Whether include values that bigger than `max`.
  70408. align: 'auto', // 'auto', 'left', 'right'
  70409. itemWidth: 20, // When put the controller vertically, it is the length of
  70410. // horizontal side of each item. Otherwise, vertical side.
  70411. itemHeight: 14, // When put the controller vertically, it is the length of
  70412. // vertical side of each item. Otherwise, horizontal side.
  70413. itemSymbol: 'roundRect',
  70414. pieceList: null, // Each item is Object, with some of those attrs:
  70415. // {min, max, lt, gt, lte, gte, value,
  70416. // color, colorSaturation, colorAlpha, opacity,
  70417. // symbol, symbolSize}, which customize the range or visual
  70418. // coding of the certain piece. Besides, see "Order Rule".
  70419. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  70420. // Attr min/max are ignored when categories set. See "Order Rule"
  70421. splitNumber: 5, // If set to 5, auto split five pieces equally.
  70422. // If set to 0 and component type not set, component type will be
  70423. // determined as "continuous". (It is less reasonable but for ec2
  70424. // compatibility, see echarts/component/visualMap/typeDefaulter)
  70425. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  70426. itemGap: 10, // The gap between two items, in px.
  70427. hoverLink: true, // Enable hover highlight.
  70428. showLabel: null // By default, when text is used, label will hide (the logic
  70429. // is remained for compatibility reason)
  70430. },
  70431. /**
  70432. * @override
  70433. */
  70434. optionUpdated: function (newOption, isInit) {
  70435. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  70436. /**
  70437. * The order is always [low, ..., high].
  70438. * [{text: string, interval: Array.<number>}, ...]
  70439. * @private
  70440. * @type {Array.<Object>}
  70441. */
  70442. this._pieceList = [];
  70443. this.resetExtent();
  70444. /**
  70445. * 'pieces', 'categories', 'splitNumber'
  70446. * @type {string}
  70447. */
  70448. var mode = this._mode = this._determineMode();
  70449. resetMethods[this._mode].call(this);
  70450. this._resetSelected(newOption, isInit);
  70451. var categories = this.option.categories;
  70452. this.resetVisual(function (mappingOption, state) {
  70453. if (mode === 'categories') {
  70454. mappingOption.mappingMethod = 'category';
  70455. mappingOption.categories = clone(categories);
  70456. }
  70457. else {
  70458. mappingOption.dataExtent = this.getExtent();
  70459. mappingOption.mappingMethod = 'piecewise';
  70460. mappingOption.pieceList = map(this._pieceList, function (piece) {
  70461. var piece = clone(piece);
  70462. if (state !== 'inRange') {
  70463. // FIXME
  70464. // outOfRange do not support special visual in pieces.
  70465. piece.visual = null;
  70466. }
  70467. return piece;
  70468. });
  70469. }
  70470. });
  70471. },
  70472. /**
  70473. * @protected
  70474. * @override
  70475. */
  70476. completeVisualOption: function () {
  70477. // Consider this case:
  70478. // visualMap: {
  70479. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  70480. // }
  70481. // where no inRange/outOfRange set but only pieces. So we should make
  70482. // default inRange/outOfRange for this case, otherwise visuals that only
  70483. // appear in `pieces` will not be taken into account in visual encoding.
  70484. var option = this.option;
  70485. var visualTypesInPieces = {};
  70486. var visualTypes = VisualMapping.listVisualTypes();
  70487. var isCategory = this.isCategory();
  70488. each$1(option.pieces, function (piece) {
  70489. each$1(visualTypes, function (visualType) {
  70490. if (piece.hasOwnProperty(visualType)) {
  70491. visualTypesInPieces[visualType] = 1;
  70492. }
  70493. });
  70494. });
  70495. each$1(visualTypesInPieces, function (v, visualType) {
  70496. var exists = 0;
  70497. each$1(this.stateList, function (state) {
  70498. exists |= has(option, state, visualType)
  70499. || has(option.target, state, visualType);
  70500. }, this);
  70501. !exists && each$1(this.stateList, function (state) {
  70502. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  70503. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  70504. );
  70505. });
  70506. }, this);
  70507. function has(obj, state, visualType) {
  70508. return obj && obj[state] && (
  70509. isObject$1(obj[state])
  70510. ? obj[state].hasOwnProperty(visualType)
  70511. : obj[state] === visualType // e.g., inRange: 'symbol'
  70512. );
  70513. }
  70514. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  70515. },
  70516. _resetSelected: function (newOption, isInit) {
  70517. var thisOption = this.option;
  70518. var pieceList = this._pieceList;
  70519. // Selected do not merge but all override.
  70520. var selected = (isInit ? thisOption : newOption).selected || {};
  70521. thisOption.selected = selected;
  70522. // Consider 'not specified' means true.
  70523. each$1(pieceList, function (piece, index) {
  70524. var key = this.getSelectedMapKey(piece);
  70525. if (!selected.hasOwnProperty(key)) {
  70526. selected[key] = true;
  70527. }
  70528. }, this);
  70529. if (thisOption.selectedMode === 'single') {
  70530. // Ensure there is only one selected.
  70531. var hasSel = false;
  70532. each$1(pieceList, function (piece, index) {
  70533. var key = this.getSelectedMapKey(piece);
  70534. if (selected[key]) {
  70535. hasSel
  70536. ? (selected[key] = false)
  70537. : (hasSel = true);
  70538. }
  70539. }, this);
  70540. }
  70541. // thisOption.selectedMode === 'multiple', default: all selected.
  70542. },
  70543. /**
  70544. * @public
  70545. */
  70546. getSelectedMapKey: function (piece) {
  70547. return this._mode === 'categories'
  70548. ? piece.value + '' : piece.index + '';
  70549. },
  70550. /**
  70551. * @public
  70552. */
  70553. getPieceList: function () {
  70554. return this._pieceList;
  70555. },
  70556. /**
  70557. * @private
  70558. * @return {string}
  70559. */
  70560. _determineMode: function () {
  70561. var option = this.option;
  70562. return option.pieces && option.pieces.length > 0
  70563. ? 'pieces'
  70564. : this.option.categories
  70565. ? 'categories'
  70566. : 'splitNumber';
  70567. },
  70568. /**
  70569. * @public
  70570. * @override
  70571. */
  70572. setSelected: function (selected) {
  70573. this.option.selected = clone(selected);
  70574. },
  70575. /**
  70576. * @public
  70577. * @override
  70578. */
  70579. getValueState: function (value) {
  70580. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  70581. return index != null
  70582. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  70583. ? 'inRange' : 'outOfRange'
  70584. )
  70585. : 'outOfRange';
  70586. },
  70587. /**
  70588. * @public
  70589. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  70590. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  70591. */
  70592. findTargetDataIndices: function (pieceIndex) {
  70593. var result = [];
  70594. this.eachTargetSeries(function (seriesModel) {
  70595. var dataIndices = [];
  70596. var data = seriesModel.getData();
  70597. data.each(this.getDataDimension(data), function (value, dataIndex) {
  70598. // Should always base on model pieceList, because it is order sensitive.
  70599. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  70600. pIdx === pieceIndex && dataIndices.push(dataIndex);
  70601. }, this);
  70602. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  70603. }, this);
  70604. return result;
  70605. },
  70606. /**
  70607. * @private
  70608. * @param {Object} piece piece.value or piece.interval is required.
  70609. * @return {number} Can be Infinity or -Infinity
  70610. */
  70611. getRepresentValue: function (piece) {
  70612. var representValue;
  70613. if (this.isCategory()) {
  70614. representValue = piece.value;
  70615. }
  70616. else {
  70617. if (piece.value != null) {
  70618. representValue = piece.value;
  70619. }
  70620. else {
  70621. var pieceInterval = piece.interval || [];
  70622. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  70623. ? 0
  70624. : (pieceInterval[0] + pieceInterval[1]) / 2;
  70625. }
  70626. }
  70627. return representValue;
  70628. },
  70629. getVisualMeta: function (getColorVisual) {
  70630. // Do not support category. (category axis is ordinal, numerical)
  70631. if (this.isCategory()) {
  70632. return;
  70633. }
  70634. var stops = [];
  70635. var outerColors = [];
  70636. var visualMapModel = this;
  70637. function setStop(interval, valueState) {
  70638. var representValue = visualMapModel.getRepresentValue({interval: interval});
  70639. if (!valueState) {
  70640. valueState = visualMapModel.getValueState(representValue);
  70641. }
  70642. var color = getColorVisual(representValue, valueState);
  70643. if (interval[0] === -Infinity) {
  70644. outerColors[0] = color;
  70645. }
  70646. else if (interval[1] === Infinity) {
  70647. outerColors[1] = color;
  70648. }
  70649. else {
  70650. stops.push(
  70651. {value: interval[0], color: color},
  70652. {value: interval[1], color: color}
  70653. );
  70654. }
  70655. }
  70656. // Suplement
  70657. var pieceList = this._pieceList.slice();
  70658. if (!pieceList.length) {
  70659. pieceList.push({interval: [-Infinity, Infinity]});
  70660. }
  70661. else {
  70662. var edge = pieceList[0].interval[0];
  70663. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  70664. edge = pieceList[pieceList.length - 1].interval[1];
  70665. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  70666. }
  70667. var curr = -Infinity;
  70668. each$1(pieceList, function (piece) {
  70669. var interval = piece.interval;
  70670. if (interval) {
  70671. // Fulfill gap.
  70672. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  70673. setStop(interval.slice());
  70674. curr = interval[1];
  70675. }
  70676. }, this);
  70677. return {stops: stops, outerColors: outerColors};
  70678. }
  70679. });
  70680. /**
  70681. * Key is this._mode
  70682. * @type {Object}
  70683. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  70684. */
  70685. var resetMethods = {
  70686. splitNumber: function () {
  70687. var thisOption = this.option;
  70688. var pieceList = this._pieceList;
  70689. var precision = Math.min(thisOption.precision, 20);
  70690. var dataExtent = this.getExtent();
  70691. var splitNumber = thisOption.splitNumber;
  70692. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  70693. thisOption.splitNumber = splitNumber;
  70694. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  70695. // Precision auto-adaption
  70696. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  70697. precision++;
  70698. }
  70699. thisOption.precision = precision;
  70700. splitStep = +splitStep.toFixed(precision);
  70701. var index = 0;
  70702. if (thisOption.minOpen) {
  70703. pieceList.push({
  70704. index: index++,
  70705. interval: [-Infinity, dataExtent[0]],
  70706. close: [0, 0]
  70707. });
  70708. }
  70709. for (
  70710. var curr = dataExtent[0], len = index + splitNumber;
  70711. index < len;
  70712. curr += splitStep
  70713. ) {
  70714. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  70715. pieceList.push({
  70716. index: index++,
  70717. interval: [curr, max],
  70718. close: [1, 1]
  70719. });
  70720. }
  70721. if (thisOption.maxOpen) {
  70722. pieceList.push({
  70723. index: index++,
  70724. interval: [dataExtent[1], Infinity],
  70725. close: [0, 0]
  70726. });
  70727. }
  70728. reformIntervals(pieceList);
  70729. each$1(pieceList, function (piece) {
  70730. piece.text = this.formatValueText(piece.interval);
  70731. }, this);
  70732. },
  70733. categories: function () {
  70734. var thisOption = this.option;
  70735. each$1(thisOption.categories, function (cate) {
  70736. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  70737. // 是否改一致。
  70738. this._pieceList.push({
  70739. text: this.formatValueText(cate, true),
  70740. value: cate
  70741. });
  70742. }, this);
  70743. // See "Order Rule".
  70744. normalizeReverse(thisOption, this._pieceList);
  70745. },
  70746. pieces: function () {
  70747. var thisOption = this.option;
  70748. var pieceList = this._pieceList;
  70749. each$1(thisOption.pieces, function (pieceListItem, index) {
  70750. if (!isObject$1(pieceListItem)) {
  70751. pieceListItem = {value: pieceListItem};
  70752. }
  70753. var item = {text: '', index: index};
  70754. if (pieceListItem.label != null) {
  70755. item.text = pieceListItem.label;
  70756. }
  70757. if (pieceListItem.hasOwnProperty('value')) {
  70758. var value = item.value = pieceListItem.value;
  70759. item.interval = [value, value];
  70760. item.close = [1, 1];
  70761. }
  70762. else {
  70763. // `min` `max` is legacy option.
  70764. // `lt` `gt` `lte` `gte` is recommanded.
  70765. var interval = item.interval = [];
  70766. var close = item.close = [0, 0];
  70767. var closeList = [1, 0, 1];
  70768. var infinityList = [-Infinity, Infinity];
  70769. var useMinMax = [];
  70770. for (var lg = 0; lg < 2; lg++) {
  70771. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  70772. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  70773. interval[lg] = pieceListItem[names[i]];
  70774. close[lg] = closeList[i];
  70775. useMinMax[lg] = i === 2;
  70776. }
  70777. interval[lg] == null && (interval[lg] = infinityList[lg]);
  70778. }
  70779. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  70780. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  70781. if (__DEV__) {
  70782. if (interval[0] > interval[1]) {
  70783. console.warn(
  70784. 'Piece ' + index + 'is illegal: ' + interval
  70785. + ' lower bound should not greater then uppper bound.'
  70786. );
  70787. }
  70788. }
  70789. if (interval[0] === interval[1] && close[0] && close[1]) {
  70790. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  70791. // we use value to lift the priority when min === max
  70792. item.value = interval[0];
  70793. }
  70794. }
  70795. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  70796. pieceList.push(item);
  70797. }, this);
  70798. // See "Order Rule".
  70799. normalizeReverse(thisOption, pieceList);
  70800. // Only pieces
  70801. reformIntervals(pieceList);
  70802. each$1(pieceList, function (piece) {
  70803. var close = piece.close;
  70804. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  70805. piece.text = piece.text || this.formatValueText(
  70806. piece.value != null ? piece.value : piece.interval,
  70807. false,
  70808. edgeSymbols
  70809. );
  70810. }, this);
  70811. }
  70812. };
  70813. function normalizeReverse(thisOption, pieceList) {
  70814. var inverse = thisOption.inverse;
  70815. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  70816. pieceList.reverse();
  70817. }
  70818. }
  70819. /*
  70820. * Licensed to the Apache Software Foundation (ASF) under one
  70821. * or more contributor license agreements. See the NOTICE file
  70822. * distributed with this work for additional information
  70823. * regarding copyright ownership. The ASF licenses this file
  70824. * to you under the Apache License, Version 2.0 (the
  70825. * "License"); you may not use this file except in compliance
  70826. * with the License. You may obtain a copy of the License at
  70827. *
  70828. * http://www.apache.org/licenses/LICENSE-2.0
  70829. *
  70830. * Unless required by applicable law or agreed to in writing,
  70831. * software distributed under the License is distributed on an
  70832. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70833. * KIND, either express or implied. See the License for the
  70834. * specific language governing permissions and limitations
  70835. * under the License.
  70836. */
  70837. var PiecewiseVisualMapView = VisualMapView.extend({
  70838. type: 'visualMap.piecewise',
  70839. /**
  70840. * @protected
  70841. * @override
  70842. */
  70843. doRender: function () {
  70844. var thisGroup = this.group;
  70845. thisGroup.removeAll();
  70846. var visualMapModel = this.visualMapModel;
  70847. var textGap = visualMapModel.get('textGap');
  70848. var textStyleModel = visualMapModel.textStyleModel;
  70849. var textFont = textStyleModel.getFont();
  70850. var textFill = textStyleModel.getTextColor();
  70851. var itemAlign = this._getItemAlign();
  70852. var itemSize = visualMapModel.itemSize;
  70853. var viewData = this._getViewData();
  70854. var endsText = viewData.endsText;
  70855. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  70856. endsText && this._renderEndsText(
  70857. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  70858. );
  70859. each$1(viewData.viewPieceList, renderItem, this);
  70860. endsText && this._renderEndsText(
  70861. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  70862. );
  70863. box(
  70864. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  70865. );
  70866. this.renderBackground(thisGroup);
  70867. this.positionGroup(thisGroup);
  70868. function renderItem(item) {
  70869. var piece = item.piece;
  70870. var itemGroup = new Group();
  70871. itemGroup.onclick = bind(this._onItemClick, this, piece);
  70872. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  70873. var representValue = visualMapModel.getRepresentValue(piece);
  70874. this._createItemSymbol(
  70875. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  70876. );
  70877. if (showLabel) {
  70878. var visualState = this.visualMapModel.getValueState(representValue);
  70879. itemGroup.add(new Text({
  70880. style: {
  70881. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  70882. y: itemSize[1] / 2,
  70883. text: piece.text,
  70884. textVerticalAlign: 'middle',
  70885. textAlign: itemAlign,
  70886. textFont: textFont,
  70887. textFill: textFill,
  70888. opacity: visualState === 'outOfRange' ? 0.5 : 1
  70889. }
  70890. }));
  70891. }
  70892. thisGroup.add(itemGroup);
  70893. }
  70894. },
  70895. /**
  70896. * @private
  70897. */
  70898. _enableHoverLink: function (itemGroup, pieceIndex) {
  70899. itemGroup
  70900. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  70901. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  70902. function onHoverLink(method) {
  70903. var visualMapModel = this.visualMapModel;
  70904. visualMapModel.option.hoverLink && this.api.dispatchAction({
  70905. type: method,
  70906. batch: convertDataIndex(
  70907. visualMapModel.findTargetDataIndices(pieceIndex)
  70908. )
  70909. });
  70910. }
  70911. },
  70912. /**
  70913. * @private
  70914. */
  70915. _getItemAlign: function () {
  70916. var visualMapModel = this.visualMapModel;
  70917. var modelOption = visualMapModel.option;
  70918. if (modelOption.orient === 'vertical') {
  70919. return getItemAlign(
  70920. visualMapModel, this.api, visualMapModel.itemSize
  70921. );
  70922. }
  70923. else { // horizontal, most case left unless specifying right.
  70924. var align = modelOption.align;
  70925. if (!align || align === 'auto') {
  70926. align = 'left';
  70927. }
  70928. return align;
  70929. }
  70930. },
  70931. /**
  70932. * @private
  70933. */
  70934. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  70935. if (!text) {
  70936. return;
  70937. }
  70938. var itemGroup = new Group();
  70939. var textStyleModel = this.visualMapModel.textStyleModel;
  70940. itemGroup.add(new Text({
  70941. style: {
  70942. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  70943. y: itemSize[1] / 2,
  70944. textVerticalAlign: 'middle',
  70945. textAlign: showLabel ? itemAlign : 'center',
  70946. text: text,
  70947. textFont: textStyleModel.getFont(),
  70948. textFill: textStyleModel.getTextColor()
  70949. }
  70950. }));
  70951. group.add(itemGroup);
  70952. },
  70953. /**
  70954. * @private
  70955. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  70956. */
  70957. _getViewData: function () {
  70958. var visualMapModel = this.visualMapModel;
  70959. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  70960. return {piece: piece, indexInModelPieceList: index};
  70961. });
  70962. var endsText = visualMapModel.get('text');
  70963. // Consider orient and inverse.
  70964. var orient = visualMapModel.get('orient');
  70965. var inverse = visualMapModel.get('inverse');
  70966. // Order of model pieceList is always [low, ..., high]
  70967. if (orient === 'horizontal' ? inverse : !inverse) {
  70968. viewPieceList.reverse();
  70969. }
  70970. // Origin order of endsText is [high, low]
  70971. else if (endsText) {
  70972. endsText = endsText.slice().reverse();
  70973. }
  70974. return {viewPieceList: viewPieceList, endsText: endsText};
  70975. },
  70976. /**
  70977. * @private
  70978. */
  70979. _createItemSymbol: function (group, representValue, shapeParam) {
  70980. group.add(createSymbol(
  70981. this.getControllerVisual(representValue, 'symbol'),
  70982. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  70983. this.getControllerVisual(representValue, 'color')
  70984. ));
  70985. },
  70986. /**
  70987. * @private
  70988. */
  70989. _onItemClick: function (piece) {
  70990. var visualMapModel = this.visualMapModel;
  70991. var option = visualMapModel.option;
  70992. var selected = clone(option.selected);
  70993. var newKey = visualMapModel.getSelectedMapKey(piece);
  70994. if (option.selectedMode === 'single') {
  70995. selected[newKey] = true;
  70996. each$1(selected, function (o, key) {
  70997. selected[key] = key === newKey;
  70998. });
  70999. }
  71000. else {
  71001. selected[newKey] = !selected[newKey];
  71002. }
  71003. this.api.dispatchAction({
  71004. type: 'selectDataRange',
  71005. from: this.uid,
  71006. visualMapId: this.visualMapModel.id,
  71007. selected: selected
  71008. });
  71009. }
  71010. });
  71011. /*
  71012. * Licensed to the Apache Software Foundation (ASF) under one
  71013. * or more contributor license agreements. See the NOTICE file
  71014. * distributed with this work for additional information
  71015. * regarding copyright ownership. The ASF licenses this file
  71016. * to you under the Apache License, Version 2.0 (the
  71017. * "License"); you may not use this file except in compliance
  71018. * with the License. You may obtain a copy of the License at
  71019. *
  71020. * http://www.apache.org/licenses/LICENSE-2.0
  71021. *
  71022. * Unless required by applicable law or agreed to in writing,
  71023. * software distributed under the License is distributed on an
  71024. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71025. * KIND, either express or implied. See the License for the
  71026. * specific language governing permissions and limitations
  71027. * under the License.
  71028. */
  71029. /**
  71030. * DataZoom component entry
  71031. */
  71032. registerPreprocessor(preprocessor$2);
  71033. /*
  71034. * Licensed to the Apache Software Foundation (ASF) under one
  71035. * or more contributor license agreements. See the NOTICE file
  71036. * distributed with this work for additional information
  71037. * regarding copyright ownership. The ASF licenses this file
  71038. * to you under the Apache License, Version 2.0 (the
  71039. * "License"); you may not use this file except in compliance
  71040. * with the License. You may obtain a copy of the License at
  71041. *
  71042. * http://www.apache.org/licenses/LICENSE-2.0
  71043. *
  71044. * Unless required by applicable law or agreed to in writing,
  71045. * software distributed under the License is distributed on an
  71046. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71047. * KIND, either express or implied. See the License for the
  71048. * specific language governing permissions and limitations
  71049. * under the License.
  71050. */
  71051. /**
  71052. * visualMap component entry
  71053. */
  71054. /*
  71055. * Licensed to the Apache Software Foundation (ASF) under one
  71056. * or more contributor license agreements. See the NOTICE file
  71057. * distributed with this work for additional information
  71058. * regarding copyright ownership. The ASF licenses this file
  71059. * to you under the Apache License, Version 2.0 (the
  71060. * "License"); you may not use this file except in compliance
  71061. * with the License. You may obtain a copy of the License at
  71062. *
  71063. * http://www.apache.org/licenses/LICENSE-2.0
  71064. *
  71065. * Unless required by applicable law or agreed to in writing,
  71066. * software distributed under the License is distributed on an
  71067. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71068. * KIND, either express or implied. See the License for the
  71069. * specific language governing permissions and limitations
  71070. * under the License.
  71071. */
  71072. var addCommas$1 = addCommas;
  71073. var encodeHTML$1 = encodeHTML;
  71074. function fillLabel(opt) {
  71075. defaultEmphasis(opt, 'label', ['show']);
  71076. }
  71077. var MarkerModel = extendComponentModel({
  71078. type: 'marker',
  71079. dependencies: ['series', 'grid', 'polar', 'geo'],
  71080. /**
  71081. * @overrite
  71082. */
  71083. init: function (option, parentModel, ecModel, extraOpt) {
  71084. if (__DEV__) {
  71085. if (this.type === 'marker') {
  71086. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  71087. }
  71088. }
  71089. this.mergeDefaultAndTheme(option, ecModel);
  71090. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  71091. },
  71092. /**
  71093. * @return {boolean}
  71094. */
  71095. isAnimationEnabled: function () {
  71096. if (env$1.node) {
  71097. return false;
  71098. }
  71099. var hostSeries = this.__hostSeries;
  71100. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  71101. },
  71102. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  71103. var MarkerModel = this.constructor;
  71104. var modelPropName = this.mainType + 'Model';
  71105. if (!createdBySelf) {
  71106. ecModel.eachSeries(function (seriesModel) {
  71107. var markerOpt = seriesModel.get(this.mainType, true);
  71108. var markerModel = seriesModel[modelPropName];
  71109. if (!markerOpt || !markerOpt.data) {
  71110. seriesModel[modelPropName] = null;
  71111. return;
  71112. }
  71113. if (!markerModel) {
  71114. if (isInit) {
  71115. // Default label emphasis `position` and `show`
  71116. fillLabel(markerOpt);
  71117. }
  71118. each$1(markerOpt.data, function (item) {
  71119. // FIXME Overwrite fillLabel method ?
  71120. if (item instanceof Array) {
  71121. fillLabel(item[0]);
  71122. fillLabel(item[1]);
  71123. }
  71124. else {
  71125. fillLabel(item);
  71126. }
  71127. });
  71128. markerModel = new MarkerModel(
  71129. markerOpt, this, ecModel
  71130. );
  71131. extend(markerModel, {
  71132. mainType: this.mainType,
  71133. // Use the same series index and name
  71134. seriesIndex: seriesModel.seriesIndex,
  71135. name: seriesModel.name,
  71136. createdBySelf: true
  71137. });
  71138. markerModel.__hostSeries = seriesModel;
  71139. }
  71140. else {
  71141. markerModel.mergeOption(markerOpt, ecModel, true);
  71142. }
  71143. seriesModel[modelPropName] = markerModel;
  71144. }, this);
  71145. }
  71146. },
  71147. formatTooltip: function (dataIndex) {
  71148. var data = this.getData();
  71149. var value = this.getRawValue(dataIndex);
  71150. var formattedValue = isArray(value)
  71151. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  71152. var name = data.getName(dataIndex);
  71153. var html = encodeHTML$1(this.name);
  71154. if (value != null || name) {
  71155. html += '<br />';
  71156. }
  71157. if (name) {
  71158. html += encodeHTML$1(name);
  71159. if (value != null) {
  71160. html += ' : ';
  71161. }
  71162. }
  71163. if (value != null) {
  71164. html += encodeHTML$1(formattedValue);
  71165. }
  71166. return html;
  71167. },
  71168. getData: function () {
  71169. return this._data;
  71170. },
  71171. setData: function (data) {
  71172. this._data = data;
  71173. }
  71174. });
  71175. mixin(MarkerModel, dataFormatMixin);
  71176. /*
  71177. * Licensed to the Apache Software Foundation (ASF) under one
  71178. * or more contributor license agreements. See the NOTICE file
  71179. * distributed with this work for additional information
  71180. * regarding copyright ownership. The ASF licenses this file
  71181. * to you under the Apache License, Version 2.0 (the
  71182. * "License"); you may not use this file except in compliance
  71183. * with the License. You may obtain a copy of the License at
  71184. *
  71185. * http://www.apache.org/licenses/LICENSE-2.0
  71186. *
  71187. * Unless required by applicable law or agreed to in writing,
  71188. * software distributed under the License is distributed on an
  71189. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71190. * KIND, either express or implied. See the License for the
  71191. * specific language governing permissions and limitations
  71192. * under the License.
  71193. */
  71194. MarkerModel.extend({
  71195. type: 'markPoint',
  71196. defaultOption: {
  71197. zlevel: 0,
  71198. z: 5,
  71199. symbol: 'pin',
  71200. symbolSize: 50,
  71201. //symbolRotate: 0,
  71202. //symbolOffset: [0, 0]
  71203. tooltip: {
  71204. trigger: 'item'
  71205. },
  71206. label: {
  71207. show: true,
  71208. position: 'inside'
  71209. },
  71210. itemStyle: {
  71211. borderWidth: 2
  71212. },
  71213. emphasis: {
  71214. label: {
  71215. show: true
  71216. }
  71217. }
  71218. }
  71219. });
  71220. /*
  71221. * Licensed to the Apache Software Foundation (ASF) under one
  71222. * or more contributor license agreements. See the NOTICE file
  71223. * distributed with this work for additional information
  71224. * regarding copyright ownership. The ASF licenses this file
  71225. * to you under the Apache License, Version 2.0 (the
  71226. * "License"); you may not use this file except in compliance
  71227. * with the License. You may obtain a copy of the License at
  71228. *
  71229. * http://www.apache.org/licenses/LICENSE-2.0
  71230. *
  71231. * Unless required by applicable law or agreed to in writing,
  71232. * software distributed under the License is distributed on an
  71233. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71234. * KIND, either express or implied. See the License for the
  71235. * specific language governing permissions and limitations
  71236. * under the License.
  71237. */
  71238. var indexOf$2 = indexOf;
  71239. function hasXOrY(item) {
  71240. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  71241. }
  71242. function hasXAndY(item) {
  71243. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  71244. }
  71245. // Make it simple, do not visit all stacked value to count precision.
  71246. // function getPrecision(data, valueAxisDim, dataIndex) {
  71247. // var precision = -1;
  71248. // var stackedDim = data.mapDimension(valueAxisDim);
  71249. // do {
  71250. // precision = Math.max(
  71251. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  71252. // precision
  71253. // );
  71254. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  71255. // if (stackedOnSeries) {
  71256. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  71257. // data = stackedOnSeries.getData();
  71258. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  71259. // stackedDim = data.getCalculationInfo('stackedDimension');
  71260. // }
  71261. // else {
  71262. // data = null;
  71263. // }
  71264. // } while (data);
  71265. // return precision;
  71266. // }
  71267. function markerTypeCalculatorWithExtent(
  71268. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  71269. ) {
  71270. var coordArr = [];
  71271. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  71272. var calcDataDim = stacked
  71273. ? data.getCalculationInfo('stackResultDimension')
  71274. : targetDataDim;
  71275. var value = numCalculate(data, calcDataDim, mlType);
  71276. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  71277. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  71278. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  71279. // Make it simple, do not visit all stacked value to count precision.
  71280. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  71281. precision = Math.min(precision, 20);
  71282. if (precision >= 0) {
  71283. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  71284. }
  71285. return coordArr;
  71286. }
  71287. var curry$7 = curry;
  71288. // TODO Specified percent
  71289. var markerTypeCalculator = {
  71290. /**
  71291. * @method
  71292. * @param {module:echarts/data/List} data
  71293. * @param {string} baseAxisDim
  71294. * @param {string} valueAxisDim
  71295. */
  71296. min: curry$7(markerTypeCalculatorWithExtent, 'min'),
  71297. /**
  71298. * @method
  71299. * @param {module:echarts/data/List} data
  71300. * @param {string} baseAxisDim
  71301. * @param {string} valueAxisDim
  71302. */
  71303. max: curry$7(markerTypeCalculatorWithExtent, 'max'),
  71304. /**
  71305. * @method
  71306. * @param {module:echarts/data/List} data
  71307. * @param {string} baseAxisDim
  71308. * @param {string} valueAxisDim
  71309. */
  71310. average: curry$7(markerTypeCalculatorWithExtent, 'average')
  71311. };
  71312. /**
  71313. * Transform markPoint data item to format used in List by do the following
  71314. * 1. Calculate statistic like `max`, `min`, `average`
  71315. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  71316. * @param {module:echarts/model/Series} seriesModel
  71317. * @param {module:echarts/coord/*} [coordSys]
  71318. * @param {Object} item
  71319. * @return {Object}
  71320. */
  71321. function dataTransform(seriesModel, item) {
  71322. var data = seriesModel.getData();
  71323. var coordSys = seriesModel.coordinateSystem;
  71324. // 1. If not specify the position with pixel directly
  71325. // 2. If `coord` is not a data array. Which uses `xAxis`,
  71326. // `yAxis` to specify the coord on each dimension
  71327. // parseFloat first because item.x and item.y can be percent string like '20%'
  71328. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  71329. var dims = coordSys.dimensions;
  71330. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  71331. // Clone the option
  71332. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  71333. item = clone(item);
  71334. if (item.type
  71335. && markerTypeCalculator[item.type]
  71336. && axisInfo.baseAxis && axisInfo.valueAxis
  71337. ) {
  71338. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  71339. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  71340. item.coord = markerTypeCalculator[item.type](
  71341. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  71342. otherCoordIndex, targetCoordIndex
  71343. );
  71344. // Force to use the value of calculated value.
  71345. item.value = item.coord[targetCoordIndex];
  71346. }
  71347. else {
  71348. // FIXME Only has one of xAxis and yAxis.
  71349. var coord = [
  71350. item.xAxis != null ? item.xAxis : item.radiusAxis,
  71351. item.yAxis != null ? item.yAxis : item.angleAxis
  71352. ];
  71353. // Each coord support max, min, average
  71354. for (var i = 0; i < 2; i++) {
  71355. if (markerTypeCalculator[coord[i]]) {
  71356. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  71357. }
  71358. }
  71359. item.coord = coord;
  71360. }
  71361. }
  71362. return item;
  71363. }
  71364. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  71365. var ret = {};
  71366. if (item.valueIndex != null || item.valueDim != null) {
  71367. ret.valueDataDim = item.valueIndex != null
  71368. ? data.getDimension(item.valueIndex) : item.valueDim;
  71369. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  71370. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  71371. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  71372. }
  71373. else {
  71374. ret.baseAxis = seriesModel.getBaseAxis();
  71375. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  71376. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  71377. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  71378. }
  71379. return ret;
  71380. }
  71381. function dataDimToCoordDim(seriesModel, dataDim) {
  71382. var data = seriesModel.getData();
  71383. var dimensions = data.dimensions;
  71384. dataDim = data.getDimension(dataDim);
  71385. for (var i = 0; i < dimensions.length; i++) {
  71386. var dimItem = data.getDimensionInfo(dimensions[i]);
  71387. if (dimItem.name === dataDim) {
  71388. return dimItem.coordDim;
  71389. }
  71390. }
  71391. }
  71392. /**
  71393. * Filter data which is out of coordinateSystem range
  71394. * [dataFilter description]
  71395. * @param {module:echarts/coord/*} [coordSys]
  71396. * @param {Object} item
  71397. * @return {boolean}
  71398. */
  71399. function dataFilter$1(coordSys, item) {
  71400. // Alwalys return true if there is no coordSys
  71401. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  71402. ? coordSys.containData(item.coord) : true;
  71403. }
  71404. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  71405. // x, y, radius, angle
  71406. if (dimIndex < 2) {
  71407. return item.coord && item.coord[dimIndex];
  71408. }
  71409. return item.value;
  71410. }
  71411. function numCalculate(data, valueDataDim, type) {
  71412. if (type === 'average') {
  71413. var sum = 0;
  71414. var count = 0;
  71415. data.each(valueDataDim, function (val, idx) {
  71416. if (!isNaN(val)) {
  71417. sum += val;
  71418. count++;
  71419. }
  71420. });
  71421. return sum / count;
  71422. }
  71423. else if (type === 'median') {
  71424. return data.getMedian(valueDataDim);
  71425. }
  71426. else {
  71427. // max & min
  71428. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  71429. }
  71430. }
  71431. /*
  71432. * Licensed to the Apache Software Foundation (ASF) under one
  71433. * or more contributor license agreements. See the NOTICE file
  71434. * distributed with this work for additional information
  71435. * regarding copyright ownership. The ASF licenses this file
  71436. * to you under the Apache License, Version 2.0 (the
  71437. * "License"); you may not use this file except in compliance
  71438. * with the License. You may obtain a copy of the License at
  71439. *
  71440. * http://www.apache.org/licenses/LICENSE-2.0
  71441. *
  71442. * Unless required by applicable law or agreed to in writing,
  71443. * software distributed under the License is distributed on an
  71444. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71445. * KIND, either express or implied. See the License for the
  71446. * specific language governing permissions and limitations
  71447. * under the License.
  71448. */
  71449. var MarkerView = extendComponentView({
  71450. type: 'marker',
  71451. init: function () {
  71452. /**
  71453. * Markline grouped by series
  71454. * @private
  71455. * @type {module:zrender/core/util.HashMap}
  71456. */
  71457. this.markerGroupMap = createHashMap();
  71458. },
  71459. render: function (markerModel, ecModel, api) {
  71460. var markerGroupMap = this.markerGroupMap;
  71461. markerGroupMap.each(function (item) {
  71462. item.__keep = false;
  71463. });
  71464. var markerModelKey = this.type + 'Model';
  71465. ecModel.eachSeries(function (seriesModel) {
  71466. var markerModel = seriesModel[markerModelKey];
  71467. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  71468. }, this);
  71469. markerGroupMap.each(function (item) {
  71470. !item.__keep && this.group.remove(item.group);
  71471. }, this);
  71472. },
  71473. renderSeries: function () {}
  71474. });
  71475. /*
  71476. * Licensed to the Apache Software Foundation (ASF) under one
  71477. * or more contributor license agreements. See the NOTICE file
  71478. * distributed with this work for additional information
  71479. * regarding copyright ownership. The ASF licenses this file
  71480. * to you under the Apache License, Version 2.0 (the
  71481. * "License"); you may not use this file except in compliance
  71482. * with the License. You may obtain a copy of the License at
  71483. *
  71484. * http://www.apache.org/licenses/LICENSE-2.0
  71485. *
  71486. * Unless required by applicable law or agreed to in writing,
  71487. * software distributed under the License is distributed on an
  71488. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71489. * KIND, either express or implied. See the License for the
  71490. * specific language governing permissions and limitations
  71491. * under the License.
  71492. */
  71493. function updateMarkerLayout(mpData, seriesModel, api) {
  71494. var coordSys = seriesModel.coordinateSystem;
  71495. mpData.each(function (idx) {
  71496. var itemModel = mpData.getItemModel(idx);
  71497. var point;
  71498. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  71499. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  71500. if (!isNaN(xPx) && !isNaN(yPx)) {
  71501. point = [xPx, yPx];
  71502. }
  71503. // Chart like bar may have there own marker positioning logic
  71504. else if (seriesModel.getMarkerPosition) {
  71505. // Use the getMarkerPoisition
  71506. point = seriesModel.getMarkerPosition(
  71507. mpData.getValues(mpData.dimensions, idx)
  71508. );
  71509. }
  71510. else if (coordSys) {
  71511. var x = mpData.get(coordSys.dimensions[0], idx);
  71512. var y = mpData.get(coordSys.dimensions[1], idx);
  71513. point = coordSys.dataToPoint([x, y]);
  71514. }
  71515. // Use x, y if has any
  71516. if (!isNaN(xPx)) {
  71517. point[0] = xPx;
  71518. }
  71519. if (!isNaN(yPx)) {
  71520. point[1] = yPx;
  71521. }
  71522. mpData.setItemLayout(idx, point);
  71523. });
  71524. }
  71525. MarkerView.extend({
  71526. type: 'markPoint',
  71527. // updateLayout: function (markPointModel, ecModel, api) {
  71528. // ecModel.eachSeries(function (seriesModel) {
  71529. // var mpModel = seriesModel.markPointModel;
  71530. // if (mpModel) {
  71531. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  71532. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  71533. // }
  71534. // }, this);
  71535. // },
  71536. updateTransform: function (markPointModel, ecModel, api) {
  71537. ecModel.eachSeries(function (seriesModel) {
  71538. var mpModel = seriesModel.markPointModel;
  71539. if (mpModel) {
  71540. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  71541. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  71542. }
  71543. }, this);
  71544. },
  71545. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  71546. var coordSys = seriesModel.coordinateSystem;
  71547. var seriesId = seriesModel.id;
  71548. var seriesData = seriesModel.getData();
  71549. var symbolDrawMap = this.markerGroupMap;
  71550. var symbolDraw = symbolDrawMap.get(seriesId)
  71551. || symbolDrawMap.set(seriesId, new SymbolDraw());
  71552. var mpData = createList$1(coordSys, seriesModel, mpModel);
  71553. // FIXME
  71554. mpModel.setData(mpData);
  71555. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  71556. mpData.each(function (idx) {
  71557. var itemModel = mpData.getItemModel(idx);
  71558. var symbolSize = itemModel.getShallow('symbolSize');
  71559. if (typeof symbolSize === 'function') {
  71560. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  71561. symbolSize = symbolSize(
  71562. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  71563. );
  71564. }
  71565. mpData.setItemVisual(idx, {
  71566. symbolSize: symbolSize,
  71567. color: itemModel.get('itemStyle.color')
  71568. || seriesData.getVisual('color'),
  71569. symbol: itemModel.getShallow('symbol')
  71570. });
  71571. });
  71572. // TODO Text are wrong
  71573. symbolDraw.updateData(mpData);
  71574. this.group.add(symbolDraw.group);
  71575. // Set host model for tooltip
  71576. // FIXME
  71577. mpData.eachItemGraphicEl(function (el) {
  71578. el.traverse(function (child) {
  71579. child.dataModel = mpModel;
  71580. });
  71581. });
  71582. symbolDraw.__keep = true;
  71583. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  71584. }
  71585. });
  71586. /**
  71587. * @inner
  71588. * @param {module:echarts/coord/*} [coordSys]
  71589. * @param {module:echarts/model/Series} seriesModel
  71590. * @param {module:echarts/model/Model} mpModel
  71591. */
  71592. function createList$1(coordSys, seriesModel, mpModel) {
  71593. var coordDimsInfos;
  71594. if (coordSys) {
  71595. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  71596. var info = seriesModel.getData().getDimensionInfo(
  71597. seriesModel.getData().mapDimension(coordDim)
  71598. ) || {};
  71599. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  71600. return defaults({name: coordDim}, info);
  71601. });
  71602. }
  71603. else {
  71604. coordDimsInfos =[{
  71605. name: 'value',
  71606. type: 'float'
  71607. }];
  71608. }
  71609. var mpData = new List(coordDimsInfos, mpModel);
  71610. var dataOpt = map(mpModel.get('data'), curry(
  71611. dataTransform, seriesModel
  71612. ));
  71613. if (coordSys) {
  71614. dataOpt = filter(
  71615. dataOpt, curry(dataFilter$1, coordSys)
  71616. );
  71617. }
  71618. mpData.initData(dataOpt, null,
  71619. coordSys ? dimValueGetter : function (item) {
  71620. return item.value;
  71621. }
  71622. );
  71623. return mpData;
  71624. }
  71625. /*
  71626. * Licensed to the Apache Software Foundation (ASF) under one
  71627. * or more contributor license agreements. See the NOTICE file
  71628. * distributed with this work for additional information
  71629. * regarding copyright ownership. The ASF licenses this file
  71630. * to you under the Apache License, Version 2.0 (the
  71631. * "License"); you may not use this file except in compliance
  71632. * with the License. You may obtain a copy of the License at
  71633. *
  71634. * http://www.apache.org/licenses/LICENSE-2.0
  71635. *
  71636. * Unless required by applicable law or agreed to in writing,
  71637. * software distributed under the License is distributed on an
  71638. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71639. * KIND, either express or implied. See the License for the
  71640. * specific language governing permissions and limitations
  71641. * under the License.
  71642. */
  71643. // HINT Markpoint can't be used too much
  71644. registerPreprocessor(function (opt) {
  71645. // Make sure markPoint component is enabled
  71646. opt.markPoint = opt.markPoint || {};
  71647. });
  71648. /*
  71649. * Licensed to the Apache Software Foundation (ASF) under one
  71650. * or more contributor license agreements. See the NOTICE file
  71651. * distributed with this work for additional information
  71652. * regarding copyright ownership. The ASF licenses this file
  71653. * to you under the Apache License, Version 2.0 (the
  71654. * "License"); you may not use this file except in compliance
  71655. * with the License. You may obtain a copy of the License at
  71656. *
  71657. * http://www.apache.org/licenses/LICENSE-2.0
  71658. *
  71659. * Unless required by applicable law or agreed to in writing,
  71660. * software distributed under the License is distributed on an
  71661. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71662. * KIND, either express or implied. See the License for the
  71663. * specific language governing permissions and limitations
  71664. * under the License.
  71665. */
  71666. MarkerModel.extend({
  71667. type: 'markLine',
  71668. defaultOption: {
  71669. zlevel: 0,
  71670. z: 5,
  71671. symbol: ['circle', 'arrow'],
  71672. symbolSize: [8, 16],
  71673. //symbolRotate: 0,
  71674. precision: 2,
  71675. tooltip: {
  71676. trigger: 'item'
  71677. },
  71678. label: {
  71679. show: true,
  71680. position: 'end'
  71681. },
  71682. lineStyle: {
  71683. type: 'dashed'
  71684. },
  71685. emphasis: {
  71686. label: {
  71687. show: true
  71688. },
  71689. lineStyle: {
  71690. width: 3
  71691. }
  71692. },
  71693. animationEasing: 'linear'
  71694. }
  71695. });
  71696. /*
  71697. * Licensed to the Apache Software Foundation (ASF) under one
  71698. * or more contributor license agreements. See the NOTICE file
  71699. * distributed with this work for additional information
  71700. * regarding copyright ownership. The ASF licenses this file
  71701. * to you under the Apache License, Version 2.0 (the
  71702. * "License"); you may not use this file except in compliance
  71703. * with the License. You may obtain a copy of the License at
  71704. *
  71705. * http://www.apache.org/licenses/LICENSE-2.0
  71706. *
  71707. * Unless required by applicable law or agreed to in writing,
  71708. * software distributed under the License is distributed on an
  71709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71710. * KIND, either express or implied. See the License for the
  71711. * specific language governing permissions and limitations
  71712. * under the License.
  71713. */
  71714. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  71715. var data = seriesModel.getData();
  71716. // Special type markLine like 'min', 'max', 'average', 'median'
  71717. var mlType = item.type;
  71718. if (!isArray(item)
  71719. && (
  71720. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  71721. // In case
  71722. // data: [{
  71723. // yAxis: 10
  71724. // }]
  71725. || (item.xAxis != null || item.yAxis != null)
  71726. )
  71727. ) {
  71728. var valueAxis;
  71729. var valueDataDim;
  71730. var value;
  71731. if (item.yAxis != null || item.xAxis != null) {
  71732. valueDataDim = item.yAxis != null ? 'y' : 'x';
  71733. valueAxis = coordSys.getAxis(valueDataDim);
  71734. value = retrieve(item.yAxis, item.xAxis);
  71735. }
  71736. else {
  71737. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  71738. valueDataDim = axisInfo.valueDataDim;
  71739. valueAxis = axisInfo.valueAxis;
  71740. value = numCalculate(data, valueDataDim, mlType);
  71741. }
  71742. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  71743. var baseIndex = 1 - valueIndex;
  71744. var mlFrom = clone(item);
  71745. var mlTo = {};
  71746. mlFrom.type = null;
  71747. mlFrom.coord = [];
  71748. mlTo.coord = [];
  71749. mlFrom.coord[baseIndex] = -Infinity;
  71750. mlTo.coord[baseIndex] = Infinity;
  71751. var precision = mlModel.get('precision');
  71752. if (precision >= 0 && typeof value === 'number') {
  71753. value = +value.toFixed(Math.min(precision, 20));
  71754. }
  71755. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  71756. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  71757. type: mlType,
  71758. valueIndex: item.valueIndex,
  71759. // Force to use the value of calculated value.
  71760. value: value
  71761. }];
  71762. }
  71763. item = [
  71764. dataTransform(seriesModel, item[0]),
  71765. dataTransform(seriesModel, item[1]),
  71766. extend({}, item[2])
  71767. ];
  71768. // Avoid line data type is extended by from(to) data type
  71769. item[2].type = item[2].type || '';
  71770. // Merge from option and to option into line option
  71771. merge(item[2], item[0]);
  71772. merge(item[2], item[1]);
  71773. return item;
  71774. };
  71775. function isInifinity(val) {
  71776. return !isNaN(val) && !isFinite(val);
  71777. }
  71778. // If a markLine has one dim
  71779. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  71780. var otherDimIndex = 1 - dimIndex;
  71781. var dimName = coordSys.dimensions[dimIndex];
  71782. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  71783. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  71784. }
  71785. function markLineFilter(coordSys, item) {
  71786. if (coordSys.type === 'cartesian2d') {
  71787. var fromCoord = item[0].coord;
  71788. var toCoord = item[1].coord;
  71789. // In case
  71790. // {
  71791. // markLine: {
  71792. // data: [{ yAxis: 2 }]
  71793. // }
  71794. // }
  71795. if (
  71796. fromCoord && toCoord &&
  71797. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  71798. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  71799. ) {
  71800. return true;
  71801. }
  71802. }
  71803. return dataFilter$1(coordSys, item[0])
  71804. && dataFilter$1(coordSys, item[1]);
  71805. }
  71806. function updateSingleMarkerEndLayout(
  71807. data, idx, isFrom, seriesModel, api
  71808. ) {
  71809. var coordSys = seriesModel.coordinateSystem;
  71810. var itemModel = data.getItemModel(idx);
  71811. var point;
  71812. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  71813. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  71814. if (!isNaN(xPx) && !isNaN(yPx)) {
  71815. point = [xPx, yPx];
  71816. }
  71817. else {
  71818. // Chart like bar may have there own marker positioning logic
  71819. if (seriesModel.getMarkerPosition) {
  71820. // Use the getMarkerPoisition
  71821. point = seriesModel.getMarkerPosition(
  71822. data.getValues(data.dimensions, idx)
  71823. );
  71824. }
  71825. else {
  71826. var dims = coordSys.dimensions;
  71827. var x = data.get(dims[0], idx);
  71828. var y = data.get(dims[1], idx);
  71829. point = coordSys.dataToPoint([x, y]);
  71830. }
  71831. // Expand line to the edge of grid if value on one axis is Inifnity
  71832. // In case
  71833. // markLine: {
  71834. // data: [{
  71835. // yAxis: 2
  71836. // // or
  71837. // type: 'average'
  71838. // }]
  71839. // }
  71840. if (coordSys.type === 'cartesian2d') {
  71841. var xAxis = coordSys.getAxis('x');
  71842. var yAxis = coordSys.getAxis('y');
  71843. var dims = coordSys.dimensions;
  71844. if (isInifinity(data.get(dims[0], idx))) {
  71845. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  71846. }
  71847. else if (isInifinity(data.get(dims[1], idx))) {
  71848. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  71849. }
  71850. }
  71851. // Use x, y if has any
  71852. if (!isNaN(xPx)) {
  71853. point[0] = xPx;
  71854. }
  71855. if (!isNaN(yPx)) {
  71856. point[1] = yPx;
  71857. }
  71858. }
  71859. data.setItemLayout(idx, point);
  71860. }
  71861. MarkerView.extend({
  71862. type: 'markLine',
  71863. // updateLayout: function (markLineModel, ecModel, api) {
  71864. // ecModel.eachSeries(function (seriesModel) {
  71865. // var mlModel = seriesModel.markLineModel;
  71866. // if (mlModel) {
  71867. // var mlData = mlModel.getData();
  71868. // var fromData = mlModel.__from;
  71869. // var toData = mlModel.__to;
  71870. // // Update visual and layout of from symbol and to symbol
  71871. // fromData.each(function (idx) {
  71872. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  71873. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  71874. // });
  71875. // // Update layout of line
  71876. // mlData.each(function (idx) {
  71877. // mlData.setItemLayout(idx, [
  71878. // fromData.getItemLayout(idx),
  71879. // toData.getItemLayout(idx)
  71880. // ]);
  71881. // });
  71882. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  71883. // }
  71884. // }, this);
  71885. // },
  71886. updateTransform: function (markLineModel, ecModel, api) {
  71887. ecModel.eachSeries(function (seriesModel) {
  71888. var mlModel = seriesModel.markLineModel;
  71889. if (mlModel) {
  71890. var mlData = mlModel.getData();
  71891. var fromData = mlModel.__from;
  71892. var toData = mlModel.__to;
  71893. // Update visual and layout of from symbol and to symbol
  71894. fromData.each(function (idx) {
  71895. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  71896. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  71897. });
  71898. // Update layout of line
  71899. mlData.each(function (idx) {
  71900. mlData.setItemLayout(idx, [
  71901. fromData.getItemLayout(idx),
  71902. toData.getItemLayout(idx)
  71903. ]);
  71904. });
  71905. this.markerGroupMap.get(seriesModel.id).updateLayout();
  71906. }
  71907. }, this);
  71908. },
  71909. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  71910. var coordSys = seriesModel.coordinateSystem;
  71911. var seriesId = seriesModel.id;
  71912. var seriesData = seriesModel.getData();
  71913. var lineDrawMap = this.markerGroupMap;
  71914. var lineDraw = lineDrawMap.get(seriesId)
  71915. || lineDrawMap.set(seriesId, new LineDraw());
  71916. this.group.add(lineDraw.group);
  71917. var mlData = createList$2(coordSys, seriesModel, mlModel);
  71918. var fromData = mlData.from;
  71919. var toData = mlData.to;
  71920. var lineData = mlData.line;
  71921. mlModel.__from = fromData;
  71922. mlModel.__to = toData;
  71923. // Line data for tooltip and formatter
  71924. mlModel.setData(lineData);
  71925. var symbolType = mlModel.get('symbol');
  71926. var symbolSize = mlModel.get('symbolSize');
  71927. if (!isArray(symbolType)) {
  71928. symbolType = [symbolType, symbolType];
  71929. }
  71930. if (typeof symbolSize === 'number') {
  71931. symbolSize = [symbolSize, symbolSize];
  71932. }
  71933. // Update visual and layout of from symbol and to symbol
  71934. mlData.from.each(function (idx) {
  71935. updateDataVisualAndLayout(fromData, idx, true);
  71936. updateDataVisualAndLayout(toData, idx, false);
  71937. });
  71938. // Update visual and layout of line
  71939. lineData.each(function (idx) {
  71940. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  71941. lineData.setItemVisual(idx, {
  71942. color: lineColor || fromData.getItemVisual(idx, 'color')
  71943. });
  71944. lineData.setItemLayout(idx, [
  71945. fromData.getItemLayout(idx),
  71946. toData.getItemLayout(idx)
  71947. ]);
  71948. lineData.setItemVisual(idx, {
  71949. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  71950. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  71951. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  71952. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  71953. });
  71954. });
  71955. lineDraw.updateData(lineData);
  71956. // Set host model for tooltip
  71957. // FIXME
  71958. mlData.line.eachItemGraphicEl(function (el, idx) {
  71959. el.traverse(function (child) {
  71960. child.dataModel = mlModel;
  71961. });
  71962. });
  71963. function updateDataVisualAndLayout(data, idx, isFrom) {
  71964. var itemModel = data.getItemModel(idx);
  71965. updateSingleMarkerEndLayout(
  71966. data, idx, isFrom, seriesModel, api
  71967. );
  71968. data.setItemVisual(idx, {
  71969. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  71970. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  71971. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  71972. });
  71973. }
  71974. lineDraw.__keep = true;
  71975. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  71976. }
  71977. });
  71978. /**
  71979. * @inner
  71980. * @param {module:echarts/coord/*} coordSys
  71981. * @param {module:echarts/model/Series} seriesModel
  71982. * @param {module:echarts/model/Model} mpModel
  71983. */
  71984. function createList$2(coordSys, seriesModel, mlModel) {
  71985. var coordDimsInfos;
  71986. if (coordSys) {
  71987. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  71988. var info = seriesModel.getData().getDimensionInfo(
  71989. seriesModel.getData().mapDimension(coordDim)
  71990. ) || {};
  71991. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  71992. return defaults({name: coordDim}, info);
  71993. });
  71994. }
  71995. else {
  71996. coordDimsInfos =[{
  71997. name: 'value',
  71998. type: 'float'
  71999. }];
  72000. }
  72001. var fromData = new List(coordDimsInfos, mlModel);
  72002. var toData = new List(coordDimsInfos, mlModel);
  72003. // No dimensions
  72004. var lineData = new List([], mlModel);
  72005. var optData = map(mlModel.get('data'), curry(
  72006. markLineTransform, seriesModel, coordSys, mlModel
  72007. ));
  72008. if (coordSys) {
  72009. optData = filter(
  72010. optData, curry(markLineFilter, coordSys)
  72011. );
  72012. }
  72013. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  72014. return item.value;
  72015. };
  72016. fromData.initData(
  72017. map(optData, function (item) { return item[0]; }),
  72018. null, dimValueGetter$$1
  72019. );
  72020. toData.initData(
  72021. map(optData, function (item) { return item[1]; }),
  72022. null, dimValueGetter$$1
  72023. );
  72024. lineData.initData(
  72025. map(optData, function (item) { return item[2]; })
  72026. );
  72027. lineData.hasItemOption = true;
  72028. return {
  72029. from: fromData,
  72030. to: toData,
  72031. line: lineData
  72032. };
  72033. }
  72034. /*
  72035. * Licensed to the Apache Software Foundation (ASF) under one
  72036. * or more contributor license agreements. See the NOTICE file
  72037. * distributed with this work for additional information
  72038. * regarding copyright ownership. The ASF licenses this file
  72039. * to you under the Apache License, Version 2.0 (the
  72040. * "License"); you may not use this file except in compliance
  72041. * with the License. You may obtain a copy of the License at
  72042. *
  72043. * http://www.apache.org/licenses/LICENSE-2.0
  72044. *
  72045. * Unless required by applicable law or agreed to in writing,
  72046. * software distributed under the License is distributed on an
  72047. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72048. * KIND, either express or implied. See the License for the
  72049. * specific language governing permissions and limitations
  72050. * under the License.
  72051. */
  72052. registerPreprocessor(function (opt) {
  72053. // Make sure markLine component is enabled
  72054. opt.markLine = opt.markLine || {};
  72055. });
  72056. /*
  72057. * Licensed to the Apache Software Foundation (ASF) under one
  72058. * or more contributor license agreements. See the NOTICE file
  72059. * distributed with this work for additional information
  72060. * regarding copyright ownership. The ASF licenses this file
  72061. * to you under the Apache License, Version 2.0 (the
  72062. * "License"); you may not use this file except in compliance
  72063. * with the License. You may obtain a copy of the License at
  72064. *
  72065. * http://www.apache.org/licenses/LICENSE-2.0
  72066. *
  72067. * Unless required by applicable law or agreed to in writing,
  72068. * software distributed under the License is distributed on an
  72069. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72070. * KIND, either express or implied. See the License for the
  72071. * specific language governing permissions and limitations
  72072. * under the License.
  72073. */
  72074. MarkerModel.extend({
  72075. type: 'markArea',
  72076. defaultOption: {
  72077. zlevel: 0,
  72078. // PENDING
  72079. z: 1,
  72080. tooltip: {
  72081. trigger: 'item'
  72082. },
  72083. // markArea should fixed on the coordinate system
  72084. animation: false,
  72085. label: {
  72086. show: true,
  72087. position: 'top'
  72088. },
  72089. itemStyle: {
  72090. // color and borderColor default to use color from series
  72091. // color: 'auto'
  72092. // borderColor: 'auto'
  72093. borderWidth: 0
  72094. },
  72095. emphasis: {
  72096. label: {
  72097. show: true,
  72098. position: 'top'
  72099. }
  72100. }
  72101. }
  72102. });
  72103. /*
  72104. * Licensed to the Apache Software Foundation (ASF) under one
  72105. * or more contributor license agreements. See the NOTICE file
  72106. * distributed with this work for additional information
  72107. * regarding copyright ownership. The ASF licenses this file
  72108. * to you under the Apache License, Version 2.0 (the
  72109. * "License"); you may not use this file except in compliance
  72110. * with the License. You may obtain a copy of the License at
  72111. *
  72112. * http://www.apache.org/licenses/LICENSE-2.0
  72113. *
  72114. * Unless required by applicable law or agreed to in writing,
  72115. * software distributed under the License is distributed on an
  72116. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72117. * KIND, either express or implied. See the License for the
  72118. * specific language governing permissions and limitations
  72119. * under the License.
  72120. */
  72121. // TODO Better on polar
  72122. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  72123. var lt = dataTransform(seriesModel, item[0]);
  72124. var rb = dataTransform(seriesModel, item[1]);
  72125. var retrieve$$1 = retrieve;
  72126. // FIXME make sure lt is less than rb
  72127. var ltCoord = lt.coord;
  72128. var rbCoord = rb.coord;
  72129. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  72130. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  72131. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  72132. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  72133. // Merge option into one
  72134. var result = mergeAll([{}, lt, rb]);
  72135. result.coord = [
  72136. lt.coord, rb.coord
  72137. ];
  72138. result.x0 = lt.x;
  72139. result.y0 = lt.y;
  72140. result.x1 = rb.x;
  72141. result.y1 = rb.y;
  72142. return result;
  72143. };
  72144. function isInifinity$1(val) {
  72145. return !isNaN(val) && !isFinite(val);
  72146. }
  72147. // If a markArea has one dim
  72148. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  72149. var otherDimIndex = 1 - dimIndex;
  72150. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  72151. }
  72152. function markAreaFilter(coordSys, item) {
  72153. var fromCoord = item.coord[0];
  72154. var toCoord = item.coord[1];
  72155. if (coordSys.type === 'cartesian2d') {
  72156. // In case
  72157. // {
  72158. // markArea: {
  72159. // data: [{ yAxis: 2 }]
  72160. // }
  72161. // }
  72162. if (
  72163. fromCoord && toCoord &&
  72164. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  72165. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  72166. ) {
  72167. return true;
  72168. }
  72169. }
  72170. return dataFilter$1(coordSys, {
  72171. coord: fromCoord,
  72172. x: item.x0,
  72173. y: item.y0
  72174. })
  72175. || dataFilter$1(coordSys, {
  72176. coord: toCoord,
  72177. x: item.x1,
  72178. y: item.y1
  72179. });
  72180. }
  72181. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  72182. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  72183. var coordSys = seriesModel.coordinateSystem;
  72184. var itemModel = data.getItemModel(idx);
  72185. var point;
  72186. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  72187. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  72188. if (!isNaN(xPx) && !isNaN(yPx)) {
  72189. point = [xPx, yPx];
  72190. }
  72191. else {
  72192. // Chart like bar may have there own marker positioning logic
  72193. if (seriesModel.getMarkerPosition) {
  72194. // Use the getMarkerPoisition
  72195. point = seriesModel.getMarkerPosition(
  72196. data.getValues(dims, idx)
  72197. );
  72198. }
  72199. else {
  72200. var x = data.get(dims[0], idx);
  72201. var y = data.get(dims[1], idx);
  72202. var pt = [x, y];
  72203. coordSys.clampData && coordSys.clampData(pt, pt);
  72204. point = coordSys.dataToPoint(pt, true);
  72205. }
  72206. if (coordSys.type === 'cartesian2d') {
  72207. var xAxis = coordSys.getAxis('x');
  72208. var yAxis = coordSys.getAxis('y');
  72209. var x = data.get(dims[0], idx);
  72210. var y = data.get(dims[1], idx);
  72211. if (isInifinity$1(x)) {
  72212. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  72213. }
  72214. else if (isInifinity$1(y)) {
  72215. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  72216. }
  72217. }
  72218. // Use x, y if has any
  72219. if (!isNaN(xPx)) {
  72220. point[0] = xPx;
  72221. }
  72222. if (!isNaN(yPx)) {
  72223. point[1] = yPx;
  72224. }
  72225. }
  72226. return point;
  72227. }
  72228. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  72229. MarkerView.extend({
  72230. type: 'markArea',
  72231. // updateLayout: function (markAreaModel, ecModel, api) {
  72232. // ecModel.eachSeries(function (seriesModel) {
  72233. // var maModel = seriesModel.markAreaModel;
  72234. // if (maModel) {
  72235. // var areaData = maModel.getData();
  72236. // areaData.each(function (idx) {
  72237. // var points = zrUtil.map(dimPermutations, function (dim) {
  72238. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72239. // });
  72240. // // Layout
  72241. // areaData.setItemLayout(idx, points);
  72242. // var el = areaData.getItemGraphicEl(idx);
  72243. // el.setShape('points', points);
  72244. // });
  72245. // }
  72246. // }, this);
  72247. // },
  72248. updateTransform: function (markAreaModel, ecModel, api) {
  72249. ecModel.eachSeries(function (seriesModel) {
  72250. var maModel = seriesModel.markAreaModel;
  72251. if (maModel) {
  72252. var areaData = maModel.getData();
  72253. areaData.each(function (idx) {
  72254. var points = map(dimPermutations, function (dim) {
  72255. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72256. });
  72257. // Layout
  72258. areaData.setItemLayout(idx, points);
  72259. var el = areaData.getItemGraphicEl(idx);
  72260. el.setShape('points', points);
  72261. });
  72262. }
  72263. }, this);
  72264. },
  72265. renderSeries: function (seriesModel, maModel, ecModel, api) {
  72266. var coordSys = seriesModel.coordinateSystem;
  72267. var seriesId = seriesModel.id;
  72268. var seriesData = seriesModel.getData();
  72269. var areaGroupMap = this.markerGroupMap;
  72270. var polygonGroup = areaGroupMap.get(seriesId)
  72271. || areaGroupMap.set(seriesId, {group: new Group()});
  72272. this.group.add(polygonGroup.group);
  72273. polygonGroup.__keep = true;
  72274. var areaData = createList$3(coordSys, seriesModel, maModel);
  72275. // Line data for tooltip and formatter
  72276. maModel.setData(areaData);
  72277. // Update visual and layout of line
  72278. areaData.each(function (idx) {
  72279. // Layout
  72280. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  72281. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72282. }));
  72283. // Visual
  72284. areaData.setItemVisual(idx, {
  72285. color: seriesData.getVisual('color')
  72286. });
  72287. });
  72288. areaData.diff(polygonGroup.__data)
  72289. .add(function (idx) {
  72290. var polygon = new Polygon({
  72291. shape: {
  72292. points: areaData.getItemLayout(idx)
  72293. }
  72294. });
  72295. areaData.setItemGraphicEl(idx, polygon);
  72296. polygonGroup.group.add(polygon);
  72297. })
  72298. .update(function (newIdx, oldIdx) {
  72299. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  72300. updateProps(polygon, {
  72301. shape: {
  72302. points: areaData.getItemLayout(newIdx)
  72303. }
  72304. }, maModel, newIdx);
  72305. polygonGroup.group.add(polygon);
  72306. areaData.setItemGraphicEl(newIdx, polygon);
  72307. })
  72308. .remove(function (idx) {
  72309. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  72310. polygonGroup.group.remove(polygon);
  72311. })
  72312. .execute();
  72313. areaData.eachItemGraphicEl(function (polygon, idx) {
  72314. var itemModel = areaData.getItemModel(idx);
  72315. var labelModel = itemModel.getModel('label');
  72316. var labelHoverModel = itemModel.getModel('emphasis.label');
  72317. var color = areaData.getItemVisual(idx, 'color');
  72318. polygon.useStyle(
  72319. defaults(
  72320. itemModel.getModel('itemStyle').getItemStyle(),
  72321. {
  72322. fill: modifyAlpha(color, 0.4),
  72323. stroke: color
  72324. }
  72325. )
  72326. );
  72327. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  72328. setLabelStyle(
  72329. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  72330. {
  72331. labelFetcher: maModel,
  72332. labelDataIndex: idx,
  72333. defaultText: areaData.getName(idx) || '',
  72334. isRectText: true,
  72335. autoColor: color
  72336. }
  72337. );
  72338. setHoverStyle(polygon, {});
  72339. polygon.dataModel = maModel;
  72340. });
  72341. polygonGroup.__data = areaData;
  72342. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  72343. }
  72344. });
  72345. /**
  72346. * @inner
  72347. * @param {module:echarts/coord/*} coordSys
  72348. * @param {module:echarts/model/Series} seriesModel
  72349. * @param {module:echarts/model/Model} mpModel
  72350. */
  72351. function createList$3(coordSys, seriesModel, maModel) {
  72352. var coordDimsInfos;
  72353. var areaData;
  72354. var dims = ['x0', 'y0', 'x1', 'y1'];
  72355. if (coordSys) {
  72356. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  72357. var data = seriesModel.getData();
  72358. var info = data.getDimensionInfo(
  72359. data.mapDimension(coordDim)
  72360. ) || {};
  72361. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  72362. return defaults({name: coordDim}, info);
  72363. });
  72364. areaData = new List(map(dims, function (dim, idx) {
  72365. return {
  72366. name: dim,
  72367. type: coordDimsInfos[idx % 2].type
  72368. };
  72369. }), maModel);
  72370. }
  72371. else {
  72372. coordDimsInfos =[{
  72373. name: 'value',
  72374. type: 'float'
  72375. }];
  72376. areaData = new List(coordDimsInfos, maModel);
  72377. }
  72378. var optData = map(maModel.get('data'), curry(
  72379. markAreaTransform, seriesModel, coordSys, maModel
  72380. ));
  72381. if (coordSys) {
  72382. optData = filter(
  72383. optData, curry(markAreaFilter, coordSys)
  72384. );
  72385. }
  72386. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  72387. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  72388. } : function (item) {
  72389. return item.value;
  72390. };
  72391. areaData.initData(optData, null, dimValueGetter$$1);
  72392. areaData.hasItemOption = true;
  72393. return areaData;
  72394. }
  72395. /*
  72396. * Licensed to the Apache Software Foundation (ASF) under one
  72397. * or more contributor license agreements. See the NOTICE file
  72398. * distributed with this work for additional information
  72399. * regarding copyright ownership. The ASF licenses this file
  72400. * to you under the Apache License, Version 2.0 (the
  72401. * "License"); you may not use this file except in compliance
  72402. * with the License. You may obtain a copy of the License at
  72403. *
  72404. * http://www.apache.org/licenses/LICENSE-2.0
  72405. *
  72406. * Unless required by applicable law or agreed to in writing,
  72407. * software distributed under the License is distributed on an
  72408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72409. * KIND, either express or implied. See the License for the
  72410. * specific language governing permissions and limitations
  72411. * under the License.
  72412. */
  72413. registerPreprocessor(function (opt) {
  72414. // Make sure markArea component is enabled
  72415. opt.markArea = opt.markArea || {};
  72416. });
  72417. /*
  72418. * Licensed to the Apache Software Foundation (ASF) under one
  72419. * or more contributor license agreements. See the NOTICE file
  72420. * distributed with this work for additional information
  72421. * regarding copyright ownership. The ASF licenses this file
  72422. * to you under the Apache License, Version 2.0 (the
  72423. * "License"); you may not use this file except in compliance
  72424. * with the License. You may obtain a copy of the License at
  72425. *
  72426. * http://www.apache.org/licenses/LICENSE-2.0
  72427. *
  72428. * Unless required by applicable law or agreed to in writing,
  72429. * software distributed under the License is distributed on an
  72430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72431. * KIND, either express or implied. See the License for the
  72432. * specific language governing permissions and limitations
  72433. * under the License.
  72434. */
  72435. var preprocessor$3 = function (option) {
  72436. var timelineOpt = option && option.timeline;
  72437. if (!isArray(timelineOpt)) {
  72438. timelineOpt = timelineOpt ? [timelineOpt] : [];
  72439. }
  72440. each$1(timelineOpt, function (opt) {
  72441. if (!opt) {
  72442. return;
  72443. }
  72444. compatibleEC2(opt);
  72445. });
  72446. };
  72447. function compatibleEC2(opt) {
  72448. var type = opt.type;
  72449. var ec2Types = {'number': 'value', 'time': 'time'};
  72450. // Compatible with ec2
  72451. if (ec2Types[type]) {
  72452. opt.axisType = ec2Types[type];
  72453. delete opt.type;
  72454. }
  72455. transferItem(opt);
  72456. if (has$2(opt, 'controlPosition')) {
  72457. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  72458. if (!has$2(controlStyle, 'position')) {
  72459. controlStyle.position = opt.controlPosition;
  72460. }
  72461. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  72462. controlStyle.show = false;
  72463. delete controlStyle.position;
  72464. }
  72465. delete opt.controlPosition;
  72466. }
  72467. each$1(opt.data || [], function (dataItem) {
  72468. if (isObject$1(dataItem) && !isArray(dataItem)) {
  72469. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  72470. // In ec2, using name as value.
  72471. dataItem.value = dataItem.name;
  72472. }
  72473. transferItem(dataItem);
  72474. }
  72475. });
  72476. }
  72477. function transferItem(opt) {
  72478. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  72479. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  72480. // Transfer label out
  72481. var label = opt.label || (opt.label || {});
  72482. var labelNormal = label.normal || (label.normal = {});
  72483. var excludeLabelAttr = {normal: 1, emphasis: 1};
  72484. each$1(label, function (value, name) {
  72485. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  72486. labelNormal[name] = value;
  72487. }
  72488. });
  72489. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  72490. label.emphasis = itemStyleEmphasis.label;
  72491. delete itemStyleEmphasis.label;
  72492. }
  72493. }
  72494. function has$2(obj, attr) {
  72495. return obj.hasOwnProperty(attr);
  72496. }
  72497. /*
  72498. * Licensed to the Apache Software Foundation (ASF) under one
  72499. * or more contributor license agreements. See the NOTICE file
  72500. * distributed with this work for additional information
  72501. * regarding copyright ownership. The ASF licenses this file
  72502. * to you under the Apache License, Version 2.0 (the
  72503. * "License"); you may not use this file except in compliance
  72504. * with the License. You may obtain a copy of the License at
  72505. *
  72506. * http://www.apache.org/licenses/LICENSE-2.0
  72507. *
  72508. * Unless required by applicable law or agreed to in writing,
  72509. * software distributed under the License is distributed on an
  72510. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72511. * KIND, either express or implied. See the License for the
  72512. * specific language governing permissions and limitations
  72513. * under the License.
  72514. */
  72515. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  72516. // Only slider now.
  72517. return 'slider';
  72518. });
  72519. /*
  72520. * Licensed to the Apache Software Foundation (ASF) under one
  72521. * or more contributor license agreements. See the NOTICE file
  72522. * distributed with this work for additional information
  72523. * regarding copyright ownership. The ASF licenses this file
  72524. * to you under the Apache License, Version 2.0 (the
  72525. * "License"); you may not use this file except in compliance
  72526. * with the License. You may obtain a copy of the License at
  72527. *
  72528. * http://www.apache.org/licenses/LICENSE-2.0
  72529. *
  72530. * Unless required by applicable law or agreed to in writing,
  72531. * software distributed under the License is distributed on an
  72532. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72533. * KIND, either express or implied. See the License for the
  72534. * specific language governing permissions and limitations
  72535. * under the License.
  72536. */
  72537. registerAction(
  72538. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  72539. function (payload, ecModel) {
  72540. var timelineModel = ecModel.getComponent('timeline');
  72541. if (timelineModel && payload.currentIndex != null) {
  72542. timelineModel.setCurrentIndex(payload.currentIndex);
  72543. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  72544. timelineModel.setPlayState(false);
  72545. }
  72546. }
  72547. // Set normalized currentIndex to payload.
  72548. ecModel.resetOption('timeline');
  72549. return defaults({
  72550. currentIndex: timelineModel.option.currentIndex
  72551. }, payload);
  72552. }
  72553. );
  72554. registerAction(
  72555. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  72556. function (payload, ecModel) {
  72557. var timelineModel = ecModel.getComponent('timeline');
  72558. if (timelineModel && payload.playState != null) {
  72559. timelineModel.setPlayState(payload.playState);
  72560. }
  72561. }
  72562. );
  72563. /*
  72564. * Licensed to the Apache Software Foundation (ASF) under one
  72565. * or more contributor license agreements. See the NOTICE file
  72566. * distributed with this work for additional information
  72567. * regarding copyright ownership. The ASF licenses this file
  72568. * to you under the Apache License, Version 2.0 (the
  72569. * "License"); you may not use this file except in compliance
  72570. * with the License. You may obtain a copy of the License at
  72571. *
  72572. * http://www.apache.org/licenses/LICENSE-2.0
  72573. *
  72574. * Unless required by applicable law or agreed to in writing,
  72575. * software distributed under the License is distributed on an
  72576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72577. * KIND, either express or implied. See the License for the
  72578. * specific language governing permissions and limitations
  72579. * under the License.
  72580. */
  72581. var TimelineModel = ComponentModel.extend({
  72582. type: 'timeline',
  72583. layoutMode: 'box',
  72584. /**
  72585. * @protected
  72586. */
  72587. defaultOption: {
  72588. zlevel: 0, // 一级层叠
  72589. z: 4, // 二级层叠
  72590. show: true,
  72591. axisType: 'time', // 模式是时间类型,支持 value, category
  72592. realtime: true,
  72593. left: '20%',
  72594. top: null,
  72595. right: '20%',
  72596. bottom: 0,
  72597. width: null,
  72598. height: 40,
  72599. padding: 5,
  72600. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  72601. autoPlay: false,
  72602. rewind: false, // 反向播放
  72603. loop: true,
  72604. playInterval: 2000, // 播放时间间隔,单位ms
  72605. currentIndex: 0,
  72606. itemStyle: {},
  72607. label: {
  72608. color: '#000'
  72609. },
  72610. data: []
  72611. },
  72612. /**
  72613. * @override
  72614. */
  72615. init: function (option, parentModel, ecModel) {
  72616. /**
  72617. * @private
  72618. * @type {module:echarts/data/List}
  72619. */
  72620. this._data;
  72621. /**
  72622. * @private
  72623. * @type {Array.<string>}
  72624. */
  72625. this._names;
  72626. this.mergeDefaultAndTheme(option, ecModel);
  72627. this._initData();
  72628. },
  72629. /**
  72630. * @override
  72631. */
  72632. mergeOption: function (option) {
  72633. TimelineModel.superApply(this, 'mergeOption', arguments);
  72634. this._initData();
  72635. },
  72636. /**
  72637. * @param {number} [currentIndex]
  72638. */
  72639. setCurrentIndex: function (currentIndex) {
  72640. if (currentIndex == null) {
  72641. currentIndex = this.option.currentIndex;
  72642. }
  72643. var count = this._data.count();
  72644. if (this.option.loop) {
  72645. currentIndex = (currentIndex % count + count) % count;
  72646. }
  72647. else {
  72648. currentIndex >= count && (currentIndex = count - 1);
  72649. currentIndex < 0 && (currentIndex = 0);
  72650. }
  72651. this.option.currentIndex = currentIndex;
  72652. },
  72653. /**
  72654. * @return {number} currentIndex
  72655. */
  72656. getCurrentIndex: function () {
  72657. return this.option.currentIndex;
  72658. },
  72659. /**
  72660. * @return {boolean}
  72661. */
  72662. isIndexMax: function () {
  72663. return this.getCurrentIndex() >= this._data.count() - 1;
  72664. },
  72665. /**
  72666. * @param {boolean} state true: play, false: stop
  72667. */
  72668. setPlayState: function (state) {
  72669. this.option.autoPlay = !!state;
  72670. },
  72671. /**
  72672. * @return {boolean} true: play, false: stop
  72673. */
  72674. getPlayState: function () {
  72675. return !!this.option.autoPlay;
  72676. },
  72677. /**
  72678. * @private
  72679. */
  72680. _initData: function () {
  72681. var thisOption = this.option;
  72682. var dataArr = thisOption.data || [];
  72683. var axisType = thisOption.axisType;
  72684. var names = this._names = [];
  72685. if (axisType === 'category') {
  72686. var idxArr = [];
  72687. each$1(dataArr, function (item, index) {
  72688. var value = getDataItemValue(item);
  72689. var newItem;
  72690. if (isObject$1(item)) {
  72691. newItem = clone(item);
  72692. newItem.value = index;
  72693. }
  72694. else {
  72695. newItem = index;
  72696. }
  72697. idxArr.push(newItem);
  72698. if (!isString(value) && (value == null || isNaN(value))) {
  72699. value = '';
  72700. }
  72701. names.push(value + '');
  72702. });
  72703. dataArr = idxArr;
  72704. }
  72705. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  72706. var data = this._data = new List([{name: 'value', type: dimType}], this);
  72707. data.initData(dataArr, names);
  72708. },
  72709. getData: function () {
  72710. return this._data;
  72711. },
  72712. /**
  72713. * @public
  72714. * @return {Array.<string>} categoreis
  72715. */
  72716. getCategories: function () {
  72717. if (this.get('axisType') === 'category') {
  72718. return this._names.slice();
  72719. }
  72720. }
  72721. });
  72722. /*
  72723. * Licensed to the Apache Software Foundation (ASF) under one
  72724. * or more contributor license agreements. See the NOTICE file
  72725. * distributed with this work for additional information
  72726. * regarding copyright ownership. The ASF licenses this file
  72727. * to you under the Apache License, Version 2.0 (the
  72728. * "License"); you may not use this file except in compliance
  72729. * with the License. You may obtain a copy of the License at
  72730. *
  72731. * http://www.apache.org/licenses/LICENSE-2.0
  72732. *
  72733. * Unless required by applicable law or agreed to in writing,
  72734. * software distributed under the License is distributed on an
  72735. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72736. * KIND, either express or implied. See the License for the
  72737. * specific language governing permissions and limitations
  72738. * under the License.
  72739. */
  72740. var SliderTimelineModel = TimelineModel.extend({
  72741. type: 'timeline.slider',
  72742. /**
  72743. * @protected
  72744. */
  72745. defaultOption: {
  72746. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  72747. borderColor: '#ccc', // 时间轴边框颜色
  72748. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  72749. orient: 'horizontal', // 'vertical'
  72750. inverse: false,
  72751. tooltip: { // boolean or Object
  72752. trigger: 'item' // data item may also have tootip attr.
  72753. },
  72754. symbol: 'emptyCircle',
  72755. symbolSize: 10,
  72756. lineStyle: {
  72757. show: true,
  72758. width: 2,
  72759. color: '#304654'
  72760. },
  72761. label: { // 文本标签
  72762. position: 'auto', // auto left right top bottom
  72763. // When using number, label position is not
  72764. // restricted by viewRect.
  72765. // positive: right/bottom, negative: left/top
  72766. show: true,
  72767. interval: 'auto',
  72768. rotate: 0,
  72769. // formatter: null,
  72770. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  72771. color: '#304654'
  72772. },
  72773. itemStyle: {
  72774. color: '#304654',
  72775. borderWidth: 1
  72776. },
  72777. checkpointStyle: {
  72778. symbol: 'circle',
  72779. symbolSize: 13,
  72780. color: '#c23531',
  72781. borderWidth: 5,
  72782. borderColor: 'rgba(194,53,49, 0.5)',
  72783. animation: true,
  72784. animationDuration: 300,
  72785. animationEasing: 'quinticInOut'
  72786. },
  72787. controlStyle: {
  72788. show: true,
  72789. showPlayBtn: true,
  72790. showPrevBtn: true,
  72791. showNextBtn: true,
  72792. itemSize: 22,
  72793. itemGap: 12,
  72794. position: 'left', // 'left' 'right' 'top' 'bottom'
  72795. 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
  72796. 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
  72797. 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
  72798. 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
  72799. color: '#304654',
  72800. borderColor: '#304654',
  72801. borderWidth: 1
  72802. },
  72803. emphasis: {
  72804. label: {
  72805. show: true,
  72806. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  72807. color: '#c23531'
  72808. },
  72809. itemStyle: {
  72810. color: '#c23531'
  72811. },
  72812. controlStyle: {
  72813. color: '#c23531',
  72814. borderColor: '#c23531',
  72815. borderWidth: 2
  72816. }
  72817. },
  72818. data: []
  72819. }
  72820. });
  72821. mixin(SliderTimelineModel, dataFormatMixin);
  72822. /*
  72823. * Licensed to the Apache Software Foundation (ASF) under one
  72824. * or more contributor license agreements. See the NOTICE file
  72825. * distributed with this work for additional information
  72826. * regarding copyright ownership. The ASF licenses this file
  72827. * to you under the Apache License, Version 2.0 (the
  72828. * "License"); you may not use this file except in compliance
  72829. * with the License. You may obtain a copy of the License at
  72830. *
  72831. * http://www.apache.org/licenses/LICENSE-2.0
  72832. *
  72833. * Unless required by applicable law or agreed to in writing,
  72834. * software distributed under the License is distributed on an
  72835. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72836. * KIND, either express or implied. See the License for the
  72837. * specific language governing permissions and limitations
  72838. * under the License.
  72839. */
  72840. var TimelineView = Component.extend({
  72841. type: 'timeline'
  72842. });
  72843. /*
  72844. * Licensed to the Apache Software Foundation (ASF) under one
  72845. * or more contributor license agreements. See the NOTICE file
  72846. * distributed with this work for additional information
  72847. * regarding copyright ownership. The ASF licenses this file
  72848. * to you under the Apache License, Version 2.0 (the
  72849. * "License"); you may not use this file except in compliance
  72850. * with the License. You may obtain a copy of the License at
  72851. *
  72852. * http://www.apache.org/licenses/LICENSE-2.0
  72853. *
  72854. * Unless required by applicable law or agreed to in writing,
  72855. * software distributed under the License is distributed on an
  72856. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72857. * KIND, either express or implied. See the License for the
  72858. * specific language governing permissions and limitations
  72859. * under the License.
  72860. */
  72861. /**
  72862. * Extend axis 2d
  72863. * @constructor module:echarts/coord/cartesian/Axis2D
  72864. * @extends {module:echarts/coord/cartesian/Axis}
  72865. * @param {string} dim
  72866. * @param {*} scale
  72867. * @param {Array.<number>} coordExtent
  72868. * @param {string} axisType
  72869. * @param {string} position
  72870. */
  72871. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  72872. Axis.call(this, dim, scale, coordExtent);
  72873. /**
  72874. * Axis type
  72875. * - 'category'
  72876. * - 'value'
  72877. * - 'time'
  72878. * - 'log'
  72879. * @type {string}
  72880. */
  72881. this.type = axisType || 'value';
  72882. /**
  72883. * Axis model
  72884. * @param {module:echarts/component/TimelineModel}
  72885. */
  72886. this.model = null;
  72887. };
  72888. TimelineAxis.prototype = {
  72889. constructor: TimelineAxis,
  72890. /**
  72891. * @override
  72892. */
  72893. getLabelModel: function () {
  72894. return this.model.getModel('label');
  72895. },
  72896. /**
  72897. * @override
  72898. */
  72899. isHorizontal: function () {
  72900. return this.model.get('orient') === 'horizontal';
  72901. }
  72902. };
  72903. inherits(TimelineAxis, Axis);
  72904. /*
  72905. * Licensed to the Apache Software Foundation (ASF) under one
  72906. * or more contributor license agreements. See the NOTICE file
  72907. * distributed with this work for additional information
  72908. * regarding copyright ownership. The ASF licenses this file
  72909. * to you under the Apache License, Version 2.0 (the
  72910. * "License"); you may not use this file except in compliance
  72911. * with the License. You may obtain a copy of the License at
  72912. *
  72913. * http://www.apache.org/licenses/LICENSE-2.0
  72914. *
  72915. * Unless required by applicable law or agreed to in writing,
  72916. * software distributed under the License is distributed on an
  72917. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72918. * KIND, either express or implied. See the License for the
  72919. * specific language governing permissions and limitations
  72920. * under the License.
  72921. */
  72922. var bind$6 = bind;
  72923. var each$27 = each$1;
  72924. var PI$4 = Math.PI;
  72925. TimelineView.extend({
  72926. type: 'timeline.slider',
  72927. init: function (ecModel, api) {
  72928. this.api = api;
  72929. /**
  72930. * @private
  72931. * @type {module:echarts/component/timeline/TimelineAxis}
  72932. */
  72933. this._axis;
  72934. /**
  72935. * @private
  72936. * @type {module:zrender/core/BoundingRect}
  72937. */
  72938. this._viewRect;
  72939. /**
  72940. * @type {number}
  72941. */
  72942. this._timer;
  72943. /**
  72944. * @type {module:zrender/Element}
  72945. */
  72946. this._currentPointer;
  72947. /**
  72948. * @type {module:zrender/container/Group}
  72949. */
  72950. this._mainGroup;
  72951. /**
  72952. * @type {module:zrender/container/Group}
  72953. */
  72954. this._labelGroup;
  72955. },
  72956. /**
  72957. * @override
  72958. */
  72959. render: function (timelineModel, ecModel, api, payload) {
  72960. this.model = timelineModel;
  72961. this.api = api;
  72962. this.ecModel = ecModel;
  72963. this.group.removeAll();
  72964. if (timelineModel.get('show', true)) {
  72965. var layoutInfo = this._layout(timelineModel, api);
  72966. var mainGroup = this._createGroup('mainGroup');
  72967. var labelGroup = this._createGroup('labelGroup');
  72968. /**
  72969. * @private
  72970. * @type {module:echarts/component/timeline/TimelineAxis}
  72971. */
  72972. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  72973. timelineModel.formatTooltip = function (dataIndex) {
  72974. return encodeHTML(axis.scale.getLabel(dataIndex));
  72975. };
  72976. each$27(
  72977. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  72978. function (name) {
  72979. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  72980. },
  72981. this
  72982. );
  72983. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  72984. this._position(layoutInfo, timelineModel);
  72985. }
  72986. this._doPlayStop();
  72987. },
  72988. /**
  72989. * @override
  72990. */
  72991. remove: function () {
  72992. this._clearTimer();
  72993. this.group.removeAll();
  72994. },
  72995. /**
  72996. * @override
  72997. */
  72998. dispose: function () {
  72999. this._clearTimer();
  73000. },
  73001. _layout: function (timelineModel, api) {
  73002. var labelPosOpt = timelineModel.get('label.position');
  73003. var orient = timelineModel.get('orient');
  73004. var viewRect = getViewRect$4(timelineModel, api);
  73005. // Auto label offset.
  73006. if (labelPosOpt == null || labelPosOpt === 'auto') {
  73007. labelPosOpt = orient === 'horizontal'
  73008. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  73009. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  73010. }
  73011. else if (isNaN(labelPosOpt)) {
  73012. labelPosOpt = ({
  73013. horizontal: {top: '-', bottom: '+'},
  73014. vertical: {left: '-', right: '+'}
  73015. })[orient][labelPosOpt];
  73016. }
  73017. var labelAlignMap = {
  73018. horizontal: 'center',
  73019. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  73020. };
  73021. var labelBaselineMap = {
  73022. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  73023. vertical: 'middle'
  73024. };
  73025. var rotationMap = {
  73026. horizontal: 0,
  73027. vertical: PI$4 / 2
  73028. };
  73029. // Position
  73030. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  73031. var controlModel = timelineModel.getModel('controlStyle');
  73032. var showControl = controlModel.get('show', true);
  73033. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  73034. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  73035. var sizePlusGap = controlSize + controlGap;
  73036. // Special label rotate.
  73037. var labelRotation = timelineModel.get('label.rotate') || 0;
  73038. labelRotation = labelRotation * PI$4 / 180; // To radian.
  73039. var playPosition;
  73040. var prevBtnPosition;
  73041. var nextBtnPosition;
  73042. var axisExtent;
  73043. var controlPosition = controlModel.get('position', true);
  73044. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  73045. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  73046. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  73047. var xLeft = 0;
  73048. var xRight = mainLength;
  73049. // position[0] means left, position[1] means middle.
  73050. if (controlPosition === 'left' || controlPosition === 'bottom') {
  73051. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  73052. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  73053. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73054. }
  73055. else { // 'top' 'right'
  73056. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73057. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  73058. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73059. }
  73060. axisExtent = [xLeft, xRight];
  73061. if (timelineModel.get('inverse')) {
  73062. axisExtent.reverse();
  73063. }
  73064. return {
  73065. viewRect: viewRect,
  73066. mainLength: mainLength,
  73067. orient: orient,
  73068. rotation: rotationMap[orient],
  73069. labelRotation: labelRotation,
  73070. labelPosOpt: labelPosOpt,
  73071. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  73072. labelBaseline: timelineModel.get('label.verticalAlign')
  73073. || timelineModel.get('label.baseline')
  73074. || labelBaselineMap[orient],
  73075. // Based on mainGroup.
  73076. playPosition: playPosition,
  73077. prevBtnPosition: prevBtnPosition,
  73078. nextBtnPosition: nextBtnPosition,
  73079. axisExtent: axisExtent,
  73080. controlSize: controlSize,
  73081. controlGap: controlGap
  73082. };
  73083. },
  73084. _position: function (layoutInfo, timelineModel) {
  73085. // Position is be called finally, because bounding rect is needed for
  73086. // adapt content to fill viewRect (auto adapt offset).
  73087. // Timeline may be not all in the viewRect when 'offset' is specified
  73088. // as a number, because it is more appropriate that label aligns at
  73089. // 'offset' but not the other edge defined by viewRect.
  73090. var mainGroup = this._mainGroup;
  73091. var labelGroup = this._labelGroup;
  73092. var viewRect = layoutInfo.viewRect;
  73093. if (layoutInfo.orient === 'vertical') {
  73094. // transform to horizontal, inverse rotate by left-top point.
  73095. var m = create$1();
  73096. var rotateOriginX = viewRect.x;
  73097. var rotateOriginY = viewRect.y + viewRect.height;
  73098. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  73099. rotate(m, m, -PI$4 / 2);
  73100. translate(m, m, [rotateOriginX, rotateOriginY]);
  73101. viewRect = viewRect.clone();
  73102. viewRect.applyTransform(m);
  73103. }
  73104. var viewBound = getBound(viewRect);
  73105. var mainBound = getBound(mainGroup.getBoundingRect());
  73106. var labelBound = getBound(labelGroup.getBoundingRect());
  73107. var mainPosition = mainGroup.position;
  73108. var labelsPosition = labelGroup.position;
  73109. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  73110. var labelPosOpt = layoutInfo.labelPosOpt;
  73111. if (isNaN(labelPosOpt)) { // '+' or '-'
  73112. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  73113. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73114. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  73115. }
  73116. else {
  73117. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  73118. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73119. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  73120. }
  73121. mainGroup.attr('position', mainPosition);
  73122. labelGroup.attr('position', labelsPosition);
  73123. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  73124. setOrigin(mainGroup);
  73125. setOrigin(labelGroup);
  73126. function setOrigin(targetGroup) {
  73127. var pos = targetGroup.position;
  73128. targetGroup.origin = [
  73129. viewBound[0][0] - pos[0],
  73130. viewBound[1][0] - pos[1]
  73131. ];
  73132. }
  73133. function getBound(rect) {
  73134. // [[xmin, xmax], [ymin, ymax]]
  73135. return [
  73136. [rect.x, rect.x + rect.width],
  73137. [rect.y, rect.y + rect.height]
  73138. ];
  73139. }
  73140. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  73141. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  73142. }
  73143. },
  73144. _createAxis: function (layoutInfo, timelineModel) {
  73145. var data = timelineModel.getData();
  73146. var axisType = timelineModel.get('axisType');
  73147. var scale = createScaleByModel(timelineModel, axisType);
  73148. // Customize scale. The `tickValue` is `dataIndex`.
  73149. scale.getTicks = function () {
  73150. return data.mapArray(['value'], function (value) {
  73151. return value;
  73152. });
  73153. };
  73154. var dataExtent = data.getDataExtent('value');
  73155. scale.setExtent(dataExtent[0], dataExtent[1]);
  73156. scale.niceTicks();
  73157. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  73158. axis.model = timelineModel;
  73159. return axis;
  73160. },
  73161. _createGroup: function (name) {
  73162. var newGroup = this['_' + name] = new Group();
  73163. this.group.add(newGroup);
  73164. return newGroup;
  73165. },
  73166. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  73167. var axisExtent = axis.getExtent();
  73168. if (!timelineModel.get('lineStyle.show')) {
  73169. return;
  73170. }
  73171. group.add(new Line({
  73172. shape: {
  73173. x1: axisExtent[0], y1: 0,
  73174. x2: axisExtent[1], y2: 0
  73175. },
  73176. style: extend(
  73177. {lineCap: 'round'},
  73178. timelineModel.getModel('lineStyle').getLineStyle()
  73179. ),
  73180. silent: true,
  73181. z2: 1
  73182. }));
  73183. },
  73184. /**
  73185. * @private
  73186. */
  73187. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  73188. var data = timelineModel.getData();
  73189. // Show all ticks, despite ignoring strategy.
  73190. var ticks = axis.scale.getTicks();
  73191. // The value is dataIndex, see the costomized scale.
  73192. each$27(ticks, function (value) {
  73193. var tickCoord = axis.dataToCoord(value);
  73194. var itemModel = data.getItemModel(value);
  73195. var itemStyleModel = itemModel.getModel('itemStyle');
  73196. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  73197. var symbolOpt = {
  73198. position: [tickCoord, 0],
  73199. onclick: bind$6(this._changeTimeline, this, value)
  73200. };
  73201. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  73202. setHoverStyle(el, hoverStyleModel.getItemStyle());
  73203. if (itemModel.get('tooltip')) {
  73204. el.dataIndex = value;
  73205. el.dataModel = timelineModel;
  73206. }
  73207. else {
  73208. el.dataIndex = el.dataModel = null;
  73209. }
  73210. }, this);
  73211. },
  73212. /**
  73213. * @private
  73214. */
  73215. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  73216. var labelModel = axis.getLabelModel();
  73217. if (!labelModel.get('show')) {
  73218. return;
  73219. }
  73220. var data = timelineModel.getData();
  73221. var labels = axis.getViewLabels();
  73222. each$27(labels, function (labelItem) {
  73223. // The tickValue is dataIndex, see the costomized scale.
  73224. var dataIndex = labelItem.tickValue;
  73225. var itemModel = data.getItemModel(dataIndex);
  73226. var normalLabelModel = itemModel.getModel('label');
  73227. var hoverLabelModel = itemModel.getModel('emphasis.label');
  73228. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  73229. var textEl = new Text({
  73230. position: [tickCoord, 0],
  73231. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  73232. onclick: bind$6(this._changeTimeline, this, dataIndex),
  73233. silent: false
  73234. });
  73235. setTextStyle(textEl.style, normalLabelModel, {
  73236. text: labelItem.formattedLabel,
  73237. textAlign: layoutInfo.labelAlign,
  73238. textVerticalAlign: layoutInfo.labelBaseline
  73239. });
  73240. group.add(textEl);
  73241. setHoverStyle(
  73242. textEl, setTextStyle({}, hoverLabelModel)
  73243. );
  73244. }, this);
  73245. },
  73246. /**
  73247. * @private
  73248. */
  73249. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  73250. var controlSize = layoutInfo.controlSize;
  73251. var rotation = layoutInfo.rotation;
  73252. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  73253. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  73254. var rect = [0, -controlSize / 2, controlSize, controlSize];
  73255. var playState = timelineModel.getPlayState();
  73256. var inverse = timelineModel.get('inverse', true);
  73257. makeBtn(
  73258. layoutInfo.nextBtnPosition,
  73259. 'controlStyle.nextIcon',
  73260. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  73261. );
  73262. makeBtn(
  73263. layoutInfo.prevBtnPosition,
  73264. 'controlStyle.prevIcon',
  73265. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  73266. );
  73267. makeBtn(
  73268. layoutInfo.playPosition,
  73269. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  73270. bind$6(this._handlePlayClick, this, !playState),
  73271. true
  73272. );
  73273. function makeBtn(position, iconPath, onclick, willRotate) {
  73274. if (!position) {
  73275. return;
  73276. }
  73277. var opt = {
  73278. position: position,
  73279. origin: [controlSize / 2, 0],
  73280. rotation: willRotate ? -rotation : 0,
  73281. rectHover: true,
  73282. style: itemStyle,
  73283. onclick: onclick
  73284. };
  73285. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  73286. group.add(btn);
  73287. setHoverStyle(btn, hoverStyle);
  73288. }
  73289. },
  73290. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  73291. var data = timelineModel.getData();
  73292. var currentIndex = timelineModel.getCurrentIndex();
  73293. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  73294. var me = this;
  73295. var callback = {
  73296. onCreate: function (pointer) {
  73297. pointer.draggable = true;
  73298. pointer.drift = bind$6(me._handlePointerDrag, me);
  73299. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  73300. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  73301. },
  73302. onUpdate: function (pointer) {
  73303. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  73304. }
  73305. };
  73306. // Reuse when exists, for animation and drag.
  73307. this._currentPointer = giveSymbol(
  73308. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  73309. );
  73310. },
  73311. _handlePlayClick: function (nextState) {
  73312. this._clearTimer();
  73313. this.api.dispatchAction({
  73314. type: 'timelinePlayChange',
  73315. playState: nextState,
  73316. from: this.uid
  73317. });
  73318. },
  73319. _handlePointerDrag: function (dx, dy, e) {
  73320. this._clearTimer();
  73321. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  73322. },
  73323. _handlePointerDragend: function (e) {
  73324. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  73325. },
  73326. _pointerChangeTimeline: function (mousePos, trigger) {
  73327. var toCoord = this._toAxisCoord(mousePos)[0];
  73328. var axis = this._axis;
  73329. var axisExtent = asc(axis.getExtent().slice());
  73330. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  73331. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  73332. this._currentPointer.position[0] = toCoord;
  73333. this._currentPointer.dirty();
  73334. var targetDataIndex = this._findNearestTick(toCoord);
  73335. var timelineModel = this.model;
  73336. if (trigger || (
  73337. targetDataIndex !== timelineModel.getCurrentIndex()
  73338. && timelineModel.get('realtime')
  73339. )) {
  73340. this._changeTimeline(targetDataIndex);
  73341. }
  73342. },
  73343. _doPlayStop: function () {
  73344. this._clearTimer();
  73345. if (this.model.getPlayState()) {
  73346. this._timer = setTimeout(
  73347. bind$6(handleFrame, this),
  73348. this.model.get('playInterval')
  73349. );
  73350. }
  73351. function handleFrame() {
  73352. // Do not cache
  73353. var timelineModel = this.model;
  73354. this._changeTimeline(
  73355. timelineModel.getCurrentIndex()
  73356. + (timelineModel.get('rewind', true) ? -1 : 1)
  73357. );
  73358. }
  73359. },
  73360. _toAxisCoord: function (vertex) {
  73361. var trans = this._mainGroup.getLocalTransform();
  73362. return applyTransform$1(vertex, trans, true);
  73363. },
  73364. _findNearestTick: function (axisCoord) {
  73365. var data = this.model.getData();
  73366. var dist = Infinity;
  73367. var targetDataIndex;
  73368. var axis = this._axis;
  73369. data.each(['value'], function (value, dataIndex) {
  73370. var coord = axis.dataToCoord(value);
  73371. var d = Math.abs(coord - axisCoord);
  73372. if (d < dist) {
  73373. dist = d;
  73374. targetDataIndex = dataIndex;
  73375. }
  73376. });
  73377. return targetDataIndex;
  73378. },
  73379. _clearTimer: function () {
  73380. if (this._timer) {
  73381. clearTimeout(this._timer);
  73382. this._timer = null;
  73383. }
  73384. },
  73385. _changeTimeline: function (nextIndex) {
  73386. var currentIndex = this.model.getCurrentIndex();
  73387. if (nextIndex === '+') {
  73388. nextIndex = currentIndex + 1;
  73389. }
  73390. else if (nextIndex === '-') {
  73391. nextIndex = currentIndex - 1;
  73392. }
  73393. this.api.dispatchAction({
  73394. type: 'timelineChange',
  73395. currentIndex: nextIndex,
  73396. from: this.uid
  73397. });
  73398. }
  73399. });
  73400. function getViewRect$4(model, api) {
  73401. return getLayoutRect(
  73402. model.getBoxLayoutParams(),
  73403. {
  73404. width: api.getWidth(),
  73405. height: api.getHeight()
  73406. },
  73407. model.get('padding')
  73408. );
  73409. }
  73410. function makeIcon(timelineModel, objPath, rect, opts) {
  73411. var icon = makePath(
  73412. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  73413. clone(opts || {}),
  73414. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  73415. 'center'
  73416. );
  73417. return icon;
  73418. }
  73419. /**
  73420. * Create symbol or update symbol
  73421. * opt: basic position and event handlers
  73422. */
  73423. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  73424. var color = itemStyleModel.get('color');
  73425. if (!symbol) {
  73426. var symbolType = hostModel.get('symbol');
  73427. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  73428. symbol.setStyle('strokeNoScale', true);
  73429. group.add(symbol);
  73430. callback && callback.onCreate(symbol);
  73431. }
  73432. else {
  73433. symbol.setColor(color);
  73434. group.add(symbol); // Group may be new, also need to add.
  73435. callback && callback.onUpdate(symbol);
  73436. }
  73437. // Style
  73438. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  73439. symbol.setStyle(itemStyle);
  73440. // Transform and events.
  73441. opt = merge({
  73442. rectHover: true,
  73443. z2: 100
  73444. }, opt, true);
  73445. var symbolSize = hostModel.get('symbolSize');
  73446. symbolSize = symbolSize instanceof Array
  73447. ? symbolSize.slice()
  73448. : [+symbolSize, +symbolSize];
  73449. symbolSize[0] /= 2;
  73450. symbolSize[1] /= 2;
  73451. opt.scale = symbolSize;
  73452. var symbolOffset = hostModel.get('symbolOffset');
  73453. if (symbolOffset) {
  73454. var pos = opt.position = opt.position || [0, 0];
  73455. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  73456. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  73457. }
  73458. var symbolRotate = hostModel.get('symbolRotate');
  73459. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  73460. symbol.attr(opt);
  73461. // FIXME
  73462. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  73463. // getBoundingRect will return wrong result.
  73464. // (This is supposed to be resolved in zrender, but it is a little difficult to
  73465. // leverage performance and auto updateTransform)
  73466. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  73467. symbol.updateTransform();
  73468. return symbol;
  73469. }
  73470. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  73471. if (pointer.dragging) {
  73472. return;
  73473. }
  73474. var pointerModel = timelineModel.getModel('checkpointStyle');
  73475. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  73476. if (noAnimation || !pointerModel.get('animation', true)) {
  73477. pointer.attr({position: [toCoord, 0]});
  73478. }
  73479. else {
  73480. pointer.stopAnimation(true);
  73481. pointer.animateTo(
  73482. {position: [toCoord, 0]},
  73483. pointerModel.get('animationDuration', true),
  73484. pointerModel.get('animationEasing', true)
  73485. );
  73486. }
  73487. }
  73488. /*
  73489. * Licensed to the Apache Software Foundation (ASF) under one
  73490. * or more contributor license agreements. See the NOTICE file
  73491. * distributed with this work for additional information
  73492. * regarding copyright ownership. The ASF licenses this file
  73493. * to you under the Apache License, Version 2.0 (the
  73494. * "License"); you may not use this file except in compliance
  73495. * with the License. You may obtain a copy of the License at
  73496. *
  73497. * http://www.apache.org/licenses/LICENSE-2.0
  73498. *
  73499. * Unless required by applicable law or agreed to in writing,
  73500. * software distributed under the License is distributed on an
  73501. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73502. * KIND, either express or implied. See the License for the
  73503. * specific language governing permissions and limitations
  73504. * under the License.
  73505. */
  73506. /**
  73507. * DataZoom component entry
  73508. */
  73509. registerPreprocessor(preprocessor$3);
  73510. /*
  73511. * Licensed to the Apache Software Foundation (ASF) under one
  73512. * or more contributor license agreements. See the NOTICE file
  73513. * distributed with this work for additional information
  73514. * regarding copyright ownership. The ASF licenses this file
  73515. * to you under the Apache License, Version 2.0 (the
  73516. * "License"); you may not use this file except in compliance
  73517. * with the License. You may obtain a copy of the License at
  73518. *
  73519. * http://www.apache.org/licenses/LICENSE-2.0
  73520. *
  73521. * Unless required by applicable law or agreed to in writing,
  73522. * software distributed under the License is distributed on an
  73523. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73524. * KIND, either express or implied. See the License for the
  73525. * specific language governing permissions and limitations
  73526. * under the License.
  73527. */
  73528. var ToolboxModel = extendComponentModel({
  73529. type: 'toolbox',
  73530. layoutMode: {
  73531. type: 'box',
  73532. ignoreSize: true
  73533. },
  73534. optionUpdated: function () {
  73535. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  73536. each$1(this.option.feature, function (featureOpt, featureName) {
  73537. var Feature = get$1(featureName);
  73538. Feature && merge(featureOpt, Feature.defaultOption);
  73539. });
  73540. },
  73541. defaultOption: {
  73542. show: true,
  73543. z: 6,
  73544. zlevel: 0,
  73545. orient: 'horizontal',
  73546. left: 'right',
  73547. top: 'top',
  73548. // right
  73549. // bottom
  73550. backgroundColor: 'transparent',
  73551. borderColor: '#ccc',
  73552. borderRadius: 0,
  73553. borderWidth: 0,
  73554. padding: 5,
  73555. itemSize: 15,
  73556. itemGap: 8,
  73557. showTitle: true,
  73558. iconStyle: {
  73559. borderColor: '#666',
  73560. color: 'none'
  73561. },
  73562. emphasis: {
  73563. iconStyle: {
  73564. borderColor: '#3E98C5'
  73565. }
  73566. }
  73567. // textStyle: {},
  73568. // feature
  73569. }
  73570. });
  73571. /*
  73572. * Licensed to the Apache Software Foundation (ASF) under one
  73573. * or more contributor license agreements. See the NOTICE file
  73574. * distributed with this work for additional information
  73575. * regarding copyright ownership. The ASF licenses this file
  73576. * to you under the Apache License, Version 2.0 (the
  73577. * "License"); you may not use this file except in compliance
  73578. * with the License. You may obtain a copy of the License at
  73579. *
  73580. * http://www.apache.org/licenses/LICENSE-2.0
  73581. *
  73582. * Unless required by applicable law or agreed to in writing,
  73583. * software distributed under the License is distributed on an
  73584. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73585. * KIND, either express or implied. See the License for the
  73586. * specific language governing permissions and limitations
  73587. * under the License.
  73588. */
  73589. extendComponentView({
  73590. type: 'toolbox',
  73591. render: function (toolboxModel, ecModel, api, payload) {
  73592. var group = this.group;
  73593. group.removeAll();
  73594. if (!toolboxModel.get('show')) {
  73595. return;
  73596. }
  73597. var itemSize = +toolboxModel.get('itemSize');
  73598. var featureOpts = toolboxModel.get('feature') || {};
  73599. var features = this._features || (this._features = {});
  73600. var featureNames = [];
  73601. each$1(featureOpts, function (opt, name) {
  73602. featureNames.push(name);
  73603. });
  73604. (new DataDiffer(this._featureNames || [], featureNames))
  73605. .add(processFeature)
  73606. .update(processFeature)
  73607. .remove(curry(processFeature, null))
  73608. .execute();
  73609. // Keep for diff.
  73610. this._featureNames = featureNames;
  73611. function processFeature(newIndex, oldIndex) {
  73612. var featureName = featureNames[newIndex];
  73613. var oldName = featureNames[oldIndex];
  73614. var featureOpt = featureOpts[featureName];
  73615. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  73616. var feature;
  73617. if (featureName && !oldName) { // Create
  73618. if (isUserFeatureName(featureName)) {
  73619. feature = {
  73620. model: featureModel,
  73621. onclick: featureModel.option.onclick,
  73622. featureName: featureName
  73623. };
  73624. }
  73625. else {
  73626. var Feature = get$1(featureName);
  73627. if (!Feature) {
  73628. return;
  73629. }
  73630. feature = new Feature(featureModel, ecModel, api);
  73631. }
  73632. features[featureName] = feature;
  73633. }
  73634. else {
  73635. feature = features[oldName];
  73636. // If feature does not exsit.
  73637. if (!feature) {
  73638. return;
  73639. }
  73640. feature.model = featureModel;
  73641. feature.ecModel = ecModel;
  73642. feature.api = api;
  73643. }
  73644. if (!featureName && oldName) {
  73645. feature.dispose && feature.dispose(ecModel, api);
  73646. return;
  73647. }
  73648. if (!featureModel.get('show') || feature.unusable) {
  73649. feature.remove && feature.remove(ecModel, api);
  73650. return;
  73651. }
  73652. createIconPaths(featureModel, feature, featureName);
  73653. featureModel.setIconStatus = function (iconName, status) {
  73654. var option = this.option;
  73655. var iconPaths = this.iconPaths;
  73656. option.iconStatus = option.iconStatus || {};
  73657. option.iconStatus[iconName] = status;
  73658. // FIXME
  73659. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  73660. };
  73661. if (feature.render) {
  73662. feature.render(featureModel, ecModel, api, payload);
  73663. }
  73664. }
  73665. function createIconPaths(featureModel, feature, featureName) {
  73666. var iconStyleModel = featureModel.getModel('iconStyle');
  73667. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  73668. // If one feature has mutiple icon. they are orginaized as
  73669. // {
  73670. // icon: {
  73671. // foo: '',
  73672. // bar: ''
  73673. // },
  73674. // title: {
  73675. // foo: '',
  73676. // bar: ''
  73677. // }
  73678. // }
  73679. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  73680. var titles = featureModel.get('title') || {};
  73681. if (typeof icons === 'string') {
  73682. var icon = icons;
  73683. var title = titles;
  73684. icons = {};
  73685. titles = {};
  73686. icons[featureName] = icon;
  73687. titles[featureName] = title;
  73688. }
  73689. var iconPaths = featureModel.iconPaths = {};
  73690. each$1(icons, function (iconStr, iconName) {
  73691. var path = createIcon(
  73692. iconStr,
  73693. {},
  73694. {
  73695. x: -itemSize / 2,
  73696. y: -itemSize / 2,
  73697. width: itemSize,
  73698. height: itemSize
  73699. }
  73700. );
  73701. path.setStyle(iconStyleModel.getItemStyle());
  73702. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  73703. setHoverStyle(path);
  73704. if (toolboxModel.get('showTitle')) {
  73705. path.__title = titles[iconName];
  73706. path.on('mouseover', function () {
  73707. // Should not reuse above hoverStyle, which might be modified.
  73708. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  73709. path.setStyle({
  73710. text: titles[iconName],
  73711. textPosition: hoverStyle.textPosition || 'bottom',
  73712. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  73713. textAlign: hoverStyle.textAlign || 'center'
  73714. });
  73715. })
  73716. .on('mouseout', function () {
  73717. path.setStyle({
  73718. textFill: null
  73719. });
  73720. });
  73721. }
  73722. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  73723. group.add(path);
  73724. path.on('click', bind(
  73725. feature.onclick, feature, ecModel, api, iconName
  73726. ));
  73727. iconPaths[iconName] = path;
  73728. });
  73729. }
  73730. layout$3(group, toolboxModel, api);
  73731. // Render background after group is layout
  73732. // FIXME
  73733. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  73734. // Adjust icon title positions to avoid them out of screen
  73735. group.eachChild(function (icon) {
  73736. var titleText = icon.__title;
  73737. var hoverStyle = icon.hoverStyle;
  73738. // May be background element
  73739. if (hoverStyle && titleText) {
  73740. var rect = getBoundingRect(
  73741. titleText, makeFont(hoverStyle)
  73742. );
  73743. var offsetX = icon.position[0] + group.position[0];
  73744. var offsetY = icon.position[1] + group.position[1] + itemSize;
  73745. var needPutOnTop = false;
  73746. if (offsetY + rect.height > api.getHeight()) {
  73747. hoverStyle.textPosition = 'top';
  73748. needPutOnTop = true;
  73749. }
  73750. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  73751. if (offsetX + rect.width / 2 > api.getWidth()) {
  73752. hoverStyle.textPosition = ['100%', topOffset];
  73753. hoverStyle.textAlign = 'right';
  73754. }
  73755. else if (offsetX - rect.width / 2 < 0) {
  73756. hoverStyle.textPosition = [0, topOffset];
  73757. hoverStyle.textAlign = 'left';
  73758. }
  73759. }
  73760. });
  73761. },
  73762. updateView: function (toolboxModel, ecModel, api, payload) {
  73763. each$1(this._features, function (feature) {
  73764. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  73765. });
  73766. },
  73767. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  73768. // zrUtil.each(this._features, function (feature) {
  73769. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  73770. // });
  73771. // },
  73772. remove: function (ecModel, api) {
  73773. each$1(this._features, function (feature) {
  73774. feature.remove && feature.remove(ecModel, api);
  73775. });
  73776. this.group.removeAll();
  73777. },
  73778. dispose: function (ecModel, api) {
  73779. each$1(this._features, function (feature) {
  73780. feature.dispose && feature.dispose(ecModel, api);
  73781. });
  73782. }
  73783. });
  73784. function isUserFeatureName(featureName) {
  73785. return featureName.indexOf('my') === 0;
  73786. }
  73787. /*
  73788. * Licensed to the Apache Software Foundation (ASF) under one
  73789. * or more contributor license agreements. See the NOTICE file
  73790. * distributed with this work for additional information
  73791. * regarding copyright ownership. The ASF licenses this file
  73792. * to you under the Apache License, Version 2.0 (the
  73793. * "License"); you may not use this file except in compliance
  73794. * with the License. You may obtain a copy of the License at
  73795. *
  73796. * http://www.apache.org/licenses/LICENSE-2.0
  73797. *
  73798. * Unless required by applicable law or agreed to in writing,
  73799. * software distributed under the License is distributed on an
  73800. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73801. * KIND, either express or implied. See the License for the
  73802. * specific language governing permissions and limitations
  73803. * under the License.
  73804. */
  73805. var saveAsImageLang = lang.toolbox.saveAsImage;
  73806. function SaveAsImage(model) {
  73807. this.model = model;
  73808. }
  73809. SaveAsImage.defaultOption = {
  73810. show: true,
  73811. 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',
  73812. title: saveAsImageLang.title,
  73813. type: 'png',
  73814. // Default use option.backgroundColor
  73815. // backgroundColor: '#fff',
  73816. name: '',
  73817. excludeComponents: ['toolbox'],
  73818. pixelRatio: 1,
  73819. lang: saveAsImageLang.lang.slice()
  73820. };
  73821. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  73822. var proto$4 = SaveAsImage.prototype;
  73823. proto$4.onclick = function (ecModel, api) {
  73824. var model = this.model;
  73825. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  73826. var $a = document.createElement('a');
  73827. var type = model.get('type', true) || 'png';
  73828. $a.download = title + '.' + type;
  73829. $a.target = '_blank';
  73830. var url = api.getConnectedDataURL({
  73831. type: type,
  73832. backgroundColor: model.get('backgroundColor', true)
  73833. || ecModel.get('backgroundColor') || '#fff',
  73834. excludeComponents: model.get('excludeComponents'),
  73835. pixelRatio: model.get('pixelRatio')
  73836. });
  73837. $a.href = url;
  73838. // Chrome and Firefox
  73839. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  73840. var evt = new MouseEvent('click', {
  73841. view: window,
  73842. bubbles: true,
  73843. cancelable: false
  73844. });
  73845. $a.dispatchEvent(evt);
  73846. }
  73847. // IE
  73848. else {
  73849. if (window.navigator.msSaveOrOpenBlob) {
  73850. var bstr = atob(url.split(',')[1]);
  73851. var n = bstr.length;
  73852. var u8arr = new Uint8Array(n);
  73853. while(n--) {
  73854. u8arr[n] = bstr.charCodeAt(n);
  73855. }
  73856. var blob = new Blob([u8arr]);
  73857. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  73858. }
  73859. else {
  73860. var lang$$1 = model.get('lang');
  73861. var html = '' +
  73862. '<body style="margin:0;">' +
  73863. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  73864. '</body>';
  73865. var tab = window.open();
  73866. tab.document.write(html);
  73867. }
  73868. }
  73869. };
  73870. register$1(
  73871. 'saveAsImage', SaveAsImage
  73872. );
  73873. /*
  73874. * Licensed to the Apache Software Foundation (ASF) under one
  73875. * or more contributor license agreements. See the NOTICE file
  73876. * distributed with this work for additional information
  73877. * regarding copyright ownership. The ASF licenses this file
  73878. * to you under the Apache License, Version 2.0 (the
  73879. * "License"); you may not use this file except in compliance
  73880. * with the License. You may obtain a copy of the License at
  73881. *
  73882. * http://www.apache.org/licenses/LICENSE-2.0
  73883. *
  73884. * Unless required by applicable law or agreed to in writing,
  73885. * software distributed under the License is distributed on an
  73886. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73887. * KIND, either express or implied. See the License for the
  73888. * specific language governing permissions and limitations
  73889. * under the License.
  73890. */
  73891. var magicTypeLang = lang.toolbox.magicType;
  73892. function MagicType(model) {
  73893. this.model = model;
  73894. }
  73895. MagicType.defaultOption = {
  73896. show: true,
  73897. type: [],
  73898. // Icon group
  73899. icon: {
  73900. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  73901. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  73902. 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
  73903. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  73904. },
  73905. // `line`, `bar`, `stack`, `tiled`
  73906. title: clone(magicTypeLang.title),
  73907. option: {},
  73908. seriesIndex: {}
  73909. };
  73910. var proto$5 = MagicType.prototype;
  73911. proto$5.getIcons = function () {
  73912. var model = this.model;
  73913. var availableIcons = model.get('icon');
  73914. var icons = {};
  73915. each$1(model.get('type'), function (type) {
  73916. if (availableIcons[type]) {
  73917. icons[type] = availableIcons[type];
  73918. }
  73919. });
  73920. return icons;
  73921. };
  73922. var seriesOptGenreator = {
  73923. 'line': function (seriesType, seriesId, seriesModel, model) {
  73924. if (seriesType === 'bar') {
  73925. return merge({
  73926. id: seriesId,
  73927. type: 'line',
  73928. // Preserve data related option
  73929. data: seriesModel.get('data'),
  73930. stack: seriesModel.get('stack'),
  73931. markPoint: seriesModel.get('markPoint'),
  73932. markLine: seriesModel.get('markLine')
  73933. }, model.get('option.line') || {}, true);
  73934. }
  73935. },
  73936. 'bar': function (seriesType, seriesId, seriesModel, model) {
  73937. if (seriesType === 'line') {
  73938. return merge({
  73939. id: seriesId,
  73940. type: 'bar',
  73941. // Preserve data related option
  73942. data: seriesModel.get('data'),
  73943. stack: seriesModel.get('stack'),
  73944. markPoint: seriesModel.get('markPoint'),
  73945. markLine: seriesModel.get('markLine')
  73946. }, model.get('option.bar') || {}, true);
  73947. }
  73948. },
  73949. 'stack': function (seriesType, seriesId, seriesModel, model) {
  73950. if (seriesType === 'line' || seriesType === 'bar') {
  73951. return merge({
  73952. id: seriesId,
  73953. stack: '__ec_magicType_stack__'
  73954. }, model.get('option.stack') || {}, true);
  73955. }
  73956. },
  73957. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  73958. if (seriesType === 'line' || seriesType === 'bar') {
  73959. return merge({
  73960. id: seriesId,
  73961. stack: ''
  73962. }, model.get('option.tiled') || {}, true);
  73963. }
  73964. }
  73965. };
  73966. var radioTypes = [
  73967. ['line', 'bar'],
  73968. ['stack', 'tiled']
  73969. ];
  73970. proto$5.onclick = function (ecModel, api, type) {
  73971. var model = this.model;
  73972. var seriesIndex = model.get('seriesIndex.' + type);
  73973. // Not supported magicType
  73974. if (!seriesOptGenreator[type]) {
  73975. return;
  73976. }
  73977. var newOption = {
  73978. series: []
  73979. };
  73980. var generateNewSeriesTypes = function (seriesModel) {
  73981. var seriesType = seriesModel.subType;
  73982. var seriesId = seriesModel.id;
  73983. var newSeriesOpt = seriesOptGenreator[type](
  73984. seriesType, seriesId, seriesModel, model
  73985. );
  73986. if (newSeriesOpt) {
  73987. // PENDING If merge original option?
  73988. defaults(newSeriesOpt, seriesModel.option);
  73989. newOption.series.push(newSeriesOpt);
  73990. }
  73991. // Modify boundaryGap
  73992. var coordSys = seriesModel.coordinateSystem;
  73993. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  73994. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  73995. if (categoryAxis) {
  73996. var axisDim = categoryAxis.dim;
  73997. var axisType = axisDim + 'Axis';
  73998. var axisModel = ecModel.queryComponents({
  73999. mainType: axisType,
  74000. index: seriesModel.get(name + 'Index'),
  74001. id: seriesModel.get(name + 'Id')
  74002. })[0];
  74003. var axisIndex = axisModel.componentIndex;
  74004. newOption[axisType] = newOption[axisType] || [];
  74005. for (var i = 0; i <= axisIndex; i++) {
  74006. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  74007. }
  74008. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  74009. }
  74010. }
  74011. };
  74012. each$1(radioTypes, function (radio) {
  74013. if (indexOf(radio, type) >= 0) {
  74014. each$1(radio, function (item) {
  74015. model.setIconStatus(item, 'normal');
  74016. });
  74017. }
  74018. });
  74019. model.setIconStatus(type, 'emphasis');
  74020. ecModel.eachComponent(
  74021. {
  74022. mainType: 'series',
  74023. query: seriesIndex == null ? null : {
  74024. seriesIndex: seriesIndex
  74025. }
  74026. }, generateNewSeriesTypes
  74027. );
  74028. api.dispatchAction({
  74029. type: 'changeMagicType',
  74030. currentType: type,
  74031. newOption: newOption
  74032. });
  74033. };
  74034. registerAction({
  74035. type: 'changeMagicType',
  74036. event: 'magicTypeChanged',
  74037. update: 'prepareAndUpdate'
  74038. }, function (payload, ecModel) {
  74039. ecModel.mergeOption(payload.newOption);
  74040. });
  74041. register$1('magicType', MagicType);
  74042. /*
  74043. * Licensed to the Apache Software Foundation (ASF) under one
  74044. * or more contributor license agreements. See the NOTICE file
  74045. * distributed with this work for additional information
  74046. * regarding copyright ownership. The ASF licenses this file
  74047. * to you under the Apache License, Version 2.0 (the
  74048. * "License"); you may not use this file except in compliance
  74049. * with the License. You may obtain a copy of the License at
  74050. *
  74051. * http://www.apache.org/licenses/LICENSE-2.0
  74052. *
  74053. * Unless required by applicable law or agreed to in writing,
  74054. * software distributed under the License is distributed on an
  74055. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74056. * KIND, either express or implied. See the License for the
  74057. * specific language governing permissions and limitations
  74058. * under the License.
  74059. */
  74060. var dataViewLang = lang.toolbox.dataView;
  74061. var BLOCK_SPLITER = new Array(60).join('-');
  74062. var ITEM_SPLITER = '\t';
  74063. /**
  74064. * Group series into two types
  74065. * 1. on category axis, like line, bar
  74066. * 2. others, like scatter, pie
  74067. * @param {module:echarts/model/Global} ecModel
  74068. * @return {Object}
  74069. * @inner
  74070. */
  74071. function groupSeries(ecModel) {
  74072. var seriesGroupByCategoryAxis = {};
  74073. var otherSeries = [];
  74074. var meta = [];
  74075. ecModel.eachRawSeries(function (seriesModel) {
  74076. var coordSys = seriesModel.coordinateSystem;
  74077. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  74078. var baseAxis = coordSys.getBaseAxis();
  74079. if (baseAxis.type === 'category') {
  74080. var key = baseAxis.dim + '_' + baseAxis.index;
  74081. if (!seriesGroupByCategoryAxis[key]) {
  74082. seriesGroupByCategoryAxis[key] = {
  74083. categoryAxis: baseAxis,
  74084. valueAxis: coordSys.getOtherAxis(baseAxis),
  74085. series: []
  74086. };
  74087. meta.push({
  74088. axisDim: baseAxis.dim,
  74089. axisIndex: baseAxis.index
  74090. });
  74091. }
  74092. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  74093. }
  74094. else {
  74095. otherSeries.push(seriesModel);
  74096. }
  74097. }
  74098. else {
  74099. otherSeries.push(seriesModel);
  74100. }
  74101. });
  74102. return {
  74103. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  74104. other: otherSeries,
  74105. meta: meta
  74106. };
  74107. }
  74108. /**
  74109. * Assemble content of series on cateogory axis
  74110. * @param {Array.<module:echarts/model/Series>} series
  74111. * @return {string}
  74112. * @inner
  74113. */
  74114. function assembleSeriesWithCategoryAxis(series) {
  74115. var tables = [];
  74116. each$1(series, function (group, key) {
  74117. var categoryAxis = group.categoryAxis;
  74118. var valueAxis = group.valueAxis;
  74119. var valueAxisDim = valueAxis.dim;
  74120. var headers = [' '].concat(map(group.series, function (series) {
  74121. return series.name;
  74122. }));
  74123. var columns = [categoryAxis.model.getCategories()];
  74124. each$1(group.series, function (series) {
  74125. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  74126. return val;
  74127. }));
  74128. });
  74129. // Assemble table content
  74130. var lines = [headers.join(ITEM_SPLITER)];
  74131. for (var i = 0; i < columns[0].length; i++) {
  74132. var items = [];
  74133. for (var j = 0; j < columns.length; j++) {
  74134. items.push(columns[j][i]);
  74135. }
  74136. lines.push(items.join(ITEM_SPLITER));
  74137. }
  74138. tables.push(lines.join('\n'));
  74139. });
  74140. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  74141. }
  74142. /**
  74143. * Assemble content of other series
  74144. * @param {Array.<module:echarts/model/Series>} series
  74145. * @return {string}
  74146. * @inner
  74147. */
  74148. function assembleOtherSeries(series) {
  74149. return map(series, function (series) {
  74150. var data = series.getRawData();
  74151. var lines = [series.name];
  74152. var vals = [];
  74153. data.each(data.dimensions, function () {
  74154. var argLen = arguments.length;
  74155. var dataIndex = arguments[argLen - 1];
  74156. var name = data.getName(dataIndex);
  74157. for (var i = 0; i < argLen - 1; i++) {
  74158. vals[i] = arguments[i];
  74159. }
  74160. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  74161. });
  74162. return lines.join('\n');
  74163. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  74164. }
  74165. /**
  74166. * @param {module:echarts/model/Global}
  74167. * @return {Object}
  74168. * @inner
  74169. */
  74170. function getContentFromModel(ecModel) {
  74171. var result = groupSeries(ecModel);
  74172. return {
  74173. value: filter([
  74174. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  74175. assembleOtherSeries(result.other)
  74176. ], function (str) {
  74177. return str.replace(/[\n\t\s]/g, '');
  74178. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  74179. meta: result.meta
  74180. };
  74181. }
  74182. function trim$1(str) {
  74183. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  74184. }
  74185. /**
  74186. * If a block is tsv format
  74187. */
  74188. function isTSVFormat(block) {
  74189. // Simple method to find out if a block is tsv format
  74190. var firstLine = block.slice(0, block.indexOf('\n'));
  74191. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  74192. return true;
  74193. }
  74194. }
  74195. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  74196. /**
  74197. * @param {string} tsv
  74198. * @return {Object}
  74199. */
  74200. function parseTSVContents(tsv) {
  74201. var tsvLines = tsv.split(/\n+/g);
  74202. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  74203. var categories = [];
  74204. var series = map(headers, function (header) {
  74205. return {
  74206. name: header,
  74207. data: []
  74208. };
  74209. });
  74210. for (var i = 0; i < tsvLines.length; i++) {
  74211. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  74212. categories.push(items.shift());
  74213. for (var j = 0; j < items.length; j++) {
  74214. series[j] && (series[j].data[i] = items[j]);
  74215. }
  74216. }
  74217. return {
  74218. series: series,
  74219. categories: categories
  74220. };
  74221. }
  74222. /**
  74223. * @param {string} str
  74224. * @return {Array.<Object>}
  74225. * @inner
  74226. */
  74227. function parseListContents(str) {
  74228. var lines = str.split(/\n+/g);
  74229. var seriesName = trim$1(lines.shift());
  74230. var data = [];
  74231. for (var i = 0; i < lines.length; i++) {
  74232. var items = trim$1(lines[i]).split(itemSplitRegex);
  74233. var name = '';
  74234. var value;
  74235. var hasName = false;
  74236. if (isNaN(items[0])) { // First item is name
  74237. hasName = true;
  74238. name = items[0];
  74239. items = items.slice(1);
  74240. data[i] = {
  74241. name: name,
  74242. value: []
  74243. };
  74244. value = data[i].value;
  74245. }
  74246. else {
  74247. value = data[i] = [];
  74248. }
  74249. for (var j = 0; j < items.length; j++) {
  74250. value.push(+items[j]);
  74251. }
  74252. if (value.length === 1) {
  74253. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  74254. }
  74255. }
  74256. return {
  74257. name: seriesName,
  74258. data: data
  74259. };
  74260. }
  74261. /**
  74262. * @param {string} str
  74263. * @param {Array.<Object>} blockMetaList
  74264. * @return {Object}
  74265. * @inner
  74266. */
  74267. function parseContents(str, blockMetaList) {
  74268. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  74269. var newOption = {
  74270. series: []
  74271. };
  74272. each$1(blocks, function (block, idx) {
  74273. if (isTSVFormat(block)) {
  74274. var result = parseTSVContents(block);
  74275. var blockMeta = blockMetaList[idx];
  74276. var axisKey = blockMeta.axisDim + 'Axis';
  74277. if (blockMeta) {
  74278. newOption[axisKey] = newOption[axisKey] || [];
  74279. newOption[axisKey][blockMeta.axisIndex] = {
  74280. data: result.categories
  74281. };
  74282. newOption.series = newOption.series.concat(result.series);
  74283. }
  74284. }
  74285. else {
  74286. var result = parseListContents(block);
  74287. newOption.series.push(result);
  74288. }
  74289. });
  74290. return newOption;
  74291. }
  74292. /**
  74293. * @alias {module:echarts/component/toolbox/feature/DataView}
  74294. * @constructor
  74295. * @param {module:echarts/model/Model} model
  74296. */
  74297. function DataView(model) {
  74298. this._dom = null;
  74299. this.model = model;
  74300. }
  74301. DataView.defaultOption = {
  74302. show: true,
  74303. readOnly: false,
  74304. optionToContent: null,
  74305. contentToOption: null,
  74306. 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',
  74307. title: clone(dataViewLang.title),
  74308. lang: clone(dataViewLang.lang),
  74309. backgroundColor: '#fff',
  74310. textColor: '#000',
  74311. textareaColor: '#fff',
  74312. textareaBorderColor: '#333',
  74313. buttonColor: '#c23531',
  74314. buttonTextColor: '#fff'
  74315. };
  74316. DataView.prototype.onclick = function (ecModel, api) {
  74317. var container = api.getDom();
  74318. var model = this.model;
  74319. if (this._dom) {
  74320. container.removeChild(this._dom);
  74321. }
  74322. var root = document.createElement('div');
  74323. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  74324. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  74325. // Create elements
  74326. var header = document.createElement('h4');
  74327. var lang$$1 = model.get('lang') || [];
  74328. header.innerHTML = lang$$1[0] || model.get('title');
  74329. header.style.cssText = 'margin: 10px 20px;';
  74330. header.style.color = model.get('textColor');
  74331. var viewMain = document.createElement('div');
  74332. var textarea = document.createElement('textarea');
  74333. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  74334. var optionToContent = model.get('optionToContent');
  74335. var contentToOption = model.get('contentToOption');
  74336. var result = getContentFromModel(ecModel);
  74337. if (typeof optionToContent === 'function') {
  74338. var htmlOrDom = optionToContent(api.getOption());
  74339. if (typeof htmlOrDom === 'string') {
  74340. viewMain.innerHTML = htmlOrDom;
  74341. }
  74342. else if (isDom(htmlOrDom)) {
  74343. viewMain.appendChild(htmlOrDom);
  74344. }
  74345. }
  74346. else {
  74347. // Use default textarea
  74348. viewMain.appendChild(textarea);
  74349. textarea.readOnly = model.get('readOnly');
  74350. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  74351. textarea.style.color = model.get('textColor');
  74352. textarea.style.borderColor = model.get('textareaBorderColor');
  74353. textarea.style.backgroundColor = model.get('textareaColor');
  74354. textarea.value = result.value;
  74355. }
  74356. var blockMetaList = result.meta;
  74357. var buttonContainer = document.createElement('div');
  74358. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  74359. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  74360. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  74361. var closeButton = document.createElement('div');
  74362. var refreshButton = document.createElement('div');
  74363. buttonStyle += ';background-color:' + model.get('buttonColor');
  74364. buttonStyle += ';color:' + model.get('buttonTextColor');
  74365. var self = this;
  74366. function close() {
  74367. container.removeChild(root);
  74368. self._dom = null;
  74369. }
  74370. addEventListener(closeButton, 'click', close);
  74371. addEventListener(refreshButton, 'click', function () {
  74372. var newOption;
  74373. try {
  74374. if (typeof contentToOption === 'function') {
  74375. newOption = contentToOption(viewMain, api.getOption());
  74376. }
  74377. else {
  74378. newOption = parseContents(textarea.value, blockMetaList);
  74379. }
  74380. }
  74381. catch (e) {
  74382. close();
  74383. throw new Error('Data view format error ' + e);
  74384. }
  74385. if (newOption) {
  74386. api.dispatchAction({
  74387. type: 'changeDataView',
  74388. newOption: newOption
  74389. });
  74390. }
  74391. close();
  74392. });
  74393. closeButton.innerHTML = lang$$1[1];
  74394. refreshButton.innerHTML = lang$$1[2];
  74395. refreshButton.style.cssText = buttonStyle;
  74396. closeButton.style.cssText = buttonStyle;
  74397. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  74398. buttonContainer.appendChild(closeButton);
  74399. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  74400. addEventListener(textarea, 'keydown', function (e) {
  74401. if ((e.keyCode || e.which) === 9) {
  74402. // get caret position/selection
  74403. var val = this.value;
  74404. var start = this.selectionStart;
  74405. var end = this.selectionEnd;
  74406. // set textarea value to: text before caret + tab + text after caret
  74407. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  74408. // put caret at right position again
  74409. this.selectionStart = this.selectionEnd = start + 1;
  74410. // prevent the focus lose
  74411. stop(e);
  74412. }
  74413. });
  74414. root.appendChild(header);
  74415. root.appendChild(viewMain);
  74416. root.appendChild(buttonContainer);
  74417. viewMain.style.height = (container.clientHeight - 80) + 'px';
  74418. container.appendChild(root);
  74419. this._dom = root;
  74420. };
  74421. DataView.prototype.remove = function (ecModel, api) {
  74422. this._dom && api.getDom().removeChild(this._dom);
  74423. };
  74424. DataView.prototype.dispose = function (ecModel, api) {
  74425. this.remove(ecModel, api);
  74426. };
  74427. /**
  74428. * @inner
  74429. */
  74430. function tryMergeDataOption(newData, originalData) {
  74431. return map(newData, function (newVal, idx) {
  74432. var original = originalData && originalData[idx];
  74433. if (isObject$1(original) && !isArray(original)) {
  74434. if (isObject$1(newVal) && !isArray(newVal)) {
  74435. newVal = newVal.value;
  74436. }
  74437. // Original data has option
  74438. return defaults({
  74439. value: newVal
  74440. }, original);
  74441. }
  74442. else {
  74443. return newVal;
  74444. }
  74445. });
  74446. }
  74447. register$1('dataView', DataView);
  74448. registerAction({
  74449. type: 'changeDataView',
  74450. event: 'dataViewChanged',
  74451. update: 'prepareAndUpdate'
  74452. }, function (payload, ecModel) {
  74453. var newSeriesOptList = [];
  74454. each$1(payload.newOption.series, function (seriesOpt) {
  74455. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  74456. if (!seriesModel) {
  74457. // New created series
  74458. // Geuss the series type
  74459. newSeriesOptList.push(extend({
  74460. // Default is scatter
  74461. type: 'scatter'
  74462. }, seriesOpt));
  74463. }
  74464. else {
  74465. var originalData = seriesModel.get('data');
  74466. newSeriesOptList.push({
  74467. name: seriesOpt.name,
  74468. data: tryMergeDataOption(seriesOpt.data, originalData)
  74469. });
  74470. }
  74471. });
  74472. ecModel.mergeOption(defaults({
  74473. series: newSeriesOptList
  74474. }, payload.newOption));
  74475. });
  74476. /*
  74477. * Licensed to the Apache Software Foundation (ASF) under one
  74478. * or more contributor license agreements. See the NOTICE file
  74479. * distributed with this work for additional information
  74480. * regarding copyright ownership. The ASF licenses this file
  74481. * to you under the Apache License, Version 2.0 (the
  74482. * "License"); you may not use this file except in compliance
  74483. * with the License. You may obtain a copy of the License at
  74484. *
  74485. * http://www.apache.org/licenses/LICENSE-2.0
  74486. *
  74487. * Unless required by applicable law or agreed to in writing,
  74488. * software distributed under the License is distributed on an
  74489. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74490. * KIND, either express or implied. See the License for the
  74491. * specific language governing permissions and limitations
  74492. * under the License.
  74493. */
  74494. var each$29 = each$1;
  74495. var ATTR$2 = '\0_ec_hist_store';
  74496. /**
  74497. * @param {module:echarts/model/Global} ecModel
  74498. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  74499. */
  74500. function push(ecModel, newSnapshot) {
  74501. var store = giveStore$1(ecModel);
  74502. // If previous dataZoom can not be found,
  74503. // complete an range with current range.
  74504. each$29(newSnapshot, function (batchItem, dataZoomId) {
  74505. var i = store.length - 1;
  74506. for (; i >= 0; i--) {
  74507. var snapshot = store[i];
  74508. if (snapshot[dataZoomId]) {
  74509. break;
  74510. }
  74511. }
  74512. if (i < 0) {
  74513. // No origin range set, create one by current range.
  74514. var dataZoomModel = ecModel.queryComponents(
  74515. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  74516. )[0];
  74517. if (dataZoomModel) {
  74518. var percentRange = dataZoomModel.getPercentRange();
  74519. store[0][dataZoomId] = {
  74520. dataZoomId: dataZoomId,
  74521. start: percentRange[0],
  74522. end: percentRange[1]
  74523. };
  74524. }
  74525. }
  74526. });
  74527. store.push(newSnapshot);
  74528. }
  74529. /**
  74530. * @param {module:echarts/model/Global} ecModel
  74531. * @return {Object} snapshot
  74532. */
  74533. function pop(ecModel) {
  74534. var store = giveStore$1(ecModel);
  74535. var head = store[store.length - 1];
  74536. store.length > 1 && store.pop();
  74537. // Find top for all dataZoom.
  74538. var snapshot = {};
  74539. each$29(head, function (batchItem, dataZoomId) {
  74540. for (var i = store.length - 1; i >= 0; i--) {
  74541. var batchItem = store[i][dataZoomId];
  74542. if (batchItem) {
  74543. snapshot[dataZoomId] = batchItem;
  74544. break;
  74545. }
  74546. }
  74547. });
  74548. return snapshot;
  74549. }
  74550. /**
  74551. * @param {module:echarts/model/Global} ecModel
  74552. */
  74553. function clear$1(ecModel) {
  74554. ecModel[ATTR$2] = null;
  74555. }
  74556. /**
  74557. * @param {module:echarts/model/Global} ecModel
  74558. * @return {number} records. always >= 1.
  74559. */
  74560. function count(ecModel) {
  74561. return giveStore$1(ecModel).length;
  74562. }
  74563. /**
  74564. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  74565. * History length of each dataZoom may be different.
  74566. * this._history[0] is used to store origin range.
  74567. * @type {Array.<Object>}
  74568. */
  74569. function giveStore$1(ecModel) {
  74570. var store = ecModel[ATTR$2];
  74571. if (!store) {
  74572. store = ecModel[ATTR$2] = [{}];
  74573. }
  74574. return store;
  74575. }
  74576. /*
  74577. * Licensed to the Apache Software Foundation (ASF) under one
  74578. * or more contributor license agreements. See the NOTICE file
  74579. * distributed with this work for additional information
  74580. * regarding copyright ownership. The ASF licenses this file
  74581. * to you under the Apache License, Version 2.0 (the
  74582. * "License"); you may not use this file except in compliance
  74583. * with the License. You may obtain a copy of the License at
  74584. *
  74585. * http://www.apache.org/licenses/LICENSE-2.0
  74586. *
  74587. * Unless required by applicable law or agreed to in writing,
  74588. * software distributed under the License is distributed on an
  74589. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74590. * KIND, either express or implied. See the License for the
  74591. * specific language governing permissions and limitations
  74592. * under the License.
  74593. */
  74594. DataZoomModel.extend({
  74595. type: 'dataZoom.select'
  74596. });
  74597. /*
  74598. * Licensed to the Apache Software Foundation (ASF) under one
  74599. * or more contributor license agreements. See the NOTICE file
  74600. * distributed with this work for additional information
  74601. * regarding copyright ownership. The ASF licenses this file
  74602. * to you under the Apache License, Version 2.0 (the
  74603. * "License"); you may not use this file except in compliance
  74604. * with the License. You may obtain a copy of the License at
  74605. *
  74606. * http://www.apache.org/licenses/LICENSE-2.0
  74607. *
  74608. * Unless required by applicable law or agreed to in writing,
  74609. * software distributed under the License is distributed on an
  74610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74611. * KIND, either express or implied. See the License for the
  74612. * specific language governing permissions and limitations
  74613. * under the License.
  74614. */
  74615. DataZoomView.extend({
  74616. type: 'dataZoom.select'
  74617. });
  74618. /*
  74619. * Licensed to the Apache Software Foundation (ASF) under one
  74620. * or more contributor license agreements. See the NOTICE file
  74621. * distributed with this work for additional information
  74622. * regarding copyright ownership. The ASF licenses this file
  74623. * to you under the Apache License, Version 2.0 (the
  74624. * "License"); you may not use this file except in compliance
  74625. * with the License. You may obtain a copy of the License at
  74626. *
  74627. * http://www.apache.org/licenses/LICENSE-2.0
  74628. *
  74629. * Unless required by applicable law or agreed to in writing,
  74630. * software distributed under the License is distributed on an
  74631. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74632. * KIND, either express or implied. See the License for the
  74633. * specific language governing permissions and limitations
  74634. * under the License.
  74635. */
  74636. /**
  74637. * DataZoom component entry
  74638. */
  74639. /*
  74640. * Licensed to the Apache Software Foundation (ASF) under one
  74641. * or more contributor license agreements. See the NOTICE file
  74642. * distributed with this work for additional information
  74643. * regarding copyright ownership. The ASF licenses this file
  74644. * to you under the Apache License, Version 2.0 (the
  74645. * "License"); you may not use this file except in compliance
  74646. * with the License. You may obtain a copy of the License at
  74647. *
  74648. * http://www.apache.org/licenses/LICENSE-2.0
  74649. *
  74650. * Unless required by applicable law or agreed to in writing,
  74651. * software distributed under the License is distributed on an
  74652. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74653. * KIND, either express or implied. See the License for the
  74654. * specific language governing permissions and limitations
  74655. * under the License.
  74656. */
  74657. // Use dataZoomSelect
  74658. var dataZoomLang = lang.toolbox.dataZoom;
  74659. var each$28 = each$1;
  74660. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  74661. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  74662. function DataZoom(model, ecModel, api) {
  74663. /**
  74664. * @private
  74665. * @type {module:echarts/component/helper/BrushController}
  74666. */
  74667. (this._brushController = new BrushController(api.getZr()))
  74668. .on('brush', bind(this._onBrush, this))
  74669. .mount();
  74670. /**
  74671. * @private
  74672. * @type {boolean}
  74673. */
  74674. this._isZoomActive;
  74675. }
  74676. DataZoom.defaultOption = {
  74677. show: true,
  74678. // Icon group
  74679. icon: {
  74680. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  74681. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  74682. },
  74683. // `zoom`, `back`
  74684. title: clone(dataZoomLang.title)
  74685. };
  74686. var proto$6 = DataZoom.prototype;
  74687. proto$6.render = function (featureModel, ecModel, api, payload) {
  74688. this.model = featureModel;
  74689. this.ecModel = ecModel;
  74690. this.api = api;
  74691. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  74692. updateBackBtnStatus(featureModel, ecModel);
  74693. };
  74694. proto$6.onclick = function (ecModel, api, type) {
  74695. handlers$1[type].call(this);
  74696. };
  74697. proto$6.remove = function (ecModel, api) {
  74698. this._brushController.unmount();
  74699. };
  74700. proto$6.dispose = function (ecModel, api) {
  74701. this._brushController.dispose();
  74702. };
  74703. /**
  74704. * @private
  74705. */
  74706. var handlers$1 = {
  74707. zoom: function () {
  74708. var nextActive = !this._isZoomActive;
  74709. this.api.dispatchAction({
  74710. type: 'takeGlobalCursor',
  74711. key: 'dataZoomSelect',
  74712. dataZoomSelectActive: nextActive
  74713. });
  74714. },
  74715. back: function () {
  74716. this._dispatchZoomAction(pop(this.ecModel));
  74717. }
  74718. };
  74719. /**
  74720. * @private
  74721. */
  74722. proto$6._onBrush = function (areas, opt) {
  74723. if (!opt.isEnd || !areas.length) {
  74724. return;
  74725. }
  74726. var snapshot = {};
  74727. var ecModel = this.ecModel;
  74728. this._brushController.updateCovers([]); // remove cover
  74729. var brushTargetManager = new BrushTargetManager(
  74730. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  74731. );
  74732. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  74733. if (coordSys.type !== 'cartesian2d') {
  74734. return;
  74735. }
  74736. var brushType = area.brushType;
  74737. if (brushType === 'rect') {
  74738. setBatch('x', coordSys, coordRange[0]);
  74739. setBatch('y', coordSys, coordRange[1]);
  74740. }
  74741. else {
  74742. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  74743. }
  74744. });
  74745. push(ecModel, snapshot);
  74746. this._dispatchZoomAction(snapshot);
  74747. function setBatch(dimName, coordSys, minMax) {
  74748. var axis = coordSys.getAxis(dimName);
  74749. var axisModel = axis.model;
  74750. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  74751. // Restrict range.
  74752. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  74753. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  74754. minMax = sliderMove(
  74755. 0, minMax.slice(), axis.scale.getExtent(), 0,
  74756. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  74757. );
  74758. }
  74759. dataZoomModel && (snapshot[dataZoomModel.id] = {
  74760. dataZoomId: dataZoomModel.id,
  74761. startValue: minMax[0],
  74762. endValue: minMax[1]
  74763. });
  74764. }
  74765. function findDataZoom(dimName, axisModel, ecModel) {
  74766. var found;
  74767. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  74768. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  74769. has && (found = dzModel);
  74770. });
  74771. return found;
  74772. }
  74773. };
  74774. /**
  74775. * @private
  74776. */
  74777. proto$6._dispatchZoomAction = function (snapshot) {
  74778. var batch = [];
  74779. // Convert from hash map to array.
  74780. each$28(snapshot, function (batchItem, dataZoomId) {
  74781. batch.push(clone(batchItem));
  74782. });
  74783. batch.length && this.api.dispatchAction({
  74784. type: 'dataZoom',
  74785. from: this.uid,
  74786. batch: batch
  74787. });
  74788. };
  74789. function retrieveAxisSetting(option) {
  74790. var setting = {};
  74791. // Compatible with previous setting: null => all axis, false => no axis.
  74792. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  74793. setting[name] = option[name];
  74794. setting[name] == null && (setting[name] = 'all');
  74795. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  74796. });
  74797. return setting;
  74798. }
  74799. function updateBackBtnStatus(featureModel, ecModel) {
  74800. featureModel.setIconStatus(
  74801. 'back',
  74802. count(ecModel) > 1 ? 'emphasis' : 'normal'
  74803. );
  74804. }
  74805. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  74806. var zoomActive = view._isZoomActive;
  74807. if (payload && payload.type === 'takeGlobalCursor') {
  74808. zoomActive = payload.key === 'dataZoomSelect'
  74809. ? payload.dataZoomSelectActive : false;
  74810. }
  74811. view._isZoomActive = zoomActive;
  74812. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  74813. var brushTargetManager = new BrushTargetManager(
  74814. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  74815. );
  74816. view._brushController
  74817. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  74818. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  74819. ? 'lineX'
  74820. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  74821. ? 'lineY'
  74822. : 'rect';
  74823. }))
  74824. .enableBrush(
  74825. zoomActive
  74826. ? {
  74827. brushType: 'auto',
  74828. brushStyle: {
  74829. // FIXME user customized?
  74830. lineWidth: 0,
  74831. fill: 'rgba(0,0,0,0.2)'
  74832. }
  74833. }
  74834. : false
  74835. );
  74836. }
  74837. register$1('dataZoom', DataZoom);
  74838. // Create special dataZoom option for select
  74839. // FIXME consider the case of merge option, where axes options are not exists.
  74840. registerPreprocessor(function (option) {
  74841. if (!option) {
  74842. return;
  74843. }
  74844. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  74845. if (!isArray(dataZoomOpts)) {
  74846. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  74847. }
  74848. var toolboxOpt = option.toolbox;
  74849. if (toolboxOpt) {
  74850. // Assume there is only one toolbox
  74851. if (isArray(toolboxOpt)) {
  74852. toolboxOpt = toolboxOpt[0];
  74853. }
  74854. if (toolboxOpt && toolboxOpt.feature) {
  74855. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  74856. // FIXME: If add dataZoom when setOption in merge mode,
  74857. // no axis info to be added. See `test/dataZoom-extreme.html`
  74858. addForAxis('xAxis', dataZoomOpt);
  74859. addForAxis('yAxis', dataZoomOpt);
  74860. }
  74861. }
  74862. function addForAxis(axisName, dataZoomOpt) {
  74863. if (!dataZoomOpt) {
  74864. return;
  74865. }
  74866. // Try not to modify model, because it is not merged yet.
  74867. var axisIndicesName = axisName + 'Index';
  74868. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  74869. if (givenAxisIndices != null
  74870. && givenAxisIndices != 'all'
  74871. && !isArray(givenAxisIndices)
  74872. ) {
  74873. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  74874. }
  74875. forEachComponent(axisName, function (axisOpt, axisIndex) {
  74876. if (givenAxisIndices != null
  74877. && givenAxisIndices != 'all'
  74878. && indexOf(givenAxisIndices, axisIndex) === -1
  74879. ) {
  74880. return;
  74881. }
  74882. var newOpt = {
  74883. type: 'select',
  74884. $fromToolbox: true,
  74885. // Id for merge mapping.
  74886. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  74887. };
  74888. // FIXME
  74889. // Only support one axis now.
  74890. newOpt[axisIndicesName] = axisIndex;
  74891. dataZoomOpts.push(newOpt);
  74892. });
  74893. }
  74894. function forEachComponent(mainType, cb) {
  74895. var opts = option[mainType];
  74896. if (!isArray(opts)) {
  74897. opts = opts ? [opts] : [];
  74898. }
  74899. each$28(opts, cb);
  74900. }
  74901. });
  74902. /*
  74903. * Licensed to the Apache Software Foundation (ASF) under one
  74904. * or more contributor license agreements. See the NOTICE file
  74905. * distributed with this work for additional information
  74906. * regarding copyright ownership. The ASF licenses this file
  74907. * to you under the Apache License, Version 2.0 (the
  74908. * "License"); you may not use this file except in compliance
  74909. * with the License. You may obtain a copy of the License at
  74910. *
  74911. * http://www.apache.org/licenses/LICENSE-2.0
  74912. *
  74913. * Unless required by applicable law or agreed to in writing,
  74914. * software distributed under the License is distributed on an
  74915. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74916. * KIND, either express or implied. See the License for the
  74917. * specific language governing permissions and limitations
  74918. * under the License.
  74919. */
  74920. var restoreLang = lang.toolbox.restore;
  74921. function Restore(model) {
  74922. this.model = model;
  74923. }
  74924. Restore.defaultOption = {
  74925. show: true,
  74926. 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',
  74927. title: restoreLang.title
  74928. };
  74929. var proto$7 = Restore.prototype;
  74930. proto$7.onclick = function (ecModel, api, type) {
  74931. clear$1(ecModel);
  74932. api.dispatchAction({
  74933. type: 'restore',
  74934. from: this.uid
  74935. });
  74936. };
  74937. register$1('restore', Restore);
  74938. registerAction(
  74939. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  74940. function (payload, ecModel) {
  74941. ecModel.resetOption('recreate');
  74942. }
  74943. );
  74944. /*
  74945. * Licensed to the Apache Software Foundation (ASF) under one
  74946. * or more contributor license agreements. See the NOTICE file
  74947. * distributed with this work for additional information
  74948. * regarding copyright ownership. The ASF licenses this file
  74949. * to you under the Apache License, Version 2.0 (the
  74950. * "License"); you may not use this file except in compliance
  74951. * with the License. You may obtain a copy of the License at
  74952. *
  74953. * http://www.apache.org/licenses/LICENSE-2.0
  74954. *
  74955. * Unless required by applicable law or agreed to in writing,
  74956. * software distributed under the License is distributed on an
  74957. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74958. * KIND, either express or implied. See the License for the
  74959. * specific language governing permissions and limitations
  74960. * under the License.
  74961. */
  74962. var urn = 'urn:schemas-microsoft-com:vml';
  74963. var win = typeof window === 'undefined' ? null : window;
  74964. var vmlInited = false;
  74965. var doc = win && win.document;
  74966. function createNode(tagName) {
  74967. return doCreateNode(tagName);
  74968. }
  74969. // Avoid assign to an exported variable, for transforming to cjs.
  74970. var doCreateNode;
  74971. if (doc && !env$1.canvasSupported) {
  74972. try {
  74973. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  74974. doCreateNode = function (tagName) {
  74975. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  74976. };
  74977. }
  74978. catch (e) {
  74979. doCreateNode = function (tagName) {
  74980. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  74981. };
  74982. }
  74983. }
  74984. // From raphael
  74985. function initVML() {
  74986. if (vmlInited || !doc) {
  74987. return;
  74988. }
  74989. vmlInited = true;
  74990. var styleSheets = doc.styleSheets;
  74991. if (styleSheets.length < 31) {
  74992. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  74993. }
  74994. else {
  74995. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  74996. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  74997. }
  74998. }
  74999. // http://www.w3.org/TR/NOTE-VML
  75000. // TODO Use proxy like svg instead of overwrite brush methods
  75001. var CMD$3 = PathProxy.CMD;
  75002. var round$3 = Math.round;
  75003. var sqrt = Math.sqrt;
  75004. var abs$1 = Math.abs;
  75005. var cos = Math.cos;
  75006. var sin = Math.sin;
  75007. var mathMax$8 = Math.max;
  75008. if (!env$1.canvasSupported) {
  75009. var comma = ',';
  75010. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  75011. var Z = 21600;
  75012. var Z2 = Z / 2;
  75013. var ZLEVEL_BASE = 100000;
  75014. var Z_BASE$1 = 1000;
  75015. var initRootElStyle = function (el) {
  75016. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  75017. el.coordsize = Z + ',' + Z;
  75018. el.coordorigin = '0,0';
  75019. };
  75020. var encodeHtmlAttribute = function (s) {
  75021. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  75022. };
  75023. var rgb2Str = function (r, g, b) {
  75024. return 'rgb(' + [r, g, b].join(',') + ')';
  75025. };
  75026. var append = function (parent, child) {
  75027. if (child && parent && child.parentNode !== parent) {
  75028. parent.appendChild(child);
  75029. }
  75030. };
  75031. var remove = function (parent, child) {
  75032. if (child && parent && child.parentNode === parent) {
  75033. parent.removeChild(child);
  75034. }
  75035. };
  75036. var getZIndex = function (zlevel, z, z2) {
  75037. // z 的取值范围为 [0, 1000]
  75038. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  75039. };
  75040. var parsePercent$3 = function (value, maxValue) {
  75041. if (typeof value === 'string') {
  75042. if (value.lastIndexOf('%') >= 0) {
  75043. return parseFloat(value) / 100 * maxValue;
  75044. }
  75045. return parseFloat(value);
  75046. }
  75047. return value;
  75048. };
  75049. /***************************************************
  75050. * PATH
  75051. **************************************************/
  75052. var setColorAndOpacity = function (el, color, opacity) {
  75053. var colorArr = parse(color);
  75054. opacity = +opacity;
  75055. if (isNaN(opacity)) {
  75056. opacity = 1;
  75057. }
  75058. if (colorArr) {
  75059. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  75060. el.opacity = opacity * colorArr[3];
  75061. }
  75062. };
  75063. var getColorAndAlpha = function (color) {
  75064. var colorArr = parse(color);
  75065. return [
  75066. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  75067. colorArr[3]
  75068. ];
  75069. };
  75070. var updateFillNode = function (el, style, zrEl) {
  75071. // TODO pattern
  75072. var fill = style.fill;
  75073. if (fill != null) {
  75074. // Modified from excanvas
  75075. if (fill instanceof Gradient) {
  75076. var gradientType;
  75077. var angle = 0;
  75078. var focus = [0, 0];
  75079. // additional offset
  75080. var shift = 0;
  75081. // scale factor for offset
  75082. var expansion = 1;
  75083. var rect = zrEl.getBoundingRect();
  75084. var rectWidth = rect.width;
  75085. var rectHeight = rect.height;
  75086. if (fill.type === 'linear') {
  75087. gradientType = 'gradient';
  75088. var transform = zrEl.transform;
  75089. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  75090. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  75091. if (transform) {
  75092. applyTransform(p0, p0, transform);
  75093. applyTransform(p1, p1, transform);
  75094. }
  75095. var dx = p1[0] - p0[0];
  75096. var dy = p1[1] - p0[1];
  75097. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  75098. // The angle should be a non-negative number.
  75099. if (angle < 0) {
  75100. angle += 360;
  75101. }
  75102. // Very small angles produce an unexpected result because they are
  75103. // converted to a scientific notation string.
  75104. if (angle < 1e-6) {
  75105. angle = 0;
  75106. }
  75107. }
  75108. else {
  75109. gradientType = 'gradientradial';
  75110. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  75111. var transform = zrEl.transform;
  75112. var scale$$1 = zrEl.scale;
  75113. var width = rectWidth;
  75114. var height = rectHeight;
  75115. focus = [
  75116. // Percent in bounding rect
  75117. (p0[0] - rect.x) / width,
  75118. (p0[1] - rect.y) / height
  75119. ];
  75120. if (transform) {
  75121. applyTransform(p0, p0, transform);
  75122. }
  75123. width /= scale$$1[0] * Z;
  75124. height /= scale$$1[1] * Z;
  75125. var dimension = mathMax$8(width, height);
  75126. shift = 2 * 0 / dimension;
  75127. expansion = 2 * fill.r / dimension - shift;
  75128. }
  75129. // We need to sort the color stops in ascending order by offset,
  75130. // otherwise IE won't interpret it correctly.
  75131. var stops = fill.colorStops.slice();
  75132. stops.sort(function(cs1, cs2) {
  75133. return cs1.offset - cs2.offset;
  75134. });
  75135. var length$$1 = stops.length;
  75136. // Color and alpha list of first and last stop
  75137. var colorAndAlphaList = [];
  75138. var colors = [];
  75139. for (var i = 0; i < length$$1; i++) {
  75140. var stop = stops[i];
  75141. var colorAndAlpha = getColorAndAlpha(stop.color);
  75142. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  75143. if (i === 0 || i === length$$1 - 1) {
  75144. colorAndAlphaList.push(colorAndAlpha);
  75145. }
  75146. }
  75147. if (length$$1 >= 2) {
  75148. var color1 = colorAndAlphaList[0][0];
  75149. var color2 = colorAndAlphaList[1][0];
  75150. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  75151. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  75152. el.type = gradientType;
  75153. el.method = 'none';
  75154. el.focus = '100%';
  75155. el.angle = angle;
  75156. el.color = color1;
  75157. el.color2 = color2;
  75158. el.colors = colors.join(',');
  75159. // When colors attribute is used, the meanings of opacity and o:opacity2
  75160. // are reversed.
  75161. el.opacity = opacity2;
  75162. // FIXME g_o_:opacity ?
  75163. el.opacity2 = opacity1;
  75164. }
  75165. if (gradientType === 'radial') {
  75166. el.focusposition = focus.join(',');
  75167. }
  75168. }
  75169. else {
  75170. // FIXME Change from Gradient fill to color fill
  75171. setColorAndOpacity(el, fill, style.opacity);
  75172. }
  75173. }
  75174. };
  75175. var updateStrokeNode = function (el, style) {
  75176. // if (style.lineJoin != null) {
  75177. // el.joinstyle = style.lineJoin;
  75178. // }
  75179. // if (style.miterLimit != null) {
  75180. // el.miterlimit = style.miterLimit * Z;
  75181. // }
  75182. // if (style.lineCap != null) {
  75183. // el.endcap = style.lineCap;
  75184. // }
  75185. if (style.lineDash != null) {
  75186. el.dashstyle = style.lineDash.join(' ');
  75187. }
  75188. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  75189. setColorAndOpacity(el, style.stroke, style.opacity);
  75190. }
  75191. };
  75192. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  75193. var isFill = type == 'fill';
  75194. var el = vmlEl.getElementsByTagName(type)[0];
  75195. // Stroke must have lineWidth
  75196. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  75197. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  75198. // FIXME Remove before updating, or set `colors` will throw error
  75199. if (style[type] instanceof Gradient) {
  75200. remove(vmlEl, el);
  75201. }
  75202. if (!el) {
  75203. el = createNode(type);
  75204. }
  75205. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  75206. append(vmlEl, el);
  75207. }
  75208. else {
  75209. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  75210. remove(vmlEl, el);
  75211. }
  75212. };
  75213. var points$3 = [[], [], []];
  75214. var pathDataToString = function (path, m) {
  75215. var M = CMD$3.M;
  75216. var C = CMD$3.C;
  75217. var L = CMD$3.L;
  75218. var A = CMD$3.A;
  75219. var Q = CMD$3.Q;
  75220. var str = [];
  75221. var nPoint;
  75222. var cmdStr;
  75223. var cmd;
  75224. var i;
  75225. var xi;
  75226. var yi;
  75227. var data = path.data;
  75228. var dataLength = path.len();
  75229. for (i = 0; i < dataLength;) {
  75230. cmd = data[i++];
  75231. cmdStr = '';
  75232. nPoint = 0;
  75233. switch (cmd) {
  75234. case M:
  75235. cmdStr = ' m ';
  75236. nPoint = 1;
  75237. xi = data[i++];
  75238. yi = data[i++];
  75239. points$3[0][0] = xi;
  75240. points$3[0][1] = yi;
  75241. break;
  75242. case L:
  75243. cmdStr = ' l ';
  75244. nPoint = 1;
  75245. xi = data[i++];
  75246. yi = data[i++];
  75247. points$3[0][0] = xi;
  75248. points$3[0][1] = yi;
  75249. break;
  75250. case Q:
  75251. case C:
  75252. cmdStr = ' c ';
  75253. nPoint = 3;
  75254. var x1 = data[i++];
  75255. var y1 = data[i++];
  75256. var x2 = data[i++];
  75257. var y2 = data[i++];
  75258. var x3;
  75259. var y3;
  75260. if (cmd === Q) {
  75261. // Convert quadratic to cubic using degree elevation
  75262. x3 = x2;
  75263. y3 = y2;
  75264. x2 = (x2 + 2 * x1) / 3;
  75265. y2 = (y2 + 2 * y1) / 3;
  75266. x1 = (xi + 2 * x1) / 3;
  75267. y1 = (yi + 2 * y1) / 3;
  75268. }
  75269. else {
  75270. x3 = data[i++];
  75271. y3 = data[i++];
  75272. }
  75273. points$3[0][0] = x1;
  75274. points$3[0][1] = y1;
  75275. points$3[1][0] = x2;
  75276. points$3[1][1] = y2;
  75277. points$3[2][0] = x3;
  75278. points$3[2][1] = y3;
  75279. xi = x3;
  75280. yi = y3;
  75281. break;
  75282. case A:
  75283. var x = 0;
  75284. var y = 0;
  75285. var sx = 1;
  75286. var sy = 1;
  75287. var angle = 0;
  75288. if (m) {
  75289. // Extract SRT from matrix
  75290. x = m[4];
  75291. y = m[5];
  75292. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  75293. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  75294. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  75295. }
  75296. var cx = data[i++];
  75297. var cy = data[i++];
  75298. var rx = data[i++];
  75299. var ry = data[i++];
  75300. var startAngle = data[i++] + angle;
  75301. var endAngle = data[i++] + startAngle + angle;
  75302. // FIXME
  75303. // var psi = data[i++];
  75304. i++;
  75305. var clockwise = data[i++];
  75306. var x0 = cx + cos(startAngle) * rx;
  75307. var y0 = cy + sin(startAngle) * ry;
  75308. var x1 = cx + cos(endAngle) * rx;
  75309. var y1 = cy + sin(endAngle) * ry;
  75310. var type = clockwise ? ' wa ' : ' at ';
  75311. if (Math.abs(x0 - x1) < 1e-4) {
  75312. // IE won't render arches drawn counter clockwise if x0 == x1.
  75313. if (Math.abs(endAngle - startAngle) > 1e-2) {
  75314. // Offset x0 by 1/80 of a pixel. Use something
  75315. // that can be represented in binary
  75316. if (clockwise) {
  75317. x0 += 270 / Z;
  75318. }
  75319. }
  75320. else {
  75321. // Avoid case draw full circle
  75322. if (Math.abs(y0 - cy) < 1e-4) {
  75323. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  75324. y1 -= 270 / Z;
  75325. }
  75326. else {
  75327. y1 += 270 / Z;
  75328. }
  75329. }
  75330. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  75331. x1 += 270 / Z;
  75332. }
  75333. else {
  75334. x1 -= 270 / Z;
  75335. }
  75336. }
  75337. }
  75338. str.push(
  75339. type,
  75340. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  75341. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  75342. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  75343. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  75344. round$3((x0 * sx + x) * Z - Z2), comma,
  75345. round$3((y0 * sy + y) * Z - Z2), comma,
  75346. round$3((x1 * sx + x) * Z - Z2), comma,
  75347. round$3((y1 * sy + y) * Z - Z2)
  75348. );
  75349. xi = x1;
  75350. yi = y1;
  75351. break;
  75352. case CMD$3.R:
  75353. var p0 = points$3[0];
  75354. var p1 = points$3[1];
  75355. // x0, y0
  75356. p0[0] = data[i++];
  75357. p0[1] = data[i++];
  75358. // x1, y1
  75359. p1[0] = p0[0] + data[i++];
  75360. p1[1] = p0[1] + data[i++];
  75361. if (m) {
  75362. applyTransform(p0, p0, m);
  75363. applyTransform(p1, p1, m);
  75364. }
  75365. p0[0] = round$3(p0[0] * Z - Z2);
  75366. p1[0] = round$3(p1[0] * Z - Z2);
  75367. p0[1] = round$3(p0[1] * Z - Z2);
  75368. p1[1] = round$3(p1[1] * Z - Z2);
  75369. str.push(
  75370. // x0, y0
  75371. ' m ', p0[0], comma, p0[1],
  75372. // x1, y0
  75373. ' l ', p1[0], comma, p0[1],
  75374. // x1, y1
  75375. ' l ', p1[0], comma, p1[1],
  75376. // x0, y1
  75377. ' l ', p0[0], comma, p1[1]
  75378. );
  75379. break;
  75380. case CMD$3.Z:
  75381. // FIXME Update xi, yi
  75382. str.push(' x ');
  75383. }
  75384. if (nPoint > 0) {
  75385. str.push(cmdStr);
  75386. for (var k = 0; k < nPoint; k++) {
  75387. var p = points$3[k];
  75388. m && applyTransform(p, p, m);
  75389. // 不 round 会非常慢
  75390. str.push(
  75391. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  75392. k < nPoint - 1 ? comma : ''
  75393. );
  75394. }
  75395. }
  75396. }
  75397. return str.join('');
  75398. };
  75399. // Rewrite the original path method
  75400. Path.prototype.brushVML = function (vmlRoot) {
  75401. var style = this.style;
  75402. var vmlEl = this._vmlEl;
  75403. if (!vmlEl) {
  75404. vmlEl = createNode('shape');
  75405. initRootElStyle(vmlEl);
  75406. this._vmlEl = vmlEl;
  75407. }
  75408. updateFillAndStroke(vmlEl, 'fill', style, this);
  75409. updateFillAndStroke(vmlEl, 'stroke', style, this);
  75410. var m = this.transform;
  75411. var needTransform = m != null;
  75412. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  75413. if (strokeEl) {
  75414. var lineWidth = style.lineWidth;
  75415. // Get the line scale.
  75416. // Determinant of this.m_ means how much the area is enlarged by the
  75417. // transformation. So its square root can be used as a scale factor
  75418. // for width.
  75419. if (needTransform && !style.strokeNoScale) {
  75420. var det = m[0] * m[3] - m[1] * m[2];
  75421. lineWidth *= sqrt(abs$1(det));
  75422. }
  75423. strokeEl.weight = lineWidth + 'px';
  75424. }
  75425. var path = this.path || (this.path = new PathProxy());
  75426. if (this.__dirtyPath) {
  75427. path.beginPath();
  75428. this.buildPath(path, this.shape);
  75429. path.toStatic();
  75430. this.__dirtyPath = false;
  75431. }
  75432. vmlEl.path = pathDataToString(path, this.transform);
  75433. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  75434. // Append to root
  75435. append(vmlRoot, vmlEl);
  75436. // Text
  75437. if (style.text != null) {
  75438. this.drawRectText(vmlRoot, this.getBoundingRect());
  75439. }
  75440. else {
  75441. this.removeRectText(vmlRoot);
  75442. }
  75443. };
  75444. Path.prototype.onRemove = function (vmlRoot) {
  75445. remove(vmlRoot, this._vmlEl);
  75446. this.removeRectText(vmlRoot);
  75447. };
  75448. Path.prototype.onAdd = function (vmlRoot) {
  75449. append(vmlRoot, this._vmlEl);
  75450. this.appendRectText(vmlRoot);
  75451. };
  75452. /***************************************************
  75453. * IMAGE
  75454. **************************************************/
  75455. var isImage = function (img) {
  75456. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  75457. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  75458. // return img instanceof Image;
  75459. };
  75460. // Rewrite the original path method
  75461. ZImage.prototype.brushVML = function (vmlRoot) {
  75462. var style = this.style;
  75463. var image = style.image;
  75464. // Image original width, height
  75465. var ow;
  75466. var oh;
  75467. if (isImage(image)) {
  75468. var src = image.src;
  75469. if (src === this._imageSrc) {
  75470. ow = this._imageWidth;
  75471. oh = this._imageHeight;
  75472. }
  75473. else {
  75474. var imageRuntimeStyle = image.runtimeStyle;
  75475. var oldRuntimeWidth = imageRuntimeStyle.width;
  75476. var oldRuntimeHeight = imageRuntimeStyle.height;
  75477. imageRuntimeStyle.width = 'auto';
  75478. imageRuntimeStyle.height = 'auto';
  75479. // get the original size
  75480. ow = image.width;
  75481. oh = image.height;
  75482. // and remove overides
  75483. imageRuntimeStyle.width = oldRuntimeWidth;
  75484. imageRuntimeStyle.height = oldRuntimeHeight;
  75485. // Caching image original width, height and src
  75486. this._imageSrc = src;
  75487. this._imageWidth = ow;
  75488. this._imageHeight = oh;
  75489. }
  75490. image = src;
  75491. }
  75492. else {
  75493. if (image === this._imageSrc) {
  75494. ow = this._imageWidth;
  75495. oh = this._imageHeight;
  75496. }
  75497. }
  75498. if (!image) {
  75499. return;
  75500. }
  75501. var x = style.x || 0;
  75502. var y = style.y || 0;
  75503. var dw = style.width;
  75504. var dh = style.height;
  75505. var sw = style.sWidth;
  75506. var sh = style.sHeight;
  75507. var sx = style.sx || 0;
  75508. var sy = style.sy || 0;
  75509. var hasCrop = sw && sh;
  75510. var vmlEl = this._vmlEl;
  75511. if (!vmlEl) {
  75512. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  75513. // vmlEl = vmlCore.createNode('group');
  75514. vmlEl = doc.createElement('div');
  75515. initRootElStyle(vmlEl);
  75516. this._vmlEl = vmlEl;
  75517. }
  75518. var vmlElStyle = vmlEl.style;
  75519. var hasRotation = false;
  75520. var m;
  75521. var scaleX = 1;
  75522. var scaleY = 1;
  75523. if (this.transform) {
  75524. m = this.transform;
  75525. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  75526. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  75527. hasRotation = m[1] || m[2];
  75528. }
  75529. if (hasRotation) {
  75530. // If filters are necessary (rotation exists), create them
  75531. // filters are bog-slow, so only create them if abbsolutely necessary
  75532. // The following check doesn't account for skews (which don't exist
  75533. // in the canvas spec (yet) anyway.
  75534. // From excanvas
  75535. var p0 = [x, y];
  75536. var p1 = [x + dw, y];
  75537. var p2 = [x, y + dh];
  75538. var p3 = [x + dw, y + dh];
  75539. applyTransform(p0, p0, m);
  75540. applyTransform(p1, p1, m);
  75541. applyTransform(p2, p2, m);
  75542. applyTransform(p3, p3, m);
  75543. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  75544. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  75545. var transformFilter = [];
  75546. transformFilter.push('M11=', m[0] / scaleX, comma,
  75547. 'M12=', m[2] / scaleY, comma,
  75548. 'M21=', m[1] / scaleX, comma,
  75549. 'M22=', m[3] / scaleY, comma,
  75550. 'Dx=', round$3(x * scaleX + m[4]), comma,
  75551. 'Dy=', round$3(y * scaleY + m[5]));
  75552. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  75553. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  75554. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  75555. + transformFilter.join('') + ', SizingMethod=clip)';
  75556. }
  75557. else {
  75558. if (m) {
  75559. x = x * scaleX + m[4];
  75560. y = y * scaleY + m[5];
  75561. }
  75562. vmlElStyle.filter = '';
  75563. vmlElStyle.left = round$3(x) + 'px';
  75564. vmlElStyle.top = round$3(y) + 'px';
  75565. }
  75566. var imageEl = this._imageEl;
  75567. var cropEl = this._cropEl;
  75568. if (!imageEl) {
  75569. imageEl = doc.createElement('div');
  75570. this._imageEl = imageEl;
  75571. }
  75572. var imageELStyle = imageEl.style;
  75573. if (hasCrop) {
  75574. // Needs know image original width and height
  75575. if (! (ow && oh)) {
  75576. var tmpImage = new Image();
  75577. var self = this;
  75578. tmpImage.onload = function () {
  75579. tmpImage.onload = null;
  75580. ow = tmpImage.width;
  75581. oh = tmpImage.height;
  75582. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  75583. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  75584. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  75585. // Caching image original width, height and src
  75586. self._imageWidth = ow;
  75587. self._imageHeight = oh;
  75588. self._imageSrc = image;
  75589. };
  75590. tmpImage.src = image;
  75591. }
  75592. else {
  75593. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  75594. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  75595. }
  75596. if (! cropEl) {
  75597. cropEl = doc.createElement('div');
  75598. cropEl.style.overflow = 'hidden';
  75599. this._cropEl = cropEl;
  75600. }
  75601. var cropElStyle = cropEl.style;
  75602. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  75603. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  75604. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  75605. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  75606. if (! cropEl.parentNode) {
  75607. vmlEl.appendChild(cropEl);
  75608. }
  75609. if (imageEl.parentNode != cropEl) {
  75610. cropEl.appendChild(imageEl);
  75611. }
  75612. }
  75613. else {
  75614. imageELStyle.width = round$3(scaleX * dw) + 'px';
  75615. imageELStyle.height = round$3(scaleY * dh) + 'px';
  75616. vmlEl.appendChild(imageEl);
  75617. if (cropEl && cropEl.parentNode) {
  75618. vmlEl.removeChild(cropEl);
  75619. this._cropEl = null;
  75620. }
  75621. }
  75622. var filterStr = '';
  75623. var alpha = style.opacity;
  75624. if (alpha < 1) {
  75625. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  75626. }
  75627. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  75628. imageELStyle.filter = filterStr;
  75629. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  75630. // Append to root
  75631. append(vmlRoot, vmlEl);
  75632. // Text
  75633. if (style.text != null) {
  75634. this.drawRectText(vmlRoot, this.getBoundingRect());
  75635. }
  75636. };
  75637. ZImage.prototype.onRemove = function (vmlRoot) {
  75638. remove(vmlRoot, this._vmlEl);
  75639. this._vmlEl = null;
  75640. this._cropEl = null;
  75641. this._imageEl = null;
  75642. this.removeRectText(vmlRoot);
  75643. };
  75644. ZImage.prototype.onAdd = function (vmlRoot) {
  75645. append(vmlRoot, this._vmlEl);
  75646. this.appendRectText(vmlRoot);
  75647. };
  75648. /***************************************************
  75649. * TEXT
  75650. **************************************************/
  75651. var DEFAULT_STYLE_NORMAL = 'normal';
  75652. var fontStyleCache = {};
  75653. var fontStyleCacheCount = 0;
  75654. var MAX_FONT_CACHE_SIZE = 100;
  75655. var fontEl = document.createElement('div');
  75656. var getFontStyle = function (fontString) {
  75657. var fontStyle = fontStyleCache[fontString];
  75658. if (!fontStyle) {
  75659. // Clear cache
  75660. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  75661. fontStyleCacheCount = 0;
  75662. fontStyleCache = {};
  75663. }
  75664. var style = fontEl.style;
  75665. var fontFamily;
  75666. try {
  75667. style.font = fontString;
  75668. fontFamily = style.fontFamily.split(',')[0];
  75669. }
  75670. catch (e) {
  75671. }
  75672. fontStyle = {
  75673. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  75674. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  75675. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  75676. size: parseFloat(style.fontSize || 12) | 0,
  75677. family: fontFamily || 'Microsoft YaHei'
  75678. };
  75679. fontStyleCache[fontString] = fontStyle;
  75680. fontStyleCacheCount++;
  75681. }
  75682. return fontStyle;
  75683. };
  75684. var textMeasureEl;
  75685. // Overwrite measure text method
  75686. $override$1('measureText', function (text, textFont) {
  75687. var doc$$1 = doc;
  75688. if (!textMeasureEl) {
  75689. textMeasureEl = doc$$1.createElement('div');
  75690. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  75691. + 'padding:0;margin:0;border:none;white-space:pre;';
  75692. doc.body.appendChild(textMeasureEl);
  75693. }
  75694. try {
  75695. textMeasureEl.style.font = textFont;
  75696. } catch (ex) {
  75697. // Ignore failures to set to invalid font.
  75698. }
  75699. textMeasureEl.innerHTML = '';
  75700. // Don't use innerHTML or innerText because they allow markup/whitespace.
  75701. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  75702. return {
  75703. width: textMeasureEl.offsetWidth
  75704. };
  75705. });
  75706. var tmpRect$2 = new BoundingRect();
  75707. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  75708. var style = this.style;
  75709. // Optimize, avoid normalize every time.
  75710. this.__dirty && normalizeTextStyle(style, true);
  75711. var text = style.text;
  75712. // Convert to string
  75713. text != null && (text += '');
  75714. if (!text) {
  75715. return;
  75716. }
  75717. // Convert rich text to plain text. Rich text is not supported in
  75718. // IE8-, but tags in rich text template will be removed.
  75719. if (style.rich) {
  75720. var contentBlock = parseRichText(text, style);
  75721. text = [];
  75722. for (var i = 0; i < contentBlock.lines.length; i++) {
  75723. var tokens = contentBlock.lines[i].tokens;
  75724. var textLine = [];
  75725. for (var j = 0; j < tokens.length; j++) {
  75726. textLine.push(tokens[j].text);
  75727. }
  75728. text.push(textLine.join(''));
  75729. }
  75730. text = text.join('\n');
  75731. }
  75732. var x;
  75733. var y;
  75734. var align = style.textAlign;
  75735. var verticalAlign = style.textVerticalAlign;
  75736. var fontStyle = getFontStyle(style.font);
  75737. // FIXME encodeHtmlAttribute ?
  75738. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  75739. + fontStyle.size + 'px "' + fontStyle.family + '"';
  75740. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  75741. // Transform rect to view space
  75742. var m = this.transform;
  75743. // Ignore transform for text in other element
  75744. if (m && !fromTextEl) {
  75745. tmpRect$2.copy(rect);
  75746. tmpRect$2.applyTransform(m);
  75747. rect = tmpRect$2;
  75748. }
  75749. if (!fromTextEl) {
  75750. var textPosition = style.textPosition;
  75751. var distance$$1 = style.textDistance;
  75752. // Text position represented by coord
  75753. if (textPosition instanceof Array) {
  75754. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  75755. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  75756. align = align || 'left';
  75757. }
  75758. else {
  75759. var res = adjustTextPositionOnRect(
  75760. textPosition, rect, distance$$1
  75761. );
  75762. x = res.x;
  75763. y = res.y;
  75764. // Default align and baseline when has textPosition
  75765. align = align || res.textAlign;
  75766. verticalAlign = verticalAlign || res.textVerticalAlign;
  75767. }
  75768. }
  75769. else {
  75770. x = rect.x;
  75771. y = rect.y;
  75772. }
  75773. x = adjustTextX(x, textRect.width, align);
  75774. y = adjustTextY(y, textRect.height, verticalAlign);
  75775. // Force baseline 'middle'
  75776. y += textRect.height / 2;
  75777. // var fontSize = fontStyle.size;
  75778. // 1.75 is an arbitrary number, as there is no info about the text baseline
  75779. // switch (baseline) {
  75780. // case 'hanging':
  75781. // case 'top':
  75782. // y += fontSize / 1.75;
  75783. // break;
  75784. // case 'middle':
  75785. // break;
  75786. // default:
  75787. // // case null:
  75788. // // case 'alphabetic':
  75789. // // case 'ideographic':
  75790. // // case 'bottom':
  75791. // y -= fontSize / 2.25;
  75792. // break;
  75793. // }
  75794. // switch (align) {
  75795. // case 'left':
  75796. // break;
  75797. // case 'center':
  75798. // x -= textRect.width / 2;
  75799. // break;
  75800. // case 'right':
  75801. // x -= textRect.width;
  75802. // break;
  75803. // case 'end':
  75804. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  75805. // break;
  75806. // case 'start':
  75807. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  75808. // break;
  75809. // default:
  75810. // align = 'left';
  75811. // }
  75812. var createNode$$1 = createNode;
  75813. var textVmlEl = this._textVmlEl;
  75814. var pathEl;
  75815. var textPathEl;
  75816. var skewEl;
  75817. if (!textVmlEl) {
  75818. textVmlEl = createNode$$1('line');
  75819. pathEl = createNode$$1('path');
  75820. textPathEl = createNode$$1('textpath');
  75821. skewEl = createNode$$1('skew');
  75822. // FIXME Why here is not cammel case
  75823. // Align 'center' seems wrong
  75824. textPathEl.style['v-text-align'] = 'left';
  75825. initRootElStyle(textVmlEl);
  75826. pathEl.textpathok = true;
  75827. textPathEl.on = true;
  75828. textVmlEl.from = '0 0';
  75829. textVmlEl.to = '1000 0.05';
  75830. append(textVmlEl, skewEl);
  75831. append(textVmlEl, pathEl);
  75832. append(textVmlEl, textPathEl);
  75833. this._textVmlEl = textVmlEl;
  75834. }
  75835. else {
  75836. // 这里是在前面 appendChild 保证顺序的前提下
  75837. skewEl = textVmlEl.firstChild;
  75838. pathEl = skewEl.nextSibling;
  75839. textPathEl = pathEl.nextSibling;
  75840. }
  75841. var coords = [x, y];
  75842. var textVmlElStyle = textVmlEl.style;
  75843. // Ignore transform for text in other element
  75844. if (m && fromTextEl) {
  75845. applyTransform(coords, coords, m);
  75846. skewEl.on = true;
  75847. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  75848. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  75849. // Text position
  75850. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  75851. // Left top point as origin
  75852. skewEl.origin = '0 0';
  75853. textVmlElStyle.left = '0px';
  75854. textVmlElStyle.top = '0px';
  75855. }
  75856. else {
  75857. skewEl.on = false;
  75858. textVmlElStyle.left = round$3(x) + 'px';
  75859. textVmlElStyle.top = round$3(y) + 'px';
  75860. }
  75861. textPathEl.string = encodeHtmlAttribute(text);
  75862. // TODO
  75863. try {
  75864. textPathEl.style.font = font;
  75865. }
  75866. // Error font format
  75867. catch (e) {}
  75868. updateFillAndStroke(textVmlEl, 'fill', {
  75869. fill: style.textFill,
  75870. opacity: style.opacity
  75871. }, this);
  75872. updateFillAndStroke(textVmlEl, 'stroke', {
  75873. stroke: style.textStroke,
  75874. opacity: style.opacity,
  75875. lineDash: style.lineDash
  75876. }, this);
  75877. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  75878. // Attached to root
  75879. append(vmlRoot, textVmlEl);
  75880. };
  75881. var removeRectText = function (vmlRoot) {
  75882. remove(vmlRoot, this._textVmlEl);
  75883. this._textVmlEl = null;
  75884. };
  75885. var appendRectText = function (vmlRoot) {
  75886. append(vmlRoot, this._textVmlEl);
  75887. };
  75888. var list = [RectText, Displayable, ZImage, Path, Text];
  75889. // In case Displayable has been mixed in RectText
  75890. for (var i$3 = 0; i$3 < list.length; i$3++) {
  75891. var proto$8 = list[i$3].prototype;
  75892. proto$8.drawRectText = drawRectText;
  75893. proto$8.removeRectText = removeRectText;
  75894. proto$8.appendRectText = appendRectText;
  75895. }
  75896. Text.prototype.brushVML = function (vmlRoot) {
  75897. var style = this.style;
  75898. if (style.text != null) {
  75899. this.drawRectText(vmlRoot, {
  75900. x: style.x || 0, y: style.y || 0,
  75901. width: 0, height: 0
  75902. }, this.getBoundingRect(), true);
  75903. }
  75904. else {
  75905. this.removeRectText(vmlRoot);
  75906. }
  75907. };
  75908. Text.prototype.onRemove = function (vmlRoot) {
  75909. this.removeRectText(vmlRoot);
  75910. };
  75911. Text.prototype.onAdd = function (vmlRoot) {
  75912. this.appendRectText(vmlRoot);
  75913. };
  75914. }
  75915. /**
  75916. * VML Painter.
  75917. *
  75918. * @module zrender/vml/Painter
  75919. */
  75920. function parseInt10$1(val) {
  75921. return parseInt(val, 10);
  75922. }
  75923. /**
  75924. * @alias module:zrender/vml/Painter
  75925. */
  75926. function VMLPainter(root, storage) {
  75927. initVML();
  75928. this.root = root;
  75929. this.storage = storage;
  75930. var vmlViewport = document.createElement('div');
  75931. var vmlRoot = document.createElement('div');
  75932. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  75933. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  75934. root.appendChild(vmlViewport);
  75935. this._vmlRoot = vmlRoot;
  75936. this._vmlViewport = vmlViewport;
  75937. this.resize();
  75938. // Modify storage
  75939. var oldDelFromStorage = storage.delFromStorage;
  75940. var oldAddToStorage = storage.addToStorage;
  75941. storage.delFromStorage = function (el) {
  75942. oldDelFromStorage.call(storage, el);
  75943. if (el) {
  75944. el.onRemove && el.onRemove(vmlRoot);
  75945. }
  75946. };
  75947. storage.addToStorage = function (el) {
  75948. // Displayable already has a vml node
  75949. el.onAdd && el.onAdd(vmlRoot);
  75950. oldAddToStorage.call(storage, el);
  75951. };
  75952. this._firstPaint = true;
  75953. }
  75954. VMLPainter.prototype = {
  75955. constructor: VMLPainter,
  75956. getType: function () {
  75957. return 'vml';
  75958. },
  75959. /**
  75960. * @return {HTMLDivElement}
  75961. */
  75962. getViewportRoot: function () {
  75963. return this._vmlViewport;
  75964. },
  75965. getViewportRootOffset: function () {
  75966. var viewportRoot = this.getViewportRoot();
  75967. if (viewportRoot) {
  75968. return {
  75969. offsetLeft: viewportRoot.offsetLeft || 0,
  75970. offsetTop: viewportRoot.offsetTop || 0
  75971. };
  75972. }
  75973. },
  75974. /**
  75975. * 刷新
  75976. */
  75977. refresh: function () {
  75978. var list = this.storage.getDisplayList(true, true);
  75979. this._paintList(list);
  75980. },
  75981. _paintList: function (list) {
  75982. var vmlRoot = this._vmlRoot;
  75983. for (var i = 0; i < list.length; i++) {
  75984. var el = list[i];
  75985. if (el.invisible || el.ignore) {
  75986. if (!el.__alreadyNotVisible) {
  75987. el.onRemove(vmlRoot);
  75988. }
  75989. // Set as already invisible
  75990. el.__alreadyNotVisible = true;
  75991. }
  75992. else {
  75993. if (el.__alreadyNotVisible) {
  75994. el.onAdd(vmlRoot);
  75995. }
  75996. el.__alreadyNotVisible = false;
  75997. if (el.__dirty) {
  75998. el.beforeBrush && el.beforeBrush();
  75999. (el.brushVML || el.brush).call(el, vmlRoot);
  76000. el.afterBrush && el.afterBrush();
  76001. }
  76002. }
  76003. el.__dirty = false;
  76004. }
  76005. if (this._firstPaint) {
  76006. // Detached from document at first time
  76007. // to avoid page refreshing too many times
  76008. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  76009. this._vmlViewport.appendChild(vmlRoot);
  76010. this._firstPaint = false;
  76011. }
  76012. },
  76013. resize: function (width, height) {
  76014. var width = width == null ? this._getWidth() : width;
  76015. var height = height == null ? this._getHeight() : height;
  76016. if (this._width != width || this._height != height) {
  76017. this._width = width;
  76018. this._height = height;
  76019. var vmlViewportStyle = this._vmlViewport.style;
  76020. vmlViewportStyle.width = width + 'px';
  76021. vmlViewportStyle.height = height + 'px';
  76022. }
  76023. },
  76024. dispose: function () {
  76025. this.root.innerHTML = '';
  76026. this._vmlRoot =
  76027. this._vmlViewport =
  76028. this.storage = null;
  76029. },
  76030. getWidth: function () {
  76031. return this._width;
  76032. },
  76033. getHeight: function () {
  76034. return this._height;
  76035. },
  76036. clear: function () {
  76037. if (this._vmlViewport) {
  76038. this.root.removeChild(this._vmlViewport);
  76039. }
  76040. },
  76041. _getWidth: function () {
  76042. var root = this.root;
  76043. var stl = root.currentStyle;
  76044. return ((root.clientWidth || parseInt10$1(stl.width))
  76045. - parseInt10$1(stl.paddingLeft)
  76046. - parseInt10$1(stl.paddingRight)) | 0;
  76047. },
  76048. _getHeight: function () {
  76049. var root = this.root;
  76050. var stl = root.currentStyle;
  76051. return ((root.clientHeight || parseInt10$1(stl.height))
  76052. - parseInt10$1(stl.paddingTop)
  76053. - parseInt10$1(stl.paddingBottom)) | 0;
  76054. }
  76055. };
  76056. // Not supported methods
  76057. function createMethodNotSupport(method) {
  76058. return function () {
  76059. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  76060. };
  76061. }
  76062. // Unsupported methods
  76063. each$1([
  76064. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  76065. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  76066. ], function (name) {
  76067. VMLPainter.prototype[name] = createMethodNotSupport(name);
  76068. });
  76069. registerPainter('vml', VMLPainter);
  76070. var svgURI = 'http://www.w3.org/2000/svg';
  76071. function createElement(name) {
  76072. return document.createElementNS(svgURI, name);
  76073. }
  76074. // TODO
  76075. // 1. shadow
  76076. // 2. Image: sx, sy, sw, sh
  76077. var CMD$4 = PathProxy.CMD;
  76078. var arrayJoin = Array.prototype.join;
  76079. var NONE = 'none';
  76080. var mathRound = Math.round;
  76081. var mathSin$3 = Math.sin;
  76082. var mathCos$3 = Math.cos;
  76083. var PI$5 = Math.PI;
  76084. var PI2$7 = Math.PI * 2;
  76085. var degree = 180 / PI$5;
  76086. var EPSILON$4 = 1e-4;
  76087. function round4(val) {
  76088. return mathRound(val * 1e4) / 1e4;
  76089. }
  76090. function isAroundZero$1(val) {
  76091. return val < EPSILON$4 && val > -EPSILON$4;
  76092. }
  76093. function pathHasFill(style, isText) {
  76094. var fill = isText ? style.textFill : style.fill;
  76095. return fill != null && fill !== NONE;
  76096. }
  76097. function pathHasStroke(style, isText) {
  76098. var stroke = isText ? style.textStroke : style.stroke;
  76099. return stroke != null && stroke !== NONE;
  76100. }
  76101. function setTransform(svgEl, m) {
  76102. if (m) {
  76103. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  76104. }
  76105. }
  76106. function attr(el, key, val) {
  76107. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  76108. // Don't set attribute for gradient, since it need new dom nodes
  76109. if (typeof val === 'string' && val.indexOf('NaN') > -1) {
  76110. console.log(val);
  76111. }
  76112. el.setAttribute(key, val);
  76113. }
  76114. }
  76115. function attrXLink(el, key, val) {
  76116. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  76117. }
  76118. function bindStyle(svgEl, style, isText) {
  76119. if (pathHasFill(style, isText)) {
  76120. var fill = isText ? style.textFill : style.fill;
  76121. fill = fill === 'transparent' ? NONE : fill;
  76122. /**
  76123. * FIXME:
  76124. * This is a temporary fix for Chrome's clipping bug
  76125. * that happens when a clip-path is referring another one.
  76126. * This fix should be used before Chrome's bug is fixed.
  76127. * For an element that has clip-path, and fill is none,
  76128. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  76129. * Otherwise, it will show black fill color.
  76130. * 0.002 is used because this won't work for alpha values smaller
  76131. * than 0.002.
  76132. *
  76133. * See
  76134. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  76135. * for more information.
  76136. */
  76137. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  76138. fill = 'rgba(0, 0, 0, 0.002)';
  76139. }
  76140. attr(svgEl, 'fill', fill);
  76141. attr(svgEl, 'fill-opacity', style.opacity);
  76142. }
  76143. else {
  76144. attr(svgEl, 'fill', NONE);
  76145. }
  76146. if (pathHasStroke(style, isText)) {
  76147. var stroke = isText ? style.textStroke : style.stroke;
  76148. stroke = stroke === 'transparent' ? NONE : stroke;
  76149. attr(svgEl, 'stroke', stroke);
  76150. var strokeWidth = isText
  76151. ? style.textStrokeWidth
  76152. : style.lineWidth;
  76153. var strokeScale = !isText && style.strokeNoScale
  76154. ? style.host.getLineScale()
  76155. : 1;
  76156. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  76157. // stroke then fill for text; fill then stroke for others
  76158. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  76159. attr(svgEl, 'stroke-opacity', style.opacity);
  76160. var lineDash = style.lineDash;
  76161. if (lineDash) {
  76162. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  76163. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  76164. }
  76165. else {
  76166. attr(svgEl, 'stroke-dasharray', '');
  76167. }
  76168. // PENDING
  76169. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  76170. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  76171. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  76172. }
  76173. else {
  76174. attr(svgEl, 'stroke', NONE);
  76175. }
  76176. }
  76177. /***************************************************
  76178. * PATH
  76179. **************************************************/
  76180. function pathDataToString$1(path) {
  76181. var str = [];
  76182. var data = path.data;
  76183. var dataLength = path.len();
  76184. for (var i = 0; i < dataLength;) {
  76185. var cmd = data[i++];
  76186. var cmdStr = '';
  76187. var nData = 0;
  76188. switch (cmd) {
  76189. case CMD$4.M:
  76190. cmdStr = 'M';
  76191. nData = 2;
  76192. break;
  76193. case CMD$4.L:
  76194. cmdStr = 'L';
  76195. nData = 2;
  76196. break;
  76197. case CMD$4.Q:
  76198. cmdStr = 'Q';
  76199. nData = 4;
  76200. break;
  76201. case CMD$4.C:
  76202. cmdStr = 'C';
  76203. nData = 6;
  76204. break;
  76205. case CMD$4.A:
  76206. var cx = data[i++];
  76207. var cy = data[i++];
  76208. var rx = data[i++];
  76209. var ry = data[i++];
  76210. var theta = data[i++];
  76211. var dTheta = data[i++];
  76212. var psi = data[i++];
  76213. var clockwise = data[i++];
  76214. var dThetaPositive = Math.abs(dTheta);
  76215. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  76216. && !isAroundZero$1(dThetaPositive);
  76217. var large = false;
  76218. if (dThetaPositive >= PI2$7) {
  76219. large = true;
  76220. }
  76221. else if (isAroundZero$1(dThetaPositive)) {
  76222. large = false;
  76223. }
  76224. else {
  76225. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  76226. === !!clockwise;
  76227. }
  76228. var x0 = round4(cx + rx * mathCos$3(theta));
  76229. var y0 = round4(cy + ry * mathSin$3(theta));
  76230. // It will not draw if start point and end point are exactly the same
  76231. // We need to shift the end point with a small value
  76232. // FIXME A better way to draw circle ?
  76233. if (isCircle) {
  76234. if (clockwise) {
  76235. dTheta = PI2$7 - 1e-4;
  76236. }
  76237. else {
  76238. dTheta = -PI2$7 + 1e-4;
  76239. }
  76240. large = true;
  76241. if (i === 9) {
  76242. // Move to (x0, y0) only when CMD.A comes at the
  76243. // first position of a shape.
  76244. // For instance, when drawing a ring, CMD.A comes
  76245. // after CMD.M, so it's unnecessary to move to
  76246. // (x0, y0).
  76247. str.push('M', x0, y0);
  76248. }
  76249. }
  76250. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  76251. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  76252. // FIXME Ellipse
  76253. str.push('A', round4(rx), round4(ry),
  76254. mathRound(psi * degree), +large, +clockwise, x, y);
  76255. break;
  76256. case CMD$4.Z:
  76257. cmdStr = 'Z';
  76258. break;
  76259. case CMD$4.R:
  76260. var x = round4(data[i++]);
  76261. var y = round4(data[i++]);
  76262. var w = round4(data[i++]);
  76263. var h = round4(data[i++]);
  76264. str.push(
  76265. 'M', x, y,
  76266. 'L', x + w, y,
  76267. 'L', x + w, y + h,
  76268. 'L', x, y + h,
  76269. 'L', x, y
  76270. );
  76271. break;
  76272. }
  76273. cmdStr && str.push(cmdStr);
  76274. for (var j = 0; j < nData; j++) {
  76275. // PENDING With scale
  76276. str.push(round4(data[i++]));
  76277. }
  76278. }
  76279. return str.join(' ');
  76280. }
  76281. var svgPath = {};
  76282. svgPath.brush = function (el) {
  76283. var style = el.style;
  76284. var svgEl = el.__svgEl;
  76285. if (!svgEl) {
  76286. svgEl = createElement('path');
  76287. el.__svgEl = svgEl;
  76288. }
  76289. if (!el.path) {
  76290. el.createPathProxy();
  76291. }
  76292. var path = el.path;
  76293. if (el.__dirtyPath) {
  76294. path.beginPath();
  76295. el.buildPath(path, el.shape);
  76296. el.__dirtyPath = false;
  76297. var pathStr = pathDataToString$1(path);
  76298. if (pathStr.indexOf('NaN') < 0) {
  76299. // Ignore illegal path, which may happen such in out-of-range
  76300. // data in Calendar series.
  76301. attr(svgEl, 'd', pathStr);
  76302. }
  76303. }
  76304. bindStyle(svgEl, style);
  76305. setTransform(svgEl, el.transform);
  76306. if (style.text != null) {
  76307. svgTextDrawRectText(el, el.getBoundingRect());
  76308. }
  76309. };
  76310. /***************************************************
  76311. * IMAGE
  76312. **************************************************/
  76313. var svgImage = {};
  76314. svgImage.brush = function (el) {
  76315. var style = el.style;
  76316. var image = style.image;
  76317. if (image instanceof HTMLImageElement) {
  76318. var src = image.src;
  76319. image = src;
  76320. }
  76321. if (! image) {
  76322. return;
  76323. }
  76324. var x = style.x || 0;
  76325. var y = style.y || 0;
  76326. var dw = style.width;
  76327. var dh = style.height;
  76328. var svgEl = el.__svgEl;
  76329. if (! svgEl) {
  76330. svgEl = createElement('image');
  76331. el.__svgEl = svgEl;
  76332. }
  76333. if (image !== el.__imageSrc) {
  76334. attrXLink(svgEl, 'href', image);
  76335. // Caching image src
  76336. el.__imageSrc = image;
  76337. }
  76338. attr(svgEl, 'width', dw);
  76339. attr(svgEl, 'height', dh);
  76340. attr(svgEl, 'x', x);
  76341. attr(svgEl, 'y', y);
  76342. setTransform(svgEl, el.transform);
  76343. if (style.text != null) {
  76344. svgTextDrawRectText(el, el.getBoundingRect());
  76345. }
  76346. };
  76347. /***************************************************
  76348. * TEXT
  76349. **************************************************/
  76350. var svgText = {};
  76351. var tmpRect$3 = new BoundingRect();
  76352. var svgTextDrawRectText = function (el, rect, textRect) {
  76353. var style = el.style;
  76354. el.__dirty && normalizeTextStyle(style, true);
  76355. var text = style.text;
  76356. // Convert to string
  76357. if (text == null) {
  76358. // Draw no text only when text is set to null, but not ''
  76359. return;
  76360. }
  76361. else {
  76362. text += '';
  76363. }
  76364. var textSvgEl = el.__textSvgEl;
  76365. if (! textSvgEl) {
  76366. textSvgEl = createElement('text');
  76367. el.__textSvgEl = textSvgEl;
  76368. }
  76369. var x;
  76370. var y;
  76371. var textPosition = style.textPosition;
  76372. var distance = style.textDistance;
  76373. var align = style.textAlign || 'left';
  76374. if (typeof style.fontSize === 'number') {
  76375. style.fontSize += 'px';
  76376. }
  76377. var font = style.font
  76378. || [
  76379. style.fontStyle || '',
  76380. style.fontWeight || '',
  76381. style.fontSize || '',
  76382. style.fontFamily || ''
  76383. ].join(' ')
  76384. || DEFAULT_FONT;
  76385. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  76386. textRect = getBoundingRect(text, font, align,
  76387. verticalAlign);
  76388. var lineHeight = textRect.lineHeight;
  76389. // Text position represented by coord
  76390. if (textPosition instanceof Array) {
  76391. x = rect.x + textPosition[0];
  76392. y = rect.y + textPosition[1];
  76393. }
  76394. else {
  76395. var newPos = adjustTextPositionOnRect(
  76396. textPosition, rect, distance
  76397. );
  76398. x = newPos.x;
  76399. y = newPos.y;
  76400. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  76401. align = newPos.textAlign;
  76402. }
  76403. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  76404. if (font) {
  76405. textSvgEl.style.font = font;
  76406. }
  76407. var textPadding = style.textPadding;
  76408. // Make baseline top
  76409. attr(textSvgEl, 'x', x);
  76410. attr(textSvgEl, 'y', y);
  76411. bindStyle(textSvgEl, style, true);
  76412. if (el instanceof Text || el.style.transformText) {
  76413. // Transform text with element
  76414. setTransform(textSvgEl, el.transform);
  76415. }
  76416. else {
  76417. if (el.transform) {
  76418. tmpRect$3.copy(rect);
  76419. tmpRect$3.applyTransform(el.transform);
  76420. rect = tmpRect$3;
  76421. }
  76422. else {
  76423. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  76424. rect.x = pos[0];
  76425. rect.y = pos[1];
  76426. }
  76427. // Text rotation, but no element transform
  76428. var origin = style.textOrigin;
  76429. if (origin === 'center') {
  76430. x = textRect.width / 2 + x;
  76431. y = textRect.height / 2 + y;
  76432. }
  76433. else if (origin) {
  76434. x = origin[0] + x;
  76435. y = origin[1] + y;
  76436. }
  76437. var rotate$$1 = -style.textRotation || 0;
  76438. var transform = create$1();
  76439. // Apply textRotate to element matrix
  76440. rotate(transform, el.transform, rotate$$1);
  76441. setTransform(textSvgEl, transform);
  76442. }
  76443. var textLines = text.split('\n');
  76444. var nTextLines = textLines.length;
  76445. var textAnchor = align;
  76446. // PENDING
  76447. if (textAnchor === 'left') {
  76448. textAnchor = 'start';
  76449. textPadding && (x += textPadding[3]);
  76450. }
  76451. else if (textAnchor === 'right') {
  76452. textAnchor = 'end';
  76453. textPadding && (x -= textPadding[1]);
  76454. }
  76455. else if (textAnchor === 'center') {
  76456. textAnchor = 'middle';
  76457. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  76458. }
  76459. var dy = 0;
  76460. if (verticalAlign === 'baseline') {
  76461. dy = -textRect.height + lineHeight;
  76462. textPadding && (dy -= textPadding[2]);
  76463. }
  76464. else if (verticalAlign === 'middle') {
  76465. dy = (-textRect.height + lineHeight) / 2;
  76466. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  76467. }
  76468. else {
  76469. textPadding && (dy += textPadding[0]);
  76470. }
  76471. // Font may affect position of each tspan elements
  76472. if (el.__text !== text || el.__textFont !== font) {
  76473. var tspanList = el.__tspanList || [];
  76474. el.__tspanList = tspanList;
  76475. for (var i = 0; i < nTextLines; i++) {
  76476. // Using cached tspan elements
  76477. var tspan = tspanList[i];
  76478. if (! tspan) {
  76479. tspan = tspanList[i] = createElement('tspan');
  76480. textSvgEl.appendChild(tspan);
  76481. attr(tspan, 'alignment-baseline', verticalAlign);
  76482. attr(tspan, 'text-anchor', textAnchor);
  76483. }
  76484. else {
  76485. tspan.innerHTML = '';
  76486. }
  76487. attr(tspan, 'x', x);
  76488. attr(tspan, 'y', y + i * lineHeight + dy);
  76489. tspan.appendChild(document.createTextNode(textLines[i]));
  76490. }
  76491. // Remove unsed tspan elements
  76492. for (; i < tspanList.length; i++) {
  76493. textSvgEl.removeChild(tspanList[i]);
  76494. }
  76495. tspanList.length = nTextLines;
  76496. el.__text = text;
  76497. el.__textFont = font;
  76498. }
  76499. else if (el.__tspanList.length) {
  76500. // Update span x and y
  76501. var len = el.__tspanList.length;
  76502. for (var i = 0; i < len; ++i) {
  76503. var tspan = el.__tspanList[i];
  76504. if (tspan) {
  76505. attr(tspan, 'x', x);
  76506. attr(tspan, 'y', y + i * lineHeight + dy);
  76507. }
  76508. }
  76509. }
  76510. };
  76511. function getVerticalAlignForSvg(verticalAlign) {
  76512. if (verticalAlign === 'middle') {
  76513. return 'middle';
  76514. }
  76515. else if (verticalAlign === 'bottom') {
  76516. return 'baseline';
  76517. }
  76518. else {
  76519. return 'hanging';
  76520. }
  76521. }
  76522. svgText.drawRectText = svgTextDrawRectText;
  76523. svgText.brush = function (el) {
  76524. var style = el.style;
  76525. if (style.text != null) {
  76526. // 强制设置 textPosition
  76527. style.textPosition = [0, 0];
  76528. svgTextDrawRectText(el, {
  76529. x: style.x || 0, y: style.y || 0,
  76530. width: 0, height: 0
  76531. }, el.getBoundingRect());
  76532. }
  76533. };
  76534. // Myers' Diff Algorithm
  76535. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  76536. function Diff() {}
  76537. Diff.prototype = {
  76538. diff: function (oldArr, newArr, equals) {
  76539. if (!equals) {
  76540. equals = function (a, b) {
  76541. return a === b;
  76542. };
  76543. }
  76544. this.equals = equals;
  76545. var self = this;
  76546. oldArr = oldArr.slice();
  76547. newArr = newArr.slice();
  76548. // Allow subclasses to massage the input prior to running
  76549. var newLen = newArr.length;
  76550. var oldLen = oldArr.length;
  76551. var editLength = 1;
  76552. var maxEditLength = newLen + oldLen;
  76553. var bestPath = [{ newPos: -1, components: [] }];
  76554. // Seed editLength = 0, i.e. the content starts with the same values
  76555. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  76556. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  76557. var indices = [];
  76558. for (var i = 0; i < newArr.length; i++) {
  76559. indices.push(i);
  76560. }
  76561. // Identity per the equality and tokenizer
  76562. return [{
  76563. indices: indices, count: newArr.length
  76564. }];
  76565. }
  76566. // Main worker method. checks all permutations of a given edit length for acceptance.
  76567. function execEditLength() {
  76568. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  76569. var basePath;
  76570. var addPath = bestPath[diagonalPath - 1];
  76571. var removePath = bestPath[diagonalPath + 1];
  76572. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  76573. if (addPath) {
  76574. // No one else is going to attempt to use this value, clear it
  76575. bestPath[diagonalPath - 1] = undefined;
  76576. }
  76577. var canAdd = addPath && addPath.newPos + 1 < newLen;
  76578. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  76579. if (!canAdd && !canRemove) {
  76580. // If this path is a terminal then prune
  76581. bestPath[diagonalPath] = undefined;
  76582. continue;
  76583. }
  76584. // Select the diagonal that we want to branch from. We select the prior
  76585. // path whose position in the new string is the farthest from the origin
  76586. // and does not pass the bounds of the diff graph
  76587. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  76588. basePath = clonePath(removePath);
  76589. self.pushComponent(basePath.components, undefined, true);
  76590. }
  76591. else {
  76592. basePath = addPath; // No need to clone, we've pulled it from the list
  76593. basePath.newPos++;
  76594. self.pushComponent(basePath.components, true, undefined);
  76595. }
  76596. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  76597. // If we have hit the end of both strings, then we are done
  76598. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  76599. return buildValues(self, basePath.components, newArr, oldArr);
  76600. }
  76601. else {
  76602. // Otherwise track this path as a potential candidate and continue.
  76603. bestPath[diagonalPath] = basePath;
  76604. }
  76605. }
  76606. editLength++;
  76607. }
  76608. while (editLength <= maxEditLength) {
  76609. var ret = execEditLength();
  76610. if (ret) {
  76611. return ret;
  76612. }
  76613. }
  76614. },
  76615. pushComponent: function (components, added, removed) {
  76616. var last = components[components.length - 1];
  76617. if (last && last.added === added && last.removed === removed) {
  76618. // We need to clone here as the component clone operation is just
  76619. // as shallow array clone
  76620. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  76621. }
  76622. else {
  76623. components.push({count: 1, added: added, removed: removed });
  76624. }
  76625. },
  76626. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  76627. var newLen = newArr.length;
  76628. var oldLen = oldArr.length;
  76629. var newPos = basePath.newPos;
  76630. var oldPos = newPos - diagonalPath;
  76631. var commonCount = 0;
  76632. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  76633. newPos++;
  76634. oldPos++;
  76635. commonCount++;
  76636. }
  76637. if (commonCount) {
  76638. basePath.components.push({count: commonCount});
  76639. }
  76640. basePath.newPos = newPos;
  76641. return oldPos;
  76642. },
  76643. tokenize: function (value) {
  76644. return value.slice();
  76645. },
  76646. join: function (value) {
  76647. return value.slice();
  76648. }
  76649. };
  76650. function buildValues(diff, components, newArr, oldArr) {
  76651. var componentPos = 0;
  76652. var componentLen = components.length;
  76653. var newPos = 0;
  76654. var oldPos = 0;
  76655. for (; componentPos < componentLen; componentPos++) {
  76656. var component = components[componentPos];
  76657. if (!component.removed) {
  76658. var indices = [];
  76659. for (var i = newPos; i < newPos + component.count; i++) {
  76660. indices.push(i);
  76661. }
  76662. component.indices = indices;
  76663. newPos += component.count;
  76664. // Common case
  76665. if (!component.added) {
  76666. oldPos += component.count;
  76667. }
  76668. }
  76669. else {
  76670. var indices = [];
  76671. for (var i = oldPos; i < oldPos + component.count; i++) {
  76672. indices.push(i);
  76673. }
  76674. component.indices = indices;
  76675. oldPos += component.count;
  76676. }
  76677. }
  76678. return components;
  76679. }
  76680. function clonePath(path) {
  76681. return { newPos: path.newPos, components: path.components.slice(0) };
  76682. }
  76683. var arrayDiff = new Diff();
  76684. var arrayDiff$1 = function (oldArr, newArr, callback) {
  76685. return arrayDiff.diff(oldArr, newArr, callback);
  76686. };
  76687. /**
  76688. * @file Manages elements that can be defined in <defs> in SVG,
  76689. * e.g., gradients, clip path, etc.
  76690. * @author Zhang Wenli
  76691. */
  76692. var MARK_UNUSED = '0';
  76693. var MARK_USED = '1';
  76694. /**
  76695. * Manages elements that can be defined in <defs> in SVG,
  76696. * e.g., gradients, clip path, etc.
  76697. *
  76698. * @class
  76699. * @param {number} zrId zrender instance id
  76700. * @param {SVGElement} svgRoot root of SVG document
  76701. * @param {string|string[]} tagNames possible tag names
  76702. * @param {string} markLabel label name to make if the element
  76703. * is used
  76704. */
  76705. function Definable(
  76706. zrId,
  76707. svgRoot,
  76708. tagNames,
  76709. markLabel,
  76710. domName
  76711. ) {
  76712. this._zrId = zrId;
  76713. this._svgRoot = svgRoot;
  76714. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  76715. this._markLabel = markLabel;
  76716. this._domName = domName || '_dom';
  76717. this.nextId = 0;
  76718. }
  76719. Definable.prototype.createElement = createElement;
  76720. /**
  76721. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  76722. *
  76723. * @param {boolean} isForceCreating if need to create when not exists
  76724. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  76725. * exist and isForceCreating is false
  76726. */
  76727. Definable.prototype.getDefs = function (isForceCreating) {
  76728. var svgRoot = this._svgRoot;
  76729. var defs = this._svgRoot.getElementsByTagName('defs');
  76730. if (defs.length === 0) {
  76731. // Not exist
  76732. if (isForceCreating) {
  76733. defs = svgRoot.insertBefore(
  76734. this.createElement('defs'), // Create new tag
  76735. svgRoot.firstChild // Insert in the front of svg
  76736. );
  76737. if (!defs.contains) {
  76738. // IE doesn't support contains method
  76739. defs.contains = function (el) {
  76740. var children = defs.children;
  76741. if (!children) {
  76742. return false;
  76743. }
  76744. for (var i = children.length - 1; i >= 0; --i) {
  76745. if (children[i] === el) {
  76746. return true;
  76747. }
  76748. }
  76749. return false;
  76750. };
  76751. }
  76752. return defs;
  76753. }
  76754. else {
  76755. return null;
  76756. }
  76757. }
  76758. else {
  76759. return defs[0];
  76760. }
  76761. };
  76762. /**
  76763. * Update DOM element if necessary.
  76764. *
  76765. * @param {Object|string} element style element. e.g., for gradient,
  76766. * it may be '#ccc' or {type: 'linear', ...}
  76767. * @param {Function|undefined} onUpdate update callback
  76768. */
  76769. Definable.prototype.update = function (element, onUpdate) {
  76770. if (!element) {
  76771. return;
  76772. }
  76773. var defs = this.getDefs(false);
  76774. if (element[this._domName] && defs.contains(element[this._domName])) {
  76775. // Update DOM
  76776. if (typeof onUpdate === 'function') {
  76777. onUpdate(element);
  76778. }
  76779. }
  76780. else {
  76781. // No previous dom, create new
  76782. var dom = this.add(element);
  76783. if (dom) {
  76784. element[this._domName] = dom;
  76785. }
  76786. }
  76787. };
  76788. /**
  76789. * Add gradient dom to defs
  76790. *
  76791. * @param {SVGElement} dom DOM to be added to <defs>
  76792. */
  76793. Definable.prototype.addDom = function (dom) {
  76794. var defs = this.getDefs(true);
  76795. defs.appendChild(dom);
  76796. };
  76797. /**
  76798. * Remove DOM of a given element.
  76799. *
  76800. * @param {SVGElement} element element to remove dom
  76801. */
  76802. Definable.prototype.removeDom = function (element) {
  76803. var defs = this.getDefs(false);
  76804. if (defs && element[this._domName]) {
  76805. defs.removeChild(element[this._domName]);
  76806. element[this._domName] = null;
  76807. }
  76808. };
  76809. /**
  76810. * Get DOMs of this element.
  76811. *
  76812. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  76813. */
  76814. Definable.prototype.getDoms = function () {
  76815. var defs = this.getDefs(false);
  76816. if (!defs) {
  76817. // No dom when defs is not defined
  76818. return [];
  76819. }
  76820. var doms = [];
  76821. each$1(this._tagNames, function (tagName) {
  76822. var tags = defs.getElementsByTagName(tagName);
  76823. // Note that tags is HTMLCollection, which is array-like
  76824. // rather than real array.
  76825. // So `doms.concat(tags)` add tags as one object.
  76826. doms = doms.concat([].slice.call(tags));
  76827. });
  76828. return doms;
  76829. };
  76830. /**
  76831. * Mark DOMs to be unused before painting, and clear unused ones at the end
  76832. * of the painting.
  76833. */
  76834. Definable.prototype.markAllUnused = function () {
  76835. var doms = this.getDoms();
  76836. var that = this;
  76837. each$1(doms, function (dom) {
  76838. dom[that._markLabel] = MARK_UNUSED;
  76839. });
  76840. };
  76841. /**
  76842. * Mark a single DOM to be used.
  76843. *
  76844. * @param {SVGElement} dom DOM to mark
  76845. */
  76846. Definable.prototype.markUsed = function (dom) {
  76847. if (dom) {
  76848. dom[this._markLabel] = MARK_USED;
  76849. }
  76850. };
  76851. /**
  76852. * Remove unused DOMs defined in <defs>
  76853. */
  76854. Definable.prototype.removeUnused = function () {
  76855. var defs = this.getDefs(false);
  76856. if (!defs) {
  76857. // Nothing to remove
  76858. return;
  76859. }
  76860. var doms = this.getDoms();
  76861. var that = this;
  76862. each$1(doms, function (dom) {
  76863. if (dom[that._markLabel] !== MARK_USED) {
  76864. // Remove gradient
  76865. defs.removeChild(dom);
  76866. }
  76867. });
  76868. };
  76869. /**
  76870. * Get SVG proxy.
  76871. *
  76872. * @param {Displayable} displayable displayable element
  76873. * @return {Path|Image|Text} svg proxy of given element
  76874. */
  76875. Definable.prototype.getSvgProxy = function (displayable) {
  76876. if (displayable instanceof Path) {
  76877. return svgPath;
  76878. }
  76879. else if (displayable instanceof ZImage) {
  76880. return svgImage;
  76881. }
  76882. else if (displayable instanceof Text) {
  76883. return svgText;
  76884. }
  76885. else {
  76886. return svgPath;
  76887. }
  76888. };
  76889. /**
  76890. * Get text SVG element.
  76891. *
  76892. * @param {Displayable} displayable displayable element
  76893. * @return {SVGElement} SVG element of text
  76894. */
  76895. Definable.prototype.getTextSvgElement = function (displayable) {
  76896. return displayable.__textSvgEl;
  76897. };
  76898. /**
  76899. * Get SVG element.
  76900. *
  76901. * @param {Displayable} displayable displayable element
  76902. * @return {SVGElement} SVG element
  76903. */
  76904. Definable.prototype.getSvgElement = function (displayable) {
  76905. return displayable.__svgEl;
  76906. };
  76907. /**
  76908. * @file Manages SVG gradient elements.
  76909. * @author Zhang Wenli
  76910. */
  76911. /**
  76912. * Manages SVG gradient elements.
  76913. *
  76914. * @class
  76915. * @extends Definable
  76916. * @param {number} zrId zrender instance id
  76917. * @param {SVGElement} svgRoot root of SVG document
  76918. */
  76919. function GradientManager(zrId, svgRoot) {
  76920. Definable.call(
  76921. this,
  76922. zrId,
  76923. svgRoot,
  76924. ['linearGradient', 'radialGradient'],
  76925. '__gradient_in_use__'
  76926. );
  76927. }
  76928. inherits(GradientManager, Definable);
  76929. /**
  76930. * Create new gradient DOM for fill or stroke if not exist,
  76931. * but will not update gradient if exists.
  76932. *
  76933. * @param {SvgElement} svgElement SVG element to paint
  76934. * @param {Displayable} displayable zrender displayable element
  76935. */
  76936. GradientManager.prototype.addWithoutUpdate = function (
  76937. svgElement,
  76938. displayable
  76939. ) {
  76940. if (displayable && displayable.style) {
  76941. var that = this;
  76942. each$1(['fill', 'stroke'], function (fillOrStroke) {
  76943. if (displayable.style[fillOrStroke]
  76944. && (displayable.style[fillOrStroke].type === 'linear'
  76945. || displayable.style[fillOrStroke].type === 'radial')
  76946. ) {
  76947. var gradient = displayable.style[fillOrStroke];
  76948. var defs = that.getDefs(true);
  76949. // Create dom in <defs> if not exists
  76950. var dom;
  76951. if (gradient._dom) {
  76952. // Gradient exists
  76953. dom = gradient._dom;
  76954. if (!defs.contains(gradient._dom)) {
  76955. // _dom is no longer in defs, recreate
  76956. that.addDom(dom);
  76957. }
  76958. }
  76959. else {
  76960. // New dom
  76961. dom = that.add(gradient);
  76962. }
  76963. that.markUsed(displayable);
  76964. var id = dom.getAttribute('id');
  76965. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  76966. }
  76967. });
  76968. }
  76969. };
  76970. /**
  76971. * Add a new gradient tag in <defs>
  76972. *
  76973. * @param {Gradient} gradient zr gradient instance
  76974. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  76975. * created DOM
  76976. */
  76977. GradientManager.prototype.add = function (gradient) {
  76978. var dom;
  76979. if (gradient.type === 'linear') {
  76980. dom = this.createElement('linearGradient');
  76981. }
  76982. else if (gradient.type === 'radial') {
  76983. dom = this.createElement('radialGradient');
  76984. }
  76985. else {
  76986. zrLog('Illegal gradient type.');
  76987. return null;
  76988. }
  76989. // Set dom id with gradient id, since each gradient instance
  76990. // will have no more than one dom element.
  76991. // id may exists before for those dirty elements, in which case
  76992. // id should remain the same, and other attributes should be
  76993. // updated.
  76994. gradient.id = gradient.id || this.nextId++;
  76995. dom.setAttribute('id', 'zr' + this._zrId
  76996. + '-gradient-' + gradient.id);
  76997. this.updateDom(gradient, dom);
  76998. this.addDom(dom);
  76999. return dom;
  77000. };
  77001. /**
  77002. * Update gradient.
  77003. *
  77004. * @param {Gradient} gradient zr gradient instance
  77005. */
  77006. GradientManager.prototype.update = function (gradient) {
  77007. var that = this;
  77008. Definable.prototype.update.call(this, gradient, function () {
  77009. var type = gradient.type;
  77010. var tagName = gradient._dom.tagName;
  77011. if (type === 'linear' && tagName === 'linearGradient'
  77012. || type === 'radial' && tagName === 'radialGradient'
  77013. ) {
  77014. // Gradient type is not changed, update gradient
  77015. that.updateDom(gradient, gradient._dom);
  77016. }
  77017. else {
  77018. // Remove and re-create if type is changed
  77019. that.removeDom(gradient);
  77020. that.add(gradient);
  77021. }
  77022. });
  77023. };
  77024. /**
  77025. * Update gradient dom
  77026. *
  77027. * @param {Gradient} gradient zr gradient instance
  77028. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  77029. * DOM to update
  77030. */
  77031. GradientManager.prototype.updateDom = function (gradient, dom) {
  77032. if (gradient.type === 'linear') {
  77033. dom.setAttribute('x1', gradient.x);
  77034. dom.setAttribute('y1', gradient.y);
  77035. dom.setAttribute('x2', gradient.x2);
  77036. dom.setAttribute('y2', gradient.y2);
  77037. }
  77038. else if (gradient.type === 'radial') {
  77039. dom.setAttribute('cx', gradient.x);
  77040. dom.setAttribute('cy', gradient.y);
  77041. dom.setAttribute('r', gradient.r);
  77042. }
  77043. else {
  77044. zrLog('Illegal gradient type.');
  77045. return;
  77046. }
  77047. if (gradient.global) {
  77048. // x1, x2, y1, y2 in range of 0 to canvas width or height
  77049. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  77050. }
  77051. else {
  77052. // x1, x2, y1, y2 in range of 0 to 1
  77053. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  77054. }
  77055. // Remove color stops if exists
  77056. dom.innerHTML = '';
  77057. // Add color stops
  77058. var colors = gradient.colorStops;
  77059. for (var i = 0, len = colors.length; i < len; ++i) {
  77060. var stop = this.createElement('stop');
  77061. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  77062. stop.setAttribute('stop-color', colors[i].color);
  77063. dom.appendChild(stop);
  77064. }
  77065. // Store dom element in gradient, to avoid creating multiple
  77066. // dom instances for the same gradient element
  77067. gradient._dom = dom;
  77068. };
  77069. /**
  77070. * Mark a single gradient to be used
  77071. *
  77072. * @param {Displayable} displayable displayable element
  77073. */
  77074. GradientManager.prototype.markUsed = function (displayable) {
  77075. if (displayable.style) {
  77076. var gradient = displayable.style.fill;
  77077. if (gradient && gradient._dom) {
  77078. Definable.prototype.markUsed.call(this, gradient._dom);
  77079. }
  77080. gradient = displayable.style.stroke;
  77081. if (gradient && gradient._dom) {
  77082. Definable.prototype.markUsed.call(this, gradient._dom);
  77083. }
  77084. }
  77085. };
  77086. /**
  77087. * @file Manages SVG clipPath elements.
  77088. * @author Zhang Wenli
  77089. */
  77090. /**
  77091. * Manages SVG clipPath elements.
  77092. *
  77093. * @class
  77094. * @extends Definable
  77095. * @param {number} zrId zrender instance id
  77096. * @param {SVGElement} svgRoot root of SVG document
  77097. */
  77098. function ClippathManager(zrId, svgRoot) {
  77099. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  77100. }
  77101. inherits(ClippathManager, Definable);
  77102. /**
  77103. * Update clipPath.
  77104. *
  77105. * @param {Displayable} displayable displayable element
  77106. */
  77107. ClippathManager.prototype.update = function (displayable) {
  77108. var svgEl = this.getSvgElement(displayable);
  77109. if (svgEl) {
  77110. this.updateDom(svgEl, displayable.__clipPaths, false);
  77111. }
  77112. var textEl = this.getTextSvgElement(displayable);
  77113. if (textEl) {
  77114. // Make another clipPath for text, since it's transform
  77115. // matrix is not the same with svgElement
  77116. this.updateDom(textEl, displayable.__clipPaths, true);
  77117. }
  77118. this.markUsed(displayable);
  77119. };
  77120. /**
  77121. * Create an SVGElement of displayable and create a <clipPath> of its
  77122. * clipPath
  77123. *
  77124. * @param {Displayable} parentEl parent element
  77125. * @param {ClipPath[]} clipPaths clipPaths of parent element
  77126. * @param {boolean} isText if parent element is Text
  77127. */
  77128. ClippathManager.prototype.updateDom = function (
  77129. parentEl,
  77130. clipPaths,
  77131. isText
  77132. ) {
  77133. if (clipPaths && clipPaths.length > 0) {
  77134. // Has clipPath, create <clipPath> with the first clipPath
  77135. var defs = this.getDefs(true);
  77136. var clipPath = clipPaths[0];
  77137. var clipPathEl;
  77138. var id;
  77139. var dom = isText ? '_textDom' : '_dom';
  77140. if (clipPath[dom]) {
  77141. // Use a dom that is already in <defs>
  77142. id = clipPath[dom].getAttribute('id');
  77143. clipPathEl = clipPath[dom];
  77144. // Use a dom that is already in <defs>
  77145. if (!defs.contains(clipPathEl)) {
  77146. // This happens when set old clipPath that has
  77147. // been previously removed
  77148. defs.appendChild(clipPathEl);
  77149. }
  77150. }
  77151. else {
  77152. // New <clipPath>
  77153. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  77154. ++this.nextId;
  77155. clipPathEl = this.createElement('clipPath');
  77156. clipPathEl.setAttribute('id', id);
  77157. defs.appendChild(clipPathEl);
  77158. clipPath[dom] = clipPathEl;
  77159. }
  77160. // Build path and add to <clipPath>
  77161. var svgProxy = this.getSvgProxy(clipPath);
  77162. if (clipPath.transform
  77163. && clipPath.parent.invTransform
  77164. && !isText
  77165. ) {
  77166. /**
  77167. * If a clipPath has a parent with transform, the transform
  77168. * of parent should not be considered when setting transform
  77169. * of clipPath. So we need to transform back from parent's
  77170. * transform, which is done by multiplying parent's inverse
  77171. * transform.
  77172. */
  77173. // Store old transform
  77174. var transform = Array.prototype.slice.call(
  77175. clipPath.transform
  77176. );
  77177. // Transform back from parent, and brush path
  77178. mul$1(
  77179. clipPath.transform,
  77180. clipPath.parent.invTransform,
  77181. clipPath.transform
  77182. );
  77183. svgProxy.brush(clipPath);
  77184. // Set back transform of clipPath
  77185. clipPath.transform = transform;
  77186. }
  77187. else {
  77188. svgProxy.brush(clipPath);
  77189. }
  77190. var pathEl = this.getSvgElement(clipPath);
  77191. clipPathEl.innerHTML = '';
  77192. /**
  77193. * Use `cloneNode()` here to appendChild to multiple parents,
  77194. * which may happend when Text and other shapes are using the same
  77195. * clipPath. Since Text will create an extra clipPath DOM due to
  77196. * different transform rules.
  77197. */
  77198. clipPathEl.appendChild(pathEl.cloneNode());
  77199. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  77200. if (clipPaths.length > 1) {
  77201. // Make the other clipPaths recursively
  77202. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  77203. }
  77204. }
  77205. else {
  77206. // No clipPath
  77207. if (parentEl) {
  77208. parentEl.setAttribute('clip-path', 'none');
  77209. }
  77210. }
  77211. };
  77212. /**
  77213. * Mark a single clipPath to be used
  77214. *
  77215. * @param {Displayable} displayable displayable element
  77216. */
  77217. ClippathManager.prototype.markUsed = function (displayable) {
  77218. var that = this;
  77219. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  77220. each$1(displayable.__clipPaths, function (clipPath) {
  77221. if (clipPath._dom) {
  77222. Definable.prototype.markUsed.call(that, clipPath._dom);
  77223. }
  77224. if (clipPath._textDom) {
  77225. Definable.prototype.markUsed.call(that, clipPath._textDom);
  77226. }
  77227. });
  77228. }
  77229. };
  77230. /**
  77231. * @file Manages SVG shadow elements.
  77232. * @author Zhang Wenli
  77233. */
  77234. /**
  77235. * Manages SVG shadow elements.
  77236. *
  77237. * @class
  77238. * @extends Definable
  77239. * @param {number} zrId zrender instance id
  77240. * @param {SVGElement} svgRoot root of SVG document
  77241. */
  77242. function ShadowManager(zrId, svgRoot) {
  77243. Definable.call(
  77244. this,
  77245. zrId,
  77246. svgRoot,
  77247. ['filter'],
  77248. '__filter_in_use__',
  77249. '_shadowDom'
  77250. );
  77251. }
  77252. inherits(ShadowManager, Definable);
  77253. /**
  77254. * Create new shadow DOM for fill or stroke if not exist,
  77255. * but will not update shadow if exists.
  77256. *
  77257. * @param {SvgElement} svgElement SVG element to paint
  77258. * @param {Displayable} displayable zrender displayable element
  77259. */
  77260. ShadowManager.prototype.addWithoutUpdate = function (
  77261. svgElement,
  77262. displayable
  77263. ) {
  77264. if (displayable && hasShadow(displayable.style)) {
  77265. var style = displayable.style;
  77266. // Create dom in <defs> if not exists
  77267. var dom;
  77268. if (style._shadowDom) {
  77269. // Gradient exists
  77270. dom = style._shadowDom;
  77271. var defs = this.getDefs(true);
  77272. if (!defs.contains(style._shadowDom)) {
  77273. // _shadowDom is no longer in defs, recreate
  77274. this.addDom(dom);
  77275. }
  77276. }
  77277. else {
  77278. // New dom
  77279. dom = this.add(displayable);
  77280. }
  77281. this.markUsed(displayable);
  77282. var id = dom.getAttribute('id');
  77283. svgElement.style.filter = 'url(#' + id + ')';
  77284. }
  77285. };
  77286. /**
  77287. * Add a new shadow tag in <defs>
  77288. *
  77289. * @param {Displayable} displayable zrender displayable element
  77290. * @return {SVGFilterElement} created DOM
  77291. */
  77292. ShadowManager.prototype.add = function (displayable) {
  77293. var dom = this.createElement('filter');
  77294. var style = displayable.style;
  77295. // Set dom id with shadow id, since each shadow instance
  77296. // will have no more than one dom element.
  77297. // id may exists before for those dirty elements, in which case
  77298. // id should remain the same, and other attributes should be
  77299. // updated.
  77300. style._shadowDomId = style._shadowDomId || this.nextId++;
  77301. dom.setAttribute('id', 'zr' + this._zrId
  77302. + '-shadow-' + style._shadowDomId);
  77303. this.updateDom(displayable, dom);
  77304. this.addDom(dom);
  77305. return dom;
  77306. };
  77307. /**
  77308. * Update shadow.
  77309. *
  77310. * @param {Displayable} displayable zrender displayable element
  77311. */
  77312. ShadowManager.prototype.update = function (svgElement, displayable) {
  77313. var style = displayable.style;
  77314. if (hasShadow(style)) {
  77315. var that = this;
  77316. Definable.prototype.update.call(this, displayable, function (style) {
  77317. that.updateDom(displayable, style._shadowDom);
  77318. });
  77319. }
  77320. else {
  77321. // Remove shadow
  77322. this.remove(svgElement, style);
  77323. }
  77324. };
  77325. /**
  77326. * Remove DOM and clear parent filter
  77327. */
  77328. ShadowManager.prototype.remove = function (svgElement, style) {
  77329. if (style._shadowDomId != null) {
  77330. this.removeDom(style);
  77331. svgElement.style.filter = '';
  77332. }
  77333. };
  77334. /**
  77335. * Update shadow dom
  77336. *
  77337. * @param {Displayable} displayable zrender displayable element
  77338. * @param {SVGFilterElement} dom DOM to update
  77339. */
  77340. ShadowManager.prototype.updateDom = function (displayable, dom) {
  77341. var domChild = dom.getElementsByTagName('feDropShadow');
  77342. if (domChild.length === 0) {
  77343. domChild = this.createElement('feDropShadow');
  77344. }
  77345. else {
  77346. domChild = domChild[0];
  77347. }
  77348. var style = displayable.style;
  77349. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  77350. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  77351. // TODO: textBoxShadowBlur is not supported yet
  77352. var offsetX, offsetY, blur, color;
  77353. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  77354. offsetX = style.shadowOffsetX || 0;
  77355. offsetY = style.shadowOffsetY || 0;
  77356. blur = style.shadowBlur;
  77357. color = style.shadowColor;
  77358. }
  77359. else if (style.textShadowBlur) {
  77360. offsetX = style.textShadowOffsetX || 0;
  77361. offsetY = style.textShadowOffsetY || 0;
  77362. blur = style.textShadowBlur;
  77363. color = style.textShadowColor;
  77364. }
  77365. else {
  77366. // Remove shadow
  77367. this.removeDom(dom, style);
  77368. return;
  77369. }
  77370. domChild.setAttribute('dx', offsetX / scaleX);
  77371. domChild.setAttribute('dy', offsetY / scaleY);
  77372. domChild.setAttribute('flood-color', color);
  77373. // Divide by two here so that it looks the same as in canvas
  77374. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  77375. var stdDx = blur / 2 / scaleX;
  77376. var stdDy = blur / 2 / scaleY;
  77377. var stdDeviation = stdDx + ' ' + stdDy;
  77378. domChild.setAttribute('stdDeviation', stdDeviation);
  77379. // Fix filter clipping problem
  77380. dom.setAttribute('x', '-100%');
  77381. dom.setAttribute('y', '-100%');
  77382. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  77383. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  77384. dom.appendChild(domChild);
  77385. // Store dom element in shadow, to avoid creating multiple
  77386. // dom instances for the same shadow element
  77387. style._shadowDom = dom;
  77388. };
  77389. /**
  77390. * Mark a single shadow to be used
  77391. *
  77392. * @param {Displayable} displayable displayable element
  77393. */
  77394. ShadowManager.prototype.markUsed = function (displayable) {
  77395. var style = displayable.style;
  77396. if (style && style._shadowDom) {
  77397. Definable.prototype.markUsed.call(this, style._shadowDom);
  77398. }
  77399. };
  77400. function hasShadow(style) {
  77401. // TODO: textBoxShadowBlur is not supported yet
  77402. return style
  77403. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  77404. || style.textShadowBlur || style.textShadowOffsetX
  77405. || style.textShadowOffsetY);
  77406. }
  77407. /**
  77408. * SVG Painter
  77409. * @module zrender/svg/Painter
  77410. */
  77411. function parseInt10$2(val) {
  77412. return parseInt(val, 10);
  77413. }
  77414. function getSvgProxy(el) {
  77415. if (el instanceof Path) {
  77416. return svgPath;
  77417. }
  77418. else if (el instanceof ZImage) {
  77419. return svgImage;
  77420. }
  77421. else if (el instanceof Text) {
  77422. return svgText;
  77423. }
  77424. else {
  77425. return svgPath;
  77426. }
  77427. }
  77428. function checkParentAvailable(parent, child) {
  77429. return child && parent && child.parentNode !== parent;
  77430. }
  77431. function insertAfter(parent, child, prevSibling) {
  77432. if (checkParentAvailable(parent, child) && prevSibling) {
  77433. var nextSibling = prevSibling.nextSibling;
  77434. nextSibling ? parent.insertBefore(child, nextSibling)
  77435. : parent.appendChild(child);
  77436. }
  77437. }
  77438. function prepend(parent, child) {
  77439. if (checkParentAvailable(parent, child)) {
  77440. var firstChild = parent.firstChild;
  77441. firstChild ? parent.insertBefore(child, firstChild)
  77442. : parent.appendChild(child);
  77443. }
  77444. }
  77445. function remove$1(parent, child) {
  77446. if (child && parent && child.parentNode === parent) {
  77447. parent.removeChild(child);
  77448. }
  77449. }
  77450. function getTextSvgElement(displayable) {
  77451. return displayable.__textSvgEl;
  77452. }
  77453. function getSvgElement(displayable) {
  77454. return displayable.__svgEl;
  77455. }
  77456. /**
  77457. * @alias module:zrender/svg/Painter
  77458. * @constructor
  77459. * @param {HTMLElement} root 绘图容器
  77460. * @param {module:zrender/Storage} storage
  77461. * @param {Object} opts
  77462. */
  77463. var SVGPainter = function (root, storage, opts, zrId) {
  77464. this.root = root;
  77465. this.storage = storage;
  77466. this._opts = opts = extend({}, opts || {});
  77467. var svgRoot = createElement('svg');
  77468. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  77469. svgRoot.setAttribute('version', '1.1');
  77470. svgRoot.setAttribute('baseProfile', 'full');
  77471. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  77472. this.gradientManager = new GradientManager(zrId, svgRoot);
  77473. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  77474. this.shadowManager = new ShadowManager(zrId, svgRoot);
  77475. var viewport = document.createElement('div');
  77476. viewport.style.cssText = 'overflow:hidden;position:relative';
  77477. this._svgRoot = svgRoot;
  77478. this._viewport = viewport;
  77479. root.appendChild(viewport);
  77480. viewport.appendChild(svgRoot);
  77481. this.resize(opts.width, opts.height);
  77482. this._visibleList = [];
  77483. };
  77484. SVGPainter.prototype = {
  77485. constructor: SVGPainter,
  77486. getType: function () {
  77487. return 'svg';
  77488. },
  77489. getViewportRoot: function () {
  77490. return this._viewport;
  77491. },
  77492. getViewportRootOffset: function () {
  77493. var viewportRoot = this.getViewportRoot();
  77494. if (viewportRoot) {
  77495. return {
  77496. offsetLeft: viewportRoot.offsetLeft || 0,
  77497. offsetTop: viewportRoot.offsetTop || 0
  77498. };
  77499. }
  77500. },
  77501. refresh: function () {
  77502. var list = this.storage.getDisplayList(true);
  77503. this._paintList(list);
  77504. },
  77505. setBackgroundColor: function (backgroundColor) {
  77506. // TODO gradient
  77507. this._viewport.style.background = backgroundColor;
  77508. },
  77509. _paintList: function (list) {
  77510. this.gradientManager.markAllUnused();
  77511. this.clipPathManager.markAllUnused();
  77512. this.shadowManager.markAllUnused();
  77513. var svgRoot = this._svgRoot;
  77514. var visibleList = this._visibleList;
  77515. var listLen = list.length;
  77516. var newVisibleList = [];
  77517. var i;
  77518. for (i = 0; i < listLen; i++) {
  77519. var displayable = list[i];
  77520. var svgProxy = getSvgProxy(displayable);
  77521. var svgElement = getSvgElement(displayable)
  77522. || getTextSvgElement(displayable);
  77523. if (!displayable.invisible) {
  77524. if (displayable.__dirty) {
  77525. svgProxy && svgProxy.brush(displayable);
  77526. // Update clipPath
  77527. this.clipPathManager.update(displayable);
  77528. // Update gradient and shadow
  77529. if (displayable.style) {
  77530. this.gradientManager
  77531. .update(displayable.style.fill);
  77532. this.gradientManager
  77533. .update(displayable.style.stroke);
  77534. this.shadowManager
  77535. .update(svgElement, displayable);
  77536. }
  77537. displayable.__dirty = false;
  77538. }
  77539. newVisibleList.push(displayable);
  77540. }
  77541. }
  77542. var diff = arrayDiff$1(visibleList, newVisibleList);
  77543. var prevSvgElement;
  77544. // First do remove, in case element moved to the head and do remove
  77545. // after add
  77546. for (i = 0; i < diff.length; i++) {
  77547. var item = diff[i];
  77548. if (item.removed) {
  77549. for (var k = 0; k < item.count; k++) {
  77550. var displayable = visibleList[item.indices[k]];
  77551. var svgElement = getSvgElement(displayable);
  77552. var textSvgElement = getTextSvgElement(displayable);
  77553. remove$1(svgRoot, svgElement);
  77554. remove$1(svgRoot, textSvgElement);
  77555. }
  77556. }
  77557. }
  77558. for (i = 0; i < diff.length; i++) {
  77559. var item = diff[i];
  77560. if (item.added) {
  77561. for (var k = 0; k < item.count; k++) {
  77562. var displayable = newVisibleList[item.indices[k]];
  77563. var svgElement = getSvgElement(displayable);
  77564. var textSvgElement = getTextSvgElement(displayable);
  77565. prevSvgElement
  77566. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  77567. : prepend(svgRoot, svgElement);
  77568. if (svgElement) {
  77569. insertAfter(svgRoot, textSvgElement, svgElement);
  77570. }
  77571. else if (prevSvgElement) {
  77572. insertAfter(
  77573. svgRoot, textSvgElement, prevSvgElement
  77574. );
  77575. }
  77576. else {
  77577. prepend(svgRoot, textSvgElement);
  77578. }
  77579. // Insert text
  77580. insertAfter(svgRoot, textSvgElement, svgElement);
  77581. prevSvgElement = textSvgElement || svgElement
  77582. || prevSvgElement;
  77583. this.gradientManager
  77584. .addWithoutUpdate(svgElement, displayable);
  77585. this.shadowManager
  77586. .addWithoutUpdate(prevSvgElement, displayable);
  77587. this.clipPathManager.markUsed(displayable);
  77588. }
  77589. }
  77590. else if (!item.removed) {
  77591. for (var k = 0; k < item.count; k++) {
  77592. var displayable = newVisibleList[item.indices[k]];
  77593. prevSvgElement
  77594. = svgElement
  77595. = getTextSvgElement(displayable)
  77596. || getSvgElement(displayable)
  77597. || prevSvgElement;
  77598. this.gradientManager.markUsed(displayable);
  77599. this.gradientManager
  77600. .addWithoutUpdate(svgElement, displayable);
  77601. this.shadowManager.markUsed(displayable);
  77602. this.shadowManager
  77603. .addWithoutUpdate(svgElement, displayable);
  77604. this.clipPathManager.markUsed(displayable);
  77605. }
  77606. }
  77607. }
  77608. this.gradientManager.removeUnused();
  77609. this.clipPathManager.removeUnused();
  77610. this.shadowManager.removeUnused();
  77611. this._visibleList = newVisibleList;
  77612. },
  77613. _getDefs: function (isForceCreating) {
  77614. var svgRoot = this._svgRoot;
  77615. var defs = this._svgRoot.getElementsByTagName('defs');
  77616. if (defs.length === 0) {
  77617. // Not exist
  77618. if (isForceCreating) {
  77619. var defs = svgRoot.insertBefore(
  77620. createElement('defs'), // Create new tag
  77621. svgRoot.firstChild // Insert in the front of svg
  77622. );
  77623. if (!defs.contains) {
  77624. // IE doesn't support contains method
  77625. defs.contains = function (el) {
  77626. var children = defs.children;
  77627. if (!children) {
  77628. return false;
  77629. }
  77630. for (var i = children.length - 1; i >= 0; --i) {
  77631. if (children[i] === el) {
  77632. return true;
  77633. }
  77634. }
  77635. return false;
  77636. };
  77637. }
  77638. return defs;
  77639. }
  77640. else {
  77641. return null;
  77642. }
  77643. }
  77644. else {
  77645. return defs[0];
  77646. }
  77647. },
  77648. resize: function (width, height) {
  77649. var viewport = this._viewport;
  77650. // FIXME Why ?
  77651. viewport.style.display = 'none';
  77652. // Save input w/h
  77653. var opts = this._opts;
  77654. width != null && (opts.width = width);
  77655. height != null && (opts.height = height);
  77656. width = this._getSize(0);
  77657. height = this._getSize(1);
  77658. viewport.style.display = '';
  77659. if (this._width !== width || this._height !== height) {
  77660. this._width = width;
  77661. this._height = height;
  77662. var viewportStyle = viewport.style;
  77663. viewportStyle.width = width + 'px';
  77664. viewportStyle.height = height + 'px';
  77665. var svgRoot = this._svgRoot;
  77666. // Set width by 'svgRoot.width = width' is invalid
  77667. svgRoot.setAttribute('width', width);
  77668. svgRoot.setAttribute('height', height);
  77669. }
  77670. },
  77671. /**
  77672. * 获取绘图区域宽度
  77673. */
  77674. getWidth: function () {
  77675. return this._width;
  77676. },
  77677. /**
  77678. * 获取绘图区域高度
  77679. */
  77680. getHeight: function () {
  77681. return this._height;
  77682. },
  77683. _getSize: function (whIdx) {
  77684. var opts = this._opts;
  77685. var wh = ['width', 'height'][whIdx];
  77686. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  77687. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  77688. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  77689. if (opts[wh] != null && opts[wh] !== 'auto') {
  77690. return parseFloat(opts[wh]);
  77691. }
  77692. var root = this.root;
  77693. // IE8 does not support getComputedStyle, but it use VML.
  77694. var stl = document.defaultView.getComputedStyle(root);
  77695. return (
  77696. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  77697. - (parseInt10$2(stl[plt]) || 0)
  77698. - (parseInt10$2(stl[prb]) || 0)
  77699. ) | 0;
  77700. },
  77701. dispose: function () {
  77702. this.root.innerHTML = '';
  77703. this._svgRoot
  77704. = this._viewport
  77705. = this.storage
  77706. = null;
  77707. },
  77708. clear: function () {
  77709. if (this._viewport) {
  77710. this.root.removeChild(this._viewport);
  77711. }
  77712. },
  77713. pathToDataUrl: function () {
  77714. this.refresh();
  77715. var html = this._svgRoot.outerHTML;
  77716. return 'data:image/svg+xml;charset=UTF-8,' + html;
  77717. }
  77718. };
  77719. // Not supported methods
  77720. function createMethodNotSupport$1(method) {
  77721. return function () {
  77722. zrLog('In SVG mode painter not support method "' + method + '"');
  77723. };
  77724. }
  77725. // Unsuppoted methods
  77726. each$1([
  77727. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  77728. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  77729. 'toDataURL', 'pathToImage'
  77730. ], function (name) {
  77731. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  77732. });
  77733. registerPainter('svg', SVGPainter);
  77734. /*
  77735. * Licensed to the Apache Software Foundation (ASF) under one
  77736. * or more contributor license agreements. See the NOTICE file
  77737. * distributed with this work for additional information
  77738. * regarding copyright ownership. The ASF licenses this file
  77739. * to you under the Apache License, Version 2.0 (the
  77740. * "License"); you may not use this file except in compliance
  77741. * with the License. You may obtain a copy of the License at
  77742. *
  77743. * http://www.apache.org/licenses/LICENSE-2.0
  77744. *
  77745. * Unless required by applicable law or agreed to in writing,
  77746. * software distributed under the License is distributed on an
  77747. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77748. * KIND, either express or implied. See the License for the
  77749. * specific language governing permissions and limitations
  77750. * under the License.
  77751. */
  77752. // Import all charts and components
  77753. exports.version = version;
  77754. exports.dependencies = dependencies;
  77755. exports.PRIORITY = PRIORITY;
  77756. exports.init = init;
  77757. exports.connect = connect;
  77758. exports.disConnect = disConnect;
  77759. exports.disconnect = disconnect;
  77760. exports.dispose = dispose;
  77761. exports.getInstanceByDom = getInstanceByDom;
  77762. exports.getInstanceById = getInstanceById;
  77763. exports.registerTheme = registerTheme;
  77764. exports.registerPreprocessor = registerPreprocessor;
  77765. exports.registerProcessor = registerProcessor;
  77766. exports.registerPostUpdate = registerPostUpdate;
  77767. exports.registerAction = registerAction;
  77768. exports.registerCoordinateSystem = registerCoordinateSystem;
  77769. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  77770. exports.registerLayout = registerLayout;
  77771. exports.registerVisual = registerVisual;
  77772. exports.registerLoading = registerLoading;
  77773. exports.extendComponentModel = extendComponentModel;
  77774. exports.extendComponentView = extendComponentView;
  77775. exports.extendSeriesModel = extendSeriesModel;
  77776. exports.extendChartView = extendChartView;
  77777. exports.setCanvasCreator = setCanvasCreator;
  77778. exports.registerMap = registerMap;
  77779. exports.getMap = getMap;
  77780. exports.dataTool = dataTool;
  77781. exports.zrender = zrender;
  77782. exports.graphic = graphic;
  77783. exports.number = number;
  77784. exports.format = format;
  77785. exports.throttle = throttle;
  77786. exports.helper = helper;
  77787. exports.matrix = matrix;
  77788. exports.vector = vector;
  77789. exports.color = color;
  77790. exports.parseGeoJSON = parseGeoJson$1;
  77791. exports.parseGeoJson = parseGeoJson;
  77792. exports.util = ecUtil;
  77793. exports.List = List;
  77794. exports.Model = Model;
  77795. exports.Axis = Axis;
  77796. exports.env = env$1;
  77797. })));
  77798. //# sourceMappingURL=echarts.js.map