UNPKG

contrastrast

Version:

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

46 lines (45 loc) 2.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.textContrastForBGColor = void 0; const constants_js_1 = require("../constants.js"); const colorStringParsers_js_1 = require("../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 */ const textContrastForBGColor = (bgColorString, options = {}) => { const opts = { ...DEFAULT_CONTRASTRAST_OPTIONS, ...options, }; try { const rgb = (0, colorStringParsers_js_1.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 > constants_js_1.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; } } }; exports.textContrastForBGColor = textContrastForBGColor;