fixed unit[s] typo in svgedit.units.convertUnit, added the corresponding test

git-svn-id: http://svg-edit.googlecode.com/svn/trunk@2382 eee81c28-f429-11dd-99c0-75d572ba1ddd
This commit is contained in:
Bruno Heridet
2013-02-14 12:18:13 +00:00
parent 7f560c0ed1
commit 5e68aefef8
2 changed files with 94 additions and 82 deletions

View File

@@ -18,10 +18,10 @@ if (!svgedit.units) {
svgedit.units = {}; svgedit.units = {};
} }
var w_attrs = ['x', 'x1', 'cx', 'rx', 'width']; var wAttrs = ['x', 'x1', 'cx', 'rx', 'width'];
var h_attrs = ['y', 'y1', 'cy', 'ry', 'height']; var hAttrs = ['y', 'y1', 'cy', 'ry', 'height'];
var unit_attrs = $.merge(['r','radius'], w_attrs); var unitAttrs = ['r','radius'].concat(wAttrs, hAttrs);
// unused
var unitNumMap = { var unitNumMap = {
'%': 2, '%': 2,
'em': 3, 'em': 3,
@@ -34,15 +34,13 @@ var unitNumMap = {
'pc': 10 'pc': 10
}; };
$.merge(unit_attrs, h_attrs);
// Container of elements. // Container of elements.
var elementContainer_; var elementContainer_;
/** /**
* Stores mapping of unit type to user coordinates. * Stores mapping of unit type to user coordinates.
*/ */
var typeMap_ = {px: 1}; var typeMap_ = {};
/** /**
* ElementContainer interface * ElementContainer interface
@@ -78,14 +76,17 @@ svgedit.units.init = function(elementContainer) {
document.body.removeChild(svg); document.body.removeChild(svg);
var inch = bb.x; var inch = bb.x;
typeMap_['em'] = bb.width; typeMap_ = {
typeMap_['ex'] = bb.height; 'em': bb.width,
typeMap_['in'] = inch; 'ex': bb.height,
typeMap_['cm'] = inch / 2.54; 'in': inch,
typeMap_['mm'] = inch / 25.4; 'cm': inch / 2.54,
typeMap_['pt'] = inch / 72; 'mm': inch / 25.4,
typeMap_['pc'] = inch / 6; 'pt': inch / 72,
typeMap_['%'] = 0; 'pc': inch / 6,
'px': 1,
'%': 0
};
}; };
// Group: Unit conversion functions // Group: Unit conversion functions
@@ -99,7 +100,7 @@ svgedit.units.getTypeMap = function() {
// Function: svgedit.units.shortFloat // Function: svgedit.units.shortFloat
// Rounds a given value to a float with number of digits defined in save_options // Rounds a given value to a float with number of digits defined in save_options
// //
// Parameters: // Parameters:
// val - The value as a String, Number or Array of two numbers to be rounded // val - The value as a String, Number or Array of two numbers to be rounded
// //
// Returns: // Returns:
@@ -107,10 +108,11 @@ svgedit.units.getTypeMap = function() {
// with comma-seperated floats // with comma-seperated floats
svgedit.units.shortFloat = function(val) { svgedit.units.shortFloat = function(val) {
var digits = elementContainer_.getRoundDigits(); var digits = elementContainer_.getRoundDigits();
if(!isNaN(val)) { if (!isNaN(val)) {
// Note that + converts to Number // Note that + converts to Number
return +((+val).toFixed(digits)); return +((+val).toFixed(digits));
} else if($.isArray(val)) { }
if ($.isArray(val)) {
return svgedit.units.shortFloat(val[0]) + ',' + svgedit.units.shortFloat(val[1]); return svgedit.units.shortFloat(val[0]) + ',' + svgedit.units.shortFloat(val[1]);
} }
return parseFloat(val).toFixed(digits) - 0; return parseFloat(val).toFixed(digits) - 0;
@@ -123,45 +125,45 @@ svgedit.units.convertUnit = function(val, unit) {
// baseVal.convertToSpecifiedUnits(unitNumMap[unit]); // baseVal.convertToSpecifiedUnits(unitNumMap[unit]);
// var val = baseVal.valueInSpecifiedUnits; // var val = baseVal.valueInSpecifiedUnits;
// baseVal.convertToSpecifiedUnits(1); // baseVal.convertToSpecifiedUnits(1);
return svgedit.unit.shortFloat(val / typeMap_[unit]); return svgedit.units.shortFloat(val / typeMap_[unit]);
}; };
// Function: svgedit.units.setUnitAttr // Function: svgedit.units.setUnitAttr
// Sets an element's attribute based on the unit in its current value. // Sets an element's attribute based on the unit in its current value.
// //
// Parameters: // Parameters:
// elem - DOM element to be changed // elem - DOM element to be changed
// attr - String with the name of the attribute associated with the value // attr - String with the name of the attribute associated with the value
// val - String with the attribute value to convert // val - String with the attribute value to convert
svgedit.units.setUnitAttr = function(elem, attr, val) { svgedit.units.setUnitAttr = function(elem, attr, val) {
if(!isNaN(val)) { if (!isNaN(val)) {
// New value is a number, so check currently used unit // New value is a number, so check currently used unit
var old_val = elem.getAttribute(attr); // var old_val = elem.getAttribute(attr);
// Enable this for alternate mode // Enable this for alternate mode
// if(old_val !== null && (isNaN(old_val) || elementContainer_.getBaseUnit() !== 'px')) { // if (old_val !== null && (isNaN(old_val) || elementContainer_.getBaseUnit() !== 'px')) {
// // Old value was a number, so get unit, then convert // // Old value was a number, so get unit, then convert
// var unit; // var unit;
// if(old_val.substr(-1) === '%') { // if (old_val.substr(-1) === '%') {
// var res = getResolution(); // var res = getResolution();
// unit = '%'; // unit = '%';
// val *= 100; // val *= 100;
// if(w_attrs.indexOf(attr) >= 0) { // if (wAttrs.indexOf(attr) >= 0) {
// val = val / res.w; // val = val / res.w;
// } else if(h_attrs.indexOf(attr) >= 0) { // } else if (hAttrs.indexOf(attr) >= 0) {
// val = val / res.h; // val = val / res.h;
// } else { // } else {
// return val / Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2); // return val / Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2);
// } // }
// } else { // } else {
// if(elementContainer_.getBaseUnit() !== 'px') { // if (elementContainer_.getBaseUnit() !== 'px') {
// unit = elementContainer_.getBaseUnit(); // unit = elementContainer_.getBaseUnit();
// } else { // } else {
// unit = old_val.substr(-2); // unit = old_val.substr(-2);
// } // }
// val = val / typeMap_[unit]; // val = val / typeMap_[unit];
// } // }
// //
// val += unit; // val += unit;
// } // }
} }
@@ -188,13 +190,14 @@ svgedit.units.convertAttrs = function(element) {
var elName = element.tagName; var elName = element.tagName;
var unit = elementContainer_.getBaseUnit(); var unit = elementContainer_.getBaseUnit();
var attrs = attrsToConvert[elName]; var attrs = attrsToConvert[elName];
if(!attrs) return; if (!attrs) return;
var len = attrs.length
for(var i = 0; i < len; i++) { var len = attrs.length;
for (var i = 0; i < len; i++) {
var attr = attrs[i]; var attr = attrs[i];
var cur = element.getAttribute(attr); var cur = element.getAttribute(attr);
if(cur) { if (cur) {
if(!isNaN(cur)) { if (!isNaN(cur)) {
element.setAttribute(attr, (cur / typeMap_[unit]) + unit); element.setAttribute(attr, (cur / typeMap_[unit]) + unit);
} else { } else {
// Convert existing? // Convert existing?
@@ -212,17 +215,17 @@ svgedit.units.convertAttrs = function(element) {
// val - String with the attribute value to convert // val - String with the attribute value to convert
svgedit.units.convertToNum = function(attr, val) { svgedit.units.convertToNum = function(attr, val) {
// Return a number if that's what it already is // Return a number if that's what it already is
if(!isNaN(val)) return val-0; if (!isNaN(val)) return val-0;
if(val.substr(-1) === '%') { if (val.substr(-1) === '%') {
// Deal with percentage, depends on attribute // Deal with percentage, depends on attribute
var num = val.substr(0, val.length-1)/100; var num = val.substr(0, val.length-1)/100;
var width = elementContainer_.getWidth(); var width = elementContainer_.getWidth();
var height = elementContainer_.getHeight(); var height = elementContainer_.getHeight();
if(w_attrs.indexOf(attr) >= 0) { if (wAttrs.indexOf(attr) >= 0) {
return num * width; return num * width;
} else if(h_attrs.indexOf(attr) >= 0) { } else if (hAttrs.indexOf(attr) >= 0) {
return num * height; return num * height;
} else { } else {
return num * Math.sqrt((width*width) + (height*height))/Math.sqrt(2); return num * Math.sqrt((width*width) + (height*height))/Math.sqrt(2);
@@ -238,22 +241,22 @@ svgedit.units.convertToNum = function(attr, val) {
// Function: svgedit.units.isValidUnit // Function: svgedit.units.isValidUnit
// Check if an attribute's value is in a valid format // Check if an attribute's value is in a valid format
// //
// Parameters: // Parameters:
// attr - String with the name of the attribute associated with the value // attr - String with the name of the attribute associated with the value
// val - String with the attribute value to check // val - String with the attribute value to check
svgedit.units.isValidUnit = function(attr, val, selectedElement) { svgedit.units.isValidUnit = function(attr, val, selectedElement) {
var valid = false; var valid = false;
if(unit_attrs.indexOf(attr) >= 0) { if (unitAttrs.indexOf(attr) >= 0) {
// True if it's just a number // True if it's just a number
if(!isNaN(val)) { if (!isNaN(val)) {
valid = true; valid = true;
} else { } else {
// Not a number, check if it has a valid unit // Not a number, check if it has a valid unit
val = val.toLowerCase(); val = val.toLowerCase();
$.each(typeMap_, function(unit) { $.each(typeMap_, function(unit) {
if(valid) return; if (valid) return;
var re = new RegExp('^-?[\\d\\.]+' + unit + '$'); var re = new RegExp('^-?[\\d\\.]+' + unit + '$');
if(re.test(val)) valid = true; if (re.test(val)) valid = true;
}); });
} }
} else if (attr == "id") { } else if (attr == "id") {
@@ -273,9 +276,8 @@ svgedit.units.isValidUnit = function(attr, val, selectedElement) {
} else { } else {
valid = true; valid = true;
} }
return valid; return valid;
}; };
})(); })();

View File

@@ -1,29 +1,29 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<link rel='stylesheet' href='qunit/qunit.css' type='text/css'/> <link rel='stylesheet' href='qunit/qunit.css' type='text/css'/>
<script type='text/javascript' src='../editor/jquery.js'></script> <script type='text/javascript' src='../editor/jquery.js'></script>
<script type='text/javascript' src='../editor/units.js'></script> <script type='text/javascript' src='../editor/units.js'></script>
<script type='text/javascript' src='qunit/qunit.js'></script> <script type='text/javascript' src='qunit/qunit.js'></script>
<script type='text/javascript'> <script type='text/javascript'>
$(function() { $(function() {
// log function // log function
QUnit.log = function(result, message) { QUnit.log = function(result, message) {
if (window.console && window.console.log) { if (window.console && window.console.log) {
window.console.log(result +' :: '+ message); window.console.log(result +' :: '+ message);
} }
}; };
function setUp() { function setUp() {
svgedit.units.init({ svgedit.units.init({
getBaseUnit: function() { return "cm"; }, getBaseUnit: function() { return "cm"; },
getHeight: function() { return 600; }, getHeight: function() { return 600; },
getWidth: function() { return 800; }, getWidth: function() { return 800; },
getRoundDigits: function() { return 4; }, getRoundDigits: function() { return 4; },
getElement:function(elementId){ return document.getElementById(elementId);} getElement: function(elementId){ return document.getElementById(elementId); }
}); });
} }
test('Test svgedit.units package', function() { test('Test svgedit.units package', function() {
expect(2); expect(2);
ok(svgedit.units); ok(svgedit.units);
@@ -34,7 +34,7 @@
expect(7); expect(7);
setUp(); setUp();
ok(svgedit.units.shortFloat); ok(svgedit.units.shortFloat);
equals(typeof svgedit.units.shortFloat, typeof function(){}); equals(typeof svgedit.units.shortFloat, typeof function(){});
@@ -50,7 +50,7 @@
expect(18); expect(18);
setUp(); setUp();
ok(svgedit.units.isValidUnit); ok(svgedit.units.isValidUnit);
equals(typeof svgedit.units.isValidUnit, typeof function(){}); equals(typeof svgedit.units.isValidUnit, typeof function(){});
@@ -68,28 +68,38 @@
ok(isValidUnit("-0.ex")); ok(isValidUnit("-0.ex"));
ok(isValidUnit("40.123%")); ok(isValidUnit("40.123%"));
equals(isValidUnit("id","uniqueId",document.getElementById("uniqueId")), true);
equals(isValidUnit("id","uniqueId",document.getElementById("uniqueId")), true); equals(isValidUnit("id","newId",document.getElementById("uniqueId")), true);
equals(isValidUnit("id","newId",document.getElementById("uniqueId")), true); equals(isValidUnit("id","uniqueId"), false);
equals(isValidUnit("id","uniqueId"), false); equals(isValidUnit("id","uniqueId",document.getElementById("nonUniqueId")), false);
equals(isValidUnit("id","uniqueId",document.getElementById("nonUniqueId")), false);
}); });
});
</script>
</head>
<body>
<h1 id='qunit-header'>Unit Tests for units.js</h1>
<h2 id='qunit-banner'></h2>
<h2 id='qunit-userAgent'></h2>
<ol id='qunit-tests'>
</ol>
<div id='anchor' style='visibility:hidden'>
</div>
<div id="elementsContainer">
<div id='uniqueId' style='visibility:hidden'></div>
<div id='nonUniqueId' style='visibility:hidden'></div>
</div>
</div> test('Test svgedit.units.convertUnit()', function() {
</body> expect(4);
setUp();
ok(svgedit.units.convertUnit);
equals(typeof svgedit.units.convertUnit, typeof function(){});
// cm in default setup
equals(svgedit.units.convertUnit(42), 1.1113);
equals(svgedit.units.convertUnit(42, 'px'), 42);
});
});
</script>svgedit.units.convertUnit
</head>
<body>
<h1 id='qunit-header'>Unit Tests for units.js</h1>
<h2 id='qunit-banner'></h2>
<h2 id='qunit-userAgent'></h2>
<ol id='qunit-tests'>
</ol>
<div id='anchor' style='visibility:hidden'>
</div>
<div id="elementsContainer">
<div id='uniqueId' style='visibility:hidden'></div>
<div id='nonUniqueId' style='visibility:hidden'></div>
</div>
</div>
</body>
</html> </html>