@public-ui/components
Version:
Contains all web components that belong to KoliBri - The accessible HTML-Standard.
65 lines (64 loc) • 2.64 kB
JavaScript
/*!
* KoliBri - The accessible HTML-Standard
*/
import { hex } from "wcag-contrast";
import rgba from "color-rgba";
import rgbaConvert from "rgba-convert";
export const getContrastYIQ = (r, g, b) => {
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
return yiq >= 128 ? -1 : 1;
};
export const calcColorContrast = (baseColor, contrastColor, ratio, dir = 1) => {
const color = [
Math.max(Math.min(Math.round(contrastColor[0] + dir * Math.max(1, contrastColor[0] / 100)), 255), 0),
Math.max(Math.min(Math.round(contrastColor[1] + dir * Math.max(1, contrastColor[1] / 100)), 255), 0),
Math.max(Math.min(Math.round(contrastColor[2] + dir * Math.max(1, contrastColor[2] / 100)), 255), 0),
];
const contrast = hex(rgbaConvert.hex(`rgba(${baseColor.join(',')},1)`), rgbaConvert.hex(`rgba(${color.join(',')},1)`));
const summe = color[0] + color[1] + color[2];
if (summe === 0 || summe === 765 || contrast > ratio) {
return {
background: baseColor,
foreground: color,
contrast,
};
}
else {
return calcColorContrast(baseColor, color, ratio, dir);
}
};
const cache = new Map();
export const getColorContrast = (baseColor, contrastColor, ratio, dir = 1) => {
if (cache.has(baseColor)) {
return cache.get(baseColor);
}
const color = calcColorContrast(baseColor, contrastColor, ratio, dir);
cache.set(baseColor, color);
return color;
};
export const createContrastColorPair = (color, contrastRatio = 7) => {
let baseColor = [0, 0, 0, 1];
let contrastColor = [255, 255, 255, 1];
if (typeof color === 'string') {
baseColor = rgba(color);
contrastColor = baseColor;
}
else if (typeof color === 'object' && color !== null && typeof color.background === 'string' && typeof color.foreground === 'string') {
baseColor = rgba(color.background);
if (typeof color.foreground === 'string') {
contrastColor = rgba(color.foreground);
}
else {
contrastColor = baseColor;
}
}
const yiq = getContrastYIQ(baseColor[0], baseColor[1], baseColor[2]);
const colorContrast = getColorContrast([baseColor[0], baseColor[1], baseColor[2]], [contrastColor[0], contrastColor[1], contrastColor[2]], contrastRatio, yiq);
contrastColor = [...colorContrast.foreground, 1];
return {
background: rgbaConvert.hex(`rgba(${baseColor.join(',')})`),
foreground: rgbaConvert.hex(`rgba(${contrastColor.join(',')})`),
contrast: colorContrast.contrast,
};
};
//# sourceMappingURL=contrast.js.map