Add color utils with relevant tests
This commit is contained in:
parent
59a5a89c61
commit
29a7c83eb3
|
@ -0,0 +1,25 @@
|
||||||
|
/**
|
||||||
|
* Convert hex color to rgb array
|
||||||
|
*
|
||||||
|
* @param hex string
|
||||||
|
* @returns array|null
|
||||||
|
*/
|
||||||
|
export const hexToRgb = hex => {
|
||||||
|
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
|
||||||
|
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
|
||||||
|
const fullHex = hex.replace(shorthandRegex, (_m, r, g, b) => r + r + g + g + b + b);
|
||||||
|
|
||||||
|
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(fullHex);
|
||||||
|
return result
|
||||||
|
? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)]
|
||||||
|
: null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const textColorForBackground = backgroundColor => {
|
||||||
|
const [r, g, b] = hexToRgb(backgroundColor);
|
||||||
|
|
||||||
|
if (r + g + b > 500) {
|
||||||
|
return '#333333';
|
||||||
|
}
|
||||||
|
return '#FFFFFF';
|
||||||
|
};
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { textColorForBackground, hexToRgb } from '~/lib/utils/color_utils';
|
||||||
|
|
||||||
|
describe('Color utils', () => {
|
||||||
|
describe('Converting hex code to rgb', () => {
|
||||||
|
it('convert hex code to rgb', () => {
|
||||||
|
expect(hexToRgb('#000000')).toEqual([0, 0, 0]);
|
||||||
|
expect(hexToRgb('#ffffff')).toEqual([255, 255, 255]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('convert short hex code to rgb', () => {
|
||||||
|
expect(hexToRgb('#000')).toEqual([0, 0, 0]);
|
||||||
|
expect(hexToRgb('#fff')).toEqual([255, 255, 255]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handle conversion regardless of the characters case', () => {
|
||||||
|
expect(hexToRgb('#f0F')).toEqual([255, 0, 255]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Getting text color for given background', () => {
|
||||||
|
// following tests are being ported from `text_color_for_bg` section in labels_helper_spec.rb
|
||||||
|
it('uses light text on dark backgrounds', () => {
|
||||||
|
expect(textColorForBackground('#222E2E')).toEqual('#FFFFFF');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses dark text on light backgrounds', () => {
|
||||||
|
expect(textColorForBackground('#EEEEEE')).toEqual('#333333');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supports RGB triplets', () => {
|
||||||
|
expect(textColorForBackground('#FFF')).toEqual('#333333');
|
||||||
|
expect(textColorForBackground('#000')).toEqual('#FFFFFF');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
Loading…
Reference in New Issue