color-cleaner
Version:
A CLI tool to clean and consolidate colors in your project files.
107 lines (92 loc) • 2.96 kB
JavaScript
import Color from "color";
function getHexColors(colorObjects) {
return colorObjects.map((obj) => {
if (obj.color.toLowerCase() === "transparent") {
return {
...obj,
color: "#00000000",
};
}
try {
const color = Color(obj.color);
return {
...obj,
color: color.hex().toLowerCase(),
originalColor: obj.color,
};
} catch (error) {
return obj;
}
});
}
function consolidateColors(colorObjects, threshold = 10) {
const groups = [];
const processed = new Set();
let cssVarCounter = 0;
for (let index = 0; index < colorObjects.length; index++) {
if (processed.has(index)) continue;
const obj = colorObjects[index];
const currentColor = obj.color;
const cssVarName = `--color-${cssVarCounter++}`;
const group = {
color: obj.color,
cssVariable: cssVarName,
items: [
{
lineNumber: obj.lineNumber,
currentPath: obj.currentPath,
color: obj.color,
cssVariable: cssVarName,
originalColor: obj.originalColor,
},
],
};
for (let otherIndex = 0; otherIndex < colorObjects.length; otherIndex++) {
if (index === otherIndex || processed.has(otherIndex)) continue;
const otherObj = colorObjects[otherIndex];
const otherColor = otherObj.color;
if (threshold === 0 && currentColor === otherColor) {
group.items.push({
lineNumber: otherObj.lineNumber,
currentPath: otherObj.currentPath,
color: otherObj.color,
cssVariable: cssVarName,
});
processed.add(otherIndex);
} else if (threshold > 0) {
let currentColorNormalized = Color(currentColor);
let otherColorNormalized = Color(otherColor);
const distance = Math.sqrt(
Math.pow(currentColorNormalized.red() - otherColorNormalized.red(), 2) +
Math.pow(currentColorNormalized.green() - otherColorNormalized.green(), 2) +
Math.pow(currentColorNormalized.blue() - otherColorNormalized.blue(), 2)
);
if (distance <= threshold) {
group.items.push({
lineNumber: otherObj.lineNumber,
currentPath: otherObj.currentPath,
color: otherObj.color,
cssVariable: cssVarName,
});
processed.add(otherIndex);
}
}
}
groups.push(group);
processed.add(index);
}
return groups;
}
function convertMapColorsToHex(colorMap) {
const result = new Map();
for (const [key, value] of colorMap) {
try {
const color = Color(value);
result.set(key, color.hexa().toLowerCase());
} catch (error) {
result.set(key, value);
}
}
return result;
}
export { getHexColors, consolidateColors, convertMapColorsToHex };