CustomView.js 39 KB

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