nexfield-contrast 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +52 -2
  2. package/cli.mjs +41 -0
  3. package/contrast.mjs +144 -0
  4. package/package.json +13 -4
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # nexfield-contrast — WCAG colour contrast checker CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Check the contrast of two colours against **WCAG 2.2** from the command line, in CI or in a design-token pipeline. Made by [Nexfield Academy](https://nexfield.academy/), an online school of UX/UI, graphic and web design.
4
+
5
+ ```bash
6
+ docker run --rm nexfield/contrast "#767676" "#ffffff"
7
+ # 4.54:1 AA text ✓ AA large ✓ AAA text ✗ AAA large ✓ UI ✓
8
+ ```
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install -g nexfield-contrast # then: contrast "#767676" white
14
+ npx nexfield-contrast "#767676" white
15
+ ```
16
+
17
+ Or with Docker: `docker run --rm nexfield/contrast "#767676" white`.
18
+
19
+ ## Usage
20
+
21
+ ```bash
22
+ docker run --rm nexfield/contrast <text colour> <background colour> [--json]
23
+ ```
24
+
25
+ - Colours: `#rgb`, `#rrggbb`, `#rrggbbaa`, `rgb()`, `hsl()` (comma or space syntax), `white`, `black`.
26
+ - Translucent colours are laid over the background before measuring.
27
+ - `--json` prints a machine-readable result.
28
+ - Exit code: `0` passes AA for normal text (4.5:1), `1` fails, `2` bad input — handy as a CI check.
29
+
30
+ ```bash
31
+ docker run --rm nexfield/contrast "rgb(0 64 255)" white --json
32
+ # {"foreground":"rgb(0 64 255)","background":"white","ratio":6.6,"aaNormal":true,...}
33
+ ```
34
+
35
+ ## Thresholds
36
+
37
+ | Check | AA | AAA |
38
+ |---|---|---|
39
+ | Normal text | 4.5:1 | 7:1 |
40
+ | Large text (24 px, or 18.66 px bold) | 3:1 | 4.5:1 |
41
+ | Icons, borders, focus rings (WCAG 1.4.11) | 3:1 | — |
42
+
43
+ The ratio is rounded down to two decimals before it is compared, so 4.49:1 never passes as 4.5:1.
44
+
45
+ ## Other tools
46
+
47
+ - [Online contrast checker](https://nexfield.academy/resources/services/contrast-checker/) with a colour picker
48
+ - [VS Code extension](https://marketplace.visualstudio.com/items?itemName=nexfield.nexfield-color-contrast): contrast on hover in CSS
49
+ - Source: [github.com/stepan-wemake/nexfield-vscode](https://github.com/stepan-wemake/nexfield-vscode) (`cli/`)
50
+
51
+ Want to learn how designers choose accessible colours? See the [UX/UI design course](https://nexfield.academy/courses/ux-ui/) at Nexfield Academy.
52
+
53
+ License: MIT
package/cli.mjs ADDED
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * nexfield/contrast: WCAG 2.2 contrast ratio of two colours from the command line.
4
+ * contrast "#767676" "#ffffff"
5
+ * contrast "rgb(0 64 255)" white --json
6
+ * Exit code 0 when the pair passes AA for normal text, 1 when it fails, 2 on bad input.
7
+ */
8
+ import { contrast, parseColor } from './contrast.mjs'
9
+
10
+ const NAMED = { white: '#ffffff', black: '#000000' }
11
+ const args = process.argv.slice(2)
12
+ const json = args.includes('--json')
13
+ const colors = args.filter((a) => !a.startsWith('--'))
14
+
15
+ if (args.includes('--help') || args.includes('-h') || colors.length !== 2) {
16
+ console.log(`Usage: contrast <text colour> <background colour> [--json]
17
+
18
+ Colours: #rgb, #rrggbb, #rrggbbaa, rgb(), hsl(), white, black.
19
+ Example: docker run --rm nexfield/contrast "#767676" "#ffffff"
20
+
21
+ Online checker: https://nexfield.academy/resources/services/contrast-checker/
22
+ Made by Nexfield Academy: https://nexfield.academy/`)
23
+ process.exit(colors.length === 2 ? 0 : 2)
24
+ }
25
+
26
+ const [fgText, bgText] = colors.map((c) => NAMED[c.toLowerCase()] ?? c)
27
+ const fg = parseColor(fgText)
28
+ const bg = parseColor(bgText)
29
+ if (!fg || !bg) {
30
+ console.error(`Cannot read colour: ${!fg ? colors[0] : colors[1]}`)
31
+ process.exit(2)
32
+ }
33
+
34
+ const v = contrast(fg, bg)
35
+ if (json) {
36
+ console.log(JSON.stringify({ foreground: colors[0], background: colors[1], ratio: Math.floor(v.ratio * 100) / 100, aaNormal: v.aaNormal, aaLarge: v.aaLarge, aaaNormal: v.aaaNormal, aaaLarge: v.aaaLarge, uiComponents: v.uiComponents }))
37
+ } else {
38
+ const m = (ok) => (ok ? '✓' : '✗')
39
+ console.log(`${v.label} AA text ${m(v.aaNormal)} AA large ${m(v.aaLarge)} AAA text ${m(v.aaaNormal)} AAA large ${m(v.aaaLarge)} UI ${m(v.uiComponents)}`)
40
+ }
41
+ process.exit(v.aaNormal ? 0 : 1)
package/contrast.mjs ADDED
@@ -0,0 +1,144 @@
1
+ // Generated from nexfield-vscode/src/contrast.ts (tsc, ES2020 module). Edit the source there.
2
+ /**
3
+ * Colour parsing and WCAG 2.x contrast maths. Pure: no VS Code API here, so
4
+ * the tests run on plain Node.
5
+ *
6
+ * Contrast ratio = (L1 + 0.05) / (L2 + 0.05), where L is the relative
7
+ * luminance of the lighter (L1) and darker (L2) colour, per WCAG 2.2 §1.4.3,
8
+ * §1.4.6 and §1.4.11. Thresholds are inclusive (4.5:1 passes AA), as the
9
+ * specification words them ("at least").
10
+ */
11
+ const clamp = (v, min, max) => Math.min(max, Math.max(min, v));
12
+ /** `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa` → colour; anything else → null. */
13
+ export function parseHex(text) {
14
+ const m = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(text.trim());
15
+ if (!m)
16
+ return null;
17
+ let hex = m[1];
18
+ if (hex.length <= 4)
19
+ hex = [...hex].map((c) => c + c).join('');
20
+ const n = (i) => parseInt(hex.slice(i, i + 2), 16);
21
+ return { r: n(0), g: n(2), b: n(4), a: hex.length === 8 ? n(6) / 255 : 1 };
22
+ }
23
+ function parseChannel(token, max) {
24
+ const t = token.trim();
25
+ if (t.endsWith('%')) {
26
+ const v = Number(t.slice(0, -1));
27
+ return Number.isFinite(v) ? clamp((v / 100) * max, 0, max) : null;
28
+ }
29
+ const v = Number(t);
30
+ return Number.isFinite(v) ? clamp(v, 0, max) : null;
31
+ }
32
+ function parseAlpha(token) {
33
+ if (token === undefined)
34
+ return 1;
35
+ return parseChannel(token, 1);
36
+ }
37
+ /** Splits `rgb(1 2 3 / 50%)` and `rgb(1, 2, 3, .5)` into channel tokens. */
38
+ function splitArgs(inner) {
39
+ const [main, slashAlpha] = inner.split('/');
40
+ const parts = main.split(/[\s,]+/).filter(Boolean);
41
+ if (slashAlpha !== undefined)
42
+ parts.push(slashAlpha.trim());
43
+ return parts;
44
+ }
45
+ /** `rgb()` / `rgba()` in legacy (commas) or modern (spaces, `/ alpha`) syntax. */
46
+ export function parseRgbFunction(text) {
47
+ const m = /^rgba?\(\s*([^)]*)\)$/i.exec(text.trim());
48
+ if (!m)
49
+ return null;
50
+ const parts = splitArgs(m[1]);
51
+ if (parts.length !== 3 && parts.length !== 4)
52
+ return null;
53
+ const [r, g, b] = parts.slice(0, 3).map((p) => parseChannel(p, 255));
54
+ const a = parseAlpha(parts[3]);
55
+ if (r === null || g === null || b === null || a === null)
56
+ return null;
57
+ return { r: Math.round(r), g: Math.round(g), b: Math.round(b), a };
58
+ }
59
+ /** `hsl()` / `hsla()`; hue in degrees (unit optional), saturation and lightness in %. */
60
+ export function parseHslFunction(text) {
61
+ const m = /^hsla?\(\s*([^)]*)\)$/i.exec(text.trim());
62
+ if (!m)
63
+ return null;
64
+ const parts = splitArgs(m[1]);
65
+ if (parts.length !== 3 && parts.length !== 4)
66
+ return null;
67
+ const h = Number(parts[0].replace(/deg$/i, ''));
68
+ const s = parseChannel(parts[1].endsWith('%') ? parts[1] : `${parts[1]}%`, 1);
69
+ const l = parseChannel(parts[2].endsWith('%') ? parts[2] : `${parts[2]}%`, 1);
70
+ const a = parseAlpha(parts[3]);
71
+ if (!Number.isFinite(h) || s === null || l === null || a === null)
72
+ return null;
73
+ const hue = ((h % 360) + 360) % 360;
74
+ const k = (n) => (n + hue / 30) % 12;
75
+ const f = (n) => l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
76
+ return { r: Math.round(f(0) * 255), g: Math.round(f(8) * 255), b: Math.round(f(4) * 255), a };
77
+ }
78
+ /** Any supported colour notation → colour, else null. */
79
+ export function parseColor(text) {
80
+ return parseHex(text) ?? parseRgbFunction(text) ?? parseHslFunction(text);
81
+ }
82
+ const COLOR_RE = /#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})\b|\b(?:rgba?|hsla?)\([^()]*\)/gi;
83
+ /** Every colour literal in a line of text, in order. */
84
+ export function findColors(line) {
85
+ const out = [];
86
+ for (const m of line.matchAll(COLOR_RE)) {
87
+ const start = m.index ?? 0;
88
+ // `#abc` inside a word or URL fragment (`page#top`) is not a colour.
89
+ if (m[0].startsWith('#') && start > 0 && /[\w&]/.test(line[start - 1]))
90
+ continue;
91
+ const color = parseColor(m[0]);
92
+ if (color)
93
+ out.push({ text: m[0], start, end: start + m[0].length, color });
94
+ }
95
+ return out;
96
+ }
97
+ /** A translucent colour painted over an opaque background. */
98
+ export function flatten(color, background) {
99
+ const a = color.a;
100
+ return {
101
+ r: Math.round(color.r * a + background.r * (1 - a)),
102
+ g: Math.round(color.g * a + background.g * (1 - a)),
103
+ b: Math.round(color.b * a + background.b * (1 - a)),
104
+ a: 1,
105
+ };
106
+ }
107
+ /** WCAG relative luminance of an opaque colour. */
108
+ export function luminance({ r, g, b }) {
109
+ const ch = (v) => {
110
+ const c = v / 255;
111
+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
112
+ };
113
+ return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b);
114
+ }
115
+ export function formatRatio(ratio) {
116
+ return `${(Math.floor(ratio * 100) / 100).toFixed(2).replace(/\.?0+$/, '')}:1`;
117
+ }
118
+ /**
119
+ * Contrast of a foreground on a background. A translucent background is
120
+ * first laid over white, a translucent foreground over that background.
121
+ */
122
+ export function contrast(foreground, background) {
123
+ const white = { r: 255, g: 255, b: 255, a: 1 };
124
+ const bg = background.a < 1 ? flatten(background, white) : background;
125
+ const fg = foreground.a < 1 ? flatten(foreground, bg) : foreground;
126
+ const l1 = luminance(fg);
127
+ const l2 = luminance(bg);
128
+ const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
129
+ // Floor to two decimals before comparing, so 4.499 never passes as «4.5».
130
+ const r = Math.floor(ratio * 100) / 100;
131
+ return {
132
+ ratio,
133
+ label: formatRatio(ratio),
134
+ aaNormal: r >= 4.5,
135
+ aaLarge: r >= 3,
136
+ aaaNormal: r >= 7,
137
+ aaaLarge: r >= 4.5,
138
+ uiComponents: r >= 3,
139
+ };
140
+ }
141
+ /** `#rrggbb` (alpha dropped) for display. */
142
+ export function toHex({ r, g, b }) {
143
+ return `#${[r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('')}`;
144
+ }
package/package.json CHANGED
@@ -1,6 +1,15 @@
1
1
  {
2
2
  "name": "nexfield-contrast",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "WCAG 2.2 colour contrast checker for the command line: ratio, AA/AAA, JSON output and CI exit codes. By Nexfield Academy.",
5
+ "type": "module",
6
+ "bin": { "contrast": "cli.mjs" },
7
+ "files": ["cli.mjs", "contrast.mjs", "README.md"],
8
+ "keywords": ["wcag", "contrast", "accessibility", "a11y", "color", "cli", "design"],
9
+ "author": "Nexfield Academy (https://nexfield.academy/)",
10
+ "homepage": "https://nexfield.academy/resources/services/contrast-checker/",
11
+ "repository": { "type": "git", "url": "git+https://github.com/stepan-wemake/nexfield-vscode.git", "directory": "cli" },
12
+ "bugs": { "url": "https://github.com/stepan-wemake/nexfield-vscode/issues" },
13
+ "license": "MIT",
14
+ "engines": { "node": ">=18" }
15
+ }