cornfield 0.39.0 → 0.40.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.
@@ -7,38 +7,28 @@
7
7
  */
8
8
 
9
9
  import { state, touchScene, escHtml } from './state.js';
10
- import { render, ensureFlowLoop } from './render.js';
10
+ import { render, ensureFlowLoop, isNodeVisible } from './render.js';
11
11
  import { renderFlowLegend } from './flows.js';
12
- import { layerOf } from './live-model.js';
13
- import { WHEN_STYLES, externalLayer } from './cloud-model.js';
12
+ import { WHEN_STYLES } from './cloud-model.js';
14
13
  import { themed } from './theme-model.js';
15
14
  import { onThemeChange } from './theme.js';
15
+ import { STARTING_LAYERS, clientLayers, kindLetters, orderRows, startingLayerOf } from '../core/layers.js';
16
+ import { rowKeyOf, shownByProposal } from './layer-model.js';
17
+ import { layerShows } from './scene.js';
18
+ import { getMapStyle, groupToken, setMapSubjects } from './map-style.js';
19
+ import { t } from './strings.js';
16
20
 
17
- export const LAYER_DEFS = [
18
- { key: 'app', label: 'Apps', color: '#6366f1', desc: 'Subdomains' },
19
- { key: 'pkg', label: 'Packages', color: '#06b6d4', desc: 'Libraries' },
20
- { key: 'page', label: 'Pages & Routes', color: '#38bdf8', desc: 'Routes' },
21
- { key: 'atom', label: 'Atoms', color: '#10b981', desc: 'Base Components' },
22
- { key: 'molecule', label: 'Molecules', color: '#a855f7', desc: 'Composites' },
23
- { key: 'token', label: 'Design Tokens', color: '#ec4899', desc: 'Pollen CSS' },
24
- { key: 'tool', label: 'Dev Tools', color: '#f43f5e', desc: 'Utilities' },
25
- { key: 'flow', label: 'Data Flow', color: '#fb923c', desc: 'Tiers & sync' },
26
- { key: 'core', label: 'Core', color: '#14b8a6', desc: 'The shared core: what the apps and packages are built on. Shows with Packages or Atoms' },
27
- { key: 'store', label: 'Stores', color: '#fb923c', desc: 'Storage tiers and the ends of the data flows. Shows with Data Flow' },
28
- { key: 'table', label: 'Tables', color: '#fde047', desc: 'SQLite tables, reads & writes' },
29
- { key: 'rom', label: 'ROM', color: '#f0abfc', desc: 'Render on Mutation' },
30
- { key: 'service', label: 'Services', color: '#84cc16', desc: 'API jobs, webhooks and hooks' },
31
- { key: 'cloud', label: 'Cloud', color: '#94a3b8', desc: 'Services outside the house that we do not control: what runs, where software comes from, accounts (topology.cloud.json)' },
32
- { key: 'web', label: 'Public web', color: '#94a3b8', desc: 'Any public page or picture a person points us at: not cloud' },
33
- { key: 'stack', label: 'Infra', color: '#a8a29e', desc: 'Compose stacks and the domains they serve' },
34
- // The physical world (spec 0029). `live`: drawn or placed from the live layer, which loads when one of them goes on
35
- { key: 'machine', label: 'Machines', color: '#78716c', desc: 'The computers the code runs on, placed in their room from the inventory (live)', live: true },
36
- { key: 'container', label: 'Containers', color: '#d6d3d1', desc: 'One service of a stack, from its compose file' },
37
- { key: 'device', label: 'Devices', color: '#2dd4bf', desc: 'Cameras, and live: phones, NFC tags, Home Assistant devices', live: true },
38
- { key: 'house', label: 'House', color: '#a3e635', desc: 'Floors and rooms (live)', live: true },
39
- { key: 'runs', label: 'Runs in flight', color: '#5eead4', desc: 'A pulsing ring on the nodes an open agent run is changing; a dashed ring and a warning where two runs change the same node', overlay: true },
40
- { key: 'persona', label: 'People', color: '#fb7185', desc: 'Personas, with a live count of their accounts (never a name)', live: true },
41
- ];
21
+ /** The dot of each starting row: the colour its nodes are drawn in (a project layer's dot is its nodes' own, or the theme's group token) */
22
+ const COLORS = {
23
+ app: '#6366f1', pkg: '#06b6d4', page: '#38bdf8', atom: '#10b981', molecule: '#a855f7', token: '#ec4899', tool: '#f43f5e', flow: '#fb923c',
24
+ core: '#14b8a6', store: '#fb923c', table: '#fde047', rom: '#f0abfc', service: '#84cc16', cloud: '#94a3b8', web: '#94a3b8', stack: '#a8a29e',
25
+ machine: '#78716c', container: '#d6d3d1', device: '#2dd4bf', house: '#a3e635', runs: '#5eead4', persona: '#fb7185',
26
+ };
27
+ /** 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) */
28
+ const STARTS_OFF = new Set(['stack', 'machine', 'container', 'device', 'house', 'persona']);
29
+
30
+ /** The starting rows (core/layers.js STARTING_LAYERS) with the colour of their dot */
31
+ export const LAYER_DEFS = STARTING_LAYERS.map((l) => ({ ...l, color: COLORS[l.key] }));
42
32
 
43
33
  const layerListeners = new Set();
44
34
  /** Calls `fn` after a layer goes on or off (live.js starts or stops the live layer). Returns how to stop. */
@@ -64,61 +54,223 @@ export function closeLegendMenu() {
64
54
  setLegendMenu(false);
65
55
  }
66
56
 
67
- /** The key of the row a node is under (the Layers menu has a row for every type on the map) */
68
- const rowKey = (n) => (n.type === 'external' ? externalLayer(n) : layerOf(n.type));
57
+ /**
58
+ * 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
59
+ * 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
60
+ * click on a row for a click outside the menu (main.js's document click handler).
61
+ * @param {EventTarget | null} target the click's target
62
+ * @param {() => void} act
63
+ */
64
+ export function clickWithLegendMenu(target, act) {
65
+ const menu = document.getElementById('legend-dropdown');
66
+ const btn = document.getElementById('legend-toggle-btn');
67
+ const inside = !!menu && target instanceof Node && (menu.contains(target) || (!!btn && btn.contains(target)));
68
+ act();
69
+ if (menu && !menu.hidden && !inside) closeLegendMenu();
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // The rows (spec 0009 D1, D3, D8)
74
+ // ---------------------------------------------------------------------------
75
+
76
+ /** What a layer is when the viewer has not touched it: the config's `off`, else a starting layer's own default, else on */
77
+ const defaultOf = (key) => (Object.hasOwn(state.layerDefaults, key) ? state.layerDefaults[key] : !STARTS_OFF.has(key));
78
+ const isOn = (key) => state.activeLayers[key] !== false;
79
+
80
+ /**
81
+ * A project layer's dot: the theme's `--corn-map-group-<key>`, else the colour of the first node the layer holds (a project layer has no
82
+ * colour of its own in the config: it is the theme's to give, so the contrast check sees it).
83
+ */
84
+ function projectColor(layer) {
85
+ const set = getMapStyle().values[groupToken(layer.key)];
86
+ if (set) return set;
87
+ const first = state.nodes.find((n) => rowKeyOf(state, n) === layer.key);
88
+ return first ? first.color : NO_COLOR;
89
+ }
90
+
91
+ const NO_COLOR = '#94a3b8';
92
+ /** 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
93
+ * (a proposal can set it), so it is checked before it reaches a style attribute, and escaped there all the same */
94
+ const SWATCH_RE = /^(#[0-9a-f]{3,8}|rgba?\([0-9.,%\s/]+\))$/i;
95
+ const swatch = (c) => (typeof c === 'string' && SWATCH_RE.test(c.trim()) ? c.trim() : NO_COLOR);
69
96
 
70
97
  /**
71
- * The rows: the defined ones, and one more for any node type on this map that none of them covers (a type a plugin or
72
- * a newer sync adds), so every type present can be turned off. `root` is always shown and has no row.
98
+ * 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
99
+ * 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.
100
+ * `root` is always shown and has no row. The overlays are the rows with `overlay`: the menu draws them under their own heading.
73
101
  */
74
102
  function layerRows() {
75
- const known = new Set(LAYER_DEFS.map((l) => l.key));
76
- const extra = [];
103
+ const held = new Set();
104
+ const left = new Set(); // starting layers a project layer took nodes from
77
105
  state.nodes.forEach((n) => {
78
- const key = rowKey(n);
79
- if (key === 'root' || known.has(key)) return;
106
+ const key = rowKeyOf(state, n);
107
+ if (!key) return;
108
+ held.add(key);
109
+ const own = startingLayerOf(n);
110
+ if (own !== key) left.add(own);
111
+ });
112
+ const project = state.projectLayers.filter((l) => held.has(l.key)).map((l) => ({ key: l.key, label: l.label, desc: l.desc || '', project: true, color: projectColor(l) }));
113
+ // 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
114
+ const starting = LAYER_DEFS.filter((l) => !l.overlay && (held.has(l.key) || !left.has(l.key)));
115
+ const known = new Set([...LAYER_DEFS.map((l) => l.key), ...state.projectLayers.map((l) => l.key)]);
116
+ const extra = [];
117
+ held.forEach((key) => {
118
+ if (known.has(key)) return;
80
119
  known.add(key);
81
120
  extra.push({ key, label: key.charAt(0).toUpperCase() + key.slice(1), color: '#94a3b8', desc: `Nodes of the type ${key}` });
82
121
  });
83
- return [...LAYER_DEFS, ...extra];
122
+ return { layers: [...orderRows(project, starting, state.layerOrder), ...extra], overlays: LAYER_DEFS.filter((l) => l.overlay) };
84
123
  }
85
124
 
86
125
  /** The chip says how many layers are on: " · 13 of 20". An overlay (Runs in flight) is not a layer: it is not counted */
87
126
  function paintCount() {
88
127
  const el = document.getElementById('layers-count');
89
128
  if (!el) return;
90
- const layers = layerRows().filter((l) => !l.overlay);
91
- const on = layers.filter((l) => state.activeLayers[l.key] !== false).length;
129
+ const { layers } = layerRows();
130
+ const on = layers.filter((l) => isOn(l.key)).length;
92
131
  el.textContent = ` · ${on} of ${layers.length}`;
93
132
  }
94
133
 
134
+ // ---------------------------------------------------------------------------
135
+ // What the viewer changed is kept in their browser (only the changes, so a layer the config adds later arrives with its default)
136
+ // ---------------------------------------------------------------------------
137
+ const STORE_KEY = 'cornfield:layers';
138
+ let changes = {};
139
+ const KEY_SHAPE = /^[a-z][a-z0-9-]{0,40}$/;
140
+
141
+ function readChanges() {
142
+ try {
143
+ const parsed = JSON.parse(window.localStorage.getItem(STORE_KEY) || '{}');
144
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
145
+ return Object.fromEntries(Object.entries(parsed).filter(([k, v]) => KEY_SHAPE.test(k) && typeof v === 'boolean'));
146
+ } catch { return {}; }
147
+ }
148
+ function writeChanges() {
149
+ try {
150
+ if (Object.keys(changes).length) window.localStorage.setItem(STORE_KEY, JSON.stringify(changes)); else window.localStorage.removeItem(STORE_KEY);
151
+ } catch { /* storage blocked: the choice holds for this visit */ }
152
+ }
153
+ /** Records what the viewer chose for a layer: a value equal to its default is no change */
154
+ function keep(key, on) {
155
+ if (on === defaultOf(key)) delete changes[key]; else changes[key] = on;
156
+ }
157
+
158
+ /**
159
+ * Takes the project's layers from the config (`layers`, as /cornfield/config.json carries it; anything that does not pass core/layers.js is
160
+ * ignored), sets what each layer is by default (the config's `off`), then lays the viewer's own changes over that.
161
+ * @param {unknown} raw
162
+ */
163
+ export function setProjectLayers(raw) {
164
+ const cfg = clientLayers(raw);
165
+ state.projectLayers = cfg.add;
166
+ state.layerOrder = cfg.order;
167
+ const defaults = {};
168
+ for (const l of LAYER_DEFS) defaults[l.key] = !STARTS_OFF.has(l.key);
169
+ for (const l of cfg.add) defaults[l.key] = true;
170
+ for (const k of cfg.off) defaults[k] = false;
171
+ state.layerDefaults = defaults;
172
+ changes = readChanges();
173
+ for (const [k, v] of Object.entries(defaults)) state.activeLayers[k] = v;
174
+ for (const [k, v] of Object.entries(changes)) state.activeLayers[k] = v;
175
+ changed();
176
+ }
177
+
178
+ // ---------------------------------------------------------------------------
179
+ // The menu
180
+ // ---------------------------------------------------------------------------
181
+ /** The rows whose kinds are open ("5 kinds"), by key: kept across redraws */
182
+ const openKinds = new Set();
183
+
184
+ /** "1 link", "3 in flight", else the number */
185
+ const UNIT = Object.assign(Object.create(null), { flow: (n) => `${n} ${n === 1 ? 'link' : 'links'}`, runs: (n) => `${n} in flight` });
186
+
187
+ /** 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) */
188
+ function kindsByRow(rowOf) {
189
+ const letters = kindLetters(state.nodes);
190
+ const rows = new Map();
191
+ state.nodes.forEach((n) => {
192
+ if (typeof n.kind !== 'string' || !n.kind || n.type === 'external') return;
193
+ const key = rowOf(n);
194
+ if (!key) return;
195
+ if (!rows.has(key)) rows.set(key, new Map());
196
+ const id = `${n.type}\u0000${n.kind}`;
197
+ const entry = rows.get(key).get(id) || { kind: n.kind, letters: letters.get(n.type).get(n.kind), n: 0 };
198
+ entry.n++;
199
+ rows.get(key).set(id, entry);
200
+ });
201
+ return new Map([...rows].map(([k, m]) => [k, [...m.values()].sort((a, b) => a.kind.localeCompare(b.kind))]));
202
+ }
203
+
204
+ /** 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) */
205
+ function kindsHtml(layer, kinds) {
206
+ if (!kinds || !kinds.length) return '';
207
+ const open = openKinds.has(layer.key);
208
+ const id = `layer-kinds-${layer.key}`;
209
+ const words = `${kinds.length} ${kinds.length === 1 ? 'kind' : 'kinds'}`;
210
+ const list = open ? `<ul class="hx-kind-keys" id="${escHtml(id)}">${kinds.map((k) => `<li class="hx-kind-key" data-corn="kind-key"><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>` : '';
211
+ 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>`;
212
+ }
213
+
214
+ /** The finer kinds and project layers on the map, so the theme's tokens for them are read (map-style.js `setMapSubjects`) */
215
+ function syncMapSubjects() {
216
+ const seen = new Set();
217
+ const kinds = [];
218
+ state.nodes.forEach((n) => {
219
+ if (typeof n.kind !== 'string' || !n.kind) return;
220
+ const id = `${n.type}\u0000${n.kind}`;
221
+ if (!seen.has(id)) { seen.add(id); kinds.push([n.type, n.kind]); }
222
+ });
223
+ setMapSubjects({ kinds, layers: state.projectLayers.map((l) => l.key) });
224
+ }
225
+
95
226
  export function renderLayerToggles() {
227
+ syncMapSubjects();
96
228
  paintCount();
97
229
  const container = document.getElementById('layer-toggles-container');
98
230
  if (!container) return;
99
231
 
100
232
  // Nodes by row. Data Flow has no nodes of its own: it counts its links, and says so; Runs in flight counts runs
101
- const counts = {};
102
- state.nodes.forEach((n) => { const key = rowKey(n); counts[key] = (counts[key] || 0) + 1; });
233
+ const rowOf = (n) => rowKeyOf(state, n);
234
+ // Keyed by layer key: a project's key may be any word, "constructor" too, so these have no prototype to read through
235
+ const counts = Object.create(null);
236
+ const byProposal = Object.create(null);
237
+ state.nodes.forEach((n) => {
238
+ const key = rowOf(n);
239
+ if (!key) return;
240
+ counts[key] = (counts[key] || 0) + 1;
241
+ if (!layerShows(state, n) && shownByProposal(state, n)) byProposal[key] = (byProposal[key] || 0) + 1;
242
+ });
103
243
  counts.flow = state.edges.filter((e) => e.kind === 'flow').length;
104
244
  counts.runs = state.runsMap ? state.runsMap.flight.size : 0;
105
- const unit = { flow: (n) => `${n} ${n === 1 ? 'link' : 'links'}`, runs: (n) => `${n} in flight` };
245
+ const kinds = kindsByRow(rowOf);
246
+ const { layers, overlays } = layerRows();
106
247
 
107
- container.innerHTML = layerRows().map((layer) => {
108
- const on = state.activeLayers[layer.key] !== false;
109
- const color = themed(layer.color, state.theme); // the dot is the colour the map draws on this ground
248
+ const row = (layer) => {
249
+ const on = isOn(layer.key);
250
+ const color = escHtml(swatch(themed(swatch(layer.color), state.theme))); // the dot is the colour the map draws on this ground
251
+ const shown = byProposal[layer.key] ? `<span class="hx-faint hx-layer-note" data-corn="layer-note">+${byProposal[layer.key]} shown by the proposal</span>` : '';
110
252
  return `
111
253
  <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">
112
254
  <span class="hx-toggle-label">
113
255
  <span class="hx-dot" data-corn="swatch" style="background-color: ${color}; box-shadow: ${on && state.theme !== 'light' ? `0 0 8px ${color}90` : 'none'}"></span>
114
256
  <span class="hx-toggle-name">${escHtml(layer.label)}</span>${layer.live ? '<span class="hx-live-tag" data-corn="live-tag">live</span>' : ''}
115
257
  </span>
116
- <span class="hx-toggle-meta">
117
- <span class="hx-count" data-corn="count">${(unit[layer.key] || String)(counts[layer.key] || 0)}</span>
258
+ <span class="hx-toggle-meta">${shown}
259
+ <span class="hx-count" data-corn="count">${(UNIT[layer.key] || String)(counts[layer.key] || 0)}</span>
118
260
  <span class="hx-tick">${on ? '✓' : '—'}</span>
119
261
  </span>
120
- </button>`;
121
- }).join('');
262
+ </button>${kindsHtml(layer, kinds.get(layer.key))}`;
263
+ };
264
+
265
+ // The focus stays where it was across the redraw: the same row or disclosure, found again by what it names
266
+ const active = document.activeElement && container.contains(document.activeElement) ? document.activeElement : null;
267
+ const was = active ? { action: active.getAttribute('data-action'), layer: active.getAttribute('data-layer') } : null;
268
+ container.innerHTML = layers.map(row).join('')
269
+ + (overlays.length ? `<div class="hx-menu-title hx-overlays" data-corn="overlays"><span>${escHtml(t('overlays'))}</span></div>${overlays.map(row).join('')}` : '');
270
+ if (was) {
271
+ const again = [...container.querySelectorAll('[data-action]')].find((el) => el.getAttribute('data-action') === was.action && el.getAttribute('data-layer') === was.layer);
272
+ if (again && typeof again.focus === 'function') again.focus({ preventScroll: true });
273
+ }
122
274
  renderFlowLegend();
123
275
  renderCloudLegend();
124
276
  }
@@ -143,14 +295,48 @@ function changed() {
143
295
  ensureFlowLoop();
144
296
  }
145
297
 
146
- export function toggleLayer(key) {
147
- state.activeLayers[key] = state.activeLayers[key] === false; // a layer with no entry yet is on, as the toggles show it
298
+ /** The words a screen reader gets when a layer goes on or off, with how many nodes it now draws */
299
+ function say(text) {
300
+ const el = document.getElementById('map-announcer');
301
+ if (!el) return;
302
+ el.textContent = '';
303
+ setTimeout(() => { el.textContent = text; }, 30);
304
+ }
305
+
306
+ /**
307
+ * Turns 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
308
+ * turns on (a deploy that lights a stack) is not a choice of theirs and is not kept.
309
+ */
310
+ export function toggleLayer(key, { viewer = false } = {}) {
311
+ const on = state.activeLayers[key] === false; // a layer with no entry yet is on, as the toggles show it
312
+ state.activeLayers[key] = on;
313
+ if (viewer) { keep(key, on); writeChanges(); }
148
314
  changed();
315
+ if (viewer) {
316
+ const { layers, overlays } = layerRows();
317
+ const layer = [...layers, ...overlays].find((l) => l.key === key);
318
+ const n = state.nodes.filter((x) => isNodeVisible(x)).length;
319
+ say(`${layer ? layer.label : key} ${on ? 'on' : 'off'}. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
320
+ }
149
321
  }
150
322
 
151
- export function toggleAllLayers(on) {
152
- LAYER_DEFS.forEach((l) => { state.activeLayers[l.key] = on; });
323
+ /** All / None: every layer on or off, never an overlay; the root stays drawn */
324
+ export function toggleAllLayers(on, { viewer = false } = {}) {
325
+ const { layers } = layerRows();
326
+ 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)]);
327
+ keys.forEach((k) => { state.activeLayers[k] = on; if (viewer) keep(k, on); });
328
+ if (viewer) writeChanges();
153
329
  changed();
330
+ if (viewer) {
331
+ const n = state.nodes.filter((x) => isNodeVisible(x)).length;
332
+ say(`${on ? 'All' : 'No'} layers on. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
333
+ }
334
+ }
335
+
336
+ /** Opens or closes the kinds of one row ("5 kinds"); the focus stays on its button */
337
+ export function toggleLayerKinds(key) {
338
+ if (openKinds.has(key)) openKinds.delete(key); else openKinds.add(key);
339
+ renderLayerToggles();
154
340
  }
155
341
 
156
342
  // The dots and the legends are drawn in the theme's colours: drawn again when it changes (theme.js)
package/explorer/main.js CHANGED
@@ -28,7 +28,7 @@ import { updateSearchStatus } from './search-status.js';
28
28
  import { render, resize, fitGraphToViewport, fitPadding, isNodeVisible, setRenderer, getRenderer, ensureFlowLoop, renderNow, holdFrames } from './render.js';
29
29
  import { createRenderer } from './renderer.js';
30
30
  import { clearFreeformPositions, layoutOrbit, loadFreeformPositions } from './layout.js';
31
- import { closeLegendMenu, toggleAllLayers, toggleLayer, toggleLegendMenu } from './layers.js';
31
+ import { clickWithLegendMenu, setProjectLayers, toggleAllLayers, toggleLayer, toggleLayerKinds, toggleLegendMenu } from './layers.js';
32
32
  import { closeDrawer, copySpec, selectNode, startRun } from './panels.js';
33
33
  import { initScenarioUi, maybeStartDemo, playOutage } from './scenario-ui.js';
34
34
  import { initSheets } from './sheets.js';
@@ -126,9 +126,10 @@ const ACTIONS = {
126
126
  'reset-view': () => fitGraphToViewport(fitPadding()),
127
127
  'fit': () => fitGraphToViewport(fitPadding()),
128
128
  'toggle-layers-menu': () => toggleLegendMenu(),
129
- 'layers-all': () => toggleAllLayers(true),
130
- 'layers-none': () => toggleAllLayers(false),
131
- 'toggle-layer': (el) => toggleLayer(el.dataset.layer),
129
+ 'layers-all': () => toggleAllLayers(true, { viewer: true }),
130
+ 'layers-none': () => toggleAllLayers(false, { viewer: true }),
131
+ 'toggle-layer': (el) => toggleLayer(el.dataset.layer, { viewer: true }),
132
+ 'toggle-layer-kinds': (el) => toggleLayerKinds(el.dataset.layer),
132
133
  'toggle-freeform': () => toggleFreeformMode(),
133
134
  'reset-positions': () => resetFreeformPositions(),
134
135
  'preset-map': () => {
@@ -151,16 +152,14 @@ const ACTIONS = {
151
152
  'set-theme': (el) => setThemeChoice(el.dataset.choice),
152
153
  };
153
154
 
154
- document.addEventListener('click', (e) => {
155
+ // Any click outside the Layers menu closes it; a click on one of its rows does not (layers.js clickWithLegendMenu reads which before the action)
156
+ document.addEventListener('click', (e) => clickWithLegendMenu(e.target, () => {
155
157
  const target = e.target.closest('[data-action]');
156
158
  if (target) {
157
159
  const action = ACTIONS[target.dataset.action];
158
160
  if (action) action(target);
159
161
  }
160
- // Any click outside the Layers menu closes it
161
- const menu = $('legend-dropdown');
162
- if (menu && !menu.hidden && !menu.contains(e.target) && !$('legend-toggle-btn').contains(e.target)) closeLegendMenu();
163
- });
162
+ }));
164
163
 
165
164
  // ---------------------------------------------------------------------------
166
165
  // /?bench=1: the scripted pan-and-zoom of bench.js on the map as loaded
@@ -220,7 +219,7 @@ $('mobile-node-search').addEventListener('input', (e) => handleSearch(e.target.v
220
219
  resize();
221
220
  syncViewUi();
222
221
  // /?proposal=<slug> opens a proposal over the map, /?view=dataflow the data-flow preset: both have a link
223
- const configReady = loadClientConfig().then((config) => { applyBranding(document, config); watchHeaderFit(document); watchHint(document); watchFocusRoom(document); applyMapTheme(document, config.theme); syncViewUi(); return config; }); // the brand, then the theme's icons for the map; the hint again, in the repo's words
222
+ const configReady = loadClientConfig().then((config) => { applyBranding(document, config); watchHeaderFit(document); watchHint(document); watchFocusRoom(document); applyMapTheme(document, config.theme); setProjectLayers(config.layers); syncViewUi(); return config; }); // the brand, then the theme's icons for the map; the hint again, in the repo's words
224
223
  loadTopology().then(async (ok) => {
225
224
  if (!ok) return;
226
225
  // The sources the repo's cornfield.config.js names (plugins.js): a live layer, a house, devices, a checker; each optional
@@ -35,6 +35,7 @@
35
35
  import { NODE_THEMES } from '../core/schema.js';
36
36
  import { parseColor } from './theme-model.js';
37
37
  import { looksFor } from './scene.js';
38
+ import { iconKeyShape, iconKeysFor, mapGroupToken, mapKindToken } from '../core/layers.js';
38
39
 
39
40
  /** The node kinds (topology types) and the groups (layers a node can belong to) the tokens exist for */
40
41
  export const MAP_KINDS = Object.freeze(Object.keys(NODE_THEMES));
@@ -69,6 +70,8 @@ export const ICON_URL_PREFIX = '/cornfield/theme/assets/';
69
70
 
70
71
  export const nodeToken = (kind) => `--corn-map-node-${kind}`;
71
72
  export const groupToken = (group) => `--corn-map-group-${group}`;
73
+ /** 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) */
74
+ export const kindToken = (type, kind) => mapKindToken(type, kind);
72
75
  export const edgeToken = (kind) => `--corn-map-edge-${kind}`;
73
76
  export const stateToken = (name) => `--corn-map-${name}`;
74
77
 
@@ -215,12 +218,13 @@ function factorOf(value) {
215
218
  /**
216
219
  * The tokens as the page computes them.
217
220
  * @param {(name: string) => string} read the value of a custom property
221
+ * @param {string[]} [extra] more colour tokens to read: those of the finer kinds and project layers on the map (`setMapSubjects`)
218
222
  * @returns {{values: Record<string, string>, strokeWidth: number, font: string | null, edgeWidth: number | null, glow: number | null}}
219
223
  * `values` holds only the tokens that are a colour (not `auto`); `font`, `edgeWidth` and `glow` are null at `auto` or when the value is not one
220
224
  */
221
- export function readMapTokens(read) {
225
+ export function readMapTokens(read, extra = []) {
222
226
  const values = {};
223
- for (const name of MAP_COLOR_TOKENS) {
227
+ for (const name of [...MAP_COLOR_TOKENS, ...extra]) {
224
228
  const c = cssColor(read(name));
225
229
  if (c) values[name] = c;
226
230
  }
@@ -266,7 +270,7 @@ export function createIconStore(urls, { load = loadImage, onChange = () => {}, w
266
270
  const entries = new Map();
267
271
  let ready = 0;
268
272
  for (const [kind, url] of Object.entries(urls || {})) {
269
- if (!MAP_KINDS.includes(kind) || typeof url !== 'string' || !url.startsWith(ICON_URL_PREFIX) || url.includes('..')) continue;
273
+ if (!iconKeyShape(kind) || typeof url !== 'string' || !url.startsWith(ICON_URL_PREFIX) || url.includes('..')) continue;
270
274
  const entry = { status: 'loading', image: null };
271
275
  entries.set(kind, entry);
272
276
  Promise.resolve().then(() => load(url)).then((image) => {
@@ -323,6 +327,22 @@ function changed() {
323
327
  listeners.forEach((fn) => fn(current));
324
328
  }
325
329
 
330
+ /** 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) */
331
+ let subjectTokens = [];
332
+ const MAX_SUBJECT_TOKENS = 500;
333
+
334
+ /**
335
+ * Tells the style which finer kinds (`[type, kind]`) and project layers (keys) are on the map, so the tokens that colour them
336
+ * (`--corn-map-kind-<type>-<kind>`, `--corn-map-group-<key>`) are read. True when the set changed and a token differed.
337
+ * @param {{kinds?: [string, string][], layers?: string[]}} [subjects]
338
+ */
339
+ export function setMapSubjects({ kinds = [], layers = [] } = {}) {
340
+ const names = [...new Set([...kinds.map(([t, k]) => mapKindToken(t, k)), ...layers.map((l) => mapGroupToken(l))].filter(Boolean))].sort().slice(0, MAX_SUBJECT_TOKENS);
341
+ if (names.length === subjectTokens.length && names.every((n, i) => n === subjectTokens[i])) return false;
342
+ subjectTokens = names;
343
+ return refreshMapStyle();
344
+ }
345
+
326
346
  /** @returns {MapStyle} */
327
347
  export const getMapStyle = () => current;
328
348
 
@@ -338,7 +358,7 @@ export function onMapStyleChange(fn) {
338
358
  */
339
359
  export function refreshMapStyle(read = pageReader()) {
340
360
  if (!read) return false;
341
- const next = readMapTokens(read);
361
+ const next = readMapTokens(read, subjectTokens);
342
362
  const same = next.strokeWidth === tokens.strokeWidth && next.font === tokens.font && next.edgeWidth === tokens.edgeWidth && next.glow === tokens.glow
343
363
  && Object.keys(next.values).length === Object.keys(tokens.values).length
344
364
  && Object.entries(next.values).every(([k, v]) => tokens.values[k] === v);
@@ -379,6 +399,7 @@ export function resetMapStyle() {
379
399
  tokens = NO_TOKENS;
380
400
  icons = null;
381
401
  pixelated = false;
402
+ subjectTokens = [];
382
403
  changed();
383
404
  }
384
405
 
@@ -452,8 +473,9 @@ function compute(scene, style) {
452
473
  const stroke = values[STROKE_TOKEN];
453
474
  const painted = scene.painted || { nodes: new Set(), edges: new Set() };
454
475
  const nodes = scene.nodes.map((n) => {
455
- const fill = !painted.nodes.has(n.id) && firstOf(values, [nodeToken(n.type), groupToken(n.group || n.type)]);
456
- const icon = style.icons && style.icons.get(n.type) ? n.type : null;
476
+ // Which fill wins, most specific first (spec 0009 D6): the finer kind, the project layer, the type, the starting layer
477
+ const fill = !painted.nodes.has(n.id) && firstOf(values, [kindToken(n.type, n.kind), n.layer ? mapGroupToken(n.layer) : null, nodeToken(n.type), groupToken(n.group || n.type)].filter(Boolean));
478
+ 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
457
479
  const glows = style.glow != null && style.glow !== 1 && n.glow > 0;
458
480
  if (!fill && !label && !stroke && !icon && !glows) return n;
459
481
  const out = { ...n };
@@ -100,7 +100,8 @@ function dataSummary(node) {
100
100
  const row = (e, side) => `${nm(e[side])}${e.label && e.label !== 'imports' ? ` · ${escHtml(e.label)}` : ''}`;
101
101
  // The summary is the first sentence of the description above: shown again only when the description does not hold it
102
102
  const again = node.summary && !String(node.desc || '').includes(node.summary);
103
- return section('Kind:', [line(`${code(node.kind)}${again ? `<div class="hx-faint">${escHtml(node.summary)}</div>` : ''}`)])
103
+ // The kind is in the badge ("Service · timer", typeWords): it has no row of its own
104
+ return (again ? section('Summary:', [line(`<span class="hx-faint">${escHtml(node.summary)}</span>`)]) : '')
104
105
  + section('Started by:', [...(node.triggers || []).map((t) => line(escHtml(t))), ...edgesOf('triggers', 'to', node.id).map((e) => line(row(e, 'from')))])
105
106
  + section('Jobs:', (node.jobs || []).map((j) => line(`${code(j.name)} · cron ${code(j.cron)}`)))
106
107
  + section('Runs:', edgesOf('triggers', 'from', node.id).map((e) => line(row(e, 'to'))))
@@ -179,10 +180,11 @@ export function repaintThreads() {
179
180
  // The head: type · host, and what the open proposal does to the node
180
181
  // ---------------------------------------------------------------------------
181
182
 
182
- /** "Page", "Cloud", "Public web": the kind of node, in words */
183
+ /** "Page", "Cloud", "Public web", "Service · timer": the kind of node, in words, with its finer kind (spec 0009 D5) after a dot. A kind is text, shown as text */
183
184
  function typeWords(node) {
184
185
  if (node.type === 'external' && node.kind) return node.kind === 'web' ? 'Public web' : 'Cloud';
185
- return node.type.charAt(0).toUpperCase() + node.type.slice(1);
186
+ const type = node.type.charAt(0).toUpperCase() + node.type.slice(1);
187
+ return typeof node.kind === 'string' && node.kind ? `${type} · ${node.kind}` : type;
186
188
  }
187
189
 
188
190
  /** The host a node answers on, when it has one */
@@ -10,6 +10,7 @@
10
10
 
11
11
  import { CORE_RATIO, ARROW, EDGE_STRIKE, MARK_MIN_PX, edgePoint, looksFor, packetPoint } from './scene.js';
12
12
  import { ICON_RATIO, getMapStyle, looksWith, styledScene } from './map-style.js';
13
+ import { LETTER_RATIO, letterImage, showsLetters } from './kind-letters.js';
13
14
 
14
15
  const TAU = Math.PI * 2;
15
16
  /** A glow thinner than this on screen (px) is not drawn: zoomed out it is a fraction of a pixel, and costs a stroke or fill per edge and node */
@@ -217,6 +218,14 @@ function drawNode(ctx, node, zoom, looks, style) {
217
218
  const side = node.r * ICON_RATIO;
218
219
  ctx.imageSmoothingEnabled = !style.pixelated;
219
220
  ctx.drawImage(image, node.x - side / 2, node.y - side / 2, side, side);
221
+ } else if (showsLetters(node, zoom)) {
222
+ // A finer kind's letters (spec 0009 D5), where a theme's icon would be: the shortest start of its name, once the node is wide enough
223
+ const letters = letterImage(node.letters);
224
+ if (letters) {
225
+ const side = node.r * LETTER_RATIO;
226
+ ctx.imageSmoothingEnabled = true;
227
+ ctx.drawImage(letters, node.x - side / 2, node.y - side / 2, side, side);
228
+ }
220
229
  }
221
230
  ctx.restore();
222
231
  }
@@ -26,6 +26,7 @@
26
26
 
27
27
  import { ARROW, CORE_RATIO, EDGE_STRIKE, MARK_MIN_PX, edgePoint, looksFor, parseColor } from './scene.js';
28
28
  import { ICON_RATIO, getMapStyle, looksWith, styledScene } from './map-style.js';
29
+ import { LETTER_MIN_PX, LETTER_RATIO, isLetterKey, letterImage, letterKey, lettersOfKey } from './kind-letters.js';
29
30
  import {
30
31
  CURVE_SEGMENTS, EDGE_FRAG, GRID_FRAG, GRID_VERT, ICON_FRAG, ICON_VERT, LANE_FRAG, LANE_VERT, NODE_FRAG, NODE_VERT, PACKET_FRAG, PACKET_VERT,
31
32
  RING_FRAG, RING_VERT, TIP_FRAG, TIP_VERT, edgeVert,
@@ -194,22 +195,29 @@ export function packStrokes(scene) {
194
195
  }
195
196
 
196
197
  /**
197
- * The icons of the nodes that have one, grouped by kind (one texture, one draw each), in scene order within a kind.
198
+ * The icons of the nodes that have one, grouped by kind (one texture, one draw each), in scene order within a kind. A node with no theme icon
199
+ * but a finer kind's letters (spec 0009 D5) goes in a group of its own letters (`letters:j`), drawn from the image in explorer/kind-letters.js;
200
+ * a group says its smallest node's radius (`minR`), for the zoom below which its letters are not drawn.
198
201
  * @param {import('./scene.js').Scene} scene a scene through `styledScene`
199
- * @param {(kind: string) => boolean} has whether the kind's image has loaded
200
- * @returns {{data: Float32Array, count: number, stride: number, groups: {kind: string, first: number, count: number}[]}}
202
+ * @param {(kind: string) => boolean} has whether the kind's image has loaded (a letters key: whether its image could be made)
203
+ * @returns {{data: Float32Array, count: number, stride: number, groups: {kind: string, first: number, count: number, minR: number}[]}}
201
204
  */
202
205
  export function packIcons(scene, has) {
203
206
  const byKind = new Map();
204
207
  scene.nodes.forEach((n) => {
205
- if (!n.icon || !has(n.icon)) return;
206
- if (!byKind.has(n.icon)) byKind.set(n.icon, []);
207
- byKind.get(n.icon).push([n.x, n.y, n.r * ICON_RATIO, n.alpha]);
208
+ let kind = n.icon && has(n.icon) ? n.icon : null;
209
+ let side = n.r * ICON_RATIO;
210
+ if (!kind && !n.icon && n.letters && has(letterKey(n.letters))) { kind = letterKey(n.letters); side = n.r * LETTER_RATIO; }
211
+ if (!kind) return;
212
+ if (!byKind.has(kind)) byKind.set(kind, { rows: [], minR: Infinity });
213
+ const group = byKind.get(kind);
214
+ group.rows.push([n.x, n.y, side, n.alpha]);
215
+ group.minR = Math.min(group.minR, n.r);
208
216
  });
209
217
  const groups = [];
210
218
  const rows = [];
211
- for (const [kind, list] of byKind) {
212
- groups.push({ kind, first: rows.length, count: list.length });
219
+ for (const [kind, { rows: list, minR }] of byKind) {
220
+ groups.push({ kind, first: rows.length, count: list.length, minR });
213
221
  rows.push(...list);
214
222
  }
215
223
  const data = new Float32Array(rows.length * ICON_STRIDE);
@@ -492,7 +500,7 @@ export function createWebglRenderer(canvas, opts = {}) {
492
500
  gpu.iconStore = style.icons;
493
501
  }
494
502
  if (scene !== packedScene || scene.version !== packedVersion) {
495
- packed = { ...packScene(scene), strokes: packStrokes(scene), icons: packIcons(scene, (kind) => !!(style.icons && style.icons.get(kind))) };
503
+ packed = { ...packScene(scene), strokes: packStrokes(scene), icons: packIcons(scene, (kind) => (isLetterKey(kind) ? !!letterImage(lettersOfKey(kind)) : !!(style.icons && style.icons.get(kind)))) };
496
504
  packedScene = scene;
497
505
  packedVersion = scene.version;
498
506
  upload();
@@ -539,9 +547,11 @@ export function createWebglRenderer(canvas, opts = {}) {
539
547
  gl.bindVertexArray(icons.vao);
540
548
  gl.bindBuffer(gl.ARRAY_BUFFER, icons.buffer);
541
549
  for (const group of packed.icons.groups) {
542
- const image = style.icons && style.icons.get(group.kind);
550
+ const letters = isLetterKey(group.kind);
551
+ if (letters && group.minR * 2 * camera.zoom < LETTER_MIN_PX) continue; // too small on screen: the letters would be a smudge (kind-letters.js)
552
+ const image = letters ? letterImage(lettersOfKey(group.kind)) : style.icons && style.icons.get(group.kind);
543
553
  if (!image) continue;
544
- gl.bindTexture(gl.TEXTURE_2D, textureOf(group.kind, image, !!style.pixelated));
554
+ gl.bindTexture(gl.TEXTURE_2D, textureOf(group.kind, image, !!style.pixelated && !letters));
545
555
  gl.vertexAttribPointer(1, 4, gl.FLOAT, false, ICON_STRIDE * 4, group.first * ICON_STRIDE * 4); // this kind's rows
546
556
  gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, group.count);
547
557
  stats.draws++;