cornfield 0.43.0 → 0.45.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 CHANGED
@@ -14,14 +14,36 @@
14
14
  * toHex([r,g,b]) '#rrggbb'
15
15
  *
16
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.
17
+ * percentages), `transparent`, the 148 CSS named colours, and `color-mix(in srgb, A p%, B [p%])` (of any of these, nested). Anything else
18
+ * (`oklch()`, `hwb()`, `lab()`, `color()`, the system colours, `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
19
  */
20
20
 
21
+ /** The 148 CSS named colours (CSS Color 4), as a browser reads them: a name the map draws is a name validate reads */
21
22
  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',
23
+ aliceblue: '#f0f8ff', antiquewhite: '#faebd7', aqua: '#00ffff', aquamarine: '#7fffd4', azure: '#f0ffff', beige: '#f5f5dc', bisque: '#ffe4c4',
24
+ black: '#000000', blanchedalmond: '#ffebcd', blue: '#0000ff', blueviolet: '#8a2be2', brown: '#a52a2a', burlywood: '#deb887', cadetblue: '#5f9ea0',
25
+ chartreuse: '#7fff00', chocolate: '#d2691e', coral: '#ff7f50', cornflowerblue: '#6495ed', cornsilk: '#fff8dc', crimson: '#dc143c', cyan: '#00ffff',
26
+ darkblue: '#00008b', darkcyan: '#008b8b', darkgoldenrod: '#b8860b', darkgray: '#a9a9a9', darkgreen: '#006400', darkgrey: '#a9a9a9',
27
+ darkkhaki: '#bdb76b', darkmagenta: '#8b008b', darkolivegreen: '#556b2f', darkorange: '#ff8c00', darkorchid: '#9932cc', darkred: '#8b0000',
28
+ darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkslategrey: '#2f4f4f',
29
+ darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dimgrey: '#696969',
30
+ dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0', forestgreen: '#228b22', fuchsia: '#ff00ff', gainsboro: '#dcdcdc',
31
+ ghostwhite: '#f8f8ff', gold: '#ffd700', goldenrod: '#daa520', gray: '#808080', green: '#008000', greenyellow: '#adff2f', grey: '#808080',
32
+ honeydew: '#f0fff0', hotpink: '#ff69b4', indianred: '#cd5c5c', indigo: '#4b0082', ivory: '#fffff0', khaki: '#f0e68c', lavender: '#e6e6fa',
33
+ lavenderblush: '#fff0f5', lawngreen: '#7cfc00', lemonchiffon: '#fffacd', lightblue: '#add8e6', lightcoral: '#f08080', lightcyan: '#e0ffff',
34
+ lightgoldenrodyellow: '#fafad2', lightgray: '#d3d3d3', lightgreen: '#90ee90', lightgrey: '#d3d3d3', lightpink: '#ffb6c1', lightsalmon: '#ffa07a',
35
+ lightseagreen: '#20b2aa', lightskyblue: '#87cefa', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#b0c4de',
36
+ lightyellow: '#ffffe0', lime: '#00ff00', limegreen: '#32cd32', linen: '#faf0e6', magenta: '#ff00ff', maroon: '#800000',
37
+ mediumaquamarine: '#66cdaa', mediumblue: '#0000cd', mediumorchid: '#ba55d3', mediumpurple: '#9370db', mediumseagreen: '#3cb371',
38
+ mediumslateblue: '#7b68ee', mediumspringgreen: '#00fa9a', mediumturquoise: '#48d1cc', mediumvioletred: '#c71585', midnightblue: '#191970',
39
+ mintcream: '#f5fffa', mistyrose: '#ffe4e1', moccasin: '#ffe4b5', navajowhite: '#ffdead', navy: '#000080', oldlace: '#fdf5e6', olive: '#808000',
40
+ olivedrab: '#6b8e23', orange: '#ffa500', orangered: '#ff4500', orchid: '#da70d6', palegoldenrod: '#eee8aa', palegreen: '#98fb98',
41
+ paleturquoise: '#afeeee', palevioletred: '#db7093', papayawhip: '#ffefd5', peachpuff: '#ffdab9', peru: '#cd853f', pink: '#ffc0cb', plum: '#dda0dd',
42
+ powderblue: '#b0e0e6', purple: '#800080', rebeccapurple: '#663399', red: '#ff0000', rosybrown: '#bc8f8f', royalblue: '#4169e1',
43
+ saddlebrown: '#8b4513', salmon: '#fa8072', sandybrown: '#f4a460', seagreen: '#2e8b57', seashell: '#fff5ee', sienna: '#a0522d', silver: '#c0c0c0',
44
+ skyblue: '#87ceeb', slateblue: '#6a5acd', slategray: '#708090', slategrey: '#708090', snow: '#fffafa', springgreen: '#00ff7f',
45
+ steelblue: '#4682b4', tan: '#d2b48c', teal: '#008080', thistle: '#d8bfd8', tomato: '#ff6347', turquoise: '#40e0d0', violet: '#ee82ee',
46
+ wheat: '#f5deb3', white: '#ffffff', whitesmoke: '#f5f5f5', yellow: '#ffff00', yellowgreen: '#9acd32',
25
47
  });
26
48
 
27
49
  /** How deep `color-mix()` may nest: deeper is not read (a hostile stylesheet cannot make the parser crawl or overflow the stack) */
@@ -71,10 +93,18 @@ function hslToRgb(h, s, l) {
71
93
  return [f(0) * 255, f(8) * 255, f(4) * 255];
72
94
  }
73
95
 
74
- /** The arguments of rgb()/hsl(), comma or space syntax, as [a, b, c, alpha?] strings; null when the shape is wrong */
96
+ /**
97
+ * The arguments of rgb()/hsl() as [a, b, c, alpha?] strings, in one of the two shapes a browser reads: commas throughout (`1, 2, 3, 0.5`), or
98
+ * spaces with the alpha after a slash (`1 2 3 / 0.5`). Null for any other shape (`1 2 3 4`, `1, 2 3`), which the browser does not draw either.
99
+ */
75
100
  function fnParts(args) {
76
- const parts = args.trim().split(/\s*[,/]\s*|\s+/).filter(Boolean);
77
- return parts.length === 3 || parts.length === 4 ? parts : null;
101
+ const t = args.trim();
102
+ if (t.includes(',')) {
103
+ const parts = t.split(/\s*,\s*/);
104
+ return (parts.length === 3 || parts.length === 4) && parts.every((p) => p && !/[\s/]/.test(p)) ? parts : null;
105
+ }
106
+ const m = /^(\S+)\s+(\S+)\s+([^\s/]+)(?:\s*\/\s*(\S+))?$/.exec(t);
107
+ return m && !m.slice(1, 4).some((p) => p.includes('/')) ? m.slice(1, m[4] === undefined ? 4 : 5) : null;
78
108
  }
79
109
 
80
110
  /** @returns {number[] | null} */
package/core/contrast.js CHANGED
@@ -25,8 +25,8 @@ import { MAX_MIX_DEPTH, readColor, over, toHex, luminance, ratio, splitTop } fro
25
25
  import { MAX_THEME_BYTES, cssProblems, withoutComments } from './theme.js';
26
26
  import { MIN_SHAPE_DELTA_E, NODE_SHAPES, NODE_THEMES } from './schema.js';
27
27
  import { deltaE2000 } from './delta-e.js';
28
- import { LAYER_KEY_RE, MAX_KEY, parseKindToken } from './layers.js';
29
- import { DIFF_MARK_COLORS, DIFF_LABEL_ALPHA, markOpacity } from '../explorer/diff-marks.js';
28
+ import { LAYER_KEY_RE, MAX_KEY, mapFillNames, parseKindToken } from './layers.js';
29
+ import { DIFF_MARK_COLORS, DIFF_LABEL_ALPHA, GREY_ALPHA, GREY_LABEL_ALPHA, GREY_MIN_RATIO, markOpacity } from '../explorer/diff-marks.js';
30
30
  import { lightColor } from '../explorer/theme-model.js';
31
31
 
32
32
  /** WCAG 2.1 AA: text, and large text and user-interface parts */
@@ -311,7 +311,7 @@ function origin(props, name) {
311
311
  return at;
312
312
  }
313
313
 
314
- const READS = 'hex, rgb(), hsl(), color-mix(in srgb, …), transparent and the basic colour names';
314
+ const READS = 'hex, rgb(), hsl(), color-mix(in srgb, …), transparent and the CSS named colours';
315
315
 
316
316
  /**
317
317
  * A token (`--corn-text`) or a value (`color-mix(…)`) as `[r, g, b, a]`, or `{ problem }` naming the custom property that could not
@@ -529,7 +529,7 @@ function mapFindings(props, theme, mode, grounds, extra = []) {
529
529
  const strokeOn = isColor(stroke.color) && !(Number.parseFloat(widthText) === 0);
530
530
  for (const type of Object.keys(NODE_THEMES)) {
531
531
  for (const group of MAP_GROUPS_OF(type)) {
532
- const names = [`--corn-map-node-${type}`, `--corn-map-group-${group}`];
532
+ const names = mapFillNames({ type, group }); // the map's own order (a kind and a project layer are checked on their own, below)
533
533
  let name = null;
534
534
  let fill = null;
535
535
  let problem = null;
@@ -586,6 +586,15 @@ function mapFindings(props, theme, mode, grounds, extra = []) {
586
586
  out.push({ ...base, fg: '--corn-map-stroke', bg: weakest.on, min: MAP_FILL_MIN, kind: 'ui', use: `the outline that carries ${what}, which is ${fmt(f.ratio)} on its own`, fgValue: onGround.fgValue, bgValue: weakest.value, ratio: weakest.r });
587
587
  }
588
588
  // Labels are text: the colour against the ground, and against the halo under it (the halo is the ground's own colour at `auto`)
589
+ // What a review greys, when the theme sets the colour (issue #232): readable as a colour, and at its faded strength still told from the ground. `auto` is each tone with its hue taken away (a test holds it)
590
+ const grey = mapToken(props, '--corn-map-grey');
591
+ if (grey.problem) out.push({ ...base, fg: '--corn-map-grey', bg: GROUND, min: GREY_MIN_RATIO, kind: 'ui', use: 'a node the review greys', problem: grey.problem });
592
+ else if (grey.color) {
593
+ const alphaText = props.has('--corn-map-grey-alpha') ? substitute(props.get('--corn-map-grey-alpha'), props).trim() : '';
594
+ const a = /^\d*\.?\d+$/.test(alphaText) && +alphaText >= 0.1 && +alphaText <= 1 ? +alphaText : GREY_ALPHA;
595
+ const w = worstOnGrounds([grey.color[0], grey.color[1], grey.color[2], grey.color[3] * a], grounds);
596
+ out.push({ ...base, fg: '--corn-map-grey', bg: GROUND, min: GREY_MIN_RATIO, kind: 'ui', use: `a node the review greys, left at ${Math.round(a * 100)}% opacity`, fgValue: w.fgValue, bgValue: w.bgValue, ratio: w.ratio, ...(w.image ? { groundImage: true } : {}) });
597
+ }
589
598
  const label = mapToken(props, '--corn-map-label');
590
599
  const haloTok = mapToken(props, '--corn-map-label-halo');
591
600
  const labelColor = label.color || (label.problem ? null : readColor(mode === 'light' ? lightColor('#f8fafc') : '#f8fafc'));
@@ -670,6 +679,8 @@ function mapGrounds(grounds, base, props) {
670
679
  const DIFF_MAP_PAIRS = (mode) => [
671
680
  ...['added', 'changed', 'removed', 'edit'].map((m) => [`--corn-map-${m}`, DIFF_MARK_COLORS[mode][m], markOpacity(m), `the ${m} mark on the map, drawn at ${Math.round(markOpacity(m) * 100)}% opacity`]),
672
681
  ['--corn-map-label', mode === 'light' ? lightColor('#f8fafc', 'text') : '#f8fafc', DIFF_LABEL_ALPHA, `a label the diff dims, drawn at ${Math.round(DIFF_LABEL_ALPHA * 100)}% opacity`],
682
+ // a label a review greys (issue #232), where it is fainter than a dimmed one (the dark ground)
683
+ ...(GREY_LABEL_ALPHA[mode] !== DIFF_LABEL_ALPHA ? [['--corn-map-label', mode === 'light' ? lightColor('#f8fafc', 'text') : '#f8fafc', GREY_LABEL_ALPHA[mode], `a label a review greys, drawn at ${Math.round(GREY_LABEL_ALPHA[mode] * 100)}% opacity`]] : []),
673
684
  ];
674
685
 
675
686
  function diffMapFindings(props, theme, mode, grounds, base) {
package/core/layers.js CHANGED
@@ -88,6 +88,14 @@ const TYPE_SET = new Set(NODE_TYPES);
88
88
  export const mapKindToken = (type, kind) => (TYPE_SET.has(type) && typeof kind === 'string' && kind.length <= MAX_KIND_NAME && KIND_NAME_RE.test(kind) ? `--corn-map-kind-${type}-${kind}` : null);
89
89
  /** `--corn-map-group-<key>` for a layer key that passes LAYER_KEY_RE, else null */
90
90
  export const mapGroupToken = (key) => (typeof key === 'string' && key.length <= MAX_KEY && LAYER_KEY_RE.test(key) ? `--corn-map-group-${key}` : null);
91
+ /**
92
+ * The tokens that can fill a node, most specific first (spec 0009 D6): its finer kind, its project layer, its type, its starting group. The one
93
+ * place the order is written: the map (explorer/map-style.js `fillOf`), the Layers menu's dots and `cornfield validate`'s contrast check
94
+ * (core/contrast.js) all read it.
95
+ * @param {{type: string, kind?: unknown, layer?: string | null, group?: string}} node
96
+ * @returns {string[]}
97
+ */
98
+ export const mapFillNames = ({ type, kind, layer, group }) => [mapKindToken(type, kind), layer ? mapGroupToken(layer) : null, `--corn-map-node-${type}`, `--corn-map-group-${group || type}`].filter(Boolean);
91
99
  /** Reads a kind token's name back: `{ type, kind }`, or null (the type is the part before the first "-") */
92
100
  export function parseKindToken(name) {
93
101
  const m = /^--corn-map-kind-([a-z]+)-([a-z0-9]+(?:-[a-z0-9]+)*)$/.exec(String(name));
@@ -1,19 +1,22 @@
1
1
  /**
2
2
  * @module core/map-tokens
3
3
  *
4
- * The map's non-colour tokens, as `cornfield validate` reads them: `--corn-map-font`, `--corn-map-edge-width`, `--corn-map-glow` and `--corn-map-label-min`. The
4
+ * The map's non-colour tokens, as `cornfield validate` reads them: `--corn-map-font`, `--corn-map-edge-width`, `--corn-map-glow`, `--corn-map-label-min` and `--corn-map-grey-alpha`. The
5
5
  * map reads each with the same parser (explorer/map-style.js `readMapTokens`), and one it cannot read is drawn as if it were `auto`; this
6
6
  * says so before the theme ships, as a warning naming the token, the theme, the level and what it may hold (docs/theming.md, The map).
7
7
  */
8
8
 
9
9
  import { declaredProps, expand, projectGroupOf, resolveProps, themesToCheck } from './contrast.js';
10
10
  import { iconKeyShape, parseKindToken } from './layers.js';
11
- import { EDGE_WIDTH_TOKEN, FONT_TOKEN, GLOW_TOKEN, LABEL_MIN_TOKEN, MAX_EDGE_WIDTH, MAX_GLOW, MAX_LABEL_MIN, readMapTokens } from '../explorer/map-style.js';
11
+ import { readColor } from './color.js';
12
+ import { MAX_NODE_COLOR_CHARS } from '../explorer/css-color.js';
13
+ import { EDGE_WIDTH_TOKEN, FONT_TOKEN, GLOW_TOKEN, GREY_ALPHA_TOKEN, LABEL_MIN_TOKEN, MAX_EDGE_WIDTH, MAX_GLOW, MAX_LABEL_MIN, readMapTokens } from '../explorer/map-style.js';
12
14
 
13
15
  const WANTS = {
14
16
  [FONT_TOKEN]: ['font', 'a list of font families (quoted names or plain words, at most 8; no url(), and no punctuation but commas and quotes)'],
15
17
  [EDGE_WIDTH_TOKEN]: ['edgeWidth', `a width in px over 0 and at most ${MAX_EDGE_WIDTH}`],
16
18
  [GLOW_TOKEN]: ['glow', `a factor from 0 (no glow) to ${MAX_GLOW}`],
19
+ [GREY_ALPHA_TOKEN]: ['greyAlpha', 'a number from 0.1 to 1 (0.45 is the default; a greyed node under 0.1 would vanish)'],
17
20
  [LABEL_MIN_TOKEN]: ['labelMin', `a size in px from 9 to ${MAX_LABEL_MIN} (11px is the default and the least it draws at; under 9px is ignored)`],
18
21
  };
19
22
 
@@ -86,3 +89,84 @@ export function layerTokenWarnings(config, map) {
86
89
  }
87
90
  return out;
88
91
  }
92
+
93
+ /** How many node colours are named one by one, per kind of line: past this, one line counts the rest */
94
+ export const MAX_NODE_COLOR_WARNINGS = 10;
95
+ const SHOWN_CHARS = 40;
96
+
97
+ /** What JSON leaves as it is but a terminal must not get raw: DEL and the C1 controls, and the invisible and bidirectional marks */
98
+ const UNSEEN = new RegExp('[\\u007f-\\u009f\\u00ad\\u061c\\u200b-\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2060-\\u206f\\ufeff\\ufff9-\\ufffb]', 'g');
99
+
100
+ /**
101
+ * Project text as a terminal may print it: JSON-quoted (so a line break, an escape character and every other C0 control is `\n`, `\u001b`,
102
+ * ...), cut to `max` characters, and with the controls JSON leaves alone made visible too (DEL, the C1 controls such as U+009B, which some
103
+ * terminals read as an escape, and the invisible and bidirectional marks that could make a line read as something it is not).
104
+ * @param {unknown} v
105
+ * @param {number} [max]
106
+ * @returns {string}
107
+ */
108
+ export function quoted(v, max = SHOWN_CHARS) {
109
+ let t;
110
+ try { t = typeof v === 'string' ? v : JSON.stringify(v) ?? String(v); } catch { t = String(v); }
111
+ const chars = Array.from(t);
112
+ if (chars.length > max) t = `${chars.slice(0, max).join('')}...`;
113
+ return JSON.stringify(t).replace(UNSEEN, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
114
+ }
115
+
116
+ /** Colour functions a current browser reads that core/color.js does not work out (it reads rgb() and hsl() only in their plainer forms) */
117
+ const UNCHECKED_FN = /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color|color-mix)\(/i;
118
+ /** The CSS system colours (CSS Color 4, with the deprecated ones browsers still read): the map draws them, in the colour the device gives */
119
+ const SYSTEM_COLORS = new Set(('accentcolor accentcolortext activetext buttonborder buttonface buttontext canvas canvastext field fieldtext graytext highlight '
120
+ + 'highlighttext linktext mark marktext selecteditem selecteditemtext visitedtext activeborder activecaption appworkspace background buttonhighlight '
121
+ + 'buttonshadow captiontext inactiveborder inactivecaption inactivecaptiontext infobackground infotext menu menutext scrollbar threeddarkshadow '
122
+ + 'threedface threedhighlight threedlightshadow threedshadow window windowframe windowtext').split(' '));
123
+
124
+ /**
125
+ * How `cornfield validate` can speak of a node's own `color`, which the map checks in the browser (explorer/css-color.js `nodeColor`):
126
+ * - `ok`: core/color.js reads it (hex, rgb(), hsl(), the 148 names, transparent, color-mix in srgb), so the browser does too;
127
+ * - `unchecked`: the shape of a colour a current browser reads that core/color.js cannot work out (`oklch()`, `lab()`, `hwb()`, `color()`,
128
+ * `color-mix()` in another space, rgb()/hsl() in a newer form, a system colour): the map draws it if it is valid, else the type's fill;
129
+ * - `bad`: no browser's map draws it (a typo, `#12345`, an empty string, a number, `currentcolor`, `var()`, `light-dark()`, which a canvas
130
+ * does not read, text over MAX_NODE_COLOR_CHARS): the map draws the type's fill.
131
+ * @param {unknown} value a node's `color`, not undefined
132
+ * @returns {'ok' | 'unchecked' | 'bad'}
133
+ */
134
+ export function nodeColorClass(value) {
135
+ if (typeof value !== 'string' || value.length > MAX_NODE_COLOR_CHARS) return 'bad';
136
+ const s = value.trim();
137
+ if (!s || /currentcolor|light-dark\(|var\(|env\(|attr\(/i.test(s)) return 'bad'; // the map never draws these (explorer/css-color.js)
138
+ if (readColor(s)) return 'ok';
139
+ if (UNCHECKED_FN.test(s) && s.endsWith(')')) return 'unchecked';
140
+ return SYSTEM_COLORS.has(s.toLowerCase()) ? 'unchecked' : 'bad';
141
+ }
142
+
143
+ const nodesWithColor = (map, kind) => ((map && map.nodes) || []).filter((n) => n && n.color !== undefined && nodeColorClass(n.color) === kind);
144
+ const capped = (nodes, line, rest) => {
145
+ const out = nodes.slice(0, MAX_NODE_COLOR_WARNINGS).map(line);
146
+ if (nodes.length > MAX_NODE_COLOR_WARNINGS) out.push(rest(nodes.length - MAX_NODE_COLOR_WARNINGS, nodes.length));
147
+ return out;
148
+ };
149
+
150
+ /**
151
+ * A warning per node whose own `color` no browser's map draws (nodeColorClass `bad`): the map draws that node in its type's fill instead
152
+ * (explorer/scene.js `buildNodes`). The id and the value are printed as quoted text (`quoted`), at most MAX_NODE_COLOR_WARNINGS lines, then a count.
153
+ * @param {{ nodes?: { id?: unknown, color?: unknown }[] } | null} map the committed map
154
+ * @returns {string[]}
155
+ */
156
+ export function nodeColorWarnings(map) {
157
+ return capped(nodesWithColor(map, 'bad'),
158
+ (n) => `node ${quoted(n.id)} has color ${quoted(n.color)}, which is not a colour the map reads: it draws in its type's fill. Write #rrggbb, rgb(), rgba() or hsl().`,
159
+ (more, all) => `${more} more nodes have a color the map does not read (${all} in all): they draw in their type's fill.`);
160
+ }
161
+
162
+ /**
163
+ * A note per node whose own `color` validate cannot check (nodeColorClass `unchecked`: `oklch()`, `lab()`, a system colour, ...). Not a
164
+ * warning: a current browser draws a valid one, and only an invalid one falls back to the type's fill. Same form and cap as the warnings.
165
+ * @param {{ nodes?: { id?: unknown, color?: unknown }[] } | null} map the committed map
166
+ * @returns {string[]}
167
+ */
168
+ export function nodeColorNotes(map) {
169
+ return capped(nodesWithColor(map, 'unchecked'),
170
+ (n) => `node ${quoted(n.id)} has color ${quoted(n.color)}, which validate cannot check: a current browser draws it if it is a valid colour, else the node draws in its type's fill.`,
171
+ (more, all) => `${more} more nodes have a color validate cannot check (${all} in all).`);
172
+ }
package/core/strings.js CHANGED
@@ -39,6 +39,9 @@ export const STRINGS = Object.freeze({
39
39
  undo: 'Undo',
40
40
  approved: 'Approved',
41
41
  myEdits: 'My edits',
42
+ showWholeMap: 'Show the whole map',
43
+ wholeMap: 'Whole map',
44
+ hiddenWhileReviewing: 'hidden while reviewing',
42
45
  yourEdits: 'Your edits',
43
46
  cancelLanding: 'Cancel landing',
44
47
  queueIt: 'Queue it',
package/core/validate.js CHANGED
@@ -24,7 +24,7 @@ import { deriveTopology } from './derive.js';
24
24
  import { missingPaths, planSync } from './sync.js';
25
25
  import { repoPaths, repoReader } from './repo.js';
26
26
  import { checkThemeContrast } from './contrast.js';
27
- import { layerTokenWarnings, mapTokenWarnings } from './map-tokens.js';
27
+ import { layerTokenWarnings, mapTokenWarnings, nodeColorNotes, nodeColorWarnings, quoted } from './map-tokens.js';
28
28
  import { layersMapWarnings } from './layers.js';
29
29
  import { BRAND_IMAGE_KEYS, brandAssetFile } from './brand.js';
30
30
  import { MAX_THEME_BYTES, cssProblems, cssUrls, themeAssetFile, themeFileUrl, themeFiles, themeIconFileProblems, themeUrlTarget } from './theme.js';
@@ -113,7 +113,7 @@ export function validateTopology(topology, { requireExternalKind = true } = {})
113
113
  errors.push(`Node "${node.id}" has unknown type: "${node.type}". Valid types: ${Object.keys(NODE_THEMES).join(', ')}`);
114
114
  } else {
115
115
  if (node.type === 'page') {
116
- if (node.color !== NODE_THEMES.page.color) errors.push(`Page node "${node.id}" has color "${node.color}". All pages use "${NODE_THEMES.page.color}".`);
116
+ if (node.color !== NODE_THEMES.page.color) errors.push(`Page node "${node.id}" has color ${quoted(node.color)}. All pages use "${NODE_THEMES.page.color}".`);
117
117
  if (typeof node.label !== 'string' || !node.label.startsWith('/')) errors.push(`Page node "${node.id}" label "${node.label}" must start with a slash route (e.g. "/cart"). Put the file in 'file'.`);
118
118
  else if (node.label.includes('.html')) errors.push(`Page node "${node.id}" label "${node.label}" contains ".html". Use a clean route label and put the file in 'file'.`);
119
119
  if (node.render) {
@@ -288,6 +288,8 @@ export async function validateRepo({ config, derivers, topology = readTopology(c
288
288
  if (contrast.summary) notes.push(contrast.summary);
289
289
  warnings.push(...mapTokenWarnings(config)); // a map font, line width or glow the map cannot read draws as auto
290
290
  warnings.push(...layerTokenWarnings(config, topology)); // a kind token, a group token or an icon for a kind or layer that is not there
291
+ warnings.push(...nodeColorWarnings(topology)); // a node whose own colour the map cannot read draws in its type's fill
292
+ notes.push(...nodeColorNotes(topology)); // a node colour only a browser can work out (oklch(), lab(), ...): said, not warned
291
293
  warnings.push(...layersMapWarnings(config.layers, topology)); // a project layer that matches nothing, or whose every node an earlier layer took
292
294
  errors.push(...validateCloudNodes(topology, config.root));
293
295
  errors.push(...validateProposalFiles(topology, path.join(config.root, config.proposals), config.root));
package/explorer/check.js CHANGED
@@ -23,7 +23,8 @@
23
23
  */
24
24
 
25
25
  import { state, escHtml } from './state.js';
26
- import { toggleLayer } from './layers.js';
26
+ import { setLayer } from './layers.js';
27
+ import { layersOf } from './layer-model.js';
27
28
  import { mapIndex, personaLabel, planChecks, runChecks, stepVerdict, verdictWords } from './check-model.js';
28
29
  import { cornState } from './corn-state.js';
29
30
 
@@ -53,7 +54,7 @@ export function openChecks(scenario, onChange = () => {}) {
53
54
  if (current && current.scenario && scenario && current.scenario.id === scenario.id) { current.onChange = onChange; replan(scenario); return; }
54
55
  closeChecks();
55
56
  current = { scenario: null, as: null, nodes: null, plan: null, answer: { status: 'idle' }, controller: null, onChange };
56
- if (namesActor(scenario) && state.activeLayers.persona !== true) toggleLayer('persona');
57
+ if (namesActor(scenario) && layersOf(state).persona !== true) setLayer('persona', true, { scenario: true });
57
58
  replan(scenario);
58
59
  }
59
60
 
@@ -0,0 +1,99 @@
1
+ /**
2
+ * @module explorer/css-color
3
+ *
4
+ * A CSS colour as the renderers can use it, read once here so every reader (the map's tokens in map-style.js, a node's own
5
+ * colour in scene.js) agrees on what a colour is. The text is project or theme data: it only ever leaves here as `#rrggbb`,
6
+ * `rgb()` or `rgba()` that this file built or checked, never as the text it was given.
7
+ */
8
+
9
+ import { parseColor } from './theme-model.js';
10
+ import { readColor } from '../core/color.js';
11
+
12
+ let probe;
13
+ const normalised = new Map();
14
+
15
+ /** A canvas context to normalise a colour the way the browser reads it (`hsl()`, a name, `color-mix()`), or null where there is none */
16
+ function probeContext() {
17
+ if (probe !== undefined) return probe;
18
+ probe = null;
19
+ try { if (typeof document !== 'undefined') probe = document.createElement('canvas').getContext('2d', { willReadFrequently: true }) || null; } catch { probe = null; }
20
+ return probe;
21
+ }
22
+
23
+ /**
24
+ * A token's value as a colour the renderers can use (`#rrggbb`, `rgb()`, `rgba()`), or null for `auto`, empty, or anything that is not a colour.
25
+ * @param {string} value
26
+ * @returns {string | null}
27
+ */
28
+ export function cssColor(value) {
29
+ const s = typeof value === 'string' ? value.trim() : '';
30
+ if (!s || s.toLowerCase() === 'auto') return null;
31
+ if (inRange(s)) return s;
32
+ if (/^transparent$/i.test(s)) return 'rgba(0, 0, 0, 0)';
33
+ if (normalised.has(s)) return normalised.get(s);
34
+ let out = null;
35
+ const ctx = isColor(s) && !/currentcolor/i.test(s) ? probeContext() : null; // a canvas has no current colour: it would read as black
36
+ if (ctx) {
37
+ try {
38
+ // The browser's own reading: a value it refuses leaves fillStyle as it was, so two different starting colours tell a refusal
39
+ // from a colour that happens to equal the first one
40
+ const read = (from) => { ctx.fillStyle = from; ctx.fillStyle = s; return String(ctx.fillStyle); };
41
+ const a = read('#010203');
42
+ const got = a !== '#010203' ? a : read('#040506') !== '#040506' ? a : null;
43
+ // A colour the browser keeps in another space (`oklch()`, `color(display-p3 ...)`) is read back as the sRGB pixel it paints
44
+ out = got === null ? null : parseable(got) ? got : pixelOf(ctx, s);
45
+ } catch { out = null; }
46
+ }
47
+ normalised.set(s, out);
48
+ return out;
49
+ }
50
+
51
+ /** Whether CSS itself reads `s` as a colour (a canvas is more lenient: it takes `rgb(1.2.3, 0, 0)`); true where the page cannot say */
52
+ function isColor(s) {
53
+ try { return typeof CSS === 'undefined' || typeof CSS.supports !== 'function' || CSS.supports('color', s); } catch { return false; }
54
+ }
55
+
56
+ /** `#rgb`, `#rrggbb`, `rgb()` or `rgba()` with every channel in range: what both renderers read as written */
57
+ function inRange(s) {
58
+ if (!parseable(s)) return false;
59
+ // The numbers as written: parseColor clamps them, and an out-of-range channel must go to the browser to be read
60
+ const nums = /^rgba?\(/i.test(s.trim()) ? s.slice(s.indexOf('(') + 1, s.lastIndexOf(')')).split(',').map(Number) : null;
61
+ if (nums && (nums.slice(0, 3).some((c) => !(c >= 0 && c <= 255)) || (nums.length > 3 && !(nums[3] > 0 && nums[3] <= 1)))) return false;
62
+ const [r, g, b, a] = parseColor(s);
63
+ return [r, g, b].every((c) => Number.isFinite(c) && c >= 0 && c <= 255) && Number.isFinite(a) && a > 0 && a <= 1;
64
+ }
65
+ /** The forms parseColor (theme-model.js) reads; anything else is normalised by the browser first */
66
+ const COLOR_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$|^rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*(?:,\s*[\d.]+\s*)?\)$/i;
67
+ const parseable = (s) => COLOR_RE.test(s.trim());
68
+
69
+ /** The sRGB pixel `css` paints, as `rgba()` (or null when the context cannot be read) */
70
+ function pixelOf(ctx, css) {
71
+ if (!ctx.getImageData || !ctx.fillRect) return null;
72
+ ctx.clearRect(0, 0, 1, 1);
73
+ ctx.fillStyle = css;
74
+ ctx.fillRect(0, 0, 1, 1);
75
+ const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
76
+ return rgbaText(r, g, b, a / 255);
77
+ }
78
+
79
+ export const rgbaText = (r, g, b, a) => `rgba(${r}, ${g}, ${b}, ${+a.toFixed(3)})`;
80
+
81
+
82
+ /** The longest colour a node may carry: every real colour is far shorter, and a longer text is never handed to the browser to read */
83
+ export const MAX_NODE_COLOR_CHARS = 200;
84
+
85
+ /**
86
+ * A node's own `color` (project data) as a colour both renderers draw the same, or null when it is not one: a typo, `#12345`, an empty
87
+ * string, a number, `null`, a value with a quote or `url(`, text over MAX_NODE_COLOR_CHARS. The caller then uses the node type's fill.
88
+ * Where the page has no canvas to read with (Node, the tests), the forms core/color.js reads are kept as written.
89
+ * @param {unknown} value
90
+ * @returns {string | null}
91
+ */
92
+ export function nodeColor(value) {
93
+ if (typeof value !== 'string' || value.length > MAX_NODE_COLOR_CHARS) return null;
94
+ const s = value.trim();
95
+ if (!s || /^(?:auto|currentcolor)$/i.test(s)) return null;
96
+ const c = cssColor(s);
97
+ if (c) return c;
98
+ return probeContext() === null && readColor(s) ? s : null;
99
+ }
@@ -26,6 +26,18 @@ export const markOpacity = (mark) => EDGE_MIN_ALPHA * (mark === 'removed' || mar
26
26
  /** The opacity of the label of a node a diff dims (the node itself is at PROPOSAL_DIM_ALPHA) */
27
27
  export const DIFF_LABEL_ALPHA = 0.6;
28
28
 
29
+ /**
30
+ * How much of a node a review greys (issue #232) is left (`--corn-map-grey-alpha: auto`), and the least a greyed disc may differ from the ground it sits on
31
+ * (core/contrast.js checks a theme's `--corn-map-grey` against it): faded, but the map still reads as a map. Its label is at GREY_LABEL_ALPHA (below).
32
+ */
33
+ export const GREY_ALPHA = 0.45;
34
+ export const GREY_MIN_RATIO = 1.5;
35
+ /**
36
+ * The opacity of a greyed node's label, by ground: near the dimmed-label floor (4.4:1 on the default light ground, 5.2:1 on the dark, 4.75:1 on retro's navy),
37
+ * so the change's labels are the strongest text on the map. On the dark ground DIFF_LABEL_ALPHA would leave it near 7:1. core/contrast.js checks both.
38
+ */
39
+ export const GREY_LABEL_ALPHA = Object.freeze({ light: DIFF_LABEL_ALPHA, dark: 0.5 });
40
+
29
41
  /** How a mark differs without colour: the ring's dash (`null` is solid) and whether it is struck through. Four marks, four styles. */
30
42
  export const MARK_SHAPES = Object.freeze({
31
43
  added: Object.freeze({ ringDash: Object.freeze([5, 4]), edgeDash: Object.freeze([7, 5]), strike: false }), // a dashed ring