From 29a7c83eb30914627163f481de40836de5dc8158 Mon Sep 17 00:00:00 2001 From: Ammar Alakkad Date: Fri, 26 Jul 2019 16:05:59 +0300 Subject: [PATCH] Add color utils with relevant tests --- .../javascripts/lib/utils/color_utils.js | 25 +++++++++++++ spec/frontend/lib/utils/color_utils_spec.js | 35 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 app/assets/javascripts/lib/utils/color_utils.js create mode 100644 spec/frontend/lib/utils/color_utils_spec.js diff --git a/app/assets/javascripts/lib/utils/color_utils.js b/app/assets/javascripts/lib/utils/color_utils.js new file mode 100644 index 00000000000..07fb2915ca7 --- /dev/null +++ b/app/assets/javascripts/lib/utils/color_utils.js @@ -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'; +}; diff --git a/spec/frontend/lib/utils/color_utils_spec.js b/spec/frontend/lib/utils/color_utils_spec.js new file mode 100644 index 00000000000..433e9d5a85e --- /dev/null +++ b/spec/frontend/lib/utils/color_utils_spec.js @@ -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'); + }); + }); +});