draw.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*globals $, svgedit*/
  2. /*jslint vars: true, eqeq: true, todo: true*/
  3. /**
  4. * Package: svgedit.draw
  5. *
  6. * Licensed under the MIT License
  7. *
  8. * Copyright(c) 2011 Jeff Schiller
  9. */
  10. // Dependencies:
  11. // 1) jQuery
  12. // 2) browser.js
  13. // 3) svgutils.js
  14. (function() {'use strict';
  15. if (!svgedit.draw) {
  16. svgedit.draw = {};
  17. }
  18. // alias
  19. var NS = svgedit.NS;
  20. var visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use'.split(',');
  21. var RandomizeModes = {
  22. LET_DOCUMENT_DECIDE: 0,
  23. ALWAYS_RANDOMIZE: 1,
  24. NEVER_RANDOMIZE: 2
  25. };
  26. var randomize_ids = RandomizeModes.LET_DOCUMENT_DECIDE;
  27. /**
  28. * This class encapsulates the concept of a layer in the drawing
  29. * @param {String} name - Layer name
  30. * @param {SVGGElement} child - Layer SVG group.
  31. */
  32. svgedit.draw.Layer = function(name, group) {
  33. this.name_ = name;
  34. this.group_ = group;
  35. };
  36. /**
  37. * @returns {string} The layer name
  38. */
  39. svgedit.draw.Layer.prototype.getName = function() {
  40. return this.name_;
  41. };
  42. /**
  43. * @returns {SVGGElement} The layer SVG group
  44. */
  45. svgedit.draw.Layer.prototype.getGroup = function() {
  46. return this.group_;
  47. };
  48. /**
  49. * Called to ensure that drawings will or will not have randomized ids.
  50. * The currentDrawing will have its nonce set if it doesn't already.
  51. * @param {boolean} enableRandomization - flag indicating if documents should have randomized ids
  52. * @param {svgedit.draw.Drawing} currentDrawing
  53. */
  54. svgedit.draw.randomizeIds = function(enableRandomization, currentDrawing) {
  55. randomize_ids = enableRandomization === false ?
  56. RandomizeModes.NEVER_RANDOMIZE :
  57. RandomizeModes.ALWAYS_RANDOMIZE;
  58. if (randomize_ids == RandomizeModes.ALWAYS_RANDOMIZE && !currentDrawing.getNonce()) {
  59. currentDrawing.setNonce(Math.floor(Math.random() * 100001));
  60. } else if (randomize_ids == RandomizeModes.NEVER_RANDOMIZE && currentDrawing.getNonce()) {
  61. currentDrawing.clearNonce();
  62. }
  63. };
  64. /**
  65. * This class encapsulates the concept of a SVG-edit drawing
  66. * @param {SVGSVGElement} svgElem - The SVG DOM Element that this JS object
  67. * encapsulates. If the svgElem has a se:nonce attribute on it, then
  68. * IDs will use the nonce as they are generated.
  69. * @param {String=svg_} [opt_idPrefix] - The ID prefix to use.
  70. */
  71. svgedit.draw.Drawing = function(svgElem, opt_idPrefix) {
  72. if (!svgElem || !svgElem.tagName || !svgElem.namespaceURI ||
  73. svgElem.tagName != 'svg' || svgElem.namespaceURI != NS.SVG) {
  74. throw "Error: svgedit.draw.Drawing instance initialized without a <svg> element";
  75. }
  76. /**
  77. * The SVG DOM Element that represents this drawing.
  78. * @type {SVGSVGElement}
  79. */
  80. this.svgElem_ = svgElem;
  81. /**
  82. * The latest object number used in this drawing.
  83. * @type {number}
  84. */
  85. this.obj_num = 0;
  86. /**
  87. * The prefix to prepend to each element id in the drawing.
  88. * @type {String}
  89. */
  90. this.idPrefix = opt_idPrefix || "svg_";
  91. /**
  92. * An array of released element ids to immediately reuse.
  93. * @type {Array.<number>}
  94. */
  95. this.releasedNums = [];
  96. /**
  97. * The z-ordered array of tuples containing layer names and <g> elements.
  98. * The first layer is the one at the bottom of the rendering.
  99. * TODO: Turn this into an Array.<Layer>
  100. * @type {Array.<Array.<String, SVGGElement>>}
  101. */
  102. this.all_layers = [];
  103. /**
  104. * The current layer being used.
  105. * TODO: Make this a {Layer}.
  106. * @type {SVGGElement}
  107. */
  108. this.current_layer = null;
  109. /**
  110. * The nonce to use to uniquely identify elements across drawings.
  111. * @type {!String}
  112. */
  113. this.nonce_ = '';
  114. var n = this.svgElem_.getAttributeNS(NS.SE, 'nonce');
  115. // If already set in the DOM, use the nonce throughout the document
  116. // else, if randomizeIds(true) has been called, create and set the nonce.
  117. if (!!n && randomize_ids != RandomizeModes.NEVER_RANDOMIZE) {
  118. this.nonce_ = n;
  119. } else if (randomize_ids == RandomizeModes.ALWAYS_RANDOMIZE) {
  120. this.setNonce(Math.floor(Math.random() * 100001));
  121. }
  122. };
  123. /**
  124. * @param {string} id Element ID to retrieve
  125. * @returns {Element} SVG element within the root SVGSVGElement
  126. */
  127. svgedit.draw.Drawing.prototype.getElem_ = function (id) {
  128. if (this.svgElem_.querySelector) {
  129. // querySelector lookup
  130. return this.svgElem_.querySelector('#' + id);
  131. }
  132. // jQuery lookup: twice as slow as xpath in FF
  133. return $(this.svgElem_).find('[id=' + id + ']')[0];
  134. };
  135. /**
  136. * @returns {SVGSVGElement}
  137. */
  138. svgedit.draw.Drawing.prototype.getSvgElem = function () {
  139. return this.svgElem_;
  140. };
  141. /**
  142. * @returns {!string|number} The previously set nonce
  143. */
  144. svgedit.draw.Drawing.prototype.getNonce = function() {
  145. return this.nonce_;
  146. };
  147. /**
  148. * @param {!string|number} n The nonce to set
  149. */
  150. svgedit.draw.Drawing.prototype.setNonce = function(n) {
  151. this.svgElem_.setAttributeNS(NS.XMLNS, 'xmlns:se', NS.SE);
  152. this.svgElem_.setAttributeNS(NS.SE, 'se:nonce', n);
  153. this.nonce_ = n;
  154. };
  155. /**
  156. * Clears any previously set nonce
  157. */
  158. svgedit.draw.Drawing.prototype.clearNonce = function () {
  159. // We deliberately leave any se:nonce attributes alone,
  160. // we just don't use it to randomize ids.
  161. this.nonce_ = '';
  162. };
  163. /**
  164. * Returns the latest object id as a string.
  165. * @return {String} The latest object Id.
  166. */
  167. svgedit.draw.Drawing.prototype.getId = function () {
  168. return this.nonce_ ?
  169. this.idPrefix + this.nonce_ + '_' + this.obj_num :
  170. this.idPrefix + this.obj_num;
  171. };
  172. /**
  173. * Returns the next object Id as a string.
  174. * @return {String} The next object Id to use.
  175. */
  176. svgedit.draw.Drawing.prototype.getNextId = function () {
  177. var oldObjNum = this.obj_num;
  178. var restoreOldObjNum = false;
  179. // If there are any released numbers in the release stack,
  180. // use the last one instead of the next obj_num.
  181. // We need to temporarily use obj_num as that is what getId() depends on.
  182. if (this.releasedNums.length > 0) {
  183. this.obj_num = this.releasedNums.pop();
  184. restoreOldObjNum = true;
  185. } else {
  186. // If we are not using a released id, then increment the obj_num.
  187. this.obj_num++;
  188. }
  189. // Ensure the ID does not exist.
  190. var id = this.getId();
  191. while (this.getElem_(id)) {
  192. if (restoreOldObjNum) {
  193. this.obj_num = oldObjNum;
  194. restoreOldObjNum = false;
  195. }
  196. this.obj_num++;
  197. id = this.getId();
  198. }
  199. // Restore the old object number if required.
  200. if (restoreOldObjNum) {
  201. this.obj_num = oldObjNum;
  202. }
  203. return id;
  204. };
  205. /**
  206. * Releases the object Id, letting it be used as the next id in getNextId().
  207. * This method DOES NOT remove any elements from the DOM, it is expected
  208. * that client code will do this.
  209. * @param {string} id - The id to release.
  210. * @returns {boolean} True if the id was valid to be released, false otherwise.
  211. */
  212. svgedit.draw.Drawing.prototype.releaseId = function (id) {
  213. // confirm if this is a valid id for this Document, else return false
  214. var front = this.idPrefix + (this.nonce_ ? this.nonce_ + '_' : '');
  215. if (typeof id !== 'string' || id.indexOf(front) !== 0) {
  216. return false;
  217. }
  218. // extract the obj_num of this id
  219. var num = parseInt(id.substr(front.length), 10);
  220. // if we didn't get a positive number or we already released this number
  221. // then return false.
  222. if (typeof num !== 'number' || num <= 0 || this.releasedNums.indexOf(num) != -1) {
  223. return false;
  224. }
  225. // push the released number into the released queue
  226. this.releasedNums.push(num);
  227. return true;
  228. };
  229. /**
  230. * Returns the number of layers in the current drawing.
  231. * @returns {integer} The number of layers in the current drawing.
  232. */
  233. svgedit.draw.Drawing.prototype.getNumLayers = function() {
  234. return this.all_layers.length;
  235. };
  236. /**
  237. * Check if layer with given name already exists
  238. * @param {string} name - The layer name to check
  239. */
  240. svgedit.draw.Drawing.prototype.hasLayer = function (name) {
  241. var i;
  242. for (i = 0; i < this.getNumLayers(); i++) {
  243. if(this.all_layers[i][0] == name) {return true;}
  244. }
  245. return false;
  246. };
  247. /**
  248. * Returns the name of the ith layer. If the index is out of range, an empty string is returned.
  249. * @param {integer} i - The zero-based index of the layer you are querying.
  250. * @returns {string} The name of the ith layer (or the empty string if none found)
  251. */
  252. svgedit.draw.Drawing.prototype.getLayerName = function (i) {
  253. if (i >= 0 && i < this.getNumLayers()) {
  254. return this.all_layers[i][0];
  255. }
  256. return '';
  257. };
  258. /**
  259. * @returns {SVGGElement} The SVGGElement representing the current layer.
  260. */
  261. svgedit.draw.Drawing.prototype.getCurrentLayer = function() {
  262. return this.current_layer;
  263. };
  264. /**
  265. * Returns the name of the currently selected layer. If an error occurs, an empty string
  266. * is returned.
  267. * @returns The name of the currently active layer (or the empty string if none found).
  268. */
  269. svgedit.draw.Drawing.prototype.getCurrentLayerName = function () {
  270. var i;
  271. for (i = 0; i < this.getNumLayers(); ++i) {
  272. if (this.all_layers[i][1] == this.current_layer) {
  273. return this.getLayerName(i);
  274. }
  275. }
  276. return '';
  277. };
  278. /**
  279. * Sets the current layer. If the name is not a valid layer name, then this
  280. * function returns false. Otherwise it returns true. This is not an
  281. * undo-able action.
  282. * @param {string} name - The name of the layer you want to switch to.
  283. * @returns {boolean} true if the current layer was switched, otherwise false
  284. */
  285. svgedit.draw.Drawing.prototype.setCurrentLayer = function(name) {
  286. var i;
  287. for (i = 0; i < this.getNumLayers(); ++i) {
  288. if (name == this.getLayerName(i)) {
  289. if (this.current_layer != this.all_layers[i][1]) {
  290. this.current_layer.setAttribute("style", "pointer-events:none");
  291. this.current_layer = this.all_layers[i][1];
  292. this.current_layer.setAttribute("style", "pointer-events:all");
  293. }
  294. return true;
  295. }
  296. }
  297. return false;
  298. };
  299. /**
  300. * Deletes the current layer from the drawing and then clears the selection.
  301. * This function then calls the 'changed' handler. This is an undoable action.
  302. * @returns {SVGGElement} The SVGGElement of the layer removed or null.
  303. */
  304. svgedit.draw.Drawing.prototype.deleteCurrentLayer = function() {
  305. if (this.current_layer && this.getNumLayers() > 1) {
  306. // actually delete from the DOM and return it
  307. var parent = this.current_layer.parentNode;
  308. var nextSibling = this.current_layer.nextSibling;
  309. var oldLayerGroup = parent.removeChild(this.current_layer);
  310. this.identifyLayers();
  311. return oldLayerGroup;
  312. }
  313. return null;
  314. };
  315. /**
  316. * Updates layer system and sets the current layer to the
  317. * top-most layer (last <g> child of this drawing).
  318. */
  319. svgedit.draw.Drawing.prototype.identifyLayers = function() {
  320. this.all_layers = [];
  321. var numchildren = this.svgElem_.childNodes.length;
  322. // loop through all children of SVG element
  323. var orphans = [], layernames = [];
  324. var a_layer = null;
  325. var childgroups = false;
  326. var i;
  327. for (i = 0; i < numchildren; ++i) {
  328. var child = this.svgElem_.childNodes.item(i);
  329. // for each g, find its layer name
  330. if (child && child.nodeType == 1) {
  331. if (child.tagName == "g") {
  332. childgroups = true;
  333. var name = $("title", child).text();
  334. // Hack for Opera 10.60
  335. if(!name && svgedit.browser.isOpera() && child.querySelectorAll) {
  336. name = $(child.querySelectorAll('title')).text();
  337. }
  338. // store layer and name in global variable
  339. if (name) {
  340. layernames.push(name);
  341. this.all_layers.push( [name, child] );
  342. a_layer = child;
  343. svgedit.utilities.walkTree(child, function(e){e.setAttribute("style", "pointer-events:inherit");});
  344. a_layer.setAttribute("style", "pointer-events:none");
  345. }
  346. // if group did not have a name, it is an orphan
  347. else {
  348. orphans.push(child);
  349. }
  350. }
  351. // if child has is "visible" (i.e. not a <title> or <defs> element), then it is an orphan
  352. else if(~visElems.indexOf(child.nodeName)) {
  353. var bb = svgedit.utilities.getBBox(child);
  354. orphans.push(child);
  355. }
  356. }
  357. }
  358. // create a new layer and add all the orphans to it
  359. var svgdoc = this.svgElem_.ownerDocument;
  360. if (orphans.length > 0 || !childgroups) {
  361. i = 1;
  362. // TODO(codedread): What about internationalization of "Layer"?
  363. while (layernames.indexOf(("Layer " + i)) >= 0) { i++; }
  364. var newname = "Layer " + i;
  365. a_layer = svgdoc.createElementNS(NS.SVG, "g");
  366. var layer_title = svgdoc.createElementNS(NS.SVG, "title");
  367. layer_title.textContent = newname;
  368. a_layer.appendChild(layer_title);
  369. var j;
  370. for (j = 0; j < orphans.length; ++j) {
  371. a_layer.appendChild(orphans[j]);
  372. }
  373. this.svgElem_.appendChild(a_layer);
  374. this.all_layers.push( [newname, a_layer] );
  375. }
  376. svgedit.utilities.walkTree(a_layer, function(e){e.setAttribute("style", "pointer-events:inherit");});
  377. this.current_layer = a_layer;
  378. this.current_layer.setAttribute("style", "pointer-events:all");
  379. };
  380. /**
  381. * Creates a new top-level layer in the drawing with the given name and
  382. * sets the current layer to it.
  383. * @param {string} name - The given name
  384. * @returns {SVGGElement} The SVGGElement of the new layer, which is
  385. * also the current layer of this drawing.
  386. */
  387. svgedit.draw.Drawing.prototype.createLayer = function(name) {
  388. var svgdoc = this.svgElem_.ownerDocument;
  389. var new_layer = svgdoc.createElementNS(NS.SVG, "g");
  390. var layer_title = svgdoc.createElementNS(NS.SVG, "title");
  391. layer_title.textContent = name;
  392. new_layer.appendChild(layer_title);
  393. this.svgElem_.appendChild(new_layer);
  394. this.identifyLayers();
  395. return new_layer;
  396. };
  397. /**
  398. * Returns whether the layer is visible. If the layer name is not valid,
  399. * then this function returns false.
  400. * @param {string} layername - The name of the layer which you want to query.
  401. * @returns {boolean} The visibility state of the layer, or false if the layer name was invalid.
  402. */
  403. svgedit.draw.Drawing.prototype.getLayerVisibility = function(layername) {
  404. // find the layer
  405. var layer = null;
  406. var i;
  407. for (i = 0; i < this.getNumLayers(); ++i) {
  408. if (this.getLayerName(i) == layername) {
  409. layer = this.all_layers[i][1];
  410. break;
  411. }
  412. }
  413. if (!layer) {return false;}
  414. return (layer.getAttribute('display') !== 'none');
  415. };
  416. /**
  417. * Sets the visibility of the layer. If the layer name is not valid, this
  418. * function returns false, otherwise it returns true. This is an
  419. * undo-able action.
  420. * @param {string} layername - The name of the layer to change the visibility
  421. * @param {boolean} bVisible - Whether the layer should be visible
  422. * @returns {?SVGGElement} The SVGGElement representing the layer if the
  423. * layername was valid, otherwise null.
  424. */
  425. svgedit.draw.Drawing.prototype.setLayerVisibility = function(layername, bVisible) {
  426. if (typeof bVisible !== 'boolean') {
  427. return null;
  428. }
  429. // find the layer
  430. var layer = null;
  431. var i;
  432. for (i = 0; i < this.getNumLayers(); ++i) {
  433. if (this.getLayerName(i) == layername) {
  434. layer = this.all_layers[i][1];
  435. break;
  436. }
  437. }
  438. if (!layer) {return null;}
  439. var oldDisplay = layer.getAttribute("display");
  440. if (!oldDisplay) {oldDisplay = "inline";}
  441. layer.setAttribute("display", bVisible ? "inline" : "none");
  442. return layer;
  443. };
  444. /**
  445. * Returns the opacity of the given layer. If the input name is not a layer, null is returned.
  446. * @param {string} layername - name of the layer on which to get the opacity
  447. * @returns {?number} The opacity value of the given layer. This will be a value between 0.0 and 1.0, or null
  448. * if layername is not a valid layer
  449. */
  450. svgedit.draw.Drawing.prototype.getLayerOpacity = function(layername) {
  451. var i;
  452. for (i = 0; i < this.getNumLayers(); ++i) {
  453. if (this.getLayerName(i) == layername) {
  454. var g = this.all_layers[i][1];
  455. var opacity = g.getAttribute('opacity');
  456. if (!opacity) {
  457. opacity = '1.0';
  458. }
  459. return parseFloat(opacity);
  460. }
  461. }
  462. return null;
  463. };
  464. /**
  465. * Sets the opacity of the given layer. If the input name is not a layer,
  466. * nothing happens. If opacity is not a value between 0.0 and 1.0, then
  467. * nothing happens.
  468. * @param {string} layername - Name of the layer on which to set the opacity
  469. * @param {number} opacity - A float value in the range 0.0-1.0
  470. */
  471. svgedit.draw.Drawing.prototype.setLayerOpacity = function(layername, opacity) {
  472. if (typeof opacity !== 'number' || opacity < 0.0 || opacity > 1.0) {
  473. return;
  474. }
  475. var i;
  476. for (i = 0; i < this.getNumLayers(); ++i) {
  477. if (this.getLayerName(i) == layername) {
  478. var g = this.all_layers[i][1];
  479. g.setAttribute("opacity", opacity);
  480. break;
  481. }
  482. }
  483. };
  484. }());