@popcorn245/cornfield 0.48.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/core/strings.js +14 -0
  2. package/explorer/check.js +7 -227
  3. package/explorer/connection.js +3 -3
  4. package/explorer/css/review.css +49 -0
  5. package/explorer/decision-model.js +6 -0
  6. package/explorer/engine/checks.js +252 -0
  7. package/explorer/engine/connection.js +36 -0
  8. package/explorer/engine/layers.js +1 -0
  9. package/explorer/engine/layout.js +8 -3
  10. package/explorer/engine/player.js +489 -0
  11. package/explorer/engine/proposal.js +373 -0
  12. package/explorer/engine/render.js +1 -0
  13. package/explorer/engine/sheets.js +40 -7
  14. package/explorer/engine/source.js +315 -0
  15. package/explorer/engine/theme-sheet.js +444 -0
  16. package/explorer/engine/topology.js +126 -0
  17. package/explorer/index.html +6 -59
  18. package/explorer/instance.js +87 -7
  19. package/explorer/page-address.js +59 -0
  20. package/explorer/page-pieces.js +33 -5
  21. package/explorer/page.js +20 -20
  22. package/explorer/panels.js +1 -3
  23. package/explorer/pieces/changes.js +495 -0
  24. package/explorer/pieces/decision.js +664 -0
  25. package/explorer/pieces/layers.js +4 -0
  26. package/explorer/pieces/map.js +117 -25
  27. package/explorer/pieces/node-panel.js +34 -1
  28. package/explorer/pieces/proposal.js +488 -0
  29. package/explorer/pieces/review.js +280 -0
  30. package/explorer/pieces/scope-link.js +50 -0
  31. package/explorer/pieces/scope.js +247 -0
  32. package/explorer/pieces/status.css +24 -0
  33. package/explorer/pieces/status.js +144 -0
  34. package/explorer/plugins.js +0 -10
  35. package/explorer/proposal.js +64 -697
  36. package/explorer/review-column.js +24 -439
  37. package/explorer/review.js +27 -673
  38. package/explorer/scenario-ui.js +32 -478
  39. package/explorer/sheets.js +8 -7
  40. package/explorer/view.js +12 -64
  41. package/explorer/waiting-line.js +7 -50
  42. package/package.json +1 -1
@@ -0,0 +1,444 @@
1
+ /**
2
+ * @module explorer/engine/theme-sheet
3
+ *
4
+ * The server's theme in another app's page (spec 0011 D7): `/cornfield/theme.css` (and the named theme the config makes the default), read once
5
+ * for a scope and given to its pieces in two parts that go to two places. Nothing else of the stylesheet reaches the host's document.
6
+ *
7
+ * THE RULES One constructable `CSSStyleSheet`, built from the text with `replaceSync` and adopted into each piece's shadow root, where its
8
+ * `[data-corn]` hook rules apply as written (and its `::part`-less `*`, `body` and element rules reach only that piece's own tree,
9
+ * because a shadow root's stylesheet cannot match outside it). It is never adopted by the document.
10
+ * THE TOKENS A rule on `:root` cannot match inside a shadow root, so the `--corn-*` declarations of the rules that name `:root` (and the light and
11
+ * dark blocks docs/theming.md documents) are copied onto the scope element, which every piece inherits from. They are found by walking
12
+ * the parsed sheet's `cssRules` and reading `CSSStyleDeclaration`s: the CSS text is never searched, cut or rewritten. Any other custom
13
+ * property, any ordinary declaration and any other rule stays in the sheet and goes nowhere else.
14
+ *
15
+ * What a constructable sheet does not do, and so a theme that relied on it:
16
+ * `@import` dropped by the browser (with a console warning): what the imported sheet held is not there. Put it in the theme file.
17
+ * `@font-face` a shadow root's stylesheet cannot define a font for the page, so a theme's own fonts are not loaded and the font stack falls to
18
+ * its next family. The host can load them itself (a `@font-face` of its own that names the server's /cornfield/theme/assets/…).
19
+ * The `fonts` links of the server's page (Google Fonts) are not in the theme file and are not reached either.
20
+ * a relative `url()` would be resolved against the host page; the ones in a value that is copied, or in a rule of the sheet, are made absolute
21
+ * against the server (a `url()` is the only thing rewritten, and in the parsed declaration, not in the text).
22
+ *
23
+ * WHAT A THEME MAY LOAD. Only what is on the server's own origin (its `/cornfield/theme/assets/…`) and `data:` images, which is all a theme the server
24
+ * accepts may name (core/theme.js). A CSS image is fetched with the host page's cookies for its own site, so a reference to another origin would make
25
+ * the host page's visitors ask that origin, as themselves: every declaration, token and rule that names one (in `url()`, `src()`, an `image-set()`
26
+ * string, written with CSS escapes, at any depth of the sheet: `@media`, nesting, `@keyframes`, `@font-face`, `@property`) is dropped before the sheet
27
+ * is adopted anywhere. The text is read no further than MAX_THEME_TEXT characters.
28
+ */
29
+
30
+ /** The longest theme text read, in characters (the server refuses a file over 256 KB) */
31
+ export const MAX_THEME_TEXT = 512 * 1024;
32
+ /** The longest value of a copied token */
33
+ const MAX_VALUE = 4096;
34
+ const TOKEN = /^--corn-[a-z0-9]+(?:-[a-z0-9]+)*$/;
35
+ export const THEME_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
36
+ export const THEME_PATH = '/cornfield/theme.css';
37
+ export const themePath = (name) => `/cornfield/theme/${name}.css`;
38
+
39
+ const squash = (s) => String(s).replace(/\s+/g, '');
40
+ const unwrap = (s) => { const m = /^:where\((.*)\)$/.exec(s); return m ? m[1] : s; };
41
+
42
+ /** The selectors of a rule's selector text, split on top-level commas, spaces removed, `:where()` taken off */
43
+ export function selectorParts(text) {
44
+ const out = [];
45
+ let depth = 0;
46
+ let from = 0;
47
+ const t = String(text);
48
+ for (let i = 0; i <= t.length; i++) {
49
+ const c = t[i];
50
+ if (c === '(' || c === '[') depth++;
51
+ else if (c === ')' || c === ']') depth--;
52
+ else if ((c === ',' && !depth) || i === t.length) { out.push(unwrap(squash(t.slice(from, i)))); from = i + 1; }
53
+ }
54
+ return out.filter(Boolean);
55
+ }
56
+
57
+ /**
58
+ * Which block of the documented theme contract a selector belongs to, or null (a selector that is not the page's root):
59
+ *
60
+ * base `:root` / `html` (dark values and everything both levels share)
61
+ * light `:root[data-theme="light"]`, and under `@media (prefers-color-scheme: light)` `:root:not([data-theme="dark"])`
62
+ * dark `:root[data-theme="dark"]`, and under `@media (prefers-color-scheme: dark)` `:root:not([data-theme="light"])`
63
+ *
64
+ * A named theme (`/cornfield/theme/<name>.css`) writes the same selectors with `[data-theme-name="<name>"]` on the root; `name` says which.
65
+ * @param {string} selector one selector, as `selectorParts` returns it
66
+ * @param {'light' | 'dark' | null} media the `prefers-color-scheme` the rule sits under, if any
67
+ * @param {string | null} [name]
68
+ * @returns {'base' | 'light' | 'dark' | null}
69
+ */
70
+ export function blockOf(selector, media, name = null) {
71
+ const root = selector.startsWith(':root') ? ':root' : selector.startsWith('html') ? 'html' : null;
72
+ if (!root) return null;
73
+ let rest = selector.slice(root.length);
74
+ const tag = name ? `[data-theme-name="${name}"]` : null;
75
+ if (tag) {
76
+ if (rest.includes(tag)) rest = rest.replace(tag, '');
77
+ else return null; // a named theme's rules name the theme
78
+ } else if (/\[data-theme-name=/.test(rest)) return null; // and the standard theme's do not
79
+ if (rest === '') return media ? media : 'base';
80
+ if (rest === '[data-theme="light"]') return 'light';
81
+ if (rest === '[data-theme="dark"]') return 'dark';
82
+ if (rest === ':not([data-theme="dark"])' && media === 'light') return 'light';
83
+ if (rest === ':not([data-theme="light"])' && media === 'dark') return 'dark';
84
+ return null;
85
+ }
86
+
87
+ /** A `data:` URL a theme may name: an image (core/theme.js allows the same on the server) */
88
+ const DATA_IMAGE = /^data:image\/(?:png|gif|webp|avif|svg\+xml)[;,]/i;
89
+ /** What can load something: `url(`, `src(`, `image(` and `image-set(` (and `-webkit-image-set(`), read after CSS escapes are undone */
90
+ const LOADS = /(?<![\w-])(?:url|src|image|(?:-webkit-)?image-set)\(/i;
91
+ const REF = /(?<![\w-])(url|src)\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s"']*))\s*\)/gi;
92
+ const STRING = /"([^"]*)"|'([^']*)'/g;
93
+
94
+ /** CSS escapes undone, as a browser's tokenizer reads them (`u\72l(` and `\75 rl(` are `url(`) */
95
+ export function unescapeCss(text) {
96
+ return String(text).replace(/\\([0-9a-f]{1,6})\s?|\\([^\n])/gi, (_m, hex, ch) => {
97
+ if (hex) { const cp = parseInt(hex, 16); return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : '\ufffd'; }
98
+ return ch;
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Where a reference of the theme leads, made absolute against the server, or null when the theme may not name it: only the server's own origin
104
+ * (its `/cornfield/theme/assets/…`, under the base's path when it has one) and a `data:` image. Another origin, another scheme, `//host`: null.
105
+ * The server refuses such a theme too (core/theme.js), so a theme that names one did not come from a cornfield that checked it.
106
+ */
107
+ function placeOf(ref, base) {
108
+ if (DATA_IMAGE.test(ref)) return ref;
109
+ try {
110
+ const at = new URL(base);
111
+ // a path that begins with a slash is the server's own (`/cornfield/theme/assets/x.png`): under the base's path when it has one
112
+ const u = ref.startsWith('/') && !ref.startsWith('//') ? new URL(at.pathname.replace(/\/+$/, '') + ref, at) : new URL(ref, `${base}/`);
113
+ if ((u.protocol !== 'https:' && u.protocol !== 'http:') || u.origin !== at.origin) return null;
114
+ return u.href;
115
+ } catch { return null; }
116
+ }
117
+
118
+ /**
119
+ * A declaration's value with every reference it may load made absolute against the server, or null when it names one the theme may not (another
120
+ * origin, another scheme), or one that cannot be read safely: a `url(` written with CSS escapes, a `url(` that is not closed, or anything else that
121
+ * loads (`image()`, `src()`) in a form that is not plain. The strings of an `image-set()` are references too. A value that loads nothing is returned
122
+ * as it was.
123
+ * @param {string} value
124
+ * @param {string} base the server's base address (`https://map.example.com`, or with a path)
125
+ * @returns {string | null}
126
+ */
127
+ export function absolutizeUrls(value, base) {
128
+ const text = String(value);
129
+ const plain = unescapeCss(text);
130
+ if (!LOADS.test(plain)) return text;
131
+ if (plain !== text && LOADS.test(plain.replace(STRING, '""'))) return null; // escapes in what loads: not rewritten, dropped
132
+ if (!base) return null;
133
+ let ok = true;
134
+ let out = text.replace(REF, (_all, fn, a, b, c) => {
135
+ const place = placeOf(a ?? b ?? c ?? '', base);
136
+ if (place === null) { ok = false; return ''; }
137
+ return `${fn.toLowerCase()}("${place.replace(/["\\\n]/g, (ch) => encodeURIComponent(ch))}")`;
138
+ });
139
+ // Every function that loads must have been one of those: `url(` left open, `image(` (or `src(`) in any other form, refuse the value
140
+ const loads = (out.replace(/(?<![\w-])(?:url|src)\("[^"]*"\)/gi, '').match(new RegExp(LOADS.source, 'gi')) || []).filter((f) => !/image-set\($/i.test(f));
141
+ if (!ok || loads.length) return null;
142
+ // The strings of an image-set() are addresses too (Chrome keeps them as written in a custom property)
143
+ if (/(?:-webkit-)?image-set\(/i.test(out)) {
144
+ out = out.replace(/((?:-webkit-)?image-set\()([^]*)$/i, (_all, head, rest) => head + rest.replace(STRING, (_s, a, b) => {
145
+ const place = placeOf(a ?? b ?? '', base);
146
+ if (place === null) { ok = false; return '""'; }
147
+ return `"${place.replace(/["\\\n]/g, (ch) => encodeURIComponent(ch))}"`;
148
+ }));
149
+ if (!ok) return null;
150
+ }
151
+ return out;
152
+ }
153
+
154
+ /** Whether every reference in a value is already absolute on the server's origin, or a `data:` image (what `absolutizeUrls` leaves) */
155
+ function refsSettled(text, base) {
156
+ const fixed = absolutizeUrls(text, base);
157
+ return fixed !== null && fixed === text;
158
+ }
159
+
160
+ /**
161
+ * The `--corn-*` declarations of the root rules of a parsed sheet, by block: `{ base, light, dark }`, each a Map of name to value. Only the
162
+ * top level and `@media (prefers-color-scheme: light | dark)` are read (a token in a `@supports`, a `@layer` or another condition is not copied).
163
+ * @param {CSSStyleSheet | { cssRules: CSSRuleList }} sheet
164
+ * @param {{ name?: string | null, base?: string }} [opts] `name`: a named theme; `base`: the server, for the `url()`s of a copied value
165
+ */
166
+ export function tokenBlocks(sheet, { name = null, base = '' } = {}) {
167
+ const blocks = { base: new Map(), light: new Map(), dark: new Map() };
168
+ const take = (rule, media) => {
169
+ const into = selectorParts(rule.selectorText).map((s) => blockOf(s, media, name)).find(Boolean);
170
+ if (!into) return;
171
+ const style = rule.style;
172
+ for (let i = 0; i < style.length; i++) {
173
+ const prop = style[i];
174
+ if (!TOKEN.test(prop)) continue;
175
+ let value = style.getPropertyValue(prop).trim();
176
+ if (!value || value.length > MAX_VALUE) continue;
177
+ if (base || LOADS.test(unescapeCss(value))) { value = base ? absolutizeUrls(value, base) : null; if (value === null) continue; } // a token that loads is the server's, or not copied
178
+ blocks[into].set(prop, value);
179
+ }
180
+ };
181
+ for (const rule of Array.from(sheet.cssRules || [])) {
182
+ if (rule.selectorText !== undefined) take(rule, null);
183
+ else if (rule.media && rule.cssRules) {
184
+ const m = /^\(\s*prefers-color-scheme\s*:\s*(light|dark)\s*\)$/.exec(rule.media.mediaText.trim());
185
+ if (m) for (const inner of Array.from(rule.cssRules)) if (inner.selectorText !== undefined) take(inner, m[1]);
186
+ }
187
+ }
188
+ return blocks;
189
+ }
190
+
191
+ /**
192
+ * The tokens an element is given for a mode, from blocks in order of strength: each block's `base`, then the mode's own (light over base in
193
+ * light mode; dark over base in dark mode).
194
+ * @param {Array<ReturnType<typeof tokenBlocks>>} layers weakest first
195
+ * @param {'light' | 'dark'} mode
196
+ * @returns {Map<string, string>}
197
+ */
198
+ export function tokensFor(layers, mode) {
199
+ const out = new Map();
200
+ for (const b of layers) {
201
+ for (const [k, v] of b.base) out.set(k, v);
202
+ for (const [k, v] of b[mode]) out.set(k, v);
203
+ }
204
+ return out;
205
+ }
206
+
207
+ /**
208
+ * The default tokens that are worked out from others (`--corn-ok-soft` mixes `--corn-ok`): declared on the element too, or they would keep the
209
+ * value the document's `:root` worked out from the default `--corn-ok` and a theme's `--corn-ok` would not reach its tint. Read from the default
210
+ * tokens' own sheet (the package generates it from explorer/tokens.css), so there is no second list.
211
+ * @param {ReturnType<typeof tokenBlocks>} defaults
212
+ * @returns {ReturnType<typeof tokenBlocks>}
213
+ */
214
+ export function derivedOf(defaults) {
215
+ const out = { base: new Map(), light: new Map(), dark: new Map() };
216
+ for (const key of Object.keys(out)) for (const [k, v] of defaults[key]) if (/var\(/.test(v)) out[key].set(k, v);
217
+ return out;
218
+ }
219
+
220
+ /**
221
+ * The text of an answer, read no further than `max` characters: a larger one is refused as soon as it is seen to be (its `Content-Length`, or the
222
+ * bytes as they come), so a theme of any size never sits whole in the page's memory.
223
+ * @param {Response} res
224
+ * @param {number} max
225
+ * @param {string} [what] what the message names
226
+ */
227
+ export async function readCapped(res, max, what = 'the answer') {
228
+ const tooBig = () => new Error(`${what} is larger than ${max} characters`);
229
+ const declared = Number(res.headers && res.headers.get ? res.headers.get('content-length') : NaN);
230
+ if (Number.isFinite(declared) && declared > max * 4) throw tooBig(); // UTF-8: at most four bytes a character
231
+ if (!res.body || typeof res.body.getReader !== 'function') {
232
+ const text = await res.text();
233
+ if (text.length > max) throw tooBig();
234
+ return text;
235
+ }
236
+ const reader = res.body.getReader();
237
+ const decoder = new TextDecoder();
238
+ let text = '';
239
+ for (;;) {
240
+ const { done, value } = await reader.read();
241
+ if (done) break;
242
+ text += decoder.decode(value, { stream: true });
243
+ if (text.length > max) { reader.cancel().catch(() => {}); throw tooBig(); }
244
+ }
245
+ text += decoder.decode();
246
+ if (text.length > max) throw tooBig();
247
+ return text;
248
+ }
249
+
250
+ /**
251
+ * The server's theme for one scope.
252
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst
253
+ * @param {object} [opts]
254
+ * @param {string} [opts.defaults] the default tokens' CSS text (the package's generated sheet), for the derived tokens
255
+ */
256
+ export function createServerTheme(inst, { defaults = '' } = {}) {
257
+ const win = inst.win;
258
+ let destroyed = false;
259
+ let controller = null;
260
+ let sheet = null;
261
+ /** Roots the sheet is adopted into */
262
+ const roots = new Set();
263
+ /** The element the tokens are on, the names set on it, and the mode they were set for */
264
+ let target = null;
265
+ let applied = [];
266
+ let layers = [];
267
+ let derived = null;
268
+ let mode = 'dark';
269
+ let state = 'none';
270
+
271
+ const make = () => {
272
+ if (sheet || !win || typeof win.CSSStyleSheet !== 'function' || !('replaceSync' in win.CSSStyleSheet.prototype)) return;
273
+ sheet = new win.CSSStyleSheet();
274
+ };
275
+
276
+ /** The derived defaults, parsed once from the generated sheet */
277
+ const derivedBlocks = () => {
278
+ if (derived || !defaults) return derived;
279
+ try {
280
+ const probe = new win.CSSStyleSheet();
281
+ probe.replaceSync(defaults);
282
+ derived = derivedOf(tokenBlocks(probe));
283
+ } catch { derived = null; }
284
+ return derived;
285
+ };
286
+
287
+ const paint = () => {
288
+ if (!target) return;
289
+ for (const name of applied) target.style.removeProperty(name);
290
+ applied = [];
291
+ if (!layers.length) return;
292
+ const all = [];
293
+ const d = derivedBlocks();
294
+ if (d) all.push(d);
295
+ all.push(...layers);
296
+ const tokens = tokensFor(all, mode);
297
+ // a derived default is declared only where the theme does not set the token itself
298
+ for (const [name, value] of tokens) { target.style.setProperty(name, value); applied.push(name); }
299
+ };
300
+
301
+ const say = (next, detail = {}) => { state = next; inst.emit('theme', { state: next, ...detail }); };
302
+
303
+ const fetchText = async (path, signal) => {
304
+ // The theme answers a listed origin without a session and without Allow-Credentials: asked for without credentials
305
+ const res = await inst.fetch(path, { credentials: 'omit', signal });
306
+ if (!res.ok) throw new Error(`GET ${path} answered ${res.status}`);
307
+ return readCapped(res, MAX_THEME_TEXT, path);
308
+ };
309
+
310
+ const theme = {
311
+ /** 'none' (not asked for, or taken back out), 'loading', 'ready' or 'failed' */
312
+ state: () => state,
313
+ /** The adopted sheet, once there is one */
314
+ sheet: () => sheet,
315
+ /**
316
+ * Fetches the standard theme and, when the config names a default, that named theme; builds the one sheet; copies the tokens.
317
+ * A theme that cannot be had leaves the pieces in their default look (`theme` event `failed`).
318
+ * @param {{ theme?: { default?: string | null } | null } | null} config
319
+ */
320
+ async load(config) {
321
+ if (destroyed || !inst.base) return;
322
+ if (controller) controller.abort();
323
+ controller = new AbortController();
324
+ const { signal } = controller;
325
+ say('loading');
326
+ try {
327
+ const name = config && config.theme && typeof config.theme.default === 'string' && THEME_NAME.test(config.theme.default) ? config.theme.default : null;
328
+ const [standard, named] = await Promise.all([
329
+ fetchText(THEME_PATH, signal).catch((err) => { if (signal.aborted) throw err; return null; }),
330
+ name ? fetchText(themePath(name), signal).catch((err) => { if (signal.aborted) throw err; return null; }) : Promise.resolve(null),
331
+ ]);
332
+ if (destroyed || signal.aborted) return;
333
+ if (standard === null && named === null) { say('failed'); return; }
334
+ make();
335
+ if (!sheet) { say('failed', { reason: 'constructable stylesheets are not available' }); return; }
336
+ // One sheet, the standard theme first and the named one after it (it is the stronger: it names the theme on the root)
337
+ sheet.replaceSync([standard, named].filter((x) => x !== null).join('\n'));
338
+ settleSheet(sheet, inst.base);
339
+ layers = [];
340
+ const parse = (text, nm) => {
341
+ const probe = new win.CSSStyleSheet();
342
+ probe.replaceSync(text);
343
+ return tokenBlocks(probe, { name: nm, base: inst.base });
344
+ };
345
+ if (standard !== null) layers.push(parse(standard, null));
346
+ if (named !== null) layers.push(parse(named, name));
347
+ paint();
348
+ say('ready');
349
+ } catch (err) {
350
+ if (destroyed || signal.aborted) return;
351
+ say('failed', { reason: err && err.message ? err.message : String(err) });
352
+ }
353
+ },
354
+ /** Adopts the sheet into a root (a piece's shadow root); returns how to take it out. Adopts it as soon as it exists if it does not yet. */
355
+ adopt(root) {
356
+ if (!root || !('adoptedStyleSheets' in root)) return () => {};
357
+ roots.add(root);
358
+ const put = () => {
359
+ if (!sheet || root.adoptedStyleSheets.includes(sheet)) return;
360
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
361
+ };
362
+ put();
363
+ const off = inst.on('theme', put);
364
+ return () => {
365
+ off();
366
+ roots.delete(root);
367
+ if (sheet && root.adoptedStyleSheets.includes(sheet)) root.adoptedStyleSheets = root.adoptedStyleSheets.filter((s) => s !== sheet);
368
+ };
369
+ },
370
+ /** The element the tokens go on (the scope element) */
371
+ tokensOn(el) {
372
+ theme.release();
373
+ target = el;
374
+ paint();
375
+ },
376
+ /** The mode the tokens are for now ('light' | 'dark') */
377
+ setMode(next) {
378
+ const m = next === 'light' ? 'light' : 'dark';
379
+ if (m === mode) return;
380
+ mode = m;
381
+ paint();
382
+ },
383
+ /** Takes the tokens off the element */
384
+ release() {
385
+ if (target) for (const name of applied) target.style.removeProperty(name);
386
+ applied = [];
387
+ target = null;
388
+ },
389
+ /** Takes the theme back out (`use-theme` turned off, or a new server): the sheet leaves every root and the tokens leave the element */
390
+ unload() {
391
+ if (controller) controller.abort();
392
+ for (const root of roots) if (sheet && root.adoptedStyleSheets.includes(sheet)) root.adoptedStyleSheets = root.adoptedStyleSheets.filter((s) => s !== sheet);
393
+ if (sheet) sheet.replaceSync('');
394
+ sheet = null;
395
+ layers = [];
396
+ paint();
397
+ say('none'); // the pieces read their tokens again: the map is drawn in the look it had without the theme
398
+ },
399
+ destroy() {
400
+ destroyed = true;
401
+ if (controller) controller.abort();
402
+ theme.release();
403
+ for (const root of [...roots]) if (sheet && root.adoptedStyleSheets.includes(sheet)) root.adoptedStyleSheets = root.adoptedStyleSheets.filter((s) => s !== sheet);
404
+ roots.clear();
405
+ sheet = null;
406
+ layers = [];
407
+ },
408
+ };
409
+ return theme;
410
+ }
411
+
412
+ /**
413
+ * Makes every reference the sheet loads the server's, in the parsed rules (never in the text): each declaration of each rule, at any depth
414
+ * (`@media`, `@supports`, `@layer`, `@container`, `@scope`, nested rules, the frames of a `@keyframes`, a `@font-face`), is made absolute against
415
+ * the server, and one that names another origin, another scheme or an escaped `url(` is removed. A rule whose text still names something that is
416
+ * not settled (a shorthand with a `var()` that the declarations do not show, an `@property` whose initial value loads) is removed whole.
417
+ */
418
+ function settleSheet(sheet, base) {
419
+ const visit = (group) => {
420
+ const rules = group.cssRules;
421
+ for (let i = rules.length - 1; i >= 0; i--) {
422
+ const rule = rules[i];
423
+ if (rule.cssRules) visit(rule);
424
+ if (rule.style) {
425
+ const style = rule.style;
426
+ for (const prop of Array.from({ length: style.length }, (_x, k) => style[k])) {
427
+ const value = style.getPropertyValue(prop);
428
+ if (!LOADS.test(unescapeCss(value))) continue;
429
+ const fixed = absolutizeUrls(value, base);
430
+ if (fixed === null) style.removeProperty(prop);
431
+ else if (fixed !== value) style.setProperty(prop, fixed, style.getPropertyPriority(prop));
432
+ }
433
+ }
434
+ // What the declarations did not show (a shorthand waiting on a var(), an @property, an @import a browser kept): the rule goes. What is
435
+ // inside it was settled first, so a group's text is its own conditions and what is left in it
436
+ const own = rule.cssText;
437
+ if (own && LOADS.test(unescapeCss(own)) && !refsSettled(own, base)) {
438
+ if (typeof rule.keyText === 'string' && typeof group.deleteRule === 'function' && group.findRule) group.deleteRule(rule.keyText);
439
+ else group.deleteRule(i);
440
+ }
441
+ }
442
+ };
443
+ visit(sheet);
444
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * @module explorer/engine/topology
3
+ *
4
+ * Giving an instance its map (spec 0011 D2, D4: the engine half of the one-tag review). A host hands a topology in (`{ nodes, edges }`, the object
5
+ * topology.json holds); this is the one place it becomes the instance's state, for the map piece (pieces/map.js) and for the review piece
6
+ * (pieces/review.js), which both call it. Nothing here reads the address or fetches: a piece that loads a topology from a server hands the object over.
7
+ *
8
+ * setTopology(inst, topology) copies the nodes and edges in as the base map (the host's object is never changed: the layout writes on the copies),
9
+ * builds the data-flow preset, keeps the selection when its node is still there; returns whether it is
10
+ * layoutMap(inst, { placeLive }) where the nodes sit for the current view (orbit, or the data-flow lanes). With a proposal open (or live nodes
11
+ * laid in) the base is laid out on its own and the nodes that were there keep their places; only what a proposal adds
12
+ * is placed beside it (proposal-model.js), and the live layer by `placeLive` (cornfield's page hands live-model.js's,
13
+ * which no component carries). The ONE layout: cornfield's page (view.js), the map piece and the review piece all
14
+ * call it. The camera is the caller's
15
+ * setMap(inst, nodes, edges) the map the instance draws from `nodes` and `edges` (the base, or `applyProposal(base, proposal)` while a proposal is
16
+ * open), laid out by layoutMap. It is what the instance answers to the `map:set` ask of engine/proposal.js (the review
17
+ * piece answers it; cornfield's page answers with view.js, which lays in its live layer first and then calls layoutMap)
18
+ */
19
+
20
+ import { buildDataFlow } from '../flow-build.js';
21
+ import { orderAddedLast, pinLanes, placeAddedNodes } from '../proposal-model.js';
22
+ import { computeDegreeCentrality, computeLaneLayout, layoutOrbit } from './layout.js';
23
+
24
+ /** The nodes and edges of a topology that have what the engine needs (an id, and two ends), as arrays; anything else is dropped */
25
+ export function cleanTopology(topology) {
26
+ const nodes = topology && Array.isArray(topology.nodes) ? topology.nodes.filter((n) => n && typeof n.id === 'string') : [];
27
+ const edges = topology && Array.isArray(topology.edges) ? topology.edges.filter((e) => e && typeof e.from === 'string' && typeof e.to === 'string') : [];
28
+ return { nodes, edges };
29
+ }
30
+
31
+ /**
32
+ * Makes `topology` the instance's base map. The selection outlives it when the new map has its node (the same id is the same selection, the
33
+ * instance says nothing), else it is cleared (the instance says so once). The scene is touched; laying out and drawing are the caller's.
34
+ * @param {ReturnType<import('../instance.js').createInstance>} inst
35
+ * @param {{ nodes?: object[], edges?: object[] } | null | undefined} topology
36
+ * @returns {boolean} whether the map has any nodes
37
+ */
38
+ export function setTopology(inst, topology) {
39
+ const { state } = inst;
40
+ const { nodes, edges } = cleanTopology(topology);
41
+ const keep = state.selectedNode ? state.selectedNode.id : null;
42
+ // The host's object is never changed: the map works on copies (the layout writes positions on them)
43
+ state.baseNodes = nodes;
44
+ state.baseEdges = edges;
45
+ state.nodes = nodes.map((n) => ({ ...n }));
46
+ state.edges = edges.map((e) => ({ ...e }));
47
+ state.mapNodes = state.nodes;
48
+ state.mapEdges = state.edges;
49
+ state.flow = buildDataFlow(state.nodes, state.edges);
50
+ const again = keep ? state.nodes.find((n) => n.id === keep) || null : null;
51
+ if (again) { state.selectedEdge = null; state.selectedNode = again; } else if (state.selectedNode || state.selectedEdge) { state.selectedNode = null; state.selectedEdge = null; }
52
+ inst.touchScene();
53
+ return state.nodes.length > 0;
54
+ }
55
+
56
+ /**
57
+ * Where nodes sit for the current view: sizes by degree, then the data-flow lanes or the orbit. With a proposal open the base map is laid out on its
58
+ * own, exactly as it is with none, and the nodes that were there keep those places and sizes: opening a proposal, switching Before, Diff and After,
59
+ * and closing it never move a node that was already on the map; an added node takes a free cell in its lane, or a place beside its parent. Live
60
+ * nodes (cornfield's page lays its live layer in: view.js) are placed beside the code map the same way.
61
+ */
62
+ export function layoutMap(inst, { placeLive } = {}) {
63
+ const { state } = inst;
64
+ computeDegreeCentrality(inst); // node sizes: by degree on the full map ...
65
+ if (state.view === 'dataflow' && state.flow) {
66
+ state.flow.tiers.forEach((tier) => tier.nodes.forEach((n) => { n.r = Math.min(n.r, 13); })); // ... all small in the lanes
67
+ if (!(state.proposal && state.baseNodes && lanesAround(inst))) computeLaneLayout(inst, state.flow);
68
+ } else if (state.baseNodes && (state.proposal || state.nodes.some((n) => n.live))) {
69
+ orbitAround(inst, placeLive); // the code map keeps its places; what a proposal adds and the live layer are placed beside it
70
+ } else layoutOrbit(inst);
71
+ }
72
+
73
+ /**
74
+ * Puts `nodes` and `edges` on the map and lays them out (layoutMap): the data-flow preset is rebuilt from them, an added node last in its lane.
75
+ */
76
+ export function setMap(inst, nodes, edges) {
77
+ const { state } = inst;
78
+ state.mapNodes = nodes;
79
+ state.mapEdges = edges;
80
+ state.nodes = nodes;
81
+ state.edges = edges;
82
+ state.flow = buildDataFlow(nodes, edges);
83
+ orderAddedLast(state.flow); // an added node goes last in its lane, so the nodes that were there keep their rows
84
+ inst.touchScene();
85
+ layoutMap(inst);
86
+ }
87
+
88
+ /** The data-flow lanes while a proposal is open: the base is laid out on its own and pinned, the added nodes take free cells; false when that cannot be done */
89
+ function lanesAround(inst) {
90
+ const { state } = inst;
91
+ const applied = { nodes: state.nodes, edges: state.edges };
92
+ const laid = state.baseNodes.map((n) => ({ ...n }));
93
+ state.nodes = laid;
94
+ state.edges = state.baseEdges;
95
+ computeDegreeCentrality(inst);
96
+ const baseFlow = buildDataFlow(laid, state.baseEdges);
97
+ baseFlow.tiers.forEach((tier) => tier.nodes.forEach((n) => { n.r = Math.min(n.r, 13); }));
98
+ computeLaneLayout(inst, baseFlow);
99
+ state.nodes = applied.nodes;
100
+ state.edges = applied.edges;
101
+ const pinned = pinLanes(state.flow, baseFlow);
102
+ inst.touchScene();
103
+ return pinned;
104
+ }
105
+
106
+ /** The orbit while a proposal is open (or live nodes are in): the base is laid out as it is with none, and only the added nodes are placed, next to their parent */
107
+ function orbitAround(inst, placeLive) {
108
+ const { state } = inst;
109
+ const applied = { nodes: state.nodes, edges: state.edges };
110
+ const laid = state.baseNodes.map((n) => ({ ...n }));
111
+ state.nodes = laid;
112
+ state.edges = state.baseEdges;
113
+ computeDegreeCentrality(inst);
114
+ layoutOrbit(inst); // also sets the rings
115
+ const at = new Map(laid.map((n) => [n.id, n]));
116
+ state.nodes = applied.nodes;
117
+ state.edges = applied.edges;
118
+ computeDegreeCentrality(inst);
119
+ state.nodes.forEach((n) => {
120
+ const was = at.get(n.id);
121
+ if (was) { n.x = was.x; n.y = was.y; n.r = was.r; }
122
+ });
123
+ placeAddedNodes(state.nodes, state.edges);
124
+ if (placeLive) placeLive(state.nodes, state.edges);
125
+ inst.touchScene();
126
+ }
@@ -167,11 +167,8 @@
167
167
  <!-- Review tokens (explorer/review-tokens.js): shown only when somebody is signed in to a forge -->
168
168
  <button type="button" id="tokens-btn" class="hx-account-item" aria-haspopup="dialog" aria-expanded="false" aria-controls="tokens-dialog" title="Review tokens: let a script or a chat bot approve or send back a proposal as you" hidden data-corn="tokens-button">Review tokens</button>
169
169
 
170
- <!-- Proposals: what a change would add, change and remove, drawn on the map (proposal.js). Only without the Work panel (no forge, or no sign-in): with it, its Specs tab lists them and forge-panel.js hides this -->
171
- <div id="proposal-wrap">
172
- <button type="button" id="proposal-btn" class="hx-account-item" data-action="toggle-proposals-menu" aria-haspopup="true" aria-expanded="false" title="Open a proposal: what a change would add, change and remove" data-corn="proposals-button"><span data-corn-string="proposals">Proposals</span><span class="hx-faint" aria-hidden="true">▾</span></button>
173
- <div id="proposal-menu" class="hx-menu hx-menu--proposals" hidden data-corn="proposals-menu"></div>
174
- </div>
170
+ <!-- Proposals: what a change would add, change and remove, drawn on the map. It is part of the proposal piece (explorer/pieces/proposal.js): page.js mounts it here. Only without the Work panel (no forge, or no sign-in): with it, its Specs tab lists them and forge-panel.js hides this -->
171
+ <!--corn-piece:proposal/menu-->
175
172
 
176
173
  <!-- The config's links (cornfield.config.js `links`), the forge and Docs, then Sign out: filled by explorer/plugins.js -->
177
174
  <div id="cf-links" class="hx-links" data-corn="links"></div>
@@ -193,61 +190,11 @@
193
190
 
194
191
  <!-- Below 768px the proposal bar, the scenario player and the node panel stack here as bottom sheets (sheets.js); from 768px the dock is display: contents -->
195
192
  <div id="sheet-dock" class="hx-dock" data-corn="dock">
196
- <!-- The open proposal, a toolbar: title, counts, Before / Diff / After, Play, Edit, Send back, Approve, ⋯ (proposal.js, review.js, whatif.js, scenario-ui.js) -->
197
- <section id="proposal-bar" class="hx-proposal-bar glass" aria-label="Open proposal" hidden data-corn="proposal-bar">
198
- <p id="proposal-message" class="hx-proposal-message" data-corn="message" role="status" hidden></p>
199
- <div id="proposal-ways" class="hx-proposal-ways" role="group" aria-label="Ways on" data-corn="proposal-ways" hidden></div>
200
- <div id="proposal-body">
201
- <div class="hx-proposal-head" data-corn="proposal-head" role="group" aria-label="Proposal actions">
202
- <h2 id="proposal-title" class="hx-proposal-name" data-corn="proposal-title"></h2>
203
- <a id="proposal-source" class="hx-proposal-source" data-corn="proposal-source" hidden></a>
204
- <div class="hx-proposal-counts">
205
- <div id="proposal-chip" class="hx-proposal-chip" data-corn="proposal-counts"></div>
206
- <p id="proposal-peek" class="hx-proposal-peek"></p>
207
- <button type="button" id="proposal-mode" class="hx-proposal-mode" data-corn="proposal-mode" data-action="toggle-proposal-mode" data-peek-ok aria-expanded="false" aria-controls="proposal-seg" title="Before, Diff or After"></button>
208
- </div>
209
- <div id="proposal-seg" class="hx-seg" data-corn="compare" role="group" aria-label="Compare">
210
- <button data-corn="compare-option" type="button" class="hx-seg-btn" data-action="proposal-view" data-view="before" aria-pressed="false" data-corn-string="before">Before</button>
211
- <button data-corn="compare-option" type="button" class="hx-seg-btn" data-action="proposal-view" data-view="diff" aria-pressed="true" data-corn-string="diff">Diff</button>
212
- <button data-corn="compare-option" type="button" class="hx-seg-btn" data-action="proposal-view" data-view="after" aria-pressed="false" data-corn-string="after">After</button>
213
- </div>
214
- <div class="hx-proposal-tools">
215
- <!-- Shown only while there are what-if edits: off, the map is the proposal as written; the edits are kept and still go with a review (whatif.js) -->
216
- <!-- The review narrows the map to the change; this puts the whole map back, as Diff always was (layers.js setWholeMap). Off at every opening -->
217
- <!-- Its words are "Whole map", which read right pressed or not; its name and tooltip are the full "Show the whole map". On a desk it sits beside the title, so the bar keeps its rows (css/proposal.css) -->
218
- <button data-corn="whole-map" data-corn-kind="secondary" type="button" id="proposal-whole" class="hx-btn" data-action="proposal-whole" aria-pressed="false" aria-label="Show the whole map" title="Show the whole map" data-peek-ok data-corn-string="wholeMap" data-corn-string-aria-label="showWholeMap">Whole map</button>
219
- <button data-corn-kind="secondary" type="button" id="proposal-myedits" class="hx-btn" aria-pressed="true" data-peek-ok data-corn-string="myEdits" hidden>My edits</button>
220
- <button data-corn-kind="secondary" type="button" id="proposal-edit" class="hx-btn" aria-expanded="false" aria-controls="whatif" title="Try a change: add a node or an edge, reword a scenario">Edit</button>
221
- </div>
222
- <div class="hx-proposal-more">
223
- <button type="button" id="proposal-more" class="hx-btn hx-btn--icon" data-action="toggle-proposal-more" aria-haspopup="menu" aria-expanded="false" aria-controls="proposal-more-menu" aria-label="More" data-corn-kind="icon"><svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><circle cx="3" cy="8" r="1.5"/><circle cx="8" cy="8" r="1.5"/><circle cx="13" cy="8" r="1.5"/></svg></button>
224
- <div id="proposal-more-menu" class="hx-proposal-more-menu glass" data-corn="proposal-menu" role="menu" aria-label="More" hidden>
225
- <button type="button" role="menuitem" class="hx-btn hx-btn--quiet" data-action="close-proposal" title="Close the proposal and go back to the map" data-corn-kind="quiet" data-corn-string="closeProposal">Close</button>
226
- </div>
227
- </div>
228
- </div>
229
- <details id="proposal-errors" class="hx-proposal-errors" data-corn="proposal-errors" hidden>
230
- <summary data-corn="summary" id="proposal-errors-count"></summary>
231
- <ul id="proposal-errors-list"></ul>
232
- <p class="hx-faint">The map shows what it can.</p>
233
- </details>
234
- </div>
235
- </section>
193
+ <!-- The open proposal, a toolbar: title, counts, Before / Diff / After, Whole map, Edit, ⋯. It is a piece (explorer/pieces/proposal.js): page.js mounts it here -->
194
+ <!--corn-piece:proposal/bar-->
236
195
 
237
- <!-- The review column (review-column.js, spec 0006): what the proposal changes, and the personas and the scenarios that apply to them. Docked left of the map from 768px, the expanded proposal sheet's body on a phone -->
238
- <aside id="review-column" class="hx-review-column glass" aria-label="Review" data-corn="review-column" hidden>
239
- <div class="hx-rc-scroll">
240
- <p id="proposal-summary" class="hx-proposal-summary" hidden></p>
241
- <div id="review-lists" class="hx-rc-lists"></div>
242
- </div>
243
- <!-- The decision, the column's foot: Send back and Approve (review.js). Spec 0007 puts its line about what Approve does above them here. -->
244
- <div id="review-decision" class="hx-rc-foot" data-corn="decision" role="group" aria-label="Decision">
245
- <div class="hx-proposal-actions">
246
- <button data-corn-kind="secondary" type="button" class="hx-btn" data-review="notes" data-peek-ok title="Send it back to the drafting agent with a note and your edits" data-corn-string="sendBack">Send back</button>
247
- <button type="button" class="hx-btn hx-btn--approve" data-review="approved" data-peek-ok title="Sign this proposal off" data-corn-kind="approve" data-corn-string="approve">Approve</button>
248
- </div>
249
- </div>
250
- </aside>
196
+ <!-- The review column (explorer/pieces/changes.js, spec 0006): what the proposal changes, and the personas and the scenarios that apply to them. Docked left of the map from 768px, the expanded proposal sheet's body on a phone. The decision (explorer/pieces/decision.js, spec 0007) is its foot: the column keeps its place -->
197
+ <!--corn-piece:changes/column-->
251
198
 
252
199
  <!-- The Work panel (forge-panel.js): Specs, PRs, Issues, Threads, Runs and Deploys, in the order of the loop. A slide-over from the left on desktop, a bottom sheet on a phone; hidden and inert until the config names a forge. `forge-panel` on the inner box is the old name of the hook, kept for one release (docs/theming.md) -->
253
200
  <p id="offline-banner" class="hx-offline" data-corn="notice" hidden></p>