@popcorn245/cornfield 0.40.0 → 0.42.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.
@@ -21,20 +21,38 @@
21
21
  * in the comment. Nothing here uses `alert`: every refusal and failure is a line on the bar.
22
22
  *
23
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.
24
34
  */
25
35
 
26
36
  import { state } from './state.js';
27
37
  import { expandSheet, isPhone } from './sheets.js';
28
38
  import { hooks } from './proposal.js';
29
39
  import { refreshMockups } from './mockups.js';
30
- import { getEdits, clearEdits } from './whatif.js';
31
- import { reviewParts, sendBackProblem, reviewBody, editsHint, isReviewable, NOT_ON_A_PR } from './review-model.js';
40
+ 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';
32
48
  import { t } from './strings.js';
33
49
  import { isOffline, notSentWords } from './connection.js';
34
50
 
35
51
  const $ = (id) => document.getElementById(id);
36
52
 
37
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;
38
56
 
39
57
  /** What is shown: the review of the proposal that is open, and the lines under the buttons */
40
58
  const ui = {
@@ -46,22 +64,32 @@ const ui = {
46
64
  noting: false, // the note field is open (Send back was pressed)
47
65
  message: '', // an inline refusal or failure
48
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)
49
73
  };
50
74
 
51
75
  let root = null;
52
76
  let wired = false;
53
77
  let barBefore = null; // the hook that was on the bar before this one
54
78
  let timer = null;
79
+ let factsTimer = null;
55
80
  let now = () => Date.now();
56
81
 
57
82
  const slugOf = () => state.proposalSlug || null;
58
83
  const keyOf = () => (state.proposal && slugOf() ? `${state.proposalSource || ''}/${slugOf()}` : null);
59
- const reviewUrl = () => `/proposals/${encodeURIComponent(slugOf())}/review${state.proposalSource ? `?source=${encodeURIComponent(state.proposalSource)}` : ''}`;
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' : ''}`;
60
87
  const q = (sel) => (root ? root.querySelector(sel) : null);
61
88
  /** The decision's buttons, in the review column's foot: Send back and Approve (index.html) */
62
89
  const button = (verdict) => document.querySelector(`#review-decision [data-review="${verdict}"]`);
90
+ const undoButton = () => document.querySelector('#review-decision [data-review-undo]');
63
91
 
64
- /** The status line, the note field and the lines under them; 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" */
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" */
65
93
  function mount() {
66
94
  const body = $('proposal-body');
67
95
  if (!body) return null;
@@ -75,6 +103,7 @@ function mount() {
75
103
  <div class="hx-review-form" id="review-form" data-review-form hidden>
76
104
  <label class="hx-review-label" for="review-note" data-corn="review-label"></label>
77
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>
78
107
  <div class="hx-review-row">
79
108
  <button type="button" class="hx-btn hx-btn--quiet" data-review-cancel data-corn-kind="quiet">Cancel</button>
80
109
  </div>
@@ -82,20 +111,53 @@ function mount() {
82
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>
83
112
  <p class="hx-review-msg" data-review-msg role="alert" hidden></p>
84
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>
85
120
  `;
86
121
  // The words are set as text and attributes, never parsed as HTML (a brand's `strings`, explorer/strings.js)
87
122
  q('.hx-review-label').textContent = t('reviewNoteLabel');
88
123
  q('#review-note').setAttribute('placeholder', t('reviewNotePlaceholder'));
124
+ q('[data-review-cancel-landing]').textContent = t('cancelLanding');
89
125
  // In the decision, the column's foot: the status and the note above Send back and Approve
90
126
  const actions = document.querySelector('#review-decision .hx-proposal-actions');
91
- if (actions) actions.before(root); else body.prepend(root);
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 (explorer.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);
92
143
  ($('review-decision') || $('proposal-bar') || root).addEventListener('click', onClick);
93
- root.addEventListener('input', () => { if (ui.message) { ui.message = ''; paint(); } });
94
- root.addEventListener('keydown', (e) => { if (e.key === 'Escape' && ui.noting) { e.stopPropagation(); closeNote(); } });
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(); } });
95
149
  }
96
150
  return root;
97
151
  }
98
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
+
99
161
  /** Everything the review shows, from `ui` */
100
162
  function paint() {
101
163
  if (!root) return;
@@ -110,29 +172,81 @@ function paint() {
110
172
  const failed = q('[data-review-loadfail]');
111
173
  failed.hidden = !ui.loadFailed;
112
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.` : '';
113
- // Off for good (not a spec PR's copy) is `disabled`, and the reason is the line next to it, which the buttons point at. While a review is being posted the button
114
- // only says it is busy (`aria-disabled`): a `disabled` button drops the focus to the page.
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';
115
200
  for (const btn of document.querySelectorAll('#review-decision [data-review]')) {
116
- btn.disabled = !ui.reviewable;
117
- if (ui.busy) btn.setAttribute('aria-disabled', 'true'); else btn.removeAttribute('aria-disabled');
118
- if (!ui.reviewable && ui.key) btn.setAttribute('aria-describedby', 'review-hint'); else btn.removeAttribute('aria-describedby');
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');
119
209
  }
120
- const approve = button('approved');
121
- if (approve) approve.textContent = t('approve');
122
- const sendBack = button('notes');
123
- if (sendBack) {
124
- sendBack.textContent = ui.noting ? t('sendBackWithNote') : t('sendBack');
125
- sendBack.setAttribute('aria-expanded', String(ui.noting));
126
- sendBack.setAttribute('aria-controls', 'review-form');
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';
127
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;
128
224
  q('[data-review-form]').hidden = !ui.noting;
129
- q('[data-review-cancel]').disabled = ui.busy;
130
- q('#review-note').disabled = !ui.reviewable;
131
- for (const [sel, text] of [['[data-review-msg]', ui.message], ['[data-review-hint]', ui.reviewable ? ui.hint : ui.key ? NOT_ON_A_PR : '']]) {
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 : '']]) {
132
230
  const el = q(sel);
133
231
  el.hidden = !text;
134
232
  el.textContent = text;
135
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.`;
136
250
  }
137
251
 
138
252
  /** Send back was pressed: the note field opens and takes focus (on a phone the sheet opens to hold it) */
@@ -150,8 +264,10 @@ function openNote() {
150
264
  /** Cancel: the field closes, what was typed goes, and focus goes back to Send back */
151
265
  function closeNote() {
152
266
  ui.noting = false;
267
+ ui.asking = null;
153
268
  ui.message = '';
154
269
  q('#review-note').value = '';
270
+ forgetNote(ui.key);
155
271
  paint();
156
272
  const sendBack = button('notes');
157
273
  if (sendBack) sendBack.focus();
@@ -163,17 +279,77 @@ function onBar(open) {
163
279
  const key = open ? keyOf() : null;
164
280
  root.hidden = !key;
165
281
  if (key === ui.key) { paint(); return; }
282
+ if (ui.hold) stopHold(open ? 'other' : 'closed', { quiet: false });
166
283
  ui.key = key;
167
284
  ui.reviewable = !!key && isReviewable(state.proposalSource);
168
285
  ui.review = null;
169
286
  ui.loadFailed = false;
170
287
  ui.busy = false;
171
288
  ui.noting = false;
289
+ ui.asking = null;
290
+ ui.sent = null;
291
+ ui.facts = null;
292
+ ui.factsState = ui.reviewable ? 'loading' : 'ready';
172
293
  ui.message = ui.hint = '';
173
294
  const note = q('#review-note');
174
- if (note) note.value = '';
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;
175
299
  paint();
176
- if (key && ui.reviewable) loadReview(key);
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();
177
353
  }
178
354
 
179
355
  /** The latest admin review on the proposal's PR, as the server reads it from the comments (none yet is a 404) */
@@ -196,11 +372,11 @@ async function loadReview(key) {
196
372
  try {
197
373
  const res = await fetch(reviewUrl(), { cache: 'no-store' });
198
374
  if (key !== ui.key) return; // another proposal has opened since
199
- if (res.status === 404) { readAgain(); return; } // none yet: the server says so with a 404
375
+ if (res.status === 404) { ui.review = null; readAgain(); return; } // none yet: the server says so with a 404
200
376
  if (!res.ok) throw new Error(`The server answered ${res.status}.`);
201
377
  const found = await res.json();
202
378
  if (key !== ui.key) return;
203
- if (found && typeof found.verdict === 'string') ui.review = { verdict: found.verdict, at: found.at };
379
+ if (found && typeof found.verdict === 'string') ui.review = { verdict: found.verdict, at: found.at, current: found.current === true };
204
380
  readAgain();
205
381
  } catch {
206
382
  // Not "no review": the read failed, so the bar says it could not look (with Retry), and the buttons stay as they were
@@ -208,27 +384,160 @@ async function loadReview(key) {
208
384
  }
209
385
  }
210
386
 
387
+ // ---------------------------------------------------------------------------
388
+ // The presses
389
+ // ---------------------------------------------------------------------------
390
+
211
391
  function onClick(e) {
212
- if (ui.busy || !e.target.closest) return;
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; }
213
399
  if (e.target.closest('[data-review-cancel]')) { closeNote(); return; }
214
400
  if (e.target.closest('[data-review-retry]')) { q('[data-review-loadfail-text]').textContent = 'Reading the reviews again …'; loadReview(ui.key); return; }
215
401
  const btn = e.target.closest('[data-review]');
216
- if (!btn || btn.disabled) return;
217
- if (btn.dataset.review === 'notes' && !ui.noting) openNote(); // the first press opens the field, the second sends
218
- else sendReview(btn.dataset.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();
219
527
  }
220
528
 
221
529
  /**
222
- * Approve or send back the open proposal.
530
+ * Approve or send back the open proposal, now (the hold is over; tests and scripts call this directly).
223
531
  * @param {'approved'|'notes'} verdict
532
+ * @param {{ body?: object }} [frozen] the body held at the press; without it, what is on screen now
224
533
  * @returns {Promise<boolean>} whether the server took the review
225
534
  */
226
- export async function sendReview(verdict) {
535
+ export async function sendReview(verdict, frozen = {}) {
227
536
  if (!state.proposal || !slugOf() || !mount() || !ui.reviewable) return false;
228
537
  const noteEl = q('#review-note');
229
538
  const note = verdict === 'notes' ? noteEl.value : ''; // an approval takes no note
230
539
  ui.hint = '';
231
- if (verdict === 'notes') {
540
+ if (verdict === 'notes' && !frozen.body) {
232
541
  const problem = sendBackProblem(note);
233
542
  if (problem) {
234
543
  ui.message = problem;
@@ -243,7 +552,8 @@ export async function sendReview(verdict) {
243
552
  ui.busy = true;
244
553
  paint();
245
554
  const key = ui.key;
246
- const body = reviewBody(verdict, note, getEdits());
555
+ const body = frozen.body || reviewBody(verdict, note, getEdits());
556
+ const sentLines = verdict === 'notes' ? describeEditsNow() : [];
247
557
  let saved;
248
558
  const what = verdict === 'approved' ? 'Your approval' : 'Your send back';
249
559
  let res;
@@ -259,33 +569,60 @@ export async function sendReview(verdict) {
259
569
  try {
260
570
  let answer = null;
261
571
  try { answer = await res.json(); } catch { /* no body */ }
262
- if (!res.ok) throw new Error((answer && answer.error) || `The server answered ${res.status}.`);
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 });
263
575
  saved = answer;
264
576
  } catch (err) {
265
577
  ui.busy = false;
266
- ui.message = `The review was not posted. ${err.message || String(err)}`;
578
+ ui.message = refusalWords(err.status || res.status, err.message);
267
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 }); }
268
582
  return false;
269
583
  }
270
584
  ui.busy = false;
271
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
272
- ui.review = { verdict: saved.verdict, at: saved.at };
273
- ui.hint = editsHint(verdict, body.edits.length);
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 };
274
592
  noteEl.value = '';
275
593
  const wasNoting = ui.noting;
276
594
  ui.noting = false;
277
595
  paint();
278
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,
279
- // says "Approved" once; moving the focus onto it would say it twice); when it was lost it goes back to Approve. Send back: the button that opened the note.
280
- const lost = !document.activeElement || document.activeElement === document.body || !document.activeElement.isConnected;
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;
281
599
  if (verdict === 'approved') { if (lost) button('approved')?.focus(); }
282
600
  else if (wasNoting || lost) button('notes')?.focus();
283
601
  if (hooks.reviewed) hooks.reviewed(); // what waits on you changed: the count is read again (spec 0010)
284
602
  refreshMockups(); // an approval covers the screens as they are now; a send back leaves them not reviewed
285
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
286
605
  return true;
287
606
  }
288
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
+ };
625
+
289
626
  /**
290
627
  * Wires the review to the proposal bar (main.js calls this once, after whatif.js is wired, so the controls come
291
628
  * in order). The bar keeps whatever hook was there before.
@@ -298,20 +635,52 @@ export function initReview() {
298
635
  if (barBefore) barBefore(open);
299
636
  onBar(open);
300
637
  };
301
- // Back online after a failed read: the reviews are read again (the same function each time, so it is added once)
302
- if (typeof window !== 'undefined') window.addEventListener('online', readOnline);
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);
303
649
  // "3 minutes ago" moves on without the bar being drawn again
304
650
  timer = setInterval(() => { if (ui.review) paint(); }, TICK_MS);
651
+ factsTimer = setInterval(() => readFactsAgain(), FACTS_MS);
305
652
  onBar(!!state.proposal);
306
653
  }
307
654
 
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
660
+
308
661
  /** For tests: forget the page this was wired to, and use `clock` for the time shown */
309
662
  export function resetReviewForTests(clock = () => Date.now()) {
310
663
  if (timer) clearInterval(timer);
664
+ if (factsTimer) clearInterval(factsTimer);
311
665
  timer = null;
312
- if (wired) hooks.bar = barBefore;
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
+ }
313
681
  wired = false;
314
682
  root = null;
315
683
  now = clock;
316
- Object.assign(ui, { key: null, reviewable: false, review: null, loadFailed: false, busy: false, noting: false, message: '', hint: '' });
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 });
317
686
  }