import type { OklchColor, RgbColor } from './types'; function srgbToLinear(channel: number): number { return channel <= 0.04045 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4); } function linearToSrgb(channel: number): number { return channel <= 0.0031308 ? 12.92 * channel : 1.055 * Math.pow(channel, 1 / 2.4) - 0.055; } /** * Convert normalized sRGB channels to OKLCH using the standard sRGB to linear * RGB to LMS to OKLab pipeline. */ export function rgbToOklch({ r, g, b }: RgbColor): OklchColor { const red = srgbToLinear(r); const green = srgbToLinear(g); const blue = srgbToLinear(b); const l = 0.4122214708 * red + 0.5363325363 * green + 0.0514459929 * blue; const m = 0.2119034982 * red + 0.6806995451 * green + 0.1073969566 * blue; const s = 0.0883024619 * red + 0.2817188376 * green + 0.6299787005 * blue; const lRoot = Math.cbrt(l); const mRoot = Math.cbrt(m); const sRoot = Math.cbrt(s); const L = 0.2104542553 * lRoot + 0.793617785 * mRoot - 0.0040720468 * sRoot; const a = 1.9779984951 * lRoot - 2.428592205 * mRoot + 0.4505937099 * sRoot; const bLab = 0.0259040371 * lRoot + 0.7827717662 * mRoot - 0.808675766 * sRoot; const h = (Math.atan2(bLab, a) * 180) / Math.PI; return { L, C: Math.sqrt(a * a + bLab * bLab), h: (h + 360) % 360, }; } /** * Convert an OKLCH color to normalized sRGB channels. Callers that emit an * sRGB value should clamp out-of-gamut channels when formatting. */ export function oklchToRgb({ L, C, h }: OklchColor): RgbColor { const radians = (h * Math.PI) / 180; const a = C * Math.cos(radians); const b = C * Math.sin(radians); const lRoot = L + 0.3963377774 * a + 0.2158037573 * b; const mRoot = L - 0.1055613458 * a - 0.0638541728 * b; const sRoot = L - 0.0894841775 * a - 1.291485548 * b; const l = lRoot * lRoot * lRoot; const m = mRoot * mRoot * mRoot; const s = sRoot * sRoot * sRoot; return { r: linearToSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s), g: linearToSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s), b: linearToSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s), }; }