CustomView.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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. /**
  20. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21. */
  22. /*
  23. * Licensed to the Apache Software Foundation (ASF) under one
  24. * or more contributor license agreements. See the NOTICE file
  25. * distributed with this work for additional information
  26. * regarding copyright ownership. The ASF licenses this file
  27. * to you under the Apache License, Version 2.0 (the
  28. * "License"); you may not use this file except in compliance
  29. * with the License. You may obtain a copy of the License at
  30. *
  31. * http://www.apache.org/licenses/LICENSE-2.0
  32. *
  33. * Unless required by applicable law or agreed to in writing,
  34. * software distributed under the License is distributed on an
  35. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36. * KIND, either express or implied. See the License for the
  37. * specific language governing permissions and limitations
  38. * under the License.
  39. */
  40. import { __extends } from "tslib";
  41. import { hasOwn, assert, isString, retrieve2, retrieve3, defaults, each, indexOf, map } from 'zrender/lib/core/util.js';
  42. import * as graphicUtil from '../../util/graphic.js';
  43. import { setDefaultStateProxy, toggleHoverEmphasis } from '../../util/states.js';
  44. import * as labelStyleHelper from '../../label/labelStyle.js';
  45. import { getDefaultLabel } from '../helper/labelHelper.js';
  46. import { computeBarLayoutForCustomSeries } from '../../layout/barGrid.js';
  47. import DataDiffer from '../../data/DataDiffer.js';
  48. import ChartView from '../../view/Chart.js';
  49. import { createClipPath } from '../helper/createClipPathFromCoordSys.js';
  50. import prepareCartesian2d from '../../coord/cartesian/prepareCustom.js';
  51. import prepareGeo from '../../coord/geo/prepareCustom.js';
  52. import prepareSingleAxis from '../../coord/single/prepareCustom.js';
  53. import preparePolar from '../../coord/polar/prepareCustom.js';
  54. import prepareCalendar from '../../coord/calendar/prepareCustom.js';
  55. import prepareMatrix from '../../coord/matrix/prepareCustom.js';
  56. import Displayable from 'zrender/lib/graphic/Displayable.js';
  57. import { convertToEC4StyleForCustomSerise, isEC4CompatibleStyle, convertFromEC4CompatibleStyle, warnDeprecated } from '../../util/styleCompat.js';
  58. import { throwError } from '../../util/log.js';
  59. import { createOrUpdatePatternFromDecal } from '../../util/decal.js';
  60. import { STYLE_VISUAL_TYPE, NON_STYLE_VISUAL_PROPS, customInnerStore } from './CustomSeries.js';
  61. import { applyLeaveTransition, applyUpdateTransition } from '../../animation/customGraphicTransition.js';
  62. import { applyKeyframeAnimation, stopPreviousKeyframeAnimationAndRestore } from '../../animation/customGraphicKeyframeAnimation.js';
  63. import { getCustomSeries } from './customSeriesRegister.js';
  64. import tokens from '../../visual/tokens.js';
  65. import { getIncrementalId } from '../../util/model.js';
  66. var EMPHASIS = 'emphasis';
  67. var NORMAL = 'normal';
  68. var BLUR = 'blur';
  69. var SELECT = 'select';
  70. var STATES = [NORMAL, EMPHASIS, BLUR, SELECT];
  71. var PATH_ITEM_STYLE = {
  72. normal: ['itemStyle'],
  73. emphasis: [EMPHASIS, 'itemStyle'],
  74. blur: [BLUR, 'itemStyle'],
  75. select: [SELECT, 'itemStyle']
  76. };
  77. var PATH_LABEL = {
  78. normal: ['label'],
  79. emphasis: [EMPHASIS, 'label'],
  80. blur: [BLUR, 'label'],
  81. select: [SELECT, 'label']
  82. };
  83. var DEFAULT_TRANSITION = ['x', 'y'];
  84. // Use prefix to avoid index to be the same as el.name,
  85. // which will cause weird update animation.
  86. var GROUP_DIFF_PREFIX = 'e\0\0';
  87. var attachedTxInfoTmp = {
  88. normal: {},
  89. emphasis: {},
  90. blur: {},
  91. select: {}
  92. };
  93. /**
  94. * FIXME: register rather than import directly, for size.
  95. *
  96. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  97. * of each coordinate systems are not required by each coordinate systems directly, but
  98. * required by the module `custom`.
  99. *
  100. * prepareInfoForCustomSeries {Function}: optional
  101. * @return {Object} {coordSys: {...}, api: {
  102. * coord: function (data, clamp) {}, // return point in global.
  103. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  104. * }}
  105. */
  106. var prepareCustoms = {
  107. cartesian2d: prepareCartesian2d,
  108. geo: prepareGeo,
  109. single: prepareSingleAxis,
  110. polar: preparePolar,
  111. calendar: prepareCalendar,
  112. matrix: prepareMatrix
  113. };
  114. function isPath(el) {
  115. return el instanceof graphicUtil.Path;
  116. }
  117. function isDisplayable(el) {
  118. return el instanceof Displayable;
  119. }
  120. function copyElement(sourceEl, targetEl) {
  121. targetEl.copyTransform(sourceEl);
  122. if (isDisplayable(targetEl) && isDisplayable(sourceEl)) {
  123. targetEl.setStyle(sourceEl.style);
  124. targetEl.z = sourceEl.z;
  125. targetEl.z2 = sourceEl.z2;
  126. targetEl.zlevel = sourceEl.zlevel;
  127. targetEl.invisible = sourceEl.invisible;
  128. targetEl.ignore = sourceEl.ignore;
  129. if (isPath(targetEl) && isPath(sourceEl)) {
  130. targetEl.setShape(sourceEl.shape);
  131. }
  132. }
  133. }
  134. var CustomChartView = /** @class */function (_super) {
  135. __extends(CustomChartView, _super);
  136. function CustomChartView() {
  137. var _this = _super !== null && _super.apply(this, arguments) || this;
  138. _this.type = CustomChartView.type;
  139. return _this;
  140. }
  141. CustomChartView.prototype.render = function (customSeries, ecModel, api, payload) {
  142. // Clear previously rendered progressive elements.
  143. this._progressiveEls = null;
  144. var oldData = this._data;
  145. var data = customSeries.getData();
  146. var group = this.group;
  147. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  148. if (!oldData) {
  149. // Previous render is incremental render or first render.
  150. // Needs remove the incremental rendered elements.
  151. group.removeAll();
  152. }
  153. data.diff(oldData).add(function (newIdx) {
  154. createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  155. }).remove(function (oldIdx) {
  156. var el = oldData.getItemGraphicEl(oldIdx);
  157. el && applyLeaveTransition(el, customInnerStore(el).option, customSeries);
  158. }).update(function (newIdx, oldIdx) {
  159. var oldEl = oldData.getItemGraphicEl(oldIdx);
  160. createOrUpdateItem(api, oldEl, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  161. }).execute();
  162. // Do clipping
  163. var clipPath = customSeries.get('clip', true) ? createClipPath(customSeries.coordinateSystem, false, customSeries) : null;
  164. if (clipPath) {
  165. group.setClipPath(clipPath);
  166. } else {
  167. group.removeClipPath();
  168. }
  169. this._data = data;
  170. };
  171. CustomChartView.prototype.incrementalPrepareRender = function (customSeries, ecModel, api) {
  172. this.group.removeAll();
  173. this._data = null;
  174. };
  175. CustomChartView.prototype.incrementalRender = function (params, customSeries, ecModel, api, payload) {
  176. var data = customSeries.getData();
  177. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  178. var progressiveEls = this._progressiveEls = [];
  179. function setIncrementalAndHoverLayer(el) {
  180. if (!el.isGroup) {
  181. el.incremental = getIncrementalId(customSeries);
  182. el.ensureState('emphasis').hoverLayer = graphicUtil.HOVER_LAYER_FOR_INCREMENTAL;
  183. }
  184. }
  185. for (var idx = params.start; idx < params.end; idx++) {
  186. var el = createOrUpdateItem(null, null, idx, renderItem(idx, payload), customSeries, this.group, data);
  187. if (el) {
  188. el.traverse(setIncrementalAndHoverLayer);
  189. progressiveEls.push(el);
  190. }
  191. }
  192. };
  193. CustomChartView.prototype.eachRendered = function (cb) {
  194. graphicUtil.traverseElements(this._progressiveEls || this.group, cb);
  195. };
  196. CustomChartView.prototype.filterForExposedEvent = function (eventType, query, targetEl, packedEvent) {
  197. var elementName = query.element;
  198. if (elementName == null || targetEl.name === elementName) {
  199. return true;
  200. }
  201. // Enable to give a name on a group made by `renderItem`, and listen
  202. // events that are triggered by its descendents.
  203. while ((targetEl = targetEl.__hostTarget || targetEl.parent) && targetEl !== this.group) {
  204. if (targetEl.name === elementName) {
  205. return true;
  206. }
  207. }
  208. return false;
  209. };
  210. CustomChartView.type = 'custom';
  211. return CustomChartView;
  212. }(ChartView);
  213. export default CustomChartView;
  214. function createEl(elOption) {
  215. var graphicType = elOption.type;
  216. var el;
  217. // Those graphic elements are not shapes. They should not be
  218. // overwritten by users, so do them first.
  219. if (graphicType === 'path') {
  220. var shape = elOption.shape;
  221. // Using pathRect brings convenience to users sacle svg path.
  222. var pathRect = shape.width != null && shape.height != null ? {
  223. x: shape.x || 0,
  224. y: shape.y || 0,
  225. width: shape.width,
  226. height: shape.height
  227. } : null;
  228. var pathData = getPathData(shape);
  229. // Path is also used for icon, so layout 'center' by default.
  230. el = graphicUtil.makePath(pathData, null, pathRect, shape.layout || 'center');
  231. customInnerStore(el).customPathData = pathData;
  232. } else if (graphicType === 'image') {
  233. el = new graphicUtil.Image({});
  234. customInnerStore(el).customImagePath = elOption.style.image;
  235. } else if (graphicType === 'text') {
  236. el = new graphicUtil.Text({});
  237. // customInnerStore(el).customText = (elOption.style as TextStyleProps).text;
  238. } else if (graphicType === 'group') {
  239. el = new graphicUtil.Group();
  240. } else if (graphicType === 'compoundPath') {
  241. var shape = elOption.shape;
  242. if (!shape || !shape.paths) {
  243. var errMsg = '';
  244. if (process.env.NODE_ENV !== 'production') {
  245. errMsg = 'shape.paths must be specified in compoundPath';
  246. }
  247. throwError(errMsg);
  248. }
  249. var paths = map(shape.paths, function (path) {
  250. if (path.type === 'path') {
  251. return graphicUtil.makePath(path.shape.pathData, path, null);
  252. }
  253. var Clz = graphicUtil.getShapeClass(path.type);
  254. if (!Clz) {
  255. var errMsg = '';
  256. if (process.env.NODE_ENV !== 'production') {
  257. errMsg = 'graphic type "' + graphicType + '" can not be found.';
  258. }
  259. throwError(errMsg);
  260. }
  261. return new Clz();
  262. });
  263. el = new graphicUtil.CompoundPath({
  264. shape: {
  265. paths: paths
  266. }
  267. });
  268. } else {
  269. var Clz = graphicUtil.getShapeClass(graphicType);
  270. if (!Clz) {
  271. var errMsg = '';
  272. if (process.env.NODE_ENV !== 'production') {
  273. errMsg = 'graphic type "' + graphicType + '" can not be found.';
  274. }
  275. throwError(errMsg);
  276. }
  277. el = new Clz();
  278. }
  279. customInnerStore(el).customGraphicType = graphicType;
  280. el.name = elOption.name;
  281. // Compat ec4: the default z2 lift is 1. If changing the number,
  282. // some cases probably be broken: hierarchy layout along z, like circle packing,
  283. // where emphasis only intending to modify color/border rather than lift z2.
  284. el.z2EmphasisLift = 1;
  285. el.z2SelectLift = 1;
  286. return el;
  287. }
  288. function updateElNormal(
  289. // Can be null/undefined
  290. api, el, dataIndex, elOption, attachedTxInfo, seriesModel, isInit) {
  291. // Stop and restore before update any other attributes.
  292. stopPreviousKeyframeAnimationAndRestore(el);
  293. var txCfgOpt = attachedTxInfo && attachedTxInfo.normal.cfg;
  294. if (txCfgOpt) {
  295. // PENDING: whether use user object directly rather than clone?
  296. // TODO:5.0 textConfig transition animation?
  297. el.setTextConfig(txCfgOpt);
  298. }
  299. // Default transition ['x', 'y']
  300. if (elOption && elOption.transition == null) {
  301. elOption.transition = DEFAULT_TRANSITION;
  302. }
  303. // Do some normalization on style.
  304. var styleOpt = elOption && elOption.style;
  305. if (styleOpt) {
  306. if (el.type === 'text') {
  307. var textOptionStyle = styleOpt;
  308. // Compatible with ec4: if `textFill` or `textStroke` exists use them.
  309. hasOwn(textOptionStyle, 'textFill') && (textOptionStyle.fill = textOptionStyle.textFill);
  310. hasOwn(textOptionStyle, 'textStroke') && (textOptionStyle.stroke = textOptionStyle.textStroke);
  311. }
  312. var decalPattern = void 0;
  313. var decalObj = isPath(el) ? styleOpt.decal : null;
  314. if (api && decalObj) {
  315. decalObj.dirty = true;
  316. decalPattern = createOrUpdatePatternFromDecal(decalObj, api);
  317. }
  318. // Always overwrite in case user specify this prop.
  319. styleOpt.__decalPattern = decalPattern;
  320. }
  321. if (isDisplayable(el)) {
  322. if (styleOpt) {
  323. var decalPattern = styleOpt.__decalPattern;
  324. if (decalPattern) {
  325. styleOpt.decal = decalPattern;
  326. }
  327. }
  328. }
  329. applyUpdateTransition(el, elOption, seriesModel, {
  330. dataIndex: dataIndex,
  331. isInit: isInit,
  332. clearStyle: true
  333. });
  334. applyKeyframeAnimation(el, elOption.keyframeAnimation, seriesModel);
  335. }
  336. function updateElOnState(state, el, elStateOpt, styleOpt, attachedTxInfo) {
  337. var elDisplayable = el.isGroup ? null : el;
  338. var txCfgOpt = attachedTxInfo && attachedTxInfo[state].cfg;
  339. // PENDING:5.0 support customize scale change and transition animation?
  340. if (elDisplayable) {
  341. // By default support auto lift color when hover whether `emphasis` specified.
  342. var stateObj = elDisplayable.ensureState(state);
  343. if (styleOpt === false) {
  344. var existingEmphasisState = elDisplayable.getState(state);
  345. if (existingEmphasisState) {
  346. existingEmphasisState.style = null;
  347. }
  348. } else {
  349. // style is needed to enable default emphasis.
  350. stateObj.style = styleOpt || null;
  351. }
  352. // If `elOption.styleEmphasis` or `elOption.emphasis.style` is `false`,
  353. // remove hover style.
  354. // If `elOption.textConfig` or `elOption.emphasis.textConfig` is null/undefined, it does not
  355. // make sense. So for simplicity, we do not ditinguish `hasOwnProperty` and null/undefined.
  356. if (txCfgOpt) {
  357. stateObj.textConfig = txCfgOpt;
  358. }
  359. setDefaultStateProxy(elDisplayable);
  360. }
  361. }
  362. function updateZ(el, elOption, seriesModel) {
  363. // Group not support textContent and not support z yet.
  364. if (el.isGroup) {
  365. return;
  366. }
  367. var elDisplayable = el;
  368. var currentZ = seriesModel.currentZ;
  369. var currentZLevel = seriesModel.currentZLevel;
  370. // Always erase.
  371. elDisplayable.z = currentZ;
  372. elDisplayable.zlevel = currentZLevel;
  373. // z2 must not be null/undefined, otherwise sort error may occur.
  374. var optZ2 = elOption.z2;
  375. optZ2 != null && (elDisplayable.z2 = optZ2 || 0);
  376. for (var i = 0; i < STATES.length; i++) {
  377. updateZForEachState(elDisplayable, elOption, STATES[i]);
  378. }
  379. }
  380. function updateZForEachState(elDisplayable, elOption, state) {
  381. var isNormal = state === NORMAL;
  382. var elStateOpt = isNormal ? elOption : retrieveStateOption(elOption, state);
  383. var optZ2 = elStateOpt ? elStateOpt.z2 : null;
  384. var stateObj;
  385. if (optZ2 != null) {
  386. // Do not `ensureState` until required.
  387. stateObj = isNormal ? elDisplayable : elDisplayable.ensureState(state);
  388. stateObj.z2 = optZ2 || 0;
  389. }
  390. }
  391. function makeRenderItem(customSeries, data, ecModel, api) {
  392. var renderItem = customSeries.get('renderItem');
  393. if (typeof renderItem === 'string') {
  394. // Find renderItem in registered custom series
  395. var registeredRenderItem = getCustomSeries(renderItem);
  396. if (registeredRenderItem) {
  397. renderItem = registeredRenderItem;
  398. } else if (process.env.NODE_ENV !== 'production') {
  399. console.warn("Custom series renderItem '" + renderItem + "' not found.\n Call 'echarts.registerCustomSeries' to register it.");
  400. }
  401. }
  402. var coordSys = customSeries.coordinateSystem;
  403. var prepareResult = {};
  404. if (coordSys) {
  405. if (process.env.NODE_ENV !== 'production') {
  406. assert(renderItem, 'series.render is required.');
  407. assert(coordSys.prepareCustoms || prepareCustoms[coordSys.type], 'This coordSys does not support custom series.');
  408. }
  409. // `coordSys.prepareCustoms` is used for external coord sys like bmap.
  410. prepareResult = coordSys.prepareCustoms ? coordSys.prepareCustoms(coordSys) : prepareCustoms[coordSys.type](coordSys);
  411. }
  412. var userAPI = defaults({
  413. getWidth: api.getWidth,
  414. getHeight: api.getHeight,
  415. getZr: api.getZr,
  416. getDevicePixelRatio: api.getDevicePixelRatio,
  417. value: value,
  418. style: style,
  419. ordinalRawValue: ordinalRawValue,
  420. styleEmphasis: styleEmphasis,
  421. visual: visual,
  422. barLayout: barLayout,
  423. currentSeriesIndices: currentSeriesIndices,
  424. font: font
  425. }, prepareResult.api || {});
  426. var userParams = {
  427. // The life cycle of context: current round of rendering.
  428. // The global life cycle is probably not necessary, because
  429. // user can store global status by themselves.
  430. context: {},
  431. seriesId: customSeries.id,
  432. seriesName: customSeries.name,
  433. seriesIndex: customSeries.seriesIndex,
  434. coordSys: prepareResult.coordSys,
  435. dataInsideLength: data.count(),
  436. encode: wrapEncodeDef(customSeries.getData()),
  437. itemPayload: customSeries.get('itemPayload') || {}
  438. };
  439. // If someday intending to refactor them to a class, should consider do not
  440. // break change: currently these attribute member are encapsulated in a closure
  441. // so that do not need to force user to call these method with a scope.
  442. // Do not support call `api` asynchronously without dataIndexInside input.
  443. var currDataIndexInside;
  444. var currItemModel;
  445. var currItemStyleModels = {};
  446. var currLabelModels = {};
  447. var seriesItemStyleModels = {};
  448. var seriesLabelModels = {};
  449. for (var i = 0; i < STATES.length; i++) {
  450. var stateName = STATES[i];
  451. seriesItemStyleModels[stateName] = customSeries.getModel(PATH_ITEM_STYLE[stateName]);
  452. seriesLabelModels[stateName] = customSeries.getModel(PATH_LABEL[stateName]);
  453. }
  454. function getItemModel(dataIndexInside) {
  455. return dataIndexInside === currDataIndexInside ? currItemModel || (currItemModel = data.getItemModel(dataIndexInside)) : data.getItemModel(dataIndexInside);
  456. }
  457. function getItemStyleModel(dataIndexInside, state) {
  458. return !data.hasItemOption ? seriesItemStyleModels[state] : dataIndexInside === currDataIndexInside ? currItemStyleModels[state] || (currItemStyleModels[state] = getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state])) : getItemModel(dataIndexInside).getModel(PATH_ITEM_STYLE[state]);
  459. }
  460. function getLabelModel(dataIndexInside, state) {
  461. return !data.hasItemOption ? seriesLabelModels[state] : dataIndexInside === currDataIndexInside ? currLabelModels[state] || (currLabelModels[state] = getItemModel(dataIndexInside).getModel(PATH_LABEL[state])) : getItemModel(dataIndexInside).getModel(PATH_LABEL[state]);
  462. }
  463. return function (dataIndexInside, payload) {
  464. currDataIndexInside = dataIndexInside;
  465. currItemModel = null;
  466. currItemStyleModels = {};
  467. currLabelModels = {};
  468. return renderItem && renderItem(defaults({
  469. dataIndexInside: dataIndexInside,
  470. dataIndex: data.getRawIndex(dataIndexInside),
  471. // Can be used for optimization when zoom or roam.
  472. actionType: payload ? payload.type : null
  473. }, userParams), userAPI);
  474. };
  475. /**
  476. * @public
  477. * @param dim by default 0.
  478. * @param dataIndexInside by default `currDataIndexInside`.
  479. */
  480. function value(dim, dataIndexInside) {
  481. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  482. return data.getStore().get(data.getDimensionIndex(dim || 0), dataIndexInside);
  483. }
  484. /**
  485. * @public
  486. * @param dim by default 0.
  487. * @param dataIndexInside by default `currDataIndexInside`.
  488. */
  489. function ordinalRawValue(dim, dataIndexInside) {
  490. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  491. dim = dim || 0;
  492. var dimInfo = data.getDimensionInfo(dim);
  493. if (!dimInfo) {
  494. var dimIndex = data.getDimensionIndex(dim);
  495. return dimIndex >= 0 ? data.getStore().get(dimIndex, dataIndexInside) : undefined;
  496. }
  497. var val = data.get(dimInfo.name, dataIndexInside);
  498. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  499. return ordinalMeta ? ordinalMeta.categories[val] : val;
  500. }
  501. /**
  502. * @deprecated The original intention of `api.style` is enable to set itemStyle
  503. * like other series. But it is not necessary and not easy to give a strict definition
  504. * of what it returns. And since echarts5 it needs to be make compat work. So
  505. * deprecates it since echarts5.
  506. *
  507. * By default, `visual` is applied to style (to support visualMap).
  508. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  509. * it can be implemented as:
  510. * `api.style({stroke: api.visual('color'), fill: null})`;
  511. *
  512. * [Compat]: since ec5, RectText has been separated from its hosts el.
  513. * so `api.style()` will only return the style from `itemStyle` but not handle `label`
  514. * any more. But `series.label` config is never published in doc.
  515. * We still compat it in `api.style()`. But not encourage to use it and will still not
  516. * to pulish it to doc.
  517. * @public
  518. * @param dataIndexInside by default `currDataIndexInside`.
  519. */
  520. function style(userProps, dataIndexInside) {
  521. if (process.env.NODE_ENV !== 'production') {
  522. warnDeprecated('api.style', 'Please write literal style directly instead.');
  523. }
  524. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  525. var style = data.getItemVisual(dataIndexInside, 'style');
  526. var visualColor = style && style.fill;
  527. var opacity = style && style.opacity;
  528. var itemStyle = getItemStyleModel(dataIndexInside, NORMAL).getItemStyle();
  529. visualColor != null && (itemStyle.fill = visualColor);
  530. opacity != null && (itemStyle.opacity = opacity);
  531. var opt = {
  532. inheritColor: isString(visualColor) ? visualColor : tokens.color.neutral99
  533. };
  534. var labelModel = getLabelModel(dataIndexInside, NORMAL);
  535. // Now that the feature of "auto adjust text fill/stroke" has been migrated to zrender
  536. // since ec5, we should set `isAttached` as `false` here and make compat in
  537. // `convertToEC4StyleForCustomSerise`.
  538. var textStyle = labelStyleHelper.createTextStyle(labelModel, null, opt, false, true);
  539. textStyle.text = labelModel.getShallow('show') ? retrieve2(customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  540. var textConfig = labelStyleHelper.createTextConfig(labelModel, opt, false);
  541. preFetchFromExtra(userProps, itemStyle);
  542. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  543. userProps && applyUserPropsAfter(itemStyle, userProps);
  544. itemStyle.legacy = true;
  545. return itemStyle;
  546. }
  547. /**
  548. * @deprecated The reason see `api.style()`
  549. * @public
  550. * @param dataIndexInside by default `currDataIndexInside`.
  551. */
  552. function styleEmphasis(userProps, dataIndexInside) {
  553. if (process.env.NODE_ENV !== 'production') {
  554. warnDeprecated('api.styleEmphasis', 'Please write literal style directly instead.');
  555. }
  556. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  557. var itemStyle = getItemStyleModel(dataIndexInside, EMPHASIS).getItemStyle();
  558. var labelModel = getLabelModel(dataIndexInside, EMPHASIS);
  559. var textStyle = labelStyleHelper.createTextStyle(labelModel, null, null, true, true);
  560. textStyle.text = labelModel.getShallow('show') ? retrieve3(customSeries.getFormattedLabel(dataIndexInside, EMPHASIS), customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  561. var textConfig = labelStyleHelper.createTextConfig(labelModel, null, true);
  562. preFetchFromExtra(userProps, itemStyle);
  563. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  564. userProps && applyUserPropsAfter(itemStyle, userProps);
  565. itemStyle.legacy = true;
  566. return itemStyle;
  567. }
  568. function applyUserPropsAfter(itemStyle, extra) {
  569. for (var key in extra) {
  570. if (hasOwn(extra, key)) {
  571. itemStyle[key] = extra[key];
  572. }
  573. }
  574. }
  575. function preFetchFromExtra(extra, itemStyle) {
  576. // A trick to retrieve those props firstly, which are used to
  577. // apply auto inside fill/stroke in `convertToEC4StyleForCustomSerise`.
  578. // (It's not reasonable but only for a degree of compat)
  579. if (extra) {
  580. extra.textFill && (itemStyle.textFill = extra.textFill);
  581. extra.textPosition && (itemStyle.textPosition = extra.textPosition);
  582. }
  583. }
  584. /**
  585. * @public
  586. * @param dataIndexInside by default `currDataIndexInside`.
  587. */
  588. function visual(visualType, dataIndexInside) {
  589. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  590. if (hasOwn(STYLE_VISUAL_TYPE, visualType)) {
  591. var style_1 = data.getItemVisual(dataIndexInside, 'style');
  592. return style_1 ? style_1[STYLE_VISUAL_TYPE[visualType]] : null;
  593. }
  594. // Only support these visuals. Other visual might be inner tricky
  595. // for performance (like `style`), do not expose to users.
  596. if (hasOwn(NON_STYLE_VISUAL_PROPS, visualType)) {
  597. return data.getItemVisual(dataIndexInside, visualType);
  598. }
  599. }
  600. /**
  601. * @public
  602. * @return If not support, return undefined.
  603. */
  604. function barLayout(opt) {
  605. if (coordSys.type === 'cartesian2d') {
  606. var baseAxis = coordSys.getBaseAxis();
  607. return computeBarLayoutForCustomSeries(defaults({
  608. axis: baseAxis
  609. }, opt));
  610. }
  611. }
  612. /**
  613. * @public
  614. */
  615. function currentSeriesIndices() {
  616. return ecModel.getCurrentSeriesIndices();
  617. }
  618. /**
  619. * @public
  620. * @return font string
  621. */
  622. function font(opt) {
  623. return labelStyleHelper.getFont(opt, ecModel);
  624. }
  625. }
  626. function wrapEncodeDef(data) {
  627. var encodeDef = {};
  628. each(data.dimensions, function (dimName) {
  629. var dimInfo = data.getDimensionInfo(dimName);
  630. if (!dimInfo.isExtraCoord) {
  631. var coordDim = dimInfo.coordDim;
  632. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  633. dataDims[dimInfo.coordDimIndex] = data.getDimensionIndex(dimName);
  634. }
  635. });
  636. return encodeDef;
  637. }
  638. function createOrUpdateItem(api, existsEl, dataIndex, elOption, seriesModel, group, data) {
  639. // [Rule]
  640. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  641. // (It seems that violate the "merge" principle, but most of users probably intuitively
  642. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  643. // most cases.)
  644. // The rule or "merge" see [STRATEGY_MERGE].
  645. // If `elOption` is `null`/`undefined`/`false` (when `renderItem` returns nothing).
  646. if (!elOption) {
  647. group.remove(existsEl);
  648. return;
  649. }
  650. var el = doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group);
  651. el && data.setItemGraphicEl(dataIndex, el);
  652. el && toggleHoverEmphasis(el, elOption.focus, elOption.blurScope, elOption.emphasisDisabled);
  653. return el;
  654. }
  655. function doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group) {
  656. if (process.env.NODE_ENV !== 'production') {
  657. assert(elOption, 'should not have an null/undefined element setting');
  658. }
  659. var toBeReplacedIdx = -1;
  660. var oldEl = existsEl;
  661. if (existsEl && doesElNeedRecreate(existsEl, elOption, seriesModel)
  662. // || (
  663. // // PENDING: even in one-to-one mapping case, if el is marked as morph,
  664. // // do not sure whether the el will be mapped to another el with different
  665. // // hierarchy in Group tree. So always recreate el rather than reuse the el.
  666. // morphHelper && morphHelper.isOneToOneFrom(el)
  667. // )
  668. ) {
  669. // Should keep at the original index, otherwise "merge by index" will be incorrect.
  670. toBeReplacedIdx = indexOf(group.childrenRef(), existsEl);
  671. existsEl = null;
  672. }
  673. var isInit = !existsEl;
  674. var el = existsEl;
  675. if (!el) {
  676. el = createEl(elOption);
  677. if (oldEl) {
  678. copyElement(oldEl, el);
  679. }
  680. } else {
  681. // FIMXE:NEXT unified clearState?
  682. // If in some case the performance issue arised, consider
  683. // do not clearState but update cached normal state directly.
  684. el.clearStates();
  685. }
  686. // Need to set morph: false explictly to disable automatically morphing.
  687. if (elOption.morph === false) {
  688. el.disableMorphing = true;
  689. } else if (el.disableMorphing) {
  690. el.disableMorphing = false;
  691. }
  692. if (elOption.tooltipDisabled) {
  693. el.tooltipDisabled = true;
  694. }
  695. attachedTxInfoTmp.normal.cfg = attachedTxInfoTmp.normal.conOpt = attachedTxInfoTmp.emphasis.cfg = attachedTxInfoTmp.emphasis.conOpt = attachedTxInfoTmp.blur.cfg = attachedTxInfoTmp.blur.conOpt = attachedTxInfoTmp.select.cfg = attachedTxInfoTmp.select.conOpt = null;
  696. attachedTxInfoTmp.isLegacy = false;
  697. doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfoTmp);
  698. doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit);
  699. updateElNormal(api, el, dataIndex, elOption, attachedTxInfoTmp, seriesModel, isInit);
  700. // `elOption.info` enables user to mount some info on
  701. // elements and use them in event handlers.
  702. // Update them only when user specified, otherwise, remain.
  703. hasOwn(elOption, 'info') && (customInnerStore(el).info = elOption.info);
  704. for (var i = 0; i < STATES.length; i++) {
  705. var stateName = STATES[i];
  706. if (stateName !== NORMAL) {
  707. var otherStateOpt = retrieveStateOption(elOption, stateName);
  708. var otherStyleOpt = retrieveStyleOptionOnState(elOption, otherStateOpt, stateName);
  709. updateElOnState(stateName, el, otherStateOpt, otherStyleOpt, attachedTxInfoTmp);
  710. }
  711. }
  712. updateZ(el, elOption, seriesModel);
  713. if (elOption.type === 'group') {
  714. mergeChildren(api, el, dataIndex, elOption, seriesModel);
  715. }
  716. if (toBeReplacedIdx >= 0) {
  717. group.replaceAt(el, toBeReplacedIdx);
  718. } else {
  719. group.add(el);
  720. }
  721. return el;
  722. }
  723. // `el` must not be null/undefined.
  724. function doesElNeedRecreate(el, elOption, seriesModel) {
  725. var elInner = customInnerStore(el);
  726. var elOptionType = elOption.type;
  727. var elOptionShape = elOption.shape;
  728. var elOptionStyle = elOption.style;
  729. return (
  730. // Always create new if universal transition is enabled.
  731. // Because we do transition after render. It needs to know what old element is. Replacement will loose it.
  732. seriesModel.isUniversalTransitionEnabled()
  733. // If `elOptionType` is `null`, follow the merge principle.
  734. || elOptionType != null && elOptionType !== elInner.customGraphicType || elOptionType === 'path' && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== elInner.customPathData || elOptionType === 'image' && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== elInner.customImagePath
  735. // // FIXME test and remove this restriction?
  736. // || (elOptionType === 'text'
  737. // && hasOwn(elOptionStyle, 'text')
  738. // && (elOptionStyle as TextStyleProps).text !== elInner.customText
  739. // )
  740. );
  741. }
  742. function doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit) {
  743. // Based on the "merge" principle, if no clipPath provided,
  744. // do nothing. The exists clip will be totally removed only if
  745. // `el.clipPath` is `false`. Otherwise it will be merged/replaced.
  746. var clipPathOpt = elOption.clipPath;
  747. if (clipPathOpt === false) {
  748. if (el && el.getClipPath()) {
  749. el.removeClipPath();
  750. }
  751. } else if (clipPathOpt) {
  752. var clipPath = el.getClipPath();
  753. if (clipPath && doesElNeedRecreate(clipPath, clipPathOpt, seriesModel)) {
  754. clipPath = null;
  755. }
  756. if (!clipPath) {
  757. clipPath = createEl(clipPathOpt);
  758. if (process.env.NODE_ENV !== 'production') {
  759. assert(isPath(clipPath), 'Only any type of `path` can be used in `clipPath`, rather than ' + clipPath.type + '.');
  760. }
  761. el.setClipPath(clipPath);
  762. }
  763. updateElNormal(null, clipPath, dataIndex, clipPathOpt, null, seriesModel, isInit);
  764. }
  765. // If not define `clipPath` in option, do nothing unnecessary.
  766. }
  767. function doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfo) {
  768. // Group does not support textContent temporarily until necessary.
  769. if (el.isGroup || el.type === 'compoundPath') {
  770. return;
  771. }
  772. // Normal must be called before emphasis, for `isLegacy` detection.
  773. processTxInfo(elOption, null, attachedTxInfo);
  774. processTxInfo(elOption, EMPHASIS, attachedTxInfo);
  775. // If `elOption.textConfig` or `elOption.textContent` is null/undefined, it does not make sense.
  776. // So for simplicity, if "elOption hasOwnProperty of them but be null/undefined", we do not
  777. // trade them as set to null to el.
  778. // Especially:
  779. // `elOption.textContent: false` means remove textContent.
  780. // `elOption.textContent.emphasis.style: false` means remove the style from emphasis state.
  781. var txConOptNormal = attachedTxInfo.normal.conOpt;
  782. var txConOptEmphasis = attachedTxInfo.emphasis.conOpt;
  783. var txConOptBlur = attachedTxInfo.blur.conOpt;
  784. var txConOptSelect = attachedTxInfo.select.conOpt;
  785. if (txConOptNormal != null || txConOptEmphasis != null || txConOptSelect != null || txConOptBlur != null) {
  786. var textContent = el.getTextContent();
  787. if (txConOptNormal === false) {
  788. textContent && el.removeTextContent();
  789. } else {
  790. txConOptNormal = attachedTxInfo.normal.conOpt = txConOptNormal || {
  791. type: 'text'
  792. };
  793. if (!textContent) {
  794. textContent = createEl(txConOptNormal);
  795. el.setTextContent(textContent);
  796. } else {
  797. // If in some case the performance issue arised, consider
  798. // do not clearState but update cached normal state directly.
  799. textContent.clearStates();
  800. }
  801. updateElNormal(null, textContent, dataIndex, txConOptNormal, null, seriesModel, isInit);
  802. var txConStlOptNormal = txConOptNormal && txConOptNormal.style;
  803. for (var i = 0; i < STATES.length; i++) {
  804. var stateName = STATES[i];
  805. if (stateName !== NORMAL) {
  806. var txConOptOtherState = attachedTxInfo[stateName].conOpt;
  807. updateElOnState(stateName, textContent, txConOptOtherState, retrieveStyleOptionOnState(txConOptNormal, txConOptOtherState, stateName), null);
  808. }
  809. }
  810. txConStlOptNormal ? textContent.dirty() : textContent.markRedraw();
  811. }
  812. }
  813. }
  814. function processTxInfo(elOption, state, attachedTxInfo) {
  815. var stateOpt = !state ? elOption : retrieveStateOption(elOption, state);
  816. var styleOpt = !state ? elOption.style : retrieveStyleOptionOnState(elOption, stateOpt, EMPHASIS);
  817. var elType = elOption.type;
  818. var txCfg = stateOpt ? stateOpt.textConfig : null;
  819. var txConOptNormal = elOption.textContent;
  820. var txConOpt = !txConOptNormal ? null : !state ? txConOptNormal : retrieveStateOption(txConOptNormal, state);
  821. if (styleOpt && (
  822. // Because emphasis style has little info to detect legacy,
  823. // if normal is legacy, emphasis is trade as legacy.
  824. attachedTxInfo.isLegacy || isEC4CompatibleStyle(styleOpt, elType, !!txCfg, !!txConOpt))) {
  825. attachedTxInfo.isLegacy = true;
  826. var convertResult = convertFromEC4CompatibleStyle(styleOpt, elType, !state);
  827. // Explicitly specified `textConfig` and `textContent` has higher priority than
  828. // the ones generated by legacy style. Otherwise if users use them and `api.style`
  829. // at the same time, they not both work and hardly to known why.
  830. if (!txCfg && convertResult.textConfig) {
  831. txCfg = convertResult.textConfig;
  832. }
  833. if (!txConOpt && convertResult.textContent) {
  834. txConOpt = convertResult.textContent;
  835. }
  836. }
  837. if (!state && txConOpt) {
  838. var txConOptNormal_1 = txConOpt;
  839. // `textContent: {type: 'text'}`, the "type" is easy to be missing. So we tolerate it.
  840. !txConOptNormal_1.type && (txConOptNormal_1.type = 'text');
  841. if (process.env.NODE_ENV !== 'production') {
  842. // Do not tolerate incorrcet type for forward compat.
  843. assert(txConOptNormal_1.type === 'text', 'textContent.type must be "text"');
  844. }
  845. }
  846. var info = !state ? attachedTxInfo.normal : attachedTxInfo[state];
  847. info.cfg = txCfg;
  848. info.conOpt = txConOpt;
  849. }
  850. function retrieveStateOption(elOption, state) {
  851. return !state ? elOption : elOption ? elOption[state] : null;
  852. }
  853. function retrieveStyleOptionOnState(stateOptionNormal, stateOption, state) {
  854. var style = stateOption && stateOption.style;
  855. if (style == null && state === EMPHASIS && stateOptionNormal) {
  856. style = stateOptionNormal.styleEmphasis;
  857. }
  858. return style;
  859. }
  860. // Usage:
  861. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates
  862. // that the existing children will not be removed, and enables the feature
  863. // that update some of the props of some of the children simply by construct
  864. // the returned children of `renderItem` like:
  865. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  866. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  867. // by child.name. But that might be lower performance.
  868. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  869. // replaced totally.
  870. // (4) If `!elOption.children`, following the "merge" principle, nothing will
  871. // happen.
  872. // (5) If `elOption.$mergeChildren` is not `false` neither `'byName'` and the
  873. // `el` is a group, and if any of the new child is null, it means to remove
  874. // the element at the same index, if exists. On the other hand, if the new
  875. // child is and empty object `{}`, it means to keep the element not changed.
  876. //
  877. // For implementation simpleness, do not provide a direct way to remove single
  878. // child (otherwise the total indices of the children array have to be modified).
  879. // User can remove a single child by setting its `ignore` to `true`.
  880. function mergeChildren(api, el, dataIndex, elOption, seriesModel) {
  881. var newChildren = elOption.children;
  882. var newLen = newChildren ? newChildren.length : 0;
  883. var mergeChildren = elOption.$mergeChildren;
  884. // `diffChildrenByName` has been deprecated.
  885. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  886. var notMerge = mergeChildren === false;
  887. // For better performance on roam update, only enter if necessary.
  888. if (!newLen && !byName && !notMerge) {
  889. return;
  890. }
  891. if (byName) {
  892. diffGroupChildren({
  893. api: api,
  894. oldChildren: el.children() || [],
  895. newChildren: newChildren || [],
  896. dataIndex: dataIndex,
  897. seriesModel: seriesModel,
  898. group: el
  899. });
  900. return;
  901. }
  902. notMerge && el.removeAll();
  903. // Mapping children of a group simply by index, which
  904. // might be better performance.
  905. var index = 0;
  906. for (; index < newLen; index++) {
  907. var newChild = newChildren[index];
  908. var oldChild = el.childAt(index);
  909. if (newChild) {
  910. if (newChild.ignore == null) {
  911. // The old child is set to be ignored if null (see comments
  912. // below). So we need to set ignore to be false back.
  913. newChild.ignore = false;
  914. }
  915. doCreateOrUpdateEl(api, oldChild, dataIndex, newChild, seriesModel, el);
  916. } else {
  917. if (process.env.NODE_ENV !== 'production') {
  918. assert(oldChild, 'renderItem should not return a group containing elements' + ' as null/undefined/{} if they do not exist before.');
  919. }
  920. // If the new element option is null, it means to remove the old
  921. // element. But we cannot really remove the element from the group
  922. // directly, because the element order may not be stable when this
  923. // element is added back. So we set the element to be ignored.
  924. oldChild.ignore = true;
  925. }
  926. }
  927. for (var i = el.childCount() - 1; i >= index; i--) {
  928. var child = el.childAt(i);
  929. removeChildFromGroup(el, child, seriesModel);
  930. }
  931. }
  932. function removeChildFromGroup(group, child, seriesModel) {
  933. // Do not support leave elements that are not mentioned in the latest
  934. // `renderItem` return. Otherwise users may not have a clear and simple
  935. // concept that how to control all of the elements.
  936. child && applyLeaveTransition(child, customInnerStore(group).option, seriesModel);
  937. }
  938. function diffGroupChildren(context) {
  939. new DataDiffer(context.oldChildren, context.newChildren, getKey, getKey, context).add(processAddUpdate).update(processAddUpdate).remove(processRemove).execute();
  940. }
  941. function getKey(item, idx) {
  942. var name = item && item.name;
  943. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  944. }
  945. function processAddUpdate(newIndex, oldIndex) {
  946. var context = this.context;
  947. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  948. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  949. doCreateOrUpdateEl(context.api, child, context.dataIndex, childOption, context.seriesModel, context.group);
  950. }
  951. function processRemove(oldIndex) {
  952. var context = this.context;
  953. var child = context.oldChildren[oldIndex];
  954. child && applyLeaveTransition(child, customInnerStore(child).option, context.seriesModel);
  955. }
  956. /**
  957. * @return SVG Path data.
  958. */
  959. function getPathData(shape) {
  960. // "d" follows the SVG convention.
  961. return shape && (shape.pathData || shape.d);
  962. }
  963. function hasOwnPathData(shape) {
  964. return shape && (hasOwn(shape, 'pathData') || hasOwn(shape, 'd'));
  965. }