Skip to content

Commit

Permalink
fix: hex colors to allow alpha channel (#1274)
Browse files Browse the repository at this point in the history
  • Loading branch information
nickofthyme committed Jul 29, 2021
1 parent 051cabc commit 03b4f42
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 15 deletions.
34 changes: 28 additions & 6 deletions packages/charts/src/common/color_library_wrappers.test.ts
Expand Up @@ -105,9 +105,10 @@ describe('d3 Utils', () => {
describe('hsl colors', () => {
it('should return RgbObject', () => {
expect(stringToRGB('hsl(0,0%,50%)')).toMatchObject({
r: 127.5,
g: 127.5,
b: 127.5,
r: 128,
g: 128,
b: 128,
opacity: 1,
});
});

Expand All @@ -117,9 +118,9 @@ describe('d3 Utils', () => {

it('should return correct RgbObject for alpha value of 0', () => {
expect(stringToRGB('hsla(0,0%,50%,0)')).toEqual({
r: 127.5,
g: 127.5,
b: 127.5,
r: 128,
g: 128,
b: 128,
opacity: 0,
});
});
Expand Down Expand Up @@ -162,6 +163,27 @@ describe('d3 Utils', () => {
expect(stringToRGB('rgba(50,50,50,0.25)', (o) => o * 2).opacity).toBe(0.5);
});
});

describe('Edge Cases', () => {
it.each([
[undefined, { r: 255, g: 0, b: 0, opacity: 1 }],
['', { r: 255, g: 0, b: 0, opacity: 1 }],
['bad', { r: 187, g: 170, b: 221, opacity: 1 }],
['#00000000', { r: 0, g: 0, b: 0, opacity: 0 }],
['#000000', { r: 0, g: 0, b: 0, opacity: 1 }],
['#6092c000', { r: 96, g: 146, b: 192, opacity: 0 }],
['#6092c06b', { r: 96, g: 146, b: 192, opacity: 0.42 }],
['blue', { r: 0, g: 0, b: 255, opacity: 1 }],
['hsl(20, 100%, 40%)', { r: 204, g: 68, b: 0, opacity: 1 }],
['hsla(20, 100%, 40%, 0.5)', { r: 204, g: 68, b: 0, opacity: 0.5 }],
['hsla(20, 100%, 40%, 0)', { r: 204, g: 68, b: 0, opacity: 0 }],
['rgb(0,128,128)', { r: 0, g: 128, b: 128, opacity: 1 }],
['rgba(0,128,128,0.5)', { r: 0, g: 128, b: 128, opacity: 0.5 }],
['rgba(0,128,128,0)', { r: 0, g: 128, b: 128, opacity: 0 }],
])('input: $1', (input, output) => {
expect(stringToRGB(input)).toEqual(output);
});
});
});

describe('validateColor', () => {
Expand Down
16 changes: 7 additions & 9 deletions packages/charts/src/common/color_library_wrappers.ts
Expand Up @@ -62,15 +62,13 @@ export function stringToRGB(cssColorSpecifier?: string, opacity?: number | Opaci
* @param cssColorSpecifier
*/
function getColor(cssColorSpecifier: string = ''): RgbObject {
const endRegEx = /,\s*0+(\.0*)?\s*\)$/;
// TODO: make this check more robust
const color: D3RGBColor =
/^(rgba|hsla)\(/i.test(cssColorSpecifier) && endRegEx.test(cssColorSpecifier)
? {
...d3Rgb(cssColorSpecifier.replace(endRegEx, ',1)')),
opacity: 0,
}
: d3Rgb(cssColorSpecifier);
if (!chroma.valid(cssColorSpecifier)) return defaultColor;

const chromaColor = chroma(cssColorSpecifier);
const color: D3RGBColor = {
...d3Rgb(chromaColor.alpha(1).css()),
opacity: chromaColor.alpha(),
};

return validateColor(color) ?? defaultColor;
}
Expand Down

0 comments on commit 03b4f42

Please sign in to comment.