Canvas.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  1. import {
  2. isNumber,
  3. assign,
  4. forEach,
  5. every,
  6. debounce,
  7. bind,
  8. reduce,
  9. find,
  10. isDefined
  11. } from 'min-dash';
  12. import {
  13. assignStyle
  14. } from 'min-dom';
  15. import {
  16. add as collectionAdd,
  17. remove as collectionRemove
  18. } from '../util/Collections';
  19. import {
  20. getType,
  21. getBBox as getBoundingBox
  22. } from '../util/Elements';
  23. import { asTRBL } from '../layout/LayoutUtil';
  24. import {
  25. append as svgAppend,
  26. attr as svgAttr,
  27. classes as svgClasses,
  28. create as svgCreate,
  29. transform as svgTransform,
  30. remove as svgRemove
  31. } from 'tiny-svg';
  32. import { createMatrix as createMatrix } from 'tiny-svg';
  33. function round(number, resolution) {
  34. return Math.round(number * resolution) / resolution;
  35. }
  36. function ensurePx(number) {
  37. return isNumber(number) ? number + 'px' : number;
  38. }
  39. function findRoot(element) {
  40. while (element.parent) {
  41. element = element.parent;
  42. }
  43. return element;
  44. }
  45. /**
  46. * Creates a HTML container element for a SVG element with
  47. * the given configuration
  48. *
  49. * @param {Object} options
  50. * @return {HTMLElement} the container element
  51. */
  52. function createContainer(options) {
  53. options = assign({}, { width: '100%', height: '100%' }, options);
  54. const container = options.container || document.body;
  55. // create a <div> around the svg element with the respective size
  56. // this way we can always get the correct container size
  57. // (this is impossible for <svg> elements at the moment)
  58. const parent = document.createElement('div');
  59. parent.setAttribute('class', 'djs-container djs-parent');
  60. assignStyle(parent, {
  61. position: 'relative',
  62. overflow: 'hidden',
  63. width: ensurePx(options.width),
  64. height: ensurePx(options.height)
  65. });
  66. container.appendChild(parent);
  67. return parent;
  68. }
  69. function createGroup(parent, cls, childIndex) {
  70. const group = svgCreate('g');
  71. svgClasses(group).add(cls);
  72. const index = childIndex !== undefined ? childIndex : parent.childNodes.length - 1;
  73. // must ensure second argument is node or _null_
  74. // cf. https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
  75. parent.insertBefore(group, parent.childNodes[index] || null);
  76. return group;
  77. }
  78. const BASE_LAYER = 'base';
  79. // render plane contents behind utility layers
  80. const PLANE_LAYER_INDEX = 0;
  81. const UTILITY_LAYER_INDEX = 1;
  82. const REQUIRED_MODEL_ATTRS = {
  83. shape: [ 'x', 'y', 'width', 'height' ],
  84. connection: [ 'waypoints' ]
  85. };
  86. /**
  87. * The main drawing canvas.
  88. *
  89. * @class
  90. * @constructor
  91. *
  92. * @emits Canvas#canvas.init
  93. *
  94. * @param {Object} config
  95. * @param {EventBus} eventBus
  96. * @param {GraphicsFactory} graphicsFactory
  97. * @param {ElementRegistry} elementRegistry
  98. */
  99. export default function Canvas(config, eventBus, graphicsFactory, elementRegistry) {
  100. this._eventBus = eventBus;
  101. this._elementRegistry = elementRegistry;
  102. this._graphicsFactory = graphicsFactory;
  103. this._rootsIdx = 0;
  104. this._layers = {};
  105. this._planes = [];
  106. this._rootElement = null;
  107. this._init(config || {});
  108. }
  109. Canvas.$inject = [
  110. 'config.canvas',
  111. 'eventBus',
  112. 'graphicsFactory',
  113. 'elementRegistry'
  114. ];
  115. /**
  116. * Creates a <svg> element that is wrapped into a <div>.
  117. * This way we are always able to correctly figure out the size of the svg element
  118. * by querying the parent node.
  119. * (It is not possible to get the size of a svg element cross browser @ 2014-04-01)
  120. * <div class="djs-container" style="width: {desired-width}, height: {desired-height}">
  121. * <svg width="100%" height="100%">
  122. * ...
  123. * </svg>
  124. * </div>
  125. */
  126. Canvas.prototype._init = function(config) {
  127. const eventBus = this._eventBus;
  128. // html container
  129. const container = this._container = createContainer(config);
  130. const svg = this._svg = svgCreate('svg');
  131. svgAttr(svg, { width: '100%', height: '100%' });
  132. svgAppend(container, svg);
  133. const viewport = this._viewport = createGroup(svg, 'viewport');
  134. // debounce canvas.viewbox.changed events
  135. // for smoother diagram interaction
  136. if (config.deferUpdate !== false) {
  137. this._viewboxChanged = debounce(bind(this._viewboxChanged, this), 300);
  138. }
  139. eventBus.on('diagram.init', function() {
  140. /**
  141. * An event indicating that the canvas is ready to be drawn on.
  142. *
  143. * @memberOf Canvas
  144. *
  145. * @event canvas.init
  146. *
  147. * @type {Object}
  148. * @property {SVGElement} svg the created svg element
  149. * @property {SVGElement} viewport the direct parent of diagram elements and shapes
  150. */
  151. eventBus.fire('canvas.init', {
  152. svg: svg,
  153. viewport: viewport
  154. });
  155. }, this);
  156. // reset viewbox on shape changes to
  157. // recompute the viewbox
  158. eventBus.on([
  159. 'shape.added',
  160. 'connection.added',
  161. 'shape.removed',
  162. 'connection.removed',
  163. 'elements.changed',
  164. 'root.set'
  165. ], function() {
  166. delete this._cachedViewbox;
  167. }, this);
  168. eventBus.on('diagram.destroy', 500, this._destroy, this);
  169. eventBus.on('diagram.clear', 500, this._clear, this);
  170. };
  171. Canvas.prototype._destroy = function(emit) {
  172. this._eventBus.fire('canvas.destroy', {
  173. svg: this._svg,
  174. viewport: this._viewport
  175. });
  176. const parent = this._container.parentNode;
  177. if (parent) {
  178. parent.removeChild(this._container);
  179. }
  180. delete this._svg;
  181. delete this._container;
  182. delete this._layers;
  183. delete this._planes;
  184. delete this._rootElement;
  185. delete this._viewport;
  186. };
  187. Canvas.prototype._clear = function() {
  188. const allElements = this._elementRegistry.getAll();
  189. // remove all elements
  190. allElements.forEach(element => {
  191. const type = getType(element);
  192. if (type === 'root') {
  193. this.removeRootElement(element);
  194. } else {
  195. this._removeElement(element, type);
  196. }
  197. });
  198. // remove all planes
  199. this._planes = [];
  200. this._rootElement = null;
  201. // force recomputation of view box
  202. delete this._cachedViewbox;
  203. };
  204. /**
  205. * Returns the default layer on which
  206. * all elements are drawn.
  207. *
  208. * @returns {SVGElement}
  209. */
  210. Canvas.prototype.getDefaultLayer = function() {
  211. return this.getLayer(BASE_LAYER, PLANE_LAYER_INDEX);
  212. };
  213. /**
  214. * Returns a layer that is used to draw elements
  215. * or annotations on it.
  216. *
  217. * Non-existing layers retrieved through this method
  218. * will be created. During creation, the optional index
  219. * may be used to create layers below or above existing layers.
  220. * A layer with a certain index is always created above all
  221. * existing layers with the same index.
  222. *
  223. * @param {string} name
  224. * @param {number} index
  225. *
  226. * @returns {SVGElement}
  227. */
  228. Canvas.prototype.getLayer = function(name, index) {
  229. if (!name) {
  230. throw new Error('must specify a name');
  231. }
  232. let layer = this._layers[name];
  233. if (!layer) {
  234. layer = this._layers[name] = this._createLayer(name, index);
  235. }
  236. // throw an error if layer creation / retrival is
  237. // requested on different index
  238. if (typeof index !== 'undefined' && layer.index !== index) {
  239. throw new Error('layer <' + name + '> already created at index <' + index + '>');
  240. }
  241. return layer.group;
  242. };
  243. /**
  244. * For a given index, return the number of layers that have a higher index and
  245. * are visible.
  246. *
  247. * This is used to determine the node a layer should be inserted at.
  248. *
  249. * @param {Number} index
  250. * @returns {Number}
  251. */
  252. Canvas.prototype._getChildIndex = function(index) {
  253. return reduce(this._layers, function(childIndex, layer) {
  254. if (layer.visible && index >= layer.index) {
  255. childIndex++;
  256. }
  257. return childIndex;
  258. }, 0);
  259. };
  260. /**
  261. * Creates a given layer and returns it.
  262. *
  263. * @param {string} name
  264. * @param {number} [index=0]
  265. *
  266. * @return {Object} layer descriptor with { index, group: SVGGroup }
  267. */
  268. Canvas.prototype._createLayer = function(name, index) {
  269. if (typeof index === 'undefined') {
  270. index = UTILITY_LAYER_INDEX;
  271. }
  272. const childIndex = this._getChildIndex(index);
  273. return {
  274. group: createGroup(this._viewport, 'layer-' + name, childIndex),
  275. index: index,
  276. visible: true
  277. };
  278. };
  279. /**
  280. * Shows a given layer.
  281. *
  282. * @param {String} layer
  283. * @returns {SVGElement}
  284. */
  285. Canvas.prototype.showLayer = function(name) {
  286. if (!name) {
  287. throw new Error('must specify a name');
  288. }
  289. const layer = this._layers[name];
  290. if (!layer) {
  291. throw new Error('layer <' + name + '> does not exist');
  292. }
  293. const viewport = this._viewport;
  294. const group = layer.group;
  295. const index = layer.index;
  296. if (layer.visible) {
  297. return group;
  298. }
  299. const childIndex = this._getChildIndex(index);
  300. viewport.insertBefore(group, viewport.childNodes[childIndex] || null);
  301. layer.visible = true;
  302. return group;
  303. };
  304. /**
  305. * Hides a given layer.
  306. *
  307. * @param {String} layer
  308. * @returns {SVGElement}
  309. */
  310. Canvas.prototype.hideLayer = function(name) {
  311. if (!name) {
  312. throw new Error('must specify a name');
  313. }
  314. const layer = this._layers[name];
  315. if (!layer) {
  316. throw new Error('layer <' + name + '> does not exist');
  317. }
  318. const group = layer.group;
  319. if (!layer.visible) {
  320. return group;
  321. }
  322. svgRemove(group);
  323. layer.visible = false;
  324. return group;
  325. };
  326. Canvas.prototype._removeLayer = function(name) {
  327. const layer = this._layers[name];
  328. if (layer) {
  329. delete this._layers[name];
  330. svgRemove(layer.group);
  331. }
  332. };
  333. /**
  334. * Returns the currently active layer. Can be null.
  335. *
  336. * @returns {SVGElement|null}
  337. */
  338. Canvas.prototype.getActiveLayer = function() {
  339. const plane = this._findPlaneForRoot(this.getRootElement());
  340. if (!plane) {
  341. return null;
  342. }
  343. return plane.layer;
  344. };
  345. /**
  346. * Returns the plane which contains the given element.
  347. *
  348. * @param {string|djs.model.Base} element
  349. *
  350. * @return {djs.model.Base} root for element
  351. */
  352. Canvas.prototype.findRoot = function(element) {
  353. if (typeof element === 'string') {
  354. element = this._elementRegistry.get(element);
  355. }
  356. if (!element) {
  357. return;
  358. }
  359. const plane = this._findPlaneForRoot(
  360. findRoot(element)
  361. ) || {};
  362. return plane.rootElement;
  363. };
  364. /**
  365. * Return a list of all root elements on the diagram.
  366. *
  367. * @return {djs.model.Root[]}
  368. */
  369. Canvas.prototype.getRootElements = function() {
  370. return this._planes.map(function(plane) {
  371. return plane.rootElement;
  372. });
  373. };
  374. Canvas.prototype._findPlaneForRoot = function(rootElement) {
  375. return find(this._planes, function(plane) {
  376. return plane.rootElement === rootElement;
  377. });
  378. };
  379. /**
  380. * Returns the html element that encloses the
  381. * drawing canvas.
  382. *
  383. * @return {DOMNode}
  384. */
  385. Canvas.prototype.getContainer = function() {
  386. return this._container;
  387. };
  388. // markers //////////////////////
  389. Canvas.prototype._updateMarker = function(element, marker, add) {
  390. let container;
  391. if (!element.id) {
  392. element = this._elementRegistry.get(element);
  393. }
  394. // we need to access all
  395. container = this._elementRegistry._elements[element.id];
  396. if (!container) {
  397. return;
  398. }
  399. forEach([ container.gfx, container.secondaryGfx ], function(gfx) {
  400. if (gfx) {
  401. // invoke either addClass or removeClass based on mode
  402. if (add) {
  403. svgClasses(gfx).add(marker);
  404. } else {
  405. svgClasses(gfx).remove(marker);
  406. }
  407. }
  408. });
  409. /**
  410. * An event indicating that a marker has been updated for an element
  411. *
  412. * @event element.marker.update
  413. * @type {Object}
  414. * @property {djs.model.Element} element the shape
  415. * @property {Object} gfx the graphical representation of the shape
  416. * @property {string} marker
  417. * @property {boolean} add true if the marker was added, false if it got removed
  418. */
  419. this._eventBus.fire('element.marker.update', { element: element, gfx: container.gfx, marker: marker, add: !!add });
  420. };
  421. /**
  422. * Adds a marker to an element (basically a css class).
  423. *
  424. * Fires the element.marker.update event, making it possible to
  425. * integrate extension into the marker life-cycle, too.
  426. *
  427. * @example
  428. * canvas.addMarker('foo', 'some-marker');
  429. *
  430. * const fooGfx = canvas.getGraphics('foo');
  431. *
  432. * fooGfx; // <g class="... some-marker"> ... </g>
  433. *
  434. * @param {string|djs.model.Base} element
  435. * @param {string} marker
  436. */
  437. Canvas.prototype.addMarker = function(element, marker) {
  438. this._updateMarker(element, marker, true);
  439. };
  440. /**
  441. * Remove a marker from an element.
  442. *
  443. * Fires the element.marker.update event, making it possible to
  444. * integrate extension into the marker life-cycle, too.
  445. *
  446. * @param {string|djs.model.Base} element
  447. * @param {string} marker
  448. */
  449. Canvas.prototype.removeMarker = function(element, marker) {
  450. this._updateMarker(element, marker, false);
  451. };
  452. /**
  453. * Check the existence of a marker on element.
  454. *
  455. * @param {string|djs.model.Base} element
  456. * @param {string} marker
  457. */
  458. Canvas.prototype.hasMarker = function(element, marker) {
  459. if (!element.id) {
  460. element = this._elementRegistry.get(element);
  461. }
  462. const gfx = this.getGraphics(element);
  463. return svgClasses(gfx).has(marker);
  464. };
  465. /**
  466. * Toggles a marker on an element.
  467. *
  468. * Fires the element.marker.update event, making it possible to
  469. * integrate extension into the marker life-cycle, too.
  470. *
  471. * @param {string|djs.model.Base} element
  472. * @param {string} marker
  473. */
  474. Canvas.prototype.toggleMarker = function(element, marker) {
  475. if (this.hasMarker(element, marker)) {
  476. this.removeMarker(element, marker);
  477. } else {
  478. this.addMarker(element, marker);
  479. }
  480. };
  481. /**
  482. * Returns the current root element.
  483. *
  484. * Supports two different modes for handling root elements:
  485. *
  486. * 1. if no root element has been added before, an implicit root will be added
  487. * and returned. This is used in applications that don't require explicit
  488. * root elements.
  489. *
  490. * 2. when root elements have been added before calling `getRootElement`,
  491. * root elements can be null. This is used for applications that want to manage
  492. * root elements themselves.
  493. *
  494. * @returns {Object|djs.model.Root|null} rootElement.
  495. */
  496. Canvas.prototype.getRootElement = function() {
  497. const rootElement = this._rootElement;
  498. // can return null if root elements are present but none was set yet
  499. if (rootElement || this._planes.length) {
  500. return rootElement;
  501. }
  502. return this.setRootElement(this.addRootElement(null));
  503. };
  504. /**
  505. * Adds a given root element and returns it.
  506. *
  507. * @param {Object|djs.model.Root} rootElement
  508. *
  509. * @return {Object|djs.model.Root} rootElement
  510. */
  511. Canvas.prototype.addRootElement = function(rootElement) {
  512. const idx = this._rootsIdx++;
  513. if (!rootElement) {
  514. rootElement = {
  515. id: '__implicitroot_' + idx,
  516. children: [],
  517. isImplicit: true
  518. };
  519. }
  520. const layerName = rootElement.layer = 'root-' + idx;
  521. this._ensureValid('root', rootElement);
  522. const layer = this.getLayer(layerName, PLANE_LAYER_INDEX);
  523. this.hideLayer(layerName);
  524. this._addRoot(rootElement, layer);
  525. this._planes.push({
  526. rootElement: rootElement,
  527. layer: layer
  528. });
  529. return rootElement;
  530. };
  531. /**
  532. * Removes a given rootElement and returns it.
  533. *
  534. * @param {djs.model.Root|String} rootElement
  535. *
  536. * @return {Object|djs.model.Root} rootElement
  537. */
  538. Canvas.prototype.removeRootElement = function(rootElement) {
  539. if (typeof rootElement === 'string') {
  540. rootElement = this._elementRegistry.get(rootElement);
  541. }
  542. const plane = this._findPlaneForRoot(rootElement);
  543. if (!plane) {
  544. return;
  545. }
  546. // hook up life-cycle events
  547. this._removeRoot(rootElement);
  548. // clean up layer
  549. this._removeLayer(rootElement.layer);
  550. // clean up plane
  551. this._planes = this._planes.filter(function(plane) {
  552. return plane.rootElement !== rootElement;
  553. });
  554. // clean up active root
  555. if (this._rootElement === rootElement) {
  556. this._rootElement = null;
  557. }
  558. return rootElement;
  559. };
  560. // root element handling //////////////////////
  561. /**
  562. * Sets a given element as the new root element for the canvas
  563. * and returns the new root element.
  564. *
  565. * @param {Object|djs.model.Root} rootElement
  566. *
  567. * @return {Object|djs.model.Root} new root element
  568. */
  569. Canvas.prototype.setRootElement = function(rootElement, override) {
  570. if (isDefined(override)) {
  571. throw new Error('override not supported');
  572. }
  573. if (rootElement === this._rootElement) {
  574. return;
  575. }
  576. let plane;
  577. if (!rootElement) {
  578. throw new Error('rootElement required');
  579. }
  580. plane = this._findPlaneForRoot(rootElement);
  581. // give set add semantics for backwards compatibility
  582. if (!plane) {
  583. rootElement = this.addRootElement(rootElement);
  584. }
  585. this._setRoot(rootElement);
  586. return rootElement;
  587. };
  588. Canvas.prototype._removeRoot = function(element) {
  589. const elementRegistry = this._elementRegistry,
  590. eventBus = this._eventBus;
  591. // simulate element remove event sequence
  592. eventBus.fire('root.remove', { element: element });
  593. eventBus.fire('root.removed', { element: element });
  594. elementRegistry.remove(element);
  595. };
  596. Canvas.prototype._addRoot = function(element, gfx) {
  597. const elementRegistry = this._elementRegistry,
  598. eventBus = this._eventBus;
  599. // resemble element add event sequence
  600. eventBus.fire('root.add', { element: element });
  601. elementRegistry.add(element, gfx);
  602. eventBus.fire('root.added', { element: element, gfx: gfx });
  603. };
  604. Canvas.prototype._setRoot = function(rootElement, layer) {
  605. const currentRoot = this._rootElement;
  606. if (currentRoot) {
  607. // un-associate previous root element <svg>
  608. this._elementRegistry.updateGraphics(currentRoot, null, true);
  609. // hide previous layer
  610. this.hideLayer(currentRoot.layer);
  611. }
  612. if (rootElement) {
  613. if (!layer) {
  614. layer = this._findPlaneForRoot(rootElement).layer;
  615. }
  616. // associate element with <svg>
  617. this._elementRegistry.updateGraphics(rootElement, this._svg, true);
  618. // show root layer
  619. this.showLayer(rootElement.layer);
  620. }
  621. this._rootElement = rootElement;
  622. this._eventBus.fire('root.set', { element: rootElement });
  623. };
  624. // add functionality //////////////////////
  625. Canvas.prototype._ensureValid = function(type, element) {
  626. if (!element.id) {
  627. throw new Error('element must have an id');
  628. }
  629. if (this._elementRegistry.get(element.id)) {
  630. throw new Error('element <' + element.id + '> already exists');
  631. }
  632. const requiredAttrs = REQUIRED_MODEL_ATTRS[type];
  633. const valid = every(requiredAttrs, function(attr) {
  634. return typeof element[attr] !== 'undefined';
  635. });
  636. if (!valid) {
  637. throw new Error(
  638. 'must supply { ' + requiredAttrs.join(', ') + ' } with ' + type);
  639. }
  640. };
  641. Canvas.prototype._setParent = function(element, parent, parentIndex) {
  642. collectionAdd(parent.children, element, parentIndex);
  643. element.parent = parent;
  644. };
  645. /**
  646. * Adds an element to the canvas.
  647. *
  648. * This wires the parent <-> child relationship between the element and
  649. * a explicitly specified parent or an implicit root element.
  650. *
  651. * During add it emits the events
  652. *
  653. * * <{type}.add> (element, parent)
  654. * * <{type}.added> (element, gfx)
  655. *
  656. * Extensions may hook into these events to perform their magic.
  657. *
  658. * @param {string} type
  659. * @param {Object|djs.model.Base} element
  660. * @param {Object|djs.model.Base} [parent]
  661. * @param {number} [parentIndex]
  662. *
  663. * @return {Object|djs.model.Base} the added element
  664. */
  665. Canvas.prototype._addElement = function(type, element, parent, parentIndex) {
  666. parent = parent || this.getRootElement();
  667. const eventBus = this._eventBus,
  668. graphicsFactory = this._graphicsFactory;
  669. this._ensureValid(type, element);
  670. eventBus.fire(type + '.add', { element: element, parent: parent });
  671. this._setParent(element, parent, parentIndex);
  672. // create graphics
  673. const gfx = graphicsFactory.create(type, element, parentIndex);
  674. this._elementRegistry.add(element, gfx);
  675. // update its visual
  676. graphicsFactory.update(type, element, gfx);
  677. eventBus.fire(type + '.added', { element: element, gfx: gfx });
  678. return element;
  679. };
  680. /**
  681. * Adds a shape to the canvas
  682. *
  683. * @param {Object|djs.model.Shape} shape to add to the diagram
  684. * @param {djs.model.Base} [parent]
  685. * @param {number} [parentIndex]
  686. *
  687. * @return {djs.model.Shape} the added shape
  688. */
  689. Canvas.prototype.addShape = function(shape, parent, parentIndex) {
  690. return this._addElement('shape', shape, parent, parentIndex);
  691. };
  692. /**
  693. * Adds a connection to the canvas
  694. *
  695. * @param {Object|djs.model.Connection} connection to add to the diagram
  696. * @param {djs.model.Base} [parent]
  697. * @param {number} [parentIndex]
  698. *
  699. * @return {djs.model.Connection} the added connection
  700. */
  701. Canvas.prototype.addConnection = function(connection, parent, parentIndex) {
  702. return this._addElement('connection', connection, parent, parentIndex);
  703. };
  704. /**
  705. * Internal remove element
  706. */
  707. Canvas.prototype._removeElement = function(element, type) {
  708. const elementRegistry = this._elementRegistry,
  709. graphicsFactory = this._graphicsFactory,
  710. eventBus = this._eventBus;
  711. element = elementRegistry.get(element.id || element);
  712. if (!element) {
  713. // element was removed already
  714. return;
  715. }
  716. eventBus.fire(type + '.remove', { element: element });
  717. graphicsFactory.remove(element);
  718. // unset parent <-> child relationship
  719. collectionRemove(element.parent && element.parent.children, element);
  720. element.parent = null;
  721. eventBus.fire(type + '.removed', { element: element });
  722. elementRegistry.remove(element);
  723. return element;
  724. };
  725. /**
  726. * Removes a shape from the canvas
  727. *
  728. * @param {string|djs.model.Shape} shape or shape id to be removed
  729. *
  730. * @return {djs.model.Shape} the removed shape
  731. */
  732. Canvas.prototype.removeShape = function(shape) {
  733. /**
  734. * An event indicating that a shape is about to be removed from the canvas.
  735. *
  736. * @memberOf Canvas
  737. *
  738. * @event shape.remove
  739. * @type {Object}
  740. * @property {djs.model.Shape} element the shape descriptor
  741. * @property {Object} gfx the graphical representation of the shape
  742. */
  743. /**
  744. * An event indicating that a shape has been removed from the canvas.
  745. *
  746. * @memberOf Canvas
  747. *
  748. * @event shape.removed
  749. * @type {Object}
  750. * @property {djs.model.Shape} element the shape descriptor
  751. * @property {Object} gfx the graphical representation of the shape
  752. */
  753. return this._removeElement(shape, 'shape');
  754. };
  755. /**
  756. * Removes a connection from the canvas
  757. *
  758. * @param {string|djs.model.Connection} connection or connection id to be removed
  759. *
  760. * @return {djs.model.Connection} the removed connection
  761. */
  762. Canvas.prototype.removeConnection = function(connection) {
  763. /**
  764. * An event indicating that a connection is about to be removed from the canvas.
  765. *
  766. * @memberOf Canvas
  767. *
  768. * @event connection.remove
  769. * @type {Object}
  770. * @property {djs.model.Connection} element the connection descriptor
  771. * @property {Object} gfx the graphical representation of the connection
  772. */
  773. /**
  774. * An event indicating that a connection has been removed from the canvas.
  775. *
  776. * @memberOf Canvas
  777. *
  778. * @event connection.removed
  779. * @type {Object}
  780. * @property {djs.model.Connection} element the connection descriptor
  781. * @property {Object} gfx the graphical representation of the connection
  782. */
  783. return this._removeElement(connection, 'connection');
  784. };
  785. /**
  786. * Return the graphical object underlaying a certain diagram element
  787. *
  788. * @param {string|djs.model.Base} element descriptor of the element
  789. * @param {boolean} [secondary=false] whether to return the secondary connected element
  790. *
  791. * @return {SVGElement}
  792. */
  793. Canvas.prototype.getGraphics = function(element, secondary) {
  794. return this._elementRegistry.getGraphics(element, secondary);
  795. };
  796. /**
  797. * Perform a viewbox update via a given change function.
  798. *
  799. * @param {Function} changeFn
  800. */
  801. Canvas.prototype._changeViewbox = function(changeFn) {
  802. // notify others of the upcoming viewbox change
  803. this._eventBus.fire('canvas.viewbox.changing');
  804. // perform actual change
  805. changeFn.apply(this);
  806. // reset the cached viewbox so that
  807. // a new get operation on viewbox or zoom
  808. // triggers a viewbox re-computation
  809. this._cachedViewbox = null;
  810. // notify others of the change; this step
  811. // may or may not be debounced
  812. this._viewboxChanged();
  813. };
  814. Canvas.prototype._viewboxChanged = function() {
  815. this._eventBus.fire('canvas.viewbox.changed', { viewbox: this.viewbox() });
  816. };
  817. /**
  818. * Gets or sets the view box of the canvas, i.e. the
  819. * area that is currently displayed.
  820. *
  821. * The getter may return a cached viewbox (if it is currently
  822. * changing). To force a recomputation, pass `false` as the first argument.
  823. *
  824. * @example
  825. *
  826. * canvas.viewbox({ x: 100, y: 100, width: 500, height: 500 })
  827. *
  828. * // sets the visible area of the diagram to (100|100) -> (600|100)
  829. * // and and scales it according to the diagram width
  830. *
  831. * const viewbox = canvas.viewbox(); // pass `false` to force recomputing the box.
  832. *
  833. * console.log(viewbox);
  834. * // {
  835. * // inner: Dimensions,
  836. * // outer: Dimensions,
  837. * // scale,
  838. * // x, y,
  839. * // width, height
  840. * // }
  841. *
  842. * // if the current diagram is zoomed and scrolled, you may reset it to the
  843. * // default zoom via this method, too:
  844. *
  845. * const zoomedAndScrolledViewbox = canvas.viewbox();
  846. *
  847. * canvas.viewbox({
  848. * x: 0,
  849. * y: 0,
  850. * width: zoomedAndScrolledViewbox.outer.width,
  851. * height: zoomedAndScrolledViewbox.outer.height
  852. * });
  853. *
  854. * @param {Object} [box] the new view box to set
  855. * @param {number} box.x the top left X coordinate of the canvas visible in view box
  856. * @param {number} box.y the top left Y coordinate of the canvas visible in view box
  857. * @param {number} box.width the visible width
  858. * @param {number} box.height
  859. *
  860. * @return {Object} the current view box
  861. */
  862. Canvas.prototype.viewbox = function(box) {
  863. if (box === undefined && this._cachedViewbox) {
  864. return this._cachedViewbox;
  865. }
  866. const viewport = this._viewport,
  867. outerBox = this.getSize();
  868. let innerBox,
  869. matrix,
  870. activeLayer,
  871. transform,
  872. scale,
  873. x, y;
  874. if (!box) {
  875. // compute the inner box based on the
  876. // diagrams active layer. This allows us to exclude
  877. // external components, such as overlays
  878. activeLayer = this._rootElement ? this.getActiveLayer() : null;
  879. innerBox = activeLayer && activeLayer.getBBox() || {};
  880. transform = svgTransform(viewport);
  881. matrix = transform ? transform.matrix : createMatrix();
  882. scale = round(matrix.a, 1000);
  883. x = round(-matrix.e || 0, 1000);
  884. y = round(-matrix.f || 0, 1000);
  885. box = this._cachedViewbox = {
  886. x: x ? x / scale : 0,
  887. y: y ? y / scale : 0,
  888. width: outerBox.width / scale,
  889. height: outerBox.height / scale,
  890. scale: scale,
  891. inner: {
  892. width: innerBox.width || 0,
  893. height: innerBox.height || 0,
  894. x: innerBox.x || 0,
  895. y: innerBox.y || 0
  896. },
  897. outer: outerBox
  898. };
  899. return box;
  900. } else {
  901. this._changeViewbox(function() {
  902. scale = Math.min(outerBox.width / box.width, outerBox.height / box.height);
  903. const matrix = this._svg.createSVGMatrix()
  904. .scale(scale)
  905. .translate(-box.x, -box.y);
  906. svgTransform(viewport, matrix);
  907. });
  908. }
  909. return box;
  910. };
  911. /**
  912. * Gets or sets the scroll of the canvas.
  913. *
  914. * @param {Object} [delta] the new scroll to apply.
  915. *
  916. * @param {number} [delta.dx]
  917. * @param {number} [delta.dy]
  918. */
  919. Canvas.prototype.scroll = function(delta) {
  920. const node = this._viewport;
  921. let matrix = node.getCTM();
  922. if (delta) {
  923. this._changeViewbox(function() {
  924. delta = assign({ dx: 0, dy: 0 }, delta || {});
  925. matrix = this._svg.createSVGMatrix().translate(delta.dx, delta.dy).multiply(matrix);
  926. setCTM(node, matrix);
  927. });
  928. }
  929. return { x: matrix.e, y: matrix.f };
  930. };
  931. /**
  932. * Scrolls the viewbox to contain the given element.
  933. * Optionally specify a padding to be applied to the edges.
  934. *
  935. * @param {Object|String} [element] the element to scroll to.
  936. * @param {Object|Number} [padding=100] the padding to be applied. Can also specify top, bottom, left and right.
  937. *
  938. */
  939. Canvas.prototype.scrollToElement = function(element, padding) {
  940. let defaultPadding = 100;
  941. if (typeof element === 'string') {
  942. element = this._elementRegistry.get(element);
  943. }
  944. // set to correct rootElement
  945. const rootElement = this.findRoot(element);
  946. if (rootElement !== this.getRootElement()) {
  947. this.setRootElement(rootElement);
  948. }
  949. if (!padding) {
  950. padding = {};
  951. }
  952. if (typeof padding === 'number') {
  953. defaultPadding = padding;
  954. }
  955. padding = {
  956. top: padding.top || defaultPadding,
  957. right: padding.right || defaultPadding,
  958. bottom: padding.bottom || defaultPadding,
  959. left: padding.left || defaultPadding
  960. };
  961. const elementBounds = getBoundingBox(element),
  962. elementTrbl = asTRBL(elementBounds),
  963. viewboxBounds = this.viewbox(),
  964. zoom = this.zoom();
  965. let dx, dy;
  966. // shrink viewboxBounds with padding
  967. viewboxBounds.y += padding.top / zoom;
  968. viewboxBounds.x += padding.left / zoom;
  969. viewboxBounds.width -= (padding.right + padding.left) / zoom;
  970. viewboxBounds.height -= (padding.bottom + padding.top) / zoom;
  971. const viewboxTrbl = asTRBL(viewboxBounds);
  972. const canFit = elementBounds.width < viewboxBounds.width && elementBounds.height < viewboxBounds.height;
  973. if (!canFit) {
  974. // top-left when element can't fit
  975. dx = elementBounds.x - viewboxBounds.x;
  976. dy = elementBounds.y - viewboxBounds.y;
  977. } else {
  978. const dRight = Math.max(0, elementTrbl.right - viewboxTrbl.right),
  979. dLeft = Math.min(0, elementTrbl.left - viewboxTrbl.left),
  980. dBottom = Math.max(0, elementTrbl.bottom - viewboxTrbl.bottom),
  981. dTop = Math.min(0, elementTrbl.top - viewboxTrbl.top);
  982. dx = dRight || dLeft;
  983. dy = dBottom || dTop;
  984. }
  985. this.scroll({ dx: -dx * zoom, dy: -dy * zoom });
  986. };
  987. /**
  988. * Gets or sets the current zoom of the canvas, optionally zooming
  989. * to the specified position.
  990. *
  991. * The getter may return a cached zoom level. Call it with `false` as
  992. * the first argument to force recomputation of the current level.
  993. *
  994. * @param {string|number} [newScale] the new zoom level, either a number, i.e. 0.9,
  995. * or `fit-viewport` to adjust the size to fit the current viewport
  996. * @param {string|Point} [center] the reference point { x: .., y: ..} to zoom to, 'auto' to zoom into mid or null
  997. *
  998. * @return {number} the current scale
  999. */
  1000. Canvas.prototype.zoom = function(newScale, center) {
  1001. if (!newScale) {
  1002. return this.viewbox(newScale).scale;
  1003. }
  1004. if (newScale === 'fit-viewport') {
  1005. return this._fitViewport(center);
  1006. }
  1007. let outer,
  1008. matrix;
  1009. this._changeViewbox(function() {
  1010. if (typeof center !== 'object') {
  1011. outer = this.viewbox().outer;
  1012. center = {
  1013. x: outer.width / 2,
  1014. y: outer.height / 2
  1015. };
  1016. }
  1017. matrix = this._setZoom(newScale, center);
  1018. });
  1019. return round(matrix.a, 1000);
  1020. };
  1021. function setCTM(node, m) {
  1022. const mstr = 'matrix(' + m.a + ',' + m.b + ',' + m.c + ',' + m.d + ',' + m.e + ',' + m.f + ')';
  1023. node.setAttribute('transform', mstr);
  1024. }
  1025. Canvas.prototype._fitViewport = function(center) {
  1026. const vbox = this.viewbox(),
  1027. outer = vbox.outer,
  1028. inner = vbox.inner;
  1029. let newScale,
  1030. newViewbox;
  1031. // display the complete diagram without zooming in.
  1032. // instead of relying on internal zoom, we perform a
  1033. // hard reset on the canvas viewbox to realize this
  1034. //
  1035. // if diagram does not need to be zoomed in, we focus it around
  1036. // the diagram origin instead
  1037. if (inner.x >= 0 &&
  1038. inner.y >= 0 &&
  1039. inner.x + inner.width <= outer.width &&
  1040. inner.y + inner.height <= outer.height &&
  1041. !center) {
  1042. newViewbox = {
  1043. x: 0,
  1044. y: 0,
  1045. width: Math.max(inner.width + inner.x, outer.width),
  1046. height: Math.max(inner.height + inner.y, outer.height)
  1047. };
  1048. } else {
  1049. newScale = Math.min(1, outer.width / inner.width, outer.height / inner.height);
  1050. newViewbox = {
  1051. x: inner.x + (center ? inner.width / 2 - outer.width / newScale / 2 : 0),
  1052. y: inner.y + (center ? inner.height / 2 - outer.height / newScale / 2 : 0),
  1053. width: outer.width / newScale,
  1054. height: outer.height / newScale
  1055. };
  1056. }
  1057. this.viewbox(newViewbox);
  1058. return this.viewbox(false).scale;
  1059. };
  1060. Canvas.prototype._setZoom = function(scale, center) {
  1061. const svg = this._svg,
  1062. viewport = this._viewport;
  1063. const matrix = svg.createSVGMatrix();
  1064. const point = svg.createSVGPoint();
  1065. let centerPoint,
  1066. originalPoint,
  1067. currentMatrix,
  1068. scaleMatrix,
  1069. newMatrix;
  1070. currentMatrix = viewport.getCTM();
  1071. const currentScale = currentMatrix.a;
  1072. if (center) {
  1073. centerPoint = assign(point, center);
  1074. // revert applied viewport transformations
  1075. originalPoint = centerPoint.matrixTransform(currentMatrix.inverse());
  1076. // create scale matrix
  1077. scaleMatrix = matrix
  1078. .translate(originalPoint.x, originalPoint.y)
  1079. .scale(1 / currentScale * scale)
  1080. .translate(-originalPoint.x, -originalPoint.y);
  1081. newMatrix = currentMatrix.multiply(scaleMatrix);
  1082. } else {
  1083. newMatrix = matrix.scale(scale);
  1084. }
  1085. setCTM(this._viewport, newMatrix);
  1086. return newMatrix;
  1087. };
  1088. /**
  1089. * Returns the size of the canvas
  1090. *
  1091. * @return {Dimensions}
  1092. */
  1093. Canvas.prototype.getSize = function() {
  1094. return {
  1095. width: this._container.clientWidth,
  1096. height: this._container.clientHeight
  1097. };
  1098. };
  1099. /**
  1100. * Return the absolute bounding box for the given element
  1101. *
  1102. * The absolute bounding box may be used to display overlays in the
  1103. * callers (browser) coordinate system rather than the zoomed in/out
  1104. * canvas coordinates.
  1105. *
  1106. * @param {ElementDescriptor} element
  1107. * @return {Bounds} the absolute bounding box
  1108. */
  1109. Canvas.prototype.getAbsoluteBBox = function(element) {
  1110. const vbox = this.viewbox();
  1111. let bbox;
  1112. // connection
  1113. // use svg bbox
  1114. if (element.waypoints) {
  1115. const gfx = this.getGraphics(element);
  1116. bbox = gfx.getBBox();
  1117. }
  1118. // shapes
  1119. // use data
  1120. else {
  1121. bbox = element;
  1122. }
  1123. const x = bbox.x * vbox.scale - vbox.x * vbox.scale;
  1124. const y = bbox.y * vbox.scale - vbox.y * vbox.scale;
  1125. const width = bbox.width * vbox.scale;
  1126. const height = bbox.height * vbox.scale;
  1127. return {
  1128. x: x,
  1129. y: y,
  1130. width: width,
  1131. height: height
  1132. };
  1133. };
  1134. /**
  1135. * Fires an event in order other modules can react to the
  1136. * canvas resizing
  1137. */
  1138. Canvas.prototype.resized = function() {
  1139. // force recomputation of view box
  1140. delete this._cachedViewbox;
  1141. this._eventBus.fire('canvas.resized');
  1142. };