@publidata/utils-colors
Version:
Collection of methods to handle colors
73 lines (64 loc) • 2.19 kB
JavaScript
import { getTints, getShades } from "./helpers";
/**
* Setup colors in the document
* @param {object} colors
* @returns {void}
*/
export const generateColors = (colors = {}, withShades = [], format = "string") => {
const output = [];
Object.keys(colors).forEach(color => {
output.push(`--${color}: ${colors[color]};`);
});
withShades.forEach(color => {
if (!colors[color]) {
withShades.splice(withShades.indexOf(color), 1);
throw new Error(`Color '${color}' is not defined`);
}
});
const shadesToGenerate = [
{ name: "50", opacityPer: "10" },
{ name: "100", opacityPer: "20" },
{ name: "200", opacityPer: "40" },
{ name: "300", opacityPer: "60" },
{ name: "400", opacityPer: "80" },
{ name: "500", opacityPer: "100" },
{ name: "600", opacityShade: "80" },
{ name: "700", opacityShade: "60" },
{ name: "800", opacityShade: "40" },
{ name: "900", opacityShade: "20" }
];
const shades = {};
withShades.forEach(color => {
const tints = getTints(colors[color].replace("#", "")).reverse();
const blackShades = getShades(colors[color].replace("#", "")).reverse();
tints.forEach((tint, index) => {
const shade = shadesToGenerate.find(
({ opacityPer }) => opacityPer === `${index * 10}`
);
if (!shade) return;
shades[`${color}-${shade.name}`] = `#${tint}`;
});
blackShades.forEach((bShade, index) => {
const shade = shadesToGenerate.find(
({ opacityShade }) => opacityShade === `${index * 10}`
);
if (!shade) return;
shades[`${color}-${shade.name}`] = `#${bShade}`;
});
});
Object.keys(shades).forEach(color => {
output.push(`--${color}: ${shades[color]};`);
});
if (format === "array") {
return output;
}
if (format === "object") {
const outputObject = {};
output.forEach(line => {
const [key, value] = line.replace(/--/g, "").split(":");
outputObject[key.trim()] = value.trim();
});
return outputObject;
}
return output.join("\n");
};