cornfield 0.25.0 → 0.26.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.
- package/core/color.js +177 -0
- package/core/config.js +2 -2
- package/core/contrast.js +599 -0
- package/core/theme.js +5 -3
- package/core/validate.js +5 -1
- package/explorer/explorer.css +9 -8
- package/explorer/theme-model.js +6 -23
- package/explorer/tokens.css +14 -9
- package/package.json +1 -1
- package/server/server.js +1 -1
package/core/color.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module core/color
|
|
3
|
+
*
|
|
4
|
+
* Colour arithmetic with no dependencies and no Node built-ins, so the explorer (served from core/, see
|
|
5
|
+
* server/server.js BROWSER_CORE), `cornfield validate` (core/contrast.js) and the tests all share one implementation.
|
|
6
|
+
*
|
|
7
|
+
* parseColor(css) a literal CSS colour as [r, g, b, a] (0..255, alpha 0..1); transparent for anything it cannot read
|
|
8
|
+
* readColor(css) the same, or null when it is not a colour this file reads (so a caller can tell "unknown" from "transparent")
|
|
9
|
+
* luminance([r,g,b]) WCAG relative luminance
|
|
10
|
+
* ratio(la, lb) the WCAG contrast ratio of two luminances
|
|
11
|
+
* contrast(a, b) the WCAG contrast ratio of two CSS colours (alpha ignored)
|
|
12
|
+
* mixColors(a, pa, b, pb) `color-mix(in srgb, …)` of two [r,g,b,a]
|
|
13
|
+
* over(fg, bg) a translucent colour composited over an opaque one: opaque [r,g,b,1], channels rounded
|
|
14
|
+
* toHex([r,g,b]) '#rrggbb'
|
|
15
|
+
*
|
|
16
|
+
* Read: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` / `rgba()` and `hsl()` / `hsla()` (comma or space syntax, an optional `/ alpha`,
|
|
17
|
+
* percentages), `transparent`, the basic colour names, and `color-mix(in srgb, A p%, B [p%])` (of any of these, nested). Anything else
|
|
18
|
+
* (`oklch()`, `var()`, `calc()`, `currentcolor`, `auto`) is not read, nor a `color-mix()` nested more than MAX_MIX_DEPTH deep, nor text over MAX_COLOR_CHARS.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const NAMED = Object.freeze({
|
|
22
|
+
black: '#000000', white: '#ffffff', red: '#ff0000', lime: '#00ff00', blue: '#0000ff', yellow: '#ffff00', cyan: '#00ffff', aqua: '#00ffff',
|
|
23
|
+
magenta: '#ff00ff', fuchsia: '#ff00ff', gray: '#808080', grey: '#808080', silver: '#c0c0c0', maroon: '#800000', olive: '#808000',
|
|
24
|
+
green: '#008000', purple: '#800080', teal: '#008080', navy: '#000080', orange: '#ffa500',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/** How deep `color-mix()` may nest: deeper is not read (a hostile stylesheet cannot make the parser crawl or overflow the stack) */
|
|
28
|
+
export const MAX_MIX_DEPTH = 8;
|
|
29
|
+
/** The longest text read as a colour; longer is not a colour this file reads */
|
|
30
|
+
export const MAX_COLOR_CHARS = 4096;
|
|
31
|
+
|
|
32
|
+
const NUM = '[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?';
|
|
33
|
+
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
|
|
34
|
+
|
|
35
|
+
/** The text between the outer parentheses of `name(...)` if `s` is exactly one such call, else null */
|
|
36
|
+
function callArgs(s, name) {
|
|
37
|
+
const m = new RegExp(`^${name}\\(`, 'i').exec(s);
|
|
38
|
+
if (!m || !s.endsWith(')')) return null;
|
|
39
|
+
let depth = 0;
|
|
40
|
+
for (let i = m[0].length - 1; i < s.length; i++) {
|
|
41
|
+
if (s[i] === '(') depth++;
|
|
42
|
+
else if (s[i] === ')' && --depth === 0 && i !== s.length - 1) return null;
|
|
43
|
+
}
|
|
44
|
+
return depth === 0 ? s.slice(m[0].length, -1) : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Split at the top level (outside parentheses) on a separator character */
|
|
48
|
+
export function splitTop(s, sep) {
|
|
49
|
+
const out = [];
|
|
50
|
+
let depth = 0;
|
|
51
|
+
let from = 0;
|
|
52
|
+
for (let i = 0; i < s.length; i++) {
|
|
53
|
+
if (s[i] === '(') depth++;
|
|
54
|
+
else if (s[i] === ')') depth--;
|
|
55
|
+
else if (s[i] === sep && depth === 0) { out.push(s.slice(from, i)); from = i + 1; }
|
|
56
|
+
}
|
|
57
|
+
out.push(s.slice(from));
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const channelValue = (t, scale) => {
|
|
62
|
+
const m = new RegExp(`^(${NUM})(%?)$`, 'i').exec(t);
|
|
63
|
+
return m ? (m[2] ? (Number(m[1]) / 100) * scale : Number(m[1])) : null;
|
|
64
|
+
};
|
|
65
|
+
const alphaValue = (t) => (t === undefined ? 1 : (() => { const v = channelValue(t, 1); return v === null ? null : clamp(v, 0, 1); })());
|
|
66
|
+
|
|
67
|
+
function hslToRgb(h, s, l) {
|
|
68
|
+
const k = (n) => (n + h / 30) % 12;
|
|
69
|
+
const a = s * Math.min(l, 1 - l);
|
|
70
|
+
const f = (n) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
|
|
71
|
+
return [f(0) * 255, f(8) * 255, f(4) * 255];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The arguments of rgb()/hsl(), comma or space syntax, as [a, b, c, alpha?] strings; null when the shape is wrong */
|
|
75
|
+
function fnParts(args) {
|
|
76
|
+
const parts = args.trim().split(/\s*[,/]\s*|\s+/).filter(Boolean);
|
|
77
|
+
return parts.length === 3 || parts.length === 4 ? parts : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** @returns {number[] | null} */
|
|
81
|
+
function readOne(css, depth = 0) {
|
|
82
|
+
const s = String(css).trim();
|
|
83
|
+
const lower = s.toLowerCase();
|
|
84
|
+
if (lower === 'transparent') return [0, 0, 0, 0];
|
|
85
|
+
if (NAMED[lower]) return readOne(NAMED[lower], depth);
|
|
86
|
+
let m = /^#([0-9a-f]{3,4})$/.exec(lower);
|
|
87
|
+
if (m) {
|
|
88
|
+
const c = [...m[1]].map((h) => parseInt(h + h, 16));
|
|
89
|
+
return [c[0], c[1], c[2], c.length === 4 ? c[3] / 255 : 1];
|
|
90
|
+
}
|
|
91
|
+
m = /^#([0-9a-f]{6}|[0-9a-f]{8})$/.exec(lower);
|
|
92
|
+
if (m) {
|
|
93
|
+
const h = m[1];
|
|
94
|
+
return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16), h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1];
|
|
95
|
+
}
|
|
96
|
+
const rgb = callArgs(lower, 'rgba?');
|
|
97
|
+
if (rgb !== null) {
|
|
98
|
+
const p = fnParts(rgb);
|
|
99
|
+
if (!p) return null;
|
|
100
|
+
const c = p.slice(0, 3).map((t) => channelValue(t, 255));
|
|
101
|
+
const a = alphaValue(p[3]);
|
|
102
|
+
return c.some((v) => v === null) || a === null ? null : [...c.map((v) => clamp(v, 0, 255)), a];
|
|
103
|
+
}
|
|
104
|
+
const hsl = callArgs(lower, 'hsla?');
|
|
105
|
+
if (hsl !== null) {
|
|
106
|
+
const p = fnParts(hsl);
|
|
107
|
+
if (!p) return null;
|
|
108
|
+
const h = new RegExp(`^(${NUM})(?:deg)?$`).exec(p[0]);
|
|
109
|
+
const sat = /%$/.test(p[1]) ? channelValue(p[1], 1) : null;
|
|
110
|
+
const lig = /%$/.test(p[2]) ? channelValue(p[2], 1) : null;
|
|
111
|
+
const a = alphaValue(p[3]);
|
|
112
|
+
if (!h || sat === null || lig === null || a === null) return null;
|
|
113
|
+
return [...hslToRgb(((Number(h[1]) % 360) + 360) % 360, clamp(sat, 0, 1), clamp(lig, 0, 1)), a];
|
|
114
|
+
}
|
|
115
|
+
const mix = depth < MAX_MIX_DEPTH ? callArgs(lower, 'color-mix') : null;
|
|
116
|
+
if (mix !== null) {
|
|
117
|
+
const parts = splitTop(mix, ',').map((t) => t.trim());
|
|
118
|
+
if (parts.length !== 3 || !/^in\s+srgb$/.test(parts[0])) return null;
|
|
119
|
+
const side = (t) => {
|
|
120
|
+
const before = /^(\d*\.?\d+)%\s+(.+)$/.exec(t);
|
|
121
|
+
const after = /^(.+?)\s+(\d*\.?\d+)%$/.exec(t);
|
|
122
|
+
const [col, pct] = before ? [before[2], before[1]] : after ? [after[1], after[2]] : [t, null];
|
|
123
|
+
const c = readOne(col, depth + 1);
|
|
124
|
+
return c && { c, p: pct === null ? null : Number(pct) / 100 };
|
|
125
|
+
};
|
|
126
|
+
const a = side(parts[1]);
|
|
127
|
+
const b = side(parts[2]);
|
|
128
|
+
if (!a || !b || (a.p !== null && (a.p < 0 || a.p > 1)) || (b.p !== null && (b.p < 0 || b.p > 1))) return null;
|
|
129
|
+
const pa = a.p ?? (b.p === null ? 0.5 : 1 - b.p);
|
|
130
|
+
const pb = b.p ?? 1 - pa;
|
|
131
|
+
if (pa + pb <= 0) return null;
|
|
132
|
+
return mixColors(a.c, pa, b.c, pb);
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** A CSS colour as `[r, g, b, a]`, or null when it is not one this file reads */
|
|
138
|
+
export function readColor(css) {
|
|
139
|
+
if (String(css).length > MAX_COLOR_CHARS) return null;
|
|
140
|
+
try { return readOne(css); } catch { return null; }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** `[r, g, b, a]` (0..255, alpha 0..1); transparent for anything that is not read. */
|
|
144
|
+
export function parseColor(css) {
|
|
145
|
+
return readColor(css) ?? [0, 0, 0, 0];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* `color-mix(in srgb, a pa, b pb)`: premultiplied, as browsers mix. Percentages that add to less than 1 scale the alpha; to more, are normalised.
|
|
150
|
+
* @param {number[]} a @param {number} pa @param {number[]} b @param {number} pb
|
|
151
|
+
*/
|
|
152
|
+
export function mixColors(a, pa, b, pb) {
|
|
153
|
+
const sum = pa + pb;
|
|
154
|
+
const [wa, wb] = [pa / sum, pb / sum];
|
|
155
|
+
const alpha = a[3] * wa + b[3] * wb;
|
|
156
|
+
const ch = (i) => (alpha === 0 ? 0 : (a[i] * a[3] * wa + b[i] * b[3] * wb) / alpha);
|
|
157
|
+
return [ch(0), ch(1), ch(2), alpha * Math.min(1, sum)];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** A colour composited over an opaque one: opaque `[r, g, b, 1]`, channels rounded to 8 bits, as a screen shows it */
|
|
161
|
+
export function over(fg, bg) {
|
|
162
|
+
const a = fg[3];
|
|
163
|
+
return [0, 1, 2].map((i) => Math.round(fg[i] * a + bg[i] * (1 - a))).concat(1);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export const toHex = ([r, g, b]) => `#${[r, g, b].map((v) => Math.round(v).toString(16).padStart(2, '0')).join('')}`;
|
|
167
|
+
|
|
168
|
+
const channel = (v) => {
|
|
169
|
+
const c = v / 255;
|
|
170
|
+
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
171
|
+
};
|
|
172
|
+
/** WCAG relative luminance of `[r, g, b]` (0..255) */
|
|
173
|
+
export const luminance = ([r, g, b]) => 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
|
|
174
|
+
export const ratio = (la, lb) => (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
|
|
175
|
+
|
|
176
|
+
/** The WCAG contrast ratio of two opaque CSS colours (alpha is ignored) */
|
|
177
|
+
export const contrast = (a, b) => ratio(luminance(parseColor(a)), luminance(parseColor(b)));
|
package/core/config.js
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
* hookPoll: { specs: '5m' }, // how often cornfield looks for ready specs and thread activity on its own, for the spec.ready and thread.* hooks; false turns it off (docs/config.md#hook-poll)
|
|
27
27
|
* threads: { label: 'idea' }, // an idea is an issue with this label, its thread the issue's comments; false turns threads off (docs/threads.md)
|
|
28
28
|
* links: [], // [{ label, href }] shown in the explorer's header
|
|
29
|
-
* theme: {}, // { css, fonts, fontHosts, names, default }: a repo's own look, CSS only (docs/config.md#theme)
|
|
29
|
+
* theme: {}, // { css, fonts, fontHosts, names, default, contrast }: a repo's own look, CSS only (docs/config.md#theme)
|
|
30
30
|
* brand: {}, // { logo, wordmark, favicon, appName, color, background }: a repo's own logo and name, images from the repo (docs/config.md#brand)
|
|
31
31
|
* proxy: {}, // { '/api/': 'http://127.0.0.1:3245' }: same-origin paths for a live source
|
|
32
32
|
* importMap: {}, // bare imports a repo-local browser module needs: { name: '/repo/path.js' }
|
|
@@ -168,7 +168,7 @@ export const DEFAULTS = Object.freeze({
|
|
|
168
168
|
hookPoll: { specs: '5m' },
|
|
169
169
|
threads: { label: 'idea' },
|
|
170
170
|
links: [],
|
|
171
|
-
theme: { css: null, fonts: [], fontHosts: [], names: {}, default: null },
|
|
171
|
+
theme: { css: null, fonts: [], fontHosts: [], names: {}, default: null, contrast: 'error' },
|
|
172
172
|
brand: { logo: null, wordmark: null, favicon: null, appName: null, color: null, background: null },
|
|
173
173
|
proxy: {},
|
|
174
174
|
importMap: {},
|
package/core/contrast.js
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module core/contrast
|
|
3
|
+
*
|
|
4
|
+
* The theme's contrast check, for `cornfield validate` (docs/theming.md#the-contrast-check). A tiny CSS custom-property resolver
|
|
5
|
+
* and the list of `--corn-*` pairs that are read against each other. No dependencies, no browser: it reads stylesheet text.
|
|
6
|
+
*
|
|
7
|
+
* resolveProps(sheets, state) the custom properties in force for a page: `{ mode, system?, name? }` over `[css, …]` in load order
|
|
8
|
+
* expand(value, props) a value with its var()s replaced, or { problem } naming the property and why (capped: never a hang)
|
|
9
|
+
* resolveColor(props, name | value) a token (or a value) as [r, g, b, a], or { problem } when it cannot be worked out
|
|
10
|
+
* contrastPairs() every pair explorer.css paints, text at 4.5:1 and the state-bearing UI at 3:1
|
|
11
|
+
* contrastProblems(themes) every pair below WCAG AA, for light and dark, on either system setting, over the ground and its image
|
|
12
|
+
* themesToCheck(config) what a repo's check reads: tokens.css, then `theme.css`, then each `theme.names` file
|
|
13
|
+
* checkThemeContrast(config) the check for `cornfield validate`, always run (cornfield's own tokens when there is no theme)
|
|
14
|
+
*
|
|
15
|
+
* What is read of a stylesheet: custom-property declarations in `:root`, `html`, `[data-theme="…"]`, `[data-theme-name="…"]` rules
|
|
16
|
+
* (with `:not()`), at the top level and inside `@media (prefers-color-scheme: light|dark)`. A rule for anything else (a class, a
|
|
17
|
+
* descendant) is not the root's and is ignored; so are other at-rules. Specificity, `!important` and source order decide, as in a browser.
|
|
18
|
+
* `var(--x, fallback)` chains are followed (a cycle is as good as unset, so its fallback is used).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { MAX_MIX_DEPTH, readColor, over, toHex, luminance, ratio, splitTop } from './color.js';
|
|
25
|
+
import { MAX_THEME_BYTES, cssProblems, withoutComments } from './theme.js';
|
|
26
|
+
|
|
27
|
+
/** WCAG 2.1 AA: text, and large text and user-interface parts */
|
|
28
|
+
export const MIN_TEXT = 4.5;
|
|
29
|
+
export const MIN_UI = 3;
|
|
30
|
+
export const CONTRAST_MODES = Object.freeze(['error', 'warn']);
|
|
31
|
+
|
|
32
|
+
/** cornfield's own token file: what a theme is applied over */
|
|
33
|
+
export const TOKENS_FILE = fileURLToPath(new URL('../explorer/tokens.css', import.meta.url));
|
|
34
|
+
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
// Stylesheet → rules
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
/** Index of the `}` that closes the block opened just before `from` (strings and nested blocks skipped), or -1 */
|
|
40
|
+
function closeOf(text, from) {
|
|
41
|
+
let depth = 1;
|
|
42
|
+
let quote = null;
|
|
43
|
+
for (let i = from; i < text.length; i++) {
|
|
44
|
+
const ch = text[i];
|
|
45
|
+
if (ch === '\\') { i++; continue; }
|
|
46
|
+
if (quote) { if (ch === quote || ch === '\n') quote = null; continue; }
|
|
47
|
+
if (ch === '"' || ch === "'") quote = ch;
|
|
48
|
+
else if (ch === '{') depth++;
|
|
49
|
+
else if (ch === '}' && --depth === 0) return i;
|
|
50
|
+
}
|
|
51
|
+
return -1;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The `--name: value` declarations at the top level of a rule's body (nested blocks skipped): [{ name, value, important }] */
|
|
55
|
+
function declarationsOf(body) {
|
|
56
|
+
const out = [];
|
|
57
|
+
let depth = 0;
|
|
58
|
+
let quote = null;
|
|
59
|
+
let from = 0;
|
|
60
|
+
const flush = (end) => {
|
|
61
|
+
const m = /^\s*(--[^\s:]+)\s*:([\s\S]*)$/.exec(body.slice(from, end));
|
|
62
|
+
if (m) {
|
|
63
|
+
const imp = /!\s*important\s*$/i.test(m[2]);
|
|
64
|
+
out.push({ name: m[1], value: m[2].replace(/!\s*important\s*$/i, '').trim(), important: imp });
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
for (let i = 0; i < body.length; i++) {
|
|
68
|
+
const ch = body[i];
|
|
69
|
+
if (ch === '\\') { i++; continue; }
|
|
70
|
+
if (quote) { if (ch === quote || ch === '\n') quote = null; continue; }
|
|
71
|
+
if (ch === '"' || ch === "'") quote = ch;
|
|
72
|
+
else if (ch === '(' || ch === '{') depth++;
|
|
73
|
+
else if (ch === ')') depth = Math.max(0, depth - 1);
|
|
74
|
+
else if (ch === '}') { depth = Math.max(0, depth - 1); if (depth === 0) from = i + 1; }
|
|
75
|
+
else if (ch === ';' && depth === 0) { flush(i); from = i + 1; }
|
|
76
|
+
}
|
|
77
|
+
flush(body.length);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The rules of a stylesheet that can set a custom property: `[{ selector, decls, media }]` in source order, `media` the condition of
|
|
83
|
+
* the `@media` it sits in (null at the top level). Other at-rules are skipped.
|
|
84
|
+
* @param {string} css
|
|
85
|
+
* @returns {{ selector: string, decls: { name: string, value: string, important: boolean }[], media: string | null }[]}
|
|
86
|
+
*/
|
|
87
|
+
export function parseRules(css) {
|
|
88
|
+
const out = [];
|
|
89
|
+
const walk = (text, media, depth) => {
|
|
90
|
+
let from = 0;
|
|
91
|
+
let i = 0;
|
|
92
|
+
let quote = null;
|
|
93
|
+
while (i < text.length) {
|
|
94
|
+
const ch = text[i];
|
|
95
|
+
if (ch === '\\') { i += 2; continue; }
|
|
96
|
+
if (quote) { if (ch === quote || ch === '\n') quote = null; i++; continue; }
|
|
97
|
+
if (ch === '"' || ch === "'") { quote = ch; i++; continue; }
|
|
98
|
+
if (ch === ';') { from = i + 1; i++; continue; } // an at-rule with no block (@import, @charset)
|
|
99
|
+
if (ch === '}') { from = i + 1; i++; continue; }
|
|
100
|
+
if (ch !== '{') { i++; continue; }
|
|
101
|
+
const end = closeOf(text, i + 1);
|
|
102
|
+
const prelude = text.slice(from, i).trim();
|
|
103
|
+
const body = text.slice(i + 1, end < 0 ? text.length : end);
|
|
104
|
+
if (/^@media\b/i.test(prelude)) { if (depth < 4) walk(body, prelude.replace(/^@media\b/i, '').trim(), depth + 1); }
|
|
105
|
+
else if (/^@layer\b/i.test(prelude) || /^@supports\b/i.test(prelude)) { if (depth < 4) walk(body, media, depth + 1); }
|
|
106
|
+
else if (prelude && !prelude.startsWith('@')) {
|
|
107
|
+
const decls = declarationsOf(body);
|
|
108
|
+
if (decls.length) out.push({ selector: prelude, decls, media });
|
|
109
|
+
}
|
|
110
|
+
if (end < 0) break;
|
|
111
|
+
i = end + 1;
|
|
112
|
+
from = i;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
walk(withoutComments(String(css), ' '), null, 0);
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// Which rules apply to the page
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
/** Whether an `@media` condition holds when the system's colour scheme is `scheme`: only `prefers-color-scheme` (and `all`, `screen`) are known */
|
|
124
|
+
function mediaMatches(cond, scheme) {
|
|
125
|
+
if (cond === null) return true;
|
|
126
|
+
return splitTop(cond, ',').some((q) => q.trim().split(/\s+and\s+/i).every((part) => {
|
|
127
|
+
const t = part.trim().toLowerCase();
|
|
128
|
+
if (t === 'all' || t === 'screen') return true;
|
|
129
|
+
const m = /^\(\s*prefers-color-scheme\s*:\s*(light|dark)\s*\)$/.exec(t);
|
|
130
|
+
return !!m && m[1] === scheme;
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Specificity as one number (ids, classes/attributes/pseudo-classes, types) */
|
|
135
|
+
const spec = (a, b, c) => a * 1e6 + b * 1e3 + c;
|
|
136
|
+
/** How deep `:not()` may nest in a selector the resolver reads; deeper, the rule is not read (it is never one a theme needs) */
|
|
137
|
+
const MAX_NOT_DEPTH = 4;
|
|
138
|
+
const maxOf = (values, floor) => values.reduce((m, v) => (v > m ? v : m), floor);
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The specificity of a compound selector on the root element, or null when it does not match the page `attrs`. A compound is
|
|
142
|
+
* `:root` / `html` / `*` with `[attr]`, `[attr="v"]` and `:not(…)` parts. A combinator, a class or any other pseudo-class is not the
|
|
143
|
+
* root's, so it never matches; nor does a compound with `:not()` nested more than MAX_NOT_DEPTH deep (it is not read).
|
|
144
|
+
* @param {string} sel
|
|
145
|
+
* @param {Record<string, string>} attrs
|
|
146
|
+
* @returns {number | null}
|
|
147
|
+
*/
|
|
148
|
+
export function matchRoot(sel, attrs) {
|
|
149
|
+
const r = matchCompound(sel, attrs, 0);
|
|
150
|
+
return r === false ? null : r;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** matchRoot's work: a specificity, null (does not match) or false (not read: too deep, so the whole rule is left out) */
|
|
154
|
+
function matchCompound(sel, attrs, depth) {
|
|
155
|
+
const s = sel.trim();
|
|
156
|
+
if (!s) return null;
|
|
157
|
+
let total = 0;
|
|
158
|
+
let i = 0;
|
|
159
|
+
while (i < s.length) {
|
|
160
|
+
let m;
|
|
161
|
+
const rest = s.slice(i, i + 256);
|
|
162
|
+
if ((m = /^:root\b/i.exec(rest))) { total += spec(0, 1, 0); i += m[0].length; }
|
|
163
|
+
else if ((m = /^html\b/i.exec(rest))) { total += spec(0, 0, 1); i += m[0].length; }
|
|
164
|
+
else if ((m = /^\*/.exec(rest))) i += 1;
|
|
165
|
+
else if ((m = /^\[\s*([\w-]+)\s*(?:=\s*(?:"([^"]*)"|'([^']*)'|([^\]\s]+))\s*(?:[is]\s*)?)?\]/i.exec(rest))) {
|
|
166
|
+
const want = m[2] ?? m[3] ?? m[4];
|
|
167
|
+
const have = attrs[m[1].toLowerCase()];
|
|
168
|
+
if (have === undefined || (want !== undefined && have !== want)) return null;
|
|
169
|
+
total += spec(0, 1, 0);
|
|
170
|
+
i += m[0].length;
|
|
171
|
+
} else if ((m = /^:not\(/i.exec(rest))) {
|
|
172
|
+
if (depth >= MAX_NOT_DEPTH) return false;
|
|
173
|
+
let level = 1;
|
|
174
|
+
let j = i + m[0].length;
|
|
175
|
+
for (; j < s.length && level; j++) { if (s[j] === '(') level++; else if (s[j] === ')') level--; }
|
|
176
|
+
if (level) return null;
|
|
177
|
+
const args = splitTop(s.slice(i + m[0].length, j - 1), ',');
|
|
178
|
+
for (const a of args) {
|
|
179
|
+
const inner = matchCompound(a, attrs, depth + 1);
|
|
180
|
+
if (inner === false) return false;
|
|
181
|
+
if (inner !== null) return null; // the argument matches, so :not() does not
|
|
182
|
+
}
|
|
183
|
+
// :not() counts as its most specific argument, matching or not
|
|
184
|
+
total += maxOf(args.map((a) => specificityOf(a)), 0);
|
|
185
|
+
i = j;
|
|
186
|
+
} else return null;
|
|
187
|
+
}
|
|
188
|
+
return total;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The specificity a compound would have, whether or not it matches (for the argument of :not()) */
|
|
192
|
+
function specificityOf(sel) {
|
|
193
|
+
let total = 0;
|
|
194
|
+
for (const _m of sel.matchAll(/:root\b|\[[^\]]*\]/gi)) total += spec(0, 1, 0);
|
|
195
|
+
if (/(^|[^\w-])html\b/i.test(sel)) total += spec(0, 0, 1);
|
|
196
|
+
return total;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The custom properties in force on <html> for a page: `mode` is the page's light or dark (`data-theme`, which theme-boot.js always
|
|
201
|
+
* sets), `system` the viewer's system setting (`prefers-color-scheme`; the same as `mode` unless the viewer picked the other one), and
|
|
202
|
+
* `name` the named theme when one is on; the stylesheets in the order the page loads them.
|
|
203
|
+
* @param {string[]} sheets
|
|
204
|
+
* @param {{ mode: 'light' | 'dark', system?: 'light' | 'dark', name?: string }} state
|
|
205
|
+
* @returns {Map<string, string>}
|
|
206
|
+
*/
|
|
207
|
+
export function resolveProps(sheets, { mode, system = mode, name } = { mode: 'dark' }) {
|
|
208
|
+
const attrs = { 'data-theme': mode };
|
|
209
|
+
if (name) attrs['data-theme-name'] = name;
|
|
210
|
+
const best = new Map(); // custom property -> { rank, value }
|
|
211
|
+
let order = 0;
|
|
212
|
+
for (const css of sheets) {
|
|
213
|
+
for (const rule of parseRules(css)) {
|
|
214
|
+
if (!mediaMatches(rule.media, system)) continue;
|
|
215
|
+
const specificity = maxOf(splitTop(rule.selector, ',').map((s) => matchRoot(s, attrs) ?? -1), -1);
|
|
216
|
+
if (specificity < 0) continue;
|
|
217
|
+
for (const d of rule.decls) {
|
|
218
|
+
const rank = [d.important ? 1 : 0, specificity, order++];
|
|
219
|
+
const had = best.get(d.name);
|
|
220
|
+
if (!had || rank[0] > had.rank[0] || (rank[0] === had.rank[0] && (rank[1] > had.rank[1] || (rank[1] === had.rank[1] && rank[2] > had.rank[2])))) best.set(d.name, { rank, value: d.value });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return new Map([...best].map(([k, v]) => [k, v.value]));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ---------------------------------------------------------------------------
|
|
228
|
+
// var() and colours
|
|
229
|
+
// ---------------------------------------------------------------------------
|
|
230
|
+
|
|
231
|
+
/** How many var()s deep a value is followed (a reference or a fallback inside a fallback), the longest a value may grow by
|
|
232
|
+
* substitution, and how many var()s one token may take to work out: past any of them the token is unresolved, never a hang */
|
|
233
|
+
export const MAX_VAR_DEPTH = 32;
|
|
234
|
+
export const MAX_VALUE_CHARS = 2048;
|
|
235
|
+
export const MAX_VAR_STEPS = 2000;
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* `value` with every `var()` replaced: `{ text }`, or `{ problem }` naming the custom property that had nothing to give and why
|
|
239
|
+
* (unset, a cycle, nested too deep, too long). A property that is unset or in a cycle is as good as unset, so a fallback is used.
|
|
240
|
+
* @param {string} value
|
|
241
|
+
* @param {Map<string, string>} props
|
|
242
|
+
* @returns {{ text: string } | { problem: string }}
|
|
243
|
+
*/
|
|
244
|
+
export function expand(value, props) {
|
|
245
|
+
return expandIn(String(value), props, [], 0, { steps: MAX_VAR_STEPS });
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const LIMIT = /more than|longer than|grows past/;
|
|
249
|
+
|
|
250
|
+
function expandIn(value, props, stack, depth, budget) {
|
|
251
|
+
const who = () => (stack.length ? stack[0] : 'the value');
|
|
252
|
+
const at = () => (stack.length > 1 ? ` (at ${stack[stack.length - 1]})` : '');
|
|
253
|
+
const fail = (problem) => ({ problem });
|
|
254
|
+
if (depth > MAX_VAR_DEPTH) return fail(`${who()}: var() is followed more than ${MAX_VAR_DEPTH} deep${at()}`);
|
|
255
|
+
if (value.length > MAX_VALUE_CHARS) return fail(`${who()}: a value is longer than ${MAX_VALUE_CHARS} characters${at()}`);
|
|
256
|
+
const re = /(?<![\w-])var\(/gi;
|
|
257
|
+
let out = '';
|
|
258
|
+
let i = 0;
|
|
259
|
+
for (let m; (m = re.exec(value)); re.lastIndex = i) {
|
|
260
|
+
if (--budget.steps < 0) return fail(`${who()}: it takes more than ${MAX_VAR_STEPS} var() substitutions to work out`);
|
|
261
|
+
let level = 1;
|
|
262
|
+
let j = m.index + m[0].length;
|
|
263
|
+
for (; j < value.length && level; j++) { if (value[j] === '(') level++; else if (value[j] === ')') level--; }
|
|
264
|
+
if (level) return fail(`${stack.length ? stack[stack.length - 1] : 'the value'}: a var() is not closed`);
|
|
265
|
+
const inner = value.slice(m.index + m[0].length, j - 1);
|
|
266
|
+
const comma = inner.indexOf(',');
|
|
267
|
+
const name = (comma < 0 ? inner : inner.slice(0, comma)).trim();
|
|
268
|
+
const fallback = comma < 0 ? null : inner.slice(comma + 1).trim();
|
|
269
|
+
let got;
|
|
270
|
+
if (!/^--[\w-]+$/.test(name)) got = fail(`${stack.length ? stack[stack.length - 1] : 'the value'}: "var(${name.slice(0, 40)})" does not name a custom property`);
|
|
271
|
+
else if (stack.includes(name)) got = fail(`${who()}: a var() cycle, ${[...stack.slice(stack.indexOf(name)), name].join(' → ')}`);
|
|
272
|
+
else if (!props.has(name)) got = fail(`${[...stack, name].join(' → ')} is not set`);
|
|
273
|
+
else got = expandIn(props.get(name), props, [...stack, name], depth + 1, budget);
|
|
274
|
+
if (got.problem && fallback !== null) {
|
|
275
|
+
const alt = expandIn(fallback, props, stack, depth + 1, budget);
|
|
276
|
+
// a fallback that cannot be worked out either: the first reason is the one to fix, unless a limit stopped the fallback
|
|
277
|
+
if (!alt.problem || LIMIT.test(alt.problem)) got = alt;
|
|
278
|
+
}
|
|
279
|
+
if (got.problem) return got;
|
|
280
|
+
out += value.slice(i, m.index) + got.text;
|
|
281
|
+
if (out.length > MAX_VALUE_CHARS) return fail(`${who()}: a value grows past ${MAX_VALUE_CHARS} characters as its var()s are replaced${at()}`);
|
|
282
|
+
i = j;
|
|
283
|
+
}
|
|
284
|
+
return { text: out + value.slice(i) };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* A value with every `var()` replaced, or null when one has nothing to give (expand() says why).
|
|
289
|
+
* @param {string} value
|
|
290
|
+
* @param {Map<string, string>} props
|
|
291
|
+
* @returns {string | null}
|
|
292
|
+
*/
|
|
293
|
+
export function substitute(value, props) {
|
|
294
|
+
const r = expand(value, props);
|
|
295
|
+
return 'text' in r ? r.text : null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** The custom property whose own value a chain of plain `var(--x)`s hands on, for saying where an unreadable colour was written */
|
|
299
|
+
function origin(props, name) {
|
|
300
|
+
let at = name;
|
|
301
|
+
for (let n = 0; n < MAX_VAR_DEPTH; n++) {
|
|
302
|
+
const m = /^var\(\s*(--[\w-]+)\s*\)$/.exec((props.get(at) || '').trim());
|
|
303
|
+
if (!m || !props.has(m[1])) break;
|
|
304
|
+
at = m[1];
|
|
305
|
+
}
|
|
306
|
+
return at;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const READS = 'hex, rgb(), hsl(), color-mix(in srgb, …), transparent and the basic colour names';
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* A token (`--corn-text`) or a value (`color-mix(…)`) as `[r, g, b, a]`, or `{ problem }` naming the custom property that could not
|
|
313
|
+
* be worked out and why: unset, a cycle (with its path), a colour syntax cornfield does not read (`oklch()`, `calc()`, `auto`), or
|
|
314
|
+
* past one of the limits above.
|
|
315
|
+
* @param {Map<string, string>} props
|
|
316
|
+
* @param {string} nameOrValue
|
|
317
|
+
* @returns {number[] | { problem: string }}
|
|
318
|
+
*/
|
|
319
|
+
export function resolveColor(props, nameOrValue) {
|
|
320
|
+
const isName = /^--[\w-]+$/.test(nameOrValue);
|
|
321
|
+
if (isName && !props.has(nameOrValue)) return { problem: `${nameOrValue} is not set` };
|
|
322
|
+
const r = expand(isName ? `var(${nameOrValue})` : nameOrValue, props);
|
|
323
|
+
if ('problem' in r) return { problem: r.problem };
|
|
324
|
+
const color = readColor(r.text);
|
|
325
|
+
if (color) return color;
|
|
326
|
+
const shown = r.text.trim().slice(0, 60) + (r.text.trim().length > 60 ? '…' : '');
|
|
327
|
+
const fn = /^([a-z-]+)\(/i.exec(r.text.trim());
|
|
328
|
+
const why = !fn ? 'that is not a colour cornfield reads'
|
|
329
|
+
: fn[1].toLowerCase() === 'color-mix' ? `that is a color-mix() cornfield cannot work out (it mixes in srgb only, colours it reads, at most ${MAX_MIX_DEPTH} deep)`
|
|
330
|
+
: `${fn[1].toLowerCase()}() is not a colour cornfield reads`;
|
|
331
|
+
if (!isName) return { problem: `${nameOrValue} is "${shown}": ${why} (it reads ${READS})` };
|
|
332
|
+
const from = origin(props, nameOrValue);
|
|
333
|
+
return { problem: `${from === nameOrValue ? nameOrValue : `${nameOrValue} → ${from}`} is "${shown}": ${why} (it reads ${READS})` };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ---------------------------------------------------------------------------
|
|
337
|
+
// The pairs
|
|
338
|
+
// ---------------------------------------------------------------------------
|
|
339
|
+
|
|
340
|
+
const SURFACES = ['--corn-surface-1', '--corn-surface-2', '--corn-surface-3'];
|
|
341
|
+
const GROUND = '--corn-ground';
|
|
342
|
+
/** A tint as explorer.css writes it: the token at a share over what is beneath */
|
|
343
|
+
const tint = (token, pct) => `color-mix(in srgb, var(${token}) ${pct}%, transparent)`;
|
|
344
|
+
/** A hue pulled toward the text colour, as explorer.css writes it for a hue that must read as text */
|
|
345
|
+
const toText = (token, pct) => `color-mix(in srgb, var(${token}) ${pct}%, var(--corn-text))`;
|
|
346
|
+
|
|
347
|
+
/** Text tokens: read on the ground and on every surface */
|
|
348
|
+
export const TEXT_TOKENS = Object.freeze(['--corn-text', '--corn-text-2', '--corn-text-3', '--corn-accent-text', '--corn-ok', '--corn-warn', '--corn-bad', '--corn-info', '--corn-added-text', '--corn-edit-text']);
|
|
349
|
+
/** The tinted backgrounds, with the text that sits on each */
|
|
350
|
+
export const SOFT_PAIRS = Object.freeze([
|
|
351
|
+
['--corn-ok', '--corn-ok-soft'], ['--corn-warn', '--corn-warn-soft'], ['--corn-bad', '--corn-bad-soft'], ['--corn-info', '--corn-info-soft'],
|
|
352
|
+
['--corn-accent-text', '--corn-accent-soft'], ['--corn-hue-orange-text', '--corn-hue-orange-soft'],
|
|
353
|
+
]);
|
|
354
|
+
/** Solid fills that carry `--corn-ground` as their text (a pressed data-flow button, a chip, the What-if toggle, the House chip) */
|
|
355
|
+
export const SOLID_FILLS = Object.freeze(['--corn-ok', '--corn-warn', '--corn-bad', '--corn-info', '--corn-hue-orange', '--corn-hue-lime', '--corn-added-text', '--corn-edit-text']);
|
|
356
|
+
/**
|
|
357
|
+
* Text that explorer.css paints on something other than a token surface: a category hue as text, or text on a tint it mixes itself.
|
|
358
|
+
* `[fg, bg, where]`, each the value explorer.css writes (test/core/contrast.test.js holds this list to explorer.css).
|
|
359
|
+
*/
|
|
360
|
+
export const PAINTED_TEXT = Object.freeze([
|
|
361
|
+
['--corn-hue-fuchsia', GROUND, 'ROM, a milestone, a link button'], ['--corn-hue-fuchsia', '--corn-surface-1', ''], ['--corn-hue-fuchsia', '--corn-surface-2', ''],
|
|
362
|
+
['--corn-hue-pink', GROUND, 'a variable'], ['--corn-hue-pink', '--corn-surface-1', ''],
|
|
363
|
+
['--corn-hue-orange', '--corn-surface-2', 'the data-flow button'],
|
|
364
|
+
[toText('--corn-hue-orange', 60), tint('--corn-hue-orange', 15), 'the data-flow button, hovered'],
|
|
365
|
+
[toText('--corn-hue-fuchsia', 60), tint('--corn-hue-fuchsia', 20), 'the ROM button'],
|
|
366
|
+
['--corn-hue-lime', tint('--corn-hue-lime', 6), 'a room on the House plan'],
|
|
367
|
+
['--corn-accent-text', tint('--corn-accent-hover', 10), 'a header link'],
|
|
368
|
+
['--corn-hue-pink', tint('--corn-hue-pink', 10), 'a header link'],
|
|
369
|
+
['--corn-edit-text', tint('--corn-edit', 10), 'a header link'],
|
|
370
|
+
['--corn-text', tint('--corn-added', 12), 'the current proposal'], ['--corn-added-text', tint('--corn-added', 12), 'the current proposal'],
|
|
371
|
+
['--corn-added-text', tint('--corn-added', 14), 'the proposals button, hovered'],
|
|
372
|
+
['--corn-added-text', tint('--corn-added', 20), 'the open proposals button, the approve button hovered'],
|
|
373
|
+
['--corn-text', tint('--corn-edit', 30), 'a What-if number'],
|
|
374
|
+
['--corn-text-2', tint('--corn-removed', 10), 'a proposal\'s errors'], ['--corn-bad', tint('--corn-removed', 10), 'a proposal\'s errors'],
|
|
375
|
+
['--corn-bad', tint('--corn-removed', 12), 'a What-if or review message'],
|
|
376
|
+
['--corn-bad', tint('--corn-removed', 16), 'a refused check'],
|
|
377
|
+
['--corn-warn', tint('--corn-changed', 16), 'a mismatched check'],
|
|
378
|
+
['--corn-text-2', tint('--corn-text-3', 12), 'a verdict, a cloud badge'], ['--corn-text-3', tint('--corn-text-3', 12), 'a cloud plan not known'],
|
|
379
|
+
['--corn-text-2', tint('--corn-text-3', 10), 'a check'],
|
|
380
|
+
['--corn-text-2', tint('--corn-text-2', 12), 'a web badge'],
|
|
381
|
+
['--corn-text-2', '--corn-line-soft', 'a text button, hovered'],
|
|
382
|
+
]);
|
|
383
|
+
/**
|
|
384
|
+
* The parts of the interface a person needs to see to use it (WCAG 1.4.11), at 3:1: `[fg, bg, what]`. The focus indicators, and the
|
|
385
|
+
* borders and marks that alone say a state: which row is selected, which proposal is current, which layers are on, a run's state.
|
|
386
|
+
* `--corn-line` is not here: it is a divider, never the only sign of anything.
|
|
387
|
+
*/
|
|
388
|
+
export const UI_PAIRS = Object.freeze([
|
|
389
|
+
...[GROUND, ...SURFACES].map((bg) => ['--corn-focus', bg, 'the focus ring']),
|
|
390
|
+
['--corn-edit-text', GROUND, 'a What-if field\'s focus ring'], ['--corn-edit-text', '--corn-surface-1', 'a What-if field\'s focus ring'],
|
|
391
|
+
['--corn-added-text', GROUND, 'the review note\'s focus ring'], ['--corn-added-text', '--corn-surface-1', 'the review note\'s focus ring'],
|
|
392
|
+
['--corn-accent-text', '--corn-surface-3', 'the selected row\'s border'], ['--corn-accent-text', '--corn-surface-1', 'the selected row\'s border'],
|
|
393
|
+
['--corn-accent-text', GROUND, 'a pressed button\'s border'], ['--corn-accent-text', '--corn-surface-1', 'a pressed button\'s border'],
|
|
394
|
+
['--corn-added-text', tint('--corn-added', 12), 'the current proposal\'s border'], ['--corn-added-text', '--corn-surface-1', 'the current proposal\'s border'],
|
|
395
|
+
['--corn-ok', '--corn-surface-2', 'a layer\'s tick'], ['--corn-ok', '--corn-surface-3', 'a layer\'s tick'],
|
|
396
|
+
...['--corn-ok', '--corn-edit-text', '--corn-bad', '--corn-warn', '--corn-text-3'].flatMap((fg) => ['--corn-surface-2', '--corn-surface-3'].map((bg) => [fg, bg, 'a state pill\'s border'])),
|
|
397
|
+
]);
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Every pair that is read against each other: `{ fg, bg, min, kind, use? }`, `fg` and `bg` each a token or a CSS colour value. A pair
|
|
401
|
+
* listed twice is checked once, at the higher minimum. How a translucent `bg` is composited: see checkState.
|
|
402
|
+
* @returns {{ fg: string, bg: string, min: number, kind: 'text' | 'ui', use?: string }[]}
|
|
403
|
+
*/
|
|
404
|
+
export function contrastPairs() {
|
|
405
|
+
const pairs = new Map();
|
|
406
|
+
const add = (fg, bg, min, kind, use) => {
|
|
407
|
+
const key = `${fg}\n${bg}`;
|
|
408
|
+
const had = pairs.get(key);
|
|
409
|
+
if (!had || had.min < min) pairs.set(key, { fg, bg, min, kind, ...(use ? { use } : {}) });
|
|
410
|
+
};
|
|
411
|
+
for (const fg of TEXT_TOKENS) for (const bg of [GROUND, ...SURFACES]) add(fg, bg, MIN_TEXT, 'text');
|
|
412
|
+
for (const bg of ['--corn-accent', '--corn-accent-hover']) add('--corn-text-on-accent', bg, MIN_TEXT, 'text');
|
|
413
|
+
for (const [fg, bg] of SOFT_PAIRS) add(fg, bg, MIN_TEXT, 'text');
|
|
414
|
+
for (const bg of SOLID_FILLS) add(GROUND, bg, MIN_TEXT, 'text');
|
|
415
|
+
for (const [fg, bg] of PAINTED_TEXT) add(fg, bg, MIN_TEXT, 'text');
|
|
416
|
+
for (const [fg, bg, use] of UI_PAIRS) add(fg, bg, MIN_UI, 'ui', use);
|
|
417
|
+
return [...pairs.values()];
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* @typedef {object} ContrastFinding
|
|
422
|
+
* @property {string} theme `standard` or the named theme
|
|
423
|
+
* @property {'light'|'dark'} mode
|
|
424
|
+
* @property {'light'|'dark'} [system] set when the worst case is with the system setting the other way (the viewer picked `mode`)
|
|
425
|
+
* @property {boolean} [groundImage] set when the worst case is over the brightest colour of the ground image
|
|
426
|
+
* @property {string} fg @property {string} bg the two tokens (or values)
|
|
427
|
+
* @property {string} [use] what the pair is, for a UI pair
|
|
428
|
+
* @property {string} [fgValue] @property {string} [bgValue] the two colours as shown (translucent ones composited)
|
|
429
|
+
* @property {number} [ratio] @property {number} min
|
|
430
|
+
* @property {'text'|'ui'} kind
|
|
431
|
+
* @property {string} [problem] set when the pair could not be worked out (then there is no ratio)
|
|
432
|
+
*/
|
|
433
|
+
|
|
434
|
+
const isColor = (v) => Array.isArray(v);
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* The colours the ground can show beneath a panel: `--corn-ground`, and the ground with each layer of `--corn-ground-image` at its most
|
|
438
|
+
* opaque colour stop over it (a radial glow at its centre). An image (`url()`) or a value that cannot be read adds nothing.
|
|
439
|
+
* @returns {{ color: number[], image: boolean }[]}
|
|
440
|
+
*/
|
|
441
|
+
function groundsOf(props, ground) {
|
|
442
|
+
const out = [{ color: ground, image: false }];
|
|
443
|
+
if (!props.has('--corn-ground-image')) return out;
|
|
444
|
+
const r = expand('var(--corn-ground-image)', props);
|
|
445
|
+
if (!('text' in r)) return out;
|
|
446
|
+
for (const layer of layerTexts(r.text).slice(0, 16)) {
|
|
447
|
+
let peak = null;
|
|
448
|
+
for (const c of colorsIn(layer, 0)) if (!peak || c[3] > peak[3]) peak = c;
|
|
449
|
+
if (peak && peak[3] > 0) out.push({ color: over(peak, ground), image: true });
|
|
450
|
+
}
|
|
451
|
+
return out;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** The layers of a background-image value (split at its top-level commas) */
|
|
455
|
+
function layerTexts(text) {
|
|
456
|
+
return splitTop(text, ',').map((t) => t.trim()).filter(Boolean);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** The colours written in a value: a colour, or the colours inside a function like linear-gradient() (two levels deep at most) */
|
|
460
|
+
function colorsIn(text, depth) {
|
|
461
|
+
const out = [];
|
|
462
|
+
for (const part of splitTop(text, ',')) {
|
|
463
|
+
for (const word of splitTop(part.trim().replace(/\s+/g, ' '), ' ').map((w) => w.trim()).filter(Boolean)) {
|
|
464
|
+
const c = readColor(word);
|
|
465
|
+
if (c) { out.push(c); continue; }
|
|
466
|
+
const m = /^[a-z-]+\((.*)\)$/is.exec(word);
|
|
467
|
+
if (m && depth < 2 && !/^url\(/i.test(word)) out.push(...colorsIn(m[1], depth + 1));
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return out;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Pair results for one page state: one per pair, the worst over the ground and the ground image */
|
|
474
|
+
function checkState(props, theme, mode) {
|
|
475
|
+
const out = [];
|
|
476
|
+
const canvas = mode === 'dark' ? [0, 0, 0, 1] : [255, 255, 255, 1];
|
|
477
|
+
const cache = new Map();
|
|
478
|
+
const color = (v) => { if (!cache.has(v)) cache.set(v, resolveColor(props, v)); return cache.get(v); };
|
|
479
|
+
const g = color(GROUND);
|
|
480
|
+
const grounds = isColor(g) ? groundsOf(props, over(g, canvas)) : [];
|
|
481
|
+
const panel = color('--corn-surface-1');
|
|
482
|
+
for (const p of contrastPairs()) {
|
|
483
|
+
const finding = { theme, mode, fg: p.fg, bg: p.bg, min: p.min, kind: p.kind, ...(p.use ? { use: p.use } : {}) };
|
|
484
|
+
const fg0 = color(p.fg);
|
|
485
|
+
const bg0 = p.bg === GROUND ? g : color(p.bg);
|
|
486
|
+
const bad = [isColor(g) ? null : g, isColor(bg0) ? null : bg0, isColor(fg0) ? null : fg0].find(Boolean);
|
|
487
|
+
if (bad) { out.push({ ...finding, problem: bad.problem }); continue; }
|
|
488
|
+
let worst = null;
|
|
489
|
+
for (const { color: ground, image } of grounds) {
|
|
490
|
+
// A surface sits on the ground; a tint sits on the ground or on the panel (--corn-surface-1) it is drawn in
|
|
491
|
+
const beneath = p.bg === GROUND || SURFACES.includes(p.bg) || !isColor(panel) ? [ground] : [over(panel, ground)];
|
|
492
|
+
for (const under of beneath) {
|
|
493
|
+
const bg = p.bg === GROUND ? ground : over(bg0, under);
|
|
494
|
+
const fg = over(fg0, bg);
|
|
495
|
+
const r = ratio(luminance(fg), luminance(bg));
|
|
496
|
+
if (!worst || r < worst.ratio) worst = { fgValue: toHex(fg), bgValue: toHex(bg), ratio: r, image };
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
const { image, ...rest } = worst;
|
|
500
|
+
out.push({ ...finding, ...rest, ...(image ? { groundImage: true } : {}) });
|
|
501
|
+
}
|
|
502
|
+
return out;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Every pair, for light and dark, with the stylesheets applied in load order: one finding per pair, theme and mode, the worst of the
|
|
507
|
+
* two system settings (a viewer can pick light on a dark system) and of the ground and its image. `themes` is one entry per theme to
|
|
508
|
+
* check: `{ theme, sheets, name? }`.
|
|
509
|
+
* @param {{ theme: string, sheets: string[], name?: string }[]} themes
|
|
510
|
+
* @returns {ContrastFinding[]}
|
|
511
|
+
*/
|
|
512
|
+
export function checkSheets(themes) {
|
|
513
|
+
const out = [];
|
|
514
|
+
for (const { theme, sheets, name } of themes) {
|
|
515
|
+
for (const mode of ['light', 'dark']) {
|
|
516
|
+
const other = mode === 'light' ? 'dark' : 'light';
|
|
517
|
+
const same = checkState(resolveProps(sheets, { mode, system: mode, name }), theme, mode);
|
|
518
|
+
const flipped = checkState(resolveProps(sheets, { mode, system: other, name }), theme, mode);
|
|
519
|
+
same.forEach((f, i) => {
|
|
520
|
+
const g = flipped[i];
|
|
521
|
+
const worse = (f.problem === undefined && g.problem !== undefined) || (f.ratio !== undefined && g.ratio !== undefined && g.ratio < f.ratio && g.ratio < g.min && f.ratio >= f.min);
|
|
522
|
+
out.push(worse ? { ...g, system: other } : f);
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return out;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** The pairs under their minimum: { fails, unresolved } */
|
|
530
|
+
export function contrastProblems(themes) {
|
|
531
|
+
const all = checkSheets(themes);
|
|
532
|
+
return { fails: all.filter((f) => f.ratio !== undefined && f.ratio < f.min), unresolved: all.filter((f) => f.problem) };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const fmt = (r) => `${(Math.floor(r * 100) / 100).toFixed(2)}:1`;
|
|
536
|
+
const kindWord = (f) => (f.kind === 'ui' ? 'the UI minimum' : 'AA for text');
|
|
537
|
+
|
|
538
|
+
/** One line for a finding */
|
|
539
|
+
export function describeFinding(f) {
|
|
540
|
+
const who = f.theme === 'standard' ? 'standard theme' : `named theme "${f.theme}"`;
|
|
541
|
+
const where = `${who} (${f.mode}${f.system ? `, on a system set to ${f.system}` : ''})`;
|
|
542
|
+
const fg = f.use ? `${f.fg} (${f.use})` : f.fg;
|
|
543
|
+
if (f.problem) return `${where}: ${fg} on ${f.bg} could not be checked: ${f.problem}.`;
|
|
544
|
+
const bgWord = f.groundImage ? `${f.bg} over the ground image` : f.bg;
|
|
545
|
+
return `${where}: ${fg} (${f.fgValue}) on ${bgWord} (${f.bgValue}) is ${fmt(f.ratio)}, below ${f.min}:1 (${kindWord(f)}).`;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** A theme file's text, or null when validateThemeFiles refuses it (missing, outside the repo, over the size cap, not CSS): it reports that */
|
|
549
|
+
function readThemeFile(root, rel, fonts) {
|
|
550
|
+
try {
|
|
551
|
+
const base = fs.realpathSync(root);
|
|
552
|
+
const real = fs.realpathSync(path.resolve(root, rel));
|
|
553
|
+
if (!real.startsWith(base + path.sep)) return null;
|
|
554
|
+
const stats = fs.statSync(real);
|
|
555
|
+
if (!stats.isFile() || stats.size > MAX_THEME_BYTES) return null;
|
|
556
|
+
const text = fs.readFileSync(real, 'utf8');
|
|
557
|
+
return cssProblems(text, { fonts }).length ? null : text;
|
|
558
|
+
} catch {
|
|
559
|
+
return null;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* What the contrast check of a repo reads: `explorer/tokens.css`, then `theme.css`, as the standard theme; then each named theme with
|
|
565
|
+
* its file loaded after both. With no theme it is cornfield's own tokens, so the defaults are held by every `validate`. A theme file
|
|
566
|
+
* validateThemeFiles refuses is not read here (that is its error to report); with a refused `theme.css` there is nothing to check (null).
|
|
567
|
+
* @param {{ root: string, theme?: { css?: string|null, names?: Record<string,string>, fonts?: string[] } }} config
|
|
568
|
+
* @returns {{ theme: string, sheets: string[], name?: string }[] | null}
|
|
569
|
+
*/
|
|
570
|
+
export function themesToCheck(config) {
|
|
571
|
+
const theme = config.theme || {};
|
|
572
|
+
const base = [fs.readFileSync(TOKENS_FILE, 'utf8')];
|
|
573
|
+
if (theme.css) {
|
|
574
|
+
const css = readThemeFile(config.root, theme.css, theme.fonts);
|
|
575
|
+
if (css === null) return null;
|
|
576
|
+
base.push(css);
|
|
577
|
+
}
|
|
578
|
+
const themes = [{ theme: 'standard', sheets: base }];
|
|
579
|
+
for (const [name, rel] of Object.entries(theme.names || {})) {
|
|
580
|
+
const css = readThemeFile(config.root, rel, theme.fonts);
|
|
581
|
+
if (css !== null) themes.push({ theme: name, name, sheets: [...base, css] });
|
|
582
|
+
}
|
|
583
|
+
return themes;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* The contrast check of a repo, for `cornfield validate`: every pair under its minimum is an error (a warning with
|
|
588
|
+
* `theme.contrast: 'warn'`), and a pair that could not be worked out is a warning naming the token and why.
|
|
589
|
+
* @param {{ root: string, theme?: { css?: string|null, names?: Record<string,string>, fonts?: string[], contrast?: string } }} config
|
|
590
|
+
* @returns {{ errors: string[], warnings: string[] }}
|
|
591
|
+
*/
|
|
592
|
+
export function checkThemeContrast(config) {
|
|
593
|
+
const themes = themesToCheck(config);
|
|
594
|
+
if (!themes) return { errors: [], warnings: [] };
|
|
595
|
+
const { fails, unresolved } = contrastProblems(themes);
|
|
596
|
+
const lines = fails.map((f) => `theme contrast: ${describeFinding(f)}`);
|
|
597
|
+
const warnings = unresolved.map((f) => `theme contrast: ${describeFinding(f)}`);
|
|
598
|
+
return (config.theme || {}).contrast === 'warn' ? { errors: [], warnings: [...lines, ...warnings] } : { errors: lines, warnings };
|
|
599
|
+
}
|
package/core/theme.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* fontHosts: [], // the hosts of the font FILES, when a fonts host is not a known pair
|
|
12
12
|
* names: { day: './tools/cornfield/day.css' }, // named themes: data-theme-name on <html>, a picker in the header
|
|
13
13
|
* default: 'day', // the name used until a viewer picks one
|
|
14
|
+
* contrast: 'error', // 'warn' turns a failing contrast pair in `validate` into a warning
|
|
14
15
|
* }
|
|
15
16
|
*
|
|
16
17
|
* A theme is CSS only: never script, never inlined into the page.
|
|
@@ -19,7 +20,7 @@
|
|
|
19
20
|
import fs from 'node:fs';
|
|
20
21
|
import path from 'node:path';
|
|
21
22
|
|
|
22
|
-
export const THEME_KEYS = Object.freeze(['css', 'fonts', 'fontHosts', 'names', 'default']);
|
|
23
|
+
export const THEME_KEYS = Object.freeze(['css', 'fonts', 'fontHosts', 'names', 'default', 'contrast']);
|
|
23
24
|
/** The largest a theme file may be, in bytes */
|
|
24
25
|
export const MAX_THEME_BYTES = 256 * 1024;
|
|
25
26
|
export const MAX_THEME_NAMES = 12;
|
|
@@ -59,7 +60,7 @@ export function fontUrl(v) {
|
|
|
59
60
|
*/
|
|
60
61
|
export function themeProblems(t) {
|
|
61
62
|
if (t === undefined) return [];
|
|
62
|
-
if (!isObject(t)) return ['"theme" is { css?, fonts?, fontHosts?, names?, default? }.'];
|
|
63
|
+
if (!isObject(t)) return ['"theme" is { css?, fonts?, fontHosts?, names?, default?, contrast? }.'];
|
|
63
64
|
const out = [];
|
|
64
65
|
for (const k of Object.keys(t)) if (!THEME_KEYS.includes(k)) out.push(`theme.${k}: the keys are ${THEME_KEYS.join(', ')}.`);
|
|
65
66
|
if (t.css !== undefined && t.css !== null && !cssPathInRepo(t.css)) out.push('theme.css is one stylesheet (a .css file) inside the repo, written relative to it, like "./tools/cornfield/theme.css".');
|
|
@@ -94,6 +95,7 @@ export function themeProblems(t) {
|
|
|
94
95
|
}
|
|
95
96
|
}
|
|
96
97
|
}
|
|
98
|
+
if (t.contrast !== undefined && t.contrast !== 'error' && t.contrast !== 'warn') out.push('theme.contrast is "error" (a pair below WCAG AA fails validate; the default) or "warn" (it is a warning).');
|
|
97
99
|
if (t.default !== undefined && t.default !== null) {
|
|
98
100
|
if (!isText(t.default)) out.push('theme.default is the name of one of theme.names.');
|
|
99
101
|
else if (!names.includes(t.default)) out.push(`theme.default "${t.default}" is not one of theme.names (${names.join(', ') || 'none are listed'}).`);
|
|
@@ -146,7 +148,7 @@ const FORBIDDEN = [
|
|
|
146
148
|
* @param {string} text
|
|
147
149
|
* @param {string} gap
|
|
148
150
|
*/
|
|
149
|
-
function withoutComments(text, gap) {
|
|
151
|
+
export function withoutComments(text, gap) {
|
|
150
152
|
let out = '';
|
|
151
153
|
let quote = null;
|
|
152
154
|
for (let i = 0; i < text.length; i++) {
|
package/core/validate.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* - `validateRepo(...)`: everything, against the repo. The schema, the paths the map cites, drift from
|
|
9
9
|
* the code (every deriver run again, `planSync` must change nothing), what the derivers themselves
|
|
10
10
|
* report, the personas file, the cloud file against the map's cloud nodes, every proposal file, and
|
|
11
|
-
* each deriver's own `validate
|
|
11
|
+
* each deriver's own `validate`, and the theme's contrast (core/contrast.js: WCAG AA on the `--corn-*` pairs, light and dark).
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
import fs from 'node:fs';
|
|
@@ -23,6 +23,7 @@ import { CLOUD_FILE, cloudNodeProblems } from './cloud.js';
|
|
|
23
23
|
import { deriveTopology } from './derive.js';
|
|
24
24
|
import { missingPaths, planSync } from './sync.js';
|
|
25
25
|
import { repoPaths, repoReader } from './repo.js';
|
|
26
|
+
import { checkThemeContrast } from './contrast.js';
|
|
26
27
|
import { BRAND_IMAGE_KEYS, brandAssetFile } from './brand.js';
|
|
27
28
|
import { MAX_THEME_BYTES, cssProblems, cssUrls, themeAssetFile, themeFileUrl, themeFiles, themeUrlTarget } from './theme.js';
|
|
28
29
|
|
|
@@ -276,6 +277,9 @@ export async function validateRepo({ config, derivers, topology = readTopology(c
|
|
|
276
277
|
errors.push(...validatePersonasFile(config.root, config.personas.roles));
|
|
277
278
|
errors.push(...validateThemeFiles(config));
|
|
278
279
|
errors.push(...validateBrandFiles(config));
|
|
280
|
+
const contrast = checkThemeContrast(config);
|
|
281
|
+
errors.push(...contrast.errors);
|
|
282
|
+
warnings.push(...contrast.warnings);
|
|
279
283
|
errors.push(...validateCloudNodes(topology, config.root));
|
|
280
284
|
errors.push(...validateProposalFiles(topology, path.join(config.root, config.proposals), config.root));
|
|
281
285
|
const io = repoReader(config.root);
|
package/explorer/explorer.css
CHANGED
|
@@ -119,7 +119,8 @@ h1, h2, h3, p { margin: 0; }
|
|
|
119
119
|
.hx-btn:hover { background: var(--corn-surface-3); color: var(--corn-text); }
|
|
120
120
|
.hx-btn:focus-visible, .hx-toggle-row:focus-visible, .hx-zoom-btn:focus-visible, .hx-textbtn:focus-visible { outline: var(--corn-focus-width) solid var(--corn-focus); outline-offset: 2px; }
|
|
121
121
|
.hx-btn--active, .hx-btn--active:hover { background: var(--corn-accent); border-color: var(--corn-accent-text); color: var(--corn-text-on-accent); box-shadow: var(--corn-shadow-sm); }
|
|
122
|
-
.hx-btn--dim {
|
|
122
|
+
.hx-btn--dim { color: var(--corn-text-3); border-color: var(--corn-line-soft); } /* dimmed by its colours, not by opacity: opacity would take the text below AA */
|
|
123
|
+
.hx-btn--dim:hover { color: var(--corn-text-2); }
|
|
123
124
|
.hx-btn--quiet { font-weight: 500; color: var(--corn-text-3); }
|
|
124
125
|
.hx-btn--icon { width: 28px; height: 28px; padding: 0; justify-content: center; font-size: var(--corn-text-base); }
|
|
125
126
|
.hx-btn--preset { border-color: color-mix(in srgb, var(--corn-hue-orange) 35%, transparent); color: var(--corn-hue-orange); }
|
|
@@ -146,7 +147,7 @@ h1, h2, h3, p { margin: 0; }
|
|
|
146
147
|
transition: width 0.2s, border-color 0.2s;
|
|
147
148
|
user-select: text;
|
|
148
149
|
}
|
|
149
|
-
.hx-input:focus { width: 208px; border-color: var(--corn-
|
|
150
|
+
.hx-input:focus { width: 208px; border-color: var(--corn-focus); }
|
|
150
151
|
.hx-input::placeholder { color: var(--corn-text-3); }
|
|
151
152
|
.hx-input--wide, .hx-input--wide:focus { width: 100%; flex: 1; }
|
|
152
153
|
|
|
@@ -193,7 +194,7 @@ h1, h2, h3, p { margin: 0; }
|
|
|
193
194
|
.hx-menu-head { padding-bottom: var(--corn-space-2); border-bottom: var(--corn-border) solid var(--corn-line); margin-bottom: var(--corn-space-3); }
|
|
194
195
|
.hx-menu-links { display: flex; align-items: center; gap: var(--corn-space-3); text-transform: none; letter-spacing: 0; }
|
|
195
196
|
.hx-menu-section { padding-top: var(--corn-space-3); margin-top: var(--corn-space-3); border-top: var(--corn-border) solid var(--corn-line); }
|
|
196
|
-
.hx-note { padding: var(--corn-space-2) var(--corn-space-3); margin-bottom: var(--corn-space-3); border-radius: var(--corn-radius-sm); background:
|
|
197
|
+
.hx-note { padding: var(--corn-space-2) var(--corn-space-3); margin-bottom: var(--corn-space-3); border-radius: var(--corn-radius-sm); background: var(--corn-hue-orange-soft); color: var(--corn-hue-orange-text); font-size: var(--corn-text-xs); line-height: 1.4; }
|
|
197
198
|
.hx-textbtn { padding: calc(var(--corn-space-1) / 2) var(--corn-space-1); border: 0; border-radius: var(--corn-radius-xs); background: none; color: var(--corn-text-3); font-size: var(--corn-text-2xs); font-weight: 600; }
|
|
198
199
|
.hx-textbtn:hover { background: var(--corn-line-soft); color: var(--corn-text-2); }
|
|
199
200
|
.hx-textbtn--accent { color: var(--corn-accent-text); }
|
|
@@ -201,7 +202,7 @@ h1, h2, h3, p { margin: 0; }
|
|
|
201
202
|
.hx-toggles { display: flex; flex-direction: column; gap: var(--corn-space-1); }
|
|
202
203
|
.hx-toggle-row { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: var(--corn-space-2) var(--corn-space-3); border-radius: var(--corn-radius); border: var(--corn-border) solid var(--corn-line); background: var(--corn-surface-2); color: var(--corn-text); text-align: left; transition: background 0.15s; }
|
|
203
204
|
.hx-toggle-row:hover { background: var(--corn-surface-3); }
|
|
204
|
-
.hx-toggle-row.is-off { background: color-mix(in srgb, var(--corn-ground) 40%, transparent); border-color: transparent; color: var(--corn-text-3);
|
|
205
|
+
.hx-toggle-row.is-off { background: color-mix(in srgb, var(--corn-ground) 40%, transparent); border-color: transparent; color: var(--corn-text-3); } /* off: dimmed by the fill, the text-3 colour and the dot, never by opacity on text */
|
|
205
206
|
.hx-toggle-label, .hx-toggle-meta { display: flex; align-items: center; gap: var(--corn-space-3); }
|
|
206
207
|
.hx-dot { width: 10px; height: 10px; border-radius: 50%; flex: none; transition: transform 0.15s; }
|
|
207
208
|
.hx-toggle-row.is-off .hx-dot { transform: scale(0.75); opacity: 0.4; }
|
|
@@ -327,7 +328,7 @@ h1, h2, h3, p { margin: 0; }
|
|
|
327
328
|
.hx-proposal-item { display: flex; flex-direction: column; align-items: flex-start; gap: var(--corn-space-1); width: 100%; padding: var(--corn-space-3) var(--corn-space-3); border-radius: var(--corn-radius); border: var(--corn-border) solid var(--corn-line); background: var(--corn-surface-2); color: var(--corn-text); text-align: left; font-size: var(--corn-text-xs); }
|
|
328
329
|
button.hx-proposal-item:hover { background: var(--corn-surface-3); }
|
|
329
330
|
button.hx-proposal-item:focus-visible { outline: var(--corn-focus-width) solid var(--corn-focus); outline-offset: 2px; }
|
|
330
|
-
.hx-proposal-item.is-current { border-color: var(--corn-added); background: color-mix(in srgb, var(--corn-added) 12%, transparent); }
|
|
331
|
+
.hx-proposal-item.is-current { border-color: var(--corn-added-text); background: color-mix(in srgb, var(--corn-added) 12%, transparent); }
|
|
331
332
|
.hx-proposal-item.is-broken { opacity: 0.8; cursor: default; }
|
|
332
333
|
.hx-proposal-title { font-size: var(--corn-text-sm); font-weight: 600; color: var(--corn-text); overflow-wrap: anywhere; }
|
|
333
334
|
.hx-proposal-sum { color: var(--corn-text-2); line-height: 1.4; }
|
|
@@ -430,7 +431,7 @@ button.hx-proposal-item:focus-visible { outline: var(--corn-focus-width) solid v
|
|
|
430
431
|
.hx-whatif-field { display: flex; align-items: center; gap: var(--corn-space-3); color: var(--corn-text-2); }
|
|
431
432
|
.hx-whatif-field > select, .hx-whatif-field > .hx-whatif-input { flex: 1; min-width: 0; }
|
|
432
433
|
.hx-whatif-input, .hx-whatif-field select, .hx-whatif select { padding: var(--corn-space-1) var(--corn-space-3); border-radius: var(--corn-radius-sm); border: var(--corn-border) solid var(--corn-line); background: color-mix(in srgb, var(--corn-ground) 80%, transparent); color: var(--corn-text); font: inherit; font-size: var(--corn-text-sm); user-select: text; }
|
|
433
|
-
.hx-whatif-input:focus, .hx-whatif-field select:focus { outline: var(--corn-focus-width) solid var(--corn-edit); outline-offset: 1px; }
|
|
434
|
+
.hx-whatif-input:focus, .hx-whatif-field select:focus { outline: var(--corn-focus-width) solid var(--corn-edit-text); outline-offset: 1px; }
|
|
434
435
|
.hx-whatif-help { margin: 0; font-size: var(--corn-text-xs); }
|
|
435
436
|
.hx-whatif-pair { margin: 0; }
|
|
436
437
|
.hx-whatif-actions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--corn-space-2); }
|
|
@@ -459,7 +460,7 @@ button.hx-proposal-item:focus-visible { outline: var(--corn-focus-width) solid v
|
|
|
459
460
|
.hx-review[hidden] { display: none; }
|
|
460
461
|
.hx-review-label { color: var(--corn-text-3); font-size: var(--corn-text-xs); }
|
|
461
462
|
.hx-review-note { width: 100%; min-height: 44px; resize: vertical; padding: var(--corn-space-2) var(--corn-space-3); border-radius: var(--corn-radius-sm); border: var(--corn-border) solid var(--corn-line); background: color-mix(in srgb, var(--corn-ground) 80%, transparent); color: var(--corn-text); font: inherit; font-size: var(--corn-text-sm); line-height: 1.4; user-select: text; }
|
|
462
|
-
.hx-review-note:focus { outline: var(--corn-focus-width) solid var(--corn-added); outline-offset: 1px; }
|
|
463
|
+
.hx-review-note:focus { outline: var(--corn-focus-width) solid var(--corn-added-text); outline-offset: 1px; }
|
|
463
464
|
.hx-review-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--corn-space-2) var(--corn-space-3); }
|
|
464
465
|
.hx-review .hx-btn:disabled { opacity: 0.4; cursor: default; }
|
|
465
466
|
.hx-btn--approve { border-color: color-mix(in srgb, var(--corn-added) 50%, transparent); color: var(--corn-added-text); }
|
|
@@ -558,7 +559,7 @@ button.hx-proposal-item:focus-visible { outline: var(--corn-focus-width) solid v
|
|
|
558
559
|
.hx-live-token-label { display: block; margin-bottom: var(--corn-space-1); color: var(--corn-text); font-size: var(--corn-text-sm); font-weight: 600; }
|
|
559
560
|
.hx-live-token-row { display: flex; gap: var(--corn-space-2); align-items: center; margin-bottom: var(--corn-space-2); }
|
|
560
561
|
.hx-live-token-input { flex: 1; min-width: 0; padding: var(--corn-space-2) var(--corn-space-3); font-size: var(--corn-text-sm); }
|
|
561
|
-
.hx-live-token-input:focus { outline: none; border-color: var(--corn-
|
|
562
|
+
.hx-live-token-input:focus { outline: none; border-color: var(--corn-focus); }
|
|
562
563
|
.hx-live-help code { font-family: var(--corn-mono); font-size: var(--corn-text-2xs); color: var(--corn-text-2); overflow-wrap: anywhere; }
|
|
563
564
|
.hx-live-second { font-size: var(--corn-text-xs); }
|
|
564
565
|
.hx-live-buttons { display: inline-flex; gap: var(--corn-space-2); }
|
package/explorer/theme-model.js
CHANGED
|
@@ -23,10 +23,12 @@
|
|
|
23
23
|
* lightColor(css, role) one colour for the light ground (memoised)
|
|
24
24
|
* themed(css, theme, role) the same, or the colour untouched in the dark theme
|
|
25
25
|
* lightenScene(scene) every colour of a built scene, in place (scene.js calls it)
|
|
26
|
-
* contrast(a, b) the WCAG contrast ratio of two CSS colours
|
|
26
|
+
* contrast(a, b) the WCAG contrast ratio of two CSS colours (core/color.js)
|
|
27
27
|
* parseColor(css) a CSS colour as [r, g, b, a] (scene.js re-exports it for the renderers)
|
|
28
28
|
*/
|
|
29
29
|
|
|
30
|
+
import { parseColor, luminance, ratio, contrast } from '../core/color.js';
|
|
31
|
+
|
|
30
32
|
export const THEME_CHOICES = ['system', 'light', 'dark'];
|
|
31
33
|
/** Where the choice is kept in the browser (theme.js); `?theme=` in the address wins over it, without being kept */
|
|
32
34
|
export const THEME_STORAGE_KEY = 'topology-explorer:theme';
|
|
@@ -101,28 +103,9 @@ export function themeWords(choice, theme) {
|
|
|
101
103
|
// Colour arithmetic
|
|
102
104
|
// ---------------------------------------------------------------------------
|
|
103
105
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
let m = /^#([0-9a-f]{3})$/.exec(s);
|
|
108
|
-
if (m) return [...m[1]].map((h) => parseInt(h + h, 16)).concat(1);
|
|
109
|
-
m = /^#([0-9a-f]{6})$/.exec(s);
|
|
110
|
-
if (m) return [parseInt(m[1].slice(0, 2), 16), parseInt(m[1].slice(2, 4), 16), parseInt(m[1].slice(4, 6), 16), 1];
|
|
111
|
-
m = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+)\s*)?\)$/.exec(s);
|
|
112
|
-
if (m) return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] === undefined ? 1 : Number(m[4])];
|
|
113
|
-
return [0, 0, 0, 0];
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
const channel = (v) => {
|
|
117
|
-
const c = v / 255;
|
|
118
|
-
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
119
|
-
};
|
|
120
|
-
/** WCAG relative luminance of `[r, g, b]` (0..255) */
|
|
121
|
-
export const luminance = ([r, g, b]) => 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
|
|
122
|
-
const ratio = (la, lb) => (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
|
|
123
|
-
|
|
124
|
-
/** The WCAG contrast ratio of two opaque CSS colours (alpha is ignored) */
|
|
125
|
-
export const contrast = (a, b) => ratio(luminance(parseColor(a)), luminance(parseColor(b)));
|
|
106
|
+
// The colour arithmetic (parseColor, luminance, ratio, contrast) is core/color.js, shared with `cornfield validate`'s contrast check;
|
|
107
|
+
// scene.js and the tests still import it from here.
|
|
108
|
+
export { parseColor, luminance, contrast };
|
|
126
109
|
|
|
127
110
|
/** `[r, g, b]` (0..255) to `[h, s, l]` (h in degrees, s and l 0..1) */
|
|
128
111
|
export function toHsl([r, g, b]) {
|
package/explorer/tokens.css
CHANGED
|
@@ -32,14 +32,14 @@
|
|
|
32
32
|
/* Text */
|
|
33
33
|
--corn-text: #f8fafc;
|
|
34
34
|
--corn-text-2: #cbd5e1;
|
|
35
|
-
--corn-text-3: #
|
|
35
|
+
--corn-text-3: #9aa9bc;
|
|
36
36
|
--corn-text-on-accent: #fff;
|
|
37
37
|
--corn-mockup-ground: #fff;
|
|
38
38
|
|
|
39
39
|
/* Accent */
|
|
40
40
|
--corn-accent: #4f46e5;
|
|
41
|
-
--corn-accent-hover: #
|
|
42
|
-
--corn-accent-text: #
|
|
41
|
+
--corn-accent-hover: #6265f1;
|
|
42
|
+
--corn-accent-text: #98a1fa;
|
|
43
43
|
--corn-accent-soft: color-mix(in srgb, var(--corn-accent-hover) 20%, transparent);
|
|
44
44
|
--corn-focus: #818cf8;
|
|
45
45
|
--corn-brand-gradient: linear-gradient(135deg, #4299e1 0%, #818cf8 50%, #e53e3e 100%);
|
|
@@ -68,6 +68,9 @@
|
|
|
68
68
|
--corn-hue-fuchsia: #e879f9;
|
|
69
69
|
--corn-hue-pink: #f472b6;
|
|
70
70
|
--corn-hue-lime: #a3e635;
|
|
71
|
+
/* The orange as text on its own tint (the data-flow note in the Layers menu): the tint is the hue at 12% */
|
|
72
|
+
--corn-hue-orange-text: var(--corn-hue-orange);
|
|
73
|
+
--corn-hue-orange-soft: color-mix(in srgb, var(--corn-hue-orange) 12%, transparent);
|
|
71
74
|
|
|
72
75
|
/* Type */
|
|
73
76
|
--corn-font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
|
@@ -135,10 +138,10 @@
|
|
|
135
138
|
--corn-focus: #4f46e5;
|
|
136
139
|
--corn-brand-gradient: linear-gradient(135deg, #2563eb 0%, #4f46e5 50%, #dc2626 100%);
|
|
137
140
|
|
|
138
|
-
--corn-ok: #
|
|
141
|
+
--corn-ok: #046f51;
|
|
139
142
|
--corn-warn: #854d0e;
|
|
140
143
|
--corn-bad: #b91c1c;
|
|
141
|
-
--corn-info: #
|
|
144
|
+
--corn-info: #03679e;
|
|
142
145
|
|
|
143
146
|
--corn-added: #209a8b;
|
|
144
147
|
--corn-changed: #b28103;
|
|
@@ -148,7 +151,8 @@
|
|
|
148
151
|
--corn-hue-orange: #c2410c;
|
|
149
152
|
--corn-hue-fuchsia: #a21caf;
|
|
150
153
|
--corn-hue-pink: #be185d;
|
|
151
|
-
--corn-hue-lime: #
|
|
154
|
+
--corn-hue-lime: #4c7b0f;
|
|
155
|
+
--corn-hue-orange-text: #9a3412;
|
|
152
156
|
|
|
153
157
|
--corn-house-line: color-mix(in srgb, var(--corn-hue-lime) 30%, transparent);
|
|
154
158
|
--corn-house-room: color-mix(in srgb, var(--corn-hue-lime) 55%, transparent);
|
|
@@ -183,10 +187,10 @@
|
|
|
183
187
|
--corn-focus: #4f46e5;
|
|
184
188
|
--corn-brand-gradient: linear-gradient(135deg, #2563eb 0%, #4f46e5 50%, #dc2626 100%);
|
|
185
189
|
|
|
186
|
-
--corn-ok: #
|
|
190
|
+
--corn-ok: #046f51;
|
|
187
191
|
--corn-warn: #854d0e;
|
|
188
192
|
--corn-bad: #b91c1c;
|
|
189
|
-
--corn-info: #
|
|
193
|
+
--corn-info: #03679e;
|
|
190
194
|
|
|
191
195
|
--corn-added: #209a8b;
|
|
192
196
|
--corn-changed: #b28103;
|
|
@@ -196,7 +200,8 @@
|
|
|
196
200
|
--corn-hue-orange: #c2410c;
|
|
197
201
|
--corn-hue-fuchsia: #a21caf;
|
|
198
202
|
--corn-hue-pink: #be185d;
|
|
199
|
-
--corn-hue-lime: #
|
|
203
|
+
--corn-hue-lime: #4c7b0f;
|
|
204
|
+
--corn-hue-orange-text: #9a3412;
|
|
200
205
|
|
|
201
206
|
--corn-house-line: color-mix(in srgb, var(--corn-hue-lime) 30%, transparent);
|
|
202
207
|
--corn-house-room: color-mix(in srgb, var(--corn-hue-lime) 55%, transparent);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cornfield",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.0",
|
|
4
4
|
"description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "popcorn245 (https://github.com/popcorn245)",
|
package/server/server.js
CHANGED
|
@@ -78,7 +78,7 @@ import { createTriggers } from './triggers.js';
|
|
|
78
78
|
export const CORNFIELD_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
79
79
|
const EXPLORER_DIR = path.join(CORNFIELD_DIR, 'explorer');
|
|
80
80
|
/** The pure core modules the explorer imports (no Node built-ins, no files): the only ones of core/ served */
|
|
81
|
-
export const BROWSER_CORE = ['schema.js', 'proposal.js', 'personas.js', 'cloud.js', 'text.js', 'mentions.js'];
|
|
81
|
+
export const BROWSER_CORE = ['schema.js', 'proposal.js', 'personas.js', 'cloud.js', 'text.js', 'mentions.js', 'color.js'];
|
|
82
82
|
/** cornfield's own browser sources, by request path */
|
|
83
83
|
const BROWSER_PLUGINS = new Map(Object.values(BUILTIN_SOURCES).map((p) => [p, path.join(CORNFIELD_DIR, p)]));
|
|
84
84
|
const PKG = JSON.parse(fs.readFileSync(path.join(CORNFIELD_DIR, 'package.json'), 'utf8'));
|