UNPKG

contrastrast

Version:

A lightweight tool that parses color strings and recommends text contrast based on WCAG Standards

42 lines (41 loc) 2.13 kB
import { CONTRAST_THRESHOLD } from "../constants.js"; import { getRGBFromColorString } from "../helpers/colorStringParsers.js"; const DEFAULT_CONTRASTRAST_OPTIONS = { fallbackOption: "dark", throwErrorOnUnhandled: false, }; /** * Recommends to use either `light` or `dark` text based on the * given background color. * * Color string can be HEX, RGB, or HSL * * @deprecated This method will go away in v2, we recommend switching to `Contrastrast(color).textContrast(bgColor)` for a more comprehensive and accurate comparison * * @param {String} bgColorString Color string of the background. Can be HEX, RGB, or HSL * @param {ContrastrastOptions} options (Optional) Partial collection `ContrastrastOptions` that you wish you apply * @param {"dark"|"light"} [options.fallbackOption="dark"] Fallback color recommendation, returns on error or unparsable color string. Defaults to `dark` * @param {Boolean} [options.throwErrorOnUnhandled=false] Force option to throw error when invalid/unhandled color string is passed. Defaults to `false` * @return {"dark"|"light"} Text color recommendation for given color string */ export const textContrastForBGColor = (bgColorString, options = {}) => { const opts = { ...DEFAULT_CONTRASTRAST_OPTIONS, ...options, }; try { const rgb = getRGBFromColorString(bgColorString); // http://www.w3.org/TR/AERT#color-contrast const brightness = Math.round((rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000); return brightness > CONTRAST_THRESHOLD ? "dark" : "light"; } catch (e) { if (opts.throwErrorOnUnhandled) { throw new Error(`[contrastrast] Error while reading color, using default value "${opts.fallbackOption}"\n`); } else { console.error(`[contrastrast] Error while reading color, using default value "${opts.fallbackOption}"\n`, e); return opts.fallbackOption; } } };