graphic.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. import {__DEV__} from '../config';
  20. import * as echarts from '../echarts';
  21. import * as zrUtil from 'zrender/src/core/util';
  22. import * as modelUtil from '../util/model';
  23. import * as graphicUtil from '../util/graphic';
  24. import * as layoutUtil from '../util/layout';
  25. import {parsePercent} from '../util/number';
  26. var _nonShapeGraphicElements = {
  27. // Reserved but not supported in graphic component.
  28. path: null,
  29. compoundPath: null,
  30. // Supported in graphic component.
  31. group: graphicUtil.Group,
  32. image: graphicUtil.Image,
  33. text: graphicUtil.Text
  34. };
  35. // -------------
  36. // Preprocessor
  37. // -------------
  38. echarts.registerPreprocessor(function (option) {
  39. var graphicOption = option.graphic;
  40. // Convert
  41. // {graphic: [{left: 10, type: 'circle'}, ...]}
  42. // or
  43. // {graphic: {left: 10, type: 'circle'}}
  44. // to
  45. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  46. if (zrUtil.isArray(graphicOption)) {
  47. if (!graphicOption[0] || !graphicOption[0].elements) {
  48. option.graphic = [{elements: graphicOption}];
  49. }
  50. else {
  51. // Only one graphic instance can be instantiated. (We dont
  52. // want that too many views are created in echarts._viewMap)
  53. option.graphic = [option.graphic[0]];
  54. }
  55. }
  56. else if (graphicOption && !graphicOption.elements) {
  57. option.graphic = [{elements: [graphicOption]}];
  58. }
  59. });
  60. // ------
  61. // Model
  62. // ------
  63. var GraphicModel = echarts.extendComponentModel({
  64. type: 'graphic',
  65. defaultOption: {
  66. // Extra properties for each elements:
  67. //
  68. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  69. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  70. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  71. // This mechanism is useful when you want to position a group/element
  72. // against the right side or the center of this container.
  73. //
  74. // width/height: (can only be pixel value, default 0)
  75. // Only be used to specify contianer(group) size, if needed. And
  76. // can not be percentage value (like '33%'). See the reason in the
  77. // layout algorithm below.
  78. //
  79. // bounding: (enum: 'all' (default) | 'raw')
  80. // Specify how to calculate boundingRect when locating.
  81. // 'all': Get uioned and transformed boundingRect
  82. // from both itself and its descendants.
  83. // This mode simplies confining a group of elements in the bounding
  84. // of their ancester container (e.g., using 'right: 0').
  85. // 'raw': Only use the boundingRect of itself and before transformed.
  86. // This mode is similar to css behavior, which is useful when you
  87. // want an element to be able to overflow its container. (Consider
  88. // a rotated circle needs to be located in a corner.)
  89. // info: custom info. enables user to mount some info on elements and use them
  90. // in event handlers. Update them only when user specified, otherwise, remain.
  91. // Note: elements is always behind its ancestors in this elements array.
  92. elements: [],
  93. parentId: null
  94. },
  95. /**
  96. * Save el options for the sake of the performance (only update modified graphics).
  97. * The order is the same as those in option. (ancesters -> descendants)
  98. *
  99. * @private
  100. * @type {Array.<Object>}
  101. */
  102. _elOptionsToUpdate: null,
  103. /**
  104. * @override
  105. */
  106. mergeOption: function (option) {
  107. // Prevent default merge to elements
  108. var elements = this.option.elements;
  109. this.option.elements = null;
  110. GraphicModel.superApply(this, 'mergeOption', arguments);
  111. this.option.elements = elements;
  112. },
  113. /**
  114. * @override
  115. */
  116. optionUpdated: function (newOption, isInit) {
  117. var thisOption = this.option;
  118. var newList = (isInit ? thisOption : newOption).elements;
  119. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  120. var flattenedList = [];
  121. this._flatten(newList, flattenedList);
  122. var mappingResult = modelUtil.mappingToExists(existList, flattenedList);
  123. modelUtil.makeIdAndName(mappingResult);
  124. // Clear elOptionsToUpdate
  125. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  126. zrUtil.each(mappingResult, function (resultItem, index) {
  127. var newElOption = resultItem.option;
  128. if (__DEV__) {
  129. zrUtil.assert(
  130. zrUtil.isObject(newElOption) || resultItem.exist,
  131. 'Empty graphic option definition'
  132. );
  133. }
  134. if (!newElOption) {
  135. return;
  136. }
  137. elOptionsToUpdate.push(newElOption);
  138. setKeyInfoToNewElOption(resultItem, newElOption);
  139. mergeNewElOptionToExist(existList, index, newElOption);
  140. setLayoutInfoToExist(existList[index], newElOption);
  141. }, this);
  142. // Clean
  143. for (var i = existList.length - 1; i >= 0; i--) {
  144. if (existList[i] == null) {
  145. existList.splice(i, 1);
  146. }
  147. else {
  148. // $action should be volatile, otherwise option gotten from
  149. // `getOption` will contain unexpected $action.
  150. delete existList[i].$action;
  151. }
  152. }
  153. },
  154. /**
  155. * Convert
  156. * [{
  157. * type: 'group',
  158. * id: 'xx',
  159. * children: [{type: 'circle'}, {type: 'polygon'}]
  160. * }]
  161. * to
  162. * [
  163. * {type: 'group', id: 'xx'},
  164. * {type: 'circle', parentId: 'xx'},
  165. * {type: 'polygon', parentId: 'xx'}
  166. * ]
  167. *
  168. * @private
  169. * @param {Array.<Object>} optionList option list
  170. * @param {Array.<Object>} result result of flatten
  171. * @param {Object} parentOption parent option
  172. */
  173. _flatten: function (optionList, result, parentOption) {
  174. zrUtil.each(optionList, function (option) {
  175. if (!option) {
  176. return;
  177. }
  178. if (parentOption) {
  179. option.parentOption = parentOption;
  180. }
  181. result.push(option);
  182. var children = option.children;
  183. if (option.type === 'group' && children) {
  184. this._flatten(children, result, option);
  185. }
  186. // Deleting for JSON output, and for not affecting group creation.
  187. delete option.children;
  188. }, this);
  189. },
  190. // FIXME
  191. // Pass to view using payload? setOption has a payload?
  192. useElOptionsToUpdate: function () {
  193. var els = this._elOptionsToUpdate;
  194. // Clear to avoid render duplicately when zooming.
  195. this._elOptionsToUpdate = null;
  196. return els;
  197. }
  198. });
  199. // -----
  200. // View
  201. // -----
  202. echarts.extendComponentView({
  203. type: 'graphic',
  204. /**
  205. * @override
  206. */
  207. init: function (ecModel, api) {
  208. /**
  209. * @private
  210. * @type {module:zrender/core/util.HashMap}
  211. */
  212. this._elMap = zrUtil.createHashMap();
  213. /**
  214. * @private
  215. * @type {module:echarts/graphic/GraphicModel}
  216. */
  217. this._lastGraphicModel;
  218. },
  219. /**
  220. * @override
  221. */
  222. render: function (graphicModel, ecModel, api) {
  223. // Having leveraged between use cases and algorithm complexity, a very
  224. // simple layout mechanism is used:
  225. // The size(width/height) can be determined by itself or its parent (not
  226. // implemented yet), but can not by its children. (Top-down travel)
  227. // The location(x/y) can be determined by the bounding rect of itself
  228. // (can including its descendants or not) and the size of its parent.
  229. // (Bottom-up travel)
  230. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  231. // view will be reused.
  232. if (graphicModel !== this._lastGraphicModel) {
  233. this._clear();
  234. }
  235. this._lastGraphicModel = graphicModel;
  236. this._updateElements(graphicModel);
  237. this._relocate(graphicModel, api);
  238. },
  239. /**
  240. * Update graphic elements.
  241. *
  242. * @private
  243. * @param {Object} graphicModel graphic model
  244. */
  245. _updateElements: function (graphicModel) {
  246. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  247. if (!elOptionsToUpdate) {
  248. return;
  249. }
  250. var elMap = this._elMap;
  251. var rootGroup = this.group;
  252. // Top-down tranverse to assign graphic settings to each elements.
  253. zrUtil.each(elOptionsToUpdate, function (elOption) {
  254. var $action = elOption.$action;
  255. var id = elOption.id;
  256. var existEl = elMap.get(id);
  257. var parentId = elOption.parentId;
  258. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  259. var elOptionStyle = elOption.style;
  260. if (elOption.type === 'text' && elOptionStyle) {
  261. // In top/bottom mode, textVerticalAlign should not be used, which cause
  262. // inaccurately locating.
  263. if (elOption.hv && elOption.hv[1]) {
  264. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  265. }
  266. // Compatible with previous setting: both support fill and textFill,
  267. // stroke and textStroke.
  268. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  269. elOptionStyle.textFill = elOptionStyle.fill
  270. );
  271. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  272. elOptionStyle.textStroke = elOptionStyle.stroke
  273. );
  274. }
  275. // Remove unnecessary props to avoid potential problems.
  276. var elOptionCleaned = getCleanedElOption(elOption);
  277. // For simple, do not support parent change, otherwise reorder is needed.
  278. if (__DEV__) {
  279. existEl && zrUtil.assert(
  280. targetElParent === existEl.parent,
  281. 'Changing parent is not supported.'
  282. );
  283. }
  284. if (!$action || $action === 'merge') {
  285. existEl
  286. ? existEl.attr(elOptionCleaned)
  287. : createEl(id, targetElParent, elOptionCleaned, elMap);
  288. }
  289. else if ($action === 'replace') {
  290. removeEl(existEl, elMap);
  291. createEl(id, targetElParent, elOptionCleaned, elMap);
  292. }
  293. else if ($action === 'remove') {
  294. removeEl(existEl, elMap);
  295. }
  296. var el = elMap.get(id);
  297. if (el) {
  298. el.__ecGraphicWidthOption = elOption.width;
  299. el.__ecGraphicHeightOption = elOption.height;
  300. setEventData(el, graphicModel, elOption);
  301. }
  302. });
  303. },
  304. /**
  305. * Locate graphic elements.
  306. *
  307. * @private
  308. * @param {Object} graphicModel graphic model
  309. * @param {module:echarts/ExtensionAPI} api extension API
  310. */
  311. _relocate: function (graphicModel, api) {
  312. var elOptions = graphicModel.option.elements;
  313. var rootGroup = this.group;
  314. var elMap = this._elMap;
  315. var apiWidth = api.getWidth();
  316. var apiHeight = api.getHeight();
  317. // Top-down to calculate percentage width/height of group
  318. for (var i = 0; i < elOptions.length; i++) {
  319. var elOption = elOptions[i];
  320. var el = elMap.get(elOption.id);
  321. if (!el || !el.isGroup) {
  322. continue;
  323. }
  324. var parentEl = el.parent;
  325. var isParentRoot = parentEl === rootGroup;
  326. // Like 'position:absolut' in css, default 0.
  327. el.__ecGraphicWidth = parsePercent(
  328. el.__ecGraphicWidthOption,
  329. isParentRoot ? apiWidth : parentEl.__ecGraphicWidth
  330. ) || 0;
  331. el.__ecGraphicHeight = parsePercent(
  332. el.__ecGraphicHeightOption,
  333. isParentRoot ? apiHeight : parentEl.__ecGraphicHeight
  334. ) || 0;
  335. }
  336. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  337. for (var i = elOptions.length - 1; i >= 0; i--) {
  338. var elOption = elOptions[i];
  339. var el = elMap.get(elOption.id);
  340. if (!el) {
  341. continue;
  342. }
  343. var parentEl = el.parent;
  344. var containerInfo = parentEl === rootGroup
  345. ? {
  346. width: apiWidth,
  347. height: apiHeight
  348. }
  349. : {
  350. width: parentEl.__ecGraphicWidth,
  351. height: parentEl.__ecGraphicHeight
  352. };
  353. // PENDING
  354. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  355. // does not include the rect of [0, 0, group.width, group.height], which
  356. // is probably weird for users. Should we make a break change for it?
  357. layoutUtil.positionElement(
  358. el, elOption, containerInfo, null,
  359. {hv: elOption.hv, boundingMode: elOption.bounding}
  360. );
  361. }
  362. },
  363. /**
  364. * Clear all elements.
  365. *
  366. * @private
  367. */
  368. _clear: function () {
  369. var elMap = this._elMap;
  370. elMap.each(function (el) {
  371. removeEl(el, elMap);
  372. });
  373. this._elMap = zrUtil.createHashMap();
  374. },
  375. /**
  376. * @override
  377. */
  378. dispose: function () {
  379. this._clear();
  380. }
  381. });
  382. function createEl(id, targetElParent, elOption, elMap) {
  383. var graphicType = elOption.type;
  384. if (__DEV__) {
  385. zrUtil.assert(graphicType, 'graphic type MUST be set');
  386. }
  387. var Clz = _nonShapeGraphicElements.hasOwnProperty(graphicType)
  388. // Those graphic elements are not shapes. They should not be
  389. // overwritten by users, so do them first.
  390. ? _nonShapeGraphicElements[graphicType]
  391. : graphicUtil.getShapeClass(graphicType);
  392. if (__DEV__) {
  393. zrUtil.assert(Clz, 'graphic type can not be found');
  394. }
  395. var el = new Clz(elOption);
  396. targetElParent.add(el);
  397. elMap.set(id, el);
  398. el.__ecGraphicId = id;
  399. }
  400. function removeEl(existEl, elMap) {
  401. var existElParent = existEl && existEl.parent;
  402. if (existElParent) {
  403. existEl.type === 'group' && existEl.traverse(function (el) {
  404. removeEl(el, elMap);
  405. });
  406. elMap.removeKey(existEl.__ecGraphicId);
  407. existElParent.remove(existEl);
  408. }
  409. }
  410. // Remove unnecessary props to avoid potential problems.
  411. function getCleanedElOption(elOption) {
  412. elOption = zrUtil.extend({}, elOption);
  413. zrUtil.each(
  414. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(layoutUtil.LOCATION_PARAMS),
  415. function (name) {
  416. delete elOption[name];
  417. }
  418. );
  419. return elOption;
  420. }
  421. function isSetLoc(obj, props) {
  422. var isSet;
  423. zrUtil.each(props, function (prop) {
  424. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  425. });
  426. return isSet;
  427. }
  428. function setKeyInfoToNewElOption(resultItem, newElOption) {
  429. var existElOption = resultItem.exist;
  430. // Set id and type after id assigned.
  431. newElOption.id = resultItem.keyInfo.id;
  432. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  433. // Set parent id if not specified
  434. if (newElOption.parentId == null) {
  435. var newElParentOption = newElOption.parentOption;
  436. if (newElParentOption) {
  437. newElOption.parentId = newElParentOption.id;
  438. }
  439. else if (existElOption) {
  440. newElOption.parentId = existElOption.parentId;
  441. }
  442. }
  443. // Clear
  444. newElOption.parentOption = null;
  445. }
  446. function mergeNewElOptionToExist(existList, index, newElOption) {
  447. // Update existing options, for `getOption` feature.
  448. var newElOptCopy = zrUtil.extend({}, newElOption);
  449. var existElOption = existList[index];
  450. var $action = newElOption.$action || 'merge';
  451. if ($action === 'merge') {
  452. if (existElOption) {
  453. if (__DEV__) {
  454. var newType = newElOption.type;
  455. zrUtil.assert(
  456. !newType || existElOption.type === newType,
  457. 'Please set $action: "replace" to change `type`'
  458. );
  459. }
  460. // We can ensure that newElOptCopy and existElOption are not
  461. // the same object, so `merge` will not change newElOptCopy.
  462. zrUtil.merge(existElOption, newElOptCopy, true);
  463. // Rigid body, use ignoreSize.
  464. layoutUtil.mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  465. // Will be used in render.
  466. layoutUtil.copyLayoutParams(newElOption, existElOption);
  467. }
  468. else {
  469. existList[index] = newElOptCopy;
  470. }
  471. }
  472. else if ($action === 'replace') {
  473. existList[index] = newElOptCopy;
  474. }
  475. else if ($action === 'remove') {
  476. // null will be cleaned later.
  477. existElOption && (existList[index] = null);
  478. }
  479. }
  480. function setLayoutInfoToExist(existItem, newElOption) {
  481. if (!existItem) {
  482. return;
  483. }
  484. existItem.hv = newElOption.hv = [
  485. // Rigid body, dont care `width`.
  486. isSetLoc(newElOption, ['left', 'right']),
  487. // Rigid body, dont care `height`.
  488. isSetLoc(newElOption, ['top', 'bottom'])
  489. ];
  490. // Give default group size. Otherwise layout error may occur.
  491. if (existItem.type === 'group') {
  492. existItem.width == null && (existItem.width = newElOption.width = 0);
  493. existItem.height == null && (existItem.height = newElOption.height = 0);
  494. }
  495. }
  496. function setEventData(el, graphicModel, elOption) {
  497. var eventData = el.eventData;
  498. // Simple optimize for large amount of elements that no need event.
  499. if (!el.silent && !el.ignore && !eventData) {
  500. eventData = el.eventData = {
  501. componentType: 'graphic',
  502. componentIndex: graphicModel.componentIndex,
  503. name: el.name
  504. };
  505. }
  506. // `elOption.info` enables user to mount some info on
  507. // elements and use them in event handlers.
  508. if (eventData) {
  509. eventData.info = el.info;
  510. }
  511. }