cornfield 0.46.0 → 0.46.2

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 (62) hide show
  1. package/explorer/capped.js +3 -2
  2. package/explorer/engine/feedback.js +49 -0
  3. package/explorer/engine/flow-ui.js +39 -0
  4. package/explorer/engine/fly.js +54 -0
  5. package/explorer/engine/hint.js +97 -0
  6. package/explorer/engine/keyboard.js +156 -0
  7. package/explorer/engine/layers.js +280 -0
  8. package/explorer/engine/layout.js +378 -0
  9. package/explorer/engine/map-style.js +547 -0
  10. package/explorer/engine/piece.js +142 -0
  11. package/explorer/engine/render.js +331 -0
  12. package/explorer/engine/search-status.js +59 -0
  13. package/explorer/engine/selection.js +42 -0
  14. package/explorer/engine/sheets.js +417 -0
  15. package/explorer/engine/strings.js +63 -0
  16. package/explorer/feedback.js +11 -45
  17. package/explorer/flow-style.js +28 -0
  18. package/explorer/flows.js +10 -51
  19. package/explorer/fly.js +11 -43
  20. package/explorer/hint.js +15 -88
  21. package/explorer/index.html +38 -75
  22. package/explorer/input.js +190 -177
  23. package/explorer/instance-state.js +172 -0
  24. package/explorer/instance.js +267 -0
  25. package/explorer/keyboard.js +14 -206
  26. package/explorer/labels.js +3 -3
  27. package/explorer/layers.js +34 -445
  28. package/explorer/layout.js +14 -372
  29. package/explorer/main.js +4 -226
  30. package/explorer/map-style.js +27 -525
  31. package/explorer/mockups-model.js +3 -3
  32. package/explorer/page-pieces.js +61 -0
  33. package/explorer/page.js +232 -0
  34. package/explorer/panels.js +29 -409
  35. package/explorer/pieces/layers.js +325 -0
  36. package/explorer/pieces/node-panel.js +536 -0
  37. package/explorer/pieces/search.js +454 -0
  38. package/explorer/proposal-model.js +1 -1
  39. package/explorer/proposal.js +1 -0
  40. package/explorer/render.js +37 -267
  41. package/explorer/renderer-canvas2d.js +4 -4
  42. package/explorer/renderer-webgl.js +21 -8
  43. package/explorer/renderer.js +11 -9
  44. package/explorer/scene.js +3 -2
  45. package/explorer/search-status.js +8 -47
  46. package/explorer/search.js +26 -324
  47. package/explorer/selection-view.js +17 -19
  48. package/explorer/sheets.js +31 -379
  49. package/explorer/state.js +38 -173
  50. package/explorer/strings.js +17 -60
  51. package/explorer/view.js +4 -5
  52. package/package.json +1 -1
  53. package/server/agent-api.js +13 -6
  54. package/server/agent-runs.js +2 -1
  55. package/server/auth.js +1 -1
  56. package/server/forge-actions.js +34 -24
  57. package/server/forge-routes.js +3 -3
  58. package/server/lander.js +3 -2
  59. package/server/proposals.js +11 -3
  60. package/server/review-api.js +13 -8
  61. package/server/server.js +5 -4
  62. package/server/throttle.js +27 -0
@@ -1,529 +1,31 @@
1
1
  /**
2
2
  * @module explorer/map-style
3
3
  *
4
- * The map's styling from the theme (docs/theming.md, "The map"). The map canvas reads its colours from `--corn-map-*` custom
5
- * properties (tokens.css) on load and again whenever the theme changes, then draws again:
6
- *
7
- * --corn-map-node-<kind> a node kind's fill (kind: a node type, `app`, `page`, `table` ...)
8
- * --corn-map-group-<group> the same by group, the node's layer in the Layers menu (`cloud`, `web`, `house`, `app` ...)
9
- * --corn-map-stroke, --corn-map-stroke-width every node's outline: its colour (none at `auto`) and its width, in world px
10
- * --corn-map-label, --corn-map-label-halo a node label's colour, and the outline under every label that keeps it readable over the lines
11
- * --corn-map-edge-<kind> an edge kind's colour (`ownership`, `usage`, `flow`, `reads`, `writes`, `calls` ...)
12
- * --corn-map-added|changed|removed|edit the diff: a proposal's marks on nodes and edges
13
- * --corn-map-selected|match the halo of the selected node, and of a search hit
14
- * --corn-map-lit the lines of the focus: the links the selection (or a walk's step) lights
15
- * --corn-map-collision the collision mark of two runs on one node (a DOM mark: explorer.css reads it)
16
- * --corn-map-font the font list of every label on the map (a list of families, `auto` for the map's own)
17
- * --corn-map-edge-width the width of an ordinary line, in map px (`auto` keeps each line's own; the focus's and the marks' keep their proportion)
18
- * --corn-map-label-min the smallest a label is drawn on screen, in px (11 by default; below 9px it is ignored; a hub's title is 2 more)
19
- * --corn-map-grey what a review greys (the nodes and lines a proposal does not involve) is drawn in: a colour, or `auto` for each one's own tone with its hue taken away
20
- * --corn-map-grey-alpha how much of a greyed node is left: a number from 0.1 to 1 (`auto` is 0.45); its lines are faded in the same proportion
21
- * --corn-map-glow the soft glow round nodes, lines and packets: a factor (`0` none, `1` as drawn, `auto` as drawn)
22
- *
23
- * `auto` (the default of every one of them but the width and the collision) means "keep what the map draws without a theme": the
24
- * node's own colour from the topology, deepened for the light ground by theme-model.js, and every other colour as scene.js has
25
- * it. So with no theme the map is exactly what it was. A colour overrides it as written, in both themes (a theme sets its own
26
- * for the light ground under :root[data-theme="light"]). A kind's token wins over its group's.
27
- *
28
- * How it reaches the pixels. scene.js stays pure: it describes the picture with the colours it always had. A renderer (and the label
29
- * layer) asks `styledScene(scene, style)` for the same picture in the theme's colours, and `looksWith(looks, style)` for the halos and
30
- * the mark rings; the style is `getMapStyle()`, which `refreshMapStyle()` reads from the page's computed style. With nothing set,
31
- * `styledScene` hands the scene back untouched. A node or an edge a painter gave a colour (an outage, a check's verdict, a pull
32
- * request: `scene.painted`) keeps it: those colours mean something.
33
- *
34
- * Icons (`theme.icons`) are loaded here, one image per node kind (`createIconStore`); a kind whose file is missing or will not load
35
- * simply has no icon. `pixelated` (`theme.pixelated`) is the renderers' cue to sample without smoothing.
36
- */
37
-
38
- import { NODE_THEMES } from '../core/schema.js';
39
- import { parseColor } from './theme-model.js';
40
- import { cssColor, rgbaText } from './css-color.js';
41
- export { cssColor };
42
- import { GREY_ALPHA, LABEL_MIN_FLOOR, looksFor } from './scene.js';
43
- import { iconKeyShape, iconKeysFor, mapFillNames, mapGroupToken, mapKindToken } from '../core/layers.js';
44
-
45
- /** The node kinds (topology types) and the groups (layers a node can belong to) the tokens exist for */
46
- export const MAP_KINDS = Object.freeze(Object.keys(NODE_THEMES));
47
- export const MAP_GROUPS = Object.freeze(['app', 'pkg', 'page', 'atom', 'molecule', 'token', 'tool', 'table', 'rom', 'service', 'cloud', 'web', 'stack', 'machine', 'container', 'device', 'house', 'persona']);
48
- /** The kinds of edge scene.js draws */
49
- export const MAP_EDGE_KINDS = Object.freeze(['ownership', 'usage', 'flow', 'reads', 'writes', 'calls', 'triggers', 'delivers', 'runs-on', 'uses', 'extends']);
50
- /** The diff marks, and the other states the map colours */
51
- export const MAP_MARKS = Object.freeze(['added', 'changed', 'removed', 'edit']);
52
- export const MAP_STATES = Object.freeze(['selected', 'match', 'lit']);
53
- export const STROKE_TOKEN = '--corn-map-stroke';
54
- export const STROKE_WIDTH_TOKEN = '--corn-map-stroke-width';
55
- export const LABEL_TOKEN = '--corn-map-label';
56
- export const LABEL_HALO_TOKEN = '--corn-map-label-halo';
57
- export const COLLISION_TOKEN = '--corn-map-collision';
58
- export const FONT_TOKEN = '--corn-map-font';
59
- export const EDGE_WIDTH_TOKEN = '--corn-map-edge-width';
60
- export const GLOW_TOKEN = '--corn-map-glow';
61
- export const LABEL_MIN_TOKEN = '--corn-map-label-min';
62
- export const GREY_TOKEN = '--corn-map-grey';
63
- export const GREY_ALPHA_TOKEN = '--corn-map-grey-alpha';
64
- /** The least a greyed node may be left at: under it the map would vanish (a value below is read as `auto`) */
65
- export const MIN_GREY_ALPHA = 0.1;
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
- export const GLYPH_TOKEN = '--corn-map-glyph';
68
- /** The largest label minimum a theme may ask for: bigger text would leave no room for another label */
69
- export const MAX_LABEL_MIN = 24;
70
- /** 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 */
71
- export const BASE_EDGE_WIDTH = 1.6;
72
- /** The most a font list may hold: the families, and the characters */
73
- export const MAX_FONT_FAMILIES = 8;
74
- export const MAX_FONT_CHARS = 200;
75
- /** The widest a line may be set, and the largest glow factor: a typo cannot draw a map of paint */
76
- export const MAX_EDGE_WIDTH = 12;
77
- export const MAX_GLOW = 4;
78
- /** The width of an outline when the token is not a length (px, world units) */
79
- export const DEFAULT_STROKE_WIDTH = 1.5;
80
- /** An icon is drawn this many radii across (a square, so it fits inside the circle) */
81
- export const ICON_RATIO = 1.2;
82
- /** Where the server serves the images beside a theme (core/theme.js THEME_ASSET_PREFIX); an icon is fetched from nowhere else */
83
- export const ICON_URL_PREFIX = '/cornfield/theme/assets/';
84
-
85
- export const nodeToken = (kind) => `--corn-map-node-${kind}`;
86
- export const groupToken = (group) => `--corn-map-group-${group}`;
87
- /** The fill token of a finer kind: `--corn-map-kind-service-timer`, or null for a kind that cannot be a part of a name (core/layers.js) */
88
- export const kindToken = (type, kind) => mapKindToken(type, kind);
89
- export const edgeToken = (kind) => `--corn-map-edge-${kind}`;
90
- export const stateToken = (name) => `--corn-map-${name}`;
91
-
92
- /** The colour tokens script reads: all of them but the width and the collision mark (which CSS reads) */
93
- export const MAP_COLOR_TOKENS = Object.freeze([
94
- ...MAP_KINDS.map(nodeToken),
95
- ...MAP_GROUPS.map(groupToken),
96
- STROKE_TOKEN,
97
- LABEL_TOKEN,
98
- LABEL_HALO_TOKEN,
99
- GLYPH_TOKEN,
100
- GREY_TOKEN,
101
- ...MAP_EDGE_KINDS.map(edgeToken),
102
- ...MAP_MARKS.map(stateToken),
103
- ...MAP_STATES.map(stateToken),
104
- ]);
105
- /** Every map token */
106
- export const mapTokenNames = () => [...MAP_COLOR_TOKENS, STROKE_WIDTH_TOKEN, COLLISION_TOKEN, FONT_TOKEN, EDGE_WIDTH_TOKEN, GLOW_TOKEN, LABEL_MIN_TOKEN, GREY_ALPHA_TOKEN];
107
-
108
- // ---------------------------------------------------------------------------
109
- // Reading a token
110
- // ---------------------------------------------------------------------------
111
-
112
- /** `token` as the colour of something that was `original`: the token's colour, with the original's own alpha kept (a faint line stays faint) */
113
- export function withAlphaOf(token, original) {
114
- const [r, g, b, a] = parseColor(token);
115
- const oa = parseColor(original)[3];
116
- if (oa >= 1) return token;
117
- return rgbaText(r, g, b, a * oa);
118
- }
119
-
120
- const GENERIC_FAMILY = /^(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-serif|ui-sans-serif|ui-monospace|ui-rounded|emoji|math|fangsong)$/i;
121
- const SYSTEM_FONT_KEYWORD = /^(?:-apple-system|BlinkMacSystemFont)$/;
122
-
123
- /**
124
- * A font list the canvas may be given, or null (`auto`, empty, or anything that is not a plain list of families). Each family is a name in
125
- * quotes, or bare words (`Nunito`, `ui-rounded`, `sans-serif`); nothing that can carry a URL or script (no parentheses, slashes, colons,
126
- * semicolons, braces, angle brackets, `@`, backslashes, `url`, `var`, `expression`) and no more than MAX_FONT_FAMILIES of them.
127
- * Returned with each name quoted, so a name with a space is one family.
128
- * @param {unknown} value
129
- * @returns {string | null}
130
- */
131
- export function cssFontList(value) {
132
- const s = typeof value === 'string' ? value.trim() : '';
133
- if (!s || s.length > MAX_FONT_CHARS || s.toLowerCase() === 'auto') return null;
134
- if (/[();:{}<>@\\/\u0000-\u001f\u007f]|\burl\b|\bvar\b|\bexpression\b|\bimport\b/i.test(s)) return null;
135
- const parts = s.split(',').map((p) => p.trim());
136
- if (parts.length > MAX_FONT_FAMILIES) return null;
137
- const out = [];
138
- for (const part of parts) {
139
- const quoted = /^"([A-Za-z0-9 ._+-]{1,60})"$|^'([A-Za-z0-9 ._+-]{1,60})'$/.exec(part);
140
- // A bare name may start with one hyphen (`-apple-system`, in cornfield's own --corn-font), never two (a custom property's name)
141
- const name = quoted ? (quoted[1] ?? quoted[2]).trim() : /^-?[A-Za-z][A-Za-z0-9 _-]{0,59}$/.test(part) ? part.replace(/\s+/g, ' ') : null;
142
- if (!name) return null;
143
- // Generic families and the two system-font keywords stay bare (quoted, they would name a font called that); every other name is quoted
144
- out.push(GENERIC_FAMILY.test(name) ? name.toLowerCase() : SYSTEM_FONT_KEYWORD.test(name) ? name : `"${name}"`);
145
- }
146
- return out.join(', ');
147
- }
148
-
149
- /** A length in px (`2px`, `2`) over 0 and at most max, or null for `auto` and anything else (a canvas ignores a line width of 0) */
150
- function pxOf(value, max) {
151
- const m = /^\s*(\d*\.?\d+)(?:px)?\s*$/i.exec(String(value ?? ''));
152
- const n = m ? parseFloat(m[1]) : NaN;
153
- return Number.isFinite(n) && n > 0 && n <= max ? n : null;
154
- }
155
-
156
- /** The label minimum: a length in px from LABEL_MIN_FLOOR to MAX_LABEL_MIN, or null for `auto` and anything else (under the floor is ignored, so a theme cannot make labels unreadable) */
157
- function labelMinOf(value) {
158
- const n = pxOf(value, MAX_LABEL_MIN);
159
- return n !== null && n >= LABEL_MIN_FLOOR ? n : null;
160
- }
161
-
162
- /** The glow factor: a number (`0` for none, `1` as drawn, up to MAX_GLOW; `0px` reads as 0), or null for `auto` and anything else */
163
- function factorOf(value) {
164
- const m = /^\s*(\d*\.?\d+)(px)?\s*$/i.exec(String(value ?? ''));
165
- if (!m) return null;
166
- const n = parseFloat(m[1]);
167
- if (m[2] && n !== 0) return null; // a length is not a factor, only zero is the same in both
168
- return Number.isFinite(n) && n >= 0 && n <= MAX_GLOW ? n : null;
169
- }
170
-
171
- /** The greyed node's opacity: a number from MIN_GREY_ALPHA to 1, or null for `auto` and anything else */
172
- function greyAlphaOf(value) {
173
- const m = /^\s*(\d*\.?\d+)\s*$/.exec(String(value ?? ''));
174
- const n = m ? parseFloat(m[1]) : NaN;
175
- return Number.isFinite(n) && n >= MIN_GREY_ALPHA && n <= 1 ? n : null;
176
- }
177
-
178
- /**
179
- * The tokens as the page computes them.
180
- * @param {(name: string) => string} read the value of a custom property
181
- * @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
- */
185
- export function readMapTokens(read, extra = []) {
186
- const values = {};
187
- for (const name of [...MAP_COLOR_TOKENS, ...extra]) {
188
- const c = cssColor(read(name));
189
- if (c) values[name] = c;
190
- }
191
- const w = parseFloat(String(read(STROKE_WIDTH_TOKEN) ?? ''));
192
- return {
193
- values,
194
- strokeWidth: Number.isFinite(w) && w >= 0 ? w : DEFAULT_STROKE_WIDTH,
195
- font: cssFontList(read(FONT_TOKEN)),
196
- edgeWidth: pxOf(read(EDGE_WIDTH_TOKEN), MAX_EDGE_WIDTH),
197
- glow: factorOf(read(GLOW_TOKEN)),
198
- labelMin: labelMinOf(read(LABEL_MIN_TOKEN)),
199
- greyAlpha: greyAlphaOf(read(GREY_ALPHA_TOKEN)),
200
- };
201
- }
202
-
4
+ * A bridge (spec 0011 D2, step 1): the map's styling now lives in engine/map-style.js, one style per instance. This file keeps the
5
+ * old names for the modules that are not yet on an instance (layers.js, theme.js, proposal.js, main.js's old callers), bound to the page's
6
+ * instance. A module that is converted reads `mapStyleOf(inst)` from the engine and stops importing this file.
7
+ */
8
+
9
+ import { pageInstance } from './state.js';
10
+ import { mapStyleOf, styledScene as styled, looksWith as looks } from './engine/map-style.js';
11
+
12
+ export * from './engine/map-style.js';
13
+
14
+ const style = () => mapStyleOf(pageInstance());
15
+
16
+ /** The page's map style */
17
+ export const getMapStyle = () => style().get();
18
+ export const onMapStyleChange = (fn) => style().onChange(fn);
19
+ export const setMapSubjects = (subjects) => style().setSubjects(subjects);
20
+ /** Reads the tokens again; `read` defaults to the page's computed style (`<html>`) */
21
+ export const refreshMapStyle = (read) => style().refresh(read);
22
+ export const setMapIcons = (theme, opts) => style().setIcons(theme, opts);
23
+ /** @param {Document} [doc] kept for the old signature: the page instance is over the document */
24
+ export const applyMapTheme = (doc, theme, opts) => style().applyTheme(theme, opts);
25
+ export const resetMapStyle = () => style().reset();
26
+ /** Keeps the page's style right as the theme changes; returns how to stop */
27
+ export const watchMapStyle = () => style().watch();
203
28
  /** A reader of the page's computed custom properties, or null where there is no page */
204
- export function pageReader(doc = typeof document !== 'undefined' ? document : null) {
205
- const win = doc && doc.defaultView;
206
- if (!doc || !doc.documentElement || !win || !win.getComputedStyle) return null;
207
- const style = win.getComputedStyle(doc.documentElement);
208
- return (name) => style.getPropertyValue(name);
209
- }
210
-
211
- // ---------------------------------------------------------------------------
212
- // Icons
213
- // ---------------------------------------------------------------------------
214
-
215
- function loadImage(url) {
216
- return new Promise((resolve, reject) => {
217
- if (typeof Image === 'undefined') { reject(new Error('no Image')); return; }
218
- const img = new Image();
219
- img.onload = () => (img.naturalWidth > 0 && img.naturalHeight > 0 ? resolve(img) : reject(new Error(`${url} has no size`)));
220
- img.onerror = () => reject(new Error(`${url} did not load`));
221
- img.src = url;
222
- });
223
- }
224
-
225
- /**
226
- * One image per node kind, loaded once. `get(kind)` is the image when it has loaded, else null: a kind with no icon, one still loading, and
227
- * one whose file is missing or is not an image are the same to the map (no icon), and one failure never touches another.
228
- * @param {Record<string, string>} urls kind to served path (only paths under ICON_URL_PREFIX, for a kind that is a node kind)
229
- * @param {{load?: (url: string) => Promise<unknown>, onChange?: () => void, warn?: (message: string) => void}} [opts]
230
- */
231
- export function createIconStore(urls, { load = loadImage, onChange = () => {}, warn = (m) => console.warn(m) } = {}) {
232
- const entries = new Map();
233
- let ready = 0;
234
- for (const [kind, url] of Object.entries(urls || {})) {
235
- if (!iconKeyShape(kind) || typeof url !== 'string' || !url.startsWith(ICON_URL_PREFIX) || url.includes('..')) continue;
236
- const entry = { status: 'loading', image: null };
237
- entries.set(kind, entry);
238
- Promise.resolve().then(() => load(url)).then((image) => {
239
- entry.status = 'ready';
240
- entry.image = image;
241
- ready++;
242
- onChange();
243
- }, (err) => {
244
- entry.status = 'failed';
245
- warn(`Map icon for "${kind}" not drawn: ${err && err.message ? err.message : err}`);
246
- });
247
- }
248
- return {
249
- kinds: [...entries.keys()],
250
- get: (kind) => { const e = entries.get(kind); return e && e.status === 'ready' ? e.image : null; },
251
- status: (kind) => (entries.has(kind) ? entries.get(kind).status : 'none'),
252
- anyReady: () => ready > 0,
253
- };
254
- }
255
-
256
- // ---------------------------------------------------------------------------
257
- // The style in force
258
- // ---------------------------------------------------------------------------
259
-
260
- /**
261
- * @typedef {object} MapStyle
262
- * @property {number} version changes whenever anything below does: a renderer draws again when it differs from the one it drew
263
- * @property {Record<string, string>} values the tokens that are a colour, by name (those at `auto` are absent)
264
- * @property {number} strokeWidth px, world units
265
- * @property {string | null} font the label font list (`--corn-map-font`), null at `auto`
266
- * @property {number | null} edgeWidth an ordinary line's width in px (`--corn-map-edge-width`), null at `auto`
267
- * @property {number | null} glow the glow factor (`--corn-map-glow`), null at `auto`
268
- * @property {number | null} labelMin the smallest label size in px (`--corn-map-label-min`), null at `auto` or under 9px
269
- * @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
270
- * @property {ReturnType<typeof createIconStore> | null} icons
271
- * @property {boolean} pixelated sample icons without smoothing
272
- * @property {boolean} plain nothing to apply: no colour set, no icon loaded (the scene is drawn as it is)
273
- */
274
-
275
- const NO_TOKENS = { values: {}, strokeWidth: DEFAULT_STROKE_WIDTH, font: null, edgeWidth: null, glow: null, labelMin: null, greyAlpha: null };
276
- let tokens = NO_TOKENS;
277
- let icons = null;
278
- let pixelated = false;
279
- let version = 0;
280
- let current = compose();
281
- const listeners = new Set();
282
-
283
- function compose() {
284
- 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;
285
- 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 });
286
- }
287
-
288
- function changed() {
289
- version++;
290
- current = compose();
291
- listeners.forEach((fn) => fn(current));
292
- }
293
-
294
- /** The tokens of the finer kinds and project layers on the map, read besides the fixed list (their names come from the map and the config, through core/layers.js, which refuses a name that is not a plain one) */
295
- let subjectTokens = [];
296
- const MAX_SUBJECT_TOKENS = 500;
297
-
298
- /**
299
- * Tells the style which finer kinds (`[type, kind]`) and project layers (keys) are on the map, so the tokens that colour them
300
- * (`--corn-map-kind-<type>-<kind>`, `--corn-map-group-<key>`) are read. True when the set changed and a token differed.
301
- * @param {{kinds?: [string, string][], layers?: string[]}} [subjects]
302
- */
303
- export function setMapSubjects({ kinds = [], layers = [] } = {}) {
304
- const names = [...new Set([...kinds.map(([t, k]) => mapKindToken(t, k)), ...layers.map((l) => mapGroupToken(l))].filter(Boolean))].sort().slice(0, MAX_SUBJECT_TOKENS);
305
- if (names.length === subjectTokens.length && names.every((n, i) => n === subjectTokens[i])) return false;
306
- subjectTokens = names;
307
- return refreshMapStyle();
308
- }
309
-
310
- /** @returns {MapStyle} */
311
- export const getMapStyle = () => current;
312
-
313
- /** Calls `fn(style)` when the style changes (a token, an icon arriving); returns how to stop */
314
- export function onMapStyleChange(fn) {
315
- listeners.add(fn);
316
- return () => listeners.delete(fn);
317
- }
318
-
319
- /**
320
- * Reads the tokens again; true when something differed (and the listeners were told). Run on load and whenever the theme changes.
321
- * @param {(name: string) => string} [read] default: the page's computed style
322
- */
323
- export function refreshMapStyle(read = pageReader()) {
324
- if (!read) return false;
325
- const next = readMapTokens(read, subjectTokens);
326
- const same = next.strokeWidth === tokens.strokeWidth && next.font === tokens.font && next.edgeWidth === tokens.edgeWidth && next.glow === tokens.glow && next.labelMin === tokens.labelMin
327
- && Object.keys(next.values).length === Object.keys(tokens.values).length
328
- && Object.entries(next.values).every(([k, v]) => tokens.values[k] === v);
329
- if (same) return false;
330
- tokens = next;
331
- changed();
332
- // A web font the labels name is fetched when something asks for it, and a canvas does not wait for one: ask now, and draw again when it is in
333
- try { if (next.font && typeof document !== 'undefined' && document.fonts && document.fonts.load) document.fonts.load(`12px ${next.font}`).catch(() => {}); } catch { /* no font loading here */ }
334
- return true;
335
- }
336
-
337
- /**
338
- * Starts loading the config's icons (`theme.icons`, as the browser is told them: kind to served path) and sets the pixelated flag.
339
- * @param {{icons?: Record<string, string>, pixelated?: boolean} | null | undefined} theme
340
- * @param {Parameters<typeof createIconStore>[1]} [opts]
341
- */
342
- export function setMapIcons(theme, opts = {}) {
343
- const urls = theme && theme.icons && typeof theme.icons === 'object' ? theme.icons : {};
344
- pixelated = !!(theme && theme.pixelated === true);
345
- icons = Object.keys(urls).length ? createIconStore(urls, { ...opts, onChange: () => { changed(); if (opts.onChange) opts.onChange(); } }) : null;
346
- changed();
347
- return icons;
348
- }
349
-
350
- /**
351
- * The config's part of the map theme once the page has it: loads the icons, sets the pixelated flag, and marks <html data-pixelated> so a
352
- * stylesheet can sample any DOM image without smoothing too (`image-rendering: pixelated`, explorer.css).
353
- * @param {Document} doc
354
- * @param {{icons?: Record<string, string>, pixelated?: boolean} | null | undefined} theme `config.theme` of /cornfield/config.json
355
- */
356
- export function applyMapTheme(doc, theme, opts = {}) {
357
- if (theme && theme.pixelated === true) doc.documentElement.setAttribute('data-pixelated', ''); else doc.documentElement.removeAttribute('data-pixelated');
358
- return setMapIcons(theme, opts);
359
- }
360
-
361
- /** Back to nothing set (for tests) */
362
- export function resetMapStyle() {
363
- tokens = NO_TOKENS;
364
- icons = null;
365
- pixelated = false;
366
- subjectTokens = [];
367
- changed();
368
- }
369
-
370
- /**
371
- * Keeps the style right as the page changes its theme: `data-theme` or `data-theme-name` on <html> changing, a stylesheet finishing loading
372
- * (a named theme's, or the theme file's), and `prefers-color-scheme` flipping. Returns how to stop.
373
- * @param {Document} doc
374
- */
375
- export function watchMapStyle(doc) {
376
- const refresh = () => { refreshMapStyle(pageReader(doc)); };
377
- const stops = [];
378
- const win = doc.defaultView;
379
- if (win && win.MutationObserver) {
380
- const obs = new win.MutationObserver(refresh);
381
- obs.observe(doc.documentElement, { attributes: true, attributeFilter: ['data-theme', 'data-theme-name', 'class'] });
382
- stops.push(() => obs.disconnect());
383
- }
384
- const onLoad = (event) => { if (event.target && event.target.tagName === 'LINK') refresh(); }; // load does not bubble: captured
385
- doc.addEventListener('load', onLoad, true);
386
- stops.push(() => doc.removeEventListener('load', onLoad, true));
387
- const media = win && win.matchMedia ? win.matchMedia('(prefers-color-scheme: light)') : null;
388
- if (media) {
389
- if (media.addEventListener) { media.addEventListener('change', refresh); stops.push(() => media.removeEventListener('change', refresh)); }
390
- else if (media.addListener) { media.addListener(refresh); stops.push(() => media.removeListener(refresh)); }
391
- }
392
- const fonts = doc.fonts;
393
- if (fonts && fonts.addEventListener) {
394
- const again = () => { if (tokens.font) changed(); }; // the label font arrived: the canvas draws again with it
395
- fonts.addEventListener('loadingdone', again);
396
- stops.push(() => fonts.removeEventListener('loadingdone', again));
397
- }
398
- refresh();
399
- return () => stops.forEach((fn) => fn());
400
- }
401
-
402
- // ---------------------------------------------------------------------------
403
- // Applying it
404
- // ---------------------------------------------------------------------------
405
-
406
- const firstOf = (values, names) => { for (const n of names) if (values[n]) return values[n]; return null; };
407
-
408
- /** The tokens that can fill a node, most specific first (core/layers.js `mapFillNames`, the one place the order is written) */
409
- export const fillNames = mapFillNames;
410
-
411
- /** The theme's fill for a node of that kind, layer, type and group (`values` of a style), or null: the node then draws its own colour (`auto`) */
412
- export const fillOf = (values, node) => firstOf(values, fillNames(node));
413
-
414
- /** A line's shape in the theme: its width scaled to `--corn-map-edge-width`, its glow and its packet's by `--corn-map-glow` (nothing at `auto`) */
415
- function shapeEdge(e, style) {
416
- const scale = style.edgeWidth == null ? 1 : style.edgeWidth / BASE_EDGE_WIDTH;
417
- const glow = style.glow == null ? 1 : style.glow;
418
- if (scale === 1 && glow === 1) return e;
419
- const out = { ...e, width: e.width * scale, glow: e.glow * glow };
420
- if (e.packet) out.packet = { ...e.packet, glow: e.packet.glow * glow };
421
- return out;
422
- }
423
-
424
- function styleEdge(e, style, painted) {
425
- const { values } = style;
426
- if (e.mark && e.mark !== 'none') {
427
- const c = values[stateToken(e.mark)];
428
- return shapeEdge(c ? { ...e, color: c, glowColor: e.glowColor ? c : e.glowColor } : e, style);
429
- }
430
- if (painted.has(e.key)) return shapeEdge(e, style);
431
- const lit = !e.curve && e.glow > 0 && !e.arrow; // a straight link the focus lights
432
- const c = (lit && values[stateToken('lit')]) || values[edgeToken(e.kind)];
433
- if (!c) return shapeEdge(e, style);
434
- const out = { ...e, color: withAlphaOf(c, e.color) };
435
- if (e.glowColor) out.glowColor = withAlphaOf(c, e.glowColor);
436
- if (e.packet) out.packet = { ...e.packet, glowColor: withAlphaOf(c, e.packet.glowColor) };
437
- return shapeEdge(out, style);
438
- }
439
-
440
- /** A colour with its hue taken away: the grey of the same lightness, alpha kept. Both renderers read the same `rgb()` */
441
- export function greyOf(color) {
442
- const [r, g, b, a] = parseColor(color);
443
- const l = Math.round(0.2126 * r + 0.7152 * g + 0.0722 * b);
444
- return a >= 1 ? `rgb(${l}, ${l}, ${l})` : rgbaText(l, l, l, a);
445
- }
446
-
447
- function compute(scene, style) {
448
- const { values } = style;
449
- const greyToken = values[GREY_TOKEN];
450
- const fade = style.greyAlpha == null ? 1 : style.greyAlpha / GREY_ALPHA;
451
- const toGrey = (c) => (greyToken ? withAlphaOf(greyToken, c) : greyOf(c));
452
- const label = values[LABEL_TOKEN];
453
- const stroke = values[STROKE_TOKEN];
454
- const painted = scene.painted || { nodes: new Set(), edges: new Set() };
455
- const nodes = scene.nodes.map((n) => {
456
- // Which fill wins, most specific first (spec 0009 D6): the finer kind, the project layer, the type, the starting layer
457
- const fill = !painted.nodes.has(n.id) && fillOf(values, n);
458
- const icon = style.icons ? iconKeysFor(n.type, n.kind, n.layer).find((k) => style.icons.get(k)) || null : null; // the same order: kind, layer, type
459
- const glows = style.glow != null && style.glow !== 1 && n.glow > 0;
460
- const grey = !!n.greyed && !painted.nodes.has(n.id); // a review greys what the change does not involve; a colour a painter gave means something and stays
461
- if (!fill && !label && !stroke && !icon && !glows && !grey) return n;
462
- const out = { ...n };
463
- if (glows) out.glow = n.glow * style.glow;
464
- if (fill) out.color = fill;
465
- if (label) out.labelColor = withAlphaOf(label, n.labelColor);
466
- if (stroke && style.strokeWidth > 0) out.stroke = { color: grey ? toGrey(stroke) : stroke, width: style.strokeWidth };
467
- if (icon && !grey) out.icon = icon; // a picture has its own hues: a greyed node keeps its silhouette, glyph and letters
468
- if (grey) { out.color = toGrey(out.color); out.alpha = Math.min(1, n.alpha * fade); }
469
- return out;
470
- });
471
- const edges = scene.edges.map((e) => {
472
- const styled = styleEdge(e, style, painted.edges);
473
- if (!e.greyed || painted.edges.has(e.key)) return styled;
474
- return { ...styled, color: toGrey(styled.color), glowColor: null, alpha: Math.min(1, styled.alpha * fade) };
475
- });
476
- const out = { ...scene, nodes, edges };
477
- if (style.font) out.labelFont = style.font; // every label's font list (labels.js reads `scene.labelFont`)
478
- if (style.labelMin != null) out.labelMin = style.labelMin; // the smallest label on screen (labels.js reads `scene.labelMin`)
479
- const halo = values[LABEL_HALO_TOKEN];
480
- if (halo) { // the outline under the labels, at the widths it has (labels.js reads `scene.labelOutline` before the ground's own)
481
- const { node, edge } = looksFor(scene.theme).labelOutline;
482
- out.labelOutline = { node: { ...node, color: halo }, edge: { ...edge, color: halo } };
483
- }
484
- return out;
485
- }
486
-
487
- const sceneMemo = new WeakMap();
488
-
489
- /**
490
- * `scene` in the style's colours, with the outline and icon of each node that has one: the same object when there is nothing to apply, and
491
- * the same result for the same scene and style version, so a renderer's cache of what it packed holds.
492
- * @param {import('./scene.js').Scene} scene
493
- * @param {MapStyle} [style]
494
- */
495
- export function styledScene(scene, style = current) {
496
- if (!style || (style.plain && !scene.greying)) return scene; // a review's greying is applied even with no theme
497
- const hit = sceneMemo.get(scene);
498
- if (hit && hit.version === style.version) return hit.out;
499
- const out = compute(scene, style);
500
- sceneMemo.set(scene, { version: style.version, out });
501
- return out;
502
- }
503
-
504
- const looksMemo = new WeakMap();
505
-
506
- /**
507
- * The halos and mark rings (scene.js `looksFor`) in the style's colours: a selected node's, a search hit's, and each diff mark's.
508
- * @param {ReturnType<typeof import('./scene.js').looksFor>} looks
509
- * @param {MapStyle} [style]
510
- */
511
- export function looksWith(looks, style = current) {
512
- if (!style || style.plain) return looks;
513
- const hit = looksMemo.get(looks);
514
- if (hit && hit.version === style.version) return hit.out;
515
- const { values } = style;
516
- const halo = { ...looks.halo };
517
- for (const name of ['selected', 'match']) {
518
- const c = values[stateToken(name)];
519
- if (c) halo[name] = { ...halo[name], ring: c, fill: halo[name].fill ? withAlphaOf(c, halo[name].fill) : halo[name].fill };
520
- }
521
- const mark = { ...looks.mark };
522
- for (const name of MAP_MARKS) {
523
- const c = values[stateToken(name)];
524
- if (c) mark[name] = { ...mark[name], color: c };
525
- }
526
- const out = { ...looks, halo, mark };
527
- looksMemo.set(looks, { version: style.version, out });
528
- return out;
529
- }
29
+ export const pageReader = () => pageInstance().tokenReader();
30
+ export const styledScene = (scene, s = getMapStyle()) => styled(scene, s);
31
+ export const looksWith = (l, s = getMapStyle()) => looks(l, s);
@@ -11,7 +11,7 @@
11
11
  * mockupUrl where the server serves one (by its position in the proposal, never by path)
12
12
  */
13
13
 
14
- import { state, escHtml } from './state.js';
14
+ import { escapeHtml as escHtml } from '../core/text.js';
15
15
  import { mockupsOf } from '../core/proposal.js';
16
16
  import { cornStateAttr } from './corn-state.js';
17
17
 
@@ -67,10 +67,10 @@ export function mockupsSectionHtml(items) {
67
67
  }
68
68
 
69
69
  /**
70
- * The section for a node of the proposal that is open now, from `state.proposal` and the review states the server
70
+ * The section for a node of the proposal that is open now, from `state.proposal` (the instance's state, passed in) and the review states the server
71
71
  * last gave (`state.mockupStates`, by index). Empty when no proposal is open or the node has no mockups.
72
72
  * @param {string} nodeId
73
73
  */
74
- export function nodeMockupsHtml(nodeId) {
74
+ export function nodeMockupsHtml(state, nodeId) {
75
75
  return mockupsSectionHtml(mockupsFor(state.proposal, state.proposalSlug, state.proposalSource, nodeId, state.mockupStates || {}));
76
76
  }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @module explorer/page-pieces
3
+ *
4
+ * cornfield's page mounts the pieces (explorer/pieces/) into the document (spec 0011 D3). `index.html` keeps only the place of each: a comment
5
+ * `<!--corn-piece:NAME/SLOT-->` where the piece's markup goes (the piece's elements are inserted before it). This module finds those places,
6
+ * mounts the piece there on the page's instance, and keeps the handle (`pagePiece(name)`) for the bridges the modules that are not yet on an
7
+ * instance still call (explorer/panels.js, layers.js, search.js).
8
+ *
9
+ * `ensurePagePieces()` is page.js's one call at start. The bridges call it too: where the document's markup was replaced (a test sets
10
+ * `document.body.innerHTML` again), a piece whose places are gone is ended and mounted again at the new ones; where nothing changed it does
11
+ * nothing. A piece whose places are not in the document is not mounted.
12
+ *
13
+ * This is page code, not a piece: it reads the page instance (state.js) and the document. It goes when the bridges do.
14
+ */
15
+
16
+ import { pageInstance } from './state.js';
17
+ import { pageMap } from './render.js';
18
+ import * as nodePanel from './pieces/node-panel.js';
19
+ import * as layers from './pieces/layers.js';
20
+ import * as search from './pieces/search.js';
21
+
22
+ /** The pieces of the page, in the order they are mounted (the node panel registers its sheet; search and the Layers menu follow the map) */
23
+ const PIECES = { 'node-panel': nodePanel, layers, search };
24
+ const mounted = new Map(); // name -> { handle, markers: Comment[] }
25
+
26
+ /** The marker comments of a piece in the document: { slot: Comment } */
27
+ function markersOf(doc, name) {
28
+ const found = {};
29
+ if (!doc || !doc.body) return found;
30
+ const walker = doc.createTreeWalker(doc.body, 128 /* NodeFilter.SHOW_COMMENT */);
31
+ const prefix = `corn-piece:${name}/`;
32
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
33
+ if (node.data.startsWith(prefix)) found[node.data.slice(prefix.length)] = node;
34
+ }
35
+ return found;
36
+ }
37
+
38
+ /** Mounts each piece at its places in the document, or again where the places were replaced; ends one whose places are gone. Returns the handles by name. */
39
+ export function ensurePagePieces() {
40
+ const inst = pageInstance();
41
+ const doc = inst.doc;
42
+ if (!doc) return {};
43
+ for (const [name, piece] of Object.entries(PIECES)) {
44
+ const have = mounted.get(name);
45
+ if (have && have.markers.every((m) => m.isConnected)) continue;
46
+ if (have) { have.handle.destroy(); mounted.delete(name); }
47
+ const slots = markersOf(doc, name);
48
+ const markers = Object.values(slots);
49
+ if (!markers.length) continue;
50
+ pageMap(); // the pieces follow the page's map: it is there before they are
51
+ mounted.set(name, { handle: piece.mount(doc.body, inst, { slots }), markers });
52
+ }
53
+ return Object.fromEntries([...mounted].map(([name, { handle }]) => [name, handle]));
54
+ }
55
+
56
+ /** The page's mounted piece by name ('node-panel', 'layers', 'search'), or null */
57
+ export function pagePiece(name) {
58
+ ensurePagePieces();
59
+ const have = mounted.get(name);
60
+ return have ? have.handle : null;
61
+ }