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 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: {},