@popcorn245/cornfield 0.37.0 → 0.39.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.
@@ -6,7 +6,10 @@
6
6
  * the map (`#sheet-dock`, which is `display: contents` from 768px up, so the desktop layout is untouched).
7
7
  * Each is a **peek** by default (a handle, a title and a line or two) and **expands** to at most half the
8
8
  * screen (60% for the node panel) with its own scroll. A tap or a swipe on the handle expands or collapses it; a tap
9
- * on the map collapses it. At most one is expanded at a time (sheet-model.js).
9
+ * on the map collapses it. At most one is expanded at a time (sheet-model.js). Spec 0010 D7: the Work panel is a sheet too, with the review
10
+ * (the proposal bar or the scenario player) and one other sheet at most (opening Work displaces the node panel and the reverse); while one is
11
+ * expanded the sheet of the other group folds to a **stub** (one 44px row: its title and its badge; a tap swaps them), and an expanded sheet is
12
+ * capped so the map keeps 35% of the screen (`--hx-sheet-cap`, sheet-model.js `sheetCap`). Escape folds an expanded sheet, then closes.
10
13
  *
11
14
  * The sheets cover the bottom of the map, so the map must not fit or follow a step into that part:
12
15
  * `measureCovered()` is the height the dock covers (0 on a desktop), kept in `state.coveredBottom`
@@ -14,7 +17,7 @@
14
17
  */
15
18
 
16
19
  import { state } from './state.js';
17
- import { createSheetModel } from './sheet-model.js';
20
+ import { createSheetModel, sheetCap } from './sheet-model.js';
18
21
  import { freeRect } from './camera.js';
19
22
 
20
23
  /** The width below which the sheets apply (matches the CSS) */
@@ -24,6 +27,9 @@ const SWIPE_PX = 20;
24
27
 
25
28
  const model = createSheetModel();
26
29
  const elements = new Map(); // id -> the sheet's element
30
+ const options = new Map(); // id -> { stub?: () => { title: string, badge?: string, label?: string }, away?: () => void } what the sheet's owner gave it
31
+ const wiredAs = new WeakMap(); // a sheet's element, and its handle -> the id their listeners were bound for
32
+ const away = new Set(); // sheets displaced by the other of their group: open on the page, hidden until opened again
27
33
  const listeners = new Set();
28
34
  let dock = null;
29
35
  let lastCovered = 0;
@@ -34,8 +40,8 @@ export const isPhone = () => typeof window !== 'undefined' && typeof window.matc
34
40
  const $ = (id) => document.getElementById(id);
35
41
  const stageOf = () => (dock && dock.parentElement) || (state.canvas ? state.canvas.parentElement : null);
36
42
 
37
- /** 'expanded' or 'peek' for a registered sheet; undefined for one that is not */
38
- export const sheetState = (id) => (model.has(id) ? (model.isExpanded(id) ? 'expanded' : 'peek') : undefined);
43
+ /** 'expanded', 'stub' or 'peek' for a registered sheet (a sheet that is not open is a peek, as it is when it opens); undefined for one that is not registered */
44
+ export const sheetState = (id) => { const st = model.stateOf(id); return st === 'hidden' ? 'peek' : st; };
39
45
  /** The id of the expanded sheet, or null */
40
46
  export const expandedSheet = () => model.expanded();
41
47
 
@@ -47,22 +53,122 @@ export function onCoveredChange(fn) {
47
53
 
48
54
  /** Puts the model on the page: each sheet's attribute and handle, the stage's `data-sheet-open`, the covered height */
49
55
  function apply() {
56
+ syncShown();
50
57
  for (const [id, el] of elements) {
51
58
  const expanded = model.isExpanded(id);
52
- el.dataset.sheetState = expanded ? 'expanded' : 'peek';
53
- const handle = el.querySelector('.hx-sheet-handle');
59
+ const st = model.stateOf(id);
60
+ el.dataset.sheetState = st === 'hidden' ? 'peek' : st;
61
+ const handle = [...el.children].find((c) => c.classList.contains('hx-sheet-handle'));
54
62
  if (handle) {
55
63
  handle.setAttribute('aria-expanded', String(expanded));
56
64
  handle.setAttribute('aria-label', expanded ? 'Collapse this panel' : 'Expand this panel');
57
65
  }
66
+ paintStub(id, el, st === 'stub');
58
67
  }
59
68
  const stage = stageOf();
60
69
  if (stage) stage.dataset.sheetOpen = model.expanded() || '';
70
+ // The expanded sheet is capped so the map keeps 35% of the screen: what is left under the stub, if there is one
71
+ if (dock && isPhone() && typeof window !== 'undefined') dock.style.setProperty('--hx-sheet-cap', `${sheetCap(window.innerHeight || 0, model.stubs())}px`);
61
72
  markLast();
62
73
  measureCovered();
63
74
  listeners.forEach((fn) => fn());
64
75
  }
65
76
 
77
+ /** Whether a sheet's element is open on the page (the proposal bar is shown, the Work panel and the node panel carry their open class) */
78
+ function isOpenOnPage(id, el) {
79
+ if (id === 'forge') return el.classList.contains('forge-open');
80
+ if (id === 'drawer') return el.classList.contains('drawer-open');
81
+ return !el.hidden && el.isConnected;
82
+ }
83
+
84
+ /**
85
+ * Brings the model's open sheets in line with the page. A sheet that has just opened beside another of its group displaces it (Work and the node
86
+ * panel take turns): the displaced one is `away` (hidden on a phone, its selection kept) and its owner is told. A sheet that is closed on the page
87
+ * is hidden in the model and is no longer away.
88
+ */
89
+ function syncShown() {
90
+ if (!isPhone()) { // the sheets are panels from 768px: nothing is displaced and nothing is a stub
91
+ away.clear();
92
+ for (const el of elements.values()) el.removeAttribute('data-sheet-away');
93
+ return;
94
+ }
95
+ for (const [id, el] of elements) {
96
+ const open = isOpenOnPage(id, el) && !away.has(id);
97
+ if (!open && !isOpenOnPage(id, el)) away.delete(id);
98
+ if (open && !model.isShown(id)) {
99
+ for (const gone of model.show(id)) displace(gone);
100
+ } else if (!open && model.isShown(id)) model.hide(id);
101
+ }
102
+ for (const [id, el] of elements) {
103
+ const gone = away.has(id);
104
+ const was = el.hasAttribute('data-sheet-away');
105
+ el.toggleAttribute('data-sheet-away', gone);
106
+ if (gone && !el.inert) el.inert = true; // out of reach of Tab while it is away
107
+ else if (!gone && was && isOpenOnPage(id, el)) el.inert = false;
108
+ }
109
+ }
110
+
111
+ /** A sheet displaced by the other of its group: hidden, not closed (the node stays selected); Work is closed by its own code */
112
+ function displace(id) {
113
+ const el = elements.get(id);
114
+ if (!el) return;
115
+ away.add(id);
116
+ const on = options.get(id);
117
+ if (on && on.away) on.away();
118
+ }
119
+
120
+ /** The stub's row: made on first use, shown only in the stub state, with the title and the badge the sheet's owner says */
121
+ function paintStub(id, el, on) {
122
+ let stub = [...el.children].find((c) => c.classList.contains('hx-sheet-stub'));
123
+ if (!stub) {
124
+ if (!on) return;
125
+ stub = document.createElement('button');
126
+ stub.type = 'button';
127
+ stub.className = 'hx-sheet-stub';
128
+ stub.dataset.corn = 'sheet-stub';
129
+ stub.addEventListener('click', (e) => { e.stopPropagation(); e.preventDefault(); expandSheet(id); const h = [...el.children].find((c) => c.classList.contains('hx-sheet-handle')); if (h && isPhone()) h.focus(); });
130
+ el.append(stub);
131
+ }
132
+ stub.hidden = !on;
133
+ if (!on) return;
134
+ const opt = options.get(id);
135
+ const said = (opt && opt.stub ? opt.stub() : null) || { title: el.getAttribute('aria-label') || id };
136
+ const title = String(said.title || '');
137
+ const badge = said.badge ? String(said.badge) : '';
138
+ const key = `${title}\u0000${badge}\u0000${said.label || ''}`;
139
+ if (stub.dataset.key === key) return;
140
+ stub.dataset.key = key;
141
+ stub.replaceChildren();
142
+ const t = document.createElement('span');
143
+ t.className = 'hx-sheet-stub-title';
144
+ t.textContent = title;
145
+ stub.append(t);
146
+ if (badge) {
147
+ const b = document.createElement('span');
148
+ b.className = 'hx-waiting-badge';
149
+ b.dataset.corn = 'waiting-badge';
150
+ b.setAttribute('aria-hidden', 'true');
151
+ b.textContent = badge;
152
+ stub.append(b);
153
+ }
154
+ stub.setAttribute('aria-label', said.label || (badge ? `${title}, ${badge}` : title));
155
+ }
156
+
157
+ /** Says a stub's words may have changed (the number waiting, a proposal's title): drawn again, if it is showing */
158
+ export function refreshStubs() {
159
+ for (const [id, el] of elements) if (model.stateOf(id) === 'stub') paintStub(id, el, true);
160
+ }
161
+
162
+ /**
163
+ * Opens a sheet's place in the dock without expanding it (Work opens as a peek, a node panel opens as a peek): the other sheet of its group is
164
+ * displaced, and this one is no longer away. Called by what opens a sheet (the node panel's code); the Work panel's open class is seen too.
165
+ */
166
+ export function showSheet(id) {
167
+ if (!elements.has(id)) return;
168
+ away.delete(id);
169
+ apply();
170
+ }
171
+
66
172
  /** The lowest visible sheet gets `data-sheet-last`: it carries the bottom safe-area inset */
67
173
  function markLast() {
68
174
  if (!dock) return;
@@ -96,7 +202,7 @@ export function measureCovered() {
96
202
  /**
97
203
  * The part of the map nothing covers, in the canvas's own CSS px: what the camera should frame a node into.
98
204
  * On a phone the dock's sheets cover the bottom; from 768px the proposal bar covers the top (and the change list it grows to hold),
99
- * the node panel the right, the Work panel the left and the scenario player the bottom. Without a layout (no page) it is the whole canvas.
205
+ * the node panel the right, the Work panel and the review column the left and the scenario player the bottom. Without a layout (no page) it is the whole canvas.
100
206
  * @returns {{ x: number, y: number, width: number, height: number }}
101
207
  */
102
208
  export function visibleMapRect() {
@@ -112,6 +218,9 @@ export function visibleMapRect() {
112
218
  if (shown(drawer) && drawer.classList.contains('drawer-open')) covers.right = drawer.offsetWidth; // its width, not its box: it slides in
113
219
  const forge = $('forge-panel');
114
220
  if (shown(forge) && forge.classList.contains('forge-open')) covers.left = forge.offsetWidth;
221
+ // the review column (review-column.js) is docked on the left under the bar: its right edge is what it covers, past the Work panel's when both are open
222
+ const column = $('review-column');
223
+ if (shown(column)) covers.left = Math.max(covers.left, Math.max(0, column.getBoundingClientRect().right - c.left) + 8);
115
224
  const player = document.querySelector('.hx-player');
116
225
  if (shown(player)) covers.bottom = Math.max(0, c.bottom - player.getBoundingClientRect().top) + 8;
117
226
  }
@@ -123,11 +232,12 @@ export function visibleMapRect() {
123
232
  // ---------------------------------------------------------------------------
124
233
 
125
234
  /** Makes `el` a sheet called `id` (a peek until expanded) and gives it a handle if it has none */
126
- export function registerSheet(id, el) {
235
+ export function registerSheet(id, el, opts = {}) {
127
236
  if (!el) return;
128
237
  unregisterSheet(id, false);
129
238
  model.add(id);
130
239
  elements.set(id, el);
240
+ options.set(id, opts);
131
241
  el.classList.add('hx-sheet');
132
242
  let handle = [...el.children].find((c) => c.classList.contains('hx-sheet-handle'));
133
243
  if (!handle) {
@@ -138,8 +248,8 @@ export function registerSheet(id, el) {
138
248
  handle.innerHTML = '<span data-corn="sheet-grip"></span>';
139
249
  el.prepend(handle);
140
250
  }
141
- bindHandle(id, handle);
142
- el.addEventListener('click', (e) => peekClick(id, e), true);
251
+ if (wiredAs.get(handle) !== id) { wiredAs.set(handle, id); bindHandle(id, handle); } // registered again (a re-init): one listener, or a tap toggles twice
252
+ if (wiredAs.get(el) !== id) { wiredAs.set(el, id); el.addEventListener('click', (e) => peekClick(id, e), true); }
143
253
  apply();
144
254
  }
145
255
 
@@ -148,13 +258,15 @@ export function unregisterSheet(id, redraw = true) {
148
258
  if (!model.has(id)) return;
149
259
  model.remove(id);
150
260
  elements.delete(id);
261
+ options.delete(id);
262
+ away.delete(id);
151
263
  if (redraw) apply();
152
264
  }
153
265
 
154
- export function expandSheet(id) { if (model.expand(id)) apply(); }
266
+ export function expandSheet(id) { syncShown(); if (model.expand(id)) apply(); } // what is open on the page is known first (a bar shown a moment ago)
155
267
  export function collapseSheet(id) { if (model.collapse(id)) apply(); }
156
268
  export function collapseAllSheets() { if (model.collapseAll()) apply(); }
157
- export function toggleSheet(id) { if (model.toggle(id)) apply(); }
269
+ export function toggleSheet(id) { syncShown(); if (model.toggle(id)) apply(); } // the same: a bar shown since the last change is open
158
270
 
159
271
  // ---------------------------------------------------------------------------
160
272
  // Taps and swipes
@@ -190,7 +302,7 @@ function bindHandle(id, handle) {
190
302
  function peekClick(id, e) {
191
303
  if (!isPhone() || model.isExpanded(id)) return;
192
304
  const target = e.target;
193
- if (target.closest && target.closest('.hx-sheet-handle')) return; // the handle's own listener
305
+ if (target.closest && target.closest('.hx-sheet-handle, .hx-sheet-stub')) return; // the handle's own listener, and the stub's (it swaps, and takes the focus to the handle)
194
306
  if (target.closest && target.closest('select, input, textarea, [data-peek-ok]')) return; // the speed menu, and the proposal's Send back, Approve and mode switcher, work from the peek
195
307
  const action = target.closest && target.closest('[data-action]');
196
308
  if (action && /close/.test(action.dataset.action)) return;
@@ -204,6 +316,20 @@ function onMapDown(e) {
204
316
  if (e.target === state.canvas && isPhone()) collapseAllSheets();
205
317
  }
206
318
 
319
+ /** Escape in an expanded sheet folds it to a peek; Escape in a peek is the sheet's own (it closes it): "folds, then closes" (spec 0010 D7) */
320
+ function onEscape(e) {
321
+ if (e.key !== 'Escape' || e.defaultPrevented || !isPhone()) return;
322
+ const id = model.expanded();
323
+ const el = id && elements.get(id);
324
+ if (!el || !el.contains(e.target)) return;
325
+ if (e.target.closest && e.target.closest('select, input, textarea')) return; // a field's own Escape first
326
+ e.preventDefault();
327
+ e.stopPropagation();
328
+ collapseSheet(id);
329
+ const handle = [...el.children].find((c) => c.classList.contains('hx-sheet-handle'));
330
+ if (handle) handle.focus();
331
+ }
332
+
207
333
  /** The dim layer behind an expanded node panel: a tap there collapses the panel to its peek (it no longer closes it) */
208
334
  function onBackdrop(e) {
209
335
  if (!isPhone()) return;
@@ -225,11 +351,13 @@ export function initSheets() {
225
351
  observers = [];
226
352
  model.ids().forEach((id) => model.remove(id));
227
353
  elements.clear();
354
+ options.clear();
355
+ away.clear();
228
356
  lastCovered = 0;
229
357
  dock = found;
230
358
  }
231
- registerSheet('proposal', $('proposal-bar'));
232
- registerSheet('drawer', $('spec-drawer'));
359
+ registerSheet('proposal', $('proposal-bar'), { stub: () => ({ title: ($('proposal-title') && $('proposal-title').textContent) || 'Proposal' }) });
360
+ registerSheet('drawer', $('spec-drawer'), { stub: () => ({ title: ($('drawer-title') && $('drawer-title').textContent) || 'Node' }) });
233
361
  if (wiredDock !== dock) {
234
362
  wiredDock = dock;
235
363
  const backdrop = $('drawer-backdrop');
@@ -248,6 +376,7 @@ export function initSheets() {
248
376
  if (!documentWired) {
249
377
  documentWired = true;
250
378
  for (const type of ['pointerdown', 'touchstart', 'mousedown']) document.addEventListener(type, onMapDown, { passive: true, capture: true });
379
+ document.addEventListener('keydown', onEscape, true);
251
380
  if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
252
381
  const mq = window.matchMedia(PHONE_QUERY);
253
382
  if (mq && mq.addEventListener) mq.addEventListener('change', () => { collapseAllSheets(); measureCovered(); });
@@ -0,0 +1,57 @@
1
+ /**
2
+ * @module explorer/waiting-line
3
+ *
4
+ * The one line under the proposal bar's buttons when a run is waiting on the open proposal (spec 0010 D2): "A run is waiting on you: Plan
5
+ * ready: approve to build, … · Answer". Answer opens Work on Runs at that run with its reply field focused (forge-panel.js). The line is its
6
+ * own element, added after the bar's head once, so the bar's own markup is not touched. The runner's words are set as text, never as HTML.
7
+ */
8
+
9
+ import { waitingLineWords } from './waiting-model.js';
10
+ import { t } from './strings.js';
11
+ import { announce } from './keyboard.js';
12
+
13
+ let line = null;
14
+ let saidFor = null;
15
+
16
+ /** The line, made on first use and kept after the bar's head; null when the bar is not on the page */
17
+ function mount() {
18
+ const body = document.getElementById('proposal-body');
19
+ if (!body) return null;
20
+ if (line && line.isConnected) return line;
21
+ line = document.createElement('p');
22
+ line.className = 'hx-waiting-line';
23
+ line.dataset.corn = 'waiting-line';
24
+ line.dataset.cornState = 'waiting';
25
+ line.hidden = true;
26
+ line.innerHTML = '<span data-waiting-words></span> <button type="button" class="hx-btn hx-forge-act" data-waiting-answer data-peek-ok data-corn-kind="secondary"></button>';
27
+ const head = body.querySelector('.hx-proposal-head');
28
+ if (head) head.after(line); else body.append(line);
29
+ return line;
30
+ }
31
+
32
+ /**
33
+ * Shows the line for `run` (the run waiting on the open proposal), or hides it for null. The first time a run is shown for a proposal it is said
34
+ * through the live region once; a repaint of the same run says nothing.
35
+ * @param {{ runId: string, report?: { note?: string } | null } | null} run
36
+ * @param {string | null} key what the line is about (the proposal), so a run is announced once for it
37
+ */
38
+ export function paintWaitingLine(run, key) {
39
+ const el = mount();
40
+ if (!el) return;
41
+ el.hidden = !run;
42
+ if (!run) { saidFor = null; return; }
43
+ const words = waitingLineWords(run);
44
+ el.querySelector('[data-waiting-words]').textContent = words;
45
+ const button = el.querySelector('[data-waiting-answer]');
46
+ button.textContent = t('answer');
47
+ button.dataset.waitingAnswer = run.runId;
48
+ button.setAttribute('aria-label', `${t('answer')}: ${words}`);
49
+ const said = `${key}|${run.runId}`;
50
+ if (saidFor !== said) { saidFor = said; announce(words); }
51
+ }
52
+
53
+ /** For tests: forget the line */
54
+ export function resetWaitingLineForTests() {
55
+ line = null;
56
+ saidFor = null;
57
+ }
@@ -0,0 +1,287 @@
1
+ /**
2
+ * @module explorer/waiting-model
3
+ *
4
+ * What is waiting on the maintainer (spec 0010), the pure half: no DOM, no `window`, no clock of its own (`nowMs` is handed in).
5
+ * One number says what asks for a decision: the specs to decide plus the runs waiting on an answer (D1). Everything else the
6
+ * panel shows of it is a function of the two lists it is handed:
7
+ *
8
+ * specStateOf a listing entry's review state: its group, its pill and since when it has been that way (D3, D4)
9
+ * specGroups the Specs tab's groups: To decide, With the agent, Approved, Drafts (D3), with the search applied (D5)
10
+ * waitingSpecs the specs to decide, as counted (a spec whose review could not be read is not counted: nobody knows it waits)
11
+ * runGroups the Runs tab's groups: Needs you, In motion, Finished, each in its order (D6)
12
+ * waitingRuns the open runs that wait on an answer (`canAnswer`)
13
+ * waiting the one number, and the tab with the oldest thing waiting (D2)
14
+ *
15
+ * The review state is the server's (`review: { verdict, by, at, current }` on a listing entry, server/proposal-pulls.js); the words that
16
+ * come from the forge (a login, a date) are data and are escaped by the view, never here.
17
+ */
18
+
19
+ import { canAnswer, groupRuns } from './runs-model.js';
20
+ import { relativeTime } from './review-model.js';
21
+ import { t } from './strings.js';
22
+
23
+ /** The groups of the Specs tab, in order, with the key each carries as `data-group` and the `strings` key of its title */
24
+ export const SPEC_GROUPS = Object.freeze([
25
+ { key: 'decide', title: 'toDecide' },
26
+ { key: 'agent', title: 'withAgent' },
27
+ { key: 'approved', title: 'approvedGroup' },
28
+ { key: 'drafts', title: 'drafts' },
29
+ ]);
30
+
31
+ /** The groups of the Runs tab, in order */
32
+ export const RUN_GROUPS = Object.freeze([
33
+ { key: 'needs', title: 'needsYou' },
34
+ { key: 'motion', title: 'inMotion' },
35
+ { key: 'finished', title: 'finished' },
36
+ ]);
37
+
38
+ /** The words of a Specs group's header (a repo may say them in its own voice: `strings`) */
39
+ export function specGroupTitle(key) {
40
+ switch (key) {
41
+ case 'decide': return t('toDecide');
42
+ case 'agent': return t('withAgent');
43
+ case 'approved': return t('approvedGroup');
44
+ default: return t('drafts');
45
+ }
46
+ }
47
+
48
+ /** The words of a Runs group's header */
49
+ export function runGroupTitle(key) {
50
+ switch (key) {
51
+ case 'needs': return t('needsYou');
52
+ case 'motion': return t('inMotion');
53
+ default: return t('finished');
54
+ }
55
+ }
56
+
57
+ /** The words of the proposal bar's button that goes to the run waiting on the proposal */
58
+ export const answerWord = () => t('answer');
59
+
60
+ /** Drafts past this many rows are collapsed behind their header (D3) */
61
+ export const DRAFTS_OPEN_MAX = 10;
62
+
63
+ /** The states of a spec row's pill, in the order the contract lists them; each is a fixed word (`SPEC_STATE_WORDS`), never the forge's */
64
+ export const SPEC_STATES = Object.freeze(['to-decide', 'changed', 'sent-back', 'approved', 'draft-pr', 'local', 'unknown']);
65
+
66
+ /** The pill's words for each state */
67
+ export const SPEC_STATE_WORDS = Object.freeze({
68
+ 'to-decide': 'To decide',
69
+ changed: 'Changed since approved',
70
+ 'sent-back': 'Sent back',
71
+ approved: 'Approved',
72
+ 'draft-pr': 'Draft PR',
73
+ local: 'Local',
74
+ unknown: 'Review state unknown',
75
+ });
76
+
77
+ /**
78
+ * The public `data-corn-state` of each pill (docs/theming.md): a spec to decide and a changed one are `waiting`, approved is `success`,
79
+ * and `sent-back` is this spec's own. A draft PR and a local copy are the `draft` they already were; an unread review is a `failure` line.
80
+ */
81
+ export const SPEC_STATE_CORN = Object.freeze({
82
+ 'to-decide': 'waiting', changed: 'waiting', 'sent-back': 'sent-back', approved: 'success', 'draft-pr': 'draft', local: 'draft', unknown: 'failure',
83
+ });
84
+
85
+ const time = (iso) => {
86
+ const ms = typeof iso === 'string' ? Date.parse(iso) : NaN;
87
+ return Number.isFinite(ms) ? ms : null;
88
+ };
89
+
90
+ /**
91
+ * What a listing entry's review says, in one of the states above, which group it is in, and since when (ms, or null when the forge gave no date):
92
+ *
93
+ * - no pull request: a draft in a checkout or a worktree (`local`, Drafts);
94
+ * - a draft pull request: with the agent (`draft-pr`), whatever was said on it before;
95
+ * - a review that could not be read (`review.error`): `unknown`. It is shown under To decide, so it is not missed, and not counted;
96
+ * - never reviewed, or pushed to since a send-back: to decide;
97
+ * - approved at the file's current hash: Approved; approved and the file changed since (`current` false): to decide, `changed`;
98
+ * - sent back and not pushed since: with the agent.
99
+ * `since` is the push that is being waited on for a spec to decide (else the pull request's own dates), the review's time for the others.
100
+ * @param {{ pull?: { draft?: boolean, createdAt?: string, updatedAt?: string, pushedAt?: string | null }, review?: { verdict?: string, at?: string, current?: boolean, error?: string } | null }} entry
101
+ * @returns {{ group: 'decide' | 'agent' | 'approved' | 'drafts', state: string, since: number | null, counted: boolean }}
102
+ */
103
+ export function specStateOf(entry) {
104
+ const pull = entry && entry.pull;
105
+ if (!pull) return { group: 'drafts', state: 'local', since: null, counted: false };
106
+ const pushed = time(pull.pushedAt) ?? time(pull.updatedAt) ?? time(pull.createdAt);
107
+ if (pull.draft) return { group: 'agent', state: 'draft-pr', since: time(pull.updatedAt) ?? time(pull.createdAt), counted: false };
108
+ const review = entry.review;
109
+ if (review && review.error) return { group: 'decide', state: 'unknown', since: pushed, counted: false };
110
+ const at = review ? time(review.at) : null;
111
+ if (!review || !['approved', 'notes'].includes(review.verdict)) return { group: 'decide', state: 'to-decide', since: pushed, counted: true };
112
+ if (review.verdict === 'approved') {
113
+ return review.current === true
114
+ ? { group: 'approved', state: 'approved', since: at, counted: false }
115
+ : { group: 'decide', state: 'changed', since: pushed, counted: true };
116
+ }
117
+ return review.current === true
118
+ ? { group: 'agent', state: 'sent-back', since: at, counted: false }
119
+ : { group: 'decide', state: 'to-decide', since: pushed, counted: true };
120
+ }
121
+
122
+ /** The specs that ask for a decision, as the number counts them (Drafts, draft PRs, sent-back, approved and unread ones are not) */
123
+ export const waitingSpecs = (entries) => (Array.isArray(entries) ? entries.filter((e) => specStateOf(e).counted) : []);
124
+
125
+ /** Whether a row matches the search: its title, slug or summary contains every word typed, in any case (D5) */
126
+ export function specMatches(entry, query) {
127
+ const words = String(query || '').toLowerCase().split(/\s+/).filter(Boolean);
128
+ if (!words.length) return true;
129
+ const hay = `${entry.title || ''}\n${entry.slug || ''}\n${entry.summary || ''}`.toLowerCase();
130
+ return words.every((w) => hay.includes(w));
131
+ }
132
+
133
+ /** Oldest first; a row with no date is last */
134
+ const oldest = (a, b) => (a.since ?? Infinity) - (b.since ?? Infinity);
135
+ /** Newest first; a row with no date is last */
136
+ const newest = (a, b) => (b.since ?? -Infinity) - (a.since ?? -Infinity);
137
+
138
+ /**
139
+ * The Specs tab's groups. Empty groups are left out (D3), unless the search emptied them: then the header still says "0 of 6" so the
140
+ * list does not seem to lose them. Each row is `{ entry, state, since }`. Within a group: To decide waiting longest first, With the agent
141
+ * and Approved newest first, Drafts by slug (spec number first, as the files are named).
142
+ * @param {object[]} entries one row for each proposal (`mergeSpecs`)
143
+ * @param {{ query?: string }} [opts]
144
+ * @returns {{ key: string, title: string, total: number, shown: number, rows: { entry: object, state: string, since: number | null, counted: boolean }[], collapsed: boolean }[]}
145
+ */
146
+ export function specGroups(entries, { query = '' } = {}) {
147
+ const rows = (Array.isArray(entries) ? entries : []).map((entry) => ({ entry, ...specStateOf(entry) }));
148
+ const filtering = String(query || '').trim() !== '';
149
+ const out = [];
150
+ for (const g of SPEC_GROUPS) {
151
+ const all = rows.filter((r) => r.group === g.key);
152
+ if (!all.length) continue;
153
+ const kept = all.filter((r) => specMatches(r.entry, query));
154
+ if (filtering && !kept.length) continue; // a search with no match in a group drops its header: "2 of 6" is for a group with something to show
155
+ const sorted = [...kept].sort(g.key === 'decide' ? oldest : g.key === 'drafts' ? (a, b) => String(a.entry.slug).localeCompare(String(b.entry.slug)) : newest);
156
+ out.push({ key: g.key, title: g.title, total: all.length, shown: kept.length, rows: sorted, collapsed: g.key === 'drafts' && !filtering && all.length > DRAFTS_OPEN_MAX });
157
+ }
158
+ return out;
159
+ }
160
+
161
+ // ---------------------------------------------------------------------------
162
+ // Runs
163
+ // ---------------------------------------------------------------------------
164
+
165
+ /** Statuses that are under way: asked for, claimed, working, or asked to stop and not stopped yet (D6) */
166
+ const IN_MOTION = new Set(['requested', 'claimed', 'working', 'stop-requested']);
167
+
168
+ /**
169
+ * Which group a run is in: `needs` (`waiting`, nobody asked it to stop: `canAnswer`), `motion`, or `finished` (done, failed, stopped, and quiet,
170
+ * which no longer counts as open). A status this does not know is finished: it is not asking anything.
171
+ * @returns {'needs' | 'motion' | 'finished'}
172
+ */
173
+ export function runGroupOf(run) {
174
+ if (canAnswer(run)) return 'needs';
175
+ if (run.open === true && IN_MOTION.has(run.status)) return 'motion';
176
+ return 'finished';
177
+ }
178
+
179
+ /** The runs waiting on an answer */
180
+ export const waitingRuns = (runs) => (Array.isArray(runs) ? runs.filter(canAnswer) : []);
181
+
182
+ /** When a run began to wait: its latest report (the question), else when it was asked (ms, or null) */
183
+ export function waitingSinceOf(run) {
184
+ const reports = (run.timeline || []).filter((e) => e && e.kind === 'report' && time(e.at) !== null);
185
+ if (reports.length) return Math.max(...reports.map((e) => time(e.at)));
186
+ return time(run.requestedAt);
187
+ }
188
+
189
+ /**
190
+ * The Runs list in groups (D6): Needs you, oldest question first; In motion, newest first; Finished, newest first. Runs of one request under
191
+ * several profiles stay together (`groupRuns`), in the group of the most urgent of them. Empty groups are left out.
192
+ * @param {object[]} runs
193
+ * @returns {{ key: string, title: string, items: ReturnType<typeof groupRuns>, count: number }[]}
194
+ */
195
+ export function runGroups(runs) {
196
+ const rank = { needs: 0, motion: 1, finished: 2 };
197
+ const placed = groupRuns(Array.isArray(runs) ? runs : []).map((item) => {
198
+ const members = item.kind === 'run' ? [item.run] : item.runs;
199
+ const key = members.map(runGroupOf).sort((a, b) => rank[a] - rank[b])[0];
200
+ const here = members.filter((r) => runGroupOf(r) === key);
201
+ const when = key === 'needs' ? Math.min(...here.map((r) => waitingSinceOf(r) ?? Infinity)) : Math.max(...members.map((r) => time(r.requestedAt) ?? -Infinity));
202
+ return { item, key, when, count: members.length };
203
+ });
204
+ return RUN_GROUPS.map((g) => {
205
+ const mine = placed.filter((p) => p.key === g.key).sort((a, b) => (g.key === 'needs' ? a.when - b.when : b.when - a.when));
206
+ return { key: g.key, title: g.title, items: mine.map((p) => p.item), count: mine.reduce((n, p) => n + p.count, 0) };
207
+ }).filter((g) => g.items.length);
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // The number
212
+ // ---------------------------------------------------------------------------
213
+
214
+ /**
215
+ * What waits on the maintainer: `specs` (to decide) plus `runs` (waiting on an answer), `total`, and the tab that holds the oldest thing
216
+ * waiting: Specs or Runs ('work' is the Runs tab's kind), null when nothing waits. A list that has not been read counts nothing.
217
+ * @param {{ specs?: object[] | null, runs?: object[] | null }} lists
218
+ * @returns {{ specs: number, runs: number, total: number, oldest: 'specs' | 'work' | null }}
219
+ */
220
+ export function waiting({ specs, runs } = {}) {
221
+ const s = waitingSpecs(specs);
222
+ const r = waitingRuns(runs);
223
+ const sSince = s.length ? Math.min(...s.map((e) => specStateOf(e).since ?? Infinity)) : null;
224
+ const rSince = r.length ? Math.min(...r.map((x) => waitingSinceOf(x) ?? Infinity)) : null;
225
+ let oldest = null;
226
+ if (s.length && r.length) oldest = (rSince ?? Infinity) < (sSince ?? Infinity) ? 'work' : 'specs';
227
+ else if (s.length) oldest = 'specs';
228
+ else if (r.length) oldest = 'work';
229
+ return { specs: s.length, runs: r.length, total: s.length + r.length, oldest };
230
+ }
231
+
232
+ /** "3 waiting on you" (the Work button's name, spoken: "Work, 3 waiting on you"), or '' when nothing waits */
233
+ export const waitingWords = (n) => (n > 0 ? `${n} ${t('waitingOnYou')}` : '');
234
+
235
+ /** The Work button's accessible name: its label, then what waits ("Work, 3 waiting on you") */
236
+ export const workButtonName = (label, n) => (n > 0 ? `${label}, ${waitingWords(n)}` : label);
237
+
238
+ /** What a group's header says: "To decide · 2", or "To decide · 2 of 6" while a search narrows it */
239
+ export const groupCountWords = (g) => (g.shown === g.total ? String(g.total) : `${g.shown} of ${g.total}`);
240
+
241
+ /**
242
+ * The words under a spec row's pill: who and when ("Approved by maintainer-one · 2 h ago", "Sent back by maintainer-one · yesterday",
243
+ * "Waiting 2 days"), or '' when there is nothing to add. `by` and the dates come from the forge: the caller escapes the result.
244
+ * @param {{ pull?: object, review?: { verdict?: string, by?: string, at?: string, error?: string } | null }} entry
245
+ * @param {number} nowMs
246
+ */
247
+ export function specStateWords(entry, nowMs) {
248
+ const s = specStateOf(entry);
249
+ const review = entry.review;
250
+ const ago = (ms) => (ms === null ? '' : relativeTime(new Date(ms).toISOString(), nowMs) || '');
251
+ const by = (verb) => [`${verb}${review && review.by ? ` by ${review.by}` : ''}`, ago(time(review && review.at))].filter(Boolean).join(' · ');
252
+ switch (s.state) {
253
+ case 'approved': return by('Approved');
254
+ case 'sent-back': return by('Sent back');
255
+ case 'changed': return `${by('Approved')}; changed since`;
256
+ case 'to-decide': {
257
+ const w = s.since === null ? '' : ago(s.since);
258
+ return !w ? '' : w === 'just now' ? 'Just arrived' : `Waiting ${w.replace(/ ago$/, '')}`;
259
+ }
260
+ default: return '';
261
+ }
262
+ }
263
+
264
+ // ---------------------------------------------------------------------------
265
+ // The proposal bar's line
266
+ // ---------------------------------------------------------------------------
267
+
268
+ /** The open run waiting on an answer that is about proposal `slug`, the one that has waited longest; null when none is */
269
+ export function runWaitingOn(runs, slug) {
270
+ if (!slug) return null;
271
+ const mine = waitingRuns(runs).filter((r) => r.refs && r.refs.proposal === slug);
272
+ return mine.sort((a, b) => (waitingSinceOf(a) ?? Infinity) - (waitingSinceOf(b) ?? Infinity))[0] || null;
273
+ }
274
+
275
+ /** The longest the runner's question is shown in the bar's line, in characters */
276
+ export const LINE_NOTE_MAX = 90;
277
+
278
+ /**
279
+ * The bar's line: "A run is waiting on you: Plan ready: approve to build, or say what to change". The runner's own words are cut to
280
+ * `LINE_NOTE_MAX` characters (the whole of it is in the run's card) and are data: the caller sets them as text.
281
+ * @param {{ report?: { note?: string } | null }} run
282
+ */
283
+ export function waitingLineWords(run) {
284
+ const note = run && run.report && typeof run.report.note === 'string' ? run.report.note.replace(/\s+/g, ' ').trim() : '';
285
+ const cut = note.length > LINE_NOTE_MAX ? `${note.slice(0, LINE_NOTE_MAX - 1).trimEnd()}\u2026` : note;
286
+ return `A run is waiting on you${cut ? `: ${cut}` : ''}`;
287
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @module explorer/waiting-view
3
+ *
4
+ * The markup of what is waiting on the maintainer (spec 0010), as strings: the Specs tab's groups with their headers, and the Runs tab's group
5
+ * headings. Pure: no DOM, no clock of its own. Every word from the forge is escaped (a row's own markup is proposal-model.js `specRowHtml`).
6
+ */
7
+
8
+ import { escHtml } from './state.js';
9
+ import { specRowHtml } from './proposal-model.js';
10
+ import { specGroupTitle, runGroupTitle, groupCountWords } from './waiting-model.js';
11
+
12
+ /**
13
+ * The Specs tab's groups, each a heading with its count and its rows. Drafts past ten rows are folded behind a button on the header
14
+ * (`draftsOpen` says whether the person opened it). With a search, a group's count reads "2 of 6".
15
+ * @param {ReturnType<import('./waiting-model.js').specGroups>} groups
16
+ * @param {{ current?: { slug: string, source: string } | null, nowMs?: number, draftsOpen?: boolean | null }} [opts]
17
+ */
18
+ export function specGroupsHtml(groups, { current = null, nowMs = Date.now(), draftsOpen = null } = {}) {
19
+ return groups.map((g) => {
20
+ const id = `spec-group-${g.key}`;
21
+ const words = `${specGroupTitle(g.key)} · ${groupCountWords(g)}`;
22
+ const foldable = g.key === 'drafts' && g.total > 10 && g.shown === g.total; // not while a search narrows it: then it is open
23
+ const folded = foldable && (draftsOpen === null ? g.collapsed : !draftsOpen);
24
+ const title = foldable
25
+ ? `<button type="button" class="hx-forge-gtoggle" data-spec-group-toggle="${escHtml(g.key)}" aria-expanded="${!folded}" aria-controls="${id}-list" data-corn-kind="quiet">${escHtml(words)}</button>`
26
+ : escHtml(words);
27
+ const rows = g.rows.map((r) => specRowHtml(r.entry, { current, nowMs })).join('');
28
+ return `<li class="hx-forge-group hx-spec-group" data-key="${id}" data-corn="spec-group" data-group="${escHtml(g.key)}"><h3 class="hx-forge-gtitle" id="${id}">${title}</h3>`
29
+ + `<ul class="hx-forge-list" id="${id}-list" aria-labelledby="${id}"${folded ? ' hidden' : ''}>${rows}</ul></li>`;
30
+ }).join('');
31
+ }
32
+
33
+ /** The heading that starts a group of the Runs list: "Needs you · 1". It is an item of the flat list (a run's card is never moved into a section) */
34
+ export function runGroupHeadingHtml(g) {
35
+ const id = `run-group-${g.key}`;
36
+ return `<li class="hx-run-heading" data-key="${id}" data-corn="run-group" data-group="${escHtml(g.key)}"><h4 class="hx-forge-gtitle" id="${id}">${escHtml(`${runGroupTitle(g.key)} · ${g.count}`)}</h4></li>`;
37
+ }