@popcorn245/cornfield 0.51.7 → 0.52.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/cli/cornfield.js +7 -0
  2. package/core/config.js +2 -1
  3. package/core/map-tokens.js +2 -4
  4. package/core/repo.js +59 -4
  5. package/core/strings.js +5 -0
  6. package/core/text.js +18 -0
  7. package/core/validate.js +17 -10
  8. package/explorer/engine/flow-legend.js +28 -0
  9. package/explorer/engine/flow-ui.js +3 -22
  10. package/explorer/engine/keyboard.js +28 -15
  11. package/explorer/engine/map-rect.js +2 -2
  12. package/explorer/engine/piece.js +27 -2
  13. package/explorer/engine/render.js +7 -4
  14. package/explorer/engine/roots.js +71 -0
  15. package/explorer/engine/search-status.js +2 -8
  16. package/explorer/flows.js +2 -1
  17. package/explorer/instance.js +39 -10
  18. package/explorer/pieces/around.js +114 -0
  19. package/explorer/pieces/layers.js +28 -14
  20. package/explorer/pieces/map.js +14 -1
  21. package/explorer/pieces/node-panel.js +33 -15
  22. package/explorer/pieces/search.js +43 -12
  23. package/explorer/scene.js +1 -1
  24. package/explorer/search-match.js +53 -0
  25. package/explorer/search-model.js +6 -48
  26. package/package.json +1 -1
  27. package/plugins/cloud/index.js +5 -3
  28. package/plugins/compose/index.js +12 -6
  29. package/plugins/docs/site.js +2 -2
  30. package/plugins/openapi/index.js +10 -5
  31. package/plugins/starter/index.js +2 -2
  32. package/plugins/world/index.js +3 -2
  33. package/server/agent-runs.js +3 -4
  34. package/server/components.js +4 -3
  35. package/server/db.js +7 -0
  36. package/server/files.js +97 -15
  37. package/server/forge-routes.js +8 -6
  38. package/server/proposal-walk.js +25 -6
  39. package/server/proposals.js +5 -3
  40. package/server/reviews.js +9 -2
  41. package/server/server.js +43 -31
  42. package/server/spec-poll.js +2 -2
package/cli/cornfield.js CHANGED
@@ -27,6 +27,8 @@ import { deriveTopology } from '../core/derive.js';
27
27
  import { planSync, placeholderCounts } from '../core/sync.js';
28
28
  import { validateRepo, readTopology } from '../core/validate.js';
29
29
  import { proposalProblems, proposalStatus, summarize, personaWarnings } from '../core/proposal.js';
30
+ import { repoReader } from '../core/repo.js';
31
+ import { quote } from '../core/text.js';
30
32
 
31
33
  const HERE = path.dirname(fileURLToPath(import.meta.url));
32
34
  const PKG = JSON.parse(fs.readFileSync(path.join(HERE, '..', 'package.json'), 'utf8'));
@@ -84,6 +86,11 @@ async function setup(flags) {
84
86
 
85
87
  function saveTopology(config, data) {
86
88
  const file = path.join(config.root, config.topology);
89
+ // The write follows a symlink, so the map is written only where it really lies in the repo: never through a link out, or a link to nothing (which would make a file wherever it points)
90
+ const io = repoReader(config.root);
91
+ let link = false;
92
+ try { link = fs.lstatSync(file).isSymbolicLink(); } catch { /* not there yet */ }
93
+ if (!io.inside(config.topology) || (link && !io.exists(config.topology))) throw new Error(`${quote(config.topology)} leads outside the repo or to nothing; the map is not written.`);
87
94
  fs.writeFileSync(file, `${JSON.stringify({ version: data.version || '1.0.0', ...data, updatedAt: new Date().toISOString() }, null, 2)}\n`, 'utf8');
88
95
  }
89
96
 
package/core/config.js CHANGED
@@ -45,6 +45,7 @@ import fs from 'node:fs';
45
45
  import os from 'node:os';
46
46
  import path from 'node:path';
47
47
  import { pathToFileURL, fileURLToPath } from 'node:url';
48
+ import { repoReader } from './repo.js';
48
49
  import { themeProblems } from './theme.js';
49
50
  import { brandProblems } from './brand.js';
50
51
  import { stringsProblems } from './strings.js';
@@ -643,7 +644,7 @@ export async function loadConfig(root, { env = process.env, file } = {}) {
643
644
 
644
645
  function readPackageName(root) {
645
646
  try {
646
- return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).name || null;
647
+ return JSON.parse(repoReader(root).read('package.json')).name || null; // a package.json that links out of the repo is not read
647
648
  } catch {
648
649
  return null;
649
650
  }
@@ -9,6 +9,7 @@
9
9
  import { declaredProps, expand, projectGroupOf, resolveProps, themesToCheck } from './contrast.js';
10
10
  import { iconKeyShape, parseKindToken } from './layers.js';
11
11
  import { readColor } from './color.js';
12
+ import { quote } from './text.js';
12
13
  import { MAX_NODE_COLOR_CHARS } from '../explorer/css-color.js';
13
14
  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';
14
15
 
@@ -94,9 +95,6 @@ export function layerTokenWarnings(config, map) {
94
95
  export const MAX_NODE_COLOR_WARNINGS = 10;
95
96
  const SHOWN_CHARS = 40;
96
97
 
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
98
  /**
101
99
  * 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
100
  * ...), cut to `max` characters, and with the controls JSON leaves alone made visible too (DEL, the C1 controls such as U+009B, which some
@@ -110,7 +108,7 @@ export function quoted(v, max = SHOWN_CHARS) {
110
108
  try { t = typeof v === 'string' ? v : JSON.stringify(v) ?? String(v); } catch { t = String(v); }
111
109
  const chars = Array.from(t);
112
110
  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')}`);
111
+ return quote(t);
114
112
  }
115
113
 
116
114
  /** Colour functions a current browser reads that core/color.js does not work out (it reads rgb() and hsl() only in their plainer forms) */
package/core/repo.js CHANGED
@@ -8,10 +8,14 @@
8
8
 
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
+ import { quote } from './text.js';
11
12
 
12
13
  /** Folders a walk never goes into */
13
14
  export const SKIP_DIRS = new Set(['node_modules', '.git', '.claude', '.worktrees', 'dist', 'coverage', '.cornfield']);
14
15
 
16
+ /** What a reader throws for a path whose real path is outside the repo: it names the path as given, as a JSON string, never where it leads */
17
+ export const outsideError = (rel) => Object.assign(new Error(`${quote(String(rel))} is outside the repo.`), { code: 'EOUTSIDE' });
18
+
15
19
  /**
16
20
  * The readers for a repo root. Every path is relative to the root with forward slashes.
17
21
  * @param {string} root an absolute folder
@@ -65,14 +69,21 @@ export function repoReader(root) {
65
69
  if (st.isSymbolicLink()) return { link: true, ok: insideAbs(at), st };
66
70
  return { link: false, ok: at === rootAt || folderInside(path.dirname(at)), st };
67
71
  };
68
- const outside = (rel) => Object.assign(new Error(`${JSON.stringify(String(rel))} is outside the repo.`), { code: 'EOUTSIDE' });
69
72
  const read = (rel) => {
70
73
  while (pending.length) for (const f of pending.pop()) walked.add(f);
71
74
  if (!walked.has(rel)) {
72
75
  const m = look(rel);
73
- if (m && !m.ok) throw outside(rel);
76
+ if (m && !m.ok) throw outsideError(rel);
77
+ }
78
+ // Opened without waiting, and read only if it is a file (a folder still fails as EISDIR): a FIFO or a device in the repo would block a read forever
79
+ const fd = fs.openSync(abs(rel), fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0));
80
+ try {
81
+ const st = fs.fstatSync(fd);
82
+ if (!st.isFile() && !st.isDirectory()) throw Object.assign(new Error(`${quote(String(rel))} is not a file.`), { code: 'ENOTFILE' });
83
+ return fs.readFileSync(fd, 'utf8').replace(/\r\n/g, '\n');
84
+ } finally {
85
+ fs.closeSync(fd);
74
86
  }
75
- return fs.readFileSync(abs(rel), 'utf8').replace(/\r\n/g, '\n');
76
87
  };
77
88
  const exists = (rel) => { const m = look(rel); return !!m && m.ok && (!m.link || fs.existsSync(abs(rel))); };
78
89
  const rawIsDir = (rel) => {
@@ -148,7 +159,51 @@ export function leavesRepo(io, p) {
148
159
  * @param {string} who the deriver's name
149
160
  * @param {unknown} p
150
161
  */
151
- export const outsideProblem = (who, p) => `${who}: ${JSON.stringify(p)} is outside the repo; only files and folders of the repo are read.`;
162
+ export const outsideProblem = (who, p) => `${who}: ${quote(p)} is outside the repo; only files and folders of the repo are read.`;
163
+
164
+ /**
165
+ * The problem `validate` fails on for a config value that names a folder where a file is wanted (`''`, `.` and `src/` are folders).
166
+ * @param {string} who the deriver's name
167
+ * @param {string} option the option, as the config spells it (`caddyfiles`, `specs[].file`)
168
+ * @param {unknown} p
169
+ */
170
+ export const notFileProblem = (who, option, p) => `${who}: options.${option} ${quote(p)} is a folder, not a file.`;
171
+
172
+ /**
173
+ * What is wrong with a config value that must name a file of the repo, or null: it leaves the repo (`outsideProblem`), or is a folder
174
+ * (`notFileProblem`). A file that is not there is the deriver's own word. `io` is a repo reader.
175
+ * @param {{ inside: (rel: string) => boolean, isDir: (rel: string) => boolean }} io
176
+ * @param {string} who
177
+ * @param {string} option
178
+ * @param {unknown} p
179
+ * @returns {string | null}
180
+ */
181
+ export function fileOptionProblem(io, who, option, p) {
182
+ if (leavesRepo(io, p)) return outsideProblem(who, p);
183
+ if (typeof p === 'string' && io.isDir(p)) return notFileProblem(who, option, p);
184
+ return null;
185
+ }
186
+
187
+ /**
188
+ * A list of paths a config names, each place once: `a`, `./a`, `a/`, `a/.` and `a/../a` are one place, and so are `` and `.` (the
189
+ * repo itself). The first spelling stays; a later one is dropped, as the deriver would read the same place twice. `key` picks the path of an entry.
190
+ * @template T
191
+ * @param {T[]} list
192
+ * @param {(entry: T) => unknown} [key]
193
+ * @returns {T[]}
194
+ */
195
+ export function eachPlaceOnce(list, key = (e) => e) {
196
+ const seen = new Set();
197
+ return list.filter((e) => {
198
+ const p = key(e);
199
+ if (typeof p !== 'string') return true;
200
+ const at = path.posix.normalize(p.replace(/^\.\/+/, '') || '.').replace(/\/+$/, '');
201
+ const k = at === '.' ? '' : at;
202
+ if (seen.has(k)) return false;
203
+ seen.add(k);
204
+ return true;
205
+ });
206
+ }
152
207
 
153
208
  /**
154
209
  * For `missingPaths`: whether a path `repoPaths` does not list is in the repo all the same, because a symlink on its way
package/core/strings.js CHANGED
@@ -118,6 +118,11 @@ export const STRINGS = Object.freeze({
118
118
  sourceBadAddress: 'That is not the address of a cornfield server',
119
119
  sourceVersion: 'This map and its server are different versions',
120
120
  sourceSecondMap: 'This scope already has a map',
121
+ // The pieces around the map (corn-node-panel, corn-layers, corn-search) when they have nothing to work with
122
+ nodePanelEmpty: 'Select a node on the map to see its details',
123
+ needsScope: 'This needs a corn-scope around it, with a corn-map in it',
124
+ needsMap: 'This needs a corn-map in the same corn-scope',
125
+ waitingForMap: 'Waiting for the map',
121
126
  });
122
127
 
123
128
  /** The longest a value may be, in characters */
package/core/text.js CHANGED
@@ -16,3 +16,21 @@ const ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&
16
16
  export function escapeHtml(value) {
17
17
  return String(value ?? '').replace(/[&<>"']/g, (ch) => ESCAPES[ch]);
18
18
  }
19
+
20
+ /** What JSON leaves as it is but a terminal must not get raw: DEL and the C1 controls (U+009B is an escape to some terminals), and the invisible and bidirectional marks */
21
+ const UNSEEN = new RegExp('[\\u007f-\\u009f\\u00ad\\u061c\\u200b-\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2060-\\u206f\\ufeff\\ufff9-\\ufffb]', 'g');
22
+
23
+ /**
24
+ * A path or a value from the config or from a file of the repo, as a message prints it: a JSON string (`"a/b"`; any
25
+ * other value as `JSON.stringify` writes it), so a line break or an escape character in it is `\n`, `\u001b`, and it
26
+ * cannot forge a line of output; DEL, the C1 controls and the invisible and bidirectional marks, which JSON leaves
27
+ * alone, are written as escapes too (a zero-width joiner or non-joiner among them). Letters and marks of any script, emoji
28
+ * and a non-breaking space are left as they are.
29
+ * @param {unknown} value
30
+ * @returns {string}
31
+ */
32
+ export function quote(value) {
33
+ let t;
34
+ try { t = JSON.stringify(value) ?? String(value); } catch { t = String(value); }
35
+ return t.replace(UNSEEN, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
36
+ }
package/core/validate.js CHANGED
@@ -22,7 +22,7 @@ import { PERSONAS_FILE, validatePersonas } from './personas.js';
22
22
  import { CLOUD_FILE, cloudNodeProblems } from './cloud.js';
23
23
  import { deriveTopology } from './derive.js';
24
24
  import { missingPaths, planSync } from './sync.js';
25
- import { reachable, repoPaths, repoReader } from './repo.js';
25
+ import { leavesRepo, outsideError, outsideProblem, reachable, repoPaths, repoReader } from './repo.js';
26
26
  import { checkThemeContrast } from './contrast.js';
27
27
  import { layerTokenWarnings, mapTokenWarnings, nodeColorNotes, nodeColorWarnings, quoted } from './map-tokens.js';
28
28
  import { layersMapWarnings } from './layers.js';
@@ -184,13 +184,19 @@ export function validateTopology(topology, { requireExternalKind = true } = {})
184
184
  * @returns {string[]} one line per problem, naming the file
185
185
  */
186
186
  export function validateProposalFiles(topology, dir, root = path.dirname(dir)) {
187
- if (!fs.existsSync(dir)) return [];
187
+ // Read through the repo's reader (core/repo.js): a proposal, or a mockup, that is a link out of the repo is not read, and nothing quotes from it
188
+ const io = repoReader(root);
189
+ const posix = (p) => p.split(path.sep).join('/');
190
+ const dirRel = posix(path.relative(root, dir)) || '.';
191
+ if (leavesRepo(io, dirRel)) return [outsideProblem('proposals', dirRel)];
192
+ if (!io.exists(dirRel)) return [];
188
193
  const problems = [];
189
- for (const file of fs.readdirSync(dir).filter((f) => f.endsWith('.json') && !f.endsWith('.review.json')).sort()) {
190
- const where = path.relative(root, path.join(dir, file)).split(path.sep).join('/');
194
+ for (const file of io.list(dirRel).filter((f) => f.endsWith('.json') && !f.endsWith('.review.json'))) {
195
+ const rel = path.posix.join(dirRel, file);
196
+ const where = posix(path.relative(root, path.join(dir, file)));
191
197
  let proposal;
192
198
  try {
193
- proposal = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));
199
+ proposal = JSON.parse(io.read(rel));
194
200
  } catch (err) {
195
201
  problems.push(`${where} is not valid JSON: ${err.message}`);
196
202
  continue;
@@ -200,8 +206,8 @@ export function validateProposalFiles(topology, dir, root = path.dirname(dir)) {
200
206
  // A mockup the proposal lists must be a file beside it, so a typo fails here and not only in the explorer
201
207
  for (const m of mockupsOf(proposal)) {
202
208
  let ok = false;
203
- try { ok = fs.statSync(path.join(dir, ...m.path.split('/'))).isFile(); } catch { ok = false; }
204
- if (!ok) problems.push(`${where}: mockups[${m.index}].path: "${m.path}" is not a file in ${path.relative(root, dir).split(path.sep).join('/') || '.'}.`);
209
+ try { const at = path.posix.join(dirRel, ...m.path.split('/')); ok = io.exists(at) && fs.statSync(path.join(root, ...at.split('/'))).isFile(); } catch { ok = false; }
210
+ if (!ok) problems.push(`${where}: mockups[${m.index}].path: "${m.path}" is not a file in ${dirRel}.`);
205
211
  }
206
212
  }
207
213
  return problems;
@@ -246,9 +252,10 @@ export function validateCloudNodes(topology, root) {
246
252
 
247
253
  /** The committed map of a repo, or null when there is none yet */
248
254
  export function readTopology(config) {
249
- const file = path.join(config.root, config.topology);
250
- if (!fs.existsSync(file)) return null;
251
- return JSON.parse(fs.readFileSync(file, 'utf8'));
255
+ const io = repoReader(config.root); // a map that leads out of the repo is not read: it is refused, not taken for a missing one (sync would write a new map over it)
256
+ if (io.exists(config.topology)) return JSON.parse(io.read(config.topology));
257
+ if (!io.inside(config.topology)) throw outsideError(config.topology);
258
+ return null;
252
259
  }
253
260
 
254
261
  /**
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @module explorer/engine/flow-legend
3
+ *
4
+ * The legend of the data-flow lines in the Layers menu, on an instance. Its own module, apart from the node panel's flow block (flow-ui.js), so a
5
+ * component that has the panel and not the menu does not carry it.
6
+ */
7
+
8
+ import { escapeHtml as escHtml } from '../../core/text.js';
9
+ import { themed } from '../theme-model.js';
10
+ import { layersOf } from '../layer-model.js';
11
+ import { FLOW_STYLES } from '../flow-style.js';
12
+
13
+ /** Draws the data-flow legend into `el`, the Layers menu's own place for it (the piece that owns it says which) */
14
+ export function renderFlowLegend(inst, el) {
15
+ if (!el) return;
16
+ const { state } = inst;
17
+ const activeLayers = layersOf(state);
18
+ if (activeLayers.flow === false && activeLayers.table === false) { el.innerHTML = ''; el.hidden = true; return; }
19
+ el.hidden = false;
20
+ const row = (swatch, text) => `<div class="hx-legend-row"><span class="hx-legend-swatch">${swatch}</span><span>${text}</span></div>`;
21
+ el.innerHTML = `
22
+ <div class="hx-menu-section" data-corn="menu-section" part="menu-section">
23
+ <div class="hx-menu-title" data-corn="menu-title" part="menu-title">
24
+ <span>Data Flow</span>
25
+ </div>
26
+ ${Object.values(FLOW_STYLES).map((s) => row(`<span data-corn="swatch" part="swatch" class="hx-swatch-line" data-style="background:${escHtml(themed(s.color, state.theme))}"></span>`, s.label)).join('')}
27
+ </div>`;
28
+ }
@@ -1,33 +1,14 @@
1
1
  /**
2
2
  * @module explorer/engine/flow-ui
3
3
  *
4
- * Data flow in the Layers menu and the node panel, on an instance: the legend of the flow lines and the "Sends to / Gets from" block of a node's
5
- * panel. How a flow edge is styled is flow-style.js; the data-flow preset is flows.js `buildDataFlow` (a pure function of nodes and edges).
4
+ * Data flow in the node panel, on an instance: the "Sends to / Gets from" block of a node's panel (the Layers menu's legend of the flow lines is
5
+ * flow-legend.js). How a flow edge is styled is flow-style.js; the data-flow preset is flows.js `buildDataFlow` (a pure function of nodes and edges).
6
6
  */
7
7
 
8
8
  import { escapeHtml as escHtml } from '../../core/text.js';
9
- import { themed } from '../theme-model.js';
10
9
  import { capped } from '../capped.js';
11
- import { layersOf } from '../layer-model.js';
12
- import { FLOW_STYLES } from '../flow-style.js';
13
-
14
- export function renderFlowLegend(inst) {
15
- const el = inst.el('flow-legend');
16
- if (!el) return;
17
- const { state } = inst;
18
- const activeLayers = layersOf(state);
19
- if (activeLayers.flow === false && activeLayers.table === false) { el.innerHTML = ''; el.hidden = true; return; }
20
- el.hidden = false;
21
- const row = (swatch, text) => `<div class="hx-legend-row"><span class="hx-legend-swatch">${swatch}</span><span>${text}</span></div>`;
22
- el.innerHTML = `
23
- <div class="hx-menu-section" data-corn="menu-section" part="menu-section">
24
- <div class="hx-menu-title" data-corn="menu-title" part="menu-title">
25
- <span>Data Flow</span>
26
- </div>
27
- ${Object.values(FLOW_STYLES).map((s) => row(`<span data-corn="swatch" part="swatch" class="hx-swatch-line" style="background:${themed(s.color, state.theme)}"></span>`, s.label)).join('')}
28
- </div>`;
29
- }
30
10
 
11
+ /** The "Sends to" and "Gets from" block of a node's panel */
31
12
  export function flowSummary(inst, node) {
32
13
  const { state } = inst;
33
14
  const nameOf = (id) => (state.nodes.find((n) => n.id === id) || { label: id }).label;
@@ -8,7 +8,7 @@
8
8
  * the middle, 0 fits, N and P (or ] and [) step through the visible nodes in reading order and select each, centred, Home and End the first
9
9
  * and the last, Enter goes into the panel, Escape closes it, and in Freeform Alt+arrow moves the selected node. The keys are the canvas's:
10
10
  * they act only while the canvas has the focus, so another instance on the page is not moved;
11
- * - `#map-announcer` (a polite live region) says where the keyboard landed: the node, its type, its connections, its place; the zoom; a
11
+ * - the map's announcer (a polite live region, `#map-announcer`) says where the keyboard landed: the node, its type, its connections, its place; the zoom; a
12
12
  * search's hit. `announce(inst, text)` also tells the instance (`announce`), for a host that keeps its live region elsewhere;
13
13
  * - with a search on, N and P step through its matches: the search piece answers `search:active` and `search:step` (pieces/search.js).
14
14
  *
@@ -22,20 +22,33 @@ import { saveFreeformPositions } from './layout.js';
22
22
  import * as K from '../keyboard-model.js';
23
23
  import { frameSelection, litNodes } from '../selection-view.js';
24
24
 
25
- /** Tells a screen reader `text` (politely: after what it is reading). The same words twice are said twice. */
25
+ /**
26
+ * A writer for one live region (`el`): the text is cleared, then set a moment later, which is what makes a region speak the same words again.
27
+ * The piece that owns the region answers `announce:write` (or `announce:fallback`) with it.
28
+ */
29
+ export function speaker(inst, el) {
30
+ let timer = null;
31
+ inst.own(() => clearTimeout(timer));
32
+ return (text) => {
33
+ el.textContent = '';
34
+ clearTimeout(timer);
35
+ timer = setTimeout(() => { el.textContent = text; }, 30);
36
+ };
37
+ }
38
+
39
+ /**
40
+ * Tells a screen reader `text` (politely: after what it is reading). The same words twice are said twice. It is told to the instance (`announce`),
41
+ * and written by the piece that owns a live region: the map's (`announce:write`), else one of a piece that stands without a map (`announce:fallback`).
42
+ */
26
43
  export function announce(inst, text) {
27
- const mem = inst.slot('announce', () => {
28
- const m = { timer: null };
29
- inst.own(() => clearTimeout(m.timer));
30
- return m;
31
- });
32
44
  inst.emit('announce', text);
45
+ if (inst.ask('announce:write', text) === true || inst.ask('announce:fallback', text) === true) return;
46
+ // No piece answered: an instance whose own root holds the announcer (markup a host or a test built by hand, with no map piece mounted) is still told
33
47
  const el = inst.el('map-announcer');
34
48
  if (!el) return;
35
- el.textContent = '';
36
- clearTimeout(mem.timer);
37
- // a fresh text node a moment later is what makes a live region speak again
38
- mem.timer = setTimeout(() => { el.textContent = text; }, 30);
49
+ const mem = inst.slot('announce', () => ({ el: null, say: null }));
50
+ if (mem.el !== el) { mem.el = el; mem.say = speaker(inst, el); }
51
+ mem.say(text);
39
52
  }
40
53
 
41
54
  /** The visible nodes, in the order the keys step through them */
@@ -45,8 +58,8 @@ const stepOrder = (inst) => K.readingOrder(inst.state.nodes.filter((n) => inst.m
45
58
  export function centreTarget(inst, node, zoom = inst.state.camera.zoom) {
46
59
  const { width, height } = inst.state;
47
60
  const visibleHeight = Math.max(160, height - (inst.state.coveredBottom || 0));
48
- const panel = inst.el('spec-drawer');
49
- const visibleWidth = width >= 768 && panel && panel.classList.contains('drawer-open') ? Math.max(160, width - (panel.offsetWidth || 480)) : width;
61
+ const covers = inst.ask('panel:covers'); // an open slide-over node panel covers the right of the map (pieces/node-panel.js); one in a box of its own covers nothing
62
+ const visibleWidth = width >= 768 && covers ? Math.max(160, width - (covers.right || 480)) : width;
50
63
  // The issues and PRs panel slides in from the left (forge-panel.js)
51
64
  const forge = inst.el('forge-panel');
52
65
  const left = width >= 768 && forge && forge.classList.contains('forge-open') ? Math.min(forge.offsetWidth || 400, visibleWidth - 160) : 0;
@@ -60,7 +73,7 @@ export function centreOn(inst, node) {
60
73
  }
61
74
 
62
75
  function land(inst, node, order) {
63
- if (!node) { announce(inst, inst.el('legend-dropdown') ? 'No nodes are shown. Turn a layer on in the Layers menu.' : 'No nodes are shown.'); return; } // the Layers menu, when the instance has one
76
+ if (!node) { announce(inst, inst.ask('layers:present') ? 'No nodes are shown. Turn a layer on in the Layers menu.' : 'No nodes are shown.'); return; } // the Layers menu, when the instance has one
64
77
  selectNode(inst, node, { frame: true, source: 'keyboard' }); // the keyboard's selection frames the node and what it lights (spec 0008 D6)
65
78
  announce(inst, K.describeNode(node, order.length, order.indexOf(node)));
66
79
  }
@@ -132,7 +145,7 @@ function onMapKey(inst, e) {
132
145
  break;
133
146
  case 'close':
134
147
  clearSelection(inst, { source: 'keyboard' });
135
- announce(inst, inst.el('spec-drawer') ? 'Panel closed' : 'Selection cleared'); // a map with no node panel beside it (a component) has none to close
148
+ announce(inst, inst.ask('panel:present') ? 'Panel closed' : 'Selection cleared'); // a map with no node panel beside it (a component) has none to close
136
149
  break;
137
150
  case 'move':
138
151
  moveSelected(inst, action.dx, action.dy);
@@ -83,8 +83,8 @@ export function visibleMapRect(inst) {
83
83
  const c = canvas.getBoundingClientRect();
84
84
  const bar = inst.el('proposal-bar');
85
85
  if (shown(bar)) covers.top = Math.max(0, bar.getBoundingClientRect().bottom - c.top) + 8;
86
- const drawer = inst.el('spec-drawer');
87
- if (shown(drawer) && drawer.classList.contains('drawer-open')) covers.right = drawer.offsetWidth; // its width, not its box: it slides in
86
+ const panel = inst.ask('panel:covers'); // the node panel, when it slides over the map: its width, not its box (it slides in)
87
+ if (panel && panel.right) covers.right = panel.right;
88
88
  const forge = inst.el('forge-panel');
89
89
  if (shown(forge) && forge.classList.contains('forge-open')) covers.left = forge.offsetWidth;
90
90
  // the review column (review-column.js) is docked on the left under the bar: its right edge is what it covers, past the Work panel's when both are open
@@ -22,9 +22,34 @@ export function withParts(html) {
22
22
  return String(html).replace(/<[a-zA-Z][^<>]*>/g, (tag) => (/\spart=/.test(tag) ? tag : tag.replace(HOOK, (_all, hook) => ` data-corn=\"${hook}\" part=\"${hook}\"`)));
23
23
  }
24
24
 
25
- /** Gives every element under `el` that has a hook and no part the part of the same name */
25
+ /**
26
+ * A style the markup wants (a swatch's colour) is written as `data-style="…"` and set here through the CSS object model: an inline `style="…"` that
27
+ * came in as a string is blocked by a host's `style-src 'self'` (spec 0011 D10), and the CSS object model is not.
28
+ */
29
+ export function applyStyles(el) {
30
+ const own = el.hasAttribute && el.hasAttribute('data-style') ? [el] : [];
31
+ for (const x of [...own, ...el.querySelectorAll('[data-style]')]) {
32
+ const text = x.getAttribute('data-style') || '';
33
+ x.removeAttribute('data-style');
34
+ // Only the properties a swatch is drawn with, each set on its own: a value can never add a declaration, and never fetches anything
35
+ for (const decl of text.split(';')) {
36
+ const at = decl.indexOf(':');
37
+ if (at < 0) continue;
38
+ const prop = decl.slice(0, at).trim().toLowerCase();
39
+ const value = decl.slice(at + 1).trim();
40
+ if (STYLE_PROPS.has(prop) && value && !UNSAFE_VALUE.test(value)) x.style.setProperty(prop, value);
41
+ }
42
+ }
43
+ }
44
+ /** What `data-style` may set (the Layers dots and the flow swatches) */
45
+ export const STYLE_PROPS = new Set(['background', 'background-color', 'box-shadow', '--hx-dot-ring']);
46
+ /** A value that could fetch or escape its declaration: refused */
47
+ const UNSAFE_VALUE = /url\(|image|src\(|\\|[<>{}"'@!]/i;
48
+
49
+ /** Gives every element under `el` that has a hook and no part the part of the same name; applies the styles the markup asks for (`applyStyles`) */
26
50
  export function addParts(el) {
27
51
  for (const x of el.querySelectorAll('[data-corn]:not([part])')) x.setAttribute('part', x.getAttribute('data-corn'));
52
+ applyStyles(el);
28
53
  }
29
54
 
30
55
  /**
@@ -67,7 +92,7 @@ export function scopeOf(inst) {
67
92
  for (const n of m.addedNodes) {
68
93
  if (n.nodeType !== 1) continue;
69
94
  if (n.hasAttribute('data-corn') && !n.hasAttribute('part')) n.setAttribute('part', n.getAttribute('data-corn'));
70
- addParts(n);
95
+ addParts(n); // (and the styles it asks for)
71
96
  }
72
97
  }
73
98
  });
@@ -300,21 +300,24 @@ export function createMap(inst, opts = {}) {
300
300
 
301
301
  // Any pointer, wheel, touch or key event counts as the visitor being there: after 30 s without one the
302
302
  // packets stop, and the next one starts them again. Passive listeners on the root (captured, so no handler hides one), so no handler is slowed.
303
+ // They are this map's: an instance that outlives it (a scope's, whose map is removed and put back) is not left holding them (destroy)
304
+ const listening = [];
303
305
  if (inst.root) {
304
306
  const onInput = () => scheduler.noteInput();
305
- for (const type of ACTIVITY) inst.listen(inst.root, type, onInput, { passive: true, capture: true });
307
+ for (const type of ACTIVITY) listening.push(inst.listen(inst.root, type, onInput, { passive: true, capture: true }));
306
308
  }
307
- inst.onShown(() => scheduler.shown());
309
+ listening.push(inst.onShown(() => scheduler.shown()));
308
310
  // A page that loaded hidden (a background tab, a pane not yet shown) has had no frames, and a ResizeObserver reports nothing while it is hidden:
309
311
  // the box is read again when it is shown (resize() fits the map again if nobody has moved the camera)
310
- inst.onShown(() => {
312
+ listening.push(inst.onShown(() => {
311
313
  const box = state.canvas && state.canvas.parentElement;
312
314
  if (!ended && box && box.clientWidth && box.clientHeight && (box.clientWidth !== state.width || box.clientHeight !== state.height)) resize();
313
- });
315
+ }));
314
316
 
315
317
  /** Ends the map: no frame is waiting, the renderer's GPU context and the label layer are released, nothing is called again */
316
318
  function destroy() {
317
319
  ended = true;
320
+ for (const off of listening.splice(0)) off();
318
321
  if (inst.map === map) inst.map = null; // an instance that outlives its map (a scope's) can be given another
319
322
  scheduler.cancel();
320
323
  // the end of this map: the renderer gives its WebGL context back too (`release`); a swap (setRenderer) only destroys, so the next renderer on the canvas has a live one
@@ -0,0 +1,71 @@
1
+ /**
2
+ * @module explorer/engine/roots
3
+ *
4
+ * More than one root for one instance (spec 0011 D2, D4, D5). Inside a `<corn-scope>` each leaf piece (the map, the node panel, the Layers menu, the
5
+ * search) has a shadow root of its own, and they share one instance. The instance has one primary root (the map's, once it attached it: `inst.el` looks
6
+ * there); every other piece's root joins it here, so that what is the instance's by root is the instance's in all of them:
7
+ *
8
+ * joinRoot(inst, node) the root `node` is in belongs to the instance, until the returned function is called or the instance ends:
9
+ * its focus (`inst.active()`) and its keys (`listenRoots`) are the instance's. A root the instance covers already
10
+ * (cornfield's document, the review's one root) is not added again
11
+ * listenRoots(inst, type, fn, opts) a listener on every root of the instance, those that join later too; an event that reaches two of them (a root
12
+ * inside another) is handled once. Removed by `destroy()`
13
+ * onPageClick(inst, fn, { capture }) a click anywhere in the page, outside every root too, heard first (capture, the default) or last: what closes a
14
+ * menu a click beside it in the host's page lands on. The event's `composedPath()` says what was in the way, but
15
+ * not inside a host's closed shadow root: a piece asks its own element too (pieces/layers.js)
16
+ *
17
+ * A piece owns its own elements and never looks for a neighbour's by id: it reaches it by an event or an `ask` on the instance (instance.js lists them).
18
+ * This module is the sister of instance.js: it is where the instance meets the page's own roots, so it is exempt from the same tripwire rules.
19
+ */
20
+
21
+ /** @param {ReturnType<typeof import('../instance.js').createInstance>} inst */
22
+ const rootsOf = (inst) => [inst.root, ...inst.extraRoots].filter(Boolean);
23
+
24
+ /**
25
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst
26
+ * @param {Node} node
27
+ * @returns {() => void} how to leave
28
+ */
29
+ export function joinRoot(inst, node) {
30
+ if (!node || inst.ended) return () => {};
31
+ const tree = typeof node.getRootNode === 'function' ? node.getRootNode() : node;
32
+ if (!tree || rootsOf(inst).some((r) => r === tree || r === node)) return () => {};
33
+ inst.extraRoots.add(tree);
34
+ inst.emit('root:changed');
35
+ const off = () => { if (inst.extraRoots.delete(tree)) inst.emit('root:changed'); inst.release(off); };
36
+ inst.own(off);
37
+ return off;
38
+ }
39
+
40
+ /**
41
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst
42
+ * @param {string} type
43
+ * @param {(e: Event) => void} fn
44
+ * @param {boolean | AddEventListenerOptions} [opts]
45
+ * @returns {() => void}
46
+ */
47
+ export function listenRoots(inst, type, fn, opts) {
48
+ const seen = new WeakSet();
49
+ const handler = (e) => { if (seen.has(e)) return; seen.add(e); fn(e); };
50
+ const offs = new Map();
51
+ const sync = () => {
52
+ const now = new Set(rootsOf(inst));
53
+ for (const [r, off] of [...offs]) if (!now.has(r)) { off(); offs.delete(r); }
54
+ for (const r of now) if (!offs.has(r)) offs.set(r, inst.listen(r, type, handler, opts));
55
+ };
56
+ sync();
57
+ const stop = inst.on('root:changed', sync);
58
+ const off = () => { stop(); for (const o of offs.values()) o(); offs.clear(); inst.release(off); };
59
+ inst.own(off);
60
+ return off;
61
+ }
62
+
63
+ /**
64
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst
65
+ * @param {(e: MouseEvent) => void} fn
66
+ * @param {{ capture?: boolean }} [opts] heard first (the default), or last, once the click has reached everything in its way
67
+ * @returns {() => void}
68
+ */
69
+ export function onPageClick(inst, fn, { capture = true } = {}) {
70
+ return inst.doc ? inst.listen(inst.doc, 'click', (e) => fn(e), capture) : () => {};
71
+ }
@@ -9,9 +9,6 @@
9
9
 
10
10
  import { t } from './strings.js';
11
11
 
12
- /** The two fields' status lines: the desktop box and the phone's bar */
13
- const IDS = ['search-status', 'mobile-search-status'];
14
-
15
12
  /** How long the typing must pause before what a search found is said: a live region that changed on every key would be read out on every key */
16
13
  export const NO_MATCH_DELAY_MS = 400;
17
14
 
@@ -24,12 +21,9 @@ const pendingOf = (inst) => inst.slot('search-status', () => {
24
21
  return m;
25
22
  });
26
23
 
27
- /** Writes `text` into the region(s) at once; '' clears them */
24
+ /** Says `text` in the region(s) at once, '' clears them: the search piece owns them and hears `search:status` (they may be in a root of their own) */
28
25
  function write(inst, text) {
29
- for (const id of IDS) {
30
- const el = inst.el(id);
31
- if (el) el.textContent = text;
32
- }
26
+ inst.emit('search:status', text);
33
27
  }
34
28
 
35
29
  /** Shows `text` by the search field(s) at once, ending any wait for what the typing found; '' clears it */
package/explorer/flows.js CHANGED
@@ -16,6 +16,7 @@
16
16
  import { pageInstance } from './state.js';
17
17
  import { FLOW_STYLES } from './flow-style.js';
18
18
  import * as F from './engine/flow-ui.js';
19
+ import { renderFlowLegend as drawFlowLegend } from './engine/flow-legend.js';
19
20
 
20
21
  export { FLOW_STYLES, flowStyleOf } from './flow-style.js';
21
22
 
@@ -30,5 +31,5 @@ export { buildDataFlow } from './flow-build.js';
30
31
  // ---------------------------------------------------------------------------
31
32
  // Legend and the panel's "Data flows" block (engine/flow-ui.js, on an instance)
32
33
  // ---------------------------------------------------------------------------
33
- export const renderFlowLegend = () => F.renderFlowLegend(pageInstance());
34
+ export const renderFlowLegend = () => drawFlowLegend(pageInstance(), pageInstance().el('flow-legend'));
34
35
  export const flowSummary = (node) => F.flowSummary(pageInstance(), node);