@popcorn245/cornfield 0.46.1 → 0.47.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 (56) 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 +98 -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 +552 -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-build.js +88 -0
  18. package/explorer/flow-style.js +28 -0
  19. package/explorer/flows.js +11 -132
  20. package/explorer/fly.js +11 -43
  21. package/explorer/hint.js +15 -88
  22. package/explorer/index.html +40 -82
  23. package/explorer/input.js +197 -177
  24. package/explorer/instance-state.js +172 -0
  25. package/explorer/instance.js +267 -0
  26. package/explorer/keyboard.js +14 -206
  27. package/explorer/labels.js +3 -3
  28. package/explorer/layers.js +34 -445
  29. package/explorer/layout.js +14 -372
  30. package/explorer/main.js +4 -226
  31. package/explorer/map-style.js +27 -525
  32. package/explorer/mockups-model.js +3 -3
  33. package/explorer/page-pieces.js +66 -0
  34. package/explorer/page.js +223 -0
  35. package/explorer/panels.js +29 -409
  36. package/explorer/pieces/adopt-tokens.js +38 -0
  37. package/explorer/pieces/layers.js +325 -0
  38. package/explorer/pieces/map-stage.css +14 -0
  39. package/explorer/pieces/map.js +332 -0
  40. package/explorer/pieces/node-panel.js +536 -0
  41. package/explorer/pieces/search.js +454 -0
  42. package/explorer/proposal-model.js +1 -1
  43. package/explorer/proposal.js +1 -0
  44. package/explorer/render.js +37 -267
  45. package/explorer/renderer-canvas2d.js +4 -4
  46. package/explorer/renderer-webgl.js +21 -8
  47. package/explorer/renderer.js +12 -9
  48. package/explorer/scene.js +3 -2
  49. package/explorer/search-status.js +8 -47
  50. package/explorer/search.js +26 -324
  51. package/explorer/selection-view.js +17 -19
  52. package/explorer/sheets.js +31 -379
  53. package/explorer/state.js +38 -173
  54. package/explorer/strings.js +17 -60
  55. package/explorer/view.js +4 -5
  56. package/package.json +1 -1
@@ -1,469 +1,58 @@
1
1
  /**
2
2
  * @module explorer/layers
3
3
  *
4
- * The Layers menu: one toggle per kind of node (apps, pages, tables, services, ...) with its
5
- * count, plus the legend of what the lines mean. The data-flow preset ignores the toggles. Outside nodes are
6
- * two layers by their kind (spec 0031): Cloud, and the Public web; the Cloud legend says what a call's `when` looks like.
4
+ * A bridge (spec 0011 D2 and D3, step 4): the layers are now the instance's (engine/layers.js) and the Layers menu is a piece
5
+ * (pieces/layers.js). This file keeps the old names for the modules that are not yet on an instance (check.js, forge-panel.js, house.js, live.js,
6
+ * proposal.js, review-column.js, scenario-ui.js, view.js, page.js), bound to the page's instance, and tells the piece when the theme changes
7
+ * (theme.js is not on an instance). It goes when the last of those callers is converted.
7
8
  */
8
9
 
9
- import { state, touchScene, escHtml } from './state.js';
10
- import { render, ensureFlowLoop, isNodeVisible } from './render.js';
11
- import { renderFlowLegend } from './flows.js';
12
- import { WHEN_STYLES } from './cloud-model.js';
13
- import { edgeKeyHtml, keySwatch } from './edge-key.js';
14
- import { themed } from './theme-model.js';
10
+ import { pageInstance } from './state.js';
11
+ import { pageMap } from './render.js';
15
12
  import { onThemeChange } from './theme.js';
16
- import { NODE_THEMES } from '../core/schema.js';
17
- import { STARTING_LAYERS, clientLayers, kindLetters, orderRows, startingLayerOf } from '../core/layers.js';
18
- import { layerOn, reviewHides, rowKeyOf, shownByProposal } from './layer-model.js';
19
- import { fillOfNode, groupOf, layerShows } from './scene.js';
20
- import { STROKE_TOKEN, cssColor, fillOf, getMapStyle, kindToken, onMapStyleChange, pageReader, setMapSubjects } from './map-style.js';
21
- import { over, parseColor, contrast } from '../core/color.js';
22
- import { DARK_GROUND, LIGHT_GROUND } from './theme-model.js';
23
- import { t } from './strings.js';
13
+ import { ensurePagePieces, pagePiece } from './page-pieces.js';
14
+ import * as L from './engine/layers.js';
24
15
 
25
- /** The types a starting row's nodes have (House: floors and rooms; Cloud and the Public web: `external`), or none for a row that is not a node type */
26
- const typesOf = (l) => (l.match && l.match.type ? [].concat(l.match.type) : []);
27
- /** The dot of the two rows that are not a node type: Data Flow's lines and the ring of a run in flight. Every other row's built-in dot is its
28
- * first type's colour in core/schema.js NODE_THEMES, the colour the map draws its nodes in when the theme sets none (one table, not two) */
29
- const NOT_A_TYPE = { flow: '#fb923c', runs: '#5eead4' };
30
- const builtIn = (l) => { const type = typesOf(l)[0]; return type && NODE_THEMES[type] ? NODE_THEMES[type].color : NOT_A_TYPE[l.key]; };
31
- /** The starting layers that start off: the infra layer is its own view, and the physical world's are loaded when first turned on (spec 0029) */
32
- const STARTS_OFF = new Set(['stack', 'machine', 'container', 'device', 'house', 'persona']);
16
+ export { LAYER_DEFS } from './engine/layers.js';
33
17
 
34
- /** The starting rows (core/layers.js STARTING_LAYERS) with the colour of their dot */
35
- export const LAYER_DEFS = STARTING_LAYERS.map((l) => ({ ...l, color: builtIn(l) }));
18
+ /** The page's instance, with its map and its pieces there: what the layers act on */
19
+ const page = () => { pageMap(); ensurePagePieces(); return pageInstance(); };
36
20
 
37
- const layerListeners = new Set();
38
21
  /** Calls `fn` after a layer goes on or off (live.js starts or stops the live layer). Returns how to stop. */
39
- export function onLayersChange(fn) {
40
- layerListeners.add(fn);
41
- return () => layerListeners.delete(fn);
42
- }
43
-
44
- /** The menu open or shut, and its button saying which (aria-expanded) */
45
- function setLegendMenu(open) {
46
- const menu = document.getElementById('legend-dropdown');
47
- if (menu) menu.hidden = !open;
48
- const btn = document.getElementById('legend-toggle-btn');
49
- if (btn) btn.setAttribute('aria-expanded', String(open));
50
- }
51
-
52
- export function toggleLegendMenu() {
53
- const menu = document.getElementById('legend-dropdown');
54
- if (menu) setLegendMenu(menu.hidden);
55
- }
22
+ export const onLayersChange = (fn) => L.onLayersChange(pageInstance(), fn);
56
23
 
57
- export function closeLegendMenu() {
58
- setLegendMenu(false);
59
- }
24
+ export const toggleLegendMenu = () => { const p = pagePiece('layers'); if (p) p.toggleMenu(); };
25
+ export const closeLegendMenu = () => { const p = pagePiece('layers'); if (p) p.closeMenu(); };
60
26
 
61
27
  /**
62
28
  * A click anywhere on the page: runs its action (`act`), then closes the Layers menu if the click was outside it. Whether it was inside is
63
29
  * read BEFORE the action: a row's action draws the rows again, the clicked node is then out of the page, and asking afterwards would take a
64
- * click on a row for a click outside the menu (main.js's document click handler).
30
+ * click on a row for a click outside the menu.
65
31
  * @param {EventTarget | null} target the click's target
66
32
  * @param {() => void} act
67
33
  */
68
34
  export function clickWithLegendMenu(target, act) {
69
- const menu = document.getElementById('legend-dropdown');
70
- const btn = document.getElementById('legend-toggle-btn');
35
+ const inst = pageInstance();
36
+ const menu = inst.el('legend-dropdown');
37
+ const btn = inst.el('legend-toggle-btn');
71
38
  const inside = !!menu && target instanceof Node && (menu.contains(target) || (!!btn && btn.contains(target)));
72
39
  act();
73
40
  if (menu && !menu.hidden && !inside) closeLegendMenu();
74
41
  }
75
42
 
76
- // ---------------------------------------------------------------------------
77
- // The rows (spec 0009 D1, D3, D8)
78
- // ---------------------------------------------------------------------------
79
-
80
- /** What a layer is when the viewer has not touched it: the config's `off`, else a starting layer's own default, else on */
81
- const defaultOf = (key) => (Object.hasOwn(state.layerDefaults, key) ? state.layerDefaults[key] : !STARTS_OFF.has(key));
82
- /** Whether a layer is on for what is drawn: the viewer's, or the review's while a proposal is under review (layer-model.js) */
83
- const isOn = (key) => layerOn(state, key);
84
-
85
- const NO_COLOR = '#94a3b8';
86
- /** A colour as the dot's style may hold it: a hex or an rgb()/rgba() of numbers, else the plain grey. A node's colour is the map's data
87
- * (a proposal can set it), so it is checked before it reaches a style attribute, and escaped there all the same */
88
- const NUM = '\\d{1,3}(?:\\.\\d+)?%?';
89
- const SWATCH_RE = new RegExp(`^(?:#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\\(\\s*${NUM}(?:\\s*,\\s*|\\s+)${NUM}(?:\\s*,\\s*|\\s+)${NUM}(?:\\s*[,/]\\s*(?:\\d*\\.)?\\d+%?)?\\s*\\))$`, 'i');
90
- const swatch = (c) => (typeof c === 'string' && c.length <= 64 && SWATCH_RE.test(c.trim()) ? c.trim() : NO_COLOR);
91
-
92
- /**
93
- * The colour of a row's dot: the fill the map draws for the row's nodes, by the map's own order (map-style.js `fillOf`: the type's or layer's
94
- * token, then the starting group's), else the row's built-in colour on this ground (`themed`). `node` is what the row's nodes are: for a
95
- * starting row its type (`typeOfRow`: a row of two types, House, speaks for its first, floors, so `--corn-map-group-house` is its dot unless
96
- * the theme gives floors a colour of their own) and its key as the group; for a project row its first node's type with the layer. A finer kind's token is left out: a dot is a row's, not a kind's.
97
- * A token's value is the theme's text and a node's colour is the project's: both go through `swatch` before they reach a style.
98
- */
99
- function rowColor(node, built) {
100
- const fill = fillOf(getMapStyle().values, node);
101
- // The built-in is a node's colour (project data): normalised as the map's renderers read it (`cssColor`, the reader of the tokens), so a
102
- // name or an `hsl()` the map draws is the dot too; anything that is not a colour is the grey
103
- return fill ? swatch(fill) : swatch(cssColor(themed(built, state.theme)));
104
- }
105
- /** The type a row's dot speaks for: of a row of several types (House), the first one the map holds, else the first; a row with no type, its key */
106
- const typeOfRow = (l) => { const types = typesOf(l); return (types.length > 1 && types.find((ty) => state.nodes.some((n) => n.type === ty))) || types[0] || l.key; };
107
-
108
- /** The ground of the menu: its surface laid over the page, as `--corn-surface-1` and `--corn-ground` say, else the theme's own ground */
109
- function menuSurface() {
110
- const fallback = state.theme === 'light' ? LIGHT_GROUND : DARK_GROUND;
111
- const read = pageReader();
112
- if (!read) return fallback;
113
- const ground = parseColor(read('--corn-ground'));
114
- const surface = parseColor(read('--corn-surface-1'));
115
- if (!ground[3] || !surface[3]) return fallback;
116
- const [r, g, b] = over(surface, over(ground, [0, 0, 0, 1]));
117
- return `rgb(${r}, ${g}, ${b})`;
118
- }
119
- /** The outline a dot or swatch gets when its fill is under 3:1 on the menu: the map's own outline colour when the theme sets one, else the CSS default (`.is-ringed`). The fill is never changed */
120
- function ringOf(color, surface) {
121
- if (contrast(color, surface) >= 3) return null;
122
- const stroke = getMapStyle().values[STROKE_TOKEN];
123
- return { stroke: stroke ? swatch(stroke) : '' };
124
- }
125
- /** A swatch of `color` on this menu: the fill, a soft glow on a dark ground, and the outline when it is needed. `extra` is more attributes (a kind's is `aria-hidden`) */
126
- function dot(color, on, surface, extra = '') {
127
- const ring = ringOf(color, surface);
128
- const glow = on && state.theme !== 'light' ? (/^#[0-9a-f]{6}$/i.test(color) ? `0 0 8px ${color}90` : `0 0 8px color-mix(in srgb, ${color} 56%, transparent)`) : 'none';
129
- const style = `background-color: ${color}; box-shadow: ${glow}${ring && ring.stroke ? `; --hx-dot-ring: ${ring.stroke}` : ''}`;
130
- return `<span class="hx-dot${extra ? ' hx-kind-swatch' : ''}${ring ? ' is-ringed' : ''}" data-corn="swatch"${extra} style="${escHtml(style)}"></span>`;
131
- }
132
-
133
- /**
134
- * The rows: the project layers that hold a node, then the starting ones in their usual order (`layers.order` first of all), and one more
135
- * for any node type on this map that none of them covers (a type a plugin or a newer sync adds), so every type present can be turned off.
136
- * `root` is always shown and has no row. The overlays are the rows with `overlay`: the menu draws them under their own heading.
137
- */
138
- function layerRows() {
139
- const dotted = (l) => { const type = typeOfRow(l); return { ...l, color: rowColor({ type, group: l.key }, NODE_THEMES[type] ? NODE_THEMES[type].color : l.color) }; };
140
- const held = new Set();
141
- const left = new Set(); // starting layers a project layer took nodes from
142
- state.nodes.forEach((n) => {
143
- const key = rowKeyOf(state, n);
144
- if (!key) return;
145
- held.add(key);
146
- const own = startingLayerOf(n);
147
- if (own !== key) left.add(own);
148
- });
149
- const projectDot = (l) => {
150
- const first = state.nodes.find((n) => rowKeyOf(state, n) === l.key);
151
- return { color: rowColor(first ? { type: first.type, layer: l.key, group: groupOf(first) } : { type: l.key, layer: l.key }, first ? fillOfNode(first) : NO_COLOR) };
152
- };
153
- const project = state.projectLayers.filter((l) => held.has(l.key)).map((l) => ({ key: l.key, label: l.label, desc: l.desc || '', project: true, ...projectDot(l) }));
154
- // A starting row a project layer has taken every node from goes (spec 0009 D7, example 3); with no project layer, every starting row stays, as it always was
155
- const starting = LAYER_DEFS.filter((l) => !l.overlay && (held.has(l.key) || !left.has(l.key))).map(dotted);
156
- const known = new Set([...LAYER_DEFS.map((l) => l.key), ...state.projectLayers.map((l) => l.key)]);
157
- const extra = [];
158
- held.forEach((key) => {
159
- if (known.has(key)) return;
160
- known.add(key);
161
- extra.push({ key, label: key.charAt(0).toUpperCase() + key.slice(1), color: rowColor({ type: key, group: key }, NO_COLOR), desc: `Nodes of the type ${key}` });
162
- });
163
- return { layers: [...orderRows(project, starting, state.layerOrder), ...extra], overlays: LAYER_DEFS.filter((l) => l.overlay).map(dotted) };
164
- }
165
-
166
- /** The chip says how many layers are on: " · 13 of 20". An overlay (Runs in flight) is not a layer: it is not counted */
167
- function paintCount() {
168
- const el = document.getElementById('layers-count');
169
- if (!el) return;
170
- const { layers } = layerRows();
171
- const on = layers.filter((l) => isOn(l.key)).length;
172
- el.textContent = ` · ${on} of ${layers.length}`;
173
- }
174
-
175
- // ---------------------------------------------------------------------------
176
- // What the viewer changed is kept in their browser (only the changes, so a layer the config adds later arrives with its default)
177
- // ---------------------------------------------------------------------------
178
- const STORE_KEY = 'cornfield:layers';
179
- let changes = {};
180
- const KEY_SHAPE = /^[a-z][a-z0-9-]{0,40}$/;
181
-
182
- function readChanges() {
183
- try {
184
- const parsed = JSON.parse(window.localStorage.getItem(STORE_KEY) || '{}');
185
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
186
- return Object.fromEntries(Object.entries(parsed).filter(([k, v]) => KEY_SHAPE.test(k) && typeof v === 'boolean'));
187
- } catch { return {}; }
188
- }
189
- function writeChanges() {
190
- try {
191
- if (Object.keys(changes).length) window.localStorage.setItem(STORE_KEY, JSON.stringify(changes)); else window.localStorage.removeItem(STORE_KEY);
192
- } catch { /* storage blocked: the choice holds for this visit */ }
193
- }
194
- /** Records what the viewer chose for a layer: a value equal to its default is no change */
195
- function keep(key, on) {
196
- if (on === defaultOf(key)) delete changes[key]; else changes[key] = on;
197
- }
198
-
199
- /**
200
- * Takes the project's layers from the config (`layers`, as /cornfield/config.json carries it; anything that does not pass core/layers.js is
201
- * ignored), sets what each layer is by default (the config's `off`), then lays the viewer's own changes over that.
202
- * @param {unknown} raw
203
- */
204
- export function setProjectLayers(raw) {
205
- const cfg = clientLayers(raw);
206
- state.projectLayers = cfg.add;
207
- state.layerOrder = cfg.order;
208
- const defaults = {};
209
- for (const l of LAYER_DEFS) defaults[l.key] = !STARTS_OFF.has(l.key);
210
- for (const l of cfg.add) defaults[l.key] = true;
211
- for (const k of cfg.off) defaults[k] = false;
212
- state.layerDefaults = defaults;
213
- changes = readChanges();
214
- for (const [k, v] of Object.entries(defaults)) state.activeLayers[k] = v;
215
- for (const [k, v] of Object.entries(changes)) state.activeLayers[k] = v;
216
- changed();
217
- }
218
-
219
- // ---------------------------------------------------------------------------
220
- // The menu
221
- // ---------------------------------------------------------------------------
222
- /** The rows whose kinds are open ("5 kinds"), by key: kept across redraws */
223
- const openKinds = new Set();
224
-
225
- /** "1 link", "3 in flight", else the number */
226
- const UNIT = Object.assign(Object.create(null), { flow: (n) => `${n} ${n === 1 ? 'link' : 'links'}`, runs: (n) => `${n} in flight` });
227
-
228
- /** The finer kinds of each row: `{ key: [{ kind, letters, n }] }`, by name, from the nodes the row holds (an outside node's kind is its layer, not a finer one) */
229
- function kindsByRow(rowOf) {
230
- const letters = kindLetters(state.nodes);
231
- const rows = new Map();
232
- state.nodes.forEach((n) => {
233
- if (typeof n.kind !== 'string' || !n.kind || n.type === 'external') return;
234
- const key = rowOf(n);
235
- if (!key) return;
236
- if (!rows.has(key)) rows.set(key, new Map());
237
- const id = `${n.type}\u0000${n.kind}`;
238
- const entry = rows.get(key).get(id) || { type: n.type, kind: n.kind, letters: letters.get(n.type).get(n.kind), n: 0 };
239
- entry.n++;
240
- rows.get(key).set(id, entry);
241
- });
242
- return new Map([...rows].map(([k, m]) => [k, [...m.values()].sort((a, b) => a.kind.localeCompare(b.kind))]));
243
- }
244
-
245
- /** The swatch of a kind: the theme's `--corn-map-kind-<type>-<kind>`, as the map draws that kind, or nothing when the token is unset (the node then has its type's colour, which is the row's dot). Decoration: the letters and the name say which kind it is */
246
- function kindSwatch(k, surface, pad) {
247
- const fill = getMapStyle().values[kindToken(k.type, k.kind)];
248
- if (!fill) return pad ? '<span class="hx-dot hx-kind-swatch is-blank" aria-hidden="true"></span>' : ''; // nothing to see, but the letters of the rows stay in line
249
- return dot(swatch(fill), true, surface, ' aria-hidden="true"');
250
- }
251
-
252
- /** What a viewer sees as "kinds" for a row: the disclosure button and, when open, the key rows. A key is a key, not a toggle (spec 0009 D5) */
253
- function kindsHtml(layer, kinds, surface) {
254
- if (!kinds || !kinds.length) return '';
255
- const open = openKinds.has(layer.key);
256
- const id = `layer-kinds-${layer.key}`;
257
- const words = `${kinds.length} ${kinds.length === 1 ? 'kind' : 'kinds'}`;
258
- const padded = kinds.some((k) => getMapStyle().values[kindToken(k.type, k.kind)]);
259
- const list = open ? `<ul class="hx-kind-keys" id="${escHtml(id)}">${kinds.map((k) => `<li class="hx-kind-key" data-corn="kind-key">${kindSwatch(k, surface, padded)}<span class="hx-kind-letter" aria-hidden="true">${escHtml(k.letters)}</span><span class="hx-kind-name">${escHtml(k.kind)}</span><span class="hx-count" data-corn="count">${k.n}</span></li>`).join('')}</ul>` : '';
260
- return `<div class="hx-kinds"><button type="button" class="hx-textbtn hx-kinds-btn" data-action="toggle-layer-kinds" data-layer="${escHtml(layer.key)}" aria-expanded="${open}" aria-controls="${escHtml(id)}" data-corn="layer-kinds" data-corn-kind="quiet">${open ? '▾' : '▸'} ${escHtml(words)}</button>${list}</div>`;
261
- }
262
-
263
- /** The finer kinds and project layers on the map, so the theme's tokens for them are read (map-style.js `setMapSubjects`) */
264
- function syncMapSubjects() {
265
- const seen = new Set();
266
- const kinds = [];
267
- state.nodes.forEach((n) => {
268
- if (typeof n.kind !== 'string' || !n.kind) return;
269
- const id = `${n.type}\u0000${n.kind}`;
270
- if (!seen.has(id)) { seen.add(id); kinds.push([n.type, n.kind]); }
271
- });
272
- setMapSubjects({ kinds, layers: state.projectLayers.map((l) => l.key) });
273
- }
274
-
275
- let drawing = false;
276
- export function renderLayerToggles() {
277
- drawing = true;
278
- try { syncMapSubjects(); } finally { drawing = false; } // reading the tokens of a new kind may tell the style listener below: this draw already has them
279
- paintCount();
280
- const container = document.getElementById('layer-toggles-container');
281
- if (!container) return;
282
-
283
- // Nodes by row. Data Flow has no nodes of its own: it counts its links, and says so; Runs in flight counts runs
284
- const rowOf = (n) => rowKeyOf(state, n);
285
- // Keyed by layer key: a project's key may be any word, "constructor" too, so these have no prototype to read through
286
- const counts = Object.create(null);
287
- const byProposal = Object.create(null);
288
- state.nodes.forEach((n) => {
289
- const key = rowOf(n);
290
- if (!key) return;
291
- counts[key] = (counts[key] || 0) + 1;
292
- if (!layerShows(state, n) && shownByProposal(state, n)) byProposal[key] = (byProposal[key] || 0) + 1;
293
- });
294
- counts.flow = state.edges.filter((e) => e.kind === 'flow').length;
295
- counts.runs = state.runsMap ? state.runsMap.flight.size : 0;
296
- const kinds = kindsByRow(rowOf);
297
- const { layers, overlays } = layerRows();
298
- const surface = menuSurface();
299
-
300
- const row = (layer) => {
301
- const on = isOn(layer.key);
302
- const shown = byProposal[layer.key] ? `<span class="hx-faint hx-layer-note" data-corn="layer-note">+${byProposal[layer.key]} shown by the proposal</span>` : '';
303
- // A row the review hid says so under its name (there is no room beside it): it can still be turned on, for the review
304
- const hid = !shown && counts[layer.key] && reviewHides(state, layer.key) ? `<span class="hx-faint hx-layer-note" data-corn="layer-note">${escHtml(t('hiddenWhileReviewing'))}</span>` : '';
305
- const name = `<span class="hx-toggle-name">${escHtml(layer.label)}</span>`;
306
- return `
307
- <button type="button" class="hx-toggle-row${on ? '' : ' is-off'}" data-action="toggle-layer" data-layer="${escHtml(layer.key)}" aria-pressed="${on}" title="${escHtml(layer.desc)}" data-corn="row">
308
- <span class="hx-toggle-label">
309
- ${dot(swatch(layer.color), on, surface)}
310
- ${hid ? `<span class="hx-toggle-text">${name}${hid}</span>` : name}${layer.live ? '<span class="hx-live-tag" data-corn="live-tag">live</span>' : ''}
311
- </span>
312
- <span class="hx-toggle-meta">${shown}
313
- <span class="hx-count" data-corn="count">${(UNIT[layer.key] || String)(counts[layer.key] || 0)}</span>
314
- <span class="hx-tick">${on ? '✓' : '—'}</span>
315
- </span>
316
- </button>${kindsHtml(layer, kinds.get(layer.key), surface)}`;
317
- };
318
-
319
- // The focus stays where it was across the redraw: the same row or disclosure, found again by what it names
320
- const active = document.activeElement && container.contains(document.activeElement) ? document.activeElement : null;
321
- const was = active ? { action: active.getAttribute('data-action'), layer: active.getAttribute('data-layer') } : null;
322
- container.innerHTML = layers.map(row).join('')
323
- + (overlays.length ? `<div class="hx-menu-title hx-overlays" data-corn="overlays"><span>${escHtml(t('overlays'))}</span></div>${overlays.map(row).join('')}` : '');
324
- if (was) {
325
- const again = [...container.querySelectorAll('[data-action]')].find((el) => el.getAttribute('data-action') === was.action && el.getAttribute('data-layer') === was.layer);
326
- if (again && typeof again.focus === 'function') again.focus({ preventScroll: true });
327
- }
328
- renderFlowLegend();
329
- renderEdgeKey();
330
- renderCloudLegend();
331
- }
332
-
333
- /** The Key (spec 0008 D7): each kind of line as the map draws it (edge-key.js) */
334
- export function renderEdgeKey() {
335
- const el = document.getElementById('edge-key');
336
- if (el) el.innerHTML = edgeKeyHtml();
337
- }
338
-
339
- /** What a call into a cloud node looks like for its `when` (spec 0031 section 6), while the Cloud layer is on */
340
- export function renderCloudLegend() {
341
- const el = document.getElementById('cloud-legend');
342
- if (!el) return;
343
- if (!layerOn(state, 'cloud')) { el.innerHTML = ''; el.hidden = true; return; }
344
- el.hidden = false;
345
- el.innerHTML = `
346
- <div class="hx-menu-title" data-corn="menu-title"><span>Cloud: when an outage bites</span></div>
347
- ${Object.entries(WHEN_STYLES).map(([when, s]) => `<div class="hx-legend-row"><span class="hx-legend-swatch hx-legend-swatch--wide hx-swatch-when--${when}">${keySwatch({ end: 'triangle', ticks: s.ticks })}</span><span>${s.legend}</span></div>`).join('')}
348
- <div class="hx-legend-row"><span class="hx-legend-swatch"></span><span class="hx-faint"><span class="hx-cloud-browser">(browser)</span> the visitor's browser makes the call, not our server</span></div>`;
349
- }
350
-
351
- function changed() {
352
- touchScene();
353
- layerListeners.forEach((fn) => fn());
354
- renderLayerToggles();
355
- render();
356
- ensureFlowLoop();
357
- }
358
-
359
- /** The words a screen reader gets when a layer goes on or off, with how many nodes it now draws */
360
- function say(text) {
361
- const el = document.getElementById('map-announcer');
362
- if (!el) return;
363
- el.textContent = '';
364
- setTimeout(() => { el.textContent = text; }, 30);
365
- }
366
-
367
- /**
368
- * Sets a layer on or off. `viewer`: the person chose it in the menu, so it is kept in their browser; a layer another part of the app
369
- * turns on (a deploy that lights a stack) is not a choice of theirs and is not kept. While a proposal is under review the choice is the review's:
370
- * kept for the review only (`state.review.manual`, or `.step` when a playing scenario needs the layer: `scenario`), never in `activeLayers` or the browser.
371
- */
372
- export function setLayer(key, on, { viewer = false, scenario = false } = {}) {
373
- const review = state.review && state.proposal ? state.review : null;
374
- if (review) {
375
- (scenario ? review.step : review.manual)[key] = on;
376
- review.rev++;
377
- } else {
378
- state.activeLayers[key] = on;
379
- if (viewer) { keep(key, on); writeChanges(); }
380
- }
381
- changed();
382
- if (viewer) {
383
- const { layers, overlays } = layerRows();
384
- const layer = [...layers, ...overlays].find((l) => l.key === key);
385
- const n = state.nodes.filter((x) => isNodeVisible(x)).length;
386
- say(`${layer ? layer.label : key} ${on ? 'on' : 'off'}${review ? ' for this review' : ''}. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
387
- }
388
- }
389
-
390
- /** Flips a layer (what a click on its row does); see `setLayer` */
391
- export function toggleLayer(key, opts = {}) {
392
- setLayer(key, !layerOn(state, key), opts);
393
- }
394
-
395
- /** All / None: every layer on or off, never an overlay; the root stays drawn. During a review it is the review's state that changes, not the viewer's */
396
- export function toggleAllLayers(on, { viewer = false } = {}) {
397
- const { layers } = layerRows();
398
- const keys = new Set([...LAYER_DEFS.filter((l) => !l.overlay).map((l) => l.key), ...state.projectLayers.map((l) => l.key), ...layers.map((l) => l.key)]);
399
- const review = state.review && state.proposal ? state.review : null;
400
- if (review) { keys.forEach((k) => { review.manual[k] = on; }); review.rev++; } else {
401
- keys.forEach((k) => { state.activeLayers[k] = on; if (viewer) keep(k, on); });
402
- if (viewer) writeChanges();
403
- }
404
- changed();
405
- if (viewer) {
406
- const n = state.nodes.filter((x) => isNodeVisible(x)).length;
407
- say(`${on ? 'All' : 'No'} layers on${review ? ' for this review' : ''}. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
408
- }
409
- }
410
-
411
- // ---------------------------------------------------------------------------
412
- // The review narrows the map to the change (issue #232)
413
- // The hiding is the review's, never the viewer's: `state.review` holds it (layer-model.js `layersOf` reads it), `activeLayers` and the saved choices are not touched.
414
- // ---------------------------------------------------------------------------
415
-
416
- /** A proposal is opened: a fresh review ("Show the whole map" off, nothing turned on by hand yet), also when one was already open */
417
- export function beginReview() {
418
- state.review = { whole: false, manual: {}, step: {}, rev: 0 }; // the map and the menu are drawn by the caller, once the proposal is on the map (proposal.js rebuildProposalMap)
419
- }
420
-
421
- /** The proposal is closed: the viewer's own layers are what is drawn again, exactly as they were */
422
- export function endReview() {
423
- if (!state.review) return;
424
- state.review = null;
425
- touchScene();
426
- renderLayerToggles();
427
- }
428
-
429
- /** What a screen reader hears when a review opens and hid layers: "Showing 4 of 22 layers: the ones this proposal changes." Nothing when no layer was hidden */
430
- export function reviewLayersLine() {
431
- if (!state.review || !state.proposal || state.review.whole) return '';
432
- const { layers } = layerRows();
433
- const held = new Set(state.nodes.map((n) => rowKeyOf(state, n))); // a layer that holds no node has nothing to hide
434
- if (!layers.some((l) => held.has(l.key) && reviewHides(state, l.key))) return '';
435
- const on = layers.filter((l) => isOn(l.key)).length;
436
- return `Showing ${on} of ${layers.length} layers: the ones this proposal changes.`;
437
- }
438
-
439
- /** "Show the whole map": on brings back every layer the viewer has on and the proposal's dimming of the rest (Diff as it always was); off narrows to the change again. Said once, here */
440
- export function setWholeMap(on) {
441
- const review = state.review && state.proposal ? state.review : null;
442
- if (!review || review.whole === on) return;
443
- review.whole = on;
444
- review.rev++;
445
- changed();
446
- say(on ? 'Showing the whole map.' : (reviewLayersLine() || 'Showing the change: the rest of the map is greyed.'));
447
- }
448
-
449
- /** A scenario ended: the layers it turned on for the review go off again (the focused view comes back). True when there were any */
450
- export function clearStepLayers() {
451
- const review = state.review;
452
- if (!review || !Object.keys(review.step).length) return false;
453
- review.step = {};
454
- review.rev++;
455
- touchScene();
456
- renderLayerToggles();
457
- return true;
458
- }
459
-
460
- /** Opens or closes the kinds of one row ("5 kinds"); the focus stays on its button */
461
- export function toggleLayerKinds(key) {
462
- if (openKinds.has(key)) openKinds.delete(key); else openKinds.add(key);
463
- renderLayerToggles();
464
- }
465
-
466
- // The dots and the legends are drawn in the theme's colours: drawn again when it changes (theme.js)
467
- onThemeChange(() => renderLayerToggles());
468
- // ... and when the map's own tokens change (a named theme, its stylesheet arriving, light and dark): the same signal the map is drawn again on
469
- onMapStyleChange(() => { if (!drawing) renderLayerToggles(); });
43
+ export const renderLayerToggles = () => L.redrawLayers(page());
44
+ export const renderEdgeKey = () => { const p = pagePiece('layers'); if (p) p.renderEdgeKey(); };
45
+ export const renderCloudLegend = () => { const p = pagePiece('layers'); if (p) p.renderCloudLegend(); };
46
+ export const setProjectLayers = (raw) => L.setProjectLayers(page(), raw);
47
+ export const setLayer = (key, on, opts) => L.setLayer(page(), key, on, opts);
48
+ export const toggleLayer = (key, opts) => L.toggleLayer(page(), key, opts);
49
+ export const toggleAllLayers = (on, opts) => L.toggleAllLayers(page(), on, opts);
50
+ export const beginReview = () => L.beginReview(pageInstance());
51
+ export const endReview = () => L.endReview(page());
52
+ export const reviewLayersLine = () => L.reviewLayersLine(pageInstance());
53
+ export const setWholeMap = (on) => L.setWholeMap(page(), on);
54
+ export const clearStepLayers = () => L.clearStepLayers(page());
55
+ export const toggleLayerKinds = (key) => { const p = pagePiece('layers'); if (p) p.toggleKinds(key); };
56
+
57
+ // The dots and the legends are drawn in the theme's colours: the piece draws them again when it changes (theme.js)
58
+ onThemeChange(() => pageInstance().emit('theme'));