cornfield 0.48.0 → 0.50.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 (42) hide show
  1. package/core/strings.js +14 -0
  2. package/explorer/check.js +7 -227
  3. package/explorer/connection.js +3 -3
  4. package/explorer/css/review.css +49 -0
  5. package/explorer/decision-model.js +6 -0
  6. package/explorer/engine/checks.js +252 -0
  7. package/explorer/engine/connection.js +36 -0
  8. package/explorer/engine/layers.js +1 -0
  9. package/explorer/engine/layout.js +8 -3
  10. package/explorer/engine/player.js +489 -0
  11. package/explorer/engine/proposal.js +373 -0
  12. package/explorer/engine/render.js +1 -0
  13. package/explorer/engine/sheets.js +40 -7
  14. package/explorer/engine/source.js +315 -0
  15. package/explorer/engine/theme-sheet.js +444 -0
  16. package/explorer/engine/topology.js +126 -0
  17. package/explorer/index.html +6 -59
  18. package/explorer/instance.js +87 -7
  19. package/explorer/page-address.js +59 -0
  20. package/explorer/page-pieces.js +33 -5
  21. package/explorer/page.js +20 -20
  22. package/explorer/panels.js +1 -3
  23. package/explorer/pieces/changes.js +495 -0
  24. package/explorer/pieces/decision.js +664 -0
  25. package/explorer/pieces/layers.js +4 -0
  26. package/explorer/pieces/map.js +117 -25
  27. package/explorer/pieces/node-panel.js +34 -1
  28. package/explorer/pieces/proposal.js +488 -0
  29. package/explorer/pieces/review.js +280 -0
  30. package/explorer/pieces/scope-link.js +50 -0
  31. package/explorer/pieces/scope.js +247 -0
  32. package/explorer/pieces/status.css +24 -0
  33. package/explorer/pieces/status.js +144 -0
  34. package/explorer/plugins.js +0 -10
  35. package/explorer/proposal.js +64 -697
  36. package/explorer/review-column.js +24 -439
  37. package/explorer/review.js +27 -673
  38. package/explorer/scenario-ui.js +32 -478
  39. package/explorer/sheets.js +8 -7
  40. package/explorer/view.js +12 -64
  41. package/explorer/waiting-line.js +7 -50
  42. package/package.json +1 -1
@@ -1,686 +1,40 @@
1
1
  /**
2
2
  * @module explorer/review
3
3
  *
4
- * Approving a proposal and sending it back: the two buttons on the proposal toolbar (index.html), the note that opens
5
- * under it, and what a click does. "Approve" takes no note. "Send back" opens the note field (focus moves to it; Cancel
6
- * closes it and gives focus back to Send back); the button then reads "Send back with this note" and a note is needed.
7
- * Both put the maintainer's what-if
8
- * edits (`getEdits()`, whatif.js) in the review, which the server posts as a comment on the spec PR, as the
9
- * signed-in maintainer (`PUT /proposals/<slug>/review`, server/proposals.js, server/reviews.js). The agent drafting
10
- * the spec reads it (`cornfield review <slug>`) and folds the edits into the proposal. Only a proposal of a spec PR
11
- * (source `pull/<n>`) has a PR to hold a review: for a draft in the checkout or a worktree the buttons are off and
12
- * the bar says to push it as a spec PR (docs/specs/0001-v1.md).
13
- *
14
- * state.proposalSlug / proposalSource which proposal the review is for (the server matches them against what it listed)
15
- * GET /proposals/<slug>/review the latest admin review on the PR, when it opens: "Approved 3 minutes ago"
16
- * PUT /proposals/<slug>/review { verdict, note, edits } -> the review as posted
17
- *
18
- * An approval of a spec PR's proposal also records its mockup files' hashes in the review comment (server/mockups.js); the panel's mockups then read "Reviewed" (mockups.js).
19
- *
20
- * After a send back the edits are emptied (`clearEdits()`: they went with the note); after an approval they stay, as they are
21
- * in the comment. Nothing here uses `alert`: every refusal and failure is a line on the bar.
22
- *
23
- * The words and the choices (what is sent, what to say) are review-model.js, tested without a page.
24
- *
25
- * **The decision (spec 0007).** Above the buttons, one line says what Approve does in this exact state (the PR, its checks, landing, a run, the runner,
26
- * the maintainer's edits): Approve's `aria-describedby`. The facts are `GET /proposals/<slug>/decision` (server/decision.js), read when the proposal
27
- * opens, every `FACTS_MS` while it is open and the tab is visible, when the window gets focus, and at the end of the hold; the words and the choices are
28
- * decision-model.js. Four states ask first, in place (the line becomes the question, the button "Approve anyway", Escape takes it back); a press then
29
- * starts a hold of `HOLD_MS` with Undo (focus on it) before anything leaves the page, and the end of the hold reads the facts once more. Closing the
30
- * proposal, opening another, hiding the tab, going offline, changing the edits, a push seen at the end of the hold, Undo and Escape each stop it, and
31
- * say so. What is sent is what was on screen at the press, with the version it was about (`sha256`, `headSha`). The server is the rule: it refuses a
32
- * version or a head the page was not shown (409), a maintainer who is one no longer (403) and a missing sign-in (401), and answers a repeat of an
33
- * approval that stands with that one, posting nothing, whatever this page did.
4
+ * A bridge (spec 0011 D2 and D3, step 5): approving a proposal and sending it back is now the decision piece (pieces/decision.js). This file keeps the old
5
+ * names for page.js and tests, bound to the page's instance, and answers for the what-if editor and the mockups, which are not on an instance yet: what the
6
+ * decision asks of them (their edits, an open form, the lines of the edits sent) and what it tells them (the edits went, the screens were reviewed). It goes
7
+ * when those two are converted.
34
8
  */
35
9
 
36
- import { state } from './state.js';
37
- import { expandSheet, isPhone } from './sheets.js';
38
- import { hooks } from './proposal.js';
39
- import { refreshMockups } from './mockups.js';
10
+ import { pageInstance } from './state.js';
11
+ import { pagePiece, setPagePieceOptions } from './page-pieces.js';
40
12
  import { getEdits, clearEdits, onEditsChange, openFormInfo, describeEditsNow } from './whatif.js';
41
- import { reviewParts, sendBackProblem, reviewBody, editsHint, isReviewable } from './review-model.js';
42
- import {
43
- HOLD_MS, decide, askReasons, askWords, newReasons, sendBackLine, sendBackDecision, refusalWords, holdWords, holdStartWords, holdCancelledWords, editsSentWords,
44
- } from './decision-model.js';
45
- import { pullNumberOf } from './proposal-model.js';
46
- import { playedLine, onReviewColumnPaint } from './review-column.js';
47
- import { announce } from './keyboard.js';
48
- import { t } from './strings.js';
49
- import { isOffline, notSentWords } from './connection.js';
50
-
51
- const $ = (id) => document.getElementById(id);
52
-
53
- const TICK_MS = 30_000;
54
- /** How often the facts of the decision are read again while a proposal with a PR is open and the tab is visible (spec 0007 D1) */
55
- export const FACTS_MS = 30_000;
56
-
57
- /** What is shown: the review of the proposal that is open, and the lines under the buttons */
58
- const ui = {
59
- key: null, // `${source}/${slug}` of the proposal the review below belongs to
60
- reviewable: false, // whether it is on a spec PR
61
- review: null, // { verdict, at } | null: the last review of it
62
- loadFailed: false, // the past reviews could not be read: the bar must not look as if there were none
63
- busy: false,
64
- noting: false, // the note field is open (Send back was pressed)
65
- message: '', // an inline refusal or failure
66
- hint: '', // what happens to the edits
67
- facts: null, // the decision route's answer for the open proposal
68
- factsState: 'loading', // 'loading' | 'ready' | 'unread'
69
- factsAt: 0,
70
- asking: null, // { verdict, answered }: the first press asked, and the button reads "Approve anyway"
71
- hold: null, // { verdict, body, answered, left, tick, end }: pressed, not yet sent (D3)
72
- sent: null, // { count, lines }: the edits a send back carried, kept readable (D4)
73
- };
74
-
75
- let root = null;
76
- let wired = false;
77
- let barBefore = null; // the hook that was on the bar before this one
78
- let timer = null;
79
- let factsTimer = null;
80
- let now = () => Date.now();
81
-
82
- const slugOf = () => state.proposalSlug || null;
83
- const keyOf = () => (state.proposal && slugOf() ? `${state.proposalSource || ''}/${slugOf()}` : null);
84
- const enc = () => (state.proposalSource ? `?source=${encodeURIComponent(state.proposalSource)}` : '');
85
- const reviewUrl = () => `/proposals/${encodeURIComponent(slugOf())}/review${enc()}`;
86
- const decisionUrl = (fresh) => `/proposals/${encodeURIComponent(slugOf())}/decision${enc()}${fresh ? '&fresh=1' : ''}`;
87
- const q = (sel) => (root ? root.querySelector(sel) : null);
88
- /** The decision's buttons, in the review column's foot: Send back and Approve (index.html) */
89
- const button = (verdict) => document.querySelector(`#review-decision [data-review="${verdict}"]`);
90
- const undoButton = () => document.querySelector('#review-decision [data-review-undo]');
91
-
92
- /** The status line, the note field, the line above the buttons and the hold; added to the decision (the review column's foot) once, just before Send back and Approve, so Tab goes from the note to Cancel and then to "Send back with this note" */
93
- function mount() {
94
- const body = $('proposal-body');
95
- if (!body) return null;
96
- if (!root) {
97
- root = document.createElement('div');
98
- root.id = 'review';
99
- root.className = 'hx-review';
100
- root.dataset.corn = 'review-bar';
101
- root.innerHTML = `
102
- <p class="hx-review-status" data-review-status hidden><span data-review-verdict role="status"></span><span data-review-when></span></p>
103
- <div class="hx-review-form" id="review-form" data-review-form hidden>
104
- <label class="hx-review-label" for="review-note" data-corn="review-label"></label>
105
- <textarea data-corn="review-note" id="review-note" class="hx-review-note" rows="2" maxlength="20000"></textarea>
106
- <p class="hx-review-line" id="review-sendback-line" data-review-sendback-line></p>
107
- <div class="hx-review-row">
108
- <button type="button" class="hx-btn hx-btn--quiet" data-review-cancel data-corn-kind="quiet">Cancel</button>
109
- </div>
110
- </div>
111
- <p class="hx-review-msg" data-review-loadfail role="alert" hidden data-corn="message" data-corn-state="failure"><span data-review-loadfail-text></span> <button type="button" class="hx-btn hx-btn--quiet" data-review-retry data-corn-kind="quiet">Retry</button></p>
112
- <p class="hx-review-msg" data-review-msg role="alert" hidden></p>
113
- <p class="hx-review-line" id="review-hint" data-review-hint role="status" hidden></p>
114
- <details class="hx-sent-edits" data-corn="sent-edits" data-review-sent hidden><summary data-corn="summary" data-review-sent-summary></summary><ul class="hx-whatif-list" data-review-sent-list></ul></details>
115
- <div class="hx-review-landing" data-corn="notice" data-corn-state="waiting" data-review-landing hidden><p data-review-landing-text></p><button type="button" class="hx-btn hx-btn--quiet" data-review-cancel-landing data-corn-kind="quiet"></button></div>
116
- <p class="hx-review-ask" id="review-ask" data-corn="message" data-corn-state="waiting" data-review-ask role="alert" hidden></p>
117
- <p class="hx-decision-line" id="review-line" data-review-line></p>
118
- <div class="hx-hold" data-review-hold hidden aria-hidden="true"><span class="hx-hold-fill" data-review-hold-fill></span></div>
119
- <p class="hx-sr-only" data-review-hold-live role="status"></p>
120
- `;
121
- // The words are set as text and attributes, never parsed as HTML (a brand's `strings`, explorer/strings.js)
122
- q('.hx-review-label').textContent = t('reviewNoteLabel');
123
- q('#review-note').setAttribute('placeholder', t('reviewNotePlaceholder'));
124
- q('[data-review-cancel-landing]').textContent = t('cancelLanding');
125
- // In the decision, the column's foot: the status and the note above Send back and Approve
126
- const actions = document.querySelector('#review-decision .hx-proposal-actions');
127
- if (actions) {
128
- actions.before(root);
129
- if (!actions.querySelector('[data-review-undo]')) {
130
- const undo = document.createElement('button');
131
- undo.type = 'button';
132
- undo.className = 'hx-btn hx-review-undo';
133
- undo.dataset.reviewUndo = '';
134
- undo.dataset.cornKind = 'secondary';
135
- undo.hidden = true;
136
- undo.textContent = t('undo');
137
- // Before Approve, not after it: Approve keeps its place under the pointer, so the second click of a double click lands on the held
138
- // button (which ignores it), never on Undo; on a phone Undo takes a row of its own under the two (css/decision.css)
139
- const approve = actions.querySelector('[data-review="approved"]');
140
- if (approve) approve.before(undo); else actions.append(undo);
141
- }
142
- } else body.prepend(root);
143
- ($('review-decision') || $('proposal-bar') || root).addEventListener('click', onClick);
144
- root.addEventListener('input', (e) => {
145
- if (e.target && e.target.id === 'review-note') keepNote(ui.key, e.target.value);
146
- if (ui.message) { ui.message = ''; paint(); }
147
- });
148
- root.addEventListener('keydown', (e) => { if (e.key === 'Escape' && ui.noting && !ui.asking && !ui.hold) { e.stopPropagation(); closeNote(); } });
149
- }
150
- return root;
151
- }
152
-
153
- /** What the decision says now: the line and what a press of Approve does (decision-model.js) */
154
- function decision() {
155
- return decide({
156
- source: state.proposalSource, facts: ui.facts, factsState: ui.factsState, review: ui.review, edits: state.whatIf ? state.whatIf.edits.length : 0,
157
- form: openFormInfo(), played: playedLine(), now: now(),
158
- });
159
- }
160
-
161
- /** Everything the review shows, from `ui` */
162
- function paint() {
163
- if (!root) return;
164
- // Only the verdict is a live region, written when it changes: the time beside it ticks every TICK_MS and is never said again
165
- const status = q('[data-review-status]');
166
- const { verdict, when } = reviewParts(ui.review, now());
167
- const said = q('[data-review-verdict]');
168
- if (said.textContent !== verdict) said.textContent = verdict;
169
- q('[data-review-when]').textContent = when ? ` ${when}` : '';
170
- status.hidden = !verdict;
171
- // A failed read of the past reviews says so: an approved proposal must not look as if nobody had reviewed it
172
- const failed = q('[data-review-loadfail]');
173
- failed.hidden = !ui.loadFailed;
174
- q('[data-review-loadfail-text]').textContent = ui.loadFailed ? `Could not load this proposal's reviews.${isOffline() ? ' You are offline.' : ''} It may already be approved or sent back; try again before you decide.` : '';
175
-
176
- const d = decision();
177
- // What asks now. An ask that has nothing left to ask about (the check passed since, the form was added) goes by itself
178
- let askText = '';
179
- if (ui.asking && !ui.hold) {
180
- if (ui.asking.verdict === 'approved') askText = d.reasons.length ? askWords(d.reasons) : '';
181
- else { const sb = sendBackDecision({ form: openFormInfo() }); askText = sb.asks ? sb.ask : ''; }
182
- if (!askText) ui.asking = null;
183
- }
184
- const holding = ui.hold;
185
- const approveBtn = button('approved');
186
- const sendBtn = button('notes');
187
- const approveMode = ui.asking && ui.asking.verdict === 'approved' ? 'anyway' : holding && holding.verdict === 'approved' ? 'hold' : d.approve === 'done' ? 'done' : 'plain';
188
- const sendMode = ui.asking && ui.asking.verdict === 'notes' ? 'anyway' : holding && holding.verdict === 'notes' ? 'hold' : 'plain';
189
-
190
- // The line is Approve's description (the question while one is asked); not on a PR it is the reason for both buttons
191
- const line = q('[data-review-line]');
192
- line.textContent = ui.key ? d.line : '';
193
- line.hidden = !ui.key || !!askText; // the question takes the line's place while one is asked
194
- const ask = q('[data-review-ask]');
195
- if (ask.textContent !== askText) ask.textContent = askText;
196
- ask.hidden = !askText;
197
- q('[data-review-sendback-line]').textContent = sendBackLine({ source: state.proposalSource, edits: state.whatIf ? state.whatIf.edits.length : 0 });
198
-
199
- const refused = ui.key && d.approve === 'refused';
200
- for (const btn of document.querySelectorAll('#review-decision [data-review]')) {
201
- // Never `disabled` while a verdict is in flight, a press is held, or one is refused: those keep the focus and say why (the line); aria-disabled only
202
- const off = !ui.reviewable || ui.busy || !!holding || (btn === approveBtn && (d.approve === 'done' || d.approve === 'reading'));
203
- if (off) btn.setAttribute('aria-disabled', 'true'); else btn.removeAttribute('aria-disabled');
204
- btn.disabled = false;
205
- if (ui.key && btn === approveBtn) btn.setAttribute('aria-describedby', askText ? 'review-ask' : 'review-line');
206
- else if (ui.key && !ui.noting && btn === sendBtn && refused) btn.setAttribute('aria-describedby', 'review-line');
207
- else if (ui.key && ui.noting && btn === sendBtn) btn.setAttribute('aria-describedby', 'review-sendback-line');
208
- else btn.removeAttribute('aria-describedby');
209
- }
210
- if (approveBtn) {
211
- approveBtn.textContent = approveMode === 'hold' ? holdWords('approved', holding.left) : approveMode === 'anyway' ? t('approveAnyway') : approveMode === 'done' ? t('approved') : t('approve');
212
- approveBtn.dataset.holding = approveMode === 'hold' ? 'true' : 'false';
213
- }
214
- if (sendBtn) {
215
- sendBtn.textContent = sendMode === 'hold' ? holdWords('notes', holding.left) : sendMode === 'anyway' ? t('sendBackAnyway') : ui.noting ? t('sendBackWithNote') : t('sendBack');
216
- sendBtn.setAttribute('aria-expanded', String(ui.noting));
217
- sendBtn.setAttribute('aria-controls', 'review-form');
218
- sendBtn.dataset.holding = sendMode === 'hold' ? 'true' : 'false';
219
- }
220
- const undo = undoButton();
221
- if (undo) { undo.hidden = !holding; undo.textContent = t('undo'); }
222
- const bar = q('[data-review-hold]');
223
- bar.hidden = !holding;
224
- q('[data-review-form]').hidden = !ui.noting;
225
- q('[data-review-cancel]').disabled = ui.busy || !!holding;
226
- const note = q('#review-note');
227
- note.disabled = !ui.reviewable;
228
- note.readOnly = !!holding; // what was on screen at the press is what is sent
229
- for (const [sel, text] of [['[data-review-msg]', ui.message], ['[data-review-hint]', ui.reviewable ? ui.hint : '']]) {
230
- const el = q(sel);
231
- el.hidden = !text;
232
- el.textContent = text;
233
- }
234
- // The edits a send back carried: kept readable, read-only (D4)
235
- const sent = q('[data-review-sent]');
236
- sent.hidden = !ui.sent;
237
- if (ui.sent) {
238
- q('[data-review-sent-summary]').textContent = editsSentWords(ui.sent.lines.length);
239
- const list = q('[data-review-sent-list]');
240
- if (list.dataset.for !== ui.sent.key) {
241
- list.dataset.for = ui.sent.key;
242
- list.replaceChildren(...ui.sent.lines.map((text) => { const li = document.createElement('li'); li.className = 'hx-whatif-edit'; li.textContent = text; return li; }));
243
- }
244
- }
245
- // A landing that waits on this PR: Cancel landing, brought here from the Work panel (D3)
246
- const landing = q('[data-review-landing]');
247
- const landingNow = ui.reviewable && ui.facts && ui.facts.landing ? ui.facts.landing : null;
248
- landing.hidden = !landingNow;
249
- if (landingNow) q('[data-review-landing-text]').textContent = `Landing on approval waits for PR #${ui.facts.pull.number} to be ready and green.`;
250
- }
251
-
252
- /** Send back was pressed: the note field opens and takes focus (on a phone the sheet opens to hold it) */
253
- function openNote() {
254
- ui.noting = true;
255
- ui.message = '';
256
- paint();
257
- if (isPhone()) expandSheet('proposal');
258
- q('#review-note').focus();
259
- // On a phone the keyboard is about to take half the screen: the note and the button that sends it stay in view above it
260
- const send = button('notes');
261
- if (isPhone() && send && typeof send.scrollIntoView === 'function') send.scrollIntoView({ block: 'nearest' });
262
- }
263
-
264
- /** Cancel: the field closes, what was typed goes, and focus goes back to Send back */
265
- function closeNote() {
266
- ui.noting = false;
267
- ui.asking = null;
268
- ui.message = '';
269
- q('#review-note').value = '';
270
- forgetNote(ui.key);
271
- paint();
272
- const sendBack = button('notes');
273
- if (sendBack) sendBack.focus();
274
- }
275
-
276
- /** hooks.bar: the bar was drawn. Mount, and when it is another proposal than the one shown, start again for it. */
277
- function onBar(open) {
278
- if (!mount()) return;
279
- const key = open ? keyOf() : null;
280
- root.hidden = !key;
281
- if (key === ui.key) { paint(); return; }
282
- if (ui.hold) stopHold(open ? 'other' : 'closed', { quiet: false });
283
- ui.key = key;
284
- ui.reviewable = !!key && isReviewable(state.proposalSource);
285
- ui.review = null;
286
- ui.loadFailed = false;
287
- ui.busy = false;
288
- ui.noting = false;
289
- ui.asking = null;
290
- ui.sent = null;
291
- ui.facts = null;
292
- ui.factsState = ui.reviewable ? 'loading' : 'ready';
293
- ui.message = ui.hint = '';
294
- const note = q('#review-note');
295
- // A note typed for Send back and not sent survives a reload or a way back to this proposal (in this tab only); it is never sent by itself
296
- const kept = key && ui.reviewable ? keptNote(key) : '';
297
- if (note) note.value = kept;
298
- if (kept) ui.noting = true;
299
- paint();
300
- if (key && ui.reviewable) { loadReview(key); loadFacts(); }
301
- }
302
-
303
- // ---------------------------------------------------------------------------
304
- // The facts of the decision (D1)
305
- // ---------------------------------------------------------------------------
306
-
307
- /**
308
- * Reads what Approve would do in this state. The server keeps the read for every tab, so this is cheap; `fresh` (the end of the hold) skips what is kept.
309
- * @returns {Promise<void>}
310
- */
311
- export async function loadFacts({ fresh = false } = {}) {
312
- const key = ui.key;
313
- if (!key || !ui.reviewable || !pullNumberOf(state.proposalSource)) return;
314
- ui.factsAt = now();
315
- let facts = null;
316
- try {
317
- const res = await fetch(decisionUrl(fresh), { cache: 'no-store' });
318
- if (res.ok) facts = await res.json();
319
- } catch { facts = null; }
320
- if (key !== ui.key) return; // another proposal has opened since
321
- const head = facts && facts.pull ? facts.pull.head : null;
322
- const before = ui.facts && ui.facts.pull ? ui.facts.pull.head : null;
323
- ui.facts = facts && facts.pull ? facts : null;
324
- ui.factsState = ui.facts ? 'ready' : 'unread';
325
- // A push since the review was read: what stood is not what stands, so it is read again ("a push makes it live again")
326
- if (head && before && head !== before) loadReview(key);
327
- paint();
328
- }
329
-
330
- // ---------------------------------------------------------------------------
331
- // The note, kept for this tab (a reload during a hold, or by mistake, does not lose what was typed)
332
- // ---------------------------------------------------------------------------
333
-
334
- const NOTE_KEY = 'cornfield.reviewNote.';
335
- function keepNote(key, text) {
336
- if (!key) return;
337
- try { if (text && text.trim()) sessionStorage.setItem(NOTE_KEY + key, text.slice(0, 20000)); else sessionStorage.removeItem(NOTE_KEY + key); } catch { /* storage off: nothing kept */ }
338
- }
339
- function keptNote(key) {
340
- try { return sessionStorage.getItem(NOTE_KEY + key) || ''; } catch { return ''; }
341
- }
342
- function forgetNote(key) {
343
- if (!key) return;
344
- try { sessionStorage.removeItem(NOTE_KEY + key); } catch { /* storage off */ }
345
- }
346
-
347
- /** The read repeats while a proposal with a PR is open and the tab is visible: nothing when hidden or with none open */
348
- function readFactsAgain(min = 0) {
349
- if (!ui.key || !ui.reviewable || ui.hold || ui.busy) return;
350
- if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
351
- if (now() - ui.factsAt < min) return;
352
- loadFacts();
353
- }
354
-
355
- /** The latest admin review on the proposal's PR, as the server reads it from the comments (none yet is a 404) */
356
- /** The reviews were read: the failure line goes, and Retry, if it had the focus, hands it to the proposal's name (the status line is a live region: it says the review itself, and is not a place for the focus) */
357
- function readAgain() {
358
- const retried = !!root && root.contains(document.activeElement) && document.activeElement.matches('[data-review-retry]');
359
- ui.loadFailed = false;
360
- paint();
361
- const title = $('proposal-title');
362
- if (!retried || !title) return;
363
- title.tabIndex = -1;
364
- title.focus();
365
- }
366
-
367
- function readOnline() {
368
- if (ui.loadFailed && ui.key) loadReview(ui.key);
369
- }
370
-
371
- async function loadReview(key) {
372
- try {
373
- const res = await fetch(reviewUrl(), { cache: 'no-store' });
374
- if (key !== ui.key) return; // another proposal has opened since
375
- if (res.status === 404) { ui.review = null; readAgain(); return; } // none yet: the server says so with a 404
376
- if (!res.ok) throw new Error(`The server answered ${res.status}.`);
377
- const found = await res.json();
378
- if (key !== ui.key) return;
379
- if (found && typeof found.verdict === 'string') ui.review = { verdict: found.verdict, at: found.at, current: found.current === true };
380
- readAgain();
381
- } catch {
382
- // Not "no review": the read failed, so the bar says it could not look (with Retry), and the buttons stay as they were
383
- if (key === ui.key) { ui.loadFailed = true; paint(); }
384
- }
385
- }
386
-
387
- // ---------------------------------------------------------------------------
388
- // The presses
389
- // ---------------------------------------------------------------------------
390
-
391
- function onClick(e) {
392
- if (!e.target.closest) return;
393
- // The second click of a double click (or a double tap) is not a second decision: it must not answer the question the first one asked, nor undo
394
- // the hold it started (keyboard presses have a detail of 0)
395
- if (e.detail > 1 && e.target.closest('[data-review], [data-review-undo]')) return;
396
- if (e.target.closest('[data-review-undo]')) { if (ui.hold) stopHold('undo'); return; }
397
- if (ui.hold || ui.busy) return; // a double press: the first one is being held or sent, a second starts nothing
398
- if (e.target.closest('[data-review-cancel-landing]')) { cancelLanding(); return; }
399
- if (e.target.closest('[data-review-cancel]')) { closeNote(); return; }
400
- if (e.target.closest('[data-review-retry]')) { q('[data-review-loadfail-text]').textContent = 'Reading the reviews again …'; loadReview(ui.key); return; }
401
- const btn = e.target.closest('[data-review]');
402
- if (!btn) return;
403
- const verdict = btn.dataset.review;
404
- // Any other action takes an open question back
405
- if (ui.asking && ui.asking.verdict !== verdict) { ui.asking = null; paint(); }
406
- if (btn.getAttribute('aria-disabled') === 'true' || !ui.reviewable) return;
407
- if (verdict === 'notes' && !ui.noting) { openNote(); return; } // the first press opens the field, the second sends
408
- press(verdict);
409
- }
410
-
411
- /** A press of Approve or of "Send back with this note": it needs a note, may ask first, and then holds */
412
- function press(verdict) {
413
- ui.message = '';
414
- ui.hint = '';
415
- ui.sent = null;
416
- // Offline there is nothing to hold: it says so now, and what was typed and edited is kept
417
- if (isOffline()) { ui.asking = null; ui.message = notSentWords(verdict === 'approved' ? 'Your approval' : 'Your send back'); paint(); return; }
418
- let answered = [];
419
- if (verdict === 'notes') {
420
- const problem = sendBackProblem(q('#review-note').value);
421
- if (problem) {
422
- ui.message = problem;
423
- ui.noting = true; // the refusal is about the note: show it
424
- paint();
425
- if (isPhone()) expandSheet('proposal');
426
- q('#review-note').focus();
427
- return;
428
- }
429
- const sb = sendBackDecision({ form: openFormInfo() });
430
- if (sb.asks && !(ui.asking && ui.asking.verdict === 'notes')) { ui.asking = { verdict: 'notes', answered: [] }; paint(); announce(sb.ask); return; }
431
- answered = sb.reasons.map((r) => r.key);
432
- } else {
433
- const d = decision();
434
- if (d.approve === 'refused' || d.approve === 'done' || d.approve === 'reading') { paint(); return; }
435
- if (d.approve === 'asks' && !(ui.asking && ui.asking.verdict === 'approved')) { ui.asking = { verdict: 'approved', answered: [] }; paint(); return; } // the question is a role=alert: said once
436
- answered = d.reasons.map((r) => r.key);
437
- }
438
- startHold(verdict, answered);
439
- }
440
-
441
- // ---------------------------------------------------------------------------
442
- // The hold (D3)
443
- // ---------------------------------------------------------------------------
444
-
445
- /** Starts the hold: what was on screen at the press is what will be sent; nothing leaves the page until it ends */
446
- function startHold(verdict, answered) {
447
- // What was on screen at the press, and only that, is sent: the note, the edits, and which version they were about (the proposal file's SHA-256 and
448
- // the PR's head commit). The server refuses (409) a review whose version or head is not the PR's any more, so a push during the hold, or before
449
- // the press on a page opened earlier, is never approved unseen
450
- const shown = { ...(state.proposalSha256 ? { sha256: state.proposalSha256 } : {}), ...(ui.facts && ui.facts.pull && ui.facts.pull.head ? { headSha: ui.facts.pull.head } : {}) };
451
- const body = { ...reviewBody(verdict, verdict === 'notes' ? q('#review-note').value : '', getEdits()), ...shown };
452
- ui.asking = null;
453
- const hold = { verdict, body, answered, left: HOLD_MS / 1000, tick: null, end: null };
454
- ui.hold = hold;
455
- hold.tick = setInterval(() => { hold.left = Math.max(0, hold.left - 1); paint(); }, 1000);
456
- hold.end = setTimeout(() => { endHold(hold); }, HOLD_MS);
457
- q('[data-review-hold-fill]').style.animationDuration = `${HOLD_MS}ms`;
458
- paint();
459
- q('[data-review-hold-live]').textContent = holdStartWords(verdict, HOLD_MS / 1000); // said once, not every second
460
- const undo = undoButton();
461
- if (undo) undo.focus();
462
- }
463
-
464
- /** Ends a hold without sending, and says why: nothing was sent. `quiet`: no announcement (the page it was on is gone) */
465
- function stopHold(why, { quiet = false } = {}) {
466
- const hold = ui.hold;
467
- if (!hold) return;
468
- clearInterval(hold.tick);
469
- clearTimeout(hold.end);
470
- ui.hold = null;
471
- const words = holdCancelledWords(hold.verdict, why);
472
- if (why === 'closed' || why === 'other') {
473
- if (!quiet) announce(words); // the review is not on this proposal any more: the page-wide announcer says it
474
- } else ui.message = words;
475
- paint();
476
- const live = q('[data-review-hold-live]');
477
- if (live) live.textContent = why === 'closed' || why === 'other' ? '' : words;
478
- // Undo went; the focus goes back to the button that started it
479
- if (why !== 'closed' && why !== 'other') button(hold.verdict)?.focus();
480
- }
481
-
482
- /** The end of the hold: the facts are read once more; a state that now asks, asks instead of sending */
483
- async function endHold(hold) {
484
- if (ui.hold !== hold) return;
485
- clearInterval(hold.tick);
486
- if (isOffline()) { stopHold('offline'); return; }
487
- if (typeof document !== 'undefined' && document.visibilityState === 'hidden') { stopHold('hidden'); return; }
488
- const key = ui.key;
489
- if (hold.verdict === 'approved' && ui.reviewable) await loadFacts({ fresh: true });
490
- if (ui.hold !== hold || key !== ui.key) return; // undone, or another proposal opened, while the facts were read
491
- // Pushed to during the hold: what was looked at is not the PR any more. Nothing is sent (the server would refuse it as well) and the page says so
492
- const headNow = ui.facts && ui.facts.pull ? ui.facts.pull.head : null;
493
- if (hold.verdict === 'approved' && hold.body.headSha && headNow && headNow !== hold.body.headSha) { stopHold('pushed'); return; }
494
- if (hold.verdict === 'approved') {
495
- const fresh = newReasons(askReasons({ facts: ui.facts, edits: hold.body.edits.length, form: openFormInfo() }), hold.answered);
496
- if (fresh.length) {
497
- ui.hold = null;
498
- ui.asking = { verdict: 'approved', answered: hold.answered };
499
- paint();
500
- button('approved')?.focus();
501
- return;
502
- }
503
- }
504
- ui.hold = null;
505
- const live = q('[data-review-hold-live]');
506
- if (live) live.textContent = ''; // the hold is over: what happened is said by the status line (or the refusal), not by "Approving in 5 seconds"
507
- await sendReview(hold.verdict, { body: hold.body });
508
- }
509
-
510
- /** Cancel landing (D3): the Work panel's Cancel, here; a POST from this page, then the facts are read again */
511
- async function cancelLanding() {
512
- const n = pullNumberOf(state.proposalSource);
513
- if (!n) return;
514
- ui.busy = true;
515
- paint();
516
- let words = '';
517
- try {
518
- const res = await fetch(`/api/forge/pulls/${n}/landing/cancel`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
519
- if (!res.ok) { let why = ''; try { why = (await res.json()).error || ''; } catch { /* no body */ } words = refusalWords(res.status, why); }
520
- } catch { words = notSentWords('Cancelling the landing'); }
521
- ui.busy = false;
522
- ui.message = words;
523
- await loadFacts({ fresh: true });
524
- paint();
525
- if (!words) announce('Landing cancelled. The approval stands and the PR stays open.');
526
- (button('approved') || button('notes'))?.focus();
527
- }
528
-
529
- /**
530
- * Approve or send back the open proposal, now (the hold is over; tests and scripts call this directly).
531
- * @param {'approved'|'notes'} verdict
532
- * @param {{ body?: object }} [frozen] the body held at the press; without it, what is on screen now
533
- * @returns {Promise<boolean>} whether the server took the review
534
- */
535
- export async function sendReview(verdict, frozen = {}) {
536
- if (!state.proposal || !slugOf() || !mount() || !ui.reviewable) return false;
537
- const noteEl = q('#review-note');
538
- const note = verdict === 'notes' ? noteEl.value : ''; // an approval takes no note
539
- ui.hint = '';
540
- if (verdict === 'notes' && !frozen.body) {
541
- const problem = sendBackProblem(note);
542
- if (problem) {
543
- ui.message = problem;
544
- ui.noting = true; // the refusal is about the note: show it
545
- paint();
546
- if (isPhone()) expandSheet('proposal');
547
- noteEl.focus();
548
- return false;
549
- }
550
- }
551
- ui.message = '';
552
- ui.busy = true;
553
- paint();
554
- const key = ui.key;
555
- const body = frozen.body || reviewBody(verdict, note, getEdits());
556
- const sentLines = verdict === 'notes' ? describeEditsNow() : [];
557
- let saved;
558
- const what = verdict === 'approved' ? 'Your approval' : 'Your send back';
559
- let res;
560
- try {
561
- res = await fetch(reviewUrl(), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
562
- } catch {
563
- // No answer at all: offline, or the server is not there. Said so, not as a server's error; the note and the edits are kept, and it says it was not sent
564
- ui.busy = false;
565
- ui.message = notSentWords(what);
566
- paint();
567
- return false;
568
- }
569
- try {
570
- let answer = null;
571
- try { answer = await res.json(); } catch { /* no body */ }
572
- // A sign-in that ended answers 401 (or sends the page to the sign-in): said in words, and what was typed and edited is kept
573
- if (res.status === 401 || res.redirected) throw Object.assign(new Error(''), { status: 401 });
574
- if (!res.ok) throw Object.assign(new Error((answer && answer.error) || ''), { status: res.status });
575
- saved = answer;
576
- } catch (err) {
577
- ui.busy = false;
578
- ui.message = refusalWords(err.status || res.status, err.message);
579
- paint();
580
- // Refused because something changed (a push: 409) or another tab sent one just now (429): the bar is brought up to date
581
- if ((res.status === 409 || res.status === 429) && key === ui.key) { loadReview(key); loadFacts({ fresh: true }); }
582
- return false;
583
- }
584
- ui.busy = false;
585
- if (key !== ui.key) return true; // another proposal opened while it was being saved: it is saved, the bar is not this one's any more
586
- ui.review = { verdict: saved.verdict, at: saved.at, current: saved.verdict === 'approved' };
587
- ui.hint = verdict === 'approved' ? editsHint(verdict, body.edits.length) : '';
588
- // The same approval stood already (another tab, or a send that was retried): the server posted nothing, and the page says so
589
- if (saved.posted === false) ui.hint = `It was approved already${saved.by ? ` by ${saved.by}` : ''}; nothing new was posted.`;
590
- forgetNote(key);
591
- if (verdict === 'notes' && sentLines.length) ui.sent = { key: `${saved.at}`, lines: sentLines };
592
- noteEl.value = '';
593
- const wasNoting = ui.noting;
594
- ui.noting = false;
595
- paint();
596
- // The buttons were busy while it posted, not `disabled`, so the focus stayed where it was. Approve keeps it (the status line, a live region,
597
- // says "Approved" once; moving the focus onto it would say it twice); when it was lost (Undo went with the hold) it goes back to Approve. Send back: the button that opened the note.
598
- const lost = !document.activeElement || document.activeElement === document.body || !document.activeElement.isConnected || document.activeElement.hidden;
599
- if (verdict === 'approved') { if (lost) button('approved')?.focus(); }
600
- else if (wasNoting || lost) button('notes')?.focus();
601
- if (hooks.reviewed) hooks.reviewed(); // what waits on you changed: the count is read again (spec 0010)
602
- refreshMockups(); // an approval covers the screens as they are now; a send back leaves them not reviewed
603
- if (verdict === 'notes') clearEdits(); // the edits went with the note; an approval keeps them, they are in the review
604
- loadFacts({ fresh: true }); // an approval can have started a landing: Cancel landing shows
605
- return true;
606
- }
607
-
608
- // ---------------------------------------------------------------------------
609
- // Wiring
610
- // ---------------------------------------------------------------------------
611
-
612
- /** Escape takes an open question back, or ends a hold, before anything else on the page hears it; a held key's repeats do nothing here */
613
- function onEscape(e) {
614
- // A key held down repeats: its repeats are not more decisions (Enter held on Approve would answer its own question, then undo the hold)
615
- if (e.repeat && (e.key === 'Enter' || e.key === ' ') && e.target && e.target.closest && e.target.closest('#review-decision [data-review], #review-decision [data-review-undo]')) { e.preventDefault(); e.stopPropagation(); return; }
616
- if (e.key !== 'Escape' || !ui.key) return;
617
- if (ui.hold) { e.stopPropagation(); e.preventDefault(); stopHold('escape'); return; }
618
- if (ui.asking) { e.stopPropagation(); e.preventDefault(); ui.asking = null; paint(); }
619
- }
620
-
621
- const onVisible = () => {
622
- if (document.visibilityState === 'hidden') { if (ui.hold) stopHold('hidden'); return; }
623
- readFactsAgain(5_000);
624
- };
13
+ import { refreshMockups } from './mockups.js';
14
+ export { FACTS_MS } from './pieces/decision.js';
15
+
16
+ // What the decision asks of the neighbours that are not on an instance yet, answered for the page's instance
17
+ const page = pageInstance();
18
+ page.on('whatif:edits', () => (page.state.whatIf ? getEdits() : []));
19
+ page.on('whatif:form', () => openFormInfo());
20
+ page.on('whatif:describe', () => (page.state.whatIf ? describeEditsNow() : []));
21
+ page.on('whatif:clear', () => clearEdits());
22
+ page.on('mockups:refresh', () => refreshMockups());
23
+ let stopEdits = null;
625
24
 
626
- /**
627
- * Wires the review to the proposal bar (main.js calls this once, after whatif.js is wired, so the controls come
628
- * in order). The bar keeps whatever hook was there before.
629
- */
25
+ /** Wires the what-if editor's edits to the decision (page.js calls this once the editor is started; the editor forgets its listeners when a test resets it) */
630
26
  export function initReview() {
631
- if (wired) return;
632
- wired = true;
633
- barBefore = hooks.bar;
634
- hooks.bar = (open) => {
635
- if (barBefore) barBefore(open);
636
- onBar(open);
637
- };
638
- if (typeof window !== 'undefined') {
639
- // Back online after a failed read: the reviews are read again (the same function each time, so it is added once)
640
- window.addEventListener('online', readOnline);
641
- window.addEventListener('offline', onOffline);
642
- window.addEventListener('focus', onFocus);
643
- window.addEventListener('pagehide', onPageHide);
644
- document.addEventListener('visibilitychange', onVisible);
645
- document.addEventListener('keydown', onEscape, true);
646
- }
647
- stopEdits = onEditsChange(() => { if (ui.hold) stopHold('edits'); paint(); });
648
- stopColumn = onReviewColumnPaint(paint);
649
- // "3 minutes ago" moves on without the bar being drawn again
650
- timer = setInterval(() => { if (ui.review) paint(); }, TICK_MS);
651
- factsTimer = setInterval(() => readFactsAgain(), FACTS_MS);
652
- onBar(!!state.proposal);
27
+ if (stopEdits) stopEdits();
28
+ stopEdits = onEditsChange(() => page.emit('whatif:edits-changed'));
29
+ pagePiece('decision');
653
30
  }
654
31
 
655
- let stopEdits = null;
656
- let stopColumn = null;
657
- const onOffline = () => { if (ui.hold) stopHold('offline'); };
658
- const onFocus = () => readFactsAgain(5_000);
659
- const onPageHide = () => { if (ui.hold) stopHold('closed', { quiet: true }); }; // the page is going: nothing was sent, and nothing will be
32
+ /** Approve or send back the open proposal, now (the hold is over; tests and scripts call this directly) */
33
+ export async function sendReview(verdict, frozen) { const p = pagePiece('decision'); return p ? p.sendReview(verdict, frozen) : false; }
34
+ export async function loadFacts(opts) { const p = pagePiece('decision'); if (p) await p.loadFacts(opts); }
660
35
 
661
- /** For tests: forget the page this was wired to, and use `clock` for the time shown */
36
+ /** For tests: the decision is made again for the page it was on, and uses `clock` for the time shown */
662
37
  export function resetReviewForTests(clock = () => Date.now()) {
663
- if (timer) clearInterval(timer);
664
- if (factsTimer) clearInterval(factsTimer);
665
- timer = null;
666
- factsTimer = null;
667
- if (ui.hold) { clearInterval(ui.hold.tick); clearTimeout(ui.hold.end); }
668
- if (wired) {
669
- hooks.bar = barBefore;
670
- if (typeof window !== 'undefined') {
671
- window.removeEventListener('online', readOnline);
672
- window.removeEventListener('offline', onOffline);
673
- window.removeEventListener('focus', onFocus);
674
- window.removeEventListener('pagehide', onPageHide);
675
- document.removeEventListener('visibilitychange', onVisible);
676
- document.removeEventListener('keydown', onEscape, true);
677
- }
678
- if (stopEdits) stopEdits();
679
- if (stopColumn) stopColumn();
680
- }
681
- wired = false;
682
- root = null;
683
- now = clock;
684
- try { for (const k of Object.keys(sessionStorage)) if (k.startsWith(NOTE_KEY)) sessionStorage.removeItem(k); } catch { /* none */ }
685
- Object.assign(ui, { key: null, reviewable: false, review: null, loadFailed: false, busy: false, noting: false, message: '', hint: '', facts: null, factsState: 'loading', factsAt: 0, asking: null, hold: null, sent: null });
38
+ try { for (const k of Object.keys(sessionStorage)) if (k.startsWith('cornfield.reviewNote.')) sessionStorage.removeItem(k); } catch { /* none */ }
39
+ setPagePieceOptions('decision', { now: clock });
686
40
  }