export const hexToHsb = (hex: string) => {
// Remove the "#" symbol if present
hex = hex.replace("#", "");
// Convert HEX to RGB
const r = parseInt(hex.substring(0, 2), 16) / 255;
const g = parseInt(hex.substring(2, 4), 16) / 255;
const b = parseInt(hex.substring(4, 6), 16) / 255;
// Calculate the maximum and minimum RGB values
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
// Calculate brightness (V)
const brightness = max;
// Calculate saturation (S)
const saturation = max === 0 ? 0 : (max - min) / max;
// Calculate hue (H)
let hue;
if (max === min) {
hue = 0; // No saturation, so hue is undefined
} else {
if (max === r) {
hue = (g - b) / (max - min);
} else if (max === g) {
hue = 2 + (b - r) / (max - min);
} else {
hue = 4 + (r - g) / (max - min);
}
hue *= 60;
if (hue < 0) {
hue += 360;
}
}
// Round HSB values to two decimal places
const roundedHue = Math.round(hue * 100) / 100;
const roundedSaturation = Math.round(saturation * 100) / 100;
const roundedBrightness = Math.round(brightness * 100) / 100;
return {
hue: roundedHue,
saturation: roundedSaturation,
brightness: roundedBrightness,
};
};