@popcorn245/cornfield 0.51.8 → 0.52.1
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/cli/cornfield.js +7 -0
- package/core/config.js +2 -1
- package/core/map-tokens.js +2 -4
- package/core/repo.js +59 -4
- package/core/strings.js +5 -0
- package/core/text.js +18 -0
- package/core/validate.js +17 -10
- package/explorer/engine/flow-legend.js +28 -0
- package/explorer/engine/flow-ui.js +3 -22
- package/explorer/engine/keyboard.js +28 -15
- package/explorer/engine/map-rect.js +2 -2
- package/explorer/engine/map-style.js +12 -6
- package/explorer/engine/piece.js +27 -2
- package/explorer/engine/render.js +7 -4
- package/explorer/engine/roots.js +71 -0
- package/explorer/engine/search-status.js +2 -8
- package/explorer/flows.js +2 -1
- package/explorer/glyphs.js +14 -6
- package/explorer/instance.js +39 -10
- package/explorer/pieces/around.js +114 -0
- package/explorer/pieces/layers.js +31 -17
- package/explorer/pieces/map.js +14 -1
- package/explorer/pieces/node-panel.js +33 -15
- package/explorer/pieces/search.js +43 -12
- package/explorer/renderer-canvas2d.js +46 -12
- package/explorer/renderer-webgl.js +3 -1
- package/explorer/scene.js +1 -1
- package/explorer/search-match.js +53 -0
- package/explorer/search-model.js +6 -48
- package/explorer/shaders.js +17 -6
- package/package.json +1 -1
- package/plugins/cloud/index.js +5 -3
- package/plugins/compose/index.js +12 -6
- package/plugins/docs/site.js +2 -2
- package/plugins/openapi/index.js +10 -5
- package/plugins/starter/index.js +2 -2
- package/plugins/world/index.js +3 -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(
|
|
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
|
}
|
package/core/map-tokens.js
CHANGED
|
@@ -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
|
|
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
|
|
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}: ${
|
|
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 = { '&': '&', '<': '<', '>': '>', '"': '"', "'": '&
|
|
|
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
|
-
|
|
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
|
|
190
|
-
const
|
|
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(
|
|
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(
|
|
204
|
-
if (!ok) problems.push(`${where}: mockups[${m.index}].path: "${m.path}" is not a file in ${
|
|
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
|
|
250
|
-
if (
|
|
251
|
-
|
|
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
|
|
5
|
-
*
|
|
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
|
-
* -
|
|
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
|
-
/**
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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
|
|
49
|
-
const visibleWidth = width >= 768 &&
|
|
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.
|
|
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.
|
|
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
|
|
87
|
-
if (
|
|
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
|
|
@@ -65,6 +65,8 @@ export const GREY_ALPHA_TOKEN = '--corn-map-grey-alpha';
|
|
|
65
65
|
export const MIN_GREY_ALPHA = 0.1;
|
|
66
66
|
/** The ink of a node's glyph and of a finer kind's letters (spec 0008 D8); `auto` is the white or the dark that reads on the node's fill (glyphs.js) */
|
|
67
67
|
export const GLYPH_TOKEN = '--corn-map-glyph';
|
|
68
|
+
/** The page's ground under the map (tokens.css; a theme sets its own): what a translucent node's fill is seen over, so what its glyph's ink is chosen against (glyphs.js) */
|
|
69
|
+
export const GROUND_TOKEN = '--corn-ground';
|
|
68
70
|
/** The largest label minimum a theme may ask for: bigger text would leave no room for another label */
|
|
69
71
|
export const MAX_LABEL_MIN = 24;
|
|
70
72
|
/** The width an ordinary line has with no theme (scene.js `flowEdge`): the `--corn-map-edge-width` scales every line by its ratio to this */
|
|
@@ -179,8 +181,9 @@ function greyAlphaOf(value) {
|
|
|
179
181
|
* The tokens as the page computes them.
|
|
180
182
|
* @param {(name: string) => string} read the value of a custom property
|
|
181
183
|
* @param {string[]} [extra] more colour tokens to read: those of the finer kinds and project layers on the map (`setMapSubjects`)
|
|
182
|
-
* @returns {{values: Record<string, string>, strokeWidth: number, font: string | null, edgeWidth: number | null, glow: number | null, labelMin: number | null, greyAlpha: number | null}}
|
|
183
|
-
* `values` holds only the tokens that are a colour (not `auto`); `font`, `edgeWidth`, `glow`, `labelMin` and `greyAlpha` are null at `auto` or when the value is not one
|
|
184
|
+
* @returns {{values: Record<string, string>, strokeWidth: number, font: string | null, edgeWidth: number | null, glow: number | null, labelMin: number | null, greyAlpha: number | null, ground: string | null}}
|
|
185
|
+
* `values` holds only the tokens that are a colour (not `auto`); `font`, `edgeWidth`, `glow`, `labelMin` and `greyAlpha` are null at `auto` or when the value is not one;
|
|
186
|
+
* `ground` is the page's ground (`--corn-ground`) as a colour, or null when it is not one
|
|
184
187
|
*/
|
|
185
188
|
export function readMapTokens(read, extra = []) {
|
|
186
189
|
const values = {};
|
|
@@ -197,6 +200,7 @@ export function readMapTokens(read, extra = []) {
|
|
|
197
200
|
glow: factorOf(read(GLOW_TOKEN)),
|
|
198
201
|
labelMin: labelMinOf(read(LABEL_MIN_TOKEN)),
|
|
199
202
|
greyAlpha: greyAlphaOf(read(GREY_ALPHA_TOKEN)),
|
|
203
|
+
ground: cssColor(read(GROUND_TOKEN)),
|
|
200
204
|
};
|
|
201
205
|
}
|
|
202
206
|
|
|
@@ -261,14 +265,16 @@ export function createIconStore(urls, { load = loadImage, onChange = () => {}, w
|
|
|
261
265
|
* @property {number | null} glow the glow factor (`--corn-map-glow`), null at `auto`
|
|
262
266
|
* @property {number | null} labelMin the smallest label size in px (`--corn-map-label-min`), null at `auto` or under 9px
|
|
263
267
|
* @property {number | null} greyAlpha how much of a greyed node is left (`--corn-map-grey-alpha`), null at `auto` or when it is not a number from 0.1 to 1
|
|
268
|
+
* @property {string | null} ground the page's ground (`--corn-ground`), null when it is not a colour: a translucent node is seen over it (glyphs.js). It sets nothing
|
|
269
|
+
* in the picture, so it does not make a style less plain
|
|
264
270
|
* @property {ReturnType<typeof createIconStore> | null} icons
|
|
265
271
|
* @property {boolean} pixelated sample icons without smoothing
|
|
266
272
|
* @property {boolean} plain nothing to apply: no colour set, no icon loaded (the scene is drawn as it is)
|
|
267
273
|
*/
|
|
268
274
|
|
|
269
|
-
const NO_TOKENS = { values: {}, strokeWidth: DEFAULT_STROKE_WIDTH, font: null, edgeWidth: null, glow: null, labelMin: null, greyAlpha: null };
|
|
275
|
+
const NO_TOKENS = { values: {}, strokeWidth: DEFAULT_STROKE_WIDTH, font: null, edgeWidth: null, glow: null, labelMin: null, greyAlpha: null, ground: null };
|
|
270
276
|
/** The style with nothing set: what a renderer or a label layer made without an instance draws with (the scene as it is) */
|
|
271
|
-
export const PLAIN_STYLE = Object.freeze({ version: 0, values: Object.freeze({}), strokeWidth: DEFAULT_STROKE_WIDTH, font: null, edgeWidth: null, glow: null, labelMin: null, greyAlpha: null, icons: null, pixelated: false, plain: true });
|
|
277
|
+
export const PLAIN_STYLE = Object.freeze({ version: 0, values: Object.freeze({}), strokeWidth: DEFAULT_STROKE_WIDTH, font: null, edgeWidth: null, glow: null, labelMin: null, greyAlpha: null, ground: null, icons: null, pixelated: false, plain: true });
|
|
272
278
|
const MAX_SUBJECT_TOKENS = 500;
|
|
273
279
|
|
|
274
280
|
/**
|
|
@@ -287,7 +293,7 @@ export function createMapStyle(inst) {
|
|
|
287
293
|
|
|
288
294
|
const compose = () => {
|
|
289
295
|
const plain = !Object.keys(tokens.values).length && !(icons && icons.anyReady()) && tokens.font === null && tokens.edgeWidth === null && tokens.glow === null && tokens.labelMin === null && tokens.greyAlpha === null;
|
|
290
|
-
return Object.freeze({ version, values: tokens.values, strokeWidth: tokens.strokeWidth, font: tokens.font, edgeWidth: tokens.edgeWidth, glow: tokens.glow, labelMin: tokens.labelMin, greyAlpha: tokens.greyAlpha, icons, pixelated, plain });
|
|
296
|
+
return Object.freeze({ version, values: tokens.values, strokeWidth: tokens.strokeWidth, font: tokens.font, edgeWidth: tokens.edgeWidth, glow: tokens.glow, labelMin: tokens.labelMin, greyAlpha: tokens.greyAlpha, ground: tokens.ground, icons, pixelated, plain });
|
|
291
297
|
};
|
|
292
298
|
let current = compose();
|
|
293
299
|
|
|
@@ -330,7 +336,7 @@ export function createMapStyle(inst) {
|
|
|
330
336
|
refresh(read = inst.tokenReader()) {
|
|
331
337
|
if (!read) return false;
|
|
332
338
|
const next = readMapTokens(read, subjectTokens);
|
|
333
|
-
const same = next.strokeWidth === tokens.strokeWidth && next.font === tokens.font && next.edgeWidth === tokens.edgeWidth && next.glow === tokens.glow && next.labelMin === tokens.labelMin
|
|
339
|
+
const same = next.strokeWidth === tokens.strokeWidth && next.font === tokens.font && next.edgeWidth === tokens.edgeWidth && next.glow === tokens.glow && next.labelMin === tokens.labelMin && next.ground === tokens.ground
|
|
334
340
|
&& Object.keys(next.values).length === Object.keys(tokens.values).length
|
|
335
341
|
&& Object.entries(next.values).every(([k, v]) => tokens.values[k] === v);
|
|
336
342
|
if (same) return false;
|
package/explorer/engine/piece.js
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
+
}
|