showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
contrast_test.go
6.3 KB · 228 lines
1package web23import (4 "fmt"5 "math"6 "regexp"7 "strconv"8 "strings"9 "testing"10)1112// TestContrast checks that text tokens meet WCAG AA (4.5:1) on the layers13// they sit on, in every palette. It reads the tokens from style.css: saturn's14// moss values from `html {`, each `[data-theme]` override, then the derived15// daum.dev tokens in part 2's `:root {`, and evaluates their color-mix()16// chains in OKLab like a browser does. Run with -v to print the ratios.17func TestContrast(t *testing.T) {18 css, err := FS.ReadFile("static/style.css")19 if err != nil {20 t.Fatal(err)21 }22 s := string(css)23 part2 := strings.Index(s, "part 2: daum.dev only")24 if part2 < 0 {25 t.Fatal("no part 2 marker in style.css")26 }27 base := block(t, s, "\nhtml {")28 derived := block(t, s[part2:], ":root {")2930 pairs := []struct{ fg, bg string }{31 {"--text-headings", "--page"}, {"--text-headings", "--box"}, {"--text-headings", "--box-head"}, {"--text-headings", "--hover"},32 {"--body-text", "--page"}, {"--body-text", "--box"}, {"--body-text", "--box-head"}, {"--body-text", "--hover"},33 {"--text-secondary", "--page"}, {"--text-secondary", "--box"}, {"--text-secondary", "--box-head"},34 {"--text-secondary", "--hover"},35 {"--accent-bright", "--page"}, {"--accent-bright", "--box"}, {"--accent-bright", "--box-head"}, {"--accent-bright", "--hover"},36 {"--accent", "--page"}, {"--background-dark", "--accent"},37 {"--syn-constant", "--box"}, {"--add", "--box"}, {"--del", "--box"},38 {"--add", "--sig"}, {"--text-secondary", "--sig"}, {"--text-headings", "--sig"},39 }40 var report strings.Builder41 fmt.Fprintf(&report, "%-18s %-18s", "text", "on")42 themes := []string{"moss", "ink", "wine", "plum", "teal", "flexoki"}43 for _, th := range themes {44 fmt.Fprintf(&report, " %7s", th)45 }46 report.WriteString("\n")47 for _, p := range pairs {48 fmt.Fprintf(&report, "%-18s %-18s", p.fg, p.bg)49 for _, th := range themes {50 vars := map[string]string{}51 for k, v := range base {52 vars[k] = v53 }54 if th != "moss" {55 for k, v := range block(t, s, `[data-theme="`+th+`"] {`) {56 vars[k] = v57 }58 }59 for k, v := range derived {60 vars[k] = v61 }62 r := ratio(eval(t, vars, "var("+p.fg+")"), eval(t, vars, "var("+p.bg+")"))63 fmt.Fprintf(&report, " %7.2f", r)64 if r < 4.5 {65 t.Errorf("%s: %s on %s is %.2f:1, below 4.5:1", th, p.fg, p.bg, r)66 }67 }68 report.WriteString("\n")69 }70 t.Log("contrast ratios\n" + report.String())71}7273var declRe = regexp.MustCompile(`(--[\w-]+)\s*:\s*([^;]+);`)7475// block returns the custom properties declared in the first rule that76// starts with head.77func block(t *testing.T, s, head string) map[string]string {78 t.Helper()79 i := strings.Index(s, head)80 if i < 0 {81 t.Fatalf("style.css has no %q block", head)82 }83 body := s[i+len(head):]84 body = body[:strings.Index(body, "}")]85 vars := map[string]string{}86 for _, m := range declRe.FindAllStringSubmatch(body, -1) {87 vars[m[1]] = strings.TrimSpace(m[2])88 }89 return vars90}9192type rgb [3]float64 // sRGB, 0..19394// eval resolves a colour expression: var(), #hex, black, white and95// color-mix(in oklab, …).96func eval(t *testing.T, vars map[string]string, e string) rgb {97 t.Helper()98 e = strings.TrimSpace(e)99 switch {100 case strings.HasPrefix(e, "var("):101 name := strings.TrimSuffix(strings.TrimPrefix(e, "var("), ")")102 v, ok := vars[name]103 if !ok {104 t.Fatalf("unknown token %s", name)105 }106 return eval(t, vars, v)107 case strings.HasPrefix(e, "#") && len(e) == 7:108 var c rgb109 for i := range c {110 n, _ := strconv.ParseUint(e[1+2*i:3+2*i], 16, 8)111 c[i] = float64(n) / 255112 }113 return c114 case e == "black":115 return rgb{}116 case e == "white":117 return rgb{1, 1, 1}118 case strings.HasPrefix(e, "color-mix(in oklab,"):119 args := split(e[len("color-mix(in oklab,") : len(e)-1])120 if len(args) != 2 {121 t.Fatalf("color-mix needs two colours: %s", e)122 }123 ca, pa := percent(args[0])124 cb, pb := percent(args[1])125 switch {126 case pa < 0 && pb < 0:127 pa, pb = 50, 50128 case pa < 0:129 pa = 100 - pb130 case pb < 0:131 pb = 100 - pa132 }133 if pa+pb != 100 {134 t.Fatalf("color-mix percentages must add to 100 here: %s", e)135 }136 a, b := oklab(eval(t, vars, ca)), oklab(eval(t, vars, cb))137 var m [3]float64138 for i := range m {139 m[i] = a[i]*pa/100 + b[i]*pb/100140 }141 return fromOklab(m)142 }143 t.Fatalf("can't evaluate colour %q", e)144 return rgb{}145}146147// split cuts at top-level commas.148func split(s string) []string {149 var out []string150 depth, start := 0, 0151 for i, r := range s {152 switch r {153 case '(':154 depth++155 case ')':156 depth--157 case ',':158 if depth == 0 {159 out = append(out, s[start:i])160 start = i + 1161 }162 }163 }164 return append(out, s[start:])165}166167// percent splits "var(--x) 40%" into the colour and 40, or -1 if absent.168func percent(s string) (string, float64) {169 s = strings.TrimSpace(s)170 if i := strings.LastIndex(s, " "); i > 0 && strings.HasSuffix(s, "%") && !strings.Contains(s[i:], ")") {171 p, err := strconv.ParseFloat(s[i+1:len(s)-1], 64)172 if err == nil {173 return strings.TrimSpace(s[:i]), p174 }175 }176 return s, -1177}178179func lin(c float64) float64 {180 if c <= 0.04045 {181 return c / 12.92182 }183 return math.Pow((c+0.055)/1.055, 2.4)184}185186func gam(c float64) float64 {187 c = math.Max(0, math.Min(1, c))188 if c <= 0.0031308 {189 return c * 12.92190 }191 return 1.055*math.Pow(c, 1/2.4) - 0.055192}193194// oklab and fromOklab follow Björn Ottosson's reference matrices.195func oklab(c rgb) [3]float64 {196 r, g, b := lin(c[0]), lin(c[1]), lin(c[2])197 l := math.Cbrt(0.4122214708*r + 0.5363325363*g + 0.0514459929*b)198 m := math.Cbrt(0.2119034982*r + 0.6806995451*g + 0.1073969566*b)199 s := math.Cbrt(0.0883024619*r + 0.2817188376*g + 0.6299787005*b)200 return [3]float64{201 0.2104542553*l + 0.7936177850*m - 0.0040720468*s,202 1.9779984951*l - 2.4285922050*m + 0.4505937099*s,203 0.0259040371*l + 0.7827717662*m - 0.8086757660*s,204 }205}206207func fromOklab(c [3]float64) rgb {208 l := math.Pow(c[0]+0.3963377774*c[1]+0.2158037573*c[2], 3)209 m := math.Pow(c[0]-0.1055613458*c[1]-0.0638541728*c[2], 3)210 s := math.Pow(c[0]-0.0894841775*c[1]-1.2914855480*c[2], 3)211 return rgb{212 gam(4.0767416621*l - 3.3077115913*m + 0.2309699292*s),213 gam(-1.2684380046*l + 2.6097574011*m - 0.3413193965*s),214 gam(-0.0041960863*l - 0.7034186147*m + 1.7076147010*s),215 }216}217218func luminance(c rgb) float64 {219 return 0.2126*lin(c[0]) + 0.7152*lin(c[1]) + 0.0722*lin(c[2])220}221222func ratio(a, b rgb) float64 {223 la, lb := luminance(a), luminance(b)224 if la < lb {225 la, lb = lb, la226 }227 return (la + 0.05) / (lb + 0.05)228}