@popcorn245/cornfield 0.54.0 → 0.56.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 (45) hide show
  1. package/core/contrast.js +28 -0
  2. package/core/schema.js +24 -0
  3. package/explorer/css/page.css +0 -8
  4. package/explorer/css/work.css +3 -26
  5. package/explorer/deep-link.js +11 -24
  6. package/explorer/engine/layers.js +5 -2
  7. package/explorer/engine/map-style.js +8 -1
  8. package/explorer/engine/render.js +2 -1
  9. package/explorer/forge-panel-model.js +2 -36
  10. package/explorer/forge-panel.js +3 -7
  11. package/explorer/index.html +5 -11
  12. package/explorer/instance-state.js +0 -6
  13. package/explorer/instance.js +9 -5
  14. package/explorer/layer-model.js +1 -0
  15. package/explorer/page.js +8 -5
  16. package/explorer/pieces/layers.js +1 -1
  17. package/explorer/pieces/node-panel.js +26 -4
  18. package/explorer/pieces/search.js +9 -3
  19. package/explorer/pieces/work-agent.js +3 -2
  20. package/explorer/pieces/work-common.js +14 -15
  21. package/explorer/pieces/work-confirm.js +11 -10
  22. package/explorer/pieces/work-data.js +24 -31
  23. package/explorer/pieces/work-deploys.js +42 -41
  24. package/explorer/pieces/work-issues.js +32 -29
  25. package/explorer/pieces/work-list.js +406 -0
  26. package/explorer/pieces/work-markup.js +9 -15
  27. package/explorer/pieces/work-notes.js +0 -1
  28. package/explorer/pieces/work-paint.js +57 -67
  29. package/explorer/pieces/work-prs.js +25 -66
  30. package/explorer/pieces/work-runs.js +47 -57
  31. package/explorer/pieces/work-specs.js +19 -2
  32. package/explorer/pieces/work-threads.js +29 -49
  33. package/explorer/pieces/work.js +28 -28
  34. package/explorer/proposal-model.js +5 -5
  35. package/explorer/runs-view.js +10 -18
  36. package/explorer/scene.js +17 -10
  37. package/explorer/search-match.js +3 -2
  38. package/explorer/tokens.css +11 -0
  39. package/explorer/view.js +8 -1
  40. package/explorer/waiting-view.js +3 -3
  41. package/explorer/work-model.js +722 -0
  42. package/explorer/work-view.css +50 -0
  43. package/explorer/work-view.js +570 -0
  44. package/package.json +1 -1
  45. package/explorer/pieces/work-events.js +0 -285
@@ -0,0 +1,722 @@
1
+ /**
2
+ * @module explorer/work-model
3
+ *
4
+ * The pure half of the Work view (spec 0012 D1 to D5, D8): the map of work, from the server's answer to `GET /api/forge/work-graph`
5
+ * (server/work-graph.js: `{ ok, nodes, edges, problems }`) to nodes the scene draws, where they sit, what a layer hides, what the node panel
6
+ * says of one, what search finds and what an address asks for. No DOM, no state, no fetch: work-view.js (the page's half) holds those.
7
+ *
8
+ * - `workScene(graph, mapNodes)` the nodes and edges of the Work view: the work, the code it touches (copies of the map's nodes, and the planned
9
+ * ones a proposal adds), and the lines between them with their words
10
+ * - `layoutWork(nodes, edges, { phone })` where each node sits, and the lanes behind them; writes `x`, `y` and `r` on the nodes it is given
11
+ * - `applyFilters(nodes, edges, { layers, waiting })` sets `hidden` (a layer is off) and `dim` ("Waiting on you" is on) on the nodes
12
+ * - `layerRowsOf(nodes)` the Layers menu's rows in the Work view, each with its count in words
13
+ * - `panelOf(node, nodes, edges)` what the node panel says of a work node (kind, pills, the connected list, the words saying what comes next)
14
+ * - `workAddress(search)` what `?view=work`, `?pr=`, `?issue=`, `?run=`, `?thread=` and `?spec=` ask for
15
+ */
16
+
17
+ import { NODE_THEMES } from '../core/schema.js';
18
+ import { WORK_KINDS, WORK_THEMES, WORK_EDGE_THEMES, workType } from '../core/schema.js';
19
+ import { relativeTime } from './review-model.js';
20
+ import { SPEC_STATE_WORDS, specStateOf } from './waiting-model.js';
21
+ import { runName, canAnswer } from './runs-model.js';
22
+ import { cornState } from './corn-state.js';
23
+ import { escapeHtml as esc } from '../core/text.js';
24
+ import { safeUrl } from './pieces/work-common.js';
25
+
26
+ /** The words of a kind of work, singular and as a layer */
27
+ export const KIND_WORDS = Object.freeze({ thread: 'Thread', issue: 'Issue', proposal: 'Proposal', run: 'Agent run', pull: 'Pull request', deploy: 'Deploy' });
28
+ export const LAYER_WORDS = Object.freeze({ thread: 'Threads', issue: 'Issues', proposal: 'Proposals', run: 'Agent runs', pull: 'Pull requests', deploy: 'Deploys' });
29
+ /** The key of the one layer that holds the code the work touches, and a kind's key (the node type it has in the Work view) */
30
+ export const CODE_LAYER = 'work-code';
31
+ /** The layer of the proposals that are only files in the checkout (`state: 'local'`): nobody has asked anyone to decide them, so it starts off (spec 0012 D4) */
32
+ export const DRAFT_LAYER = 'work-drafts';
33
+ export const layerKey = workType;
34
+ /** The rows of the Layers menu, in order (the mock's: threads, issues, proposals, pull requests, agent runs, deploys; then the drafts and the code) */
35
+ export const KIND_ORDER = Object.freeze(['thread', 'issue', 'proposal', 'pull', 'run', 'deploy']);
36
+ export const LAYER_KEYS = Object.freeze([...KIND_ORDER.map(workType), DRAFT_LAYER, CODE_LAYER]);
37
+ export const CODE_LAYER_WORDS = 'Code they touch';
38
+ export const DRAFT_LAYER_WORDS = 'Drafts';
39
+ /** A proposal that is only a file in the checkout: no pull request holds it, so nobody has been asked to decide it */
40
+ export const isDraft = (item) => !!item && item.kind === 'proposal' && item.state === 'local';
41
+
42
+ /** The lanes, in order: the stage each holds (server/work-graph.js STAGES) and its title */
43
+ export const LANES = Object.freeze([
44
+ { key: 'talk', title: 'Talk' },
45
+ { key: 'decide', title: 'Decide' },
46
+ { key: 'build', title: 'Build' },
47
+ { key: 'ship', title: 'Ship' },
48
+ ]);
49
+ /** The local drafts, when their layer is on, have a lane of their own beside Decide (they are the Decide stage's, and not many people have been asked about them) */
50
+ export const DRAFT_LANE_TITLE = 'Drafts';
51
+ export const CODE_LANE_TITLE = 'Code it touches';
52
+
53
+ /** The words beside a line: the rel as the line reads from its start, and as the node at its end reads it (a connection listed in the node panel) */
54
+ export const REL_WORDS = Object.freeze({
55
+ became: ['became', 'came from'],
56
+ discusses: ['discusses', 'discussed in'],
57
+ 'agent-on': ['agent on it', 'works on'],
58
+ opened: ['opened', 'opened by'],
59
+ closes: ['closes', 'closed by'],
60
+ implements: ['implements', 'built by'],
61
+ shipped: ['shipped in', 'shipped'],
62
+ changes: ['changes', 'changed by'],
63
+ adds: ['adds', 'added by'],
64
+ mentions: ['mentions', 'mentioned in'],
65
+ restarts: ['restarts', 'restarted by'],
66
+ });
67
+ /** The word on the map for a line (once, from its start): the same as `REL_WORDS[rel][0]` */
68
+ export const relWord = (rel) => (Object.hasOwn(REL_WORDS, rel) ? REL_WORDS[rel][0] : String(rel));
69
+
70
+ /** The most characters of a title in a node's name (the whole title is the node panel's), and of the whole text drawn under a node on a desktop (its tag and the start of its title: a lane is not much wider
71
+ * than that on screen); on a phone a piece of work is drawn as its tag alone */
72
+ export const LABEL_CHARS = 34;
73
+ export const DRAWN_CHARS = 28;
74
+ const clip = (s, n) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s);
75
+ /** The same, cut at a word when one is near the end of what fits */
76
+ const clipWords = (s, n) => { if (s.length <= n) return s; const cut = s.slice(0, n - 1); const sp = cut.lastIndexOf(' '); return `${(sp > n * 0.6 ? cut.slice(0, sp) : cut).trimEnd()}…`; };
77
+ const text = (v) => (typeof v === 'string' ? v : '');
78
+ const isWork = (kind) => typeof kind === 'string' && Object.hasOwn(WORK_THEMES, kind);
79
+
80
+ /** The number of a spec: the leading digits of its slug ("0100-flow" is "0100"), else the slug */
81
+ const specNumber = (slug) => { const m = /^(\d{2,6})(?:-|$)/.exec(slug); return m ? m[1] : slug; };
82
+
83
+ /** What a piece of work is called on the map, short: "PR #27", "Issue #14", "Thread #31", "Spec 0100", "Run abc123", "Deploy" */
84
+ export function tagOf(item) {
85
+ switch (item.kind) {
86
+ case 'pull': return `PR #${item.number}`;
87
+ case 'issue': return `Issue #${item.number}`;
88
+ case 'thread': return `Thread #${item.number}`;
89
+ case 'proposal': return `Spec ${specNumber(text(item.slug))}`;
90
+ case 'run': return `Run ${text(item.runId).slice(-6)}`;
91
+ default: return 'Deploy';
92
+ }
93
+ }
94
+
95
+ /** What a search reads of a piece of work besides its label: `#21`, `PR 21`, `pull request 21`, the slug, the run id, the title */
96
+ export function termsOf(item) {
97
+ const terms = [tagOf(item), text(item.title), KIND_WORDS[item.kind]];
98
+ const n = item.number;
99
+ if (Number.isInteger(n)) terms.push(`#${n}`, String(n), `pr ${n}`, `pull ${n}`, `pull request ${n}`, `issue ${n}`, `thread ${n}`);
100
+ if (item.slug) terms.push(item.slug, specNumber(item.slug), `spec ${specNumber(item.slug)}`);
101
+ if (item.runId) terms.push(item.runId);
102
+ if (item.name) terms.push(item.name);
103
+ return terms.filter((t) => typeof t === 'string' && t !== '');
104
+ }
105
+
106
+ /** A node the graph names that the map does not hold: a planned one, by its type (an unknown type reads as a page) */
107
+ const plannedType = (type) => (typeof type === 'string' && Object.hasOwn(NODE_THEMES, type) ? type : 'page');
108
+
109
+ /**
110
+ * The node of a piece of work: what the scene draws and the node panel shows for it. `item` is a node of the server's graph, or an old piece of work made
111
+ * by `oldItem` (older than the graph's 14 days, or past its caps: the Work list reaches it, and the node panel shows it by the same path, `old: true`).
112
+ */
113
+ export function workNode(item, degree = 0) {
114
+ const theme = WORK_THEMES[item.kind];
115
+ const title = text(item.title) || tagOf(item);
116
+ const draft = isDraft(item);
117
+ return {
118
+ id: item.id, type: workType(item.kind), work: item.kind, shape: theme.shape, label: item.kind === 'deploy' ? `Deploy · ${clip(title, LABEL_CHARS)}` : `${tagOf(item)} · ${clip(title, LABEL_CHARS)}`,
119
+ title, item, r: theme.r, color: theme.color, letters: theme.letters, terms: termsOf(item), groupName: draft ? DRAFT_LAYER_WORDS : LAYER_WORDS[item.kind],
120
+ draft, waiting: item.waiting === true, updated: text(item.updated), stage: text(item.stage), degree, x: 0, y: 0,
121
+ };
122
+ }
123
+
124
+ /** What the Work list holds that the graph does not: a node for it, drawn nowhere (`old`), for the node panel */
125
+ export const oldNode = (item) => ({ ...workNode(item), old: true });
126
+
127
+ /**
128
+ * A piece of work the graph does not hold (older than its 14 days, or past its caps), as a node of the graph would give it, made from what the Work list read
129
+ * of it: a pull request or an issue of the lists, a thread, a run of the runs list, a deploy, a proposal of the specs list. Null for a kind or a shape it cannot read.
130
+ * Every word of it is the forge's: the panel escapes it, and `url` is an http(s) link or nothing.
131
+ * @param {string} kind pull | issue | thread | run | deploy | proposal
132
+ * @param {object} src the list's own item
133
+ */
134
+ export function oldItem(kind, src) {
135
+ if (!src || typeof src !== 'object') return null;
136
+ const who = (a) => (a && typeof a.login === 'string' ? a.login : null);
137
+ const base = { kind, title: text(src.title), url: safeUrl(src.url), updated: text(src.updatedAt) || text(src.createdAt), waiting: false };
138
+ const num = Number.isInteger(src.number) ? src.number : null;
139
+ switch (kind) {
140
+ case 'pull': return num === null ? null : { ...base, id: `pull:${num}`, stage: 'build', state: text(src.state), open: src.state === 'open', number: num, draft: src.draft === true, author: who(src.author) };
141
+ case 'issue': return num === null ? null : { ...base, id: `issue:${num}`, stage: 'talk', state: text(src.state), open: src.state === 'open', number: num, author: who(src.author) };
142
+ case 'thread': return num === null ? null : { ...base, id: `thread:${num}`, stage: 'talk', state: text(src.state), open: src.state === 'open', number: num, threadKind: text(src.kind), author: who(src.author) };
143
+ case 'run': return typeof src.runId === 'string' ? { ...base, id: `run:${src.runId}`, stage: 'build', title: runName(src), state: text(src.status), open: src.open === true, waiting: canAnswer(src), runId: src.runId, number: null, url: safeUrl(src.report && src.report.url) || safeUrl(src.comment && src.comment.url) || safeUrl(src.pull && src.pull.url), updated: text(src.lastActivity) || text(src.requestedAt), runKind: text(src.kind), requestedBy: src.requestedBy ?? null } : null;
144
+ case 'deploy': return typeof src.id === 'string' ? { ...base, id: `deploy:${src.id}`, stage: 'ship', title: text(src.title) || text(src.name), state: text(src.state), open: src.state === 'queued' || src.state === 'running', deployId: src.id, number: null, updated: text(src.updatedAt) || text(src.createdAt), name: text(src.name), branch: text(src.branch), sha: text(src.sha), author: who(src.actor) } : null;
145
+ case 'proposal': {
146
+ if (typeof src.slug !== 'string') return null;
147
+ const { state, counted } = specStateOf(src);
148
+ const pull = src.pull && Number.isInteger(src.pull.number) ? src.pull : null;
149
+ return { ...base, id: `proposal:${src.slug}`, stage: 'decide', title: text(src.title) || src.slug, state, open: true, waiting: counted, slug: src.slug, number: pull ? pull.number : null, url: safeUrl(pull && pull.url), updated: text(pull && (pull.updatedAt || pull.createdAt)), draft: state === 'local', author: who(pull && pull.author), source: text(src.source) };
150
+ }
151
+ default: return null;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * The scene of the Work view.
157
+ * @param {{ nodes?: object[], edges?: { from: string, to: string, rel: string }[] } | null} graph the server's answer
158
+ * @param {{ id: string, label?: string, type?: string }[]} mapNodes the map's nodes (the code a piece of work touches is found among them by id)
159
+ * @returns {{ nodes: object[], edges: object[], counts: { work: number, code: number, waiting: number } }}
160
+ */
161
+ export function workScene(graph, mapNodes) {
162
+ const items = Array.isArray(graph && graph.nodes) ? graph.nodes : [];
163
+ const links = Array.isArray(graph && graph.edges) ? graph.edges : [];
164
+ const onMap = new Map((mapNodes || []).map((n) => [n.id, n]));
165
+ const work = new Map();
166
+ const planned = new Map();
167
+ for (const item of items) {
168
+ if (!item || typeof item.id !== 'string') continue;
169
+ if (item.kind === 'code') { if (item.planned === true) planned.set(item.id, item); continue; }
170
+ if (isWork(item.kind)) work.set(item.id, item);
171
+ }
172
+ // The edges that join two things on this map: work to work, or work to code the map holds or a proposal plans
173
+ const edges = [];
174
+ const seen = new Set();
175
+ for (const e of links) {
176
+ if (!e || typeof e.from !== 'string' || typeof e.to !== 'string' || !Object.hasOwn(REL_WORDS, e.rel)) continue;
177
+ const from = work.has(e.from) ? 'work' : null;
178
+ const to = work.has(e.to) ? 'work' : onMap.has(e.to) || planned.has(e.to) ? 'code' : null;
179
+ if (!from || !to) continue;
180
+ const key = `${e.from}->${e.to}|${e.rel}`;
181
+ if (seen.has(key)) continue;
182
+ seen.add(key);
183
+ edges.push({ from: e.from, to: e.to, kind: e.rel, tone: to === 'work' ? 'work' : 'code', word: relWord(e.rel) });
184
+ }
185
+ // The code that work touches, and by how many pieces of it
186
+ const touched = new Map();
187
+ for (const e of edges) if (e.tone === 'code') touched.set(e.to, (touched.get(e.to) || new Set()).add(e.from));
188
+
189
+ const degree = new Map();
190
+ for (const e of edges) { degree.set(e.from, (degree.get(e.from) || 0) + 1); degree.set(e.to, (degree.get(e.to) || 0) + 1); }
191
+ const nodes = [];
192
+ for (const item of work.values()) nodes.push(workNode(item, degree.get(item.id) || 0));
193
+ let code = 0;
194
+ for (const [id, by] of touched) {
195
+ const base = onMap.get(id);
196
+ const plan = planned.get(id);
197
+ if (!base && !plan) continue;
198
+ code++;
199
+ nodes.push(base
200
+ ? { ...base, x: 0, y: 0, r: CODE_R, touches: by.size, degree: by.size, hidden: false, dim: false }
201
+ : { id, type: plannedType(plan.type), label: text(plan.label) || id, planned: true, r: CODE_R, touches: by.size, degree: by.size, x: 0, y: 0, groupName: CODE_LAYER_WORDS });
202
+ }
203
+ const waiting = nodes.filter((n) => n.waiting).length;
204
+ return { nodes, edges, counts: { work: work.size, code, waiting } };
205
+ }
206
+
207
+ /**
208
+ * One line of the Work view for the scene (spec 0012 D2, D3): a work-to-work link solid, `mentions` dotted, `adds` dashed; the word of its rel beside a lit one. The scene calls it
209
+ * for every line (`state.workEdge`, put there by `showWork`), so the map's own code carries no table of the Work view's lines.
210
+ * @param {object} edge the line, `{ from, to, kind, tone, word }`
211
+ * @param {object} source the node it starts at
212
+ * @param {object} target the node it ends at
213
+ * @param {boolean} connected whether it joins the selection's neighbourhood
214
+ * @param {boolean} focused whether a node is selected
215
+ * @param {string} key the line's key
216
+ * @param {{ PROPOSED_DASH: number[], USAGE_DASH: number[] }} dashes the map's two dash patterns
217
+ * @param {Partial<Record<'work' | 'code' | 'adds', string>>} [colors] what the theme's `--corn-work-edge-<name>` tokens say (`state.workEdgeColors`); a name it does not set is drawn in its default (core/schema.js WORK_EDGE_THEMES)
218
+ */
219
+ export function workEdge(edge, source, target, connected, focused, key, dashes, colors) {
220
+ const lit = focused && connected;
221
+ const name = edge.kind === 'adds' ? 'adds' : edge.tone === 'work' ? 'work' : 'code';
222
+ const color = (colors && colors[name]) || WORK_EDGE_THEMES[name];
223
+ const faded = source.dim === true && target.dim === true; // "Waiting on you" is on and neither end waits
224
+ return {
225
+ key, from: edge.from, to: edge.to, kind: edge.kind,
226
+ x1: source.x, y1: source.y, x2: target.x, y2: target.y, r1: source.r, r2: target.r,
227
+ color, width: lit ? 2.4 : 1.4, alpha: faded ? 0.12 : focused ? (connected ? 1 : 0.08) : 0.35,
228
+ dash: edge.kind === 'adds' ? dashes.PROPOSED_DASH : edge.kind === 'mentions' ? dashes.USAGE_DASH : null,
229
+ ticks: 0, curve: null, arrow: false, end: null, glow: 0, glowColor: null,
230
+ label: lit ? { text: typeof edge.word === 'string' && edge.word ? edge.word : edge.kind, x: (source.x + target.x) / 2, y: (source.y + target.y) / 2, color, italic: false } : null,
231
+ packet: null, mark: 'none', live: false,
232
+ };
233
+ }
234
+
235
+ /** The radius of a node of code in the Work view: small beside the work it is touched by */
236
+ export const CODE_R = 9;
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // Where it sits
240
+ // ---------------------------------------------------------------------------
241
+
242
+ /** Waiting first, then the newest, then by id: the order within a lane (spec 0012 D3) */
243
+ export const byLane = (a, b) => (a.waiting === b.waiting ? 0 : a.waiting ? -1 : 1) || (a.updated < b.updated ? 1 : a.updated > b.updated ? -1 : 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
244
+ /** Most touched first, then by name: the order of the code */
245
+ export const byTouch = (a, b) => (b.touches || 0) - (a.touches || 0) || String(a.label).localeCompare(String(b.label)) || (a.id < b.id ? -1 : 1);
246
+
247
+ /**
248
+ * The sizes the layout works in. World units, laid out for the zoom the first fit will have, so a name under a node (11 px at least, whatever the zoom: labels.js) has
249
+ * the room on screen it needs: a cell is wide enough for a name, a row tall enough for a disc and a name under it, and lanes next to each other are staggered by half a row
250
+ * so a name that runs past its lane lands between the next lane's. `margin` is what the first fit leaves on screen around the lanes, in px (the names at the edge, and the toggles at the top).
251
+ */
252
+ const DESK = { cell: 200, row: 70, codeCell: 190, codeRow: 44, gap: 14, pad: 6, margin: { x: 100, top: 56, bottom: 24 }, caps: [100, 64, 48, 40, 32, 28, 24, 20, 18, 16, 14, 12, 10, 9, 8, 7, 6, 5] };
253
+ const PHONE = { cell: 104, row: 84, codeCell: 150, codeRow: 40, gap: 12, pad: 4, margin: { x: 36, top: 112, bottom: 16 } };
254
+ /** A lane's title (screen px) the first node sits under, and a name under a node (its gap and its line, px) */
255
+ const TITLE_PX = 40;
256
+ const NAME_PX = 22;
257
+ const LANE_FILL = 'rgba(66, 153, 225, 0.05)';
258
+ const LANE_STROKE = 'rgba(66, 153, 225, 0.18)';
259
+
260
+ /** A lane behind the nodes (`SceneLane`: scene.js, with no text of its own: its title is a line of the page, in screen space, work-view.js), and what the title says */
261
+ const lane = (key, title, count, x, y, w, h) => ({ key, name: title, count, x, y, w, h, radius: 14, fill: LANE_FILL, stroke: LANE_STROKE, strokeWidth: 1, title: null, note: null, arrow: null });
262
+
263
+ /** The text drawn under a node: a piece of work's tag and the start of its title (a phone: the tag), the name of a node of code (a phone: the start of it) */
264
+ function nameNodes(nodes, phone) {
265
+ for (const n of nodes) {
266
+ if (n.work) { const tag = tagOf(n.item); n.labelText = phone ? tag : `${tag} · ${clipWords(n.title, Math.max(8, DRAWN_CHARS - tag.length - 3))}`; }
267
+ else n.labelText = clip(String(n.label), phone ? 12 : 32);
268
+ }
269
+ }
270
+
271
+ /** The zoom that shows `w` by `h` world units with the margins left around them, on a screen `v.width` by `v.height`; at most 1 */
272
+ const zoomFor = (w, h, v, m) => Math.min(1, Math.max(1, v.width - 2 * m.x) / Math.max(1, w), Math.max(1, v.height - m.top - m.bottom) / Math.max(1, h));
273
+
274
+ /** The box the camera fits (engine/render.js `fitTarget`): the lanes, and around them the margins at the zoom that shows them; the engine's own padding `p` is taken out of it */
275
+ function fitBoxOf(w, h, z, m, p, v) {
276
+ const minY = -(m.top - p) / z;
277
+ // as tall as the screen shows at that zoom, so the lanes stay under the toggles when they are shorter than the screen (the fit centres the box)
278
+ return { minX: -(m.x - p) / z, maxX: w + (m.x - p) / z, minY, maxY: Math.max(h + (m.bottom - p) / z, minY + (v.height - 2 * p) / z), zoom: z };
279
+ }
280
+
281
+ /**
282
+ * Where the nodes sit: four lanes of work, then the code it touches (spec 0012 D3), made for the screen it is on. A desktop's lanes run left to right, and a lane (the
283
+ * drafts' and the code's most of all) is cut into as many columns as show the most of it at once; a phone's run top to bottom (Talk, Decide, Build and Ship in one), with the code in
284
+ * columns beside them. Only what is not hidden is laid out. Writes `x`, `y` and `labelText` on the nodes and returns the lanes behind them and the box the first fit shows.
285
+ * @param {object[]} nodes the nodes of `workScene`
286
+ * @param {{ phone?: boolean, width?: number, height?: number, padding?: number }} [opts] the map's size in px, and the engine's padding around a fit
287
+ * @returns {{ lanes: object[], order: string[], bounds: { x: number, y: number, w: number, h: number }, fit: { minX: number, maxX: number, minY: number, maxY: number, zoom: number } }}
288
+ */
289
+ export function layoutWork(nodes, { phone = false, width = 1200, height = 800, padding = phone ? 44 : 96 } = {}) {
290
+ nameNodes(nodes, phone);
291
+ const shown = nodes.filter((n) => !n.hidden);
292
+ const mine = (key) => shown.filter((n) => n.work && !n.draft && n.stage === key).sort(byLane);
293
+ const stages = LANES.map((l) => ({ ...l, nodes: mine(l.key) }));
294
+ // A kind of work the server gave no stage still has a lane: the kind's own
295
+ const known = new Set(stages.flatMap((s) => s.nodes.map((n) => n.id)));
296
+ for (const n of shown.filter((x) => x.work && !x.draft && !known.has(x.id))) stages.find((s) => s.key === { thread: 'talk', issue: 'talk', proposal: 'decide', run: 'build', pull: 'build', deploy: 'ship' }[n.work]).nodes.push(n);
297
+ stages.forEach((s) => s.nodes.sort(byLane));
298
+ const drafts = shown.filter((n) => n.draft).sort(byLane);
299
+ const code = shown.filter((n) => !n.work).sort(byTouch);
300
+ const v = { width: Math.max(160, width), height: Math.max(160, height) };
301
+ return phone ? layoutPhone(stages, drafts, code, v, padding) : layoutDesk(stages, drafts, code, v, padding);
302
+ }
303
+
304
+ /** How many columns a lane of `n` nodes has when a column holds at most `cap`, and how tall they are */
305
+ const cut = (n, cap) => { const cols = Math.max(1, Math.ceil(n / cap)); return { cols, rows: Math.max(1, Math.ceil(n / cols)) }; };
306
+
307
+ function layoutDesk(stages, drafts, code, v, p) {
308
+ const c = DESK;
309
+ // Left to right: Talk, Decide, the drafts (when they are shown), Build, Ship, then the code
310
+ const lanes = [stages[0], stages[1], ...(drafts.length ? [{ key: 'drafts', title: DRAFT_LANE_TITLE, nodes: drafts }] : []), stages[2], stages[3], ...(code.length ? [{ key: 'code', title: CODE_LANE_TITLE, nodes: code, code: true }] : [])];
311
+ const plan = (z, cap) => {
312
+ const room = TITLE_PX / z;
313
+ const below = NAME_PX / z;
314
+ let left = 0;
315
+ let tall = 0;
316
+ const parts = lanes.map((l, i) => {
317
+ const cell = l.code ? c.codeCell : c.cell;
318
+ const row = l.code ? c.codeRow : c.row;
319
+ const r = l.code ? CODE_R : 20;
320
+ const { cols, rows } = cut(l.nodes.length, cap);
321
+ const w = cols * cell + 2 * c.pad;
322
+ const stagger = cols > 1 || i % 2 ? 0.5 : 0;
323
+ const h = room + 2 * r + (rows - 1 + stagger) * row + below + 8;
324
+ tall = Math.max(tall, h);
325
+ const part = { l, i, cell, row, r, cols, rows, x: left, w, h };
326
+ left += w + c.gap;
327
+ return part;
328
+ });
329
+ return { parts, w: left - c.gap, h: tall, room };
330
+ };
331
+ let z = 0.6;
332
+ let best = null;
333
+ for (let pass = 0; pass < 3; pass++) {
334
+ best = null;
335
+ for (const cap of c.caps) {
336
+ const g = plan(z, cap);
337
+ const fit = zoomFor(g.w, g.h, v, c.margin);
338
+ if (!best || fit > best.fit * 1.01) best = { g, fit, cap };
339
+ }
340
+ z = best.fit;
341
+ }
342
+ const { g } = best;
343
+ const out = [];
344
+ for (const part of g.parts) {
345
+ const { l, i, cell, row, r, cols, rows } = part;
346
+ l.nodes.forEach((n, j) => {
347
+ const col = Math.floor(j / rows);
348
+ n.x = part.x + c.pad + (col + 0.5) * cell;
349
+ n.y = g.room + r + (j % rows + ((i + col) % 2) * 0.5) * row;
350
+ });
351
+ out.push(lane(l.key, l.title, l.nodes.length, part.x, 0, part.w, g.h));
352
+ }
353
+ return { lanes: out, order: g.parts.flatMap((part) => part.l.nodes.map((n) => n.id)), bounds: { x: 0, y: 0, w: g.w, h: g.h }, fit: fitBoxOf(g.w, g.h, z, c.margin, p, v) };
354
+ }
355
+
356
+ function layoutPhone(stages, drafts, code, v, p) {
357
+ const c = PHONE;
358
+ const bands = [stages[0], stages[1], ...(drafts.length ? [{ key: 'drafts', title: DRAFT_LANE_TITLE, nodes: drafts }] : []), { key: 'build-ship', title: 'Build · Ship', nodes: [...stages[2].nodes, ...stages[3].nodes] }];
359
+ const plan = (z, perRow, codeCols) => {
360
+ const room = TITLE_PX / z;
361
+ const below = NAME_PX / z;
362
+ const wBand = perRow * c.cell + 2 * c.pad;
363
+ let y = 0;
364
+ const parts = bands.map((b) => {
365
+ const rows = Math.max(1, Math.ceil(b.nodes.length / perRow));
366
+ const h = room + 40 + (rows - 1 + (perRow > 1 ? 0.5 : 0)) * c.row + below + 8;
367
+ const part = { b, rows, y, h };
368
+ y += h + c.gap;
369
+ return part;
370
+ });
371
+ const hBands = y - c.gap;
372
+ const codeRows = Math.max(1, Math.ceil(code.length / codeCols));
373
+ const wCode = code.length ? codeCols * c.codeCell + 2 * c.pad : 0;
374
+ const hCode = code.length ? room + 2 * CODE_R + (codeRows - 1 + (codeCols > 1 ? 0.5 : 0)) * c.codeRow + below + 8 : 0;
375
+ return { parts, wBand, wCode, hBands, hCode, codeRows, room, w: wBand + (code.length ? c.gap + wCode : 0), h: Math.max(hBands, hCode) };
376
+ };
377
+ let z = 0.5;
378
+ let best = null;
379
+ for (let pass = 0; pass < 3; pass++) {
380
+ best = null;
381
+ for (const perRow of [2, 3, 4]) {
382
+ for (const codeCols of code.length ? [1, 2, 3] : [1]) {
383
+ const g = plan(z, perRow, codeCols);
384
+ const fit = zoomFor(g.w, g.h, v, c.margin);
385
+ if (!best || fit > best.fit * 1.01) best = { g, fit, perRow, codeCols };
386
+ }
387
+ }
388
+ z = best.fit;
389
+ }
390
+ const { g, perRow, codeCols } = best;
391
+ const out = [];
392
+ for (const part of g.parts) {
393
+ part.b.nodes.forEach((n, j) => { n.x = c.pad + (j % perRow + 0.5) * c.cell; n.y = part.y + g.room + 20 + (Math.floor(j / perRow) + ((j % perRow) % 2) * 0.5) * c.row; });
394
+ out.push(lane(part.b.key, part.b.title, part.b.nodes.length, 0, part.y, g.wBand, part.h));
395
+ }
396
+ if (code.length) {
397
+ const x0 = g.wBand + c.gap;
398
+ code.forEach((n, j) => { const col = Math.floor(j / g.codeRows); n.x = x0 + c.pad + (col + 0.5) * c.codeCell; n.y = g.room + CODE_R + (j % g.codeRows + (col % 2) * 0.5) * c.codeRow; });
399
+ out.push(lane('code', CODE_LANE_TITLE, code.length, x0, 0, g.wCode, g.hCode));
400
+ }
401
+ return { lanes: out, order: [...g.parts.flatMap((part) => part.b.nodes.map((n) => n.id)), ...code.map((n) => n.id)], bounds: { x: 0, y: 0, w: g.w, h: g.h }, fit: fitBoxOf(g.w, g.h, z, c.margin, p, v) };
402
+ }
403
+
404
+ // ---------------------------------------------------------------------------
405
+ // Layers and "Waiting on you"
406
+ // ---------------------------------------------------------------------------
407
+
408
+ /** The layers as the Work view starts them: every one on but the drafts (the local proposals nobody has been asked to decide) */
409
+ export const startLayers = () => Object.fromEntries(LAYER_KEYS.map((k) => [k, k !== DRAFT_LAYER]));
410
+
411
+ /**
412
+ * Sets `hidden` and `dim` on the nodes. A piece of work is hidden when its layer is off; code when its layer is off or every piece of work that touches it is
413
+ * hidden (only code that work touches is drawn). With "Waiting on you" on, everything that does not wait is dimmed.
414
+ */
415
+ export function applyFilters(nodes, edges, { layers = startLayers(), waiting = false } = {}) {
416
+ const on = (key) => layers[key] !== false;
417
+ const shown = new Set();
418
+ for (const n of nodes) { n.hidden = n.draft ? !on(DRAFT_LAYER) : n.work ? !on(workType(n.work)) : false; if (n.work && !n.hidden) shown.add(n.id); }
419
+ const reached = new Set();
420
+ for (const e of edges) if (e.tone === 'code' && shown.has(e.from)) reached.add(e.to);
421
+ for (const n of nodes) {
422
+ if (!n.work) n.hidden = !on(CODE_LAYER) || !reached.has(n.id);
423
+ n.dim = waiting && !n.waiting;
424
+ }
425
+ return nodes;
426
+ }
427
+
428
+ /** The Layers menu's rows in the Work view: `{ key, label, color, desc, countText }`, the six kinds, the local drafts and the code they touch */
429
+ export function layerRowsOf(nodes) {
430
+ const of = (kind) => nodes.filter((n) => n.work === kind && !n.draft);
431
+ const word = (n, w) => `${n} ${w}`;
432
+ const rows = KIND_ORDER.map((kind) => {
433
+ const list = of(kind);
434
+ const open = list.filter((n) => n.item.open === true).length;
435
+ const waiting = list.filter((n) => n.waiting).length;
436
+ const countText = kind === 'proposal' ? (waiting ? word(waiting, 'to decide') : String(list.length))
437
+ : kind === 'run' ? (waiting ? word(waiting, 'waiting') : String(list.length))
438
+ : kind === 'pull' || kind === 'issue' ? word(open, 'open')
439
+ : String(list.length);
440
+ return { key: workType(kind), label: LAYER_WORDS[kind], color: WORK_THEMES[kind].color, desc: `${KIND_WORDS[kind]} nodes: ${list.length}`, countText, count: list.length };
441
+ });
442
+ const drafts = nodes.filter((n) => n.draft).length;
443
+ rows.push({ key: DRAFT_LAYER, label: DRAFT_LAYER_WORDS, color: WORK_THEMES.proposal.color, desc: 'Proposals that are only files in the checkout: no pull request holds them, nobody has been asked to decide them', countText: word(drafts, 'local'), count: drafts });
444
+ const codeCount = nodes.filter((n) => !n.work).length;
445
+ rows.push({ key: CODE_LAYER, label: CODE_LAYER_WORDS, color: NODE_THEMES.page.color, desc: 'The code the work touches', countText: String(codeCount), count: codeCount });
446
+ return rows;
447
+ }
448
+
449
+ /** How many wait on the maintainer in this answer (spec 0010 D1's number: the server worked it out) */
450
+ export const waitingCountOf = (nodes) => nodes.filter((n) => n.waiting).length;
451
+
452
+ // ---------------------------------------------------------------------------
453
+ // The node panel
454
+ // ---------------------------------------------------------------------------
455
+
456
+ const PILL_OF = { open: 'open', closed: 'closed', merged: 'merged', success: 'success', failure: 'failure', running: 'running', queued: 'queued', waiting: 'waiting', done: 'done', failed: 'failed', stopped: 'stopped' };
457
+
458
+ /** A word for a piece of work's own state: "Open", "Merged", "To decide", "Failed" */
459
+ export function stateWordsOf(item) {
460
+ if (item.kind === 'proposal') return SPEC_STATE_WORDS[item.state] || text(item.state) || 'Proposal';
461
+ if (item.kind === 'pull') return item.state === 'open' ? (item.draft ? 'Draft' : 'Open') : item.state === 'merged' ? 'Merged' : 'Closed';
462
+ if (item.kind === 'deploy') return ({ success: 'Succeeded', failure: 'Failed', running: 'Running', queued: 'Waiting', cancelled: 'Cancelled', skipped: 'Skipped', neutral: 'Finished' })[item.state] || text(item.state);
463
+ if (item.kind === 'run') return text(item.state).replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase());
464
+ return item.open ? 'Open' : 'Closed';
465
+ }
466
+
467
+ /** The public `data-corn-state` word of a piece of work's state (corn-state.js), or '' */
468
+ export function pillStateOf(item) {
469
+ if (item.waiting) return 'waiting';
470
+ if (item.kind === 'pull') return item.draft ? 'draft' : PILL_OF[item.state] || '';
471
+ if (item.kind === 'proposal') return ({ 'to-decide': 'waiting', changed: 'waiting', approved: 'success', 'sent-back': 'sent-back', 'draft-pr': 'draft' })[item.state] || '';
472
+ if (item.kind === 'run') return ({ requested: 'requested', claimed: 'claimed', working: 'working', waiting: 'waiting', quiet: 'waiting', done: 'done', failed: 'failed', stopped: 'stopped' })[item.state] || '';
473
+ return PILL_OF[item.state] || (item.open ? 'open' : 'closed');
474
+ }
475
+
476
+ /** What the node panel says of what comes next, above the actions: what each will do */
477
+ export function saysOf(item) {
478
+ switch (item.kind) {
479
+ case 'proposal': return item.waiting ? 'This waits on you. Review opens it over the map (Before, Diff, After); there you approve it or send it back.' : 'Review opens it over the map (Before, Diff, After).';
480
+ case 'pull': return item.state === 'open' ? 'Land it merges this pull request at the head shown, once every check has passed; a failed check can be run again.' : 'Nothing waits on you.';
481
+ case 'issue': return item.open ? 'Start an agent asks a runner to work on this issue; a confirm step shows what will be asked.' : 'Nothing waits on you.';
482
+ case 'run': return item.waiting ? 'This waits on your answer: reply, continue or stop it.' : item.open ? 'You can stop it while it works.' : 'Nothing waits on you.';
483
+ case 'thread': return 'A thread is a conversation on the forge: read it here, and reply there.';
484
+ default: return 'Its logs are on the forge; here is what it restarted.';
485
+ }
486
+ }
487
+
488
+ /**
489
+ * What the node panel says of a piece of work (the page draws it: work-view.js).
490
+ * @param {object} node a node of the Work view (a piece of work)
491
+ * @param {object[]} nodes every node of the view
492
+ * @param {object[]} edges every edge of the view
493
+ * @param {{ now?: number }} [opts]
494
+ */
495
+ export function panelOf(node, nodes, edges, { now = Date.now() } = {}) {
496
+ const item = node.item;
497
+ const byId = new Map(nodes.map((n) => [n.id, n]));
498
+ const pills = [{ text: stateWordsOf(item), state: pillStateOf(item) }];
499
+ if (item.waiting) pills.push({ text: 'Waiting on you', state: 'waiting' });
500
+ if (item.kind === 'proposal' && Number.isInteger(item.number)) pills.push({ text: `PR #${item.number}`, state: '' });
501
+ if (item.kind === 'run' && item.runKind) pills.push({ text: text(item.runKind), state: '' });
502
+ const meta = [item.author ? text(item.author) : '', relativeTime(item.updated, now)].filter(Boolean).join(' · ');
503
+ const links = [];
504
+ for (const e of edges) {
505
+ const out = e.from === node.id;
506
+ const other = byId.get(out ? e.to : e.from);
507
+ if (!other || (!out && e.to !== node.id)) continue;
508
+ links.push({ rel: REL_WORDS[e.kind][out ? 0 : 1], id: other.id, label: other.label, work: other.work || '', code: !other.work, planned: other.planned === true });
509
+ }
510
+ // Work first (in the order of the lanes), then code; the same words together
511
+ const rank = (l) => (l.work ? LANES.findIndex((x) => x.key === (byId.get(l.id).stage || '')) : 9);
512
+ links.sort((a, b) => rank(a) - rank(b) || a.rel.localeCompare(b.rel) || a.label.localeCompare(b.label));
513
+ return { kind: KIND_WORDS[item.kind], tag: tagOf(item), title: node.title, color: WORK_THEMES[item.kind].color, pills, meta, links, says: saysOf(item), url: text(item.url) };
514
+ }
515
+
516
+ // ---------------------------------------------------------------------------
517
+ // The panel's markup: every word that came from the forge is escaped, every link goes through `safeUrl` (an http or https address, else no link)
518
+ // ---------------------------------------------------------------------------
519
+ const pill = (p) => `<span class="hx-forge-state${p.state ? ` hx-forge-state--${esc(p.state)}` : ''}" data-corn="state-pill"${cornState(p.state) ? ` data-corn-state="${esc(cornState(p.state))}"` : ''}>${esc(p.text)}</span>`;
520
+ const dotOf = (kind, color) => { const c = typeof color === 'function' ? color(kind) : ''; return `<span class="hx-work-dot" data-corn="swatch" data-work-kind="${esc(kind || 'code')}" aria-hidden="true"${c ? ` data-style="background-color: ${esc(c)}"` : ''}></span>`; };
521
+ const linkButton = (l) => `<button type="button" class="hx-linkbtn" data-corn="node-link" data-action="select-node" data-id="${esc(l.id)}">${esc(l.label)}</button>`;
522
+
523
+ /**
524
+ * The node panel's markup for a piece of work (`panelOf`'s answer): its state, what it is connected to (each a button that selects that node), the words saying what the
525
+ * actions will do, the place the actions go (`forge-detail`: the Work piece fills it, pieces/work-paint.js `paintDetail`: Land it, the checks, a run's answer field, Start an agent ...),
526
+ * and a link to the forge when the address is a web one and the actions do not carry it.
527
+ * @param {ReturnType<typeof panelOf>} p
528
+ * @param {object} node
529
+ * @param {{ color?: (kind: string) => string }} [opts] `color`: a kind's colour as the map draws it
530
+ */
531
+ export function workPanelHtml(p, node, { color = () => '' } = {}) {
532
+ const url = safeUrl(p.url);
533
+ const kind = node.item.kind;
534
+ const links = node.old
535
+ ? '<div class="hx-fact" data-corn="section"><div class="hx-fact-k">Connected</div><div class="hx-fact-v hx-faint">Its links are not drawn here: it is older than the 14 days the map of work covers, or past its limits.</div></div>'
536
+ : p.links.length
537
+ ? `<div class="hx-fact" data-corn="section"><div class="hx-fact-k">Connected</div><div class="hx-fact-v"><ul class="hx-work-links" data-corn="work-links">${p.links.map((l) => `<li data-corn="work-link"><span class="hx-work-rel">${esc(l.rel)}</span>${dotOf(l.work, color)}${linkButton(l)}${l.planned ? ' <span class="hx-faint">planned</span>' : ''}</li>`).join('')}</ul></div></div>`
538
+ : '<div class="hx-fact" data-corn="section"><div class="hx-fact-k">Connected</div><div class="hx-fact-v hx-faint">Nothing it is linked to is drawn.</div></div>';
539
+ // A pull request's (a spec's too) and a deploy's own actions carry their link to the forge; the others get it here
540
+ const specPull = kind === 'proposal' && Number.isInteger(node.item.number); // its pull request's actions carry the link
541
+ const out = url && kind !== 'pull' && kind !== 'deploy' && !specPull ? `<a class="hx-btn hx-btn--quiet hx-foot-btn" data-corn-kind="quiet" data-corn="open-link" href="${esc(url)}" target="_blank" rel="noreferrer">Open on the forge ↗</a>` : '';
542
+ const actions = `<div class="hx-work-actions" data-corn="work-actions"><p class="hx-faint">${esc(p.says)}</p><section id="forge-detail" class="hx-forge-detail" data-corn="work-detail" aria-label="Actions" data-work-kind="${esc(kind)}" data-work-ref="${esc(node.id)}"></section>${out}</div>`;
543
+ return `<div class="hx-work-head" data-corn="work-head"><p class="hx-work-pills" data-corn="work-pills">${p.pills.map(pill).join(' ')}</p><p class="hx-faint">${esc(p.tag)}${p.meta ? ` · ${esc(p.meta)}` : ''}</p></div>${links}${actions}`;
544
+ }
545
+
546
+ /** The node panel's section for a node of code in the Work view: the work that touches it, and "Show on the map" (a planned node is not on the map yet) */
547
+ export function codePanelHtml(node, touching, { color = () => '' } = {}) {
548
+ const list = touching.length
549
+ ? `<ul class="hx-work-links" data-corn="work-links">${touching.map((l) => `<li data-corn="work-link"><span class="hx-work-rel">${esc(l.rel)}</span>${dotOf(l.work, color)}${linkButton(l)}</li>`).join('')}</ul>`
550
+ : '<p class="hx-faint">No work touches it now.</p>';
551
+ const show = node.planned ? '' : `<button type="button" class="hx-btn hx-btn--secondary hx-foot-btn" data-corn-kind="secondary" data-work-action="show-on-map" data-id="${esc(node.id)}">Show on the map</button>`;
552
+ return `<div class="hx-fact" data-corn="section"><div class="hx-fact-k">Work</div><div class="hx-fact-v">${node.planned ? '<p class="hx-faint">Planned: a proposal adds it, and the map does not hold it yet.</p>' : ''}${list}${show}</div></div>`;
553
+ }
554
+
555
+ /** The work that touches a node of code, as the node panel lists it: `{ rel, id, label, work }` */
556
+ export function touchedBy(node, nodes, edges) {
557
+ const byId = new Map(nodes.map((n) => [n.id, n]));
558
+ const out = [];
559
+ for (const e of edges) {
560
+ if (e.to !== node.id) continue;
561
+ const from = byId.get(e.from);
562
+ if (from && from.work) out.push({ rel: REL_WORDS[e.kind][1], id: from.id, label: from.label, work: from.work, waiting: from.waiting });
563
+ }
564
+ return out.sort((a, b) => Number(b.waiting) - Number(a.waiting) || a.label.localeCompare(b.label));
565
+ }
566
+
567
+ // ---------------------------------------------------------------------------
568
+ // The keyboard (N and P step through the lanes; an arrow goes to the nearest node that way)
569
+ // ---------------------------------------------------------------------------
570
+
571
+ /** The node an arrow goes to from `from`: the nearest shown node that way, a little more for each step aside; null when there is none (and the first of `order` when nothing is selected) */
572
+ export function arrowTarget(nodes, from, key) {
573
+ const dir = { ArrowRight: [1, 0], ArrowLeft: [-1, 0], ArrowDown: [0, 1], ArrowUp: [0, -1] }[key];
574
+ if (!dir) return null;
575
+ const shown = nodes.filter((n) => !n.hidden && n.x !== undefined);
576
+ if (!from) return null;
577
+ let best = null;
578
+ let bestScore = Infinity;
579
+ for (const n of shown) {
580
+ if (n === from || n.id === from.id) continue;
581
+ const along = (n.x - from.x) * dir[0] + (n.y - from.y) * dir[1];
582
+ if (along < 1) continue;
583
+ const aside = Math.abs((n.x - from.x) * dir[1]) + Math.abs((n.y - from.y) * dir[0]);
584
+ if (aside > (dir[0] ? 2 * along + 60 : 0.6 * along + 40)) continue; // a cone: Down stays in its column, Right may reach a lane whose rows are a little off
585
+ const score = along + 3 * aside;
586
+ if (score < bestScore) { best = n; bestScore = score; }
587
+ }
588
+ return best;
589
+ }
590
+
591
+ /** What a screen reader hears when the keyboard lands on a node of the Work view: its name, its kind and state, what waits, and its place in the lanes */
592
+ export function landingWords(node, index, count) {
593
+ if (!node.work) return `${node.label}, code${node.planned ? ', planned' : ''}, ${node.touches || 0} ${node.touches === 1 ? 'piece' : 'pieces'} of work touch it, ${index + 1} of ${count}`;
594
+ const item = node.item;
595
+ return `${node.label}, ${KIND_WORDS[item.kind].toLowerCase()}${node.draft ? ' (a local draft)' : ''}, ${stateWordsOf(item).toLowerCase()}${node.waiting ? ', waiting on you' : ''}, ${index + 1} of ${count}`;
596
+ }
597
+
598
+ // ---------------------------------------------------------------------------
599
+ // Addresses and search
600
+ // ---------------------------------------------------------------------------
601
+
602
+ const NUMBER = /^[1-9][0-9]{0,8}$/;
603
+ const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
604
+
605
+ /**
606
+ * What an address asks of the Work view (spec 0012 D8): `{ view: true }` for `?view=work`, and which node to select for `?pr=`, `?issue=`, `?thread=`, `?run=`
607
+ * and `?spec=` (a number or a slug). One link asks for one node: the first of them in that order. A value that cannot be a name is `{ bad }`. Null when it asks nothing.
608
+ * @param {string} search
609
+ * @returns {{ view: boolean, kind?: string, key?: string, bad?: string } | null}
610
+ */
611
+ export function workAddress(search) {
612
+ const params = new URLSearchParams(search || '');
613
+ const asks = [['pr', 'pull'], ['issue', 'issue'], ['thread', 'thread'], ['run', 'run'], ['spec', 'proposal']];
614
+ for (const [param, kind] of asks) {
615
+ if (!params.has(param)) continue;
616
+ const value = params.get(param) || '';
617
+ const good = kind === 'run' ? /^run-[0-9A-Za-z]{26}$/.test(value) : kind === 'proposal' ? SLUG.test(value) : NUMBER.test(value);
618
+ if (!good) return { view: true, kind, bad: `${value ? `"${value.slice(0, 40)}"` : 'That'} is not ${kind === 'pull' ? 'a pull request number' : kind === 'issue' ? 'an issue number' : kind === 'thread' ? 'a thread number' : kind === 'run' ? 'a run id' : 'a spec number or name'}.` };
619
+ return { view: true, kind, key: value };
620
+ }
621
+ return params.get('view') === 'work' ? { view: true } : null;
622
+ }
623
+
624
+ /** The id of the node an address or a row of the Work list names, among the nodes of the view, or null (a spec by its number, `0100`, or by its whole slug; a deploy by its id) */
625
+ export function nodeForAddress(ask, nodes) {
626
+ if (!ask || !ask.kind) return null;
627
+ const mine = nodes.filter((n) => n.work === ask.kind);
628
+ if (ask.kind === 'pull' && !mine.some((n) => String(n.item.number) === ask.key)) { const spec = nodes.find((n) => n.work === 'proposal' && String(n.item.number) === ask.key); if (spec) return spec.id; } // a spec's pull request is its proposal
629
+ if (ask.kind === 'issue' && !mine.some((n) => String(n.item.number) === ask.key)) { const idea = nodes.find((n) => n.work === 'thread' && String(n.item.number) === ask.key); if (idea) return idea.id; } // an idea is an issue on the forge, drawn as a thread
630
+ const hit = ask.kind === 'proposal'
631
+ ? mine.find((n) => n.item.slug === ask.key) || mine.find((n) => specNumber(text(n.item.slug)) === ask.key)
632
+ : ask.kind === 'run' ? mine.find((n) => n.item.runId === ask.key) : ask.kind === 'deploy' ? mine.find((n) => n.item.deployId === ask.key) : mine.find((n) => String(n.item.number) === ask.key);
633
+ return hit ? hit.id : null;
634
+ }
635
+
636
+ /** The address a node of work has in the page (`?pr=27`), so a link can be given; null for a node that has none (a deploy) */
637
+ export function addressOf(node) {
638
+ const i = node && node.item;
639
+ if (!i) return null;
640
+ if (i.kind === 'pull') return `?pr=${i.number}`;
641
+ if (i.kind === 'issue') return `?issue=${i.number}`;
642
+ if (i.kind === 'thread') return `?thread=${i.number}`;
643
+ if (i.kind === 'run') return `?run=${encodeURIComponent(i.runId)}`;
644
+ if (i.kind === 'proposal') return `?spec=${encodeURIComponent(i.slug)}`;
645
+ return null;
646
+ }
647
+
648
+ /** The words a screen reader hears when the view opens: "Work: 14 pieces of work, 3 waiting on you, and the 9 nodes of code they touch." */
649
+ export function openedWords({ work, code, waiting }) {
650
+ const w = `${work} ${work === 1 ? 'piece' : 'pieces'} of work`;
651
+ const c = code ? `, and the ${code} ${code === 1 ? 'node' : 'nodes'} of code ${code === 1 ? 'it touches' : 'they touch'}` : '';
652
+ return `Work: ${w}${waiting ? `, ${waiting} waiting on you` : ''}${c}.`;
653
+ }
654
+
655
+ // ---------------------------------------------------------------------------
656
+ // The view on the state (the same way house-model.js holds the House view's)
657
+ // ---------------------------------------------------------------------------
658
+
659
+ /** What the Work view keeps on the state (`state.work`): the answer, the scene made of it, the layers, the toggle, and the map it stands in for while it is open */
660
+ export const newWorkState = () => ({ status: 'idle', graph: null, nodes: [], edges: [], lanes: [], counts: { work: 0, code: 0, waiting: 0 }, problems: [], layers: startLayers(), waiting: false, saved: null, bounds: null, fit: null, order: [], updating: false, stale: '', lastError: '' });
661
+
662
+ /** Makes the scene of an answer (`workScene`), keeps the node a selection named, and sets the filters; the layout is `applyWorkLayout`'s */
663
+ export function setWorkGraph(state, graph, mapNodes) {
664
+ const w = state.work || (state.work = newWorkState());
665
+ const scene = workScene(graph, mapNodes);
666
+ w.graph = graph;
667
+ w.nodes = scene.nodes;
668
+ w.edges = scene.edges;
669
+ w.counts = scene.counts;
670
+ w.problems = Array.isArray(graph && graph.problems) ? graph.problems : [];
671
+ applyFilters(w.nodes, w.edges, { layers: w.layers, waiting: w.waiting });
672
+ return w;
673
+ }
674
+
675
+ /** Puts the Work view's nodes on the state, keeping the map's to put back (`leaveWork`) */
676
+ export function enterWork(state) {
677
+ const w = state.work || (state.work = newWorkState());
678
+ if (!w.saved) w.saved = { nodes: state.nodes, edges: state.edges, rings: state.rings };
679
+ showWork(state);
680
+ }
681
+
682
+ /** The Work view's nodes, edges, layers and lanes on the state (the answer changed, or the view opened) */
683
+ export function showWork(state) {
684
+ const w = state.work;
685
+ state.workEdge = workEdge; // the scene draws the Work view's lines with it (scene.js)
686
+ state.nodes = w.nodes;
687
+ state.edges = w.edges;
688
+ state.rings = { rings: [], clusters: [] };
689
+ state.workLayers = w.layers; // set only while the view is open (leaveWork clears it): the layer code reads its presence as the Work view
690
+ state.workRows = layerRowsOf(w.nodes);
691
+ state.workLanes = w.lanes;
692
+ state.selectedNode = state.selectedNode ? w.nodes.find((n) => n.id === state.selectedNode.id) || null : null; // the same id is the same selection
693
+ state.selectedEdge = null;
694
+ }
695
+
696
+ /** The map's nodes, edges and layers as they were */
697
+ export function leaveWork(state) {
698
+ const w = state.work;
699
+ if (!w || !w.saved) return;
700
+ state.nodes = w.saved.nodes;
701
+ state.edges = w.saved.edges;
702
+ state.rings = w.saved.rings;
703
+ w.saved = null;
704
+ state.workLayers = null;
705
+ state.workRows = null;
706
+ state.workLanes = null;
707
+ state.selectedNode = state.selectedNode ? state.nodes.find((n) => n.id === state.selectedNode.id) || null : null;
708
+ state.selectedEdge = null;
709
+ }
710
+
711
+ /** Lays the Work view out for the map's size (writes on its nodes), and keeps its lanes for the scene and the box the first fit shows (`state.work.fit`: engine/render.js) */
712
+ export function applyWorkLayout(state, { phone = false } = {}) {
713
+ const w = state.work;
714
+ if (!w) return;
715
+ const laid = layoutWork(w.nodes, { phone, width: state.width || (phone ? 390 : 1200), height: state.height || (phone ? 760 : 800), padding: (state.width || 1200) < 640 ? 44 : 96 }); // the engine's own padding around a fit in this view (engine/render.js `fitPadding`)
716
+ w.lanes = laid.lanes;
717
+ w.order = laid.order;
718
+ w.bounds = laid.bounds;
719
+ w.fit = laid.fit;
720
+ state.workLanes = w.lanes;
721
+ state.workRows = layerRowsOf(w.nodes);
722
+ }