Skip to content

Commit

Permalink
Add Color#toString, expose Color publicly, document it
Browse files Browse the repository at this point in the history
  • Loading branch information
David Clark committed Dec 14, 2017
1 parent f794fd6 commit 6f80cb0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
32 changes: 30 additions & 2 deletions src/style-spec/util/color.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@
const {parseCSSColor} = require('csscolorparser');

/**
* An RGBA color value. All components are in the range [0, 1] and R, B, and G are premultiplied by A.
* @private
* An RGBA color value. Create instances from color strings using the static
* method `Color.parse`. The constructor accepts RGB channel values in the range
* `[0, 1]`, premultiplied by A.
*
* @param {number} r The red channel.
* @param {number} g The green channel.
* @param {number} b The blue channel.
* @param {number} a The alpha channel.
*/
class Color {
r: number;
Expand All @@ -23,6 +29,12 @@ class Color {
static white: Color;
static transparent: Color;

/**
* Parses valid CSS color strings and returns a `Color` instance.
*
* @param input
* @returns A `Color` instance.
*/
static parse(input: ?string): Color | void {
if (!input) {
return undefined;
Expand All @@ -48,6 +60,22 @@ class Color {
rgba[3]
);
}

/**
* Returns an RGBA string representing the color value.
*
* @returns An RGBA string.
* @example
* var purple = new Color.parse('purple');
* purple.toString; // = "rgba(128,0,128,1)"
* var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');
* translucentGreen.toString(); // = "rgba(26,207,26,0.73)"
*/
toString(): string {
const transformRgb = (value: number) => Math.round(value * 255 / this.a);
const rgb = [this.r, this.g, this.b].map(transformRgb);
return `rgba(${rgb.concat(this.a).join(',')})`;
}
}

Color.black = new Color(0, 0, 0, 1);
Expand Down
14 changes: 14 additions & 0 deletions test/unit/style-spec/color.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,17 @@ test('Color.parse', (t) => {
t.deepEqual(Color.parse(undefined), undefined);
t.end();
});

test('Color#toString', (t) => {
const purple = Color.parse('purple');
if (!purple) {
throw new Error('Parsing "purple" did not work');
}
t.equal(purple.toString(), 'rgba(128,0,128,1)');
const translucentGreen = Color.parse('rgba(26, 207, 26, .73)');
if (!translucentGreen) {
throw new Error('Parsing "rgba(26, 207, 26, .73)" did not work');
}
t.equal(translucentGreen.toString(), 'rgba(26,207,26,0.73)');
t.end();
});

0 comments on commit 6f80cb0

Please sign in to comment.