diff --git a/packages/utils/src/ColorUtils.js b/packages/utils/src/ColorUtils.js deleted file mode 100644 index 94124f4d49..0000000000 --- a/packages/utils/src/ColorUtils.js +++ /dev/null @@ -1,29 +0,0 @@ -class ColorUtils { - /** - * Checks if a background color is dark (i.e. should use a light foreground). - * - * @param {string} background the background color - */ - static isDark(background) { - const d = document.createElement('div'); - d.style.display = 'none'; - d.style.color = background; - const color = getComputedStyle(document.body.appendChild(d)) - .color.match(/\d+/g) - .map(a => parseInt(a, 10)); - document.body.removeChild(d); - const brightness = ColorUtils.getBrightness(color); - return brightness < 125; - } - - static getBrightness(color) { - // http://www.w3.org/TR/AERT#color-contrast - return Math.round( - (parseInt(color[0], 10) * 299 + - parseInt(color[1], 10) * 587 + - parseInt(color[2], 10) * 114) / - 1000 - ); - } -} -export default ColorUtils; diff --git a/packages/utils/src/ColorUtils.ts b/packages/utils/src/ColorUtils.ts new file mode 100644 index 0000000000..51ba6d61b1 --- /dev/null +++ b/packages/utils/src/ColorUtils.ts @@ -0,0 +1,34 @@ +class ColorUtils { + /** + * Checks if a background color is dark (i.e. should use a light foreground). + * + * @param {string} background the background color + */ + static isDark(background: string): boolean { + const d = document.createElement('div'); + d.style.display = 'none'; + d.style.color = background; + + const computedColor = getComputedStyle(document.body.appendChild(d)).color; + const colorTokens = computedColor.match(/\d+/g); + let color: number[] = []; + + if (colorTokens) { + color = colorTokens.map(a => parseInt(a, 10)); + } else { + throw new Error(`Invalid color received. Got ${computedColor}`); + } + document.body.removeChild(d); + const brightness = ColorUtils.getBrightness(color); + return brightness < 125; + } + + // Note: leaving this as arbitrary length number[] in case of RGBA(). + static getBrightness(color: number[]): number { + // http://www.w3.org/TR/AERT#color-contrast + return Math.round( + (color[0] * 299 + color[1] * 587 + color[2] * 114) / 1000 + ); + } +} +export default ColorUtils;