Refactor physical unit support

This commit is contained in:
Tom MacWright 2013-04-15 15:59:17 -04:00
parent 207b120dee
commit c21a763dc7

View File

@ -11,49 +11,37 @@ tree.Dimension = function Dimension(value, unit, index) {
tree.Dimension.prototype = {
is: 'float',
physical_units: ['m', 'cm', 'in', 'mm', 'pt', 'pc'],
screen_units: ['px', '%'],
all_units: ['m', 'cm', 'in', 'mm', 'pt', 'pc', 'px', '%'],
densities: {
m: 0.0254,
mm: 25.4,
cm: 2.54,
pt: 72,
pc: 6
},
ev: function (env) {
if (this.unit && _.indexOf(['px', '%', 'm', 'cm', 'in',
'mm', 'pt', 'pc'], this.unit) === -1) {
if (this.unit && !_.contains(this.all_units, this.unit)) {
env.error({
message: "Invalid unit: '" + this.unit + "'",
index: this.index
});
return { is: 'undefined', value: 'undefined' };
}
// normalize units which are not px or %
if (this.unit && _.indexOf(['px', '%'], this.unit) === -1) {
if(!env.ppi) {
if (this.unit && _.contains(this.physical_units, this.unit)) {
if (!env.ppi) {
env.error({
message: "ppi is not set, so metric units can't be used",
index: this.index
});
return {
is: 'undefined',
value: 'undefined'
};
return { is: 'undefined', value: 'undefined' };
}
// convert all units to inch
switch(this.unit) {
case 'm':
this.value = this.value / 0.0254;
break;
case 'cm':
this.value = this.value / 2.54;
break;
case 'mm':
this.value = this.value / 25.4;
break;
case 'pt':
this.value = this.value / 72;
break;
case 'pc':
this.value = this.value / 6;
break;
}
// convert inch to px using ppi
this.value = this.value * env.ppi;
this.value = (this.value / this.densities[this.unit]) * env.ppi;
this.unit = 'px';
}