Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions utils/color-converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,24 @@ import { ColorFormat } from "../types";
import { Hsl } from "culori";

export const formatNumber = (num?: number) => {
if (!num) return "0";
return num % 1 === 0 ? num : num.toFixed(4);
if (num === undefined || num === null) return "0";
if (num === 0) return "0";
return num % 1 === 0 ? String(num) : num.toFixed(4);
};

const hasAlpha = (color: { alpha?: number }): boolean => {
return color.alpha !== undefined && color.alpha < 1;
};

export const formatHsl = (hsl: Hsl) => {
return `hsl(${formatNumber(hsl.h)} ${formatNumber(hsl.s * 100)}% ${formatNumber(hsl.l * 100)}%)`;
const h = formatNumber(hsl.h);
const s = formatNumber(hsl.s * 100);
const l = formatNumber(hsl.l * 100);

if (hasAlpha(hsl)) {
return `hsl(${h} ${s}% ${l}% / ${formatNumber(hsl.alpha)})`;
}
return `hsl(${h} ${s}% ${l}%)`;
};

export const colorFormatter = (
Expand All @@ -26,15 +38,28 @@ export const colorFormatter = (
if (tailwindVersion === "4") {
return formatHsl(hsl);
}
return `${formatNumber(hsl.h)} ${formatNumber(hsl.s * 100)}% ${formatNumber(hsl.l * 100)}%`;
const base = `${formatNumber(hsl.h)} ${formatNumber(hsl.s * 100)}% ${formatNumber(hsl.l * 100)}%`;
if (hasAlpha(hsl)) {
return `${base} / ${formatNumber(hsl.alpha)}`;
}
return base;
}
case "rgb":
return culori.formatRgb(color); // e.g., "rgb(64, 128, 192)"
case "oklch": {
const oklch = culori.converter("oklch")(color);
return `oklch(${formatNumber(oklch.l)} ${formatNumber(oklch.c)} ${formatNumber(oklch.h)})`;
const l = formatNumber(oklch.l);
const c = formatNumber(oklch.c);
const h = formatNumber(oklch.h);
if (hasAlpha(oklch)) {
return `oklch(${l} ${c} ${h} / ${formatNumber(oklch.alpha)})`;
}
return `oklch(${l} ${c} ${h})`;
}
case "hex":
if (hasAlpha(color)) {
return culori.formatHex8(color); // e.g., "#4080c0ff"
}
return culori.formatHex(color); // e.g., "#4080c0"
default:
return colorValue;
Expand Down