cornfield 0.24.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/check.js +3 -0
- package/explorer/cloud-model.js +4 -4
- package/explorer/corn-state.js +34 -0
- package/explorer/explorer.css +9 -8
- package/explorer/flows.js +1 -1
- package/explorer/forge-panel.js +36 -31
- package/explorer/house.js +4 -0
- package/explorer/index.html +103 -103
- package/explorer/layers.js +1 -1
- package/explorer/live-model.js +1 -1
- package/explorer/live.js +1 -1
- package/explorer/mockups-model.js +4 -3
- package/explorer/mockups.js +4 -0
- package/explorer/panels.js +1 -1
- package/explorer/plugins.js +2 -2
- package/explorer/proposal-model.js +1 -1
- package/explorer/proposal.js +4 -4
- package/explorer/renderer.js +1 -0
- package/explorer/review-tokens.js +2 -1
- package/explorer/review.js +2 -1
- package/explorer/runs-map.js +1 -0
- package/explorer/runs-view.js +6 -5
- package/explorer/scenario-ui.js +4 -2
- package/explorer/sheets.js +1 -0
- package/explorer/theme-model.js +6 -23
- package/explorer/tokens.css +14 -9
- package/explorer/whatif.js +22 -21
- package/package.json +1 -1
- package/server/server.js +3 -3
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);
|