units.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /*globals $, svgedit*/
  2. /*jslint vars: true, eqeq: true*/
  3. /**
  4. * Package: svgedit.units
  5. *
  6. * Licensed under the MIT License
  7. *
  8. * Copyright(c) 2010 Alexis Deveria
  9. * Copyright(c) 2010 Jeff Schiller
  10. */
  11. // Dependencies:
  12. // 1) jQuery
  13. (function() {'use strict';
  14. if (!svgedit.units) {
  15. svgedit.units = {};
  16. }
  17. var NS = svgedit.NS;
  18. var wAttrs = ['x', 'x1', 'cx', 'rx', 'width'];
  19. var hAttrs = ['y', 'y1', 'cy', 'ry', 'height'];
  20. var unitAttrs = ['r', 'radius'].concat(wAttrs, hAttrs);
  21. // unused
  22. var unitNumMap = {
  23. '%': 2,
  24. 'em': 3,
  25. 'ex': 4,
  26. 'px': 5,
  27. 'cm': 6,
  28. 'mm': 7,
  29. 'in': 8,
  30. 'pt': 9,
  31. 'pc': 10
  32. };
  33. // Container of elements.
  34. var elementContainer_;
  35. /**
  36. * Stores mapping of unit type to user coordinates.
  37. */
  38. var typeMap_ = {};
  39. /**
  40. * ElementContainer interface
  41. *
  42. * function getBaseUnit() - returns a string of the base unit type of the container ('em')
  43. * function getElement() - returns an element in the container given an id
  44. * function getHeight() - returns the container's height
  45. * function getWidth() - returns the container's width
  46. * function getRoundDigits() - returns the number of digits number should be rounded to
  47. */
  48. /**
  49. * Function: svgedit.units.init()
  50. * Initializes this module.
  51. *
  52. * Parameters:
  53. * elementContainer - an object implementing the ElementContainer interface.
  54. */
  55. svgedit.units.init = function(elementContainer) {
  56. elementContainer_ = elementContainer;
  57. // Get correct em/ex values by creating a temporary SVG.
  58. var svg = document.createElementNS(NS.SVG, 'svg');
  59. document.body.appendChild(svg);
  60. var rect = document.createElementNS(NS.SVG, 'rect');
  61. rect.setAttribute('width', '1em');
  62. rect.setAttribute('height', '1ex');
  63. rect.setAttribute('x', '1in');
  64. svg.appendChild(rect);
  65. var bb = rect.getBBox();
  66. document.body.removeChild(svg);
  67. var inch = bb.x;
  68. typeMap_ = {
  69. 'em': bb.width,
  70. 'ex': bb.height,
  71. 'in': inch,
  72. 'cm': inch / 2.54,
  73. 'mm': inch / 25.4,
  74. 'pt': inch / 72,
  75. 'pc': inch / 6,
  76. 'px': 1,
  77. '%': 0
  78. };
  79. };
  80. // Group: Unit conversion functions
  81. // Function: svgedit.units.getTypeMap
  82. // Returns the unit object with values for each unit
  83. svgedit.units.getTypeMap = function() {
  84. return typeMap_;
  85. };
  86. // Function: svgedit.units.shortFloat
  87. // Rounds a given value to a float with number of digits defined in save_options
  88. //
  89. // Parameters:
  90. // val - The value as a String, Number or Array of two numbers to be rounded
  91. //
  92. // Returns:
  93. // If a string/number was given, returns a Float. If an array, return a string
  94. // with comma-seperated floats
  95. svgedit.units.shortFloat = function(val) {
  96. var digits = elementContainer_.getRoundDigits();
  97. if (!isNaN(val)) {
  98. // Note that + converts to Number
  99. return +((+val).toFixed(digits));
  100. }
  101. if ($.isArray(val)) {
  102. return svgedit.units.shortFloat(val[0]) + ',' + svgedit.units.shortFloat(val[1]);
  103. }
  104. return parseFloat(val).toFixed(digits) - 0;
  105. };
  106. // Function: svgedit.units.convertUnit
  107. // Converts the number to given unit or baseUnit
  108. svgedit.units.convertUnit = function(val, unit) {
  109. unit = unit || elementContainer_.getBaseUnit();
  110. // baseVal.convertToSpecifiedUnits(unitNumMap[unit]);
  111. // var val = baseVal.valueInSpecifiedUnits;
  112. // baseVal.convertToSpecifiedUnits(1);
  113. return svgedit.units.shortFloat(val / typeMap_[unit]);
  114. };
  115. // Function: svgedit.units.setUnitAttr
  116. // Sets an element's attribute based on the unit in its current value.
  117. //
  118. // Parameters:
  119. // elem - DOM element to be changed
  120. // attr - String with the name of the attribute associated with the value
  121. // val - String with the attribute value to convert
  122. svgedit.units.setUnitAttr = function(elem, attr, val) {
  123. // if (!isNaN(val)) {
  124. // New value is a number, so check currently used unit
  125. // var old_val = elem.getAttribute(attr);
  126. // Enable this for alternate mode
  127. // if (old_val !== null && (isNaN(old_val) || elementContainer_.getBaseUnit() !== 'px')) {
  128. // // Old value was a number, so get unit, then convert
  129. // var unit;
  130. // if (old_val.substr(-1) === '%') {
  131. // var res = getResolution();
  132. // unit = '%';
  133. // val *= 100;
  134. // if (wAttrs.indexOf(attr) >= 0) {
  135. // val = val / res.w;
  136. // } else if (hAttrs.indexOf(attr) >= 0) {
  137. // val = val / res.h;
  138. // } else {
  139. // return val / Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2);
  140. // }
  141. // } else {
  142. // if (elementContainer_.getBaseUnit() !== 'px') {
  143. // unit = elementContainer_.getBaseUnit();
  144. // } else {
  145. // unit = old_val.substr(-2);
  146. // }
  147. // val = val / typeMap_[unit];
  148. // }
  149. //
  150. // val += unit;
  151. // }
  152. // }
  153. elem.setAttribute(attr, val);
  154. };
  155. var attrsToConvert = {
  156. 'line': ['x1', 'x2', 'y1', 'y2'],
  157. 'circle': ['cx', 'cy', 'r'],
  158. 'ellipse': ['cx', 'cy', 'rx', 'ry'],
  159. 'foreignObject': ['x', 'y', 'width', 'height'],
  160. 'rect': ['x', 'y', 'width', 'height'],
  161. 'image': ['x', 'y', 'width', 'height'],
  162. 'use': ['x', 'y', 'width', 'height'],
  163. 'text': ['x', 'y']
  164. };
  165. // Function: svgedit.units.convertAttrs
  166. // Converts all applicable attributes to the configured baseUnit
  167. //
  168. // Parameters:
  169. // element - a DOM element whose attributes should be converted
  170. svgedit.units.convertAttrs = function(element) {
  171. var elName = element.tagName;
  172. var unit = elementContainer_.getBaseUnit();
  173. var attrs = attrsToConvert[elName];
  174. if (!attrs) {return;}
  175. var len = attrs.length;
  176. var i;
  177. for (i = 0; i < len; i++) {
  178. var attr = attrs[i];
  179. var cur = element.getAttribute(attr);
  180. if (cur) {
  181. if (!isNaN(cur)) {
  182. element.setAttribute(attr, (cur / typeMap_[unit]) + unit);
  183. }
  184. // else {
  185. // Convert existing?
  186. // }
  187. }
  188. }
  189. };
  190. // Function: svgedit.units.convertToNum
  191. // Converts given values to numbers. Attributes must be supplied in
  192. // case a percentage is given
  193. //
  194. // Parameters:
  195. // attr - String with the name of the attribute associated with the value
  196. // val - String with the attribute value to convert
  197. svgedit.units.convertToNum = function(attr, val) {
  198. // Return a number if that's what it already is
  199. if (!isNaN(val)) {return val-0;}
  200. var num;
  201. if (val.substr(-1) === '%') {
  202. // Deal with percentage, depends on attribute
  203. num = val.substr(0, val.length-1)/100;
  204. var width = elementContainer_.getWidth();
  205. var height = elementContainer_.getHeight();
  206. if (wAttrs.indexOf(attr) >= 0) {
  207. return num * width;
  208. }
  209. if (hAttrs.indexOf(attr) >= 0) {
  210. return num * height;
  211. }
  212. return num * Math.sqrt((width*width) + (height*height))/Math.sqrt(2);
  213. }
  214. var unit = val.substr(-2);
  215. num = val.substr(0, val.length-2);
  216. // Note that this multiplication turns the string into a number
  217. return num * typeMap_[unit];
  218. };
  219. // Function: svgedit.units.isValidUnit
  220. // Check if an attribute's value is in a valid format
  221. //
  222. // Parameters:
  223. // attr - String with the name of the attribute associated with the value
  224. // val - String with the attribute value to check
  225. svgedit.units.isValidUnit = function(attr, val, selectedElement) {
  226. var valid = false;
  227. if (unitAttrs.indexOf(attr) >= 0) {
  228. // True if it's just a number
  229. if (!isNaN(val)) {
  230. valid = true;
  231. } else {
  232. // Not a number, check if it has a valid unit
  233. val = val.toLowerCase();
  234. $.each(typeMap_, function(unit) {
  235. if (valid) {return;}
  236. var re = new RegExp('^-?[\\d\\.]+' + unit + '$');
  237. if (re.test(val)) {valid = true;}
  238. });
  239. }
  240. } else if (attr == 'id') {
  241. // if we're trying to change the id, make sure it's not already present in the doc
  242. // and the id value is valid.
  243. var result = false;
  244. // because getElem() can throw an exception in the case of an invalid id
  245. // (according to http://www.w3.org/TR/xml-id/ IDs must be a NCName)
  246. // we wrap it in an exception and only return true if the ID was valid and
  247. // not already present
  248. try {
  249. var elem = elementContainer_.getElement(val);
  250. result = (elem == null || elem === selectedElement);
  251. } catch(e) {}
  252. return result;
  253. }
  254. valid = true;
  255. return valid;
  256. };
  257. }());