Skip to content

OKLCH Color Converter — Go source

Convert between hex and OKLCH — the perceptual color space behind modern CSS. Live lightness, chroma, and hue sliders with the sRGB gamut edge shown on the chroma rail; out-of-gamut points gamut-map exactly like browsers do.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package oklchconverter is the Go twin of CosmoDev's src/lib/oklch.ts (dual
// source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// Pure + deterministic, never panics. The table-driven tests in
// oklch-converter_test.go share vectors with src/lib/oklch.test.ts so the two
// implementations are held to the same contract.
//
// OKLab / OKLCH per Björn Ottosson's published matrices — ported verbatim so
// the contract is explicit: same constants, same 1e-4 sRGB gamut epsilon,
// chroma-reduction gamut mapping (edge = maxChroma*0.999), and maxChroma
// bisection over [0, 0.5] with 24 iterations. Hex endpoints reuse
// colorConvert's rgb<->hex semantics as private copies (the twin is a
// self-contained package, mirroring the TS lib's import of hexToRgb/rgbToHex).
package oklchconverter

import (
	"fmt"
	"math"
	"regexp"
	"strconv"
	"strings"
)

// Oklch is a point in the OKLCH color space. Mirrors the TS `Oklch` interface.
type Oklch struct {
	L float64 // Lightness 0..1
	C float64 // Chroma, typically 0..0.4
	H float64 // Hue in degrees, 0..360 (0 when C ≈ 0)
}

// SrgbResult is the outcome of an OKLCH → sRGB conversion. Mirrors the TS
// `SrgbResult` interface; InGamut is false when the exact OKLCH point fell
// outside sRGB and was clamped.
type SrgbResult struct {
	Hex     string
	RGB     [3]uint8
	InGamut bool
}

// ParsedOklch is the outcome of ParseOklch. Mirrors the TS `ParsedOklch`
// interface; H is wrapped into 0..360 and Alpha defaults to 1 when the input
// had no /alpha component.
type ParsedOklch struct {
	L     float64
	C     float64
	H     float64
	Alpha float64
}

// clamp01 clamps x into [0, 1] — the TS clamp01 helper.
func clamp01(x float64) float64 {
	return math.Min(1, math.Max(0, x))
}

// toLinear is the sRGB EOTF (gamma → linear) for one normalized channel.
func toLinear(c float64) float64 {
	if c <= 0.04045 {
		return c / 12.92
	}
	return math.Pow((c+0.055)/1.055, 2.4)
}

// toGamma is the inverse EOTF (linear → gamma) for one normalized channel.
func toGamma(c float64) float64 {
	if c <= 0.0031308 {
		return 12.92 * c
	}
	return 1.055*math.Pow(c, 1/2.4) - 0.055
}

// round255 rounds a normalized channel to an 8-bit byte, clamping to [0, 1]
// first. JS Math.round rounds halves toward +∞; after the [0,1] clamp every
// input is non-negative, so math.Round (halves away from zero) agrees.
func round255(x float64) uint8 {
	return uint8(math.Round(clamp01(x) * 255))
}

// SrgbToOklch converts 8-bit sRGB channels (0..255) to OKLCH. It is the Go
// twin of srgbToOklch() in src/lib/oklch.ts and uses Ottosson's forward
// matrices verbatim.
func SrgbToOklch(r, g, b float64) Oklch {
	lr := toLinear(r / 255)
	lg := toLinear(g / 255)
	lb := toLinear(b / 255)

	l := math.Cbrt(0.4122214708*lr + 0.5363325363*lg + 0.0514459929*lb)
	m := math.Cbrt(0.2119034982*lr + 0.6806995451*lg + 0.1073969566*lb)
	s := math.Cbrt(0.0883024619*lr + 0.2817188376*lg + 0.6299787005*lb)

	L := 0.2104542553*l + 0.793617785*m - 0.0040720468*s
	a := 1.9779984951*l - 2.428592205*m + 0.4505937099*s
	bb := 0.0259040371*l + 0.7827717662*m - 0.808675766*s

	C := math.Hypot(a, bb)
	H := 0.0
	if C >= 1e-6 {
		H = math.Atan2(bb, a) * 180 / math.Pi
		if H < 0 {
			H += 360
		}
	}
	return Oklch{L: L, C: C, H: H}
}

// linearFromOklch returns the unclamped linear sRGB channels for an OKLCH
// point, via Ottosson's inverse matrices. It mirrors the private
// linearFromOklch() helper in the TS lib.
func linearFromOklch(L, C, H float64) (lr, lg, lb float64) {
	rad := H * math.Pi / 180
	a := C * math.Cos(rad)
	b := C * math.Sin(rad)

	l := math.Pow(L+0.3963377774*a+0.2158037573*b, 3)
	m := math.Pow(L-0.1055613458*a-0.0638541728*b, 3)
	s := math.Pow(L-0.0894841775*a-1.291485548*b, 3)

	return 4.0767416621*l - 3.3077115913*m + 0.2309699292*s,
		-1.2684380046*l + 2.6097574011*m - 0.3413193965*s,
		-0.0041960863*l - 0.7034186147*m + 1.707614701*s
}

// inGamutEps reports whether linear sRGB channels sit inside the unit cube
// with the TS lib's 1e-4 float tolerance on every edge.
func inGamutEps(r, g, b float64) bool {
	const eps = 1e-4
	return r >= -eps && r <= 1+eps && g >= -eps && g <= 1+eps && b >= -eps && b <= 1+eps
}

// OklchToSrgb converts an OKLCH point to sRGB hex + bytes. Out-of-gamut points
// are gamut-mapped by CHROMA REDUCTION (browser-style: show the brightest
// achievable color of that hue/lightness, not a per-channel clamp), and
// flagged InGamut=false. Mirrors oklchToSrgb() in src/lib/oklch.ts.
func OklchToSrgb(o Oklch) SrgbResult {
	lr, lg, lb := linearFromOklch(o.L, o.C, o.H)
	inGamut := inGamutEps(lr, lg, lb)
	if !inGamut {
		// Shrink chroma to just inside the gamut edge (0.999 guard avoids the
		// float boundary); hue and lightness stay — CSS gamut maps the same way.
		edge := MaxChroma(o.L, o.H) * 0.999
		if edge < o.C {
			lr, lg, lb = linearFromOklch(o.L, edge, o.H)
		}
	}
	rgb := [3]uint8{round255(toGamma(lr)), round255(toGamma(lg)), round255(toGamma(lb))}
	return SrgbResult{
		Hex:     rgbToHex(float64(rgb[0]), float64(rgb[1]), float64(rgb[2])),
		RGB:     rgb,
		InGamut: inGamut,
	}
}

// hexToRgb parses `#rgb` / `#rrggbb` (case-insensitive, `#` optional) into
// 8-bit channels, or ok=false. Private copy of hexToRgb() from
// src/lib/colorConvert.ts — oklch.ts reuses it for its hex endpoint.
func hexToRgb(hex string) (rgb [3]uint8, ok bool) {
	h := strings.TrimPrefix(strings.TrimSpace(hex), "#")
	// Expand a 3-digit shorthand (e.g. "0f0" → "00ff00"). At this point h is
	// ASCII (any non-ASCII input fails the hex6 check below regardless), so
	// byte indexing agrees with the TS lib's per-character doubling.
	if len(h) == 3 {
		h = string([]byte{h[0], h[0], h[1], h[1], h[2], h[2]})
	}
	if !hex6.MatchString(h) {
		return [3]uint8{}, false
	}
	r, _ := strconv.ParseUint(h[0:2], 16, 8)
	g, _ := strconv.ParseUint(h[2:4], 16, 8)
	b, _ := strconv.ParseUint(h[4:6], 16, 8)
	return [3]uint8{uint8(r), uint8(g), uint8(b)}, true
}

// rgbToHex renders 0..255 channels as lowercase zero-padded `#rrggbb`,
// clamping each channel to 0..255 and rounding fractions. Private copy of
// rgbToHex() from src/lib/colorConvert.ts.
func rgbToHex(r, g, b float64) string {
	byteHex := func(n float64) string {
		c := uint8(math.Round(math.Min(255, math.Max(0, n))))
		return fmt.Sprintf("%02x", c)
	}
	return "#" + byteHex(r) + byteHex(g) + byteHex(b)
}

// HexToOklch parses a hex color straight to OKLCH. ok=false mirrors the TS
// lib's `null` for invalid hex.
func HexToOklch(hex string) (ok Oklch, oklchValid bool) {
	rgb, valid := hexToRgb(hex)
	if !valid {
		return Oklch{}, false
	}
	return SrgbToOklch(float64(rgb[0]), float64(rgb[1]), float64(rgb[2])), true
}

// OklchToHex converts OKLCH to sRGB hex. It is the Go twin of oklchToHex()
// in src/lib/oklch.ts.
func OklchToHex(L, C, H float64) SrgbResult {
	return OklchToSrgb(Oklch{L: L, C: C, H: H})
}

// MaxChroma returns the largest chroma at this L/H that stays inside sRGB
// (bisection over [0, 0.5], ±0.001-ish after 24 iterations). It tests raw
// linear channels directly — never OklchToSrgb, which would recurse through
// its own gamut mapping. Returns 0 when even C=0 is out (L outside 0..1).
// Mirrors maxChroma() in src/lib/oklch.ts.
func MaxChroma(L, H float64) float64 {
	inGamutAt := func(c float64) bool {
		r, g, b := linearFromOklch(L, c, H)
		return inGamutEps(r, g, b)
	}
	if !inGamutAt(0) {
		return 0
	}
	lo, hi := 0.0, 0.5 // hi above any sRGB-reachable chroma
	for i := 0; i < 24; i++ {
		mid := (lo + hi) / 2
		if inGamutAt(mid) {
			lo = mid
		} else {
			hi = mid
		}
	}
	return lo
}

// hex6 matches exactly six hexadecimal digits — the canonical expanded form
// the TS hexToRgb validates against with /^[0-9a-fA-F]{6}$/.
var hex6 = regexp.MustCompile(`^[0-9a-fA-F]{6}$`)

// oklchRe mirrors the TS OKLCH_RE exactly (case-insensitive): percent-or-0..1
// lightness, bare chroma, optional-deg hue, optional /alpha (percent or 0..1).
var oklchRe = regexp.MustCompile(
	`(?i)^oklch\(\s*([\d.]+)(%)?\s+([\d.]+)\s+(-?[\d.]+)(?:deg)?\s*(?:/\s*([\d.]+)(%)?\s*)?\)$`)

// ParseOklch parses a CSS oklch() string — accepts percent or 0..1 lightness,
// optional deg suffix on the hue, optional /alpha (percent or 0..1). Hue is
// wrapped into 0..360 (-30 → 330, 390 → 30). ok=false mirrors the TS `null`
// for anything else. Mirrors parseOklch() in src/lib/oklch.ts.
func ParseOklch(input string) (p ParsedOklch, ok bool) {
	m := oklchRe.FindStringSubmatch(strings.TrimSpace(input))
	if m == nil {
		return ParsedOklch{}, false
	}
	// The regex restricts every capture to [\d.]+, so the only rejection
	// path past a match is a non-finite number (e.g. 400 digits → +Inf),
	// which strconv flags as ErrRange — the same case the TS lib rejects
	// with its Number.isFinite check.
	l, err1 := strconv.ParseFloat(m[1], 64)
	c, err2 := strconv.ParseFloat(m[3], 64)
	h, err3 := strconv.ParseFloat(m[4], 64)
	if err1 != nil || err2 != nil || err3 != nil {
		return ParsedOklch{}, false
	}
	if m[2] == "%" {
		l /= 100
	}
	alpha := 1.0
	if m[5] != "" {
		alpha, err3 = strconv.ParseFloat(m[5], 64)
		if err3 != nil {
			return ParsedOklch{}, false
		}
		if m[6] == "%" {
			alpha /= 100
		}
	}
	// Wrap hue into 0..360 exactly like ((H % 360) + 360) % 360 in TS.
	h = math.Mod(h, 360)
	if h < 0 {
		h += 360
	}
	return ParsedOklch{L: l, C: c, H: h, Alpha: alpha}, true
}

// FormatOklch serializes to modern CSS: percent lightness (1 decimal), bare
// 3-decimal chroma, deg-suffixed hue, and ` / alpha` (2 decimals) only when
// alpha < 1. Mirrors formatOklch() in src/lib/oklch.ts, whose `alpha = 1`
// destructuring default fires only for a JS `undefined`; Go callers set Alpha
// explicitly (ParseOklch always fills it — 1 when the input had no /alpha).
func FormatOklch(p ParsedOklch) string {
	base := fmt.Sprintf("oklch(%.1f%% %.3f %.1fdeg)", p.L*100, p.C, p.H)
	if p.Alpha < 1 {
		return strings.Replace(base, ")", fmt.Sprintf(" / %.2f)", p.Alpha), 1)
	}
	return base
}

Also available in 1 other language

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in several languages — the same contract, ported. Compare all languages side by side →