pi-odd-worktree 3.9.2 → 3.11.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/LICENSE +21 -0
  2. package/README.md +68 -40
  3. package/extensions/odd-worktree-tools.ts +1028 -17
  4. package/lib/gh-issues.js +65 -10
  5. package/lib/gh-prs.js +2011 -0
  6. package/lib/issue-preview.js +70 -4
  7. package/lib/issues-cache-store.js +4 -1
  8. package/lib/issues-section.js +346 -23
  9. package/lib/issues-view.js +116 -5
  10. package/lib/pr-preview.js +353 -0
  11. package/lib/prs-rail-store.js +317 -0
  12. package/lib/prs-view.js +2896 -0
  13. package/lib/user-prompt-card.js +477 -0
  14. package/package.json +1 -1
  15. package/tools/files-bridge.test.js +2 -2
  16. package/tools/files-command.test.js +1 -1
  17. package/tools/fixtures/gh-pr-connection-page.json +84 -0
  18. package/tools/fixtures/gh-pr-metadata.json +29 -0
  19. package/tools/fixtures/gh-pr-rail.json +61 -0
  20. package/tools/fixtures/gh-pr-search-page.json +82 -0
  21. package/tools/fixtures/gh-pr-view.json +159 -0
  22. package/tools/gh-issues.test.js +4 -2
  23. package/tools/gh-prs.test.js +1828 -0
  24. package/tools/issue-preview.test.js +119 -0
  25. package/tools/issues-cache-store.test.js +2 -2
  26. package/tools/issues-command.test.js +10 -3
  27. package/tools/issues-open-guard.test.js +15 -0
  28. package/tools/issues-section.test.js +618 -9
  29. package/tools/issues-view.test.js +297 -0
  30. package/tools/package-surface.test.js +21 -5
  31. package/tools/pr-preview.test.js +281 -0
  32. package/tools/prs-command.test.js +1280 -0
  33. package/tools/prs-rail-store.test.js +343 -0
  34. package/tools/prs-t10-safety.test.js +326 -0
  35. package/tools/prs-t12-safety.test.js +348 -0
  36. package/tools/prs-t13-independent.test.js +378 -0
  37. package/tools/prs-t14-safety.test.js +340 -0
  38. package/tools/prs-t15-independent.test.js +259 -0
  39. package/tools/prs-t18-safety.test.js +217 -0
  40. package/tools/prs-t7-safety.test.js +127 -0
  41. package/tools/prs-view.test.js +1462 -0
  42. package/tools/user-prompt-card.test.js +963 -0
@@ -0,0 +1,2896 @@
1
+ 'use strict';
2
+ // Pull request viewer component (prs-panel T2, S1-S3, S6-S7): the `/issues`
3
+ // reader cloned for pull requests — a framed full-screen overlay with three
4
+ // scoped tabs (`My Pull Request` / `Needs My Review` / `Involved`), a live
5
+ // search box, ONE continuously scrolling list, a scrolling pull request pane,
6
+ // and the actions S2 asks for (comment, labels, assignees as a toggle, close,
7
+ // merge with its own confirmation step, the Development relation as a
8
+ // linked-issues editor, open on the web, insert).
9
+ //
10
+ // PURE: no `gh`, no registry, no files. Rows arrive through
11
+ // `loadPullRequestPage({bucketId, cursor, limit, query})` — the same server-page
12
+ // seam the issues reader uses, answering `{ok, rows, totalCount, hasMore,
13
+ // cursor}` — the detail through `loadPullRequest(number)`, repository labels
14
+ // through `loadLabels()` and assignable users through `loadAssignees()`, each on
15
+ // the editor's first use. Writes go through `actions`. Every failure is shown
16
+ // and keeps the local state unchanged. Host contract:
17
+ // { render(width), handleInput(data), handleMouse(event), invalidate() } plus
18
+ // `state`.
19
+ //
20
+ // S2 capability policy, cloned from issues and fail-closed: the pull request
21
+ // detail carries `permissions: {canEditLabels, canCreateLabels,
22
+ // canEditAssignees, canClosePullRequests, canMerge, canEditLinkedIssues}` and
23
+ // anything but a literal `true` is false — no footer hint, no editor, no write.
24
+ // `canMerge` additionally needs a non-draft pull request and at least one merge
25
+ // method the repository allows (`mergeMethods`), because GitHub refuses both.
26
+ // Commenting needs no capability beyond read access. The permissions may also
27
+ // arrive on the seam's own answer or, for a repository-wide role, as
28
+ // `options.permissions`; the first one present wins and the rest fail closed.
29
+ // A rejected save stays visible with the draft and its toggles intact, and a
30
+ // successful one refetches the detail through `loadPullRequest(number,
31
+ // {refresh:true})` instead of trusting the cache.
32
+ //
33
+ // S1: the three scoped buckets are the tabs; `all` is a SHORTCUT, not a fourth
34
+ // tab — `g` reads it the first time it is entered (the repository connection)
35
+ // and the same key returns to the tab the reader came from, reusing the rows and
36
+ // the scroll place that tab already had.
37
+ //
38
+ // S3: search is a SERVER search. Every page request carries `query`, a settled
39
+ // query is read after a short injected debounce, and the answer is never
40
+ // re-filtered as literal title text. The pane scrolls with the shared preview
41
+ // bindings (`lib/preview-scroll-keys.js`) and every key hint paints through
42
+ // `lib/tui-paint.js`.
43
+ //
44
+ // S6: the pane publishes the cell range of every linked issue number
45
+ // (`lib/pr-preview.js` `options.links`), and a click inside one calls
46
+ // `actions.openLinked({kind: 'issue', number})` for exactly that number — never
47
+ // for the whole line.
48
+ //
49
+ // S7: `Enter` in list mode is INSERT: it calls `actions.insert('PR #N')` and
50
+ // closes the panel. Inside the search box, the editors and the confirm steps the
51
+ // same key keeps the meaning it has there.
52
+ //
53
+ // S10 (issues, kept): every write records and paints its busy state BEFORE the
54
+ // action is invoked and ignores every key until it settles, so a second save,
55
+ // a navigation or typing can never race it.
56
+
57
+ const layout = require('./view-layout.js');
58
+ const scrollKeys = require('./preview-scroll-keys.js');
59
+ const palette = require('./tui-paint.js');
60
+ const paint = palette.paint;
61
+ const emphasize = palette.emphasize;
62
+ const highlight = palette.highlight;
63
+ const { pullRequestDetailLines, defaultWrapCache } = require('./pr-preview.js');
64
+
65
+ const CARD_PADDING = layout.CARD_PADDING;
66
+ const MIN_WIDTH = 24;
67
+ // S3: a remote search is debounced, so a burst of typing costs ONE server read
68
+ // for the query it settles on. The clock is injected (`scheduleQuery` /
69
+ // `cancelSchedule`), so no expectation depends on wall-clock timing.
70
+ const QUERY_DEBOUNCE_MS = 180;
71
+ // S1: the opening selection reads at most this many pages of its bucket, so a
72
+ // bucket with thousands of rows can never loop the panel's open.
73
+ const INITIAL_SELECTION_PAGE_LIMIT = 5;
74
+ // The frame's fixed chrome: top rule, search row, tab row, note row. The body
75
+ // starts below it, which is also where a click's `y` lands.
76
+ const BODY_TOP = 4;
77
+ // S2 (D22): the shortest frame a confirmation may act on. Below this the chrome
78
+ // (top rule, search, tabs, note), one body row, the footer and the bottom rule
79
+ // do not fit, so the step's own line cannot be given a row at all.
80
+ const MIN_STEP_ROWS = BODY_TOP + 3;
81
+ // `│ ` + the list column + ` ` + `│` + ` ` before the pane's first cell.
82
+ const PANE_LEFT = 5;
83
+
84
+ // The buckets the server seam reads from unless the caller passes its own
85
+ // `pages` metadata. `all` keeps its slot in `state.page` but never in the tab
86
+ // bar: it is the lazy view the `g` shortcut owns (S1).
87
+ const DEFAULT_BUCKETS = [
88
+ { id: 'mine', label: 'My Pull Request' },
89
+ { id: 'review', label: 'Needs My Review' },
90
+ { id: 'involved', label: 'Involved' },
91
+ { id: 'all', label: 'All', lazy: true },
92
+ ];
93
+
94
+ // S1/D1: `g` teaches itself in the ONE legend row. Outside the lazy view it
95
+ // reads `all prs`; inside it, the same key reads `related prs`, because there it
96
+ // goes back.
97
+ const SHORTCUT_HINT = {
98
+ key: 'g',
99
+ text: 'g all prs',
100
+ short: 'g',
101
+ priority: 38,
102
+ shortcut: true,
103
+ };
104
+
105
+ function shortcutHint(insideLazy) {
106
+ return {
107
+ key: SHORTCUT_HINT.key,
108
+ text: insideLazy ? 'g related prs' : SHORTCUT_HINT.text,
109
+ short: SHORTCUT_HINT.short,
110
+ priority: SHORTCUT_HINT.priority,
111
+ };
112
+ }
113
+
114
+ // S2/S16: an entry that carries `requires` leaves the row whenever that
115
+ // capability is not confirmed true, and `needsIssue` leaves it whenever no
116
+ // loaded pull request is under the cursor — so a hint can never advertise a key
117
+ // the handler refuses.
118
+ const FOOTER_KEYS = [
119
+ { key: '↑↓', text: '↑↓ move', short: '↑↓ move', priority: 90 },
120
+ { key: '←→', text: '←→ bucket', short: '←→', priority: 62 },
121
+ { key: 'l', text: 'l labels', short: 'l', priority: 50, requires: 'canEditLabels', needsIssue: true },
122
+ { key: 'a', text: 'a assign', short: 'a', priority: 48, requires: 'canEditAssignees', needsIssue: true },
123
+ { key: 'c', text: 'c comment', short: 'c', priority: 45, needsIssue: true },
124
+ { key: 'i', text: 'i linked', short: 'i', priority: 44, requires: 'canEditLinkedIssues', needsIssue: true },
125
+ { key: 'x', text: 'x close', short: 'x', priority: 40, requires: 'canClosePullRequests', needsIssue: true },
126
+ { key: 'm', text: 'm merge', short: 'm', priority: 42, requires: 'canMerge', needsIssue: true },
127
+ { key: 'o', text: 'o web', short: 'o', priority: 20, needsIssue: true },
128
+ // S7: Enter is INSERT here, and the legend says so.
129
+ { key: 'enter', text: 'enter insert', short: 'enter', priority: 36, needsIssue: true },
130
+ { key: 't', text: 't search', short: 't', priority: 35 },
131
+ SHORTCUT_HINT,
132
+ { key: 'esc', text: 'esc close', short: 'esc close', priority: 100 },
133
+ ];
134
+
135
+ // S13: while the search box holds the keyboard the footer names THAT
136
+ // interaction once, in the same slot.
137
+ const SEARCH_KEYS = [
138
+ { key: 'type', text: 'type to filter', short: 'type', priority: 30 },
139
+ { key: 'bksp', text: 'bksp edit', short: 'bksp', priority: 20 },
140
+ { key: 'del', text: 'del clear', short: 'del', priority: 50 },
141
+ { key: 'enter/esc', text: 'enter/esc keep', short: 'enter/esc', priority: 60 },
142
+ ];
143
+
144
+ // S10: a sub-mode's keys live on the ONE footer row while it holds the
145
+ // keyboard, and its pane title carries the sub-mode's name alone.
146
+ const LABEL_EDITOR_KEYS = [
147
+ { key: 'space', text: 'space toggle', short: 'space', priority: 70 },
148
+ { key: 'n', text: 'n new', short: 'n', priority: 60, needsCreate: true },
149
+ { key: 'ctrl+s', text: 'ctrl+s apply', short: 'ctrl+s', priority: 90 },
150
+ { key: 'esc', text: 'esc back', short: 'esc back', priority: 100 },
151
+ ];
152
+
153
+ const ASSIGNEE_EDITOR_KEYS = [
154
+ { key: 'space', text: 'space toggle', short: 'space', priority: 70 },
155
+ { key: 'ctrl+s', text: 'ctrl+s apply', short: 'ctrl+s', priority: 90 },
156
+ { key: 'esc', text: 'esc back', short: 'esc back', priority: 100 },
157
+ ];
158
+
159
+ const COMMENT_EDITOR_KEYS = [
160
+ { key: 'enter', text: 'enter newline', short: 'enter', priority: 70 },
161
+ { key: 'ctrl+s', text: 'ctrl+s post', short: 'ctrl+s', priority: 90 },
162
+ { key: 'esc', text: 'esc discard', short: 'esc discard', priority: 100 },
163
+ ];
164
+
165
+ const LABEL_CREATE_KEYS = [
166
+ { key: 'enter', text: 'enter add', short: 'enter', priority: 70 },
167
+ { key: 'esc', text: 'esc cancel', short: 'esc cancel', priority: 100 },
168
+ ];
169
+
170
+ const COMMENT_DISCARD_KEYS = [
171
+ { key: 'y', text: 'y discard', short: 'y', priority: 60 },
172
+ { key: 'n/esc', text: 'n/esc keep editing', short: 'n/esc', priority: 70 },
173
+ ];
174
+
175
+ // S2: the merge step. Only the allowed methods are ever offered, so its keys
176
+ // talk about the FIELD the reader is on and the one commit.
177
+ const MERGE_KEYS = [
178
+ { key: '↑↓', text: '↑↓ field', short: '↑↓', priority: 80 },
179
+ { key: '←→', text: '←→ method', short: '←→', priority: 78 },
180
+ { key: 'enter', text: 'enter select', short: 'enter', priority: 88 },
181
+ { key: 'ctrl+s', text: 'ctrl+s merge', short: 'ctrl+s', priority: 90 },
182
+ { key: 'esc', text: 'esc cancel', short: 'esc cancel', priority: 100 },
183
+ ];
184
+
185
+ // S2: the Development relation editor. GitHub has no mutation for that panel,
186
+ // so the client rewrites the `Closes #N` lines of the body; this step only
187
+ // collects the delta.
188
+ const LINKED_EDITOR_KEYS = [
189
+ { key: 'space', text: 'space toggle', short: 'space', priority: 70 },
190
+ { key: 'n', text: 'n add', short: 'n', priority: 60 },
191
+ { key: 'ctrl+s', text: 'ctrl+s apply', short: 'ctrl+s', priority: 90 },
192
+ { key: 'esc', text: 'esc back', short: 'esc back', priority: 100 },
193
+ ];
194
+
195
+ const LINKED_ADD_KEYS = [
196
+ { key: 'enter', text: 'enter add', short: 'enter', priority: 70 },
197
+ { key: 'esc', text: 'esc cancel', short: 'esc cancel', priority: 100 },
198
+ ];
199
+
200
+ // S11: while an editor's own list is still in flight its handlers accept ONE
201
+ // key — the exit — so that is the only key the footer may offer then.
202
+ const BACK_KEYS = [
203
+ { key: 'esc', text: 'esc back', short: 'esc back', priority: 100 },
204
+ ];
205
+
206
+ // Printable paging keys must not fall through to lowercase list selection.
207
+ const SHIFTED_TWINS = new Set(['j', 'k']);
208
+
209
+ // The methods GitHub allows, in the order the confirmation offers them. A
210
+ // method the repository did not allow never appears and is never sent.
211
+ const MERGE_METHODS = ['merge', 'squash', 'rebase'];
212
+
213
+ // S2: one capability contract for every editor and both write keys. Only a
214
+ // literal `true` confirms a permission, so a missing field, an unknown string
215
+ // or a truthy non-boolean all read as "not permitted" (GitHub stays the final
216
+ // authority).
217
+ const NO_PERMISSIONS = {
218
+ canEditLabels: false,
219
+ canCreateLabels: false,
220
+ canEditAssignees: false,
221
+ canClosePullRequests: false,
222
+ canMerge: false,
223
+ canEditLinkedIssues: false,
224
+ };
225
+
226
+ // One page entry, whatever the source: eager `pages` and every server answer
227
+ // pass through here so both paths share one shape.
228
+ function mapPage(page, at) {
229
+ const rows = Array.isArray(page && page.rows)
230
+ ? page.rows
231
+ : (Array.isArray(page && page.pullRequests) ? page.pullRequests : null);
232
+ return {
233
+ id: page && page.id != null ? String(page.id) : `p${at}`,
234
+ label: page && page.label ? String(page.label) : `Page ${at + 1}`,
235
+ rows: rows === null ? null : rows.slice(),
236
+ total: page && Number.isFinite(Number(page.total)) ? Number(page.total) : null,
237
+ truncated: !!(page && page.truncated),
238
+ lazy: !!(page && page.lazy === true),
239
+ };
240
+ }
241
+
242
+ function stripAnsi(text) {
243
+ return String(text).replace(/\x1b\[[0-9;]*m/g, '');
244
+ }
245
+
246
+ function measure(helpers, text) {
247
+ try {
248
+ if (helpers && typeof helpers.visibleWidth === 'function') {
249
+ const size = Number(helpers.visibleWidth(text));
250
+ if (Number.isFinite(size)) return size;
251
+ }
252
+ } catch {
253
+ // Fall through to the plain count.
254
+ }
255
+ return [...stripAnsi(text)].length;
256
+ }
257
+
258
+ function fit(helpers, text, width) {
259
+ const clean = String(text).split('\n')[0] ?? '';
260
+ if (measure(helpers, clean) <= width) return clean;
261
+ try {
262
+ if (helpers && typeof helpers.truncateToWidth === 'function') {
263
+ const cut = helpers.truncateToWidth(clean, width, '…');
264
+ if (typeof cut === 'string') return cut;
265
+ }
266
+ } catch {
267
+ // Fall through to the plain slice.
268
+ }
269
+ const chars = [...clean];
270
+ return chars.length > width ? chars.slice(0, Math.max(0, width - 1)).join('') + '…' : clean;
271
+ }
272
+
273
+ function pad(helpers, text, width) {
274
+ const clipped = fit(helpers, text, width);
275
+ return clipped + ' '.repeat(Math.max(0, width - measure(helpers, clipped)));
276
+ }
277
+
278
+ // The last cells of a query that fit `room`, prefixed with an ellipsis when
279
+ // something was dropped. Only the DISPLAY is shortened — the stored query keeps
280
+ // every character — and keeping the tail means the caret stays on screen.
281
+ function tailOf(helpers, text, room) {
282
+ const chars = [...String(text ?? '')];
283
+ if (room <= 0) return '';
284
+ if (measure(helpers, chars.join('')) <= room) return chars.join('');
285
+ let cut = '';
286
+ for (let at = chars.length - 1; at >= 0; at -= 1) {
287
+ const next = chars[at] + cut;
288
+ if (measure(helpers, `…${next}`) > room) break;
289
+ cut = next;
290
+ }
291
+ return cut === '' ? '…' : `…${cut}`;
292
+ }
293
+
294
+ function keyMatches(helpers, data, names) {
295
+ for (const name of names) {
296
+ try {
297
+ if (helpers && typeof helpers.matchesKey === 'function' && helpers.matchesKey(data, name)) return true;
298
+ } catch {
299
+ // A throwing matcher never matches; the string fallback decides below.
300
+ }
301
+ }
302
+ const text = typeof data === 'string' ? data : (data && (data.name || data.key)) || '';
303
+ return names.some((name) => sameKeyName(text, name));
304
+ }
305
+
306
+ function sameKeyName(left, right) {
307
+ const a = String(left);
308
+ const b = String(right);
309
+ if (a === b) return true;
310
+ const shiftedLetter = (text) => text.length === 1 && text >= 'A' && text <= 'Z';
311
+ if (shiftedLetter(a) && !shiftedLetter(b) && SHIFTED_TWINS.has(b.toLowerCase())) return false;
312
+ return a.toLowerCase() === b.toLowerCase();
313
+ }
314
+
315
+ function isKeyRelease(helpers, data) {
316
+ try {
317
+ if (helpers && typeof helpers.isKeyRelease === 'function') return helpers.isKeyRelease(data) === true;
318
+ } catch {
319
+ // A throwing classifier never releases; normal handling follows.
320
+ }
321
+ return false;
322
+ }
323
+
324
+ function labelName(label) {
325
+ if (typeof label === 'string') return label;
326
+ if (label && typeof label.name === 'string') return label.name;
327
+ return '';
328
+ }
329
+
330
+ function assigneeName(entry) {
331
+ if (typeof entry === 'string') return entry;
332
+ if (entry && typeof entry.login === 'string') return entry.login;
333
+ return '';
334
+ }
335
+
336
+ // One assignable user as the editor lists it: a login plus the display name
337
+ // GitHub may or may not carry.
338
+ function assigneeOption(user) {
339
+ if (typeof user === 'string') return user === '' ? null : { login: user, name: '' };
340
+ const login = user && typeof user.login === 'string' ? user.login : '';
341
+ if (login === '') return null;
342
+ return { login, name: user && typeof user.name === 'string' ? user.name : '' };
343
+ }
344
+
345
+ function wrapText(text, width) {
346
+ const out = [];
347
+ for (const paragraph of String(text ?? '').split('\n')) {
348
+ if (paragraph.trim() === '') {
349
+ out.push('');
350
+ continue;
351
+ }
352
+ const words = paragraph.split(/\s+/).filter(Boolean);
353
+ let line = '';
354
+ for (const word of words) {
355
+ if (line === '') {
356
+ line = word.length > width ? word.slice(0, width) : word;
357
+ } else if ((line + ' ' + word).length <= width) {
358
+ line += ' ' + word;
359
+ } else {
360
+ out.push(line);
361
+ line = word.length > width ? word.slice(0, width) : word;
362
+ }
363
+ }
364
+ out.push(line);
365
+ }
366
+ return out.length === 0 ? [''] : out;
367
+ }
368
+
369
+ // The local filter of the EAGER path only. The server seam answers its query
370
+ // itself, so a server answer is never re-filtered as literal title text.
371
+ function matchesQuery(row, query) {
372
+ const tokens = String(query || '').split(/\s+/).map((t) => t.trim()).filter(Boolean);
373
+ if (tokens.length === 0) return true;
374
+ const title = String(row.title || '').toLowerCase();
375
+ const author = String(row.author || '').toLowerCase();
376
+ const number = String(row.number ?? '');
377
+ return tokens.every((token) => {
378
+ if (token.startsWith('@')) {
379
+ const want = token.slice(1).toLowerCase();
380
+ return want === '' || author.includes(want);
381
+ }
382
+ if (token.startsWith('#')) {
383
+ const want = token.slice(1);
384
+ return want === '' || number.includes(want);
385
+ }
386
+ return title.includes(token.toLowerCase());
387
+ });
388
+ }
389
+
390
+ function normalizeDetail(result) {
391
+ if (!result || typeof result !== 'object') return { ok: false, error: 'pull request unreadable' };
392
+ if (result.ok === true && result.pullRequest && typeof result.pullRequest === 'object') {
393
+ return {
394
+ ok: true,
395
+ pullRequest: result.pullRequest,
396
+ comments: Array.isArray(result.comments) ? result.comments : [],
397
+ permissions: result.permissions && typeof result.permissions === 'object' ? result.permissions : null,
398
+ };
399
+ }
400
+ if (result.ok === false) return { ok: false, error: String(result.error || 'pull request unreadable') };
401
+ return { ok: false, error: 'pull request unreadable' };
402
+ }
403
+
404
+ // S2: the methods the repository actually allows, in the order the merge step
405
+ // offers them. Anything but a literal `true` allows nothing.
406
+ function allowedMergeMethods(pullRequest) {
407
+ const raw = pullRequest && typeof pullRequest.mergeMethods === 'object' && pullRequest.mergeMethods
408
+ ? pullRequest.mergeMethods
409
+ : {};
410
+ return MERGE_METHODS.filter((method) => raw[method] === true);
411
+ }
412
+
413
+ // S2: GitHub's own proposal for each allowed method, which the confirmation
414
+ // starts from and the reader may edit. A rebase merge carries neither field.
415
+ function mergeTextDefaults(pullRequest) {
416
+ const out = {};
417
+ const methods = pullRequest && pullRequest.mergeDefaults && typeof pullRequest.mergeDefaults === 'object'
418
+ ? pullRequest.mergeDefaults
419
+ : {};
420
+ for (const method of allowedMergeMethods(pullRequest)) {
421
+ const raw = methods[method] && typeof methods[method] === 'object' ? methods[method] : {};
422
+ out[method] = {
423
+ subject: typeof raw.subject === 'string' ? raw.subject : '',
424
+ body: typeof raw.body === 'string' ? raw.body : '',
425
+ };
426
+ }
427
+ return out;
428
+ }
429
+
430
+ function capabilityMap(pullRequest, fromResult, viewWide) {
431
+ const own = pullRequest && typeof pullRequest.permissions === 'object' && pullRequest.permissions !== null
432
+ ? pullRequest.permissions
433
+ : null;
434
+ const raw = own
435
+ || (fromResult && typeof fromResult === 'object' ? fromResult : null)
436
+ || (viewWide && typeof viewWide === 'object' ? viewWide : null);
437
+ const confirmed = (name) => Boolean(raw && raw[name] === true);
438
+ const methods = allowedMergeMethods(pullRequest);
439
+ // S5/S6 (D7): a pull request outside `open` — merged, closed — is READ ONLY
440
+ // here. GitHub's state is final for the panel's writes, so a numbered open of
441
+ // one shows it with its state and offers no editor, close or merge at all.
442
+ const open = !pullRequest || typeof pullRequest !== 'object'
443
+ || String(pullRequest.state || 'open').toLowerCase() === 'open';
444
+ return {
445
+ canEditLabels: open && confirmed('canEditLabels'),
446
+ canCreateLabels: open && confirmed('canCreateLabels'),
447
+ canEditAssignees: open && confirmed('canEditAssignees'),
448
+ canClosePullRequests: open && confirmed('canClosePullRequests'),
449
+ // S2: merging is the one capability with preconditions GitHub enforces on
450
+ // top of the repository role, so both are required here as well.
451
+ canMerge: open && confirmed('canMerge') && Boolean(pullRequest && typeof pullRequest === 'object')
452
+ && pullRequest.isDraft !== true && methods.length > 0,
453
+ canEditLinkedIssues: open && confirmed('canEditLinkedIssues'),
454
+ };
455
+ }
456
+
457
+ function createPrsView(options = {}) {
458
+ const {
459
+ helpers = null,
460
+ theme = null,
461
+ rowsAvailable = null,
462
+ requestRender = null,
463
+ done = null,
464
+ loadPullRequest = null,
465
+ loadPullRequestPage = null,
466
+ loadLabels = null,
467
+ loadAssignees = null,
468
+ permissions: viewPermissions = null,
469
+ actions = {},
470
+ scheduleQuery = null,
471
+ cancelSchedule = null,
472
+ } = options;
473
+
474
+ const pageLoaderFn = typeof loadPullRequestPage === 'function' ? loadPullRequestPage : null;
475
+ const serverMode = pageLoaderFn !== null;
476
+ const scheduleFn = typeof scheduleQuery === 'function' ? scheduleQuery : (fn, delay) => setTimeout(fn, delay);
477
+ const cancelFn = typeof cancelSchedule === 'function' ? cancelSchedule : (handle) => clearTimeout(handle);
478
+
479
+ let pages = Array.isArray(options.pages) && options.pages.length > 0
480
+ ? options.pages.map(mapPage)
481
+ : (serverMode
482
+ ? DEFAULT_BUCKETS.map((bucket, at) => mapPage({ id: bucket.id, label: bucket.label, rows: null, lazy: bucket.lazy === true }, at))
483
+ : [{ id: 'mine', label: 'My Pull Request', rows: null, total: null }]);
484
+
485
+ const initialBucketId = typeof options.initialBucket === 'string' ? options.initialBucket : null;
486
+ const initialNumber = Number.isFinite(Number(options.initialPullRequest)) && Number(options.initialPullRequest) > 0
487
+ ? Math.floor(Number(options.initialPullRequest))
488
+ : null;
489
+ const initialBucketFound = initialBucketId === null || pages.some((page) => page.id === initialBucketId);
490
+ const initialPageIndex = initialBucketId === null
491
+ ? 0
492
+ : Math.max(0, pages.findIndex((page) => page.id === initialBucketId));
493
+
494
+ // S1: one shot. The pending selection exists only for the OPENING read of the
495
+ // bucket the reader was opened on; it clears when it lands, misses, reaches
496
+ // its bound, or the reader presses a key.
497
+ let pendingSelection = initialNumber !== null && initialBucketFound
498
+ ? { number: initialNumber, bucketIndex: initialPageIndex, pagesRead: 0, triedFallback: false }
499
+ : null;
500
+ // S5/S6 (D7): the number a numbered open had to fetch outside every bucket.
501
+ let pinnedNumber = null;
502
+
503
+ const state = {
504
+ page: initialPageIndex,
505
+ index: 0,
506
+ // S1: while the reader is in the lazy view, the tab they came from.
507
+ allFrom: null,
508
+ listStart: 0,
509
+ scroll: 0,
510
+ query: '',
511
+ searching: false,
512
+ mode: 'list',
513
+ loading: serverMode,
514
+ loadError: null,
515
+ labelIndex: 0,
516
+ labelCreating: false,
517
+ createName: '',
518
+ assigneeIndex: 0,
519
+ commentText: '',
520
+ // S2 (D11): the pull request the composer was opened on, captured like the
521
+ // confirmations capture theirs.
522
+ commentNumber: null,
523
+ confirm: null,
524
+ discardAsk: false,
525
+ // S2: the field the merge confirmation has the focus on.
526
+ mergeField: 0,
527
+ saving: null,
528
+ searchPending: false,
529
+ };
530
+ let bodyRows = 1;
531
+ const prefetchBuckets = options.prefetchBuckets === true;
532
+ const details = new Map();
533
+ // S2/D25: how many detail reads each number has seen. Only the NEWEST read
534
+ // for a number may install its answer, and a save-time gate only decides on
535
+ // the newest one — an older positive answer can never revive a permission a
536
+ // later read revoked.
537
+ const detailSeq = new Map();
538
+ let actionError = null;
539
+ let notice = null;
540
+ let active = true;
541
+ let pageSeq = 0;
542
+ let listWidthCache = 20;
543
+ let scheduledQuery = null;
544
+ let labelsLoaded = false;
545
+ let labelsLoading = false;
546
+ let labelsError = null;
547
+ let repoLabels = Array.isArray(options.labels)
548
+ ? options.labels.map((label) => ({ name: labelName(label) })).filter((label) => label.name)
549
+ : [];
550
+ let labelDraft = null;
551
+ let assigneeDraft = null;
552
+ let assigneeUsers = [];
553
+ let assigneesLoaded = false;
554
+ let assigneesLoading = false;
555
+ let assigneesError = null;
556
+ let mergeDraft = null;
557
+ let linkedDraft = null;
558
+ // S6: the last painted frame and the click ranges it published, so a mouse
559
+ // event is answered against what the reader actually sees.
560
+ let frame = { width: 0, height: 0, ranges: [] };
561
+
562
+ const numOf = (row) => (row && row.number != null ? Number(row.number) : NaN);
563
+
564
+ // The first action seam with one of `names` that the caller actually wired.
565
+ function actionFor(names) {
566
+ for (const name of names) {
567
+ const fn = actions && typeof actions[name] === 'function' ? actions[name] : null;
568
+ if (fn !== null) return fn;
569
+ }
570
+ return null;
571
+ }
572
+
573
+ function repaint() {
574
+ if (!active) return;
575
+ try {
576
+ if (typeof requestRender === 'function') requestRender();
577
+ } catch {
578
+ // A repaint failure never breaks navigation.
579
+ }
580
+ }
581
+
582
+ function close() {
583
+ active = false;
584
+ cancelScheduledQuery();
585
+ if (typeof done === 'function') done(null);
586
+ }
587
+
588
+ // S10a (issues, kept): the list is open-only. GitHub reports `OPEN` from the
589
+ // connection and `open` from the search, so the comparison is case-folded and
590
+ // a merged pull request leaves the list like a closed one.
591
+ function rowState(row) {
592
+ return String((row && row.state) || 'open').toLowerCase();
593
+ }
594
+
595
+ function baseRows() {
596
+ const current = pages[state.page];
597
+ if (current && Array.isArray(current.rows)) return current.rows;
598
+ // A bucket with no rows is EMPTY: on the server seam it holds only the rows
599
+ // its own read returned, and the eager path has nothing else to offer.
600
+ return [];
601
+ }
602
+
603
+ // S5/S6 (D7): a numbered open may name a pull request no bucket carries — a
604
+ // merged one, or an open one of another author. The detail seam answers for
605
+ // exactly that number, and the row it answers with is PINNED into the list so
606
+ // the reader sees the pull request they asked for (and its state), never
607
+ // another row that happened to hold the focus.
608
+ function pinnedRow() {
609
+ if (pinnedNumber === null) return null;
610
+ const entry = details.get(pinnedNumber);
611
+ if (entry && entry.status === 'ready' && entry.pullRequest) return entry.pullRequest;
612
+ const known = baseRows().find((row) => numOf(row) === pinnedNumber);
613
+ if (known) return known;
614
+ if (entry && entry.pullRequest) return entry.pullRequest;
615
+ return { number: pinnedNumber, title: `#${pinnedNumber}`, state: 'open' };
616
+ }
617
+
618
+ // S3/D3: the ONE fact that decides whether a bucket's held rows answer the
619
+ // query on screen: the query those rows were READ for.
620
+ function rowsAnswerCurrentQuery(page) {
621
+ const rt = page && page.rt ? page.rt : null;
622
+ if (!rt || rt.rowsQuery === null) return true;
623
+ return rt.rowsQuery === String(state.query || '');
624
+ }
625
+
626
+ function rowsArePaintable(page) {
627
+ if (!page) return false;
628
+ if (rowsAnswerCurrentQuery(page)) return true;
629
+ const rt = page.rt;
630
+ return !(rt && rt.loading === true);
631
+ }
632
+
633
+ function filteredRows() {
634
+ if (serverMode && !rowsArePaintable(pages[state.page])) return [];
635
+ const open = baseRows().filter((row) => rowState(row) === 'open');
636
+ const rows = serverMode ? open : open.filter((row) => matchesQuery(row, state.query));
637
+ const pinned = pinnedRow();
638
+ if (pinned === null) return rows;
639
+ if (rows.some((row) => numOf(row) === numOf(pinned))) return rows;
640
+ return [pinned, ...rows];
641
+ }
642
+
643
+ function clampSelection() {
644
+ const total = filteredRows().length;
645
+ if (state.index >= total) state.index = Math.max(0, total - 1);
646
+ if (state.index < 0) state.index = 0;
647
+ }
648
+
649
+ function selected() {
650
+ const list = filteredRows();
651
+ return list[state.index] || null;
652
+ }
653
+
654
+ function availableRows() {
655
+ try {
656
+ if (typeof rowsAvailable === 'function') {
657
+ const value = Math.floor(rowsAvailable());
658
+ if (Number.isFinite(value) && value > 0) return value;
659
+ }
660
+ } catch {
661
+ // A hostile rows source never breaks the view.
662
+ }
663
+ return 24;
664
+ }
665
+
666
+ // The item budget of the left list: every body row the frame leaves.
667
+ function listBodyRows() {
668
+ return Math.max(1, availableRows() - 6);
669
+ }
670
+
671
+ // S2 (D22): whether the frame can hold a step's own line at all.
672
+ function stepRoomAvailable() {
673
+ return availableRows() >= MIN_STEP_ROWS;
674
+ }
675
+
676
+ const STEP_TOO_SHORT = 'the terminal is too short to confirm this pull request; enlarge it and press the key again';
677
+
678
+ function searchWidget(room) {
679
+ if (room <= 0) return '';
680
+ const prefix = '› ';
681
+ if (state.searching) {
682
+ const tail = tailOf(helpers, state.query, Math.max(0, room - measure(helpers, `${prefix}█`)));
683
+ return `${palette.label(theme, prefix)}${palette.value(theme, `${tail}█`)}`;
684
+ }
685
+ if (state.query === '') return `${palette.label(theme, prefix)}${palette.label(theme, 'Search')}`;
686
+ const shown = tailOf(helpers, state.query, Math.max(0, room - measure(helpers, prefix)));
687
+ return `${palette.label(theme, prefix)}${palette.value(theme, shown)}`;
688
+ }
689
+
690
+ // One bucket's continuous-read state (S3):
691
+ // - `loaded` — its rows were read for `query`, so returning to the tab paints
692
+ // them instead of refetching;
693
+ // - `hasMore`/`nextCursor` — the read continues after the loaded rows;
694
+ // - `start`/`index` — this bucket's own window and focus, restored on return;
695
+ // - `rowsQuery` — the query the rows CURRENTLY HELD answer (null when none).
696
+ function bucketState(page) {
697
+ if (!page.rt) {
698
+ page.rt = {
699
+ start: 0,
700
+ index: 0,
701
+ loading: false,
702
+ loaded: false,
703
+ seq: 0,
704
+ error: null,
705
+ hasMore: true,
706
+ nextCursor: null,
707
+ query: null,
708
+ rowsQuery: null,
709
+ };
710
+ }
711
+ return page.rt;
712
+ }
713
+
714
+ function lazyPageIndex() {
715
+ for (let at = 0; at < pages.length; at += 1) {
716
+ if (pages[at].lazy === true) return at;
717
+ }
718
+ return -1;
719
+ }
720
+
721
+ function tabPageIndices() {
722
+ const out = [];
723
+ pages.forEach((page, at) => {
724
+ if (page.lazy !== true) out.push(at);
725
+ });
726
+ return out.length > 0 ? out : pages.map((_, at) => at);
727
+ }
728
+
729
+ function insideLazyView() {
730
+ return lazyPageIndex() >= 0 && state.page === lazyPageIndex();
731
+ }
732
+
733
+ function hasFilter(text) {
734
+ return typeof text === 'string' && text.trim() !== '';
735
+ }
736
+
737
+ function normalizePageResult(result) {
738
+ if (!result || typeof result !== 'object') return { ok: false, error: 'pull requests could not be loaded' };
739
+ if (result.ok === false) {
740
+ return { ok: false, error: String(result.error || result.loadError || 'pull requests could not be loaded') };
741
+ }
742
+ const rows = Array.isArray(result.rows)
743
+ ? result.rows
744
+ : (Array.isArray(result.pullRequests) ? result.pullRequests : null);
745
+ if (rows === null) return { ok: false, error: 'pull requests could not be loaded: unexpected result' };
746
+ const total = Number.isFinite(Number(result.totalCount)) ? Number(result.totalCount) : null;
747
+ const cursor = typeof result.cursor === 'string'
748
+ ? result.cursor
749
+ : (typeof result.nextCursor === 'string'
750
+ ? result.nextCursor
751
+ : (typeof result.endCursor === 'string' ? result.endCursor : null));
752
+ return {
753
+ ok: true,
754
+ rows: rows.slice(),
755
+ total,
756
+ hasMore: result.hasMore === true || result.hasNextPage === true,
757
+ cursor,
758
+ };
759
+ }
760
+
761
+ // S3: ONE list, read continuously. A HEAD read replaces the bucket's rows with
762
+ // the first page of the current query and returns the reader to its top; an
763
+ // APPEND read continues after the last loaded row. Every read carries `query`,
764
+ // and only the newest answer for a bucket may paint (D1).
765
+ function requestBucketPage(bucketIndex, requestOptions = {}) {
766
+ const bucket = pages[bucketIndex];
767
+ if (!bucket || !pageLoaderFn) return null;
768
+ const keepSelection = Boolean(requestOptions) && requestOptions.keepSelection === true;
769
+ const append = Boolean(requestOptions) && requestOptions.append === true;
770
+ const query = String(state.query || '');
771
+ const rt = bucketState(bucket);
772
+ const loaded = Array.isArray(bucket.rows) ? bucket.rows : [];
773
+ if (append && (!rt.loaded || rt.loading || !rt.hasMore || rt.nextCursor === null)) return null;
774
+ const cursor = append ? rt.nextCursor : null;
775
+ const seq = ++pageSeq;
776
+ rt.seq = seq;
777
+ rt.loading = true;
778
+ rt.error = null;
779
+ rt.query = query;
780
+ if (!append) rt.loaded = false;
781
+ if (bucketIndex === state.page) state.loading = true;
782
+ repaint();
783
+ const request = {
784
+ bucketId: bucket.id,
785
+ cursor,
786
+ limit: listBodyRows(),
787
+ query,
788
+ };
789
+ let pending = null;
790
+ try {
791
+ pending = pageLoaderFn(request);
792
+ } catch (err) {
793
+ pending = { ok: false, error: (err && err.message) || 'pull requests could not be loaded' };
794
+ }
795
+ const settle = (result) => {
796
+ if (!active || rt.seq !== seq) return;
797
+ rt.loading = false;
798
+ const normalized = normalizePageResult(result);
799
+ if (!normalized.ok) {
800
+ rt.error = normalized.error;
801
+ const answersQuery = rt.rowsQuery !== null && rt.rowsQuery === query;
802
+ if (!answersQuery) {
803
+ bucket.rows = null;
804
+ bucket.total = null;
805
+ bucket.truncated = false;
806
+ rt.rowsQuery = null;
807
+ rt.hasMore = false;
808
+ rt.nextCursor = null;
809
+ rt.loaded = false;
810
+ }
811
+ if (bucketIndex === state.page) {
812
+ state.loading = false;
813
+ state.loadError = normalized.error;
814
+ if (!answersQuery) {
815
+ state.index = 0;
816
+ state.listStart = 0;
817
+ state.scroll = 0;
818
+ }
819
+ }
820
+ repaint();
821
+ return;
822
+ }
823
+ bucket.rows = append ? [...loaded, ...normalized.rows] : normalized.rows;
824
+ bucket.total = normalized.total;
825
+ bucket.truncated = normalized.hasMore;
826
+ rt.hasMore = normalized.hasMore;
827
+ rt.nextCursor = normalized.cursor;
828
+ rt.loaded = true;
829
+ rt.rowsQuery = query;
830
+ rt.error = null;
831
+ if (bucketIndex === state.page) {
832
+ state.loading = false;
833
+ state.loadError = null;
834
+ actionError = null;
835
+ if (keepSelection) {
836
+ clampSelection();
837
+ } else if (!append) {
838
+ state.index = 0;
839
+ state.listStart = 0;
840
+ state.scroll = 0;
841
+ }
842
+ if (!keepSelection) resolveInitialSelection(bucketIndex);
843
+ if (!append || keepSelection) {
844
+ ensurePullRequest(selected(), keepSelection ? { refresh: true } : undefined);
845
+ }
846
+ } else if (!keepSelection) {
847
+ resolveInitialSelection(bucketIndex);
848
+ }
849
+ repaint();
850
+ };
851
+ Promise.resolve(pending).then(settle).catch((err) => {
852
+ settle({ ok: false, error: (err && err.message) || 'pull requests could not be loaded' });
853
+ });
854
+ return request;
855
+ }
856
+
857
+ function loadMoreRows() {
858
+ if (!serverMode) return null;
859
+ return requestBucketPage(state.page, { append: true });
860
+ }
861
+
862
+ // S9/S10: a successful write changes the repository, so every bucket's loaded
863
+ // page is stale. The rows stay painted; the next visit reads the page again.
864
+ function invalidateLoadedPages() {
865
+ if (!serverMode) return;
866
+ pages.forEach((page) => {
867
+ bucketState(page).loaded = false;
868
+ });
869
+ }
870
+
871
+ function listTitle(row) {
872
+ return String((row && row.title) || '');
873
+ }
874
+
875
+ function listRowCost(row, width) {
876
+ return layout.rowCost(helpers, listTitle(row), width, { first: '▸ ' });
877
+ }
878
+
879
+ // S1: the two buckets a numbered open searches before it reports a miss. The
880
+ // rail already knows which bucket a linked pull request came from, so this pair
881
+ // only covers a cold caller that named one of the two scoped review buckets.
882
+ const INITIAL_FALLBACK_BUCKET = { mine: 'review', review: 'mine' };
883
+
884
+ function fallbackPageIndex(bucketIndex) {
885
+ const page = pages[bucketIndex];
886
+ const id = page && typeof page.id === 'string' ? page.id : '';
887
+ const other = INITIAL_FALLBACK_BUCKET[id];
888
+ if (!other) return -1;
889
+ return pages.findIndex((candidate) => candidate && candidate.id === other);
890
+ }
891
+
892
+ function bucketRows(bucketIndex) {
893
+ const page = pages[bucketIndex];
894
+ if (!page || !Array.isArray(page.rows)) return [];
895
+ if (serverMode && !rowsArePaintable(page)) return [];
896
+ return page.rows.filter((row) => rowState(row) === 'open');
897
+ }
898
+
899
+ function resolveInitialSelection(bucketIndex = state.page) {
900
+ const pending = pendingSelection;
901
+ if (!pending || pending.bucketIndex !== bucketIndex) return;
902
+ pending.pagesRead += 1;
903
+ const at = bucketRows(bucketIndex).findIndex((row) => numOf(row) === pending.number);
904
+ if (at >= 0) {
905
+ pendingSelection = null;
906
+ if (state.page !== bucketIndex) {
907
+ state.page = bucketIndex;
908
+ state.loading = bucketState(pages[bucketIndex]).loading;
909
+ }
910
+ state.index = at;
911
+ state.listStart = 0;
912
+ state.scroll = 0;
913
+ ensurePullRequest(selected());
914
+ return;
915
+ }
916
+ if (pending.pagesRead < INITIAL_SELECTION_PAGE_LIMIT) {
917
+ if (requestBucketPage(pending.bucketIndex, { append: true })) return;
918
+ }
919
+ if (pending.triedFallback !== true) {
920
+ const fallback = fallbackPageIndex(bucketIndex);
921
+ if (fallback >= 0 && fallback !== bucketIndex) {
922
+ pendingSelection = { number: pending.number, bucketIndex: fallback, pagesRead: 0, triedFallback: true };
923
+ const rt = bucketState(pages[fallback]);
924
+ if (rt.loaded && rt.query === String(state.query || '') && !rt.loading) {
925
+ resolveInitialSelection(fallback);
926
+ return;
927
+ }
928
+ if (requestBucketPage(fallback, {})) return;
929
+ }
930
+ }
931
+ pendingSelection = null;
932
+ // S5/S6 (D7): the buckets cannot carry a merged pull request or another
933
+ // author's open one, so the ONE detail seam is asked for exactly this
934
+ // number instead of the pane settling on a row the reader never named.
935
+ if (typeof loadPullRequest === 'function' && openByNumber(pending.number)) return;
936
+ const label = pages[initialPageIndex] ? pages[initialPageIndex].label : 'My Pull Request';
937
+ notice = `#${pending.number} is not in ${label}`;
938
+ }
939
+
940
+ // S5/S6 (D7): pin one number at the top of the list and read it through the
941
+ // detail seam. A read that fails leaves the honest "not in …" notice.
942
+ function openByNumber(number) {
943
+ if (!Number.isFinite(number)) return false;
944
+ pinnedNumber = number;
945
+ const entry = ensurePullRequest({ number, title: `#${number}`, state: 'open' });
946
+ if (entry && entry.status === 'error') {
947
+ pinnedNumber = null;
948
+ return false;
949
+ }
950
+ state.index = 0;
951
+ state.listStart = 0;
952
+ state.scroll = 0;
953
+ repaint();
954
+ return true;
955
+ }
956
+
957
+ function ensurePullRequest(row, detailOptions = {}) {
958
+ const refresh = Boolean(detailOptions) && detailOptions.refresh === true;
959
+ if (!row || !Number.isFinite(numOf(row))) return null;
960
+ const number = numOf(row);
961
+ let entry = details.get(number);
962
+ if (entry && !refresh) return entry;
963
+ const previous = entry && entry.pullRequest ? entry.pullRequest : row;
964
+ const seq = (detailSeq.get(number) || 0) + 1;
965
+ detailSeq.set(number, seq);
966
+ entry = {
967
+ status: 'loading',
968
+ pullRequest: previous,
969
+ comments: entry ? entry.comments : [],
970
+ permissions: entry ? entry.permissions : null,
971
+ error: null,
972
+ seq,
973
+ };
974
+ details.set(number, entry);
975
+ if (typeof loadPullRequest !== 'function') {
976
+ entry.status = 'ready';
977
+ entry.pullRequest = row;
978
+ return entry;
979
+ }
980
+ let pending = null;
981
+ try {
982
+ pending = refresh ? loadPullRequest(number, { refresh: true }) : loadPullRequest(number);
983
+ } catch (err) {
984
+ entry.status = 'error';
985
+ entry.error = (err && err.message) || 'pull request unreadable';
986
+ return entry;
987
+ }
988
+ const settle = (result) => {
989
+ // S2/D25: a superseded read never installs its answer.
990
+ if (detailSeq.get(number) !== seq) return;
991
+ const normalized = normalizeDetail(result);
992
+ if (normalized.ok) {
993
+ entry.status = 'ready';
994
+ entry.pullRequest = normalized.pullRequest;
995
+ entry.comments = normalized.comments;
996
+ entry.permissions = normalized.permissions;
997
+ } else {
998
+ entry.status = 'error';
999
+ entry.error = normalized.error;
1000
+ }
1001
+ repaint();
1002
+ };
1003
+ if (pending && typeof pending.then === 'function') {
1004
+ entry.pending = Promise.resolve(pending).then(settle, (err) => {
1005
+ if (detailSeq.get(number) !== seq) return;
1006
+ entry.status = 'error';
1007
+ entry.error = (err && err.message) || 'pull request unreadable';
1008
+ repaint();
1009
+ });
1010
+ } else {
1011
+ entry.pending = null;
1012
+ settle(pending);
1013
+ }
1014
+ return entry;
1015
+ }
1016
+
1017
+ // S2 (D20): the pull request a captured number names, whatever the list holds
1018
+ // now — its own row, the row a numbered open pinned, or the detail already
1019
+ // read for it. Null when nothing knows it any more.
1020
+ function rowForNumber(number) {
1021
+ const at = Number.isFinite(number) ? number : NaN;
1022
+ if (!Number.isFinite(at)) return null;
1023
+ const known = filteredRows().find((candidate) => numOf(candidate) === at);
1024
+ if (known) return known;
1025
+ const entry = details.get(at);
1026
+ return entry && entry.pullRequest ? entry.pullRequest : null;
1027
+ }
1028
+
1029
+ // S2 (D20, D25): the captured number's OWN detail is re-read before its
1030
+ // confirmation or its save proceeds, so a reload that reordered or removed the
1031
+ // row can never make it write with the capability — or the state — of whichever
1032
+ // pull request holds the focus now. The answer this gate decides on is the
1033
+ // NEWEST read for that number: when a later read landed while an older one was
1034
+ // still in flight, the newer answer (even a negative one) wins.
1035
+ function freshDetail(number) {
1036
+ const row = rowForNumber(number);
1037
+ if (!row) return Promise.resolve(null);
1038
+ const entry = ensurePullRequest(row, { refresh: true });
1039
+ if (!entry) return Promise.resolve(null);
1040
+ const newest = () => {
1041
+ const current = details.get(number);
1042
+ return current && current.seq === entry.seq ? entry : (current || entry);
1043
+ };
1044
+ if (entry.pending && typeof entry.pending.then === 'function') {
1045
+ return entry.pending.then(newest, newest);
1046
+ }
1047
+ return Promise.resolve(newest());
1048
+ }
1049
+
1050
+ // S2 (D20, D26): the two gates a captured write must pass on its FRESH detail. A
1051
+ // pull request that is no longer open, or whose detail could not be read, is
1052
+ // refused with the sentence the step names; so is one whose capability is no
1053
+ // longer confirmed. Both refusals leave the write seam untouched. The fresh
1054
+ // capability map is returned too, so an editor that needs a SECOND capability
1055
+ // (creating a label) decides on the same read.
1056
+ function freshGate(number, capability, sentences) {
1057
+ return freshDetail(number).then((entry) => {
1058
+ const pullRequest = entry && entry.status === 'ready' && entry.pullRequest ? entry.pullRequest : null;
1059
+ if (pullRequest === null) return { ok: false, error: sentences.notOpen, exit: true };
1060
+ const stateText = String(pullRequest.state || '').toLowerCase();
1061
+ if (stateText !== '' && stateText !== 'open') {
1062
+ return { ok: false, error: sentences.notOpen, exit: true };
1063
+ }
1064
+ const confirmed = capabilityMap(pullRequest, entry.permissions, viewPermissions);
1065
+ if (confirmed[capability] !== true) return { ok: false, error: sentences.refusal, exit: true };
1066
+ return { ok: true, capabilities: confirmed, pullRequest };
1067
+ });
1068
+ }
1069
+
1070
+ // The seam call itself, guarded: a throwing action is a refusal, never a crash.
1071
+ function runSeam(fn, ...args) {
1072
+ try {
1073
+ return fn(...args);
1074
+ } catch (err) {
1075
+ return { ok: false, error: (err && err.message) || 'action failed' };
1076
+ }
1077
+ }
1078
+
1079
+ // S2 (D20): a save that stops on its own fresh gate EXITS the step it belongs
1080
+ // to and names why; a write that fails keeps the step open like any other.
1081
+ function settleCaptured(pending, onOk, exit) {
1082
+ const finish = (result) => {
1083
+ if (!active) return;
1084
+ state.saving = null;
1085
+ if (result && result.ok === true) {
1086
+ onOk(result);
1087
+ return;
1088
+ }
1089
+ if (result && result.exit === true) exit();
1090
+ actionError = (result && result.error) || 'action failed';
1091
+ repaint();
1092
+ };
1093
+ Promise.resolve(pending).then(finish).catch((err) => {
1094
+ finish({ ok: false, error: (err && err.message) || 'action failed' });
1095
+ });
1096
+ }
1097
+
1098
+ function refetchDetail(number) {
1099
+ const row = filteredRows().find((candidate) => numOf(candidate) === number)
1100
+ || (numOf(selected()) === number ? selected() : null);
1101
+ if (!row) {
1102
+ details.delete(number);
1103
+ repaint();
1104
+ return;
1105
+ }
1106
+ ensurePullRequest(row, { refresh: true });
1107
+ repaint();
1108
+ }
1109
+
1110
+ // S2: the capability a key needs comes from the established detail, so a
1111
+ // permission is never a stale guess and painting the footer starts no fetch.
1112
+ function permissionsFor(row) {
1113
+ if (!row) return NO_PERMISSIONS;
1114
+ return permissionsOf(numOf(row));
1115
+ }
1116
+
1117
+ // S2 (D1, D3): the capability of ONE number — the pull request a confirmation
1118
+ // showed, or the draft an editor is holding — whatever row holds the focus by
1119
+ // the time the key is pressed.
1120
+ function permissionsOf(number) {
1121
+ const at = Number.isFinite(number) ? number : NaN;
1122
+ const entry = Number.isFinite(at) ? details.get(at) : null;
1123
+ if (entry && entry.status === 'ready') return capabilityMap(entry.pullRequest || {}, entry.permissions, viewPermissions);
1124
+ if (typeof loadPullRequest !== 'function') {
1125
+ const row = filteredRows().find((candidate) => numOf(candidate) === at) || null;
1126
+ return capabilityMap(row || {}, null, viewPermissions);
1127
+ }
1128
+ return NO_PERMISSIONS;
1129
+ }
1130
+
1131
+ // S11: the hints that act on the selected pull request need one that is both
1132
+ // focused and loaded. The detail read is that proof; a view with no detail
1133
+ // seam holds only the row, so there the row is what "loaded" means.
1134
+ function pullRequestReady(row) {
1135
+ if (!row) return false;
1136
+ if (typeof loadPullRequest !== 'function') return true;
1137
+ const number = numOf(row);
1138
+ const entry = Number.isFinite(number) ? details.get(number) : null;
1139
+ return Boolean(entry && entry.status === 'ready');
1140
+ }
1141
+
1142
+ // The pull request an editor starts from: the established detail when it is
1143
+ // ready, otherwise the row itself. Never starts a fetch of its own.
1144
+ function currentPullRequest(row) {
1145
+ if (!row) return null;
1146
+ const number = numOf(row);
1147
+ const entry = Number.isFinite(number) ? details.get(number) : null;
1148
+ if (entry && entry.status === 'ready' && entry.pullRequest) return entry.pullRequest;
1149
+ return row;
1150
+ }
1151
+
1152
+ function titleText() {
1153
+ return '◈ Pull requests';
1154
+ }
1155
+
1156
+ function clampScroll(total) {
1157
+ const max = Math.max(0, total - Math.max(1, bodyRows));
1158
+ if (state.scroll > max) state.scroll = max;
1159
+ if (state.scroll < 0) state.scroll = 0;
1160
+ }
1161
+
1162
+ function detailWrap(width) {
1163
+ return (text) => defaultWrapCache.wrap(String(text ?? ''), width);
1164
+ }
1165
+
1166
+ // S6: the published ranges are the preview's own, so the click targets are the
1167
+ // numbers it painted — never a search of the rendered text.
1168
+ function detailLines(row, width, links) {
1169
+ const entry = ensurePullRequest(row);
1170
+ if (!entry) return [paint(theme, 'muted', '(no pull request selected)')];
1171
+ if (entry.status === 'error') return [paint(theme, 'error', `unreadable: ${entry.error}`)];
1172
+ const pullRequest = entry.pullRequest || row;
1173
+ const paintRole = (role, text) => paint(theme, role, text);
1174
+ const emphasis = (text) => emphasize(theme, text);
1175
+ const wrap = detailWrap(width);
1176
+ if (entry.status !== 'ready') {
1177
+ return pullRequestDetailLines(pullRequest, [], {
1178
+ width,
1179
+ pending: true,
1180
+ paint: paintRole,
1181
+ emphasis,
1182
+ wrap,
1183
+ });
1184
+ }
1185
+ const comments = Array.isArray(entry.comments) ? entry.comments : [];
1186
+ return pullRequestDetailLines(pullRequest, comments, {
1187
+ width,
1188
+ paint: paintRole,
1189
+ emphasis,
1190
+ wrap,
1191
+ links,
1192
+ measure: (text) => measure(helpers, text),
1193
+ });
1194
+ }
1195
+
1196
+ function subModeKeys() {
1197
+ if (state.mode === 'labels') {
1198
+ if (labelsLoading) return BACK_KEYS;
1199
+ if (state.labelCreating) return LABEL_CREATE_KEYS;
1200
+ return LABEL_EDITOR_KEYS.filter((entry) => !entry.needsCreate || Boolean(labelDraft && labelDraft.createAllowed));
1201
+ }
1202
+ if (state.mode === 'assignees') return assigneesLoading ? BACK_KEYS : ASSIGNEE_EDITOR_KEYS;
1203
+ if (state.mode === 'comment') return state.discardAsk ? COMMENT_DISCARD_KEYS : COMMENT_EDITOR_KEYS;
1204
+ if (state.mode === 'merge') return MERGE_KEYS;
1205
+ if (state.mode === 'linkedIssues') return linkedDraft && linkedDraft.adding ? LINKED_ADD_KEYS : LINKED_EDITOR_KEYS;
1206
+ return null;
1207
+ }
1208
+
1209
+ // S2/D22: the pane line that names the pull request a step captured. It is
1210
+ // reserved a body row, because it is the one line that says WHERE the write
1211
+ // goes.
1212
+ function anchorLineIndex(lines) {
1213
+ const wanted = state.mode === 'merge' ? 'Confirm merge #'
1214
+ : state.mode === 'confirm' ? 'Confirm close #'
1215
+ : state.mode === 'comment' ? 'Comment on #' : null;
1216
+ if (wanted === null) return -1;
1217
+ return lines.findIndex((line) => stripAnsi(line).includes(wanted));
1218
+ }
1219
+
1220
+ function render(width) {
1221
+ const w = typeof width === 'number' && Number.isFinite(width) ? Math.floor(width) : 0;
1222
+ if (w <= 0) return [];
1223
+ const height = availableRows();
1224
+ const title = titleText();
1225
+ if (w < MIN_WIDTH || height < 4) {
1226
+ return [pad(helpers, fit(helpers, `${title} — enlarge the terminal`, w), w)];
1227
+ }
1228
+ if (state.page >= pages.length) state.page = 0;
1229
+ clampSelection();
1230
+ frame = { width: w, height, ranges: [] };
1231
+ // CARD_PADDING covers the frame's own `│ ` and ` │` cells, so this inner
1232
+ // width fills the terminal exactly (no trailing slack, corners aligned).
1233
+ const inner = Math.max(1, w - CARD_PADDING);
1234
+ const panes = layout.paneWidths(inner, { listShare: layout.READER_LIST_SHARE });
1235
+ const listWidth = panes.left;
1236
+ const rightWidth = panes.right;
1237
+ listWidthCache = listWidth;
1238
+ bodyRows = Math.max(1, height - 6);
1239
+ const border = (text) => paint(theme, 'border', text);
1240
+ const divider = border('│');
1241
+ const permissions = permissionsFor(selected());
1242
+ const documentScroll = palette.scrollHint(scrollKeys.previewScrollKeys(), 'scroll');
1243
+ const subMode = state.searching ? null : subModeKeys();
1244
+ const pullRequestAvailable = pullRequestReady(selected());
1245
+ const footerKeys = state.searching
1246
+ ? SEARCH_KEYS
1247
+ : subMode || [FOOTER_KEYS[0], documentScroll, ...FOOTER_KEYS.slice(1)]
1248
+ .filter((entry) => entry
1249
+ && (!entry.needsIssue || pullRequestAvailable)
1250
+ && (!entry.requires || permissions[entry.requires] === true))
1251
+ .map((entry) => (entry.shortcut === true ? shortcutHint(insideLazyView()) : entry));
1252
+ const footerCell = () => `${border('│')} ${pad(helpers, palette.legendRow(theme, footerKeys, inner, (text) => measure(helpers, text)), inner)} ${border('│')}`;
1253
+ const lines = [];
1254
+ const topLeft = `${border('╭─')} ${palette.title(theme, title)} `;
1255
+ const topRight = border('─╮');
1256
+ lines.push(`${topLeft}${border('─'.repeat(Math.max(0, w - measure(helpers, topLeft) - measure(helpers, topRight))))}${topRight}`);
1257
+ const searchLine = () => `${border('│')} ${pad(helpers, searchWidget(inner), inner)} ${border('│')}`;
1258
+
1259
+ const loadError = state.loadError || (options.loadError ? String(options.loadError) : null);
1260
+ if (options.ghAvailable === false) {
1261
+ lines.push(searchLine());
1262
+ lines.push(`${border('│')} ${pad(helpers, paint(theme, 'error', 'gh unavailable: install gh and authenticate to use /prs'), inner)} ${border('│')}`);
1263
+ while (lines.length < height - 2) lines.push(`${border('│')} ${pad(helpers, '', inner)} ${border('│')}`);
1264
+ lines.push(footerCell());
1265
+ lines.push(border(`╰${'─'.repeat(Math.max(0, w - 2))}╯`));
1266
+ return lines.map((line) => pad(helpers, line, w));
1267
+ }
1268
+ if (loadError && !state.loading && filteredRows().length === 0) {
1269
+ lines.push(searchLine());
1270
+ lines.push(`${border('│')} ${pad(helpers, paint(theme, 'error', `failed to load pull requests: ${loadError}`), inner)} ${border('│')}`);
1271
+ while (lines.length < height - 2) lines.push(`${border('│')} ${pad(helpers, '', inner)} ${border('│')}`);
1272
+ lines.push(footerCell());
1273
+ lines.push(border(`╰${'─'.repeat(Math.max(0, w - 2))}╯`));
1274
+ return lines.map((line) => pad(helpers, line, w));
1275
+ }
1276
+ const activeBucket = pages[state.page] || null;
1277
+ const bucketLoaded = Boolean(activeBucket && Array.isArray(activeBucket.rows));
1278
+ if (state.loading && (pages.length === 0 || (serverMode && !bucketLoaded))) {
1279
+ lines.push(searchLine());
1280
+ lines.push(`${border('│')} ${pad(helpers, paint(theme, 'muted', 'loading pull requests…'), inner)} ${border('│')}`);
1281
+ while (lines.length < height - 2) lines.push(`${border('│')} ${pad(helpers, '', inner)} ${border('│')}`);
1282
+ lines.push(footerCell());
1283
+ lines.push(border(`╰${'─'.repeat(Math.max(0, w - 2))}╯`));
1284
+ return lines.map((line) => pad(helpers, line, w));
1285
+ }
1286
+
1287
+ lines.push(searchLine());
1288
+ const barIndices = insideLazyView() ? [lazyPageIndex()] : tabPageIndices();
1289
+ const tabs = barIndices.map((at) => {
1290
+ const page = pages[at];
1291
+ const active = at === state.page;
1292
+ const name = `${active ? '▸ ' : ''}${page.label}`;
1293
+ const tabTotal = ` (${tabCount(page)})`;
1294
+ if (!active) return palette.count(theme, `${name}${tabTotal}`);
1295
+ return `${palette.title(theme, name)}${palette.count(theme, tabTotal)}`;
1296
+ }).join(paint(theme, 'border', ' │ '));
1297
+ lines.push(`${border('│')} ${pad(helpers, tabs, inner)} ${border('│')}`);
1298
+
1299
+ const savingNote = state.saving ? paint(theme, 'accent', saveLabel(state.saving)) : '';
1300
+ const errorNote = savingNote || (actionError ? paint(theme, 'error', actionError)
1301
+ : (loadError ? paint(theme, 'error', String(loadError)) : ''));
1302
+ const note = errorNote || (notice ? paint(theme, 'accent', notice) : '')
1303
+ || (state.searchPending ? paint(theme, 'muted', 'searching…') : '')
1304
+ || (state.loading ? paint(theme, 'muted', 'loading…') : '')
1305
+ || lazyReadNote();
1306
+ lines.push(`${border('│')} ${pad(helpers, note, inner)} ${border('│')}`);
1307
+
1308
+ const list = filteredRows();
1309
+ const focused = selected();
1310
+ if (focused) ensurePullRequest(focused);
1311
+ const costs = list.map((row) => listRowCost(row, listWidth));
1312
+ // S2 (D12, D17, D18): a confirmation and the composer each name ONE pull
1313
+ // request, so that row — not whatever a reload left under the cursor — is
1314
+ // the one the list highlights, and the window follows it when a reload moved
1315
+ // it out of sight. A row the list no longer holds cannot be highlighted; the
1316
+ // step's own line still names it.
1317
+ let targetNumber = null;
1318
+ if (state.mode === 'merge' && mergeDraft) targetNumber = mergeDraft.number;
1319
+ else if (state.mode === 'confirm' && state.confirm) targetNumber = state.confirm.number;
1320
+ else if (state.mode === 'comment' && Number.isFinite(state.commentNumber)) targetNumber = state.commentNumber;
1321
+ const targetIndex = targetNumber === null ? -1 : list.findIndex((row) => numOf(row) === targetNumber);
1322
+ const bounds = layout.scrollWindow(costs, {
1323
+ budget: Math.max(1, bodyRows),
1324
+ index: targetIndex >= 0 ? targetIndex : state.index,
1325
+ start: state.listStart,
1326
+ });
1327
+ state.listStart = bounds.start;
1328
+ if (serverMode && activeBucket) {
1329
+ const rt = bucketState(activeBucket);
1330
+ rt.start = bounds.start;
1331
+ rt.index = state.index;
1332
+ }
1333
+ const leftLines = [];
1334
+ for (let at = bounds.start; at < bounds.end; at += 1) {
1335
+ const isFocused = targetNumber === null ? at === state.index : numOf(list[at]) === targetNumber;
1336
+ const rows = layout.wrapLabel(helpers, listTitle(list[at]), listWidth, { first: isFocused ? '▸ ' : ' ' });
1337
+ for (const row of rows) leftLines.push(highlight(theme, pad(helpers, row, listWidth), isFocused));
1338
+ }
1339
+
1340
+ const paneLinks = [];
1341
+ let rightSource;
1342
+ if (state.mode === 'labels') {
1343
+ rightSource = labelEditorLines(rightWidth);
1344
+ } else if (state.mode === 'assignees') {
1345
+ rightSource = assigneeEditorLines(rightWidth);
1346
+ } else if (state.mode === 'comment') {
1347
+ rightSource = commentLines(rightWidth);
1348
+ } else if (state.mode === 'confirm') {
1349
+ rightSource = confirmLines(rightWidth);
1350
+ } else if (state.mode === 'merge') {
1351
+ rightSource = mergeLines(rightWidth);
1352
+ } else if (state.mode === 'linkedIssues') {
1353
+ rightSource = linkedIssuesLines(rightWidth);
1354
+ } else if (list.length === 0) {
1355
+ if (state.searchPending || state.loading) {
1356
+ rightSource = [paint(theme, 'muted', 'loading pull requests…')];
1357
+ } else if (state.query) {
1358
+ rightSource = [paint(theme, 'muted', 'no pull requests match this filter')];
1359
+ } else {
1360
+ rightSource = [paint(theme, 'muted', 'no pull requests'), paint(theme, 'dim', 'nothing to show here')];
1361
+ }
1362
+ } else {
1363
+ rightSource = detailLines(focused, rightWidth, paneLinks);
1364
+ }
1365
+ clampScroll(rightSource.length);
1366
+ const visible = rightSource.slice(state.scroll, state.scroll + bodyRows);
1367
+ // S2/D22: the captured target's own line is RESERVED a row that no scroll
1368
+ // window can clip: when the window would leave it out, it takes the first
1369
+ // row (anchor above the window) or the last one (anchor below it).
1370
+ const anchor = anchorLineIndex(rightSource);
1371
+ if (anchor >= 0 && visible.length > 0) {
1372
+ const first = state.scroll;
1373
+ const last = state.scroll + visible.length - 1;
1374
+ if (anchor < first) visible[0] = rightSource[anchor];
1375
+ else if (anchor > last) visible[visible.length - 1] = rightSource[anchor];
1376
+ }
1377
+ // S6: only the ranges that are actually painted can be clicked, mapped from
1378
+ // the pane's own line index to this frame's row and column.
1379
+ for (const link of paneLinks) {
1380
+ const rowIndex = link.line - state.scroll;
1381
+ if (rowIndex < 0 || rowIndex >= bodyRows) continue;
1382
+ frame.ranges.push({
1383
+ y: BODY_TOP + rowIndex,
1384
+ startX: PANE_LEFT + listWidth + link.start,
1385
+ endX: PANE_LEFT + listWidth + link.end,
1386
+ number: link.number,
1387
+ });
1388
+ }
1389
+ for (let row = 0; row < bodyRows; row += 1) {
1390
+ const left = pad(helpers, leftLines[row] ?? '', listWidth);
1391
+ const right = pad(helpers, visible[row] ?? '', rightWidth);
1392
+ lines.push(`${border('│')} ${left} ${divider} ${right} ${border('│')}`);
1393
+ }
1394
+ lines.push(footerCell());
1395
+ lines.push(border(`╰${'─'.repeat(Math.max(0, w - 2))}╯`));
1396
+ return lines.map((line) => pad(helpers, line, w));
1397
+ }
1398
+
1399
+ // S3/D3: the count a tab names. Row-derived counts are marked inexact exactly
1400
+ // like issues; a bucket nobody has read is UNKNOWN, never an invented zero.
1401
+ function tabCount(page) {
1402
+ const rows = Array.isArray(page.rows) ? page.rows : null;
1403
+ const rt = page.rt;
1404
+ if (serverMode && !rowsAnswerCurrentQuery(page)) return '–';
1405
+ const open = rows ? rows.filter((row) => rowState(row) === 'open') : null;
1406
+ const honorsState = !rows || open.length === rows.length;
1407
+ const searchRead = page.lazy === true && hasFilter(rt && rt.rowsQuery);
1408
+ if (page.total != null && honorsState) {
1409
+ const inexact = page.lazy === true ? searchRead : page.truncated === true;
1410
+ return `${page.total}${inexact ? '+' : ''}`;
1411
+ }
1412
+ if (rows === null && page.total == null) return '–';
1413
+ const count = open ? open.length : 0;
1414
+ const inexact = page.lazy === true ? true : page.truncated === true;
1415
+ return `${count}${inexact ? '+' : ''}`;
1416
+ }
1417
+
1418
+ // S5: the lazy view says which read is on screen — the exact connection or a
1419
+ // capped search — on the note row the frame already paints.
1420
+ function lazyReadNote() {
1421
+ const lazyAt = lazyPageIndex();
1422
+ if (lazyAt < 0 || state.page !== lazyAt) return '';
1423
+ const rt = bucketState(pages[lazyAt]);
1424
+ return paint(theme, 'muted', hasFilter(rt.rowsQuery) ? 'via search (total capped)' : 'via connection (exact total)');
1425
+ }
1426
+
1427
+ // ---- sub-modes ---------------------------------------------------------
1428
+
1429
+ function openLabelEditor() {
1430
+ const row = selected();
1431
+ if (!row) return;
1432
+ const permissions = permissionsFor(row);
1433
+ if (!permissions.canEditLabels) {
1434
+ actionError = 'labels cannot be edited: this repository permission is missing';
1435
+ repaint();
1436
+ return;
1437
+ }
1438
+ const labels = currentLabels(row);
1439
+ labelDraft = {
1440
+ number: numOf(row),
1441
+ selected: new Set(labels),
1442
+ original: new Set(labels),
1443
+ created: [],
1444
+ createAllowed: permissions.canCreateLabels,
1445
+ };
1446
+ state.mode = 'labels';
1447
+ state.labelIndex = 0;
1448
+ state.labelCreating = false;
1449
+ state.createName = '';
1450
+ actionError = null;
1451
+ state.scroll = 0;
1452
+ requestLabels();
1453
+ repaint();
1454
+ }
1455
+
1456
+ function currentLabels(row) {
1457
+ const pullRequest = currentPullRequest(row);
1458
+ return (pullRequest && Array.isArray(pullRequest.labels) ? pullRequest.labels : []).map(labelName).filter(Boolean);
1459
+ }
1460
+
1461
+ function labelEditorLines(width) {
1462
+ const out = [emphasize(theme, 'Labels')];
1463
+ if (!labelDraft) return out;
1464
+ if (labelsLoading) {
1465
+ out.push(paint(theme, 'muted', 'loading labels…'));
1466
+ return out;
1467
+ }
1468
+ if (labelsError) out.push(paint(theme, 'error', `labels unreadable: ${labelsError}`));
1469
+ const names = repoLabels.map((label) => label.name);
1470
+ const rows = labelDraft.createAllowed ? [...names, '+ create new…'] : names.slice();
1471
+ rows.forEach((name, at) => {
1472
+ const isCreate = labelDraft.createAllowed && at === rows.length - 1;
1473
+ const on = !isCreate && labelDraft.selected.has(name);
1474
+ const cursor = at === state.labelIndex ? '▸ ' : ' ';
1475
+ if (isCreate && state.labelCreating) {
1476
+ out.push(...wrapText(`${cursor}new: ${state.createName}█`, width));
1477
+ } else {
1478
+ out.push(...wrapText(`${cursor}[${on ? 'x' : ' '}] ${name}`, width));
1479
+ }
1480
+ });
1481
+ if (labelDraft.created.length > 0) out.push(...wrapText(`new labels: ${labelDraft.created.join(', ')}`, width));
1482
+ if (actionError) out.push(paint(theme, 'error', actionError));
1483
+ return out;
1484
+ }
1485
+
1486
+ function requestLabels() {
1487
+ if (typeof loadLabels !== 'function' || labelsLoaded || labelsLoading) return;
1488
+ labelsLoading = true;
1489
+ labelsError = null;
1490
+ repaint();
1491
+ let pending = null;
1492
+ try {
1493
+ pending = loadLabels();
1494
+ } catch (err) {
1495
+ pending = { ok: false, error: (err && err.message) || 'labels unreadable' };
1496
+ }
1497
+ const settle = (result) => {
1498
+ labelsLoading = false;
1499
+ if (result && result.ok === true && Array.isArray(result.labels)) {
1500
+ repoLabels = result.labels.map((label) => ({ name: labelName(label) })).filter((label) => label.name);
1501
+ labelsLoaded = true;
1502
+ labelsError = null;
1503
+ } else {
1504
+ labelsError = (result && (result.error || result.loadError)) || 'labels unreadable';
1505
+ }
1506
+ repaint();
1507
+ };
1508
+ Promise.resolve(pending).then(settle).catch((err) => {
1509
+ settle({ ok: false, error: (err && err.message) || 'labels unreadable' });
1510
+ });
1511
+ }
1512
+
1513
+ function openAssigneeEditor() {
1514
+ const row = selected();
1515
+ if (!row) return;
1516
+ if (!permissionsFor(row).canEditAssignees) {
1517
+ actionError = 'assignees cannot be edited: this repository permission is missing';
1518
+ repaint();
1519
+ return;
1520
+ }
1521
+ const current = currentAssignees(row);
1522
+ assigneeDraft = { number: numOf(row), selected: new Set(current), original: new Set(current) };
1523
+ state.mode = 'assignees';
1524
+ state.assigneeIndex = 0;
1525
+ actionError = null;
1526
+ state.scroll = 0;
1527
+ requestAssignees();
1528
+ repaint();
1529
+ }
1530
+
1531
+ function currentAssignees(row) {
1532
+ const pullRequest = currentPullRequest(row);
1533
+ return (pullRequest && Array.isArray(pullRequest.assignees) ? pullRequest.assignees : [])
1534
+ .map(assigneeName)
1535
+ .filter(Boolean);
1536
+ }
1537
+
1538
+ // Every assignable user, plus any current assignee the user list does not
1539
+ // carry, so an unexpected name can still be removed.
1540
+ function assigneeRows() {
1541
+ const logins = assigneeUsers.map((user) => user.login);
1542
+ for (const login of (assigneeDraft ? assigneeDraft.original : [])) {
1543
+ if (!logins.includes(login)) logins.push(login);
1544
+ }
1545
+ return logins;
1546
+ }
1547
+
1548
+ function assigneeEditorLines(width) {
1549
+ const out = [emphasize(theme, 'Assignees')];
1550
+ if (!assigneeDraft) return out;
1551
+ if (assigneesLoading) {
1552
+ out.push(paint(theme, 'muted', 'loading assignees…'));
1553
+ return out;
1554
+ }
1555
+ if (assigneesError) out.push(paint(theme, 'error', `assignees unreadable: ${assigneesError}`));
1556
+ const logins = assigneeRows();
1557
+ logins.forEach((login, at) => {
1558
+ const on = assigneeDraft.selected.has(login);
1559
+ const user = assigneeUsers.find((candidate) => candidate.login === login);
1560
+ const cursor = at === state.assigneeIndex ? '▸ ' : ' ';
1561
+ const label = user && user.name && user.name !== login ? `${login} (${user.name})` : login;
1562
+ out.push(...wrapText(`${cursor}[${on ? 'x' : ' '}] ${label}`, width));
1563
+ });
1564
+ if (logins.length === 0) out.push(paint(theme, 'muted', 'no assignable users'));
1565
+ if (actionError) out.push(paint(theme, 'error', actionError));
1566
+ return out;
1567
+ }
1568
+
1569
+ function requestAssignees() {
1570
+ if (typeof loadAssignees !== 'function' || assigneesLoaded || assigneesLoading) return;
1571
+ assigneesLoading = true;
1572
+ assigneesError = null;
1573
+ repaint();
1574
+ let pending = null;
1575
+ try {
1576
+ pending = loadAssignees();
1577
+ } catch (err) {
1578
+ pending = { ok: false, error: (err && err.message) || 'assignees unreadable' };
1579
+ }
1580
+ const settle = (result) => {
1581
+ assigneesLoading = false;
1582
+ if (result && result.ok === true && Array.isArray(result.users)) {
1583
+ assigneeUsers = result.users.map(assigneeOption).filter(Boolean);
1584
+ assigneesLoaded = true;
1585
+ assigneesError = null;
1586
+ } else {
1587
+ assigneesError = (result && (result.error || result.loadError)) || 'assignees unreadable';
1588
+ }
1589
+ repaint();
1590
+ };
1591
+ Promise.resolve(pending).then(settle).catch((err) => {
1592
+ settle({ ok: false, error: (err && err.message) || 'assignees unreadable' });
1593
+ });
1594
+ }
1595
+
1596
+ function commentLines(width) {
1597
+ // S2/D18: the composer names the number it will comment on, so what the
1598
+ // reader sees is where the comment goes.
1599
+ const number = Number.isFinite(state.commentNumber) ? state.commentNumber : null;
1600
+ const out = [emphasize(theme, number === null ? 'Comment' : `Comment on #${number}`)];
1601
+ if (state.discardAsk) out.push(paint(theme, 'error', 'Discard this draft?'));
1602
+ const rows = wrapText(state.commentText, width);
1603
+ const caret = paint(theme, 'accent', '█');
1604
+ const last = rows.at(-1) ?? '';
1605
+ if (measure(helpers, last) >= width) rows.push(caret);
1606
+ else rows.splice(-1, 1, `${last}${caret}`);
1607
+ out.push(...rows);
1608
+ if (actionError) out.push(paint(theme, 'error', actionError));
1609
+ return out;
1610
+ }
1611
+
1612
+ function confirmLines(width) {
1613
+ const number = state.confirm ? state.confirm.number : null;
1614
+ const out = [emphasize(theme, `Confirm close #${number === null ? '' : number} (enter confirm · esc cancel)`)];
1615
+ out.push(...wrapText('This will close the pull request on GitHub.', width));
1616
+ if (actionError) out.push(paint(theme, 'error', actionError));
1617
+ return out;
1618
+ }
1619
+
1620
+ // The caret row of a text field: it sits at the real insertion point, on the
1621
+ // wrapped row typing would continue on.
1622
+ function fieldRows(text, focused, width) {
1623
+ const rows = wrapText(text, width);
1624
+ if (!focused) return rows;
1625
+ const caret = paint(theme, 'accent', '█');
1626
+ const last = rows.at(-1) ?? '';
1627
+ if (measure(helpers, last) >= width) rows.push(caret);
1628
+ else rows.splice(-1, 1, `${last}${caret}`);
1629
+ return rows;
1630
+ }
1631
+
1632
+ function mergeLines(width) {
1633
+ const out = [emphasize(theme, 'Merge')];
1634
+ if (!mergeDraft) return out;
1635
+ const method = mergeDraft.methods[mergeDraft.methodIndex];
1636
+ const texts = mergeDraft.texts[method] || { subject: '', body: '' };
1637
+ const offered = mergeFieldRows();
1638
+ const marker = (field) => (state.mergeField === field ? '▸ ' : ' ');
1639
+ const typeRow = mergeDraft.methods.length > 1 ? `◂ ${method} ▸` : method;
1640
+ out.push(...wrapText(`${marker(0)}Type: ${typeRow}`, width));
1641
+ // S2/D12: a rebase merge rewrites the commits it replays, so it takes neither
1642
+ // a subject nor a description and neither field is offered at all.
1643
+ if (offered.includes(1)) {
1644
+ out.push(`${marker(1)}Commit message:`);
1645
+ out.push(...fieldRows(texts.subject, state.mergeField === 1, width));
1646
+ }
1647
+ if (offered.includes(2)) {
1648
+ out.push(`${marker(2)}Description:`);
1649
+ out.push(...fieldRows(texts.body, state.mergeField === 2, width));
1650
+ }
1651
+ // S2/D12: the confirmation names the pull request it will merge, exactly like
1652
+ // the close confirmation names its own.
1653
+ out.push(`${marker(3)}Confirm merge #${mergeDraft.number}`);
1654
+ out.push(`${marker(4)}Cancel`);
1655
+ if (actionError) out.push(paint(theme, 'error', actionError));
1656
+ return out;
1657
+ }
1658
+
1659
+ // The rows the merge step offers, in painting order: the type, the two
1660
+ // proposal fields when the method takes them, the confirm and the cancel.
1661
+ function mergeFieldRows() {
1662
+ const method = mergeDraft ? mergeDraft.methods[mergeDraft.methodIndex] : 'merge';
1663
+ return method === 'rebase' ? [0, 3, 4] : [0, 1, 2, 3, 4];
1664
+ }
1665
+
1666
+ function moveMergeField(step) {
1667
+ const offered = mergeFieldRows();
1668
+ const at = offered.indexOf(state.mergeField);
1669
+ const from = at < 0 ? 0 : at;
1670
+ state.mergeField = offered[(from + step + offered.length) % offered.length];
1671
+ }
1672
+
1673
+ function linkedIssuesLines(width) {
1674
+ const out = [emphasize(theme, 'Linked issues')];
1675
+ if (!linkedDraft) return out;
1676
+ if (linkedDraft.numbers.length === 0) out.push(paint(theme, 'muted', 'no linked issues'));
1677
+ linkedDraft.numbers.forEach((number, at) => {
1678
+ const on = linkedDraft.selected.has(number);
1679
+ const cursor = at === linkedDraft.index ? '▸ ' : ' ';
1680
+ out.push(`${cursor}[${on ? 'x' : ' '}] #${number}`);
1681
+ });
1682
+ if (linkedDraft.adding) out.push(...fieldRows(`#${linkedDraft.input}`, true, width));
1683
+ out.push(...wrapText('closes #N lines in the body', width));
1684
+ if (actionError) out.push(paint(theme, 'error', actionError));
1685
+ return out;
1686
+ }
1687
+
1688
+ function openMerge() {
1689
+ const row = selected();
1690
+ if (!row) return;
1691
+ const permissions = permissionsFor(row);
1692
+ if (!permissions.canMerge) {
1693
+ actionError = 'pull requests cannot be merged: this repository permission is missing';
1694
+ repaint();
1695
+ return;
1696
+ }
1697
+ const pullRequest = currentPullRequest(row);
1698
+ const methods = allowedMergeMethods(pullRequest);
1699
+ if (methods.length === 0) {
1700
+ actionError = 'pull requests cannot be merged: this repository permission is missing';
1701
+ repaint();
1702
+ return;
1703
+ }
1704
+ mergeDraft = {
1705
+ number: numOf(row),
1706
+ methods,
1707
+ methodIndex: 0,
1708
+ texts: mergeTextDefaults(pullRequest),
1709
+ };
1710
+ state.mode = 'merge';
1711
+ state.mergeField = 0;
1712
+ actionError = null;
1713
+ state.scroll = 0;
1714
+ repaint();
1715
+ }
1716
+
1717
+ function cancelMerge() {
1718
+ state.mode = 'list';
1719
+ mergeDraft = null;
1720
+ actionError = null;
1721
+ repaint();
1722
+ }
1723
+
1724
+ function openLinkedEditor() {
1725
+ const row = selected();
1726
+ if (!row) return;
1727
+ if (!permissionsFor(row).canEditLinkedIssues) {
1728
+ actionError = 'linked issues cannot be edited: this repository permission is missing';
1729
+ repaint();
1730
+ return;
1731
+ }
1732
+ const pullRequest = currentPullRequest(row);
1733
+ const numbers = (pullRequest && Array.isArray(pullRequest.linkedIssues) ? pullRequest.linkedIssues : [])
1734
+ .filter((number) => Number.isInteger(number) && number > 0)
1735
+ .slice()
1736
+ .sort((left, right) => left - right);
1737
+ linkedDraft = {
1738
+ number: numOf(row),
1739
+ numbers,
1740
+ index: 0,
1741
+ selected: new Set(numbers),
1742
+ original: new Set(numbers),
1743
+ adding: false,
1744
+ input: '',
1745
+ };
1746
+ state.mode = 'linkedIssues';
1747
+ actionError = null;
1748
+ state.scroll = 0;
1749
+ repaint();
1750
+ }
1751
+
1752
+ // S2: closing is a repository capability, resolved BEFORE the confirmation
1753
+ // opens, so an unpermitted viewer never reaches the write.
1754
+ function openCloseConfirm() {
1755
+ const row = selected();
1756
+ if (!row) return;
1757
+ if (!permissionsFor(row).canClosePullRequests) {
1758
+ actionError = 'pull requests cannot be closed: this repository permission is missing';
1759
+ repaint();
1760
+ return;
1761
+ }
1762
+ state.mode = 'confirm';
1763
+ // S2 (D1): the confirmation names the pull request it showed, and the write
1764
+ // acts on THAT number however a reload rearranged the rows behind it.
1765
+ state.confirm = { action: 'close', number: numOf(row) };
1766
+ actionError = null;
1767
+ repaint();
1768
+ }
1769
+
1770
+ function moveSelection(step) {
1771
+ const total = filteredRows().length;
1772
+ if (total === 0) return;
1773
+ state.index = (state.index + step + total) % total;
1774
+ state.scroll = 0;
1775
+ actionError = null;
1776
+ ensurePullRequest(selected());
1777
+ if (step > 0 && state.index === total - 1) loadMoreRows();
1778
+ repaint();
1779
+ }
1780
+
1781
+ function activatePage(index) {
1782
+ if (pages.length === 0) return;
1783
+ const at = Math.floor(Number(index));
1784
+ state.page = Number.isFinite(at) ? Math.max(0, Math.min(pages.length - 1, at)) : 0;
1785
+ state.index = 0;
1786
+ state.listStart = 0;
1787
+ state.scroll = 0;
1788
+ state.searching = false;
1789
+ actionError = null;
1790
+ // S5/S6 (D7): the pinned numbered open belongs to the bucket it opened in;
1791
+ // a tab the reader chose paints that bucket alone.
1792
+ pinnedNumber = null;
1793
+ if (serverMode) {
1794
+ const rt = bucketState(pages[state.page]);
1795
+ state.loadError = null;
1796
+ if (rt.query === String(state.query || '') && (rt.loaded || rt.loading)) {
1797
+ state.loading = rt.loading;
1798
+ state.listStart = Math.max(0, Math.floor(Number(rt.start) || 0));
1799
+ state.index = Math.max(0, Math.floor(Number(rt.index) || 0));
1800
+ clampSelection();
1801
+ ensurePullRequest(selected());
1802
+ repaint();
1803
+ return;
1804
+ }
1805
+ requestBucketPage(state.page, {});
1806
+ return;
1807
+ }
1808
+ ensurePullRequest(selected());
1809
+ repaint();
1810
+ }
1811
+
1812
+ function switchPage(step) {
1813
+ if (pages.length === 0) return;
1814
+ const tabs = tabPageIndices();
1815
+ const at = tabs.indexOf(state.page);
1816
+ if (at < 0) return;
1817
+ activatePage(tabs[(at + step + tabs.length) % tabs.length]);
1818
+ }
1819
+
1820
+ // S1: the shortcut enters the lazy view and, pressed again, returns to the tab
1821
+ // the reader came from.
1822
+ function toggleLazyView() {
1823
+ const lazyAt = lazyPageIndex();
1824
+ if (lazyAt < 0) return;
1825
+ if (state.page === lazyAt) {
1826
+ const tabs = tabPageIndices();
1827
+ const previous = tabs.includes(state.allFrom) ? state.allFrom : tabs[0];
1828
+ state.allFrom = null;
1829
+ activatePage(previous);
1830
+ return;
1831
+ }
1832
+ state.allFrom = state.page;
1833
+ activatePage(lazyAt);
1834
+ }
1835
+
1836
+ function scrollList(step) {
1837
+ const list = filteredRows();
1838
+ if (list.length === 0) return;
1839
+ const costs = list.map((row) => listRowCost(row, listWidthCache));
1840
+ const budget = Math.max(1, bodyRows);
1841
+ const target = layout.shiftWindow(costs, { budget, start: state.listStart, step });
1842
+ if (target !== state.listStart) {
1843
+ state.listStart = target;
1844
+ const win = layout.scrollWindow(costs, { budget, index: target, start: target });
1845
+ state.listStart = win.start;
1846
+ if (state.index < win.start || state.index >= win.end) {
1847
+ state.index = win.start;
1848
+ state.scroll = 0;
1849
+ ensurePullRequest(selected());
1850
+ }
1851
+ if (serverMode) {
1852
+ const bucket = pages[state.page];
1853
+ if (bucket) bucketState(bucket).start = state.listStart;
1854
+ }
1855
+ }
1856
+ if (step > 0) loadMoreRows();
1857
+ repaint();
1858
+ }
1859
+
1860
+ // S10: the one-line description of the write in flight.
1861
+ const SAVE_LABELS = {
1862
+ labels: 'saving labels…',
1863
+ assignees: 'saving assignees…',
1864
+ comment: 'posting comment…',
1865
+ close: 'closing pull request…',
1866
+ merge: 'merging pull request…',
1867
+ linkedIssues: 'saving linked issues…',
1868
+ };
1869
+
1870
+ function saveLabel(kind) {
1871
+ return SAVE_LABELS[kind] || 'saving…';
1872
+ }
1873
+
1874
+ function beginSave(kind) {
1875
+ state.saving = kind;
1876
+ actionError = null;
1877
+ notice = null;
1878
+ repaint();
1879
+ }
1880
+
1881
+ function settleSave(pending, onOk, onFail) {
1882
+ const finish = (result) => {
1883
+ if (!active) return;
1884
+ state.saving = null;
1885
+ if (result && result.ok === true) onOk(result);
1886
+ else onFail((result && result.error) || 'action failed');
1887
+ };
1888
+ Promise.resolve(pending).then(finish).catch((err) => {
1889
+ finish({ ok: false, error: (err && err.message) || 'action failed' });
1890
+ });
1891
+ }
1892
+
1893
+ function applyLabels() {
1894
+ if (!labelDraft || state.saving !== null) return;
1895
+ const edit = actionFor(['editLabels', 'editPullRequestLabels']);
1896
+ if (edit === null) {
1897
+ actionError = 'label editing is unavailable';
1898
+ repaint();
1899
+ return;
1900
+ }
1901
+ const draft = labelDraft;
1902
+ const number = draft.number;
1903
+ const add = [...draft.selected].filter((name) => !draft.original.has(name));
1904
+ const remove = [...draft.original].filter((name) => !draft.selected.has(name));
1905
+ const created = draft.created.slice();
1906
+ beginSave('labels');
1907
+ // S2 (D3, D14, D26): the capability is re-read for the draft's own number at
1908
+ // save time — the NEWEST answer for it wins — so a permission the reload
1909
+ // revoked never reaches the write seam. Creating a repository label is its
1910
+ // own capability, decided on the same fresh read.
1911
+ const gate = freshGate(number, 'canEditLabels', {
1912
+ refusal: 'labels cannot be edited: this repository permission is missing',
1913
+ notOpen: `pull request #${number} is not open; its labels cannot be edited`,
1914
+ });
1915
+ settleCaptured(gate.then((verdict) => {
1916
+ if (verdict.ok !== true) return verdict;
1917
+ if (created.length > 0 && verdict.capabilities.canCreateLabels !== true) {
1918
+ return { ok: false, error: 'new labels cannot be created: this repository permission is missing', exit: true };
1919
+ }
1920
+ return runSeam(edit, number, add, remove, created);
1921
+ }), () => {
1922
+ const row = filteredRows().find((candidate) => numOf(candidate) === number);
1923
+ // The list row keeps the saved labels for its own display; the DETAIL
1924
+ // cache is dropped, never patched, so the pane reads GitHub again.
1925
+ if (row) row.labels = [...draft.selected].map((name) => ({ name }));
1926
+ labelDraft = null;
1927
+ state.mode = 'list';
1928
+ actionError = null;
1929
+ invalidateLoadedPages();
1930
+ refetchDetail(number);
1931
+ repaint();
1932
+ }, () => {
1933
+ labelDraft = null;
1934
+ state.mode = 'list';
1935
+ });
1936
+ }
1937
+
1938
+ function applyAssignees() {
1939
+ if (!assigneeDraft || state.saving !== null) return;
1940
+ const edit = actionFor(['editAssignees']);
1941
+ if (edit === null) {
1942
+ actionError = 'assignee editing is unavailable';
1943
+ repaint();
1944
+ return;
1945
+ }
1946
+ const draft = assigneeDraft;
1947
+ const number = draft.number;
1948
+ const add = [...draft.selected].filter((login) => !draft.original.has(login));
1949
+ const remove = [...draft.original].filter((login) => !draft.selected.has(login));
1950
+ beginSave('assignees');
1951
+ // S2 (D3, D26): re-read for the draft's own number, exactly like the labels,
1952
+ // so an editor save never writes with a permission the reload revoked.
1953
+ const gate = freshGate(number, 'canEditAssignees', {
1954
+ refusal: 'assignees cannot be edited: this repository permission is missing',
1955
+ notOpen: `pull request #${number} is not open; its assignees cannot be edited`,
1956
+ });
1957
+ settleCaptured(gate.then((verdict) => (verdict.ok === true ? runSeam(edit, number, { add, remove }) : verdict)), () => {
1958
+ const row = filteredRows().find((candidate) => numOf(candidate) === number);
1959
+ if (row) row.assignees = [...draft.selected].map((login) => ({ login }));
1960
+ assigneeDraft = null;
1961
+ state.mode = 'list';
1962
+ actionError = null;
1963
+ invalidateLoadedPages();
1964
+ refetchDetail(number);
1965
+ repaint();
1966
+ }, () => {
1967
+ assigneeDraft = null;
1968
+ state.mode = 'list';
1969
+ });
1970
+ }
1971
+
1972
+ // S2 (D11): the composer captures the number it was opened for, exactly like
1973
+ // the close and merge confirmations capture theirs. Commenting needs no
1974
+ // capability beyond read access, in every pull request state.
1975
+ function openCommentEditor() {
1976
+ const row = selected();
1977
+ if (!row) return;
1978
+ state.mode = 'comment';
1979
+ state.commentNumber = numOf(row);
1980
+ state.commentText = '';
1981
+ state.discardAsk = false;
1982
+ actionError = null;
1983
+ repaint();
1984
+ }
1985
+
1986
+ function closeCommentEditor() {
1987
+ state.mode = 'list';
1988
+ state.commentText = '';
1989
+ state.commentNumber = null;
1990
+ state.discardAsk = false;
1991
+ actionError = null;
1992
+ repaint();
1993
+ }
1994
+
1995
+ function postComment() {
1996
+ const post = actionFor(['commentPullRequest', 'postComment']);
1997
+ // S2/D11: the composer posts to the number it was opened on, never to
1998
+ // whatever row a reload left under the cursor.
1999
+ const number = Number.isFinite(state.commentNumber) ? state.commentNumber : NaN;
2000
+ if (post === null || !Number.isFinite(number)) {
2001
+ actionError = 'commenting is unavailable';
2002
+ repaint();
2003
+ return;
2004
+ }
2005
+ if (state.saving !== null) return;
2006
+ // S2/D22: a frame too short to hold `Comment on #N` refuses too.
2007
+ if (!stepRoomAvailable()) {
2008
+ actionError = STEP_TOO_SHORT;
2009
+ repaint();
2010
+ return;
2011
+ }
2012
+ const text = state.commentText;
2013
+ beginSave('comment');
2014
+ let result = null;
2015
+ try {
2016
+ result = post(number, text);
2017
+ } catch (err) {
2018
+ result = { ok: false, error: (err && err.message) || 'action failed' };
2019
+ }
2020
+ settleSave(result, () => {
2021
+ state.mode = 'list';
2022
+ state.commentText = '';
2023
+ state.commentNumber = null;
2024
+ state.discardAsk = false;
2025
+ actionError = null;
2026
+ notice = 'comment posted';
2027
+ invalidateLoadedPages();
2028
+ refetchDetail(number);
2029
+ repaint();
2030
+ }, (error) => {
2031
+ actionError = error;
2032
+ repaint();
2033
+ });
2034
+ }
2035
+
2036
+ function confirmClose() {
2037
+ const closePull = actionFor(['closePullRequest', 'close']);
2038
+ const confirm = state.confirm;
2039
+ if (closePull === null || !confirm || confirm.action !== 'close'
2040
+ || !Number.isFinite(confirm.number) || state.mode !== 'confirm') {
2041
+ actionError = 'closing is unavailable';
2042
+ repaint();
2043
+ return;
2044
+ }
2045
+ if (state.saving !== null) return;
2046
+ // S2/D22: a frame too short to hold `Confirm close #N` refuses instead of
2047
+ // acting on a line the reader cannot see.
2048
+ if (!stepRoomAvailable()) {
2049
+ actionError = STEP_TOO_SHORT;
2050
+ repaint();
2051
+ return;
2052
+ }
2053
+ // S2 (D1, D20): the write acts on the number the confirmation showed, and
2054
+ // that number's OWN detail — capability and state together — is re-read
2055
+ // before anything is sent, so a reload that substituted or removed the row
2056
+ // can neither redirect the close nor revive a lapsed permission.
2057
+ const number = confirm.number;
2058
+ beginSave('close');
2059
+ const gate = freshGate(number, 'canClosePullRequests', {
2060
+ refusal: 'pull requests cannot be closed: this repository permission is missing',
2061
+ notOpen: `pull request #${number} is not open; it cannot be closed`,
2062
+ });
2063
+ settleCaptured(gate.then((verdict) => (verdict.ok === true ? runSeam(closePull, number) : verdict)), () => {
2064
+ const closed = filteredRows().find((candidate) => numOf(candidate) === number);
2065
+ if (closed) closed.state = 'closed';
2066
+ const cached = details.get(number);
2067
+ if (cached && cached.pullRequest) cached.pullRequest = { ...cached.pullRequest, state: 'closed' };
2068
+ state.mode = 'list';
2069
+ state.confirm = null;
2070
+ actionError = null;
2071
+ notice = 'pull request closed';
2072
+ invalidateLoadedPages();
2073
+ clampSelection();
2074
+ repaint();
2075
+ }, () => {
2076
+ state.mode = 'list';
2077
+ state.confirm = null;
2078
+ });
2079
+ }
2080
+
2081
+ function confirmMerge() {
2082
+ const merge = actionFor(['mergePullRequest', 'merge']);
2083
+ if (merge === null || !mergeDraft) {
2084
+ actionError = 'merging is unavailable';
2085
+ repaint();
2086
+ return;
2087
+ }
2088
+ if (state.saving !== null) return;
2089
+ // S2/D22: the same frame rule as the close confirmation.
2090
+ if (!stepRoomAvailable()) {
2091
+ actionError = STEP_TOO_SHORT;
2092
+ repaint();
2093
+ return;
2094
+ }
2095
+ const draft = mergeDraft;
2096
+ const number = draft.number;
2097
+ const method = draft.methods[draft.methodIndex];
2098
+ const texts = draft.texts[method] || { subject: '', body: '' };
2099
+ // S2: a rebase merge takes neither a subject nor a body, so neither is sent.
2100
+ const payload = method === 'rebase' ? { method } : { method, subject: texts.subject, body: texts.body };
2101
+ beginSave('merge');
2102
+ // S2 (D1, D20, D30): the step's own number is re-read before it merges, and
2103
+ // the method the form is holding has to be one the repository STILL allows,
2104
+ // so a method revoked while the form was open never reaches the seam.
2105
+ const gate = freshGate(number, 'canMerge', {
2106
+ refusal: 'pull requests cannot be merged: this repository permission is missing',
2107
+ notOpen: `pull request #${number} is not open; it cannot be merged`,
2108
+ });
2109
+ settleCaptured(gate.then((verdict) => {
2110
+ if (verdict.ok !== true) return verdict;
2111
+ const fresh = allowedMergeMethods(verdict.pullRequest);
2112
+ if (fresh.includes(method) !== true) {
2113
+ const sentence = fresh.length === 0
2114
+ ? `the repository allows no merge method for pull request #${number}`
2115
+ : `the repository no longer allows the ${JSON.stringify(method)} merge method (allowed: ${fresh.join(', ')})`;
2116
+ return { ok: false, error: sentence, exit: true };
2117
+ }
2118
+ return runSeam(merge, number, payload);
2119
+ }), () => {
2120
+ const target = filteredRows().find((candidate) => numOf(candidate) === number);
2121
+ if (target) target.state = 'closed';
2122
+ mergeDraft = null;
2123
+ state.mode = 'list';
2124
+ actionError = null;
2125
+ notice = 'merged';
2126
+ invalidateLoadedPages();
2127
+ clampSelection();
2128
+ repaint();
2129
+ }, () => {
2130
+ state.mode = 'list';
2131
+ mergeDraft = null;
2132
+ });
2133
+ }
2134
+
2135
+ function applyLinkedIssues() {
2136
+ if (!linkedDraft || state.saving !== null) return;
2137
+ const edit = actionFor(['editLinkedIssues']);
2138
+ if (edit === null) {
2139
+ actionError = 'linked issue editing is unavailable';
2140
+ repaint();
2141
+ return;
2142
+ }
2143
+ const add = [...linkedDraft.selected].filter((number) => !linkedDraft.original.has(number));
2144
+ const remove = [...linkedDraft.original].filter((number) => !linkedDraft.selected.has(number));
2145
+ const number = linkedDraft.number;
2146
+ beginSave('linkedIssues');
2147
+ // S2 (D3, D20): the draft's own number is re-read before the body edit, so a
2148
+ // lapsed capability — or a pull request that is no longer open — writes
2149
+ // nothing at all.
2150
+ const gate = freshGate(number, 'canEditLinkedIssues', {
2151
+ refusal: 'linked issues cannot be edited: this repository permission is missing',
2152
+ notOpen: `pull request #${number} is not open; its linked issues cannot be edited`,
2153
+ });
2154
+ settleCaptured(
2155
+ gate.then((verdict) => (verdict.ok === true ? runSeam(edit, number, { add, remove }) : verdict)),
2156
+ () => {
2157
+ const row = filteredRows().find((candidate) => numOf(candidate) === number);
2158
+ if (row) row.linkedIssues = [...linkedDraft.selected].sort((left, right) => left - right);
2159
+ linkedDraft = null;
2160
+ state.mode = 'list';
2161
+ actionError = null;
2162
+ notice = 'linked issues updated';
2163
+ invalidateLoadedPages();
2164
+ refetchDetail(number);
2165
+ repaint();
2166
+ },
2167
+ () => {
2168
+ state.mode = 'list';
2169
+ linkedDraft = null;
2170
+ },
2171
+ );
2172
+ }
2173
+
2174
+ function commitLinkedInput() {
2175
+ if (!linkedDraft) return;
2176
+ const number = Number.parseInt(linkedDraft.input, 10);
2177
+ linkedDraft.adding = false;
2178
+ linkedDraft.input = '';
2179
+ if (!Number.isFinite(number) || number <= 0) {
2180
+ actionError = 'a linked issue needs a number';
2181
+ repaint();
2182
+ return;
2183
+ }
2184
+ if (!linkedDraft.numbers.includes(number)) linkedDraft.numbers.push(number);
2185
+ linkedDraft.numbers.sort((left, right) => left - right);
2186
+ linkedDraft.selected.add(number);
2187
+ linkedDraft.index = Math.max(0, linkedDraft.numbers.indexOf(number));
2188
+ actionError = null;
2189
+ repaint();
2190
+ }
2191
+
2192
+ // ---- search ------------------------------------------------------------
2193
+
2194
+ function scheduleQueryRead(query) {
2195
+ cancelScheduledQuery();
2196
+ state.searchPending = true;
2197
+ const entry = { query, handle: null, fired: false };
2198
+ scheduledQuery = entry;
2199
+ const run = () => {
2200
+ if (entry.fired || scheduledQuery !== entry) return;
2201
+ entry.fired = true;
2202
+ scheduledQuery = null;
2203
+ state.searchPending = false;
2204
+ if (!active || query !== String(state.query || '')) return;
2205
+ readSettledQuery();
2206
+ };
2207
+ let handle = null;
2208
+ try {
2209
+ handle = scheduleFn(run, QUERY_DEBOUNCE_MS);
2210
+ } catch {
2211
+ run();
2212
+ return;
2213
+ }
2214
+ entry.handle = handle;
2215
+ repaint();
2216
+ }
2217
+
2218
+ // S3/S4: a settled filter is what every scoped tab shows, so every scoped tab
2219
+ // reads it — not only the one on screen — and the lazy view reads it too when
2220
+ // it is the one on screen.
2221
+ function readSettledQuery() {
2222
+ if (!serverMode) return;
2223
+ tabPageIndices().forEach((index) => requestBucketPage(index, {}));
2224
+ if (insideLazyView()) requestBucketPage(state.page, {});
2225
+ }
2226
+
2227
+ function cancelScheduledQuery() {
2228
+ if (scheduledQuery === null) return false;
2229
+ const { handle } = scheduledQuery;
2230
+ scheduledQuery = null;
2231
+ state.searchPending = false;
2232
+ try {
2233
+ cancelFn(handle);
2234
+ } catch {
2235
+ // A hostile scheduler never breaks the view.
2236
+ }
2237
+ return true;
2238
+ }
2239
+
2240
+ function flushScheduledQuery() {
2241
+ if (scheduledQuery === null) return false;
2242
+ const { query } = scheduledQuery;
2243
+ cancelScheduledQuery();
2244
+ if (!active || !serverMode) return false;
2245
+ if (query !== String(state.query || '')) return false;
2246
+ readSettledQuery();
2247
+ return true;
2248
+ }
2249
+
2250
+ function setQuery(next) {
2251
+ state.query = next;
2252
+ state.index = 0;
2253
+ state.listStart = 0;
2254
+ state.scroll = 0;
2255
+ if (serverMode) {
2256
+ const current = pages[state.page] || null;
2257
+ pages.forEach((page) => {
2258
+ const rt = bucketState(page);
2259
+ rt.loaded = false;
2260
+ rt.loading = false;
2261
+ rt.seq = ++pageSeq;
2262
+ if (page.lazy === true) {
2263
+ page.rows = null;
2264
+ page.total = null;
2265
+ page.truncated = false;
2266
+ rt.rowsQuery = null;
2267
+ rt.hasMore = false;
2268
+ rt.nextCursor = null;
2269
+ rt.error = null;
2270
+ }
2271
+ });
2272
+ if (current) {
2273
+ state.loading = false;
2274
+ state.loadError = null;
2275
+ scheduleQueryRead(state.query);
2276
+ return;
2277
+ }
2278
+ }
2279
+ repaint();
2280
+ }
2281
+
2282
+ function handleSearchInput(data) {
2283
+ if (keyMatches(helpers, data, ['enter'])) {
2284
+ state.searching = false;
2285
+ state.index = 0;
2286
+ state.listStart = 0;
2287
+ state.scroll = 0;
2288
+ if (!flushScheduledQuery()) repaint();
2289
+ return true;
2290
+ }
2291
+ if (keyMatches(helpers, data, ['escape'])) {
2292
+ state.searching = false;
2293
+ state.index = 0;
2294
+ state.listStart = 0;
2295
+ if (!flushScheduledQuery()) repaint();
2296
+ return true;
2297
+ }
2298
+ if (keyMatches(helpers, data, ['delete'])) {
2299
+ setQuery('');
2300
+ return true;
2301
+ }
2302
+ if (keyMatches(helpers, data, ['backspace'])) {
2303
+ setQuery(state.query.slice(0, -1));
2304
+ return true;
2305
+ }
2306
+ if (typeof data === 'string' && data.length === 1) {
2307
+ setQuery(state.query + data);
2308
+ return true;
2309
+ }
2310
+ return false;
2311
+ }
2312
+
2313
+ function handleLabelInput(data) {
2314
+ if (labelsLoading) {
2315
+ if (keyMatches(helpers, data, ['escape'])) {
2316
+ state.mode = 'list';
2317
+ labelDraft = null;
2318
+ actionError = null;
2319
+ repaint();
2320
+ }
2321
+ return true;
2322
+ }
2323
+ const names = repoLabels.map((label) => label.name);
2324
+ const createAllowed = Boolean(labelDraft && labelDraft.createAllowed);
2325
+ const rows = createAllowed ? names.length + 1 : names.length;
2326
+ if (state.labelCreating) {
2327
+ if (keyMatches(helpers, data, ['enter'])) {
2328
+ const name = state.createName.trim();
2329
+ if (name) {
2330
+ if (!names.includes(name) && !labelDraft.created.includes(name)) labelDraft.created.push(name);
2331
+ labelDraft.selected.add(name);
2332
+ }
2333
+ state.labelCreating = false;
2334
+ state.createName = '';
2335
+ repaint();
2336
+ return true;
2337
+ }
2338
+ if (keyMatches(helpers, data, ['escape'])) {
2339
+ state.labelCreating = false;
2340
+ state.createName = '';
2341
+ repaint();
2342
+ return true;
2343
+ }
2344
+ if (keyMatches(helpers, data, ['backspace'])) {
2345
+ state.createName = state.createName.slice(0, -1);
2346
+ repaint();
2347
+ return true;
2348
+ }
2349
+ if (typeof data === 'string' && data.length === 1) {
2350
+ state.createName += data;
2351
+ repaint();
2352
+ return true;
2353
+ }
2354
+ return true;
2355
+ }
2356
+ if (keyMatches(helpers, data, ['ctrl+s'])) {
2357
+ applyLabels();
2358
+ return true;
2359
+ }
2360
+ if (keyMatches(helpers, data, ['escape'])) {
2361
+ state.mode = 'list';
2362
+ labelDraft = null;
2363
+ actionError = null;
2364
+ repaint();
2365
+ return true;
2366
+ }
2367
+ if (keyMatches(helpers, data, ['up', 'k'])) {
2368
+ state.labelIndex = (state.labelIndex - 1 + rows) % rows;
2369
+ repaint();
2370
+ return true;
2371
+ }
2372
+ if (keyMatches(helpers, data, ['down', 'j'])) {
2373
+ state.labelIndex = (state.labelIndex + 1) % rows;
2374
+ repaint();
2375
+ return true;
2376
+ }
2377
+ if (keyMatches(helpers, data, ['space', ' ', 'enter'])) {
2378
+ if (createAllowed && state.labelIndex === rows - 1) {
2379
+ state.labelCreating = true;
2380
+ state.createName = '';
2381
+ } else {
2382
+ const name = names[state.labelIndex];
2383
+ if (name) {
2384
+ if (labelDraft.selected.has(name)) labelDraft.selected.delete(name);
2385
+ else labelDraft.selected.add(name);
2386
+ }
2387
+ }
2388
+ repaint();
2389
+ return true;
2390
+ }
2391
+ if (keyMatches(helpers, data, ['n'])) {
2392
+ if (!createAllowed) return true;
2393
+ state.labelCreating = true;
2394
+ state.createName = '';
2395
+ state.labelIndex = rows - 1;
2396
+ repaint();
2397
+ return true;
2398
+ }
2399
+ return false;
2400
+ }
2401
+
2402
+ function handleAssigneeInput(data) {
2403
+ if (assigneesLoading) {
2404
+ if (keyMatches(helpers, data, ['escape'])) {
2405
+ state.mode = 'list';
2406
+ assigneeDraft = null;
2407
+ actionError = null;
2408
+ repaint();
2409
+ }
2410
+ return true;
2411
+ }
2412
+ if (keyMatches(helpers, data, ['ctrl+s'])) {
2413
+ applyAssignees();
2414
+ return true;
2415
+ }
2416
+ if (keyMatches(helpers, data, ['escape'])) {
2417
+ state.mode = 'list';
2418
+ assigneeDraft = null;
2419
+ actionError = null;
2420
+ repaint();
2421
+ return true;
2422
+ }
2423
+ const logins = assigneeRows();
2424
+ if (logins.length === 0) return true;
2425
+ if (state.assigneeIndex >= logins.length) state.assigneeIndex = logins.length - 1;
2426
+ if (keyMatches(helpers, data, ['up', 'k'])) {
2427
+ state.assigneeIndex = (state.assigneeIndex - 1 + logins.length) % logins.length;
2428
+ repaint();
2429
+ return true;
2430
+ }
2431
+ if (keyMatches(helpers, data, ['down', 'j'])) {
2432
+ state.assigneeIndex = (state.assigneeIndex + 1) % logins.length;
2433
+ repaint();
2434
+ return true;
2435
+ }
2436
+ if (keyMatches(helpers, data, ['space', ' ', 'enter'])) {
2437
+ const login = logins[state.assigneeIndex];
2438
+ if (login) {
2439
+ if (assigneeDraft.selected.has(login)) assigneeDraft.selected.delete(login);
2440
+ else assigneeDraft.selected.add(login);
2441
+ }
2442
+ repaint();
2443
+ return true;
2444
+ }
2445
+ return true;
2446
+ }
2447
+
2448
+ function handleCommentInput(data) {
2449
+ if (state.discardAsk) {
2450
+ if (keyMatches(helpers, data, ['ctrl+s'])) {
2451
+ state.discardAsk = false;
2452
+ postComment();
2453
+ return true;
2454
+ }
2455
+ if (data === 'y' || (typeof data !== 'string' && keyMatches(helpers, data, ['y']))) {
2456
+ closeCommentEditor();
2457
+ return true;
2458
+ }
2459
+ if (keyMatches(helpers, data, ['n', 'escape'])) {
2460
+ state.discardAsk = false;
2461
+ repaint();
2462
+ return true;
2463
+ }
2464
+ return true;
2465
+ }
2466
+ if (keyMatches(helpers, data, ['ctrl+s'])) {
2467
+ postComment();
2468
+ return true;
2469
+ }
2470
+ if (keyMatches(helpers, data, ['escape'])) {
2471
+ if (state.commentText !== '') {
2472
+ state.discardAsk = true;
2473
+ repaint();
2474
+ return true;
2475
+ }
2476
+ closeCommentEditor();
2477
+ return true;
2478
+ }
2479
+ if (keyMatches(helpers, data, ['enter'])) {
2480
+ state.commentText += '\n';
2481
+ repaint();
2482
+ return true;
2483
+ }
2484
+ if (keyMatches(helpers, data, ['backspace'])) {
2485
+ state.commentText = state.commentText.slice(0, -1);
2486
+ repaint();
2487
+ return true;
2488
+ }
2489
+ if (typeof data === 'string' && data.length === 1) {
2490
+ state.commentText += data;
2491
+ repaint();
2492
+ return true;
2493
+ }
2494
+ return false;
2495
+ }
2496
+
2497
+ function handleMergeInput(data) {
2498
+ if (!mergeDraft) {
2499
+ state.mode = 'list';
2500
+ return true;
2501
+ }
2502
+ if (keyMatches(helpers, data, ['ctrl+s'])) {
2503
+ confirmMerge();
2504
+ return true;
2505
+ }
2506
+ if (keyMatches(helpers, data, ['escape'])) {
2507
+ cancelMerge();
2508
+ return true;
2509
+ }
2510
+ // S2/D6: while a text field holds the focus every printable letter is TEXT,
2511
+ // so `j`/`k` never navigate the form mid-sentence; the arrows and tab alone
2512
+ // move between fields. S2/D12: a field the method does not take is not one of
2513
+ // the rows the focus can land on.
2514
+ const textField = state.mergeField === 1 || state.mergeField === 2;
2515
+ if (keyMatches(helpers, data, textField ? ['up'] : ['up', 'k'])) {
2516
+ moveMergeField(-1);
2517
+ repaint();
2518
+ return true;
2519
+ }
2520
+ if (keyMatches(helpers, data, textField ? ['down', 'tab'] : ['down', 'j', 'tab'])) {
2521
+ moveMergeField(1);
2522
+ repaint();
2523
+ return true;
2524
+ }
2525
+ if (state.mergeField === 0 && mergeDraft.methods.length > 1
2526
+ && keyMatches(helpers, data, ['left', 'right', 'space', ' ', 'h', 'l'])) {
2527
+ const step = keyMatches(helpers, data, ['left', 'h']) ? -1 : 1;
2528
+ mergeDraft.methodIndex = (mergeDraft.methodIndex + step + mergeDraft.methods.length) % mergeDraft.methods.length;
2529
+ // The new method may not offer the field that had the focus.
2530
+ if (!mergeFieldRows().includes(state.mergeField)) state.mergeField = 0;
2531
+ repaint();
2532
+ return true;
2533
+ }
2534
+ if (keyMatches(helpers, data, ['enter'])) {
2535
+ if (state.mergeField === 3) {
2536
+ confirmMerge();
2537
+ return true;
2538
+ }
2539
+ if (state.mergeField === 4) {
2540
+ cancelMerge();
2541
+ return true;
2542
+ }
2543
+ moveMergeField(1);
2544
+ repaint();
2545
+ return true;
2546
+ }
2547
+ const method = mergeDraft.methods[mergeDraft.methodIndex];
2548
+ const texts = mergeDraft.texts[method];
2549
+ if (texts && (state.mergeField === 1 || state.mergeField === 2)) {
2550
+ const field = state.mergeField === 1 ? 'subject' : 'body';
2551
+ if (keyMatches(helpers, data, ['backspace'])) {
2552
+ texts[field] = texts[field].slice(0, -1);
2553
+ repaint();
2554
+ return true;
2555
+ }
2556
+ if (typeof data === 'string' && [...data].length === 1) {
2557
+ texts[field] += data;
2558
+ repaint();
2559
+ return true;
2560
+ }
2561
+ }
2562
+ return true;
2563
+ }
2564
+
2565
+ function handleLinkedInput(data) {
2566
+ if (!linkedDraft) {
2567
+ state.mode = 'list';
2568
+ return true;
2569
+ }
2570
+ if (linkedDraft.adding) {
2571
+ if (keyMatches(helpers, data, ['enter'])) {
2572
+ commitLinkedInput();
2573
+ return true;
2574
+ }
2575
+ if (keyMatches(helpers, data, ['escape'])) {
2576
+ linkedDraft.adding = false;
2577
+ linkedDraft.input = '';
2578
+ actionError = null;
2579
+ repaint();
2580
+ return true;
2581
+ }
2582
+ if (keyMatches(helpers, data, ['backspace'])) {
2583
+ linkedDraft.input = linkedDraft.input.slice(0, -1);
2584
+ repaint();
2585
+ return true;
2586
+ }
2587
+ if (typeof data === 'string' && /^[0-9]$/.test(data)) {
2588
+ linkedDraft.input += data;
2589
+ repaint();
2590
+ return true;
2591
+ }
2592
+ return true;
2593
+ }
2594
+ if (keyMatches(helpers, data, ['ctrl+s'])) {
2595
+ applyLinkedIssues();
2596
+ return true;
2597
+ }
2598
+ if (keyMatches(helpers, data, ['escape'])) {
2599
+ state.mode = 'list';
2600
+ linkedDraft = null;
2601
+ actionError = null;
2602
+ repaint();
2603
+ return true;
2604
+ }
2605
+ const total = linkedDraft.numbers.length;
2606
+ if (keyMatches(helpers, data, ['up', 'k'])) {
2607
+ if (total > 0) linkedDraft.index = (linkedDraft.index - 1 + total) % total;
2608
+ repaint();
2609
+ return true;
2610
+ }
2611
+ if (keyMatches(helpers, data, ['down', 'j'])) {
2612
+ if (total > 0) linkedDraft.index = (linkedDraft.index + 1) % total;
2613
+ repaint();
2614
+ return true;
2615
+ }
2616
+ if (keyMatches(helpers, data, ['space', ' ', 'enter'])) {
2617
+ const number = linkedDraft.numbers[linkedDraft.index];
2618
+ if (number !== undefined) {
2619
+ if (linkedDraft.selected.has(number)) linkedDraft.selected.delete(number);
2620
+ else linkedDraft.selected.add(number);
2621
+ }
2622
+ repaint();
2623
+ return true;
2624
+ }
2625
+ if (keyMatches(helpers, data, ['n'])) {
2626
+ linkedDraft.adding = true;
2627
+ linkedDraft.input = '';
2628
+ actionError = null;
2629
+ repaint();
2630
+ return true;
2631
+ }
2632
+ return true;
2633
+ }
2634
+
2635
+ function handleInput(data) {
2636
+ if (isKeyRelease(helpers, data)) return;
2637
+ // S10: a pending write owns the keyboard.
2638
+ if (state.saving !== null) return;
2639
+ notice = null;
2640
+ // S1: the reader has the keyboard now; the opening selection is spent.
2641
+ pendingSelection = null;
2642
+ if (state.searching) {
2643
+ if (handleSearchInput(data)) return;
2644
+ return;
2645
+ }
2646
+ if (state.mode === 'labels') {
2647
+ if (handleLabelInput(data)) return;
2648
+ return;
2649
+ }
2650
+ if (state.mode === 'assignees') {
2651
+ handleAssigneeInput(data);
2652
+ return;
2653
+ }
2654
+ if (state.mode === 'comment') {
2655
+ if (handleCommentInput(data)) return;
2656
+ return;
2657
+ }
2658
+ if (state.mode === 'confirm') {
2659
+ if (keyMatches(helpers, data, ['enter', 'y'])) {
2660
+ confirmClose();
2661
+ return;
2662
+ }
2663
+ if (keyMatches(helpers, data, ['escape', 'n', 'q'])) {
2664
+ state.mode = 'list';
2665
+ state.confirm = null;
2666
+ actionError = null;
2667
+ repaint();
2668
+ return;
2669
+ }
2670
+ return;
2671
+ }
2672
+ if (state.mode === 'merge') {
2673
+ handleMergeInput(data);
2674
+ return;
2675
+ }
2676
+ if (state.mode === 'linkedIssues') {
2677
+ handleLinkedInput(data);
2678
+ return;
2679
+ }
2680
+ if (keyMatches(helpers, data, ['escape', 'ctrl+c', 'q'])) {
2681
+ close();
2682
+ return;
2683
+ }
2684
+ // D3/S10: tab and the arrows select the bucket; `]`/`[` scroll the list.
2685
+ if (keyMatches(helpers, data, ['tab'])) {
2686
+ flushScheduledQuery();
2687
+ switchPage(1);
2688
+ return;
2689
+ }
2690
+ if (keyMatches(helpers, data, ['shift+tab'])) {
2691
+ flushScheduledQuery();
2692
+ switchPage(-1);
2693
+ return;
2694
+ }
2695
+ if (keyMatches(helpers, data, ['right'])) {
2696
+ flushScheduledQuery();
2697
+ switchPage(1);
2698
+ return;
2699
+ }
2700
+ if (keyMatches(helpers, data, ['left'])) {
2701
+ flushScheduledQuery();
2702
+ switchPage(-1);
2703
+ return;
2704
+ }
2705
+ if (keyMatches(helpers, data, [']'])) {
2706
+ if (!flushScheduledQuery()) scrollList(1);
2707
+ return;
2708
+ }
2709
+ if (keyMatches(helpers, data, ['['])) {
2710
+ if (!flushScheduledQuery()) scrollList(-1);
2711
+ return;
2712
+ }
2713
+ // Resolve printable paging before a host's case-folding list matcher.
2714
+ const scrollAction = scrollKeys.resolveScrollAction(helpers, data);
2715
+ if (scrollAction) {
2716
+ const page = Math.max(1, bodyRows - 1);
2717
+ const half = scrollAction === scrollKeys.ACTIONS.HALF_DOWN || scrollAction === scrollKeys.ACTIONS.HALF_UP;
2718
+ const down = scrollAction === scrollKeys.ACTIONS.PAGE_DOWN || scrollAction === scrollKeys.ACTIONS.HALF_DOWN;
2719
+ state.scroll = Math.max(0, state.scroll + (down ? 1 : -1) * (half ? Math.max(1, Math.floor(page / 2)) : page));
2720
+ repaint();
2721
+ return;
2722
+ }
2723
+ if (keyMatches(helpers, data, ['down', 'j'])) {
2724
+ moveSelection(1);
2725
+ return;
2726
+ }
2727
+ if (keyMatches(helpers, data, ['up', 'k'])) {
2728
+ moveSelection(-1);
2729
+ return;
2730
+ }
2731
+ if (keyMatches(helpers, data, ['end'])) {
2732
+ const total = filteredRows().length;
2733
+ if (total > 0) {
2734
+ state.index = total - 1;
2735
+ state.scroll = 0;
2736
+ ensurePullRequest(selected());
2737
+ loadMoreRows();
2738
+ }
2739
+ repaint();
2740
+ return;
2741
+ }
2742
+ if (keyMatches(helpers, data, ['home'])) {
2743
+ const total = filteredRows().length;
2744
+ if (total > 0) {
2745
+ state.index = 0;
2746
+ state.listStart = 0;
2747
+ ensurePullRequest(selected());
2748
+ }
2749
+ state.scroll = 0;
2750
+ repaint();
2751
+ return;
2752
+ }
2753
+ if (keyMatches(helpers, data, ['t', 'T', '/'])) {
2754
+ state.searching = true;
2755
+ repaint();
2756
+ return;
2757
+ }
2758
+ if (keyMatches(helpers, data, ['g'])) {
2759
+ flushScheduledQuery();
2760
+ toggleLazyView();
2761
+ return;
2762
+ }
2763
+ if (keyMatches(helpers, data, ['l', 'L'])) {
2764
+ openLabelEditor();
2765
+ return;
2766
+ }
2767
+ if (keyMatches(helpers, data, ['a'])) {
2768
+ openAssigneeEditor();
2769
+ return;
2770
+ }
2771
+ if (keyMatches(helpers, data, ['c'])) {
2772
+ openCommentEditor();
2773
+ return;
2774
+ }
2775
+ if (keyMatches(helpers, data, ['i'])) {
2776
+ openLinkedEditor();
2777
+ return;
2778
+ }
2779
+ if (keyMatches(helpers, data, ['m'])) {
2780
+ openMerge();
2781
+ return;
2782
+ }
2783
+ // x/X both close the pull request, each after the host's own confirm and
2784
+ // only for a viewer whose repository permission is confirmed.
2785
+ if (keyMatches(helpers, data, ['x', 'X'])) {
2786
+ openCloseConfirm();
2787
+ return;
2788
+ }
2789
+ if (keyMatches(helpers, data, ['o'])) {
2790
+ const open = actionFor(['openBrowser']);
2791
+ const row = selected();
2792
+ if (open !== null && row) {
2793
+ try {
2794
+ open(numOf(row));
2795
+ } catch {
2796
+ // Opening the browser never mutates view state.
2797
+ }
2798
+ }
2799
+ return;
2800
+ }
2801
+ // S7: Enter is INSERT in list mode — the focused pull request goes to the
2802
+ // chat input as `PR #N` and the panel closes behind it.
2803
+ if (keyMatches(helpers, data, ['enter', 'return'])) {
2804
+ const row = selected();
2805
+ if (!row) return;
2806
+ const insert = actionFor(['insert']);
2807
+ if (insert === null) {
2808
+ actionError = 'insert is unavailable';
2809
+ repaint();
2810
+ return;
2811
+ }
2812
+ try {
2813
+ insert(`PR #${numOf(row)}`);
2814
+ } catch (err) {
2815
+ actionError = (err && err.message) || 'insert failed';
2816
+ repaint();
2817
+ return;
2818
+ }
2819
+ close();
2820
+ return;
2821
+ }
2822
+ if (keyMatches(helpers, data, ['r'])) {
2823
+ const reload = actionFor(['reload']);
2824
+ if (serverMode) {
2825
+ if (flushScheduledQuery()) return;
2826
+ requestBucketPage(state.page, { keepSelection: true });
2827
+ return;
2828
+ }
2829
+ if (reload !== null) {
2830
+ let result = null;
2831
+ try {
2832
+ result = reload();
2833
+ } catch {
2834
+ return;
2835
+ }
2836
+ settleSave(result, () => {
2837
+ refetchDetail(numOf(selected()));
2838
+ repaint();
2839
+ }, (error) => {
2840
+ actionError = error;
2841
+ repaint();
2842
+ });
2843
+ return;
2844
+ }
2845
+ const row = selected();
2846
+ if (row) refetchDetail(numOf(row));
2847
+ }
2848
+ }
2849
+
2850
+ // S6: a click inside one published range opens exactly that linked issue in
2851
+ // the other panel. Anything else — a wheel notch, a press, a cell between two
2852
+ // numbers — stays unhandled, so the host keeps its own mouse behavior.
2853
+ function handleMouse(event) {
2854
+ if (!active || !event || typeof event !== 'object') return undefined;
2855
+ if (event.type !== 'click' || event.button !== 'left') return undefined;
2856
+ if (frame.ranges.length === 0) return undefined;
2857
+ const width = Number(event.width);
2858
+ const height = Number(event.height);
2859
+ if (Number.isFinite(width) && width !== frame.width) return undefined;
2860
+ if (Number.isFinite(height) && height !== frame.height) return undefined;
2861
+ const x = Number(event.x);
2862
+ const y = Number(event.y);
2863
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return undefined;
2864
+ const hit = frame.ranges.find((range) => range.y === y && x >= range.startX && x < range.endX);
2865
+ if (!hit) return undefined;
2866
+ const openLinked = actionFor(['openLinked']);
2867
+ if (openLinked === null) return undefined;
2868
+ try {
2869
+ openLinked({ kind: 'issue', number: hit.number });
2870
+ } catch {
2871
+ // A hostile opener never breaks the view.
2872
+ }
2873
+ return { handled: true, render: false };
2874
+ }
2875
+
2876
+ function invalidate() {
2877
+ frame = { width: 0, height: 0, ranges: [] };
2878
+ }
2879
+
2880
+ ensurePullRequest(selected());
2881
+ if (serverMode) {
2882
+ requestBucketPage(state.page, {});
2883
+ if (prefetchBuckets) {
2884
+ pages.forEach((page, index) => {
2885
+ if (index === state.page || page.lazy === true || Array.isArray(page.rows)) return;
2886
+ requestBucketPage(index, {});
2887
+ });
2888
+ }
2889
+ } else {
2890
+ resolveInitialSelection(state.page);
2891
+ }
2892
+
2893
+ return { render, handleInput, handleMouse, invalidate, state };
2894
+ }
2895
+
2896
+ module.exports = { createPrsView, FOOTER_KEYS, SEARCH_KEYS };