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,9 +243,15 @@ 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();
alpha = arg._alpha;
} else if (arg._class === 'Gradient') {
// TODO: Construct gradient
type = 'gradient';
} else {
// Determine type by presence of object property names
type = 'hue' in arg type = 'hue' in arg
? 'lightness' in arg ? 'lightness' in arg
? 'hsl' ? 'hsl'
@ -255,40 +261,29 @@ var Color = this.Color = Base.extend(new function() {
: 'rgb'; : 'rgb';
var properties = types[type]; var properties = types[type];
for (var i = 0, l = properties.length; i < l; i++) for (var i = 0, l = properties.length; i < l; i++)
components[i] = arg[properties[i]]; components[i] = arg[properties[i]] || 0;
alpha = arg.alpha; 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];
} }
} // Default fallbacks: rgb, black
this._type = type; this._type = type || 'rgb';
this._components = components; 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;
}
}, },
/** /**