@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
@@ -0,0 +1,280 @@
1
+ /**
2
+ * @module explorer/engine/layers
3
+ *
4
+ * The layers of the map, on an instance: one per kind of node (apps, pages, tables, services, ...), the project's own on top of them, which are
5
+ * on, what the viewer chose, and what a review of a proposal shows. The data-flow preset ignores them. Outside nodes are two layers by their kind
6
+ * (spec 0031): Cloud, and the Public web. What the viewer sees of them, the Layers menu, is a piece (pieces/layers.js); this is what it and the
7
+ * rest of the explorer ask: set a layer, set them all, begin and end a review, the rows with their counts' colours.
8
+ *
9
+ * It tells the instance: `layers` after a layer goes on or off or the layers are set (live.js starts or stops the live layer on it) and
10
+ * `layers:redraw` when the menu should be drawn again. explorer/layers.js keeps the old names for the page's instance.
11
+ */
12
+
13
+ import { announce } from './keyboard.js';
14
+ import { themed } from '../theme-model.js';
15
+ import { NODE_THEMES } from '../../core/schema.js';
16
+ import { STARTING_LAYERS, clientLayers, orderRows, startingLayerOf } from '../../core/layers.js';
17
+ import { layerOn, reviewHides, rowKeyOf } from '../layer-model.js';
18
+ import { fillOfNode, groupOf } from '../scene.js';
19
+ import { cssColor, fillOf, mapStyleOf } from './map-style.js';
20
+
21
+ /** 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 */
22
+ export const typesOf = (l) => (l.match && l.match.type ? [].concat(l.match.type) : []);
23
+ /** 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
24
+ * 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) */
25
+ const NOT_A_TYPE = { flow: '#fb923c', runs: '#5eead4' };
26
+ const builtIn = (l) => { const type = typesOf(l)[0]; return type && NODE_THEMES[type] ? NODE_THEMES[type].color : NOT_A_TYPE[l.key]; };
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
+ export 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: builtIn(l) }));
32
+
33
+ /** Where the viewer's choices are kept, and what they are: only the changes, so a layer the config adds later arrives with its default */
34
+ export const STORE_KEY = 'cornfield:layers';
35
+ const KEY_SHAPE = /^[a-z][a-z0-9-]{0,40}$/;
36
+ const memoryOf = (inst) => inst.slot('layers', () => ({ changes: {}, storeKey: STORE_KEY }));
37
+
38
+ /** Where this instance keeps what the viewer chose (`null`: nowhere, the choice holds for this visit); the page's is cornfield:layers */
39
+ export function keepLayersIn(inst, key) {
40
+ memoryOf(inst).storeKey = key;
41
+ }
42
+
43
+ /** What a layer is when the viewer has not touched it: the config's `off`, else a starting layer's own default, else on */
44
+ const defaultOf = (inst, key) => (Object.hasOwn(inst.state.layerDefaults, key) ? inst.state.layerDefaults[key] : !STARTS_OFF.has(key));
45
+ /** 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) */
46
+ export const isOn = (inst, key) => layerOn(inst.state, key);
47
+
48
+ export const NO_COLOR = '#94a3b8';
49
+ /** 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
50
+ * (a proposal can set it), so it is checked before it reaches a style attribute, and escaped there all the same */
51
+ const NUM = '\\d{1,3}(?:\\.\\d+)?%?';
52
+ 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');
53
+ export const swatch = (c) => (typeof c === 'string' && c.length <= 64 && SWATCH_RE.test(c.trim()) ? c.trim() : NO_COLOR);
54
+
55
+ /**
56
+ * 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
57
+ * 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
58
+ * 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
59
+ * 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.
60
+ * 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.
61
+ */
62
+ function rowColor(inst, node, built) {
63
+ const fill = fillOf(mapStyleOf(inst).get().values, node);
64
+ // 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
65
+ // name or an `hsl()` the map draws is the dot too; anything that is not a colour is the grey
66
+ return fill ? swatch(fill) : swatch(cssColor(themed(built, inst.state.theme)));
67
+ }
68
+ /** 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 */
69
+ const typeOfRow = (inst, l) => { const types = typesOf(l); return (types.length > 1 && types.find((ty) => inst.state.nodes.some((n) => n.type === ty))) || types[0] || l.key; };
70
+
71
+ /**
72
+ * 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
73
+ * 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.
74
+ * `root` is always shown and has no row. The overlays are the rows with `overlay`: the menu draws them under their own heading.
75
+ */
76
+ export function layerRows(inst) {
77
+ const { state } = inst;
78
+ const dotted = (l) => { const type = typeOfRow(inst, l); return { ...l, color: rowColor(inst, { type, group: l.key }, NODE_THEMES[type] ? NODE_THEMES[type].color : l.color) }; };
79
+ const held = new Set();
80
+ const left = new Set(); // starting layers a project layer took nodes from
81
+ state.nodes.forEach((n) => {
82
+ const key = rowKeyOf(state, n);
83
+ if (!key) return;
84
+ held.add(key);
85
+ const own = startingLayerOf(n);
86
+ if (own !== key) left.add(own);
87
+ });
88
+ const projectDot = (l) => {
89
+ const first = state.nodes.find((n) => rowKeyOf(state, n) === l.key);
90
+ return { color: rowColor(inst, first ? { type: first.type, layer: l.key, group: groupOf(first) } : { type: l.key, layer: l.key }, first ? fillOfNode(first) : NO_COLOR) };
91
+ };
92
+ 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) }));
93
+ // 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
94
+ const starting = LAYER_DEFS.filter((l) => !l.overlay && (held.has(l.key) || !left.has(l.key))).map(dotted);
95
+ const known = new Set([...LAYER_DEFS.map((l) => l.key), ...state.projectLayers.map((l) => l.key)]);
96
+ const extra = [];
97
+ held.forEach((key) => {
98
+ if (known.has(key)) return;
99
+ known.add(key);
100
+ extra.push({ key, label: key.charAt(0).toUpperCase() + key.slice(1), color: rowColor(inst, { type: key, group: key }, NO_COLOR), desc: `Nodes of the type ${key}` });
101
+ });
102
+ return { layers: [...orderRows(project, starting, state.layerOrder), ...extra], overlays: LAYER_DEFS.filter((l) => l.overlay).map(dotted) };
103
+ }
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // What the viewer changed is kept in their browser (only the changes, so a layer the config adds later arrives with its default)
107
+ // ---------------------------------------------------------------------------
108
+ function readChanges(inst) {
109
+ const key = memoryOf(inst).storeKey;
110
+ if (!key) return {};
111
+ try {
112
+ const parsed = JSON.parse(inst.store.get(key) || '{}');
113
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
114
+ return Object.fromEntries(Object.entries(parsed).filter(([k, v]) => KEY_SHAPE.test(k) && typeof v === 'boolean'));
115
+ } catch { return {}; }
116
+ }
117
+ function writeChanges(inst) {
118
+ const { changes, storeKey } = memoryOf(inst);
119
+ if (!storeKey) return;
120
+ if (Object.keys(changes).length) inst.store.set(storeKey, JSON.stringify(changes)); else inst.store.remove(storeKey);
121
+ }
122
+ /** Records what the viewer chose for a layer: a value equal to its default is no change */
123
+ function keep(inst, key, on) {
124
+ const { changes } = memoryOf(inst);
125
+ if (on === defaultOf(inst, key)) delete changes[key]; else changes[key] = on;
126
+ }
127
+
128
+ /**
129
+ * Takes the project's layers from the config (`layers`, as /cornfield/config.json carries it; anything that does not pass core/layers.js is
130
+ * ignored), sets what each layer is by default (the config's `off`), then lays the viewer's own changes over that.
131
+ * @param {unknown} raw
132
+ */
133
+ export function setProjectLayers(inst, raw) {
134
+ const { state } = inst;
135
+ const cfg = clientLayers(raw);
136
+ state.projectLayers = cfg.add;
137
+ state.layerOrder = cfg.order;
138
+ const defaults = {};
139
+ for (const l of LAYER_DEFS) defaults[l.key] = !STARTS_OFF.has(l.key);
140
+ for (const l of cfg.add) defaults[l.key] = true;
141
+ for (const k of cfg.off) defaults[k] = false;
142
+ state.layerDefaults = defaults;
143
+ const mem = memoryOf(inst);
144
+ mem.changes = readChanges(inst);
145
+ for (const [k, v] of Object.entries(defaults)) state.activeLayers[k] = v;
146
+ for (const [k, v] of Object.entries(mem.changes)) state.activeLayers[k] = v;
147
+ changed(inst);
148
+ }
149
+
150
+ /** The finer kinds and project layers on the map, so the theme's tokens for them are read (map-style.js `setSubjects`) */
151
+ export function syncMapSubjects(inst) {
152
+ const { state } = inst;
153
+ const seen = new Set();
154
+ const kinds = [];
155
+ state.nodes.forEach((n) => {
156
+ if (typeof n.kind !== 'string' || !n.kind) return;
157
+ const id = `${n.type}\u0000${n.kind}`;
158
+ if (!seen.has(id)) { seen.add(id); kinds.push([n.type, n.kind]); }
159
+ });
160
+ mapStyleOf(inst).setSubjects({ kinds, layers: state.projectLayers.map((l) => l.key) });
161
+ }
162
+
163
+ /** The nodes, their kinds and the theme's tokens for them are as they are now: the menu is drawn again (and the map reads the tokens of a kind it has not met) */
164
+ export function redrawLayers(inst) {
165
+ const mem = inst.slot('layers-draw', () => ({ drawing: false }));
166
+ mem.drawing = true;
167
+ try { syncMapSubjects(inst); } finally { mem.drawing = false; } // reading the tokens of a new kind may tell the style listener of the menu: this draw already has them
168
+ inst.emit('layers:redraw');
169
+ }
170
+
171
+ /** Whether the menu is being drawn in answer to the map's own style (it must not draw again for it) */
172
+ export const redrawing = (inst) => inst.slot('layers-draw', () => ({ drawing: false })).drawing;
173
+
174
+ /** Calls `fn` after a layer goes on or off (live.js starts or stops the live layer). Returns how to stop. */
175
+ export const onLayersChange = (inst, fn) => inst.on('layers', fn);
176
+
177
+ function changed(inst) {
178
+ inst.touchScene();
179
+ inst.emit('layers');
180
+ redrawLayers(inst);
181
+ inst.map.render();
182
+ inst.map.ensureFlowLoop();
183
+ }
184
+
185
+ /**
186
+ * 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
187
+ * 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:
188
+ * kept for the review only (`state.review.manual`, or `.step` when a playing scenario needs the layer: `scenario`), never in `activeLayers` or the browser.
189
+ */
190
+ export function setLayer(inst, key, on, { viewer = false, scenario = false } = {}) {
191
+ const { state } = inst;
192
+ const review = state.review && state.proposal ? state.review : null;
193
+ if (review) {
194
+ (scenario ? review.step : review.manual)[key] = on;
195
+ review.rev++;
196
+ } else {
197
+ state.activeLayers[key] = on;
198
+ if (viewer) { keep(inst, key, on); writeChanges(inst); }
199
+ }
200
+ changed(inst);
201
+ if (viewer) {
202
+ const { layers, overlays } = layerRows(inst);
203
+ const layer = [...layers, ...overlays].find((l) => l.key === key);
204
+ const n = state.nodes.filter((x) => inst.map.isNodeVisible(x)).length;
205
+ announce(inst, `${layer ? layer.label : key} ${on ? 'on' : 'off'}${review ? ' for this review' : ''}. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
206
+ }
207
+ }
208
+
209
+ /** Flips a layer (what a click on its row does); see `setLayer` */
210
+ export function toggleLayer(inst, key, opts = {}) {
211
+ setLayer(inst, key, !layerOn(inst.state, key), opts);
212
+ }
213
+
214
+ /** 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 */
215
+ export function toggleAllLayers(inst, on, { viewer = false } = {}) {
216
+ const { state } = inst;
217
+ const { layers } = layerRows(inst);
218
+ 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)]);
219
+ const review = state.review && state.proposal ? state.review : null;
220
+ if (review) { keys.forEach((k) => { review.manual[k] = on; }); review.rev++; } else {
221
+ keys.forEach((k) => { state.activeLayers[k] = on; if (viewer) keep(inst, k, on); });
222
+ if (viewer) writeChanges(inst);
223
+ }
224
+ changed(inst);
225
+ if (viewer) {
226
+ const n = state.nodes.filter((x) => inst.map.isNodeVisible(x)).length;
227
+ announce(inst, `${on ? 'All' : 'No'} layers on${review ? ' for this review' : ''}. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
228
+ }
229
+ }
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // The review narrows the map to the change (issue #232)
233
+ // 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.
234
+ // ---------------------------------------------------------------------------
235
+
236
+ /** A proposal is opened: a fresh review ("Show the whole map" off, nothing turned on by hand yet), also when one was already open */
237
+ export function beginReview(inst) {
238
+ inst.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)
239
+ }
240
+
241
+ /** The proposal is closed: the viewer's own layers are what is drawn again, exactly as they were */
242
+ export function endReview(inst) {
243
+ if (!inst.state.review) return;
244
+ inst.state.review = null;
245
+ inst.touchScene();
246
+ redrawLayers(inst);
247
+ }
248
+
249
+ /** 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 */
250
+ export function reviewLayersLine(inst) {
251
+ const { state } = inst;
252
+ if (!state.review || !state.proposal || state.review.whole) return '';
253
+ const { layers } = layerRows(inst);
254
+ const held = new Set(state.nodes.map((n) => rowKeyOf(state, n))); // a layer that holds no node has nothing to hide
255
+ if (!layers.some((l) => held.has(l.key) && reviewHides(state, l.key))) return '';
256
+ const on = layers.filter((l) => isOn(inst, l.key)).length;
257
+ return `Showing ${on} of ${layers.length} layers: the ones this proposal changes.`;
258
+ }
259
+
260
+ /** "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 */
261
+ export function setWholeMap(inst, on) {
262
+ const { state } = inst;
263
+ const review = state.review && state.proposal ? state.review : null;
264
+ if (!review || review.whole === on) return;
265
+ review.whole = on;
266
+ review.rev++;
267
+ changed(inst);
268
+ announce(inst, on ? 'Showing the whole map.' : (reviewLayersLine(inst) || 'Showing the change: the rest of the map is greyed.'));
269
+ }
270
+
271
+ /** A scenario ended: the layers it turned on for the review go off again (the focused view comes back). True when there were any */
272
+ export function clearStepLayers(inst) {
273
+ const { review } = inst.state;
274
+ if (!review || !Object.keys(review.step).length) return false;
275
+ review.step = {};
276
+ review.rev++;
277
+ inst.touchScene();
278
+ redrawLayers(inst);
279
+ return true;
280
+ }
@@ -0,0 +1,378 @@
1
+ /**
2
+ * @module explorer/engine/layout
3
+ *
4
+ * Where every node sits. topology.json stores no x/y, so this derives them:
5
+ * - the orbital layout of the whole map (data at the core, clusters that cannot overlap), and
6
+ * - the lane layout of the data-flow preset (one column per tier, left to right).
7
+ * Positions are exact: no physics pass, so the same topology always draws the same map.
8
+ * Plus the freeform mode, where the owner drags nodes and the positions are remembered.
9
+ *
10
+ * Every function takes the instance (instance.js) first, and reads and writes its state: two maps on a page lay out apart.
11
+ */
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // Degree centrality: hubs a little larger, leaves a little smaller
15
+ // ---------------------------------------------------------------------------
16
+ export function computeDegreeCentrality(inst) {
17
+ const { state } = inst;
18
+ inst.touchScene(); // node radii change
19
+ const degreeMap = {};
20
+ state.nodes.forEach((n) => {
21
+ degreeMap[n.id] = 0;
22
+ if (n.baseR === undefined) n.baseR = n.r;
23
+ });
24
+ state.edges.forEach((e) => {
25
+ if (degreeMap[e.from] !== undefined) degreeMap[e.from]++;
26
+ if (degreeMap[e.to] !== undefined) degreeMap[e.to]++;
27
+ });
28
+ state.nodes.forEach((n) => {
29
+ const d = degreeMap[n.id] || 0;
30
+ n.degree = d;
31
+ // Leaf nodes slightly smaller (-3px), hub nodes slightly larger (up to +7px)
32
+ const delta = Math.max(-3, Math.min(7, (Math.sqrt(d) - 1.4) * 2.2));
33
+ n.r = Math.max(12, Math.round(n.baseR + delta));
34
+ n.scaleDelta = delta;
35
+ });
36
+ }
37
+
38
+ const FONT = '"Segoe UI", -apple-system, sans-serif';
39
+
40
+ /** The width a node's label takes on the canvas */
41
+ export function labelWidth(inst, node) {
42
+ const { ctx } = inst.state;
43
+ ctx.save();
44
+ ctx.font = `${node.type === 'root' || node.type === 'app' ? 'bold 12px' : '11px'} ${FONT}`;
45
+ const w = ctx.measureText(node.label || '').width;
46
+ ctx.restore();
47
+ return w;
48
+ }
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // Orbital layout
52
+ // 1. The data tier (stores, tables, ROM stages) rings the root, grouped by kind.
53
+ // 2. A hub's children fill concentric rings around it; the spacing along a ring
54
+ // comes from that cluster's own label widths, so labels never collide.
55
+ // 3. Hubs with children are packed round the core, largest first (ties by label), each in the free place nearest it,
56
+ // searched from the top clockwise (spec 0008 D1); a cluster's place depends only on the ones placed before it.
57
+ // 4. Childless hubs (leaf apps, tools, packages) sit on an outer ring.
58
+ // ---------------------------------------------------------------------------
59
+ const DATA_TYPES = ['store', 'table', 'rom'];
60
+ const CHILD_TYPE_ORDER = ['core', 'atom', 'molecule', 'token', 'page', 'service', 'external', 'stack', 'table', 'store', 'tool', 'app', 'pkg'];
61
+
62
+ /** Concentric rings of `items` around (0, 0): returns the offsets and the radii used */
63
+ function ringPack(items, { first = 110, gap = 76, spacing = 90 } = {}) {
64
+ const offsets = [];
65
+ const radii = [];
66
+ let i = 0, ring = 0;
67
+ while (i < items.length) {
68
+ const r = first + ring * gap;
69
+ const capacity = Math.max(1, Math.floor((2 * Math.PI * r) / spacing));
70
+ const count = Math.min(capacity, items.length - i);
71
+ // Keep the slot under the hub free for the hub's label: turn the ring half a step if one lands there
72
+ const landsBelow = (s) => Array.from({ length: count }, (_, j) => -Math.PI / 2 + s + (j / count) * Math.PI * 2)
73
+ .some((a) => Math.abs(Math.atan2(Math.sin(a - Math.PI / 2), Math.cos(a - Math.PI / 2))) < 0.35);
74
+ let shift = ring % 2 ? Math.PI / count : 0;
75
+ if (landsBelow(shift)) shift += Math.PI / count;
76
+ for (let j = 0; j < count; j++) {
77
+ const a = -Math.PI / 2 + shift + (j / count) * Math.PI * 2;
78
+ offsets.push({ x: Math.cos(a) * r, y: Math.sin(a) * r });
79
+ }
80
+ radii.push(r);
81
+ i += count;
82
+ ring++;
83
+ }
84
+ return { offsets, radii };
85
+ }
86
+
87
+ /**
88
+ * A cluster's whole pack: `children` in rings around the centre, and a child that has children of its own (a store
89
+ * owning 46 outside services) gets its own rings, placed on an outer ring of this cluster with room for them.
90
+ * `kidsOf(node)` says who hangs under a node. Returns `{ children, offsets, radii, subs, extent }`: `subs[i]` is the
91
+ * child i's own pack (or null), `extent` how far the whole thing reaches from the centre.
92
+ */
93
+ function packTree(children, kidsOf, spacingOf, byOrder, seen = new Set()) {
94
+ const withSub = [];
95
+ const plain = [];
96
+ children.forEach((c) => {
97
+ const kids = seen.has(c.id) ? [] : kidsOf(c);
98
+ if (!kids.length) { plain.push(c); return; }
99
+ seen.add(c.id);
100
+ const sub = packTree(kids.sort(byOrder), kidsOf, spacingOf, byOrder, seen);
101
+ withSub.push({ c, sub, fp: sub.extent });
102
+ });
103
+ withSub.sort((a, b) => b.fp - a.fp);
104
+ const pack = ringPack(plain, { spacing: spacingOf(children) });
105
+ const out = {
106
+ children: [...plain], offsets: [...pack.offsets], radii: pack.radii, subs: plain.map(() => null),
107
+ extent: pack.radii.length ? pack.radii[pack.radii.length - 1] + 40 : 0,
108
+ };
109
+ if (withSub.length) {
110
+ const lastR = pack.radii.length ? pack.radii[pack.radii.length - 1] : 0;
111
+ const fpMax = withSub[0].fp;
112
+ const arc = withSub.reduce((sum, w) => sum + 2 * w.fp + 30, 0);
113
+ // Each takes arc in proportion to its size; two of them are a chord apart, not an arc, so the ring is as wide as
114
+ // the closest pair needs (for three or more large ones, more than the arc says)
115
+ const mids = [];
116
+ let a = -Math.PI / 2;
117
+ withSub.forEach((w) => { const share = ((2 * w.fp + 30) / arc) * Math.PI * 2; mids.push(a + share / 2); a += share; });
118
+ let r = Math.max(110, lastR + fpMax + 40, arc / (2 * Math.PI));
119
+ for (let i = 0; i < withSub.length; i++) {
120
+ for (let j = i + 1; j < withSub.length; j++) {
121
+ const half = Math.sin(Math.abs(mids[j] - mids[i]) / 2);
122
+ if (half > 1e-6) r = Math.max(r, (withSub[i].fp + withSub[j].fp + 30) / (2 * half));
123
+ }
124
+ }
125
+ withSub.forEach((w, i) => {
126
+ out.children.push(w.c);
127
+ out.offsets.push({ x: Math.cos(mids[i]) * r, y: Math.sin(mids[i]) * r });
128
+ out.subs.push(w.sub);
129
+ });
130
+ out.bigRadius = r;
131
+ out.extent = Math.max(out.extent, r + fpMax);
132
+ }
133
+ return out;
134
+ }
135
+
136
+ /** Puts a pack's children (and theirs) around (ox, oy); a child's own rings are added to `clusters` */
137
+ function placePack(pack, ox, oy, clusters) {
138
+ pack.children.forEach((c, i) => {
139
+ c.x = ox + pack.offsets[i].x;
140
+ c.y = oy + pack.offsets[i].y;
141
+ const sub = pack.subs[i];
142
+ if (sub) {
143
+ clusters.push({ x: c.x, y: c.y, radii: sub.radii });
144
+ placePack(sub, c.x, c.y, clusters);
145
+ }
146
+ });
147
+ }
148
+
149
+
150
+ /**
151
+ * The free place nearest (0, 0) for a disc of radius `r` among `discs` (`{ x, y, r }`, each already holding its own gap),
152
+ * searched along rays from the top clockwise every STEP degrees: on each ray the nearest point where the disc touches
153
+ * none, and of the rays the nearest of all, the first in the search order winning a tie. Exact and deterministic.
154
+ */
155
+ const PACK_STEP_DEG = 2;
156
+ function nearestFreePlace(discs, r) {
157
+ let best = null;
158
+ for (let deg = 0; deg < 360; deg += PACK_STEP_DEG) {
159
+ const a = -Math.PI / 2 + (deg * Math.PI) / 180;
160
+ const dx = Math.cos(a), dy = Math.sin(a);
161
+ // The stretches of this ray where the disc would touch another (open intervals of the distance along it)
162
+ const blocked = [];
163
+ for (const d of discs) {
164
+ const along = dx * d.x + dy * d.y;
165
+ const reach = d.r + r;
166
+ const disc = along * along - (d.x * d.x + d.y * d.y) + reach * reach;
167
+ if (disc > 0) blocked.push([along - Math.sqrt(disc), along + Math.sqrt(disc)]);
168
+ }
169
+ blocked.sort((p, q) => p[0] - q[0]);
170
+ let at = 0;
171
+ for (const [lo, hi] of blocked) if (lo < at + 1e-9 && hi > at) at = hi;
172
+ if (!best || at < best.at - 1e-6) best = { at, x: dx * at, y: dy * at };
173
+ }
174
+ return best;
175
+ }
176
+
177
+ export function computeOrbitalLayout(inst) {
178
+ const { state } = inst;
179
+ inst.touchScene(); // positions and rings change
180
+ const { nodes, edges } = state;
181
+ if (nodes.length === 0) return;
182
+ state.rings = { rings: [], clusters: [] };
183
+ const LAYOUT = state.rings;
184
+
185
+ const ids = new Set(nodes.map((n) => n.id));
186
+ const parentMap = {};
187
+ edges.forEach((e) => {
188
+ // A parent that is not on the map (an edge a proposal left behind) is no parent: the node would sit on the centre
189
+ if (!e.dashed && !e.kind && e.from && e.to && ids.has(e.from) && e.from !== e.to && !parentMap[e.to]) parentMap[e.to] = e.from;
190
+ });
191
+ // Nor is a parent that is its own ancestor: the first node of a loop loses its parent, so the loop hangs from it
192
+ nodes.forEach((n) => {
193
+ const path = new Set([n.id]);
194
+ for (let p = parentMap[n.id]; p; p = parentMap[p]) {
195
+ if (path.has(p)) { delete parentMap[p]; break; }
196
+ path.add(p);
197
+ }
198
+ });
199
+
200
+ // topology.json stores no positions; a node the passes below do not place starts at the centre
201
+ nodes.forEach((n) => { n.x = 0; n.y = 0; });
202
+ const root = nodes.find((n) => n.id === 'root');
203
+ if (root) { root.x = 0; root.y = 0; }
204
+
205
+ const isData = (n) => DATA_TYPES.includes(n.type);
206
+ const hasChildren = new Set(Object.values(parentMap));
207
+ const parentsOfNonData = new Set(nodes.filter((k) => parentMap[k.id] && !isData(k)).map((k) => parentMap[k.id]));
208
+ // A data store with children of its own (tables, outside services) is a cluster like an app; other data rings the root
209
+ // and so is any node with no parent but children of its own (its children need somewhere to go)
210
+ const isHub = (n) => n.id !== 'root' && (isData(n)
211
+ ? hasChildren.has(n.id) && (!parentMap[n.id] || parentMap[n.id] === 'root')
212
+ && (n.type === 'store' || parentsOfNonData.has(n.id))
213
+ : parentMap[n.id] === 'root' || (!parentMap[n.id] && (hasChildren.has(n.id) || ['app', 'pkg', 'tool', 'external', 'stack'].includes(n.type))));
214
+ const firstHubs = new Set(nodes.filter(isHub).map((h) => h.id));
215
+ // A data node that would ring the root (its parent is no hub) but has other nodes under it is a cluster too: the
216
+ // data ring has no room for them
217
+ const hubs = nodes.filter((n) => firstHubs.has(n.id)
218
+ || (n.id !== 'root' && isData(n) && parentsOfNonData.has(n.id) && !firstHubs.has(parentMap[n.id])));
219
+ const hubIds = new Set(hubs.map((h) => h.id));
220
+ const typeRank = (n) => { const i = CHILD_TYPE_ORDER.indexOf(n.type); return i < 0 ? 99 : i; };
221
+ const byTypeThenLabel = (a, b) => typeRank(a) - typeRank(b) || String(a.label).localeCompare(String(b.label));
222
+
223
+ // 1. Data core
224
+ const data = nodes.filter((n) => isData(n) && !hubIds.has(n.id) && !hubIds.has(parentMap[n.id]))
225
+ .sort((a, b) => DATA_TYPES.indexOf(a.type) - DATA_TYPES.indexOf(b.type) || String(a.label).localeCompare(String(b.label)));
226
+ const dataSpacing = Math.max(110, ...data.map((n) => labelWidth(inst, n) + 24));
227
+ const dataR = Math.max(150, (data.length * dataSpacing) / (2 * Math.PI));
228
+ data.forEach((n, i) => {
229
+ const a = -Math.PI / 2 + (i / Math.max(1, data.length)) * Math.PI * 2;
230
+ n.x = Math.cos(a) * dataR;
231
+ n.y = Math.sin(a) * dataR;
232
+ });
233
+ const coreExtent = data.length ? dataR + 50 : 60;
234
+ if (data.length) LAYOUT.rings.push({ x: 0, y: 0, r: dataR });
235
+
236
+ // 2. Pack each hub's children (relative to the hub). A child with children of its own (a store that owns the
237
+ // outside services) gets rings of its own, and they count in the cluster's extent.
238
+ const kidsOf = (n) => (n.id === 'root' ? [] : nodes.filter((k) => parentMap[k.id] === n.id && !hubIds.has(k.id) && !isData(k) && k.id !== 'root'));
239
+ const spacingOf = (list) => Math.min(170, Math.max(84, ...list.map((c) => labelWidth(inst, c) * 0.8 + 26)));
240
+ const packs = new Map();
241
+ hubs.forEach((hub) => {
242
+ const children = nodes.filter((n) => parentMap[n.id] === hub.id && !hubIds.has(n.id)).sort(byTypeThenLabel);
243
+ if (!children.length) return;
244
+ packs.set(hub.id, packTree(children, kidsOf, spacingOf, byTypeThenLabel, new Set([hub.id])));
245
+ });
246
+
247
+ // 3. Hubs with children, packed (spec 0008 D1): the largest cluster first (ties by label) takes the free place nearest
248
+ // the core, searched from the top clockwise, GAP from every cluster already placed. No physics: the same map
249
+ // always draws the same, and a cluster's place depends only on the ones placed before it.
250
+ const GAP = 70;
251
+ const big = hubs.filter((h) => packs.has(h.id))
252
+ .sort((a, b) => packs.get(b.id).extent - packs.get(a.id).extent || String(a.label).localeCompare(String(b.label)));
253
+ const discs = [{ x: 0, y: 0, r: coreExtent }];
254
+ let hubReach = coreExtent; // how far from the centre the packed clusters reach
255
+ big.forEach((hub) => {
256
+ const pack = packs.get(hub.id);
257
+ const at = nearestFreePlace(discs, pack.extent + GAP / 2);
258
+ hub.x = at.x;
259
+ hub.y = at.y;
260
+ discs.push({ x: hub.x, y: hub.y, r: pack.extent + GAP / 2 });
261
+ hubReach = Math.max(hubReach, Math.hypot(hub.x, hub.y) + pack.extent);
262
+ LAYOUT.clusters.push({ x: hub.x, y: hub.y, radii: pack.radii });
263
+ placePack(pack, hub.x, hub.y, LAYOUT.clusters);
264
+ });
265
+
266
+ // 4. Childless hubs on an outer ring, and with them any node that has no parent and is none of the above
267
+ // (it would otherwise sit on the centre, under whatever else is there)
268
+ const homeless = nodes.filter((n) => n.id !== 'root' && !parentMap[n.id] && !isData(n) && !hubIds.has(n.id));
269
+ const leaves = [...hubs.filter((h) => !packs.has(h.id)), ...homeless].sort(byTypeThenLabel);
270
+ const leafSpacing = Math.max(120, ...leaves.map((n) => labelWidth(inst, n) + 30));
271
+ const leafR = Math.max(hubReach + 90, (leaves.length * leafSpacing) / (2 * Math.PI));
272
+ leaves.forEach((n, i) => {
273
+ const a = -Math.PI / 2 + (i / Math.max(1, leaves.length)) * Math.PI * 2;
274
+ n.x = Math.cos(a) * leafR;
275
+ n.y = Math.sin(a) * leafR;
276
+ });
277
+ if (leaves.length) LAYOUT.rings.push({ x: 0, y: 0, r: leafR });
278
+
279
+ // Anything still on the centre is a child of a node the passes above did not pack (a child of a data node on the
280
+ // core ring, say): it goes in rings around its parent, with its own children in rings around it, never on one point
281
+ const placedAt = (n) => n.id === 'root' || n.x !== 0 || n.y !== 0;
282
+ const stuckUnder = new Map();
283
+ nodes.forEach((n) => {
284
+ const pid = parentMap[n.id];
285
+ if (placedAt(n) || !pid) return;
286
+ (stuckUnder.get(pid) || stuckUnder.set(pid, []).get(pid)).push(n);
287
+ });
288
+ const byId = new Map(nodes.map((n) => [n.id, n]));
289
+ stuckUnder.forEach((list, pid) => {
290
+ const p = byId.get(pid);
291
+ if (!p || !placedAt(p)) return; // its parent is stuck too: it is placed with it, in the parent's pack
292
+ if (list.every(placedAt)) return; // placed already, in a pack higher up
293
+ const pack = packTree(list.sort(byTypeThenLabel), kidsOf, spacingOf, byTypeThenLabel, new Set([pid]));
294
+ LAYOUT.clusters.push({ x: p.x, y: p.y, radii: pack.radii });
295
+ placePack(pack, p.x, p.y, LAYOUT.clusters);
296
+ });
297
+ }
298
+
299
+ // ---------------------------------------------------------------------------
300
+ // Lane layout: the data-flow preset, one column per tier, left to right
301
+ // A tier with many nodes (tables, services) fills several sub-columns top to bottom.
302
+ // ---------------------------------------------------------------------------
303
+ const LANE_ROW = 50; // vertical distance between two nodes in a column
304
+ const LANE_GAP = 110; // between tiers
305
+ const LANE_MAX_ROWS = 15; // a tall tier wraps into another sub-column
306
+
307
+ /**
308
+ * Places the nodes of `flow.tiers` and sets `flow.headers` (one title per tier, with the x range
309
+ * it spans). Tiers are `{ key, title, nodes }`; the nodes get their x and y.
310
+ */
311
+ export function computeLaneLayout(inst, flow) {
312
+ inst.touchScene(); // positions and headers change
313
+ let x = 0;
314
+ flow.headers = [];
315
+ const placed = [];
316
+ flow.tiers.forEach((tier) => {
317
+ if (!tier.nodes.length) return;
318
+ const subCols = Math.ceil(tier.nodes.length / LANE_MAX_ROWS);
319
+ const rows = Math.ceil(tier.nodes.length / subCols);
320
+ const colWidth = Math.max(70, ...tier.nodes.map((n) => labelWidth(inst, n) + 30));
321
+ const start = x;
322
+ tier.nodes.forEach((n, i) => {
323
+ const col = Math.floor(i / rows);
324
+ const row = i % rows;
325
+ n.x = start + col * colWidth + colWidth / 2;
326
+ n.y = (row - (rows - 1) / 2) * LANE_ROW;
327
+ placed.push(n);
328
+ });
329
+ const span = subCols * colWidth;
330
+ flow.headers.push({ title: tier.title, note: tier.note, x: start + span / 2, left: start, right: start + span, rows });
331
+ x += span + LANE_GAP;
332
+ });
333
+ // Where the tier titles sit: just above the tallest tier
334
+ flow.top = -((Math.max(1, ...flow.headers.map((h) => h.rows)) - 1) / 2) * LANE_ROW - 70;
335
+ // Centre the whole thing on x = 0
336
+ const shift = (x - LANE_GAP) / 2;
337
+ placed.forEach((n) => { n.x -= shift; });
338
+ flow.headers.forEach((h) => { h.x -= shift; h.left -= shift; h.right -= shift; });
339
+ }
340
+
341
+ // ---------------------------------------------------------------------------
342
+ // Freeform mode: dragged positions, remembered between visits
343
+ // ---------------------------------------------------------------------------
344
+ export const STORAGE_KEY = 'cornfield-freeform-positions';
345
+
346
+ export function loadFreeformPositions(inst) {
347
+ try {
348
+ const saved = inst.store.get(STORAGE_KEY);
349
+ if (saved) inst.state.freeformPositions = JSON.parse(saved);
350
+ } catch { /* unreadable: start with none */ }
351
+ }
352
+
353
+ export function saveFreeformPositions(inst) {
354
+ inst.store.set(STORAGE_KEY, JSON.stringify(inst.state.freeformPositions));
355
+ }
356
+
357
+ export function clearFreeformPositions(inst) {
358
+ inst.state.freeformPositions = {};
359
+ inst.store.remove(STORAGE_KEY);
360
+ }
361
+
362
+ /** Puts every remembered position on its node; false when there were none */
363
+ export function applyFreeformPositions(inst) {
364
+ const { state } = inst;
365
+ inst.touchScene(); // positions change
366
+ let applied = 0;
367
+ state.nodes.forEach((n) => {
368
+ const p = state.freeformPositions[n.id];
369
+ if (p) { n.x = p.x; n.y = p.y; applied++; }
370
+ });
371
+ return applied > 0;
372
+ }
373
+
374
+ /** The orbit positions, with the owner's dragged ones on top when freeform is on */
375
+ export function layoutOrbit(inst) {
376
+ computeOrbitalLayout(inst);
377
+ if (inst.state.isFreeform) applyFreeformPositions(inst);
378
+ }