import {parseColor} from "./util"; import {range256, RGBA, RGBAArray, RGBArray} from './d'; class Color implements RGBA { static alphaToString: boolean = true; static proxyDefinition = { set: (target, prop, value): boolean => { if (['red', 'green', 'blue', 'alpha'].indexOf(prop) > -1) { if (Color.isLegalValue(value)) { target[prop] = Math.round(value); return true; } else { throw new Error(`Value ${value} is not a valid value for ${prop}`) } } else { target[prop] = value; return true; } }, get: (target, prop, receiver) => { if (prop in Color.prototype) { return target[prop]; } else if (prop in String.prototype) { return target.toString()[prop] } else { return target[prop]; } } }; red: range256 = 0; green: range256 = 0; blue: range256 = 0; alpha: range256 = 255; private static toHex(n: range256): string { return ("00" + n.toString(16)).slice(-2); } private static isLegalValue(n: number): boolean { return n >= 0 && n <= 255 } constructor(initializer: RGBArray | RGBAArray | string) { if (typeof initializer == 'string') { return parseColor(initializer); } else { let [red, green, blue, alpha] = initializer; let proxy = new Proxy(this, Color.proxyDefinition); if (!isNaN(red)) proxy.red = red; if (!isNaN(green)) proxy.green = green; if (!isNaN(blue)) proxy.blue = blue; if (!isNaN(alpha)) proxy.alpha = alpha; return proxy; } } getAlphaFraction(): number { return this.alpha / 255; } toRGBArray(): RGBArray { return [this.red, this.green, this.blue]; } toRGBAArray(): RGBAArray { return [this.red, this.green, this.blue, this.alpha]; } toString(includeAlpha:boolean): string { if(includeAlpha===undefined) includeAlpha=Color.alphaToString; return '#' + Color.toHex(this.red) + Color.toHex(this.green) + Color.toHex(this.blue) + (includeAlpha ? Color.toHex(this.alpha) : "") } } export default Color;