Improve Color constructor and simplify serialization.

This commit is contained in:
Jürg Lehni 2013-04-08 07:27:48 -07:00
parent e7c6bf3d9b
commit cf21da75fc

View file

@ -243,52 +243,47 @@ var Color = this.Color = Base.extend(new function() {
components = Array.prototype.slice.call(components, 0, length); components = Array.prototype.slice.call(components, 0, length);
} else { } else {
if (argType === 'object') { if (argType === 'object') {
if (arg instanceof Color) if (arg._class === 'Color') {
return arg.clone(); type = arg._type;
// Determine type from property names components = arg._components.slice();
type = 'hue' in arg alpha = arg._alpha;
? 'lightness' in arg } else if (arg._class === 'Gradient') {
? 'hsl' // TODO: Construct gradient
: 'hsb' type = 'gradient';
: 'gray' in arg } else {
? 'gray' // Determine type by presence of object property names
: 'rgb'; type = 'hue' in arg
var properties = types[type]; ? 'lightness' in arg
for (var i = 0, l = properties.length; i < l; i++) ? 'hsl'
components[i] = arg[properties[i]]; : 'hsb'
alpha = arg.alpha; : 'gray' in arg
? 'gray'
: 'rgb';
var properties = types[type];
for (var i = 0, l = properties.length; i < l; i++)
components[i] = arg[properties[i]] || 0;
alpha = arg.alpha;
}
} else if (argType === 'string') { } else if (argType === 'string') {
components = arg.match(/^#[0-9a-f]{3,6}$/i) components = arg.match(/^#[0-9a-f]{3,6}$/i)
? hexToRgb(arg) ? hexToRgb(arg)
: nameToRgb(arg); : nameToRgb(arg);
type = 'rgb'; type = 'rgb';
} }
if (type) { if (this._read && type)
if (this._read) this._read = 1;
this._read = 1;
} else {
// Default fallback: rgb black
type = 'rgb';
components = [0, 0, 0];
}
} }
this._type = type; // Default fallbacks: rgb, black
this._components = components; this._type = type || 'rgb';
this._components = components || (type === 'gray' ? [1] : [0, 0, 0]);
this._alpha = alpha; this._alpha = alpha;
}, },
_serialize: function(options) { _serialize: function(options) {
if (/^(gray|rgb)$/.test(this._type)) { // We can ommit the type for gray and rgb:
return this._components; return /^(gray|rgb)$/.test(this._type)
} else { ? this._components
var properties = types[this._type], : [this._type].concat(this._components);
res = {};
for (var i = 0, l = properties.length; i < l; i++)
res[properties[i]] = this._components[i];
if (this._alpha != null)
res.alpha = this._alpha;
return res;
}
}, },
/** /**