cornfield 0.50.0 → 0.51.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 (67) hide show
  1. package/explorer/camera-frame.js +82 -0
  2. package/explorer/camera.js +7 -73
  3. package/explorer/check-model.js +3 -44
  4. package/explorer/cloud-model.js +2 -101
  5. package/explorer/cloud-panel.js +107 -0
  6. package/explorer/css/review.css +2 -0
  7. package/explorer/engine/connection.js +4 -1
  8. package/explorer/engine/map-rect.js +97 -0
  9. package/explorer/engine/player.js +2 -1
  10. package/explorer/engine/proposal.js +28 -7
  11. package/explorer/engine/server-load.js +64 -0
  12. package/explorer/engine/sheets.js +4 -86
  13. package/explorer/engine/source-address.js +58 -0
  14. package/explorer/engine/source.js +16 -45
  15. package/explorer/engine/theme-sheet.js +23 -1
  16. package/explorer/engine/topology.js +1 -1
  17. package/explorer/focus-room.js +1 -7
  18. package/explorer/focusables.js +1 -1
  19. package/explorer/forge-panel.js +36 -2630
  20. package/explorer/index.html +15 -147
  21. package/explorer/instance-state.js +0 -7
  22. package/explorer/instance.js +19 -2
  23. package/explorer/layer-model.js +1 -1
  24. package/explorer/outage-model.js +6 -76
  25. package/explorer/outage-scenario.js +83 -0
  26. package/explorer/page-pieces.js +21 -2
  27. package/explorer/page.js +3 -3
  28. package/explorer/panels.js +1 -5
  29. package/explorer/pieces/layers.js +1 -0
  30. package/explorer/pieces/node-panel.js +19 -8
  31. package/explorer/pieces/proposal.js +9 -0
  32. package/explorer/pieces/review-source.js +84 -0
  33. package/explorer/pieces/review.js +145 -12
  34. package/explorer/pieces/scope.js +23 -54
  35. package/explorer/pieces/status.js +5 -1
  36. package/explorer/pieces/work-agent.js +211 -0
  37. package/explorer/pieces/work-common.js +88 -0
  38. package/explorer/pieces/work-confirm.js +169 -0
  39. package/explorer/pieces/work-data.js +178 -0
  40. package/explorer/pieces/work-deploys.js +104 -0
  41. package/explorer/pieces/work-events.js +285 -0
  42. package/explorer/pieces/work-issues.js +43 -0
  43. package/explorer/pieces/work-markup.js +155 -0
  44. package/explorer/pieces/work-notes.js +177 -0
  45. package/explorer/pieces/work-paint.js +312 -0
  46. package/explorer/pieces/work-prs.js +253 -0
  47. package/explorer/pieces/work-runs.js +387 -0
  48. package/explorer/pieces/work-specs.js +71 -0
  49. package/explorer/pieces/work-threads.js +309 -0
  50. package/explorer/pieces/work.js +285 -0
  51. package/explorer/proposal-marks.js +220 -0
  52. package/explorer/proposal-model.js +23 -211
  53. package/explorer/proposal.js +1 -2
  54. package/explorer/runs-map.js +108 -103
  55. package/explorer/runs-view.js +8 -6
  56. package/explorer/scenario.js +2 -1
  57. package/explorer/scene.js +2 -2
  58. package/explorer/selection-model.js +2 -42
  59. package/explorer/selection-view.js +1 -1
  60. package/explorer/selection-words.js +52 -0
  61. package/explorer/strings.js +1 -1
  62. package/explorer/verdict-paint.js +51 -0
  63. package/explorer/waiting-model.js +12 -12
  64. package/explorer/waiting-view.js +6 -6
  65. package/package.json +1 -1
  66. package/explorer/feedback.js +0 -15
  67. package/explorer/waiting-line.js +0 -14
@@ -0,0 +1,285 @@
1
+ /**
2
+ * @module explorer/pieces/work
3
+ *
4
+ * The Work panel as a piece on the instance (spec 0011 D2 and D3; CF-07, CF-42, spec 0001 section 4, spec 0010): the Work button with its badge, the
5
+ * panel with its tabs (Specs, PRs, Issues, Threads, Runs, Deploys, and Release notes one level down on PRs), the two dialogs it opens (the confirm
6
+ * step and Start an agent) and the layer over the map that marks the nodes an open run is changing. What the panel shows, asks and does is the
7
+ * parts' (work-*.js, one module each); this file makes them for one mount, wires them to the instance, and ends them.
8
+ *
9
+ * mount(root, inst, { slots, config, clock }) -> { update, destroy, elements, ... }
10
+ * slots where cornfield's page leaves the places (`<!--corn-piece:work/button-->`, `work/panel`, `work/overlay`, `work/dialogs`); a host
11
+ * that gives none gets the four at the end of `root`
12
+ * config what `/cornfield/config.json` said: with no `forge`, or nobody signed in (`signIn`), the button and the panel stay hidden
13
+ * clock `() => ms`, for the times shown (tests)
14
+ * update({ config, clock }) the config arrived (or changed): the panel starts, or does not. `isOn()` says which.
15
+ * destroy() every listener, timer and poll ends, the elements go, an answer still on its way is not heard
16
+ *
17
+ * What it asks of the server (all through `credentialed(inst)`, served paths only; server/embed.js `ROUTES` and docs/embedding.md say which a listed origin
18
+ * may reach: of these only GET /proposals, GET /api/forge/pulls/<n> and POST /api/forge/pulls/<n>/landing/cancel, which the proposal bar uses too):
19
+ * GET /api/forge/{pulls,issues,threads}?state=<open|closed|all>&limit=100 GET /api/forge/deploys?limit=100 GET /api/forge/work
20
+ * GET /api/forge/pulls/<n> GET /api/forge/pulls/<n>/landing (approveLands) POST /api/forge/pulls/<n>/landing/cancel {}
21
+ * POST /api/forge/pulls/<n>/merge {sha, ...} POST /api/forge/pulls/<n>/rerun {sha, check} GET /api/forge/pulls/<n>/build?slug=<slug> POST /api/forge/pulls/<n>/build {digest, ...}
22
+ * GET /api/forge/issues/<n> GET /api/forge/issues/<n>/spec POST /api/forge/issues/<n>/spec {digest, ...}
23
+ * GET /api/forge/threads/<n> POST /api/forge/threads {title, body}
24
+ * GET /api/forge/release-notes[?since=<tag>] POST /api/forge/release-drafts {tag, since?}
25
+ * GET /api/agent-runs[?follow=1] POST /api/agent-runs {kind, refs, brief, profile?, limits?, force?, retryOf?} GET /api/agent-runs/<id>/brief
26
+ * POST /api/agent-runs/<id>/stop {} POST /api/agent-runs/<id>/answer {action: 'continue'|'stop'|'reply', text?}
27
+ * (and GET /proposals, which the engine reads for the Specs tab: engine/proposal.js)
28
+ *
29
+ * Events and asks (instance.js lists them): hears `work:open-specs` (ask, answers true), `forge:can-start` (ask) and `forge:start`, `thread:open`,
30
+ * `thread:start`, `threads:ensure`, `threads:index` (ask), `proposal:bar`, `decision`, `work:answer`, `work:on` (ask), `scene`; says `work:waiting {total}`,
31
+ * `work:available {on}`, `proposal:waiting`, `proposal:waiting-reset`, `runs:map {active}`, `threads:changed`, `announce`.
32
+ */
33
+
34
+ import { place, scopeOf } from '../engine/piece.js';
35
+ import { markup } from './work-markup.js';
36
+ import { freshUi, RUNS_POLL_MS, SPECS_POLL_MS } from './work-common.js';
37
+ import { announce } from '../engine/keyboard.js';
38
+ import { t } from '../engine/strings.js';
39
+ import { isPhone, registerSheet, unregisterSheet, expandSheet, collapseSheet, showSheet, refreshStubs } from '../engine/sheets.js';
40
+ import { sayResult, clearResult, resultOf, showResultIn } from '../engine/feedback.js';
41
+ import { selectNode } from '../engine/selection.js';
42
+ import { toggleLayer } from '../engine/layers.js';
43
+ import { notSentWords } from '../engine/connection.js';
44
+ import * as P from '../engine/proposal.js';
45
+ import { isNodeVisible } from '../scene.js';
46
+ import { revealInStrip } from '../focus-room.js';
47
+ import { createRunsMap } from '../runs-map.js';
48
+ import { workButtonName } from '../waiting-model.js';
49
+ import { install as installData } from './work-data.js';
50
+ import { install as installSpecs } from './work-specs.js';
51
+ import { install as installPrs } from './work-prs.js';
52
+ import { install as installIssues } from './work-issues.js';
53
+ import { install as installThreads } from './work-threads.js';
54
+ import { install as installRuns } from './work-runs.js';
55
+ import { install as installDeploys } from './work-deploys.js';
56
+ import { install as installNotes } from './work-notes.js';
57
+ import { install as installConfirm } from './work-confirm.js';
58
+ import { install as installAgent } from './work-agent.js';
59
+ import { install as installPaint } from './work-paint.js';
60
+ import { install as installEvents } from './work-events.js';
61
+
62
+ export { markup, RUNS_POLL_MS, SPECS_POLL_MS };
63
+
64
+ /**
65
+ * @param {ParentNode} root where the elements go when the host names no place
66
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst
67
+ * @param {{ slots?: Record<string, Node | null>, config?: object | null, clock?: () => number }} [options]
68
+ */
69
+ export function mount(root, inst, options = {}) {
70
+ const scope = scopeOf(inst);
71
+ const mk = markup();
72
+ const slots = options.slots || {};
73
+ const made = [
74
+ ...place(inst, root, mk.button, slots, 'button'),
75
+ ...place(inst, root, mk.panel, slots, 'panel'),
76
+ ...place(inst, root, mk.overlay, slots, 'overlay'),
77
+ ...place(inst, root, mk.dialogs, slots, 'dialogs'),
78
+ ];
79
+ const panelEl = made.find((el) => el.id === 'forge-panel');
80
+ scope.keepParts(...made);
81
+
82
+ // -- what the parts share: the state of this one panel, and the few things that are not functions ---------------------------------------
83
+ /** @type {Record<string, any>} */
84
+ const m = {
85
+ runsTimer: 0, threadToken: 0, indexToken: 0, indexLoading: false, indexCache: null, listToken: 0, pullToken: 0, notesToken: 0,
86
+ searchTimer: null, now: options.clock || (() => Date.now()), pageAway: false, specsTimer: 0, specsReading: false, primed: new Set(),
87
+ shownKey: '', shownKind: '', returnTo: null, openerEl: null, merged: { entries: null, items: [] }, redrawRuns: new Set(), agentTrap: null, confirmTrap: null,
88
+ };
89
+ const timers = new Set();
90
+ /** Timers that end with the piece, and do nothing once it has */
91
+ const setT = (f, ms) => { const id = setTimeout(() => { timers.delete(id); if (!ctx.dead) f(); }, ms); timers.add(id); return id; };
92
+ const clearT = (id) => { clearTimeout(id); timers.delete(id); };
93
+ scope.own(() => { for (const id of timers) clearTimeout(id); timers.clear(); });
94
+ const runsMap = createRunsMap(inst);
95
+
96
+ /** Each of the instance's modules, bound to this instance: the parts call these and never reach a page */
97
+ const h = {
98
+ announce: (text) => announce(inst, text),
99
+ t: (key) => t(inst, key),
100
+ isPhone: () => isPhone(inst),
101
+ registerSheet: (id, el, opts) => registerSheet(inst, id, el, opts),
102
+ expandSheet: (id) => expandSheet(inst, id),
103
+ collapseSheet: (id) => collapseSheet(inst, id),
104
+ showSheet: (id) => showSheet(inst, id),
105
+ refreshStubs: () => refreshStubs(inst),
106
+ render: () => { if (inst.map) inst.map.render(); },
107
+ touchScene: () => inst.touchScene(),
108
+ nodeById: (id) => inst.state.nodes.find((n) => n.id === id),
109
+ isNodeVisible: (node) => (inst.map ? inst.map.isNodeVisible(node) : isNodeVisible(inst.state, node)),
110
+ selectNode: (node, opts) => selectNode(inst, node, opts),
111
+ repaintThreads: () => inst.emit('threads:changed'),
112
+ toggleLayer: (key) => toggleLayer(inst, key),
113
+ sayResult: (key, text, ok) => sayResult(inst, key, text, ok),
114
+ clearResult: (key) => clearResult(inst, key),
115
+ resultOf: (key) => resultOf(inst, key),
116
+ showResultIn: (el, key) => showResultIn(inst, el, key),
117
+ isOffline: () => inst.offline(),
118
+ notSentWords: (what) => notSentWords(inst, what),
119
+ proposalListing: () => P.proposalListing(inst),
120
+ onProposalListing: (f) => P.onProposalListing(inst, f),
121
+ loadProposalList: () => P.loadProposalList(inst),
122
+ paintWaitingLine: (run, key) => inst.emit('proposal:waiting', { run, key }),
123
+ setRunsOnMap: (runs) => runsMap.set(runs),
124
+ clearRunsOnMap: () => runsMap.clear(),
125
+ setT,
126
+ clearT,
127
+ /**
128
+ * Keeps the focus in an open dialog: `keep` hears every focus that lands inside the instance's root, and, when the root is not the document
129
+ * (an element or a shadow root in a host's page), every focus that lands outside the root too, which the root never hears, unless it landed in
130
+ * another open modal dialog (a second instance's: two traps never pull the focus between them). Returns how to stop.
131
+ */
132
+ trapFocus: (keep) => {
133
+ const offs = [scope.listen(ctx.root, 'focusin', keep)];
134
+ const inModal = (e) => (e.composedPath ? e.composedPath() : [e.target]).some((n) => n && n.nodeType === 1 && n.getAttribute('aria-modal') === 'true');
135
+ if (ctx.root !== inst.doc) offs.push(scope.own(inst.onPageFocus((e) => { if (!inst.active() && !inModal(e)) keep(e); })));
136
+ return () => offs.forEach((off) => off());
137
+ },
138
+ };
139
+ const ctx = { inst, ui: freshUi(), m, fn: {}, state: inst.state, root: inst.root || root, $: (id) => inst.el(id), scope, h, dead: false };
140
+ const { ui, fn } = ctx;
141
+ for (const install of [installData, installSpecs, installPrs, installIssues, installThreads, installRuns, installDeploys, installNotes, installConfirm, installAgent, installPaint, installEvents]) install(ctx);
142
+
143
+ // -- the panel starts once the config says there is a forge and somebody is signed in ---------------------------------------------------
144
+ let on = false;
145
+ // A piece mounted after the panel started asks rather than waits for `work:available` (the proposal piece hides its Proposals entry)
146
+ scope.on('work:on', () => on);
147
+
148
+ /** Starts the panel for `config`; with no forge in it, or nobody signed in, the button and the panel stay hidden. Returns whether it is on. */
149
+ function start(config) {
150
+ const panel = ctx.$('forge-panel');
151
+ if (!config || !config.forge || !config.signIn || !panel) return false;
152
+ ui.config = config;
153
+ const first = !on;
154
+ on = true;
155
+ for (const toggle of ctx.root.querySelectorAll('[data-action="toggle-forge"]')) toggle.hidden = false;
156
+ panel.hidden = false;
157
+ inst.emit('work:available', { on: true });
158
+ // `threads: false` in the config turns the tab off; a server that does not say has threads
159
+ const threadsOn = config.threads !== false;
160
+ const tab = panel.querySelector('[data-forge-kind="threads"]');
161
+ if (tab) tab.hidden = !threadsOn;
162
+ ui.threadsOn = threadsOn;
163
+ // On a phone Work is a sheet: it opens as a peek and displaces the node panel; folded to a stub it says its title and what waits on you (spec 0010 D7)
164
+ registerSheet(inst, 'forge', panel, {
165
+ stub: () => { const n = fn.waitingNow().total; return { title: h.t('issuesAndPrs'), badge: n ? String(n) : '', label: workButtonName(h.t('issuesAndPrs'), n, h.t) }; },
166
+ away: () => fn.closeForge({ restoreFocus: false }),
167
+ });
168
+ fn.paintFilters();
169
+ fn.paint();
170
+ // The map shows the open runs whether or not the panel is open: read them once now, and again now and then while any is open
171
+ if (config.agents && config.agents.runs) fn.loadRuns(false).then(() => { if (ui.kind === 'work') fn.paint(); }, () => {});
172
+ fn.readSpecsQuiet();
173
+ fn.syncSpecsPoll();
174
+ if (first) wire(panel);
175
+ return true;
176
+ }
177
+
178
+ /** The listeners, once: they end with the piece */
179
+ function wire(panel) {
180
+ // The specs part of what waits on you is read after a review is sent; the proposal bar says so when a run waits on the proposal it shows
181
+ scope.on('decision', ({ open }) => { if (open !== false) fn.readSpecsQuiet(); });
182
+ scope.on('proposal:bar', ({ open }) => fn.paintBarLine(open));
183
+ scope.on('work:answer', ({ run }) => { fn.answerFromBar(run); });
184
+ // A bad link's way on, and the node panel's "Start a run"
185
+ scope.on('work:open-specs', () => { fn.openForge({ tab: 'specs' }); return true; });
186
+ scope.on('forge:can-start', () => fn.canStartAgent());
187
+ scope.on('forge:start', ({ slug, returnTo }) => { fn.openProposalStart(slug, returnTo); });
188
+ // A node's panel lists the threads that mention it; a click there shows one in this panel
189
+ scope.on('threads:index', (nodeId) => (ui.config && ui.threadsOn ? { threads: fn.threadsFor(nodeId), forge: fn.forgeName(), start: true } : undefined));
190
+ scope.on('threads:ensure', () => { if (ui.config && ui.threadsOn) fn.ensureThreadsList(); });
191
+ scope.on('thread:open', ({ number }) => { if (ui.threadsOn) fn.openThread(number); });
192
+ scope.on('thread:start', ({ node }) => { if (ui.threadsOn && node) fn.startThread(node); });
193
+ // The map or the proposal changed the nodes: the lights follow them. The header's Proposals menu reads the same list: the Specs tab and its count follow
194
+ scope.on('scene', fn.onNodesChange);
195
+ scope.own(P.onProposalListing(inst, () => { fn.paintWaiting(); if (ui.open) fn.paint(); }));
196
+ scope.own(inst.onNetwork((offline) => { if (!offline) fn.readOnline(); })); // ends with the piece, not only with the instance
197
+ scope.own(inst.onPageHide(() => fn.onPageHide()));
198
+ scope.own(inst.onPageShow(() => fn.onPageShow()));
199
+ // Any `data-action="toggle-forge"` opens and closes the panel
200
+ scope.listen(ctx.root, 'click', (e) => {
201
+ const el = e.target.closest && e.target.closest('[data-action="toggle-forge"]');
202
+ if (!el) return;
203
+ m.openerEl = el;
204
+ fn.toggleForge();
205
+ });
206
+ // A control tabbed to inside the strip of tabs is brought fully into view, ring and all (focus-room.js)
207
+ scope.listen(ctx.root, 'focusin', (e) => { revealInStrip(e.target); });
208
+ const tabs = panel.querySelector('.hx-forge-tabs');
209
+ if (tabs) scope.listen(tabs, 'scroll', fn.paintTabsMore, { passive: true });
210
+ scope.own(inst.onResize(() => fn.paintTabsMore()));
211
+ // The strip's fade and the top's height follow their own size too: a phone's sheet expanding shows the tabs (they were not laid out in the
212
+ // peek), and a host's box resizes without the window doing so (F42)
213
+ const Observer = inst.win && inst.win.ResizeObserver;
214
+ const top = panel.querySelector('.hx-forge-top');
215
+ if (Observer && top && tabs) {
216
+ const seen = new Observer(() => { if (!ctx.dead) fn.paintTabsMore(); });
217
+ seen.observe(top);
218
+ seen.observe(tabs);
219
+ scope.own(() => seen.disconnect());
220
+ }
221
+ scope.listen(panel, 'click', fn.onClick);
222
+ scope.listen(panel, 'change', fn.onChange);
223
+ scope.listen(panel, 'input', fn.onInput);
224
+ scope.listen(panel, 'keydown', fn.onKey);
225
+ const agent = fn.agentEl();
226
+ if (agent) {
227
+ scope.listen(agent, 'click', fn.onAgentClick);
228
+ scope.listen(agent, 'keydown', fn.onAgentKey);
229
+ scope.listen(agent.querySelector('form'), 'submit', fn.submitAgent);
230
+ scope.listen(ctx.$('agent-profile'), 'change', fn.onAgentProfile);
231
+ }
232
+ const confirm = fn.confirmEl();
233
+ if (confirm) {
234
+ scope.listen(confirm, 'click', fn.onConfirmClick);
235
+ scope.listen(confirm, 'keydown', fn.onConfirmKey);
236
+ }
237
+ }
238
+
239
+ /** What the page tells the piece after it is mounted: the config (the panel starts), a clock */
240
+ function update(patch = {}) {
241
+ if (ctx.dead) return;
242
+ if (patch.clock) m.now = patch.clock;
243
+ if (patch.config !== undefined) start(patch.config);
244
+ }
245
+
246
+ function destroy() {
247
+ if (ctx.dead) return;
248
+ ctx.dead = true;
249
+ if (ui.confirm) fn.closeConfirm({ restoreFocus: false });
250
+ if (ui.agent) fn.closeAgent({ restoreFocus: false });
251
+ // What this panel lit and said goes with it
252
+ if (inst.state.forgeLit) inst.state.forgeLit = null;
253
+ runsMap.destroy();
254
+ inst.emit('proposal:waiting-reset');
255
+ inst.emit('work:waiting', { total: 0 });
256
+ if (on) inst.emit('work:available', { on: false }); // the account menu's Proposals entry is the way to the proposals again
257
+ try { unregisterSheet(inst, 'forge', false); } catch { /* it was never registered */ }
258
+ scope.destroy();
259
+ for (const el of made) el.remove();
260
+ }
261
+
262
+ if (options.config) update({ config: options.config });
263
+
264
+ return {
265
+ elements: made,
266
+ update,
267
+ destroy,
268
+ isOn: () => on,
269
+ isForgeOpen: () => ui.open,
270
+ openForge: (opts) => fn.openForge(opts),
271
+ closeForge: (opts) => fn.closeForge(opts),
272
+ toggleForge: () => fn.toggleForge(),
273
+ refreshForge: (opts) => fn.refreshForge(opts),
274
+ clearPull: () => fn.clearPull(),
275
+ clearDeploy: () => fn.clearDeploy(),
276
+ clearThread: () => fn.clearThread(),
277
+ selectDeploy: (id) => fn.selectDeploy(id),
278
+ openRunLink: (id) => fn.openRunLink(id),
279
+ openIssueLink: (n) => fn.openIssueLink(n),
280
+ openProposalStart: (slug, opener) => fn.openProposalStart(slug, opener),
281
+ canStartAgent: () => fn.canStartAgent(),
282
+ /** For tests: force reduced motion on or off for the runs' marks (null: follow the viewer's setting) */
283
+ setReducedMotion: (v) => runsMap.setReducedMotion(v),
284
+ };
285
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * @module explorer/proposal-marks
3
+ *
4
+ * What a proposal's marks do to the map (spec 0012 B2, TOPO-09), the part a map draws with: which nodes and edges each view shows
5
+ * (`showsNode`, `showsEdge`), the mark a scene carries (`markIn`), a changed item as it was (`beforeOf`), what Diff keeps bright and the camera
6
+ * fits (`touchedIds`), and where an added node sits (`placeAddedNodes`, `orderAddedLast`, `pinLanes`). Pure: no DOM, no state.
7
+ *
8
+ * proposal-model.js re-exports all of it, with the bar's, the panel's and the list's words, which only a review and cornfield's page use: a map
9
+ * alone (scene.js, engine/topology.js, layer-model.js) imports this module and so does not carry those (the components' size budget, spec 0011 D11).
10
+ */
11
+
12
+ /**
13
+ * What a marked item IS, under the mark it is drawn with: a what-if `edit` (whatif-model.js) is drawn in violet
14
+ * but is still an addition or a removal (`editOp`), and the views and the layout treat it as one.
15
+ * @returns {'none'|'added'|'changed'|'removed'}
16
+ */
17
+ export const kindOfMark = (item) => (item.mark === 'edit' ? item.editOp || 'none' : item.mark || 'none');
18
+
19
+ /** Whether an item carries a mark (any but none) */
20
+ export const hasMark = (item) => !!item && !!item.mark && item.mark !== 'none';
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // What each view shows
24
+ // ---------------------------------------------------------------------------
25
+
26
+ /** Is this node drawn in `view`? (`view` null = no proposal is open: everything is) */
27
+ export function showsNode(view, node) {
28
+ if (view === 'before') return kindOfMark(node) !== 'added';
29
+ if (view === 'after') return kindOfMark(node) !== 'removed';
30
+ return true;
31
+ }
32
+
33
+ /** Is this edge drawn in `view`? The same rule: Before hides what is added, After what is removed */
34
+ export function showsEdge(view, edge) {
35
+ return showsNode(view, edge);
36
+ }
37
+
38
+ /**
39
+ * The mark a scene carries in `view`: the proposal's own in Diff and none in Before and After; a
40
+ * what-if `edit` is the maintainer's own and shows in all three.
41
+ * @returns {'none'|'added'|'changed'|'removed'|'edit'}
42
+ */
43
+ export function markIn(view, item) {
44
+ const mark = item.mark || 'none';
45
+ if (mark === 'edit') return 'edit';
46
+ return view === 'diff' ? mark : 'none';
47
+ }
48
+
49
+ /**
50
+ * A changed node or edge as it was before the proposal: each field in `before` is put back
51
+ * (`null` there means the item did not have it, so it is dropped). Anything else comes back as it is.
52
+ */
53
+ export function beforeOf(item) {
54
+ if (item.mark !== 'changed' || !item.before) return item;
55
+ const out = { ...item };
56
+ for (const [field, value] of Object.entries(item.before)) {
57
+ if (value === null) delete out[field];
58
+ else out[field] = value;
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /**
64
+ * Which nodes a proposal touches, for dimming and for fitting the camera.
65
+ * - `touched`: nodes with a mark, and both ends of a marked edge: what Diff keeps bright
66
+ * - `near`: `touched` and what they connect to, except the children a touched node owns (a touched
67
+ * app would otherwise bring all its hundreds of pages): what the camera fits
68
+ * @param {{id:string, mark?:string}[]} nodes
69
+ * @param {{from:string, to:string, kind?:string, dashed?:boolean, mark?:string}[]} edges
70
+ */
71
+ export function touchedIds(nodes, edges) {
72
+ const touched = new Set();
73
+ for (const n of nodes) if (hasMark(n)) touched.add(n.id);
74
+ for (const e of edges) if (hasMark(e)) { touched.add(e.from); touched.add(e.to); }
75
+ const near = new Set(touched);
76
+ for (const e of edges) {
77
+ const owns = !e.kind && !e.dashed;
78
+ if (touched.has(e.from) && !(owns && !touched.has(e.to))) near.add(e.to);
79
+ if (touched.has(e.to)) near.add(e.from);
80
+ }
81
+ return { touched, near };
82
+ }
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // Where an added node sits
86
+ // ---------------------------------------------------------------------------
87
+
88
+ /** An ownership edge: a solid line with no kind (the parent → child link) */
89
+ const isOwnership = (e) => !e.kind && !e.dashed;
90
+
91
+ /**
92
+ * Gives every node marked `added` a position, next to the node it hangs off: its parent when it has
93
+ * one, else something it connects to, else a spot on a ring around the centre. Existing nodes never
94
+ * move: the base layout is pinned, which is why the Before view and the Diff view show the same
95
+ * picture. The spot is the first free one on widening rings around the anchor, starting on the side
96
+ * facing away from the centre, where the map has room. Writes `x` and `y`; touches nothing else.
97
+ * @param {{id:string, x:number, y:number, mark?:string}[]} nodes the applied nodes; the existing ones already have x and y
98
+ * @param {{from:string, to:string, kind?:string, dashed?:boolean}[]} edges
99
+ * @param {{gap?: number}} [opts] `gap`: the closest two nodes may sit (world units)
100
+ */
101
+ export function placeAddedNodes(nodes, edges, { gap = 74 } = {}) {
102
+ const byId = new Map(nodes.map((n) => [n.id, n]));
103
+ const placed = nodes.filter((n) => kindOfMark(n) !== 'added');
104
+ const added = nodes.filter((n) => kindOfMark(n) === 'added');
105
+ if (!added.length) return;
106
+ const done = new Set(placed.map((n) => n.id));
107
+
108
+ const anchorOf = (n) => {
109
+ const own = edges.find((e) => isOwnership(e) && e.to === n.id && byId.has(e.from));
110
+ if (own) return own.from;
111
+ const other = edges.find((e) => (e.from === n.id && byId.has(e.to)) || (e.to === n.id && byId.has(e.from)));
112
+ return other ? (other.from === n.id ? other.to : other.from) : null;
113
+ };
114
+
115
+ const free = (x, y) => placed.every((p) => Math.hypot(p.x - x, p.y - y) >= gap);
116
+ const put = (n, ax, ay) => {
117
+ const out = Math.atan2(ay, ax) || -Math.PI / 2; // away from the centre
118
+ const base = ax === 0 && ay === 0 ? -Math.PI / 2 : out;
119
+ let fallback = null;
120
+ for (let r = 96; r <= 96 + 40 * 12; r += 40) {
121
+ const steps = Math.max(8, Math.round((2 * Math.PI * r) / gap));
122
+ for (let k = 0; k < steps; k++) {
123
+ // 0, +1, -1, +2, -2 ... steps either side of the outward direction
124
+ const turn = Math.ceil(k / 2) * (k % 2 ? 1 : -1) * ((2 * Math.PI) / steps);
125
+ const x = ax + Math.cos(base + turn) * r;
126
+ const y = ay + Math.sin(base + turn) * r;
127
+ if (!fallback) fallback = { x, y };
128
+ if (free(x, y)) { n.x = x; n.y = y; return; }
129
+ }
130
+ }
131
+ n.x = fallback.x; n.y = fallback.y;
132
+ };
133
+
134
+ // Parents first: an added node can hang off another added node, in any order in the file
135
+ let pending = added.slice();
136
+ for (let pass = 0; pass <= added.length && pending.length; pass++) {
137
+ const next = [];
138
+ for (const n of pending) {
139
+ const anchor = byId.get(anchorOf(n));
140
+ if (anchor && done.has(anchor.id)) {
141
+ put(n, anchor.x, anchor.y);
142
+ placed.push(n);
143
+ done.add(n.id);
144
+ } else {
145
+ next.push(n); // its anchor is another added node not placed yet, or it has none (settled below)
146
+ }
147
+ }
148
+ if (next.length === pending.length) break;
149
+ pending = next;
150
+ }
151
+ // No anchor, or an anchor that never got a place: a spot beside the centre
152
+ for (const n of pending) {
153
+ put(n, 0, 0);
154
+ placed.push(n);
155
+ }
156
+ }
157
+
158
+ /**
159
+ * The data-flow lanes fill a column in order; an added node goes last in its column, so the nodes
160
+ * that were there keep their rows. Reorders each tier's `nodes` in place, stably.
161
+ * @param {{tiers: {nodes: {mark?:string}[]}[]}|null} flow `buildDataFlow` result
162
+ */
163
+ export function orderAddedLast(flow) {
164
+ if (!flow) return;
165
+ for (const tier of flow.tiers) {
166
+ tier.nodes = [...tier.nodes.filter((n) => kindOfMark(n) !== 'added'), ...tier.nodes.filter((n) => kindOfMark(n) === 'added')];
167
+ }
168
+ }
169
+
170
+ /** The distance between two rows of a lane (layout.js `LANE_ROW`) */
171
+ const LANE_ROW = 50;
172
+
173
+ /**
174
+ * The data-flow lanes while a proposal is open: the base map's lane layout is pinned and the added
175
+ * nodes take free cells of their lane, so no node that was there moves (laying the lanes out again
176
+ * would re-flow a whole lane when one node more tips it into another row). An added node goes in the
177
+ * free cells at the foot of its lane's last column, then in new rows below it; `flow.top` moves up
178
+ * so the lane bands still cover them.
179
+ *
180
+ * Writes `x`, `y`, `r` of each existing node from `baseFlow`'s node of the same id, `x` and `y` of each
181
+ * added one, and `flow.headers` / `flow.top`. `flow` is the applied map's flow (`buildDataFlow` over
182
+ * the applied nodes, added nodes last in their tier), `baseFlow` the base map's, already laid out.
183
+ * @param {{tiers: {key:string, nodes: object[]}[], headers?: object[], top?: number}} flow
184
+ * @param {{tiers: {key:string, nodes: object[]}[], headers: object[], top: number}} baseFlow
185
+ * @returns {boolean} false when the lanes cannot be pinned (a tier has nodes now that had none, so it has no column
186
+ * to join): the caller lays the lanes out afresh
187
+ */
188
+ export function pinLanes(flow, baseFlow) {
189
+ const baseTier = new Map(baseFlow.tiers.map((t) => [t.key, t]));
190
+ if (flow.tiers.some((t) => t.nodes.length && !baseTier.get(t.key)?.nodes.length)) return false;
191
+
192
+ // `headers` has one entry per tier that has nodes, in tier order
193
+ const headerOf = new Map(baseFlow.tiers.filter((t) => t.nodes.length).map((t, i) => [t.key, baseFlow.headers[i]]));
194
+ const was = new Map(baseFlow.tiers.flatMap((t) => t.nodes).map((n) => [n.id, n]));
195
+ flow.headers = baseFlow.headers.map((h) => ({ ...h }));
196
+ let top = baseFlow.top;
197
+
198
+ for (const tier of flow.tiers) {
199
+ if (!tier.nodes.length) continue;
200
+ const kept = tier.nodes.filter((n) => was.has(n.id));
201
+ const added = tier.nodes.filter((n) => !was.has(n.id));
202
+ for (const n of kept) { const b = was.get(n.id); n.x = b.x; n.y = b.y; n.r = b.r; }
203
+ if (!added.length) continue;
204
+
205
+ const rows = headerOf.get(tier.key).rows;
206
+ const lastX = Math.max(...kept.map((n) => n.x));
207
+ const rowY = (k) => (k - (rows - 1) / 2) * LANE_ROW;
208
+ const taken = new Set(kept.filter((n) => n.x === lastX).map((n) => Math.round(n.y)));
209
+ let k = 0;
210
+ for (const n of added) {
211
+ while (taken.has(Math.round(rowY(k)))) k++;
212
+ n.x = lastX;
213
+ n.y = rowY(k);
214
+ taken.add(Math.round(n.y));
215
+ top = Math.min(top, -(n.y + 40)); // the bands run from `top` down to `-top + 40`
216
+ }
217
+ }
218
+ flow.top = top;
219
+ return true;
220
+ }