UNPKG

@kcuf/mere-color

Version:

Mere color utils for generating, manipulation, a11y purposes.

48 lines 1.94 kB
import _objectSpread from "@babel/runtime/helpers/objectSpread2"; import { rgbComputeLuminance, computeContrast, hslToRgb, toColorStringOriginalNotation } from '../util'; import { parseToHsl } from '../parse'; import { a11yLuminance } from '../a11y'; /** * Adjust the color's lightness to meet target contrast, returning the new color in the original notation normalized. */ export default function adjustLightnessForContrast(color, targetContrast) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var hsl = parseToHsl(color); if (!hsl) { return color; } var _options$bgc = options.bgc, bgc = _options$bgc === void 0 ? '#fff' : _options$bgc, _options$steps = options.steps, steps = _options$steps === void 0 ? 100 : _options$steps, _options$minLightness = options.minLightness, minLightness = _options$minLightness === void 0 ? 0 : _options$minLightness, _options$maxLightness = options.maxLightness, maxLightness = _options$maxLightness === void 0 ? 100 : _options$maxLightness; var bgcLuminance = a11yLuminance(bgc); if (bgcLuminance < 0) { return color; } var minL = minLightness; var maxL = maxLightness; var targetLightness = (minLightness + maxLightness) / 2; for (var i = 0; i < steps; i++) { var rgb = hslToRgb(_objectSpread(_objectSpread({}, hsl), {}, { l: targetLightness })); var contrast = computeContrast(rgbComputeLuminance(rgb), bgcLuminance); if (Math.abs(contrast - targetContrast) < 0.001) { return toColorStringOriginalNotation(rgb, color); } if (contrast > targetContrast) { minL = targetLightness; } else { maxL = targetLightness; } targetLightness = (minL + maxL) / 2; } return toColorStringOriginalNotation(_objectSpread(_objectSpread({}, hsl), {}, { l: targetLightness }), color); } //# sourceMappingURL=adjust-lightness-for-contrast.js.map