model.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. var zrUtil = require("zrender/lib/core/util");
  20. var env = require("zrender/lib/core/env");
  21. /*
  22. * Licensed to the Apache Software Foundation (ASF) under one
  23. * or more contributor license agreements. See the NOTICE file
  24. * distributed with this work for additional information
  25. * regarding copyright ownership. The ASF licenses this file
  26. * to you under the Apache License, Version 2.0 (the
  27. * "License"); you may not use this file except in compliance
  28. * with the License. You may obtain a copy of the License at
  29. *
  30. * http://www.apache.org/licenses/LICENSE-2.0
  31. *
  32. * Unless required by applicable law or agreed to in writing,
  33. * software distributed under the License is distributed on an
  34. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35. * KIND, either express or implied. See the License for the
  36. * specific language governing permissions and limitations
  37. * under the License.
  38. */
  39. var each = zrUtil.each;
  40. var isObject = zrUtil.isObject;
  41. var isArray = zrUtil.isArray;
  42. /**
  43. * Make the name displayable. But we should
  44. * make sure it is not duplicated with user
  45. * specified name, so use '\0';
  46. */
  47. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  48. /**
  49. * If value is not array, then translate it to array.
  50. * @param {*} value
  51. * @return {Array} [value] or value
  52. */
  53. function normalizeToArray(value) {
  54. return value instanceof Array ? value : value == null ? [] : [value];
  55. }
  56. /**
  57. * Sync default option between normal and emphasis like `position` and `show`
  58. * In case some one will write code like
  59. * label: {
  60. * show: false,
  61. * position: 'outside',
  62. * fontSize: 18
  63. * },
  64. * emphasis: {
  65. * label: { show: true }
  66. * }
  67. * @param {Object} opt
  68. * @param {string} key
  69. * @param {Array.<string>} subOpts
  70. */
  71. function defaultEmphasis(opt, key, subOpts) {
  72. // Caution: performance sensitive.
  73. if (opt) {
  74. opt[key] = opt[key] || {};
  75. opt.emphasis = opt.emphasis || {};
  76. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  77. for (var i = 0, len = subOpts.length; i < len; i++) {
  78. var subOptName = subOpts[i];
  79. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  80. opt.emphasis[key][subOptName] = opt[key][subOptName];
  81. }
  82. }
  83. }
  84. }
  85. var TEXT_STYLE_OPTIONS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth', 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY', 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding']; // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  86. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  87. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  88. // // FIXME: deprecated, check and remove it.
  89. // 'textStyle'
  90. // ]);
  91. /**
  92. * The method do not ensure performance.
  93. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  94. * This helper method retieves value from data.
  95. * @param {string|number|Date|Array|Object} dataItem
  96. * @return {number|string|Date|Array.<number|string|Date>}
  97. */
  98. function getDataItemValue(dataItem) {
  99. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  100. }
  101. /**
  102. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  103. * This helper method determine if dataItem has extra option besides value
  104. * @param {string|number|Date|Array|Object} dataItem
  105. */
  106. function isDataItemOption(dataItem) {
  107. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  108. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  109. }
  110. /**
  111. * Mapping to exists for merge.
  112. *
  113. * @public
  114. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  115. * @param {Object|Array.<Object>} newCptOptions
  116. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  117. * index of which is the same as exists.
  118. */
  119. function mappingToExists(exists, newCptOptions) {
  120. // Mapping by the order by original option (but not order of
  121. // new option) in merge mode. Because we should ensure
  122. // some specified index (like xAxisIndex) is consistent with
  123. // original option, which is easy to understand, espatially in
  124. // media query. And in most case, merge option is used to
  125. // update partial option but not be expected to change order.
  126. newCptOptions = (newCptOptions || []).slice();
  127. var result = zrUtil.map(exists || [], function (obj, index) {
  128. return {
  129. exist: obj
  130. };
  131. }); // Mapping by id or name if specified.
  132. each(newCptOptions, function (cptOption, index) {
  133. if (!isObject(cptOption)) {
  134. return;
  135. } // id has highest priority.
  136. for (var i = 0; i < result.length; i++) {
  137. if (!result[i].option // Consider name: two map to one.
  138. && cptOption.id != null && result[i].exist.id === cptOption.id + '') {
  139. result[i].option = cptOption;
  140. newCptOptions[index] = null;
  141. return;
  142. }
  143. }
  144. for (var i = 0; i < result.length; i++) {
  145. var exist = result[i].exist;
  146. if (!result[i].option // Consider name: two map to one.
  147. // Can not match when both ids exist but different.
  148. && (exist.id == null || cptOption.id == null) && cptOption.name != null && !isIdInner(cptOption) && !isIdInner(exist) && exist.name === cptOption.name + '') {
  149. result[i].option = cptOption;
  150. newCptOptions[index] = null;
  151. return;
  152. }
  153. }
  154. }); // Otherwise mapping by index.
  155. each(newCptOptions, function (cptOption, index) {
  156. if (!isObject(cptOption)) {
  157. return;
  158. }
  159. var i = 0;
  160. for (; i < result.length; i++) {
  161. var exist = result[i].exist;
  162. if (!result[i].option // Existing model that already has id should be able to
  163. // mapped to (because after mapping performed model may
  164. // be assigned with a id, whish should not affect next
  165. // mapping), except those has inner id.
  166. && !isIdInner(exist) // Caution:
  167. // Do not overwrite id. But name can be overwritten,
  168. // because axis use name as 'show label text'.
  169. // 'exist' always has id and name and we dont
  170. // need to check it.
  171. && cptOption.id == null) {
  172. result[i].option = cptOption;
  173. break;
  174. }
  175. }
  176. if (i >= result.length) {
  177. result.push({
  178. option: cptOption
  179. });
  180. }
  181. });
  182. return result;
  183. }
  184. /**
  185. * Make id and name for mapping result (result of mappingToExists)
  186. * into `keyInfo` field.
  187. *
  188. * @public
  189. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  190. * which order is the same as exists.
  191. * @return {Array.<Object>} The input.
  192. */
  193. function makeIdAndName(mapResult) {
  194. // We use this id to hash component models and view instances
  195. // in echarts. id can be specified by user, or auto generated.
  196. // The id generation rule ensures new view instance are able
  197. // to mapped to old instance when setOption are called in
  198. // no-merge mode. So we generate model id by name and plus
  199. // type in view id.
  200. // name can be duplicated among components, which is convenient
  201. // to specify multi components (like series) by one name.
  202. // Ensure that each id is distinct.
  203. var idMap = zrUtil.createHashMap();
  204. each(mapResult, function (item, index) {
  205. var existCpt = item.exist;
  206. existCpt && idMap.set(existCpt.id, item);
  207. });
  208. each(mapResult, function (item, index) {
  209. var opt = item.option;
  210. zrUtil.assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  211. opt && opt.id != null && idMap.set(opt.id, item);
  212. !item.keyInfo && (item.keyInfo = {});
  213. }); // Make name and id.
  214. each(mapResult, function (item, index) {
  215. var existCpt = item.exist;
  216. var opt = item.option;
  217. var keyInfo = item.keyInfo;
  218. if (!isObject(opt)) {
  219. return;
  220. } // name can be overwitten. Consider case: axis.name = '20km'.
  221. // But id generated by name will not be changed, which affect
  222. // only in that case: setOption with 'not merge mode' and view
  223. // instance will be recreated, which can be accepted.
  224. keyInfo.name = opt.name != null ? opt.name + '' : existCpt ? existCpt.name // Avoid diffferent series has the same name,
  225. // because name may be used like in color pallet.
  226. : DUMMY_COMPONENT_NAME_PREFIX + index;
  227. if (existCpt) {
  228. keyInfo.id = existCpt.id;
  229. } else if (opt.id != null) {
  230. keyInfo.id = opt.id + '';
  231. } else {
  232. // Consider this situatoin:
  233. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  234. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  235. // Series with the same name between optionA and optionB
  236. // should be mapped.
  237. var idNum = 0;
  238. do {
  239. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  240. } while (idMap.get(keyInfo.id));
  241. }
  242. idMap.set(keyInfo.id, item);
  243. });
  244. }
  245. function isNameSpecified(componentModel) {
  246. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  247. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  248. }
  249. /**
  250. * @public
  251. * @param {Object} cptOption
  252. * @return {boolean}
  253. */
  254. function isIdInner(cptOption) {
  255. return isObject(cptOption) && cptOption.id && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  256. }
  257. /**
  258. * A helper for removing duplicate items between batchA and batchB,
  259. * and in themselves, and categorize by series.
  260. *
  261. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  262. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  263. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  264. */
  265. function compressBatches(batchA, batchB) {
  266. var mapA = {};
  267. var mapB = {};
  268. makeMap(batchA || [], mapA);
  269. makeMap(batchB || [], mapB, mapA);
  270. return [mapToArray(mapA), mapToArray(mapB)];
  271. function makeMap(sourceBatch, map, otherMap) {
  272. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  273. var seriesId = sourceBatch[i].seriesId;
  274. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  275. var otherDataIndices = otherMap && otherMap[seriesId];
  276. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  277. var dataIndex = dataIndices[j];
  278. if (otherDataIndices && otherDataIndices[dataIndex]) {
  279. otherDataIndices[dataIndex] = null;
  280. } else {
  281. (map[seriesId] || (map[seriesId] = {}))[dataIndex] = 1;
  282. }
  283. }
  284. }
  285. }
  286. function mapToArray(map, isData) {
  287. var result = [];
  288. for (var i in map) {
  289. if (map.hasOwnProperty(i) && map[i] != null) {
  290. if (isData) {
  291. result.push(+i);
  292. } else {
  293. var dataIndices = mapToArray(map[i], true);
  294. dataIndices.length && result.push({
  295. seriesId: i,
  296. dataIndex: dataIndices
  297. });
  298. }
  299. }
  300. }
  301. return result;
  302. }
  303. }
  304. /**
  305. * @param {module:echarts/data/List} data
  306. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  307. * each of which can be Array or primary type.
  308. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  309. */
  310. function queryDataIndex(data, payload) {
  311. if (payload.dataIndexInside != null) {
  312. return payload.dataIndexInside;
  313. } else if (payload.dataIndex != null) {
  314. return zrUtil.isArray(payload.dataIndex) ? zrUtil.map(payload.dataIndex, function (value) {
  315. return data.indexOfRawIndex(value);
  316. }) : data.indexOfRawIndex(payload.dataIndex);
  317. } else if (payload.name != null) {
  318. return zrUtil.isArray(payload.name) ? zrUtil.map(payload.name, function (value) {
  319. return data.indexOfName(value);
  320. }) : data.indexOfName(payload.name);
  321. }
  322. }
  323. /**
  324. * Enable property storage to any host object.
  325. * Notice: Serialization is not supported.
  326. *
  327. * For example:
  328. * var inner = zrUitl.makeInner();
  329. *
  330. * function some1(hostObj) {
  331. * inner(hostObj).someProperty = 1212;
  332. * ...
  333. * }
  334. * function some2() {
  335. * var fields = inner(this);
  336. * fields.someProperty1 = 1212;
  337. * fields.someProperty2 = 'xx';
  338. * ...
  339. * }
  340. *
  341. * @return {Function}
  342. */
  343. function makeInner() {
  344. // Consider different scope by es module import.
  345. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  346. return function (hostObj) {
  347. return hostObj[key] || (hostObj[key] = {});
  348. };
  349. }
  350. var innerUniqueIndex = 0;
  351. /**
  352. * @param {module:echarts/model/Global} ecModel
  353. * @param {string|Object} finder
  354. * If string, e.g., 'geo', means {geoIndex: 0}.
  355. * If Object, could contain some of these properties below:
  356. * {
  357. * seriesIndex, seriesId, seriesName,
  358. * geoIndex, geoId, geoName,
  359. * bmapIndex, bmapId, bmapName,
  360. * xAxisIndex, xAxisId, xAxisName,
  361. * yAxisIndex, yAxisId, yAxisName,
  362. * gridIndex, gridId, gridName,
  363. * ... (can be extended)
  364. * }
  365. * Each properties can be number|string|Array.<number>|Array.<string>
  366. * For example, a finder could be
  367. * {
  368. * seriesIndex: 3,
  369. * geoId: ['aa', 'cc'],
  370. * gridName: ['xx', 'rr']
  371. * }
  372. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  373. * If nothing or null/undefined specified, return nothing.
  374. * @param {Object} [opt]
  375. * @param {string} [opt.defaultMainType]
  376. * @param {Array.<string>} [opt.includeMainTypes]
  377. * @return {Object} result like:
  378. * {
  379. * seriesModels: [seriesModel1, seriesModel2],
  380. * seriesModel: seriesModel1, // The first model
  381. * geoModels: [geoModel1, geoModel2],
  382. * geoModel: geoModel1, // The first model
  383. * ...
  384. * }
  385. */
  386. function parseFinder(ecModel, finder, opt) {
  387. if (zrUtil.isString(finder)) {
  388. var obj = {};
  389. obj[finder + 'Index'] = 0;
  390. finder = obj;
  391. }
  392. var defaultMainType = opt && opt.defaultMainType;
  393. if (defaultMainType && !has(finder, defaultMainType + 'Index') && !has(finder, defaultMainType + 'Id') && !has(finder, defaultMainType + 'Name')) {
  394. finder[defaultMainType + 'Index'] = 0;
  395. }
  396. var result = {};
  397. each(finder, function (value, key) {
  398. var value = finder[key]; // Exclude 'dataIndex' and other illgal keys.
  399. if (key === 'dataIndex' || key === 'dataIndexInside') {
  400. result[key] = value;
  401. return;
  402. }
  403. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  404. var mainType = parsedKey[1];
  405. var queryType = (parsedKey[2] || '').toLowerCase();
  406. if (!mainType || !queryType || value == null || queryType === 'index' && value === 'none' || opt && opt.includeMainTypes && zrUtil.indexOf(opt.includeMainTypes, mainType) < 0) {
  407. return;
  408. }
  409. var queryParam = {
  410. mainType: mainType
  411. };
  412. if (queryType !== 'index' || value !== 'all') {
  413. queryParam[queryType] = value;
  414. }
  415. var models = ecModel.queryComponents(queryParam);
  416. result[mainType + 'Models'] = models;
  417. result[mainType + 'Model'] = models[0];
  418. });
  419. return result;
  420. }
  421. function has(obj, prop) {
  422. return obj && obj.hasOwnProperty(prop);
  423. }
  424. function setAttribute(dom, key, value) {
  425. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  426. }
  427. function getAttribute(dom, key) {
  428. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  429. }
  430. function getTooltipRenderMode(renderModeOption) {
  431. if (renderModeOption === 'auto') {
  432. // Using html when `document` exists, use richText otherwise
  433. return env.domSupported ? 'html' : 'richText';
  434. } else {
  435. return renderModeOption || 'html';
  436. }
  437. }
  438. /**
  439. * Group a list by key.
  440. *
  441. * @param {Array} array
  442. * @param {Function} getKey
  443. * param {*} Array item
  444. * return {string} key
  445. * @return {Object} Result
  446. * {Array}: keys,
  447. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  448. */
  449. function groupData(array, getKey) {
  450. var buckets = zrUtil.createHashMap();
  451. var keys = [];
  452. zrUtil.each(array, function (item) {
  453. var key = getKey(item);
  454. (buckets.get(key) || (keys.push(key), buckets.set(key, []))).push(item);
  455. });
  456. return {
  457. keys: keys,
  458. buckets: buckets
  459. };
  460. }
  461. exports.normalizeToArray = normalizeToArray;
  462. exports.defaultEmphasis = defaultEmphasis;
  463. exports.TEXT_STYLE_OPTIONS = TEXT_STYLE_OPTIONS;
  464. exports.getDataItemValue = getDataItemValue;
  465. exports.isDataItemOption = isDataItemOption;
  466. exports.mappingToExists = mappingToExists;
  467. exports.makeIdAndName = makeIdAndName;
  468. exports.isNameSpecified = isNameSpecified;
  469. exports.isIdInner = isIdInner;
  470. exports.compressBatches = compressBatches;
  471. exports.queryDataIndex = queryDataIndex;
  472. exports.makeInner = makeInner;
  473. exports.parseFinder = parseFinder;
  474. exports.setAttribute = setAttribute;
  475. exports.getAttribute = getAttribute;
  476. exports.getTooltipRenderMode = getTooltipRenderMode;
  477. exports.groupData = groupData;