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