@popcorn245/cornfield 0.39.0 → 0.41.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)
@@ -51,8 +51,8 @@ export function labelWidth(node) {
51
51
  // 1. The data tier (stores, tables, ROM stages) rings the root, grouped by kind.
52
52
  // 2. A hub's children fill concentric rings around it; the spacing along a ring
53
53
  // comes from that cluster's own label widths, so labels never collide.
54
- // 3. Hubs with children share one ring around the core, each taking arc in
55
- // proportion to its cluster's size; the ring is sized so clusters never touch.
54
+ // 3. Hubs with children are packed round the core, largest first (ties by label), each in the free place nearest it,
55
+ // searched from the top clockwise (spec 0008 D1); a cluster's place depends only on the ones placed before it.
56
56
  // 4. Childless hubs (leaf apps, tools, packages) sit on an outer ring.
57
57
  // ---------------------------------------------------------------------------
58
58
  const DATA_TYPES = ['store', 'table', 'rom'];
@@ -145,6 +145,34 @@ function placePack(pack, ox, oy, clusters) {
145
145
  });
146
146
  }
147
147
 
148
+
149
+ /**
150
+ * The free place nearest (0, 0) for a disc of radius `r` among `discs` (`{ x, y, r }`, each already holding its own gap),
151
+ * searched along rays from the top clockwise every STEP degrees: on each ray the nearest point where the disc touches
152
+ * none, and of the rays the nearest of all, the first in the search order winning a tie. Exact and deterministic.
153
+ */
154
+ const PACK_STEP_DEG = 2;
155
+ function nearestFreePlace(discs, r) {
156
+ let best = null;
157
+ for (let deg = 0; deg < 360; deg += PACK_STEP_DEG) {
158
+ const a = -Math.PI / 2 + (deg * Math.PI) / 180;
159
+ const dx = Math.cos(a), dy = Math.sin(a);
160
+ // The stretches of this ray where the disc would touch another (open intervals of the distance along it)
161
+ const blocked = [];
162
+ for (const d of discs) {
163
+ const along = dx * d.x + dy * d.y;
164
+ const reach = d.r + r;
165
+ const disc = along * along - (d.x * d.x + d.y * d.y) + reach * reach;
166
+ if (disc > 0) blocked.push([along - Math.sqrt(disc), along + Math.sqrt(disc)]);
167
+ }
168
+ blocked.sort((p, q) => p[0] - q[0]);
169
+ let at = 0;
170
+ for (const [lo, hi] of blocked) if (lo < at + 1e-9 && hi > at) at = hi;
171
+ if (!best || at < best.at - 1e-6) best = { at, x: dx * at, y: dy * at };
172
+ }
173
+ return best;
174
+ }
175
+
148
176
  export function computeOrbitalLayout() {
149
177
  touchScene(); // positions and rings change
150
178
  const { nodes, edges } = state;
@@ -214,31 +242,31 @@ export function computeOrbitalLayout() {
214
242
  packs.set(hub.id, packTree(children, kidsOf, spacingOf, byTypeThenLabel, new Set([hub.id])));
215
243
  });
216
244
 
217
- // 3. Hubs with children around the core, arc proportional to cluster size
245
+ // 3. Hubs with children, packed (spec 0008 D1): the largest cluster first (ties by label) takes the free place nearest
246
+ // the core, searched from the top clockwise, GAP from every cluster already placed. No physics: the same map
247
+ // always draws the same, and a cluster's place depends only on the ones placed before it.
218
248
  const GAP = 70;
219
- const big = hubs.filter((h) => packs.has(h.id)).sort((a, b) => packs.get(b.id).extent - packs.get(a.id).extent);
220
- const maxExtent = big.length ? Math.max(...big.map((h) => packs.get(h.id).extent)) : 0;
221
- const need = big.reduce((s, h) => s + 2 * packs.get(h.id).extent + GAP, 0);
222
- const hubR = Math.max(coreExtent + maxExtent + GAP, need / (2 * Math.PI));
223
- let angle = -Math.PI / 2;
249
+ const big = hubs.filter((h) => packs.has(h.id))
250
+ .sort((a, b) => packs.get(b.id).extent - packs.get(a.id).extent || String(a.label).localeCompare(String(b.label)));
251
+ const discs = [{ x: 0, y: 0, r: coreExtent }];
252
+ let hubReach = coreExtent; // how far from the centre the packed clusters reach
224
253
  big.forEach((hub) => {
225
254
  const pack = packs.get(hub.id);
226
- const share = ((2 * pack.extent + GAP) / need) * Math.PI * 2;
227
- const a = angle + share / 2;
228
- hub.x = Math.cos(a) * hubR;
229
- hub.y = Math.sin(a) * hubR;
255
+ const at = nearestFreePlace(discs, pack.extent + GAP / 2);
256
+ hub.x = at.x;
257
+ hub.y = at.y;
258
+ discs.push({ x: hub.x, y: hub.y, r: pack.extent + GAP / 2 });
259
+ hubReach = Math.max(hubReach, Math.hypot(hub.x, hub.y) + pack.extent);
230
260
  LAYOUT.clusters.push({ x: hub.x, y: hub.y, radii: pack.radii });
231
261
  placePack(pack, hub.x, hub.y, LAYOUT.clusters);
232
- angle += share;
233
262
  });
234
- if (big.length) LAYOUT.rings.push({ x: 0, y: 0, r: hubR });
235
263
 
236
264
  // 4. Childless hubs on an outer ring, and with them any node that has no parent and is none of the above
237
265
  // (it would otherwise sit on the centre, under whatever else is there)
238
266
  const homeless = nodes.filter((n) => n.id !== 'root' && !parentMap[n.id] && !isData(n) && !hubIds.has(n.id));
239
267
  const leaves = [...hubs.filter((h) => !packs.has(h.id)), ...homeless].sort(byTypeThenLabel);
240
268
  const leafSpacing = Math.max(120, ...leaves.map((n) => labelWidth(n) + 30));
241
- const leafR = Math.max(hubR + maxExtent + 90, (leaves.length * leafSpacing) / (2 * Math.PI));
269
+ const leafR = Math.max(hubReach + 90, (leaves.length * leafSpacing) / (2 * Math.PI));
242
270
  leaves.forEach((n, i) => {
243
271
  const a = -Math.PI / 2 + (i / Math.max(1, leaves.length)) * Math.PI * 2;
244
272
  n.x = Math.cos(a) * leafR;
package/explorer/main.js CHANGED
@@ -17,6 +17,7 @@
17
17
  * scenario.js the player's pure core scenario-ui.js its bar, keys and camera
18
18
  * bench.js /?bench=1 stopwatch and /?fixture=5k (the generated topology, from the server)
19
19
  * keyboard.js the map by keyboard and the screen reader's announcer; keyboard-model.js its pure half
20
+ * search.js search: the count, the list by type and the stepping; search-model.js its pure half (what it reads and the rank)
20
21
  * live.js the live layer: the chip, polling, laying a live source's answer over the map; live-model.js its pure half
21
22
  * review-tokens.js review tokens for the review API, when somebody is signed in: make one (shown once), list, revoke; review-tokens-model.js its pure half
22
23
  * forge-panel.js the issues and PRs panel, when the config names a forge: a PR lights the nodes it changes; forge-panel-model.js its pure half
@@ -24,11 +25,11 @@
24
25
  */
25
26
 
26
27
  import { state, nodeById, touchScene } from './state.js';
27
- import { updateSearchStatus } from './search-status.js';
28
+ import { initSearch, setQuery, stepMatch } from './search.js';
28
29
  import { render, resize, fitGraphToViewport, fitPadding, isNodeVisible, setRenderer, getRenderer, ensureFlowLoop, renderNow, holdFrames } from './render.js';
29
30
  import { createRenderer } from './renderer.js';
30
31
  import { clearFreeformPositions, layoutOrbit, loadFreeformPositions } from './layout.js';
31
- import { closeLegendMenu, toggleAllLayers, toggleLayer, toggleLegendMenu } from './layers.js';
32
+ import { clickWithLegendMenu, setProjectLayers, toggleAllLayers, toggleLayer, toggleLayerKinds, toggleLegendMenu } from './layers.js';
32
33
  import { closeDrawer, copySpec, selectNode, startRun } from './panels.js';
33
34
  import { initScenarioUi, maybeStartDemo, playOutage } from './scenario-ui.js';
34
35
  import { initSheets } from './sheets.js';
@@ -87,27 +88,6 @@ function resetFreeformPositions() {
87
88
  // ---------------------------------------------------------------------------
88
89
  // Search
89
90
  // ---------------------------------------------------------------------------
90
- function handleSearch(value) {
91
- state.searchQuery = value.trim();
92
- touchScene();
93
- for (const id of ['mobile-node-search', 'node-search']) {
94
- const input = $(id);
95
- if (input && input.value !== value) input.value = value;
96
- }
97
- if (state.searchQuery) {
98
- const q = state.searchQuery.toLowerCase();
99
- const found = state.nodes.find((n) => isNodeVisible(n) && n.label.toLowerCase().includes(q));
100
- if (found) {
101
- state.camera.x = state.width / 2 - found.x * state.camera.zoom;
102
- state.camera.y = state.height / 2 - found.y * state.camera.zoom;
103
- }
104
- updateSearchStatus(state.searchQuery, !!found);
105
- } else {
106
- updateSearchStatus('', false);
107
- }
108
- render();
109
- }
110
-
111
91
  function toggleMobileSearch(open) {
112
92
  const bar = $('mobile-search-bar');
113
93
  const input = $('mobile-node-search');
@@ -126,9 +106,10 @@ const ACTIONS = {
126
106
  'reset-view': () => fitGraphToViewport(fitPadding()),
127
107
  'fit': () => fitGraphToViewport(fitPadding()),
128
108
  'toggle-layers-menu': () => toggleLegendMenu(),
129
- 'layers-all': () => toggleAllLayers(true),
130
- 'layers-none': () => toggleAllLayers(false),
131
- 'toggle-layer': (el) => toggleLayer(el.dataset.layer),
109
+ 'layers-all': () => toggleAllLayers(true, { viewer: true }),
110
+ 'layers-none': () => toggleAllLayers(false, { viewer: true }),
111
+ 'toggle-layer': (el) => toggleLayer(el.dataset.layer, { viewer: true }),
112
+ 'toggle-layer-kinds': (el) => toggleLayerKinds(el.dataset.layer),
132
113
  'toggle-freeform': () => toggleFreeformMode(),
133
114
  'reset-positions': () => resetFreeformPositions(),
134
115
  'preset-map': () => {
@@ -141,7 +122,9 @@ const ACTIONS = {
141
122
  },
142
123
  'toggle-mobile-search': () => toggleMobileSearch(),
143
124
  'close-mobile-search': () => toggleMobileSearch(false),
144
- 'clear-search': () => handleSearch(''),
125
+ 'clear-search': () => { setQuery(''); const field = $('node-search'); const bar = $('mobile-search-bar'); (bar && !bar.hidden ? $('mobile-node-search') : field).focus(); },
126
+ 'search-prev': () => stepMatch(-1),
127
+ 'search-next': () => stepMatch(1),
145
128
  'close-drawer': () => closeDrawer(),
146
129
  'copy-spec': (el) => copySpec(el),
147
130
  'start-run': () => startRun(),
@@ -151,16 +134,14 @@ const ACTIONS = {
151
134
  'set-theme': (el) => setThemeChoice(el.dataset.choice),
152
135
  };
153
136
 
154
- document.addEventListener('click', (e) => {
137
+ // 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)
138
+ document.addEventListener('click', (e) => clickWithLegendMenu(e.target, () => {
155
139
  const target = e.target.closest('[data-action]');
156
140
  if (target) {
157
141
  const action = ACTIONS[target.dataset.action];
158
142
  if (action) action(target);
159
143
  }
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
- });
144
+ }));
164
145
 
165
146
  // ---------------------------------------------------------------------------
166
147
  // /?bench=1: the scripted pan-and-zoom of bench.js on the map as loaded
@@ -214,13 +195,12 @@ initSheets();
214
195
  initScenarioUi();
215
196
  initReviewColumn(); // the review column: the changes, and the personas with their scenarios (review-column.js)
216
197
  window.addEventListener('resize', resize);
217
- $('node-search').addEventListener('input', (e) => handleSearch(e.target.value));
218
- $('mobile-node-search').addEventListener('input', (e) => handleSearch(e.target.value));
198
+ initSearch(); // the count, the list and the stepping of both search fields (search.js)
219
199
 
220
200
  resize();
221
201
  syncViewUi();
222
202
  // /?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
203
+ 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
204
  loadTopology().then(async (ok) => {
225
205
  if (!ok) return;
226
206
  // The sources the repo's cornfield.config.js names (plugins.js): a live layer, a house, devices, a checker; each optional