@popcorn245/cornfield 0.48.0 → 0.49.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.
@@ -0,0 +1,373 @@
1
+ /**
2
+ * @module explorer/engine/proposal
3
+ *
4
+ * Opening a proposal on an instance (spec 0011 D2, step 5). The open proposal is the instance's state, not the page's: a host hands one in
5
+ * (`showProposal(inst, object)`), or names one for the instance to fetch (`openProposal(inst, slug, source)`, through `inst.fetch`, so a base
6
+ * address applies), or closes it (`closeProposal`). Nothing here reads the address or writes it: the page shell turns `?proposal=` into the same
7
+ * calls a host would make, and writes the address when the instance says a proposal opened, changed view or closed (the `proposal` event).
8
+ *
9
+ * state.proposal / proposalSlug / proposalSource / proposalSha256 / proposalView / proposalErrors / effectiveProposal what is open
10
+ * state.baseNodes / baseEdges the map without it; state.nodes / edges are the base (copied) or `applyProposal(base, proposal)`
11
+ *
12
+ * What it tells its neighbours (`inst.on`):
13
+ * proposal { change: 'opened' | 'view' | 'closed', slug, source, pinSource, view, proposal } the open proposal changed
14
+ * proposal:draw { open } the bar and the review column draw again (pieces/proposal.js, pieces/changes.js), in that order
15
+ * proposal:bar { open } they have: the controls that sit on the bar draw again (the what-if editor, the decision, the mockups, the Work panel's line)
16
+ * proposal:mark { applied, effective, proposal } before the map is laid out: the what-if editor puts its `edit` mark on what the edits added or removed
17
+ * proposal:message { text, isError, ways } one line in the bar in place of a proposal: while one opens, or why it did not
18
+ * proposal:pull-head sha the PR of the open proposal was read: the review column keys what was seen by its head
19
+ * proposal:focus-title (none) the focus goes to the proposal's name (a Retry in the decision worked; the bar answers)
20
+ * changes:peek text the review column's count line for the phone's peek, for the bar to show (pieces/changes.js)
21
+ * What it asks (`inst.ask`; nobody answering is a no):
22
+ * proposal:effective proposal -> proposal the proposal the map is drawn from (the what-if editor's, with the edits in); no answer: the proposal itself
23
+ * proposal:before-close (none) -> false keeps the proposal open (the what-if editor is asking whether to keep its edits)
24
+ * work:open-specs (none) -> true the Work panel's Specs tab is open for a bad link's way on; no answer: the bar opens its Proposals menu
25
+ * map:set { nodes, edges } -> true the page lays the map out again from these (view.js setMap, not yet an instance's)
26
+ * And emits to the node panel: node:show-edge { edge }.
27
+ *
28
+ * These replace the `hooks` object proposal.js had (each assigned by whatif.js, review.js, mockups.js and forge-panel.js, and chained):
29
+ * hooks.effective -> ask proposal:effective hooks.mark -> event proposal:mark hooks.beforeClose -> ask proposal:before-close
30
+ * hooks.closed -> event proposal {closed} hooks.bar -> event proposal:bar hooks.openSpecs -> ask work:open-specs
31
+ * hooks.reviewed -> event decision (pieces/decision.js)
32
+ */
33
+
34
+ import { edgePoint } from '../scene.js';
35
+ import { frameNodes, largestGroup, READ_ZOOM, FRAME_ZOOM_MIN } from '../camera.js';
36
+ import { PROPOSAL_VIEWS, MARK_WORDS, touchedIds, viewWords, jumpWords, notFoundWords, otherCopies } from '../proposal-model.js';
37
+ import { applyProposal, edgeKey, proposalProblems } from '../../core/proposal.js';
38
+ import { beginReview, endReview, redrawLayers, reviewLayersLine } from './layers.js';
39
+ import { visibleMapRect, collapseSheet } from './sheets.js';
40
+ import { announce } from './keyboard.js';
41
+ import { selectNode, clearSelection } from './selection.js';
42
+ import { t } from './strings.js';
43
+ import { credentialed } from './connection.js';
44
+
45
+ /** What the instance keeps of proposals: the open one is in `state`; this is the rest (the list the server gave, which opening is the latest, the bar's one line) */
46
+ const memory = (inst) => inst.slot('proposal', () => ({ pinnedSource: false, listing: null, listingProblem: null, forgeProblem: null, listingAt: 0, watchers: new Set(), openToken: 0, message: null }));
47
+
48
+ /** The name the bar gives the open proposal */
49
+ export const titleOf = (state) => (state.proposal && typeof state.proposal.title === 'string' && state.proposal.title) || state.proposalSlug || 'Proposal';
50
+
51
+ /** The way on every bad link offers: the list of specs */
52
+ const specsWay = (inst) => ({ label: t(inst, 'openSpecsList'), way: 'specs' });
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // The list the server gives
56
+ // ---------------------------------------------------------------------------
57
+
58
+ /** What the server listed last, for the Work panel's Specs tab: the entries (null before the first answer), why the list could not be read, why the spec PRs are missing, and when */
59
+ export function proposalListing(inst) {
60
+ const m = memory(inst);
61
+ return { entries: m.listing, problem: m.listingProblem, forgeProblem: m.forgeProblem, at: m.listingAt };
62
+ }
63
+
64
+ /** Calls `fn` each time the list is read again; returns the way to stop */
65
+ export function onProposalListing(inst, fn) {
66
+ const m = memory(inst);
67
+ m.watchers.add(fn);
68
+ return () => m.watchers.delete(fn);
69
+ }
70
+
71
+ /** Asks the server for the proposals it can serve (`GET /proposals`) */
72
+ export async function loadProposalList(inst) {
73
+ const m = memory(inst);
74
+ const get = credentialed(inst);
75
+ try {
76
+ let res;
77
+ try { res = await get('/proposals', { cache: 'no-store' }); } catch { throw new Error(inst.offline() ? 'You are offline.' : 'cornfield could not be reached. Check that it is still running.'); }
78
+ if (!res.ok) throw new Error(`The server could not list them (error ${res.status}).`);
79
+ let body;
80
+ try { body = await res.json(); } catch { throw new Error('cornfield sent a list this page could not read.'); }
81
+ if (!Array.isArray(body)) throw new Error('cornfield sent something that is not a list of proposals.');
82
+ m.listing = body;
83
+ m.listingProblem = null;
84
+ const said = res.headers.get('X-Proposals-Forge-Error');
85
+ m.forgeProblem = said ? decodeURIComponent(said) : null;
86
+ } catch (err) {
87
+ m.listing = null;
88
+ m.forgeProblem = null;
89
+ m.listingProblem = err.message || 'cornfield did not answer.'; // always a plain sentence made above, never a parser's or a runtime's own words
90
+ }
91
+ m.listingAt = Date.now();
92
+ inst.emit('proposal:listing');
93
+ for (const fn of [...m.watchers]) fn();
94
+ return m.listing;
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Opening, showing, closing
99
+ // ---------------------------------------------------------------------------
100
+
101
+ /** One line in the bar instead of a proposal: while one opens, or why it did not (with `ways`, the buttons that go on from there) */
102
+ export function setMessage(inst, text, isError = false, ways = []) {
103
+ const m = memory(inst);
104
+ m.message = { text, isError, ways };
105
+ inst.emit('proposal:message', m.message);
106
+ }
107
+
108
+ /** The line the bar shows in place of a proposal, or null */
109
+ export const messageOf = (inst) => memory(inst).message;
110
+
111
+ /**
112
+ * Opens a proposal by name: fetches it from the server (`GET /proposals/<slug>.json`, through `inst.fetch`) and shows it. `source` is where the server
113
+ * found it (`checkout` or a worktree's name); without one the server answers with the first it lists.
114
+ * @returns {Promise<boolean>} whether it opened
115
+ */
116
+ export async function openProposal(inst, slug, source = null) {
117
+ const m = memory(inst);
118
+ const token = ++m.openToken;
119
+ setMessage(inst, `Opening ${slug} …`);
120
+ try {
121
+ let res;
122
+ try { res = await credentialed(inst)(`/proposals/${encodeURIComponent(slug)}.json${source ? `?source=${encodeURIComponent(source)}` : ''}`, { cache: 'no-store' }); } catch { throw new Error(inst.offline() ? `${slug} could not be opened: you are offline.` : `${slug} could not be opened: cornfield could not be reached.`); }
123
+ if (!res.ok) {
124
+ let why = '';
125
+ try { why = (await res.json()).error || ''; } catch { /* no body */ }
126
+ const err = new Error(res.status === 404 ? notFoundWords(slug, source) : `${slug} could not be opened: ${why || `the server had a problem (error ${res.status}).`}`);
127
+ err.notFound = res.status === 404;
128
+ throw err;
129
+ }
130
+ const found = res.headers.get('X-Proposal-Source');
131
+ let item;
132
+ try { item = await res.json(); } catch { throw new Error(`${slug} could not be opened: cornfield sent a file this page could not read.`); }
133
+ const sha256 = res.headers.get('X-Proposal-Sha256'); // the version on screen: a review names it, so a push since is refused, not approved unseen
134
+ if (inst.ended) return false; // the instance ended while the answer came
135
+ showProposal(inst, item, { slug, source: source || (found ? decodeURIComponent(found) : null), pinSource: !!source, view: 'diff', fit: true, sha256 });
136
+ // said once, here: a proposal opens on a person's asking, never on a background refresh
137
+ announce(inst, [inst.ask('changes:opened-line', titleOf(inst.state)), reviewLayersLine(inst)].filter(Boolean).join(' ')); // and, once, which layers the review hid
138
+ return true;
139
+ } catch (err) {
140
+ if (inst.ended) return false;
141
+ console.error('Opening the proposal failed', err);
142
+ // Said plainly, with the ways on: the Specs list, and the same name under another source when the list has one
143
+ // (a failure that is not "no such proposal" can be asked for again, or let go of: Retry and Close)
144
+ setMessage(inst, err.message || `${slug} could not be opened.`, true, err.notFound ? [specsWay(inst)] : [{ label: 'Retry', way: 'retry', slug, source }, { label: 'Close', way: 'close' }]);
145
+ if (err.notFound && token === m.openToken) {
146
+ await loadProposalList(inst);
147
+ const sources = new Set((Array.isArray(m.listing) ? m.listing : []).map((e) => e && e.source));
148
+ if (token === m.openToken) setMessage(inst, notFoundWords(slug, source, sources), true, [...otherCopies(m.listing, slug, source).map((c) => ({ label: c.label, way: 'open', slug: c.slug, source: c.source })), specsWay(inst)]);
149
+ }
150
+ return false;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Puts a parsed proposal on the map. The map's nodes and edges become `applyProposal(base, proposal)`. A host that has the proposal needs no fetch.
156
+ * @param {ReturnType<import('../instance.js').createInstance>} inst
157
+ * @param {object} proposal
158
+ * @param {{slug?: string|null, source?: string|null, pinSource?: boolean, view?: 'before'|'diff'|'after', fit?: boolean, sha256?: string|null}} [opts]
159
+ * `sha256`: the file's SHA-256 as the server sent it (X-Proposal-Sha256): a review names it (spec 0007)
160
+ * `fit`: fit the camera to what the proposal touches and what it connects to (default true).
161
+ * `pinSource`: the page puts `&source=` in the address (it was asked for by name; otherwise `/?proposal=<slug>` finds the same one)
162
+ */
163
+ export function showProposal(inst, proposal, { slug = null, source = null, pinSource = false, view, fit = true, sha256 = null } = {}) {
164
+ const { state } = inst;
165
+ state.proposal = proposal;
166
+ beginReview(inst); // the map narrows to the change: a review of its own, the viewer's layers untouched (layers.js, layer-model.js)
167
+ state.proposalSlug = slug;
168
+ state.proposalSource = source;
169
+ state.proposalSha256 = typeof sha256 === 'string' && /^[0-9a-f]{64}$/.test(sha256) ? sha256 : null;
170
+ memory(inst).pinnedSource = pinSource;
171
+ if (view) state.proposalView = view;
172
+ else if (!PROPOSAL_VIEWS.includes(state.proposalView)) state.proposalView = 'diff';
173
+ const answer = inst.ask('proposal:effective', proposal);
174
+ rebuildProposalMap(inst, answer === undefined ? proposal : answer, { fit });
175
+ tell(inst, 'opened');
176
+ }
177
+
178
+ /** Says that the open proposal changed: opened, another view, or closed (the page writes the address from this) */
179
+ function tell(inst, change) {
180
+ const { state } = inst;
181
+ inst.emit('proposal', { change, slug: state.proposalSlug || null, source: state.proposalSource || null, pinSource: memory(inst).pinnedSource, view: state.proposalView, proposal: state.proposal || null });
182
+ }
183
+
184
+ /** The bar and the review column draw again, then whatever sits on the bar */
185
+ export function drawBar(inst) {
186
+ const open = !!inst.state.proposal;
187
+ inst.emit('proposal:draw', { open });
188
+ inst.emit('proposal:bar', { open });
189
+ }
190
+
191
+ /**
192
+ * Redraws the map from `proposal` laid over the base, and the bar from `state.proposal`. Call it after anything the map is built from changes.
193
+ * `effective` is the proposal to apply: `state.proposal`, or an edited copy of it (what-if edits, TOPO-11).
194
+ */
195
+ export function rebuildProposalMap(inst, effective, { fit = false } = {}) {
196
+ const { state } = inst;
197
+ if (effective === undefined) { const answer = inst.ask('proposal:effective', state.proposal); effective = answer === undefined ? state.proposal : answer; }
198
+ const base = { nodes: state.baseNodes, edges: state.baseEdges };
199
+ let applied;
200
+ state.effectiveProposal = effective;
201
+ try {
202
+ state.proposalErrors = proposalProblems(base, effective).errors;
203
+ applied = applyProposal(base, effective);
204
+ inst.emit('proposal:mark', { applied, effective, proposal: state.proposal });
205
+ } catch (err) {
206
+ // A file so malformed that it cannot be read at all: the plain map, and the reason
207
+ state.proposalErrors = [{ path: '', message: `This proposal could not be read: ${err.message}` }];
208
+ applied = { nodes: state.baseNodes.map((n) => ({ ...n, mark: 'none' })), edges: state.baseEdges.map((e) => ({ ...e, mark: 'none' })) };
209
+ }
210
+ swapMap(inst, applied.nodes, applied.edges);
211
+ drawBar(inst); // first: the fit below leaves out what the bar covers, so the bar must be laid out
212
+ redrawLayers(inst); // the menu follows the layers the change touches
213
+ if (fit) fitToChange(inst);
214
+ inst.map.render();
215
+ inst.map.ensureFlowLoop();
216
+ }
217
+
218
+ /** Closes the proposal: the plain map comes back, as it was. The page takes `?proposal=` out of the address when it hears `proposal` {closed}. */
219
+ export function closeProposal(inst) {
220
+ const { state } = inst;
221
+ if (inst.ask('proposal:before-close') === false) return false;
222
+ state.proposal = null;
223
+ state.effectiveProposal = null;
224
+ state.proposalSlug = null;
225
+ state.proposalSource = null;
226
+ state.proposalSha256 = null;
227
+ state.proposalErrors = [];
228
+ endReview(inst); // the viewer's own layers are what is drawn again, exactly as they were
229
+ swapMap(inst, state.baseNodes.map((n) => ({ ...n })), state.baseEdges);
230
+ inst.map.fitGraphToViewport(inst.map.fitPadding());
231
+ inst.map.render();
232
+ inst.map.ensureFlowLoop();
233
+ drawBar(inst);
234
+ tell(inst, 'closed');
235
+ return true;
236
+ }
237
+
238
+ /** Switches between Before, Diff and After; no node moves. Entering Diff fits the camera to the change. */
239
+ export function setProposalView(inst, view, { quiet = false } = {}) {
240
+ const { state } = inst;
241
+ if (!state.proposal || !PROPOSAL_VIEWS.includes(view) || state.proposalView === view) return;
242
+ state.proposalView = view;
243
+ inst.touchScene();
244
+ if (state.selectedNode && !inst.map.isNodeVisible(state.selectedNode)) clearSelection(inst, { source: 'api' }); // it is not in this view
245
+ if (view === 'diff') fitToChange(inst);
246
+ inst.map.render();
247
+ drawBar(inst);
248
+ tell(inst, 'view');
249
+ if (!quiet) announce(inst, viewWords(view));
250
+ }
251
+
252
+ /** Hands the map new nodes and edges, keeping the selection on the same node */
253
+ function swapMap(inst, nodes, edges) {
254
+ const { state } = inst;
255
+ const selected = state.selectedNode ? state.selectedNode.id : null;
256
+ if (!inst.ask('map:set', { nodes, edges })) { // nobody lays the map out: it is these nodes as they are
257
+ state.mapNodes = nodes;
258
+ state.mapEdges = edges;
259
+ state.nodes = nodes;
260
+ state.edges = edges;
261
+ }
262
+ state.selectedEdge = null;
263
+ if (selected) {
264
+ const again = state.nodes.find((n) => n.id === selected);
265
+ if (again) state.selectedNode = again;
266
+ else clearSelection(inst, { source: 'api' });
267
+ }
268
+ inst.touchScene();
269
+ }
270
+
271
+ /**
272
+ * Frames what the proposal changes (nodes added, changed or removed, and both ends of a changed edge; not what they connect to) in the part of the
273
+ * map nothing covers (the bar, the review column, the node panel, a phone's sheets), at a zoom up to 1 so their labels read. Only what is drawn counts: a change on a
274
+ * layer that is off is not framed (the map would centre on ground the viewer cannot see). When the change is wider than FRAME_ZOOM_MIN shows,
275
+ * the biggest part of it that fits there is framed, not the whole at a zoom where it is a speck (the change list reaches the rest). A proposal that changes nothing drawn shows the whole map.
276
+ */
277
+ function fitToChange(inst) {
278
+ const { state, map } = inst;
279
+ const { touched } = touchedIds(state.nodes, inst.viewEdges());
280
+ const items = state.nodes.filter((n) => touched.has(n.id) && map.isNodeVisible(n));
281
+ const rect = visibleMapRect(inst);
282
+ const opts = { padding: map.fitPadding(), maxZoom: 1, minZoom: map.getMinZoom() };
283
+ // The whole change when it fits at FRAME_ZOOM_MIN or closer; else the biggest part of it that does (camera.js)
284
+ const group = largestGroup(items, rect, { ...opts, minZoom: Math.max(opts.minZoom, FRAME_ZOOM_MIN) });
285
+ const cam = items.length ? frameNodes(group, rect, opts) : null;
286
+ if (!cam) { map.fitGraphToViewport(map.fitPadding()); return; }
287
+ Object.assign(state.camera, cam);
288
+ map.render();
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // The change list's rows, and picking an edge
293
+ // ---------------------------------------------------------------------------
294
+
295
+ const nameOf = (state, id) => (state.nodes.find((n) => n.id === id) || { label: id }).label;
296
+ /** The kind a scene edge reports for an applied one (an ownership link has none) */
297
+ export const kindOf = (e) => e.kind || (e.dashed ? 'usage' : 'ownership');
298
+
299
+ /**
300
+ * Picks a row of the changes list: select it, centre it in the part of the map the review column, the node panel and (on a phone) the sheets leave free,
301
+ * at a zoom where its label reads, and make sure the current view shows it
302
+ */
303
+ export function focusChange(inst, kind, key, { select = true } = {}) {
304
+ const { state, map } = inst;
305
+ const item = kind === 'edge' ? state.edges.find((e) => edgeKey(e) === key) : state.nodes.find((n) => n.id === key);
306
+ if (!item) return;
307
+ const ends = (kind === 'edge' ? [state.nodes.find((n) => n.id === item.from), state.nodes.find((n) => n.id === item.to)] : [item]).filter(Boolean);
308
+ if (!ends.length) return;
309
+ if (state.proposalView !== 'diff' && ends.some((n) => !map.isNodeVisible(n))) setProposalView(inst, 'diff', { quiet: true }); // Before or After hides what it removes or adds
310
+ if (select) { if (kind === 'edge') showEdge(inst, item); else selectNode(inst, item); }
311
+ // The panel is open now, so what it covers is known
312
+ const cam = frameNodes(ends, visibleMapRect(inst), { padding: map.fitPadding(), maxZoom: Math.max(READ_ZOOM, state.camera.zoom), minZoom: map.getMinZoom() });
313
+ if (cam) Object.assign(state.camera, cam);
314
+ map.render();
315
+ announce(inst, jumpWords(MARK_WORDS[item.mark] || item.mark, kind === 'edge' ? `${nameOf(state, item.from)} to ${nameOf(state, item.to)}` : item.label));
316
+ }
317
+
318
+ /**
319
+ * The marked edge under a point of the map, or null: the nearest one within `tolerance` world units, measured along the drawn curve.
320
+ * Only the edges of the current scene, so a hidden one is never hit.
321
+ */
322
+ export function markedEdgeAt(inst, x, y, tolerance) {
323
+ let best = null;
324
+ let bestDistance = tolerance;
325
+ for (const edge of inst.map.getScene().edges) {
326
+ if (edge.mark === 'none') continue;
327
+ for (let k = 0; k <= 1; k += 1 / 20) {
328
+ const p = edgePoint(edge, k);
329
+ const d = Math.hypot(p.x - x, p.y - y);
330
+ if (d <= bestDistance) { best = edge; bestDistance = d; }
331
+ }
332
+ }
333
+ if (!best) return null;
334
+ return inst.viewEdges().find((e) => e.from === best.from && e.to === best.to && kindOf(e) === best.kind) || null;
335
+ }
336
+
337
+ /** Selects an edge and has the node panel show it (it is the panel's to fill, to open and to make reachable: `node:show-edge`) */
338
+ export function showEdge(inst, edge) {
339
+ clearSelection(inst, { source: 'api' }); // clears a node selection and any panel still loading
340
+ inst.state.selectedEdge = edge;
341
+ inst.emit('node:show-edge', { edge });
342
+ inst.touchScene();
343
+ inst.map.render();
344
+ }
345
+
346
+ /** A click on the map that picks no node but lands on a marked edge opens that edge. Returns the way to stop. */
347
+ export function bindEdgePicking(inst, listen) {
348
+ const canvas = inst.state.canvas;
349
+ if (!canvas) return () => {};
350
+ let down = null;
351
+ const offs = [
352
+ listen(canvas, 'mousedown', (e) => { down = { x: e.clientX, y: e.clientY }; }),
353
+ listen(canvas, 'click', (e) => {
354
+ const { state } = inst;
355
+ if (!state.proposal || state.proposalView === 'before') return; // Before has no marked edges
356
+ if (down && Math.hypot(e.clientX - down.x, e.clientY - down.y) > 5) return; // a drag
357
+ const rect = canvas.getBoundingClientRect();
358
+ const p = inst.map.screenToWorld(e.clientX - rect.left, e.clientY - rect.top);
359
+ const zoom = state.camera.zoom;
360
+ const onNode = state.nodes.some((n) => inst.map.isNodeVisible(n) && Math.hypot(n.x - p.x, n.y - p.y) <= n.r + 6 / zoom);
361
+ if (onNode) return; // a node: the map's own selection handles it
362
+ const edge = markedEdgeAt(inst, p.x, p.y, 8 / zoom);
363
+ if (edge) showEdge(inst, edge);
364
+ }),
365
+ ];
366
+ return () => offs.forEach((off) => off());
367
+ }
368
+
369
+ /** Whether the open proposal's source goes in the address (it was asked for by name) */
370
+ export const pinnedSource = (inst) => memory(inst).pinnedSource;
371
+
372
+ /** The phone's sheet for the bar folds when no proposal is open */
373
+ export const collapseProposalSheet = (inst) => collapseSheet(inst, 'proposal');
@@ -283,6 +283,7 @@ export function createMap(inst, opts = {}) {
283
283
  /** Ends the map: no frame is waiting, the renderer's GPU context and the label layer are released, nothing is called again */
284
284
  function destroy() {
285
285
  ended = true;
286
+ if (inst.map === map) inst.map = null; // an instance that outlives its map (a scope's) can be given another
286
287
  scheduler.cancel();
287
288
  // the end of this map: the renderer gives its WebGL context back too (`release`); a swap (setRenderer) only destroys, so the next renderer on the canvas has a live one
288
289
  if (renderer) { if (renderer.release) renderer.release(); else renderer.destroy(); renderer = null; rendererCanvas = null; }