Skip to content

Color-Blindness Simulator — Go source

See your palette through protanopia, deuteranopia, tritanopia, or achromatopsia at any severity. Simulated swatches sit beside the originals, and a contrast checker reports whether your text pair still passes WCAG AA after simulation.

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

// Package colorblindnesssimulator is the Go twin of CosmoDev's
// src/lib/color-blindness.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 color-blindness-simulator_test.go share vectors with
// src/lib/color-blindness.test.ts so the two implementations are held to the
// same contract.
//
// Viénot/Brettel-style dichromacy matrices are applied in LINEAR sRGB: each
// channel is linearized (toLinear, 0.04045 cutoff), transformed by the kind's
// matrix, blended with the original linear channel by severity (0 = identity,
// 1 = full dichromacy), gamma-encoded (toGamma), clamped AFTER gamma, and
// rounded back to 8 bits. The achromatopsia path is the luminance-only
// matrix. ContrastAfterSimulation recomputes WCAG relative luminance before
// and after simulation so callers can flag pairs that fail the WCAG AA
// 4.5:1 body-text threshold only under simulation. The hexToRgb / rgbToHex /
// relativeLuminance helpers are ported LOCALLY from src/lib/colorConvert.ts
// (twins never import other twin packages). Note: relativeLuminance keeps
// colorConvert's WCAG 2.x 0.03928 cutoff while the simulation path keeps
// color-blindness's 0.04045 cutoff, exactly as in the TS sources.
package colorblindnesssimulator

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

// CvdKind identifies a color-vision-deficiency simulation mode. It is a plain
// string type so the four constants below are usable anywhere a string is
// expected — mirroring the CvdKind union in src/lib/color-blindness.ts.
type CvdKind string

const (
	// KindProtanopia — no red response ("Protanopia (no red)").
	KindProtanopia CvdKind = "protanopia"
	// KindDeuteranopia — no green response ("Deuteranopia (no green)").
	KindDeuteranopia CvdKind = "deuteranopia"
	// KindTritanopia — no blue response ("Tritanopia (no blue)").
	KindTritanopia CvdKind = "tritanopia"
	// KindAchromatopsia — no color vision at all ("Achromatopsia (no color)").
	KindAchromatopsia CvdKind = "achromatopsia"
)

// matrix3 is a 3x3 row-major linear-RGB transform, matching Matrix3 in the TS lib.
type matrix3 = [3][3]float64

// The Viénot/Brettel-style dichromacy matrices, VERBATIM from
// src/lib/color-blindness.ts. Each row sums to ~1 so grays are fixed points.
var (
	protan = matrix3{
		{0.152286, 1.052583, -0.204868},
		{0.114503, 0.786281, 0.099216},
		{-0.003882, -0.048116, 1.051998},
	}
	deutan = matrix3{
		{0.367322, 0.860646, -0.227968},
		{0.280085, 0.672501, 0.047413},
		{-0.01182, 0.04294, 0.968881},
	}
	tritan = matrix3{
		{1.255528, -0.076749, -0.178779},
		{-0.078411, 0.930809, 0.147602},
		{0.004733, 0.691367, 0.3039},
	}
	achroma = matrix3{
		{0.2126, 0.7152, 0.0722},
		{0.2126, 0.7152, 0.0722},
		{0.2126, 0.7152, 0.0722},
	}
)

// matrices maps each kind to its matrix, mirroring MATRICES in the TS lib.
// An unknown kind is not in this map — SimulateColor reports !ok for it
// (the TS lookup would yield undefined and throw; Go never panics).
var matrices = map[CvdKind]matrix3{
	KindProtanopia:    protan,
	KindDeuteranopia:  deutan,
	KindTritanopia:    tritan,
	KindAchromatopsia: achroma,
}

// 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}$`)

// toLinear linearizes one normalized sRGB channel (sRGB transfer function,
// 0.04045 cutoff). Mirrors toLinear() in src/lib/color-blindness.ts.
func toLinear(c float64) float64 {
	if c <= 0.04045 {
		return c / 12.92
	}
	return math.Pow((c+0.055)/1.055, 2.4)
}

// toGamma re-encodes one normalized linear channel (sRGB transfer function,
// 0.0031308 cutoff). Mirrors toGamma() in src/lib/color-blindness.ts.
func toGamma(c float64) float64 {
	if c <= 0.0031308 {
		return 12.92 * c
	}
	return 1.055*math.Pow(c, 1/2.4) - 0.055
}

// clamp01 clamps a ratio to [0,1], mirroring clamp01() in the TS lib.
func clamp01(x float64) float64 {
	if x < 0 {
		return 0
	}
	if x > 1 {
		return 1
	}
	return x
}

// hexToRgb parses `#rgb` / `#rrggbb` (case-insensitive, `#` optional) into
// 8-bit channels. ok is false (with a zero [3]uint8) for unparseable input —
// mirroring hexToRgb()'s `null` in src/lib/colorConvert.ts. Ported LOCALLY
// from colorConvert.ts: twins never import other twin packages.
func hexToRgb(hex string) ([3]uint8, bool) {
	h := strings.TrimPrefix(strings.TrimSpace(hex), "#")
	if len(h) == 3 {
		// Expand a 3-digit shorthand by doubling each digit (e.g. "0f0" →
		// "00ff00"). h may be non-ASCII here, but any non-hex byte fails the
		// hex6 check below, so byte indexing agrees with the TS result.
		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 formats 8-bit channels as a lowercase zero-padded `#rrggbb`,
// mirroring rgbToHex() in src/lib/colorConvert.ts. The inputs are already
// clamped bytes, so colorConvert's clampInt(…, 0, 255) is a no-op here.
func rgbToHex(r, g, b uint8) string {
	return fmt.Sprintf("#%02x%02x%02x", r, g, b)
}

// srgbChannel linearizes one 8-bit sRGB channel per the WCAG 2.x transfer
// function (0.03928 cutoff). Mirrors the private srgbChannel() helper in
// src/lib/colorConvert.ts.
func srgbChannel(c uint8) float64 {
	s := float64(c) / 255
	if s <= 0.03928 {
		return s / 12.92
	}
	return math.Pow((s+0.055)/1.055, 2.4)
}

// relativeLuminance returns the WCAG 2.x relative luminance of a hex color in
// [0,1] (0 = black, 1 = white). ok is false (with 0) for invalid hex —
// mirroring relativeLuminance()'s `null` in src/lib/colorConvert.ts. Ported
// LOCALLY from colorConvert.ts.
func relativeLuminance(hex string) (float64, bool) {
	rgb, ok := hexToRgb(hex)
	if !ok {
		return 0, false
	}
	return 0.2126*srgbChannel(rgb[0]) + 0.7152*srgbChannel(rgb[1]) + 0.0722*srgbChannel(rgb[2]), true
}

// SimulateColor simulates one hex color under a CVD kind at severity 0..1
// (1 = full dichromacy; 0 = identity), exactly like simulateColor() in
// src/lib/color-blindness.ts. ok is false (with "") for invalid hex or an
// unknown kind — mirroring the TS `null` result (an unknown kind would throw
// in TS; Go returns the zero value instead of panicking).
func SimulateColor(hex string, kind CvdKind, severity float64) (string, bool) {
	rgb, ok := hexToRgb(hex)
	if !ok {
		return "", false
	}
	m, known := matrices[kind]
	if !known {
		return "", false
	}
	s := clamp01(severity)

	var lin [3]float64
	for i, v := range rgb {
		lin[i] = toLinear(float64(v) / 255)
	}

	var out [3]uint8
	for row := 0; row < 3; row++ {
		simulated := m[row][0]*lin[0] + m[row][1]*lin[1] + m[row][2]*lin[2]
		blended := (1-s)*lin[row] + s*simulated
		out[row] = uint8(math.Round(clamp01(toGamma(blended)) * 255))
	}
	return rgbToHex(out[0], out[1], out[2]), true
}

// SimulatePalette simulates each palette entry, passing unknown strings
// through unchanged at their original index — exactly like simulatePalette()
// in the TS lib.
func SimulatePalette(hexes []string, kind CvdKind, severity float64) []string {
	out := make([]string, len(hexes))
	for i, h := range hexes {
		if sim, ok := SimulateColor(h, kind, severity); ok {
			out[i] = sim
		} else {
			out[i] = h
		}
	}
	return out
}

// PairCheck holds the WCAG contrast ratio of a foreground/background pair
// BEFORE and AFTER simulation plus the AA verdict, mirroring the TS
// PairCheck interface. PassesAaAfterSimulation applies the WCAG AA
// body-text threshold (simulated ratio >= 4.5).
type PairCheck struct {
	OriginalRatio           float64
	SimulatedRatio          float64
	PassesAaAfterSimulation bool
}

// ContrastAfterSimulation returns the WCAG contrast ratio of the pair before
// and after simulation — the Go twin of contrastAfterSimulation() in
// src/lib/color-blindness.ts. ok is false (with the zero PairCheck) when
// either color is invalid or the kind is unknown, mirroring the TS `null`.
func ContrastAfterSimulation(fgHex, bgHex string, kind CvdKind, severity float64) (PairCheck, bool) {
	lo, okFg := relativeLuminance(fgHex)
	bo, okBg := relativeLuminance(bgHex)
	if !okFg || !okBg {
		return PairCheck{}, false
	}
	// Valid inputs (above) imply valid simulations — SimulateColor only
	// fails on the same invalid hexes relativeLuminance already rejected
	// (plus unknown kinds, which are rejected here too).
	simFg, okSimFg := SimulateColor(fgHex, kind, severity)
	simBg, okSimBg := SimulateColor(bgHex, kind, severity)
	if !okSimFg || !okSimBg {
		return PairCheck{}, false
	}
	ls, _ := relativeLuminance(simFg)
	bs, _ := relativeLuminance(simBg)

	ratio := func(a, b float64) float64 {
		if a < b {
			a, b = b, a
		}
		return (a + 0.05) / (b + 0.05)
	}
	originalRatio := ratio(lo, bo)
	simulatedRatio := ratio(ls, bs)
	return PairCheck{
		OriginalRatio:           originalRatio,
		SimulatedRatio:          simulatedRatio,
		PassesAaAfterSimulation: simulatedRatio >= 4.5,
	}, true
}

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 →