braid-design-system
Version:
Themeable design system for the SEEK Group
31 lines (30 loc) • 1.02 kB
JavaScript
import { parse } from "gradient-parser";
import { parseToRgb } from "polished";
const getLinearGradientColors = (color) => {
const gradients = parse(color);
return gradients[0].colorStops.map(({ type, value }) => {
if (typeof value !== "string") {
throw new Error(
"Gradient parsing in Braid currently only supports hex/literal values"
);
}
return `${type === "hex" ? "#" : ""}${value}`;
});
};
const calculateYiq = (color) => {
const { red, green, blue } = parseToRgb(color);
return (red * 299 + green * 587 + blue * 114) / 1e3;
};
const isLight = (inputColor, foregroundColor = "#000") => {
const colors = /^linear-gradient/.test(inputColor) ? getLinearGradientColors(inputColor) : [inputColor];
const foregroundYiq = calculateYiq(foregroundColor);
return colors.some((color) => {
const yiq = calculateYiq(color);
const midpoint = 256 / 2;
const foregroundOffset = foregroundYiq / 2;
return yiq >= midpoint + foregroundOffset;
});
};
export {
isLight
};