~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
81 lines · 3.2 KB Raw History
// The pages' colours, held to WCAG 2.2's AA contrast (1.4.3): text and
// what it is drawn on at least 4.5:1, in light and in dark
// (spec/OAUTH-PAGES.md, "Every page"). A colour is only ever text on some
// surfaces, which web/src/lib/contrast.json names; a surface with alpha is
// drawn over --bg, as the browser would. A new colour that is text goes
// there.
//
//   node harness/contrast.mjs
//
// Prints each pair that falls short as `scheme: text on surface ratio`,
// failing if any.

import { readFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const css = readFileSync(join(root, 'web/src/tokens.css'), 'utf8')
const { pairs } = JSON.parse(readFileSync(join(root, 'web/src/lib/contrast.json'), 'utf8'))
const AA = 4.5

/// The declarations of the block opening at the first `opener`, by name.
function block(opener) {
  const at = css.indexOf(opener)
  if (at < 0) throw new Error(`tokens.css has no ${opener.trim()}`)
  let depth = 0
  let i = css.indexOf('{', at)
  const start = i
  for (; i < css.length; i++) {
    if (css[i] === '{') depth++
    else if (css[i] === '}' && --depth === 0) break
  }
  const body = css.slice(start, i)
  return Object.fromEntries([...body.matchAll(/^\s*--([\w-]+):\s*([^;]+);/gm)].map((m) => [m[1], m[2].trim()]))
}

const light = block(':root {')
const dark = { ...light, ...block('@media (prefers-color-scheme: dark) {') }

function colour(env, value) {
  value = value.trim()
  let m
  if ((m = value.match(/^var\(--([\w-]+)\)$/))) {
    if (!(m[1] in env)) throw new Error(`no token --${m[1]}`)
    return colour(env, env[m[1]])
  }
  if ((m = value.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i))) {
    const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join('') : m[1]
    return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)).concat(1)
  }
  if ((m = value.match(/^rgb\((\d+) (\d+) (\d+)(?: \/ ([\d.]+))?\)$/))) return [+m[1], +m[2], +m[3], m[4] === undefined ? 1 : +m[4]]
  throw new Error(`cannot read ${value}`)
}

const over = (top, under) => [0, 1, 2].map((i) => top[i] * top[3] + under[i] * (1 - top[3])).concat(1)
const luminance = ([r, g, b]) => {
  const [lr, lg, lb] = [r, g, b].map((c) => ((c /= 255) <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4))
  return 0.2126 * lr + 0.7152 * lg + 0.0722 * lb
}
const ratio = (a, b) => {
  const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p)
  return (x + 0.05) / (y + 0.05)
}

const problems = []
let n = 0
for (const [scheme, env] of Object.entries({ light, dark })) {
  const bg = colour(env, 'var(--bg)')
  for (const { texts, on } of pairs)
    for (const text of texts)
      for (const surface of on) {
        n++
        const under = over(colour(env, `var(--${surface})`), bg)
        const r = ratio(over(colour(env, `var(--${text})`), under), under)
        if (r < AA) problems.push(`${scheme}: --${text} on --${surface} ${r.toFixed(2)}:1, under ${AA}:1`)
      }
}

for (const p of problems) console.log(p)
if (problems.length) process.exit(1)
console.log(`contrast: light and dark, ${n} pairs, every text at least ${AA}:1 on what it is drawn on`)