cornfield 0.34.1 → 0.34.2

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.
package/core/strings.js CHANGED
@@ -32,6 +32,7 @@ export const STRINGS = Object.freeze({
32
32
  sendBackWithNote: 'Send back with this note',
33
33
  reviewNoteLabel: 'Note for the drafting agent',
34
34
  reviewNotePlaceholder: 'What should change?',
35
+ openSpecsList: 'Open the Specs list',
35
36
  // The Work panel: its tabs run in the order of the loop
36
37
  tabSpecs: 'Specs',
37
38
  tabPulls: 'PRs',
@@ -60,6 +60,112 @@ export function pinchCamera(start, dist, mid, min = ZOOM_MIN) {
60
60
  return { x: mid.x - wx * zoom, y: mid.y - wy * zoom, zoom };
61
61
  }
62
62
 
63
+ // ---------------------------------------------------------------------------
64
+ // Framing: put these nodes in the part of the map nothing covers
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /** The zoom at which a node's label is about 11px on screen (labels are 11px in world units from LABEL_ZOOM up, scene.js): where a step or a picked change is shown */
68
+ export const READ_ZOOM = 1.0;
69
+ /**
70
+ * The lowest zoom a change is framed at when it opens (proposal.js `fitToChange`): below it node discs and marks run together, so a change
71
+ * wider than this shows is framed where most of it is (`largestGroup`), not shrunk to a speck; the rest is a row of the change list away.
72
+ * The map's own floor (render.js `getMinZoom()`, low enough for the whole map) is what hand zoom and Fit go down to.
73
+ */
74
+ export const FRAME_ZOOM_MIN = 0.18;
75
+
76
+ /**
77
+ * The part of a `width` × `height` map that nothing covers, given what covers it from each side (px).
78
+ * Never smaller than `minSize` in either direction: when the covers leave less, they are eased until it fits.
79
+ * @param {number} width
80
+ * @param {number} height
81
+ * @param {{ top?: number, bottom?: number, left?: number, right?: number }} [covers]
82
+ * @param {number} [minSize]
83
+ * @returns {{ x: number, y: number, width: number, height: number }}
84
+ */
85
+ export function freeRect(width, height, covers = {}, minSize = 120) {
86
+ const take = (total, a = 0, b = 0) => {
87
+ const lo = Math.max(0, a);
88
+ const hi = Math.max(0, b);
89
+ const room = Math.max(0, total - minSize);
90
+ const scale = lo + hi > room && lo + hi > 0 ? room / (lo + hi) : 1;
91
+ return [lo * scale, hi * scale];
92
+ };
93
+ const [top, bottom] = take(height, covers.top, covers.bottom);
94
+ const [left, right] = take(width, covers.left, covers.right);
95
+ return { x: left, y: top, width: Math.max(0, width - left - right), height: Math.max(0, height - top - bottom) };
96
+ }
97
+
98
+ /** The box a node needs on the map (world px): its disc, a little room round it and its label below */
99
+ const boxOf = (n) => {
100
+ const r = n.r || 18;
101
+ return { left: n.x - r - 25, right: n.x + r + 25, top: n.y - r - 25, bottom: n.y + r + 35 };
102
+ };
103
+ const padFor = (padding, rect) => Math.min(padding, rect.width / 4, rect.height / 4);
104
+
105
+ /**
106
+ * The camera that shows `items` (nodes with `x`, `y` and maybe `r`) inside `rect`, with their labels (room below each) and `padding` px to spare.
107
+ * The zoom is the largest that fits, between `minZoom` and `maxZoom`; when even `minZoom` does not fit, `minZoom` wins and the nodes
108
+ * are centred (the fit never goes under the floor it is given; see `largestGroup` for what to frame then).
109
+ * @param {{ x: number, y: number, r?: number }[]} items
110
+ * @param {{ x: number, y: number, width: number, height: number }} rect CSS px, in the canvas's own coordinates
111
+ * @param {{ padding?: number, maxZoom?: number, minZoom?: number }} [opts]
112
+ * @returns {Camera | null} null for no items
113
+ */
114
+ export function frameNodes(items, rect, { padding = 40, maxZoom = 1, minZoom = ZOOM_MIN } = {}) {
115
+ if (!items.length) return null;
116
+ let minX = Infinity;
117
+ let maxX = -Infinity;
118
+ let minY = Infinity;
119
+ let maxY = -Infinity;
120
+ for (const n of items) {
121
+ const b = boxOf(n);
122
+ minX = Math.min(minX, b.left);
123
+ maxX = Math.max(maxX, b.right);
124
+ minY = Math.min(minY, b.top);
125
+ maxY = Math.max(maxY, b.bottom);
126
+ }
127
+ const pad = padFor(padding, rect);
128
+ const fit = Math.min((rect.width - pad * 2) / (maxX - minX), (rect.height - pad * 2) / (maxY - minY));
129
+ const zoom = Math.max(minZoom, Math.min(maxZoom, fit));
130
+ return { x: rect.x + rect.width / 2 - ((minX + maxX) / 2) * zoom, y: rect.y + rect.height / 2 - ((minY + maxY) / 2) * zoom, zoom };
131
+ }
132
+
133
+ /** Whether every one of `items` is inside `rect` (with `margin` px to spare) under `camera` */
134
+ export function allInside(items, camera, rect, margin = 0) {
135
+ return items.every((n) => {
136
+ const sx = camera.x + n.x * camera.zoom;
137
+ const sy = camera.y + n.y * camera.zoom;
138
+ return sx >= rect.x + margin && sx <= rect.x + rect.width - margin && sy >= rect.y + margin && sy <= rect.y + rect.height - margin;
139
+ });
140
+ }
141
+
142
+ /**
143
+ * The most of `items` that fit in `rect` together at `minZoom`: all of them when they fit, else the biggest group a window of that size
144
+ * holds (so a change spread wider than the lowest zoom shows is framed where most of it is, not on the empty ground between).
145
+ * @param {{ x: number, y: number, r?: number }[]} items
146
+ * @param {{ x: number, y: number, width: number, height: number }} rect
147
+ * @param {{ padding?: number, minZoom?: number }} [opts]
148
+ */
149
+ export function largestGroup(items, rect, { padding = 40, minZoom = FRAME_ZOOM_MIN } = {}) {
150
+ if (items.length < 2) return items;
151
+ const pad = padFor(padding, rect);
152
+ const w = (rect.width - pad * 2) / minZoom;
153
+ const h = (rect.height - pad * 2) / minZoom;
154
+ const boxes = items.map(boxOf);
155
+ const holds = (left, top) => items.filter((_, i) => boxes[i].left >= left && boxes[i].right <= left + w && boxes[i].top >= top && boxes[i].bottom <= top + h);
156
+ // Every window worth trying has its left edge on some node's box and its top edge on some node's (a big change: only each node's own corner)
157
+ const lefts = boxes.map((b) => b.left);
158
+ const tops = boxes.map((b) => b.top);
159
+ let best = [];
160
+ const pairs = items.length <= 120 ? lefts.flatMap((l) => tops.map((t) => [l, t])) : boxes.map((b) => [b.left, b.top]);
161
+ for (const [l, t] of pairs) {
162
+ if (best.length === items.length) break;
163
+ const got = holds(l, t);
164
+ if (got.length > best.length) best = got;
165
+ }
166
+ return best.length ? best : [items[0]];
167
+ }
168
+
63
169
  /**
64
170
  * The camera panned (never zoomed) so a world point is inside `box` (screen px), or null when it already is. A point
65
171
  * outside is put in the middle of the box, on the axis it is outside of. `pad` is the room it needs from the edge
@@ -624,15 +624,16 @@ button.hx-proposal-item:focus-visible { outline: var(--corn-focus-width) solid v
624
624
 
625
625
  /* The proposal bar */
626
626
  .hx-proposal-bar { max-height: 50dvh; overflow-y: auto; padding: 0 var(--corn-space-4) var(--corn-space-3); }
627
- .hx-proposal-bar[data-sheet-state="peek"] > :not(.hx-sheet-handle):not(#proposal-message):not(#proposal-body),
627
+ .hx-proposal-bar[data-sheet-state="peek"] > :not(.hx-sheet-handle):not(#proposal-message):not(#proposal-ways):not(#proposal-body),
628
628
  .hx-proposal-bar[data-sheet-state="peek"] #proposal-body > :not(.hx-proposal-head),
629
- .hx-proposal-bar[data-sheet-state="peek"] .hx-proposal-head > :is(.hx-proposal-tools, .hx-proposal-more, .hx-proposal-more-menu, .hx-review) { display: none; }
629
+ .hx-proposal-bar[data-sheet-state="peek"] .hx-proposal-head > :is(.hx-proposal-tools, .hx-proposal-more, .hx-proposal-more-menu) { display: none; }
630
+ .hx-proposal-bar[data-sheet-state="peek"] .hx-review > :not([data-review-hint]):not([data-review-msg]) { display: none; } /* the peek keeps the reason Approve is off, and a refusal */
630
631
  .hx-proposal-bar[data-sheet-state="expanded"] .hx-scenarios, .hx-proposal-bar[data-sheet-state="expanded"] .hx-proposal-changes, .hx-proposal-bar[data-sheet-state="expanded"] .hx-whatif-panel { max-height: none; overflow: visible; }
631
632
 
632
633
  /* The scenario player: the title, then the step counter and its text on two lines */
633
634
  .hx-player { max-height: 50dvh; overflow: hidden; gap: var(--corn-space-2); padding: 0 var(--corn-space-4) var(--corn-space-4); --sheet-pb: var(--corn-space-4); }
634
635
  .hx-player[data-sheet-state="expanded"] { overflow-y: auto; }
635
- .hx-player[data-sheet-state="peek"] > :not(.hx-sheet-handle):not(.hx-player-head):not(.hx-player-text):not(.hx-player-track) { display: none; }
636
+ .hx-player[data-sheet-state="peek"] > :not(.hx-sheet-handle):not(.hx-player-head):not(.hx-player-text):not(.hx-player-controls):not(.hx-player-track) { display: none; } /* Previous, Pause and Next stay in the peek */
636
637
  .hx-player[data-sheet-state="peek"] .hx-player-text { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; min-height: 0; overflow: hidden; font-size: var(--corn-text-md); }
637
638
 
638
639
  /* The node panel: its title and type until expanded */
@@ -1005,6 +1006,45 @@ a.hx-forge-row:hover, button.hx-forge-row:hover { background: var(--corn-surface
1005
1006
  .hx-more-btn { display: block; margin-top: var(--corn-space-1); min-height: 0; padding: 0; font-size: var(--corn-text-sm); }
1006
1007
  @media (max-width: 767px) { .hx-more-btn { min-height: 44px; } }
1007
1008
 
1009
+ /* ---- the review flow, 0.34 design review (explorer/proposal.js, review.js, scenario-ui.js) -----------------------------
1010
+ F08 the source chip on the bar; F11 the player's controls in a phone peek; F14 the note above the keyboard; F15 the reason
1011
+ Approve is off in a peek; F16 the ways on from a bad link; F21 reflow at 400% zoom and with text spacing raised. */
1012
+ .hx-proposal-source { display: inline-flex; align-items: center; min-width: 0; max-width: 100%; padding: calc(var(--corn-space-1) / 2) var(--corn-space-3); border: var(--corn-border) solid var(--corn-line); border-radius: var(--corn-radius-pill); background: var(--corn-surface-2); color: var(--corn-text-2); font-size: var(--corn-text-xs); line-height: 1.4; text-decoration: none; overflow-wrap: anywhere; }
1013
+ .hx-proposal-source[hidden] { display: none; }
1014
+ a.hx-proposal-source { min-height: 24px; } /* a link: at least the WCAG 2.5.8 target (44px on a phone, below) */
1015
+ a.hx-proposal-source:hover { color: var(--corn-text); text-decoration: underline; }
1016
+ a.hx-proposal-source:focus-visible { outline: var(--corn-focus-width) solid var(--corn-focus); outline-offset: 2px; }
1017
+ .hx-proposal-source[data-corn-state="draft"] { border-color: color-mix(in srgb, var(--corn-changed) 50%, transparent); }
1018
+ .hx-proposal-ways { display: flex; flex-wrap: wrap; gap: var(--corn-space-2) var(--corn-space-3); margin-top: var(--corn-space-3); }
1019
+ .hx-proposal-ways[hidden] { display: none; }
1020
+ .hx-proposal-ways .hx-btn { height: auto; min-height: 32px; padding: var(--corn-space-1) var(--corn-space-4); white-space: normal; text-align: left; }
1021
+ .hx-btn[aria-disabled="true"] { opacity: 0.6; cursor: progress; } /* a review being posted: the button keeps the focus */
1022
+
1023
+ @media (max-width: 767px) {
1024
+ .hx-proposal-source { grid-column: 1 / -1; order: 1; justify-self: start; }
1025
+ .hx-player-controls .hx-btn { min-height: 44px; padding: 0 var(--corn-space-2); white-space: nowrap; }
1026
+ .hx-proposal-ways .hx-btn, a.hx-proposal-source { min-height: 44px; } /* targets a thumb can hit */
1027
+ .hx-proposal-source { padding: 0; border: 0; border-radius: 0; background: none; } /* a line of the sheet, not a pill 44px tall */
1028
+ a.hx-proposal-source { text-decoration: underline; text-underline-offset: 3px; }
1029
+ .hx-player-controls { gap: var(--corn-space-2); }
1030
+ /* While a scenario plays the proposal sheet folds to its title and counts: the player needs the room */
1031
+ .hx-dock:has(> .hx-player) .hx-proposal-bar[data-sheet-state="peek"] .hx-proposal-actions { display: none; }
1032
+ /* The note open: the field, Cancel and the send button are all there is, so all of them stay above the keyboard */
1033
+ .hx-proposal-bar:has(.hx-review-form:not([hidden])) :is(.hx-proposal-name, .hx-proposal-source, .hx-proposal-counts, .hx-proposal-tools, .hx-proposal-more, .hx-review-status, .hx-review-line) { display: none; }
1034
+ .hx-proposal-bar:has(.hx-review-form:not([hidden])) .hx-proposal-actions { order: 4; grid-template-columns: 1fr; }
1035
+ .hx-proposal-bar:has(.hx-review-form:not([hidden])) .hx-proposal-actions .hx-btn--approve { display: none; }
1036
+ /* Reflow: nothing is wider than the sheet, and long words and counts wrap instead of being cut */
1037
+ .hx-proposal-bar { overflow-x: hidden; overflow-wrap: anywhere; }
1038
+ .hx-proposal-head { grid-template-columns: minmax(0, 1fr) auto; }
1039
+ .hx-proposal-chip { flex-wrap: wrap; max-width: 100%; white-space: normal; text-align: left; }
1040
+ .hx-proposal-counts { min-width: 0; }
1041
+ }
1042
+ /* A short window (400% zoom is 225px tall): an open sheet may take the window, and the node panel's title wraps */
1043
+ @media (max-width: 767px) and (max-height: 480px) {
1044
+ .hx-proposal-bar[data-sheet-state="expanded"], .hx-player[data-sheet-state="expanded"] { max-height: calc(100dvh - var(--corn-space-3)); }
1045
+ .hx-drawer[data-sheet-state="peek"] .hx-drawer-title { overflow: visible; text-overflow: clip; white-space: normal; }
1046
+ }
1047
+
1008
1048
  /* Search with no match (F24): one line under the field, a polite live region. Empty it takes no room. */
1009
1049
  .hx-search { position: relative; }
1010
1050
  .hx-search-status { position: absolute; top: calc(100% + var(--corn-space-2)); left: 0; right: 0; z-index: 40; padding: var(--corn-space-2) var(--corn-space-3); border-radius: var(--corn-radius-sm); border: var(--corn-border) solid var(--corn-line); background: var(--corn-surface-2); color: var(--corn-text); font-size: var(--corn-text-sm); overflow-wrap: anywhere; }
@@ -88,7 +88,7 @@ import {
88
88
  threadsUrl, threadUrl, issueUrl, IDEAS_URL, threadKindWords, threadMeta, litForThread, mentionsIndex, ideaRequest, ideaWords,
89
89
  } from './forge-panel-model.js';
90
90
  import { cornStateAttr } from './corn-state.js';
91
- import { proposalListing, onProposalListing, loadProposalList } from './proposal.js';
91
+ import { proposalListing, onProposalListing, loadProposalList, hooks as proposalHooks } from './proposal.js';
92
92
  import { specRowHtml } from './proposal-model.js';
93
93
  import { t } from './strings.js';
94
94
 
@@ -2213,6 +2213,7 @@ export function initForgePanel(config, opts = {}) {
2213
2213
  const panel = $('forge-panel');
2214
2214
  if (!config || !config.forge || !config.signIn || !panel) return false;
2215
2215
  ui.config = config;
2216
+ proposalHooks.openSpecs = () => openForge({ tab: 'specs' }); // a bad proposal link's way on
2216
2217
  if (opts.clock) now = opts.clock;
2217
2218
  for (const toggle of document.querySelectorAll('[data-action="toggle-forge"]')) toggle.hidden = false;
2218
2219
  panel.hidden = false;
@@ -195,9 +195,11 @@
195
195
  <!-- The open proposal, a toolbar: title, counts, Before / Diff / After, Play, Edit, Send back, Approve, ⋯ (proposal.js, review.js, whatif.js, scenario-ui.js) -->
196
196
  <section id="proposal-bar" class="hx-proposal-bar glass" aria-label="Open proposal" hidden data-corn="proposal-bar">
197
197
  <p id="proposal-message" class="hx-proposal-message" role="status" hidden></p>
198
+ <div id="proposal-ways" class="hx-proposal-ways" role="group" aria-label="Ways on" data-corn="proposal-ways" hidden></div>
198
199
  <div id="proposal-body">
199
200
  <div class="hx-proposal-head" role="group" aria-label="Proposal actions">
200
201
  <strong id="proposal-title" class="hx-proposal-name"></strong>
202
+ <a id="proposal-source" class="hx-proposal-source" data-corn="proposal-source" hidden></a>
201
203
  <div class="hx-proposal-counts">
202
204
  <button type="button" id="proposal-chip" class="hx-proposal-chip" data-action="toggle-proposal-changes" aria-expanded="false"></button>
203
205
  <button type="button" id="proposal-mode" class="hx-proposal-mode" data-action="toggle-proposal-mode" data-peek-ok aria-expanded="false" aria-controls="proposal-seg" title="Before, Diff or After"></button>
@@ -234,6 +234,117 @@ export function specRowHtml(entry, { current = null } = {}) {
234
234
  + `${entry.summary ? `<span class="hx-forge-sum">${escHtml(entry.summary)}</span>` : ''}<span class="hx-forge-meta hx-forge-facts">${meta}</span></button></li>`;
235
235
  }
236
236
 
237
+ // ---------------------------------------------------------------------------
238
+ // Which copy is open: the chip on the bar, and a link that finds nothing
239
+ // ---------------------------------------------------------------------------
240
+
241
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
242
+
243
+ /**
244
+ * The checks on a PR's head in words, for the bar's source chip: "no checks", "1 check running", "2 checks failed, 1 check running",
245
+ * "all 3 checks passed". Failed first, then cancelled, then the ones still going.
246
+ * @param {{ state: string }[]} checks
247
+ */
248
+ export function checksLine(checks) {
249
+ if (!Array.isArray(checks) || checks.length === 0) return 'no checks';
250
+ const n = (states) => checks.filter((c) => states.includes(c.state)).length;
251
+ const failed = n(['failure']);
252
+ const cancelled = n(['cancelled']);
253
+ const waiting = n(['running', 'queued']);
254
+ const parts = [];
255
+ if (failed) parts.push(`${plural(failed, 'check')} failed`);
256
+ if (cancelled) parts.push(`${plural(cancelled, 'check')} cancelled`);
257
+ if (waiting) parts.push(`${plural(waiting, 'check')} running`);
258
+ if (parts.length) return parts.join(', ');
259
+ return checks.length === 1 ? '1 check passed' : `all ${checks.length} checks passed`;
260
+ }
261
+
262
+ /** `pull/<n>` to n, or null (the same shape the server reads, server/proposal-pulls.js) */
263
+ export function pullNumberOf(source) {
264
+ const m = typeof source === 'string' ? /^pull\/([1-9]\d{0,8})$/.exec(source) : null;
265
+ return m ? Number(m[1]) : null;
266
+ }
267
+
268
+ /** Where a source is, in words: "PR #21", "the checkout", "worktree <name>" */
269
+ export function sourceWhere(source) {
270
+ const n = pullNumberOf(source);
271
+ if (n) return `PR #${n}`;
272
+ if (!source || source === 'checkout') return 'the checkout';
273
+ return `worktree ${source}`;
274
+ }
275
+
276
+ /**
277
+ * What the bar's source chip says of the copy under review. A spec PR's copy: "PR #24 · draft · 1 check running" (the state and the checks
278
+ * are left out until known: `pull` is the listing's entry, `checks` the PR's checks, or null when they could not be read). A copy in the checkout
279
+ * or a worktree: "Local draft · in the checkout". `href` is the PR's address when it has one (the caller checks the scheme). `state` is the
280
+ * public `data-corn-state` of the copy (docs/theming.md): the PR's `open`, `draft`, `merged` or `closed`, and `draft` for a local copy (a
281
+ * branch with no pull request yet is `draft`); '' while the PR is not known yet.
282
+ * @param {string|null} source `pull/<n>`, `checkout` or a worktree's name
283
+ * @param {{ draft?: boolean, url?: string, state?: string }|null} [pull]
284
+ * @param {{ state: string }[]|null} [checks]
285
+ * @returns {{ text: string, href: string|null, state: ''|'open'|'draft'|'merged'|'closed', label: string }}
286
+ */
287
+ export function sourceChip(source, pull = null, checks = null) {
288
+ const n = pullNumberOf(source);
289
+ if (!n) {
290
+ const where = !source || source === 'checkout' ? 'in the checkout' : `in worktree ${source}`;
291
+ return { text: `Local draft \u00b7 ${where}`, href: null, state: 'draft', label: `This is a local draft, ${where}, not a pull request` };
292
+ }
293
+ const parts = [`PR #${n}`];
294
+ const state = !pull ? '' : pull.state === 'merged' || pull.state === 'closed' ? pull.state : typeof pull.draft === 'boolean' ? (pull.draft ? 'draft' : 'open') : '';
295
+ if (state) parts.push(state);
296
+ if (Array.isArray(checks)) parts.push(checksLine(checks));
297
+ return {
298
+ text: parts.join(' \u00b7 '),
299
+ href: pull && typeof pull.url === 'string' ? pull.url : null,
300
+ state,
301
+ label: `Reviewing spec pull request: ${parts.join(', ')}`,
302
+ };
303
+ }
304
+
305
+ /**
306
+ * What to say when a link names a proposal the server does not have: what was not found, said plainly. The place is named only when it is
307
+ * one: a PR number, the checkout, or a worktree the listing has (`sources`); anything else the link says is not repeated back.
308
+ * @param {string} slug (it passed the slug pattern)
309
+ * @param {string|null} source
310
+ * @param {Set<string>|null} [sources] the sources the listing knows, when it has been read
311
+ */
312
+ export function notFoundWords(slug, source, sources = null) {
313
+ if (!source) return `There is no proposal called ${slug}.`;
314
+ if (pullNumberOf(source) || source === 'checkout' || (sources && sources.has(source) && SLUG.test(source))) return `There is no proposal called ${slug} in ${sourceWhere(source)}.`;
315
+ return `There is no proposal called ${slug}. This link's source is not a PR, the checkout or a worktree.`;
316
+ }
317
+
318
+ /**
319
+ * What to say when `?proposal=` holds something that is not a proposal's name (a typo, a cut-off link), or null when it is a name or absent.
320
+ * The value is shown as text, cut to 60 characters; the caller sets it with `textContent`.
321
+ * @param {string} search `location.search`
322
+ * @returns {string|null}
323
+ */
324
+ export function malformedLinkWords(search) {
325
+ const params = new URLSearchParams(search || '');
326
+ if (!params.has('proposal')) return null;
327
+ const raw = params.get('proposal') || '';
328
+ if (SLUG.test(raw)) return null;
329
+ const shown = raw.length > 60 ? `${raw.slice(0, 59)}\u2026` : raw;
330
+ return shown.trim() ? `This link does not name a proposal: \u201c${shown}\u201d is not a proposal's name.` : 'This link does not name a proposal.';
331
+ }
332
+
333
+ /**
334
+ * The ways on from a link that found nothing: the same slug under another source, from the listing (a spec PR's copy before a local one),
335
+ * each as `{ slug, source, label }`. The Specs list is offered by the caller, always.
336
+ * @param {{ slug: string, source: string, error?: string, pull?: object }[]|null} listing
337
+ * @param {string} slug
338
+ * @param {string|null} source the one that was asked for (left out)
339
+ */
340
+ export function otherCopies(listing, slug, source) {
341
+ if (!Array.isArray(listing)) return [];
342
+ return listing
343
+ .filter((e) => e && e.slug === slug && e.source !== source && !e.error)
344
+ .sort((a, b) => (pullNumberOf(b.source) ? 1 : 0) - (pullNumberOf(a.source) ? 1 : 0))
345
+ .map((e) => ({ slug: e.slug, source: e.source, label: pullNumberOf(e.source) ? `Open the copy in PR #${pullNumberOf(e.source)}${e.pull && e.pull.draft ? ' (draft)' : ''}` : `Open the copy ${e.source === 'checkout' ? 'in the checkout' : `in worktree ${e.source}`}` }));
346
+ }
347
+
237
348
  // ---------------------------------------------------------------------------
238
349
  // Where an added node sits
239
350
  // ---------------------------------------------------------------------------
@@ -19,7 +19,8 @@
19
19
  */
20
20
 
21
21
  import { state, touchScene, viewEdges, nameOf, escHtml } from './state.js';
22
- import { render, getScene, fitGraphToViewport, fitPadding, isNodeVisible, ensureFlowLoop, screenToWorld } from './render.js';
22
+ import { render, getScene, fitGraphToViewport, fitPadding, isNodeVisible, ensureFlowLoop, screenToWorld, getMinZoom } from './render.js';
23
+ import { frameNodes, largestGroup, READ_ZOOM, FRAME_ZOOM_MIN } from './camera.js';
23
24
  import { setMap } from './view.js';
24
25
  import { closeDrawer, selectNode } from './panels.js';
25
26
  import { edgePoint, looksFor } from './scene.js';
@@ -27,10 +28,11 @@ import { onThemeChange } from './theme.js';
27
28
  import { looksWith, onMapStyleChange } from './map-style.js';
28
29
  import {
29
30
  PROPOSAL_VIEWS, MARKS, MARK_WORDS, chipText, barCounts, parseProposalQuery, proposalPanelHtml, touchedIds,
31
+ sourceChip, pullNumberOf, notFoundWords, otherCopies, malformedLinkWords,
30
32
  } from './proposal-model.js';
31
33
  import { applyProposal, edgeKey, proposalProblems, summarize } from '../core/proposal.js';
32
34
  import { reviewWords } from './review-model.js';
33
- import { collapseSheet } from './sheets.js';
35
+ import { collapseSheet, visibleMapRect, isPhone } from './sheets.js';
34
36
  import { t } from './strings.js';
35
37
 
36
38
  const $ = (id) => document.getElementById(id);
@@ -42,8 +44,9 @@ const $ = (id) => document.getElementById(id);
42
44
  * - `beforeClose()` returns false to keep the proposal open (it is asking whether to keep the edits)
43
45
  * - `closed()` the proposal was closed
44
46
  * - `bar(open)` the bar was drawn: redraw the editing controls
47
+ * - `openSpecs()` the Work panel's Specs tab, for a bad link's way on (forge-panel.js sets it; without it the header's Proposals menu opens)
45
48
  */
46
- export const hooks = { effective: null, mark: null, beforeClose: null, closed: null, bar: null };
49
+ export const hooks = { effective: null, mark: null, beforeClose: null, closed: null, bar: null, openSpecs: null };
47
50
 
48
51
  /** Whether the open proposal's source goes in the address (see `showProposal`) */
49
52
  let pinnedSource = false;
@@ -97,24 +100,38 @@ export async function loadProposalList() {
97
100
  * @returns {Promise<boolean>} whether it opened
98
101
  */
99
102
  export async function openProposal(slug, source = null) {
103
+ const token = ++openToken;
100
104
  setMessage(`Opening ${slug} …`);
101
105
  try {
102
106
  const res = await fetch(`/proposals/${encodeURIComponent(slug)}.json${source ? `?source=${encodeURIComponent(source)}` : ''}`, { cache: 'no-store' });
103
107
  if (!res.ok) {
104
108
  let why = '';
105
109
  try { why = (await res.json()).error || ''; } catch { /* no body */ }
106
- throw new Error(res.status === 404 ? `No proposal called ${slug}${source ? ` in ${source}` : ''}.` : why || `The server answered ${res.status}.`);
110
+ const err = new Error(res.status === 404 ? notFoundWords(slug, source) : why || `The server answered ${res.status}.`);
111
+ err.notFound = res.status === 404;
112
+ throw err;
107
113
  }
108
114
  const found = res.headers.get('X-Proposal-Source');
109
115
  showProposal(await res.json(), { slug, source: source || (found ? decodeURIComponent(found) : null), pinSource: !!source, view: 'diff', fit: true });
110
116
  return true;
111
117
  } catch (err) {
112
118
  console.error('Opening the proposal failed', err);
113
- setMessage(err.message || String(err), true);
119
+ // Said plainly, with the ways on: the Specs list, and the same name under another source when the list has one
120
+ setMessage(err.message || String(err), true, err.notFound ? [specsWay()] : []);
121
+ if (err.notFound && token === openToken) {
122
+ await loadProposalList();
123
+ const sources = new Set((Array.isArray(listing) ? listing : []).map((e) => e && e.source));
124
+ if (token === openToken) setMessage(notFoundWords(slug, source, sources), true, [...otherCopies(listing, slug, source).map((c) => ({ label: c.label, way: 'open', slug: c.slug, source: c.source })), specsWay()]);
125
+ }
114
126
  return false;
115
127
  }
116
128
  }
117
129
 
130
+ /** The way on every bad link offers: the list of specs */
131
+ const specsWay = () => ({ label: t('openSpecsList'), way: 'specs' });
132
+ /** Which `openProposal` is the latest, so a slow answer never writes over a newer one */
133
+ let openToken = 0;
134
+
118
135
  /**
119
136
  * Puts a parsed proposal on the map. The map's nodes and edges become `applyProposal(base, proposal)`.
120
137
  * @param {object} proposal
@@ -155,10 +172,10 @@ export function rebuildProposalMap(effective = hooks.effective ? hooks.effective
155
172
  applied = { nodes: state.baseNodes.map((n) => ({ ...n, mark: 'none' })), edges: state.baseEdges.map((e) => ({ ...e, mark: 'none' })) };
156
173
  }
157
174
  swapMap(applied.nodes, applied.edges);
175
+ renderBar(); // first: the fit below leaves out what the bar covers, so the bar must be laid out
158
176
  if (fit) fitToChange();
159
177
  render();
160
178
  ensureFlowLoop();
161
- renderBar();
162
179
  }
163
180
 
164
181
  /** Closes the proposal: the plain map comes back, as it was, and the address loses `?proposal=` */
@@ -203,9 +220,23 @@ function swapMap(nodes, edges) {
203
220
  touchScene();
204
221
  }
205
222
 
223
+ /**
224
+ * Frames what the proposal changes (nodes added, changed or removed, and both ends of a changed edge; not what they connect to) in the part of the
225
+ * map nothing covers (the bar, the node panel, a phone's sheets), at a zoom up to 1 so their labels read. Only what is drawn counts: a change on a
226
+ * layer that is off is not framed (the map would centre on ground the viewer cannot see). When the change is wider than FRAME_ZOOM_MIN shows,
227
+ * the biggest part of it that fits there is framed, not the whole at a zoom where it is a speck (the change list reaches the rest). A proposal that changes nothing drawn shows the whole map.
228
+ */
206
229
  function fitToChange() {
207
- const { near, touched } = touchedIds(state.nodes, viewEdges());
208
- fitGraphToViewport(fitPadding(), touched.size ? near : null);
230
+ const { touched } = touchedIds(state.nodes, viewEdges());
231
+ const items = state.nodes.filter((n) => touched.has(n.id) && isNodeVisible(n));
232
+ const rect = visibleMapRect();
233
+ const opts = { padding: fitPadding(), maxZoom: 1, minZoom: getMinZoom() };
234
+ // The whole change when it fits at FRAME_ZOOM_MIN or closer; else the biggest part of it that does (camera.js)
235
+ const group = largestGroup(items, rect, { ...opts, minZoom: Math.max(opts.minZoom, FRAME_ZOOM_MIN) });
236
+ const cam = items.length ? frameNodes(group, rect, opts) : null;
237
+ if (!cam) { fitGraphToViewport(fitPadding()); return; }
238
+ Object.assign(state.camera, cam);
239
+ render();
209
240
  }
210
241
 
211
242
  /** `?proposal=` (and `source`, `proposalView`) follow the open proposal, without a new history entry; other parameters stay */
@@ -228,8 +259,8 @@ function syncAddress() {
228
259
  // The bar: title, counts chip, Before / Diff / After, problems, Close
229
260
  // ---------------------------------------------------------------------------
230
261
 
231
- /** One line in the bar instead of a proposal: while one opens, or why it did not */
232
- function setMessage(text, isError = false) {
262
+ /** One line in the bar instead of a proposal: while one opens, or why it did not (with `ways`, the buttons that go on from there) */
263
+ function setMessage(text, isError = false, ways = []) {
233
264
  const bar = $('proposal-bar');
234
265
  if (!bar) return;
235
266
  bar.hidden = false;
@@ -238,6 +269,52 @@ function setMessage(text, isError = false) {
238
269
  const msg = $('proposal-message');
239
270
  msg.hidden = false;
240
271
  msg.textContent = text;
272
+ const box = $('proposal-ways');
273
+ if (!box) return;
274
+ box.hidden = ways.length === 0;
275
+ box.innerHTML = ways.map((w) => `<button type="button" class="hx-btn" data-action="proposal-way" data-way="${escHtml(w.way)}"${w.slug ? ` data-slug="${escHtml(w.slug)}"` : ''}${w.source ? ` data-source="${escHtml(w.source)}"` : ''} data-peek-ok data-corn-kind="quiet">${escHtml(w.label)}</button>`).join('');
276
+ }
277
+
278
+ // ---------------------------------------------------------------------------
279
+ // Which copy is open: the chip after the title
280
+ // ---------------------------------------------------------------------------
281
+
282
+ /** The spec PRs read for the chip, by number: `{ pull, checks }` of `GET /api/forge/pulls/<n>`; kept, so a proposal opened again shows it at once and then asks again */
283
+ const pullInfo = new Map();
284
+ /** The proposal the PR was last asked for (`source/slug`): asked again when another opens, not each time the bar is drawn */
285
+ let pullAskedFor = null;
286
+
287
+ const safeHref = (u) => (typeof u === 'string' && /^https?:\/\//i.test(u) ? u : null);
288
+
289
+ /** The chip says which copy is under review: a PR (number, draft or open, the checks in words) linking to it, or a local draft and where. It only tells. */
290
+ function paintSource() {
291
+ const chip = $('proposal-source');
292
+ if (!chip) return;
293
+ const source = state.proposal ? state.proposalSource : null;
294
+ chip.hidden = !source;
295
+ if (!source) return;
296
+ const n = pullNumberOf(source);
297
+ const known = n ? pullInfo.get(n) : null;
298
+ const entry = n && Array.isArray(listing) ? listing.find((e) => e.slug === state.proposalSlug && e.source === source) : null;
299
+ const words = sourceChip(source, (known && known.pull) || (entry && entry.pull) || null, known ? known.checks : null);
300
+ chip.textContent = words.text;
301
+ if (words.state) chip.dataset.cornState = words.state; else delete chip.dataset.cornState;
302
+ const href = safeHref(words.href);
303
+ if (href) { chip.setAttribute('href', href); chip.setAttribute('target', '_blank'); chip.setAttribute('rel', 'noreferrer'); chip.title = 'Open this pull request'; } else {
304
+ chip.removeAttribute('href'); chip.removeAttribute('target'); chip.removeAttribute('rel'); chip.title = words.label;
305
+ }
306
+ const key = `${source}/${state.proposalSlug}`;
307
+ if (n && pullAskedFor !== key) { pullAskedFor = key; loadPullInfo(n); }
308
+ }
309
+
310
+ /** Reads the PR's state and checks once for this opening of the bar (the server keeps its own short cache); a forge that cannot say leaves the chip as it is */
311
+ async function loadPullInfo(n) {
312
+ try {
313
+ const res = await fetch(`/api/forge/pulls/${n}`);
314
+ const body = res.ok ? await res.json() : null;
315
+ if (body && body.ok !== false && body.pull) pullInfo.set(n, { pull: body.pull, checks: Array.isArray(body.checks) ? body.checks : null });
316
+ } catch { /* no forge, or not signed in: the chip keeps what it has */ }
317
+ if (state.proposal && pullNumberOf(state.proposalSource) === n) paintSource();
241
318
  }
242
319
 
243
320
  /** The problems a proposal has, as the bar lists them (at most `max`, then "and N more") */
@@ -264,6 +341,7 @@ export function renderBar() {
264
341
  $('proposal-body').hidden = false;
265
342
  const p = state.proposal;
266
343
  $('proposal-title').textContent = (p && typeof p.title === 'string' && p.title) || state.proposalSlug || 'Proposal';
344
+ paintSource();
267
345
  const summary = $('proposal-summary');
268
346
  summary.textContent = (p && typeof p.summary === 'string' && p.summary) || '';
269
347
  const title = $('proposal-title');
@@ -311,26 +389,32 @@ function renderChanges() {
311
389
  list.innerHTML = rows.join('') || '<p class="hx-faint">This proposal changes nothing on the map.</p>';
312
390
  }
313
391
 
314
- function toggleChanges() {
392
+ function toggleChanges(refocus = false) {
315
393
  const list = $('proposal-changes');
316
394
  if (!list) return;
317
395
  list.hidden = !list.hidden;
318
396
  $('proposal-summary').hidden = list.hidden || !$('proposal-summary').textContent;
319
397
  $('proposal-chip').setAttribute('aria-expanded', String(!list.hidden));
398
+ // The list sits after the toolbar's buttons in the page, so focus goes into it when it opens (its first row), and back to the chip when it closes by Escape
399
+ if (!list.hidden) { if (!isPhone()) list.querySelector('button')?.focus(); } else if (refocus) $('proposal-chip').focus();
320
400
  }
321
401
 
322
- /** Picks a row of the changes list: select it, centre on it, and make sure the current view shows it */
402
+ /**
403
+ * Picks a row of the changes list: select it, centre it in the part of the map the open list, the node panel and (on a phone) the sheets leave free,
404
+ * at a zoom where its label reads, and make sure the current view shows it
405
+ */
323
406
  function focusChange(kind, key) {
324
407
  const item = kind === 'edge' ? state.edges.find((e) => edgeKey(e) === key) : state.nodes.find((n) => n.id === key);
325
408
  if (!item) return;
326
409
  const ends = (kind === 'edge' ? [state.nodes.find((n) => n.id === item.from), state.nodes.find((n) => n.id === item.to)] : [item]).filter(Boolean);
327
410
  if (!ends.length) return;
328
411
  if (state.proposalView !== 'diff' && ends.some((n) => !isNodeVisible(n))) setProposalView('diff'); // Before or After hides what it removes or adds
329
- const at = { x: ends.reduce((s, n) => s + n.x, 0) / ends.length, y: ends.reduce((s, n) => s + n.y, 0) / ends.length };
330
- state.camera.x = state.width / 2 - at.x * state.camera.zoom;
331
- state.camera.y = state.height / 2 - at.y * state.camera.zoom;
332
412
  if (kind === 'edge') showEdgePanel(item);
333
413
  else selectNode(item);
414
+ // The panel is open now, so what it covers is known
415
+ const cam = frameNodes(ends, visibleMapRect(), { padding: fitPadding(), maxZoom: Math.max(READ_ZOOM, state.camera.zoom), minZoom: getMinZoom() });
416
+ if (cam) Object.assign(state.camera, cam);
417
+ render();
334
418
  }
335
419
 
336
420
  // ---------------------------------------------------------------------------
@@ -532,6 +616,7 @@ const ACTIONS = {
532
616
  'toggle-proposal-mode': () => toggleMode(),
533
617
  'toggle-proposal-more': () => (moreOpen() ? closeMore() : openMore()),
534
618
  'toggle-proposal-changes': () => toggleChanges(),
619
+ 'proposal-way': (el) => (el.dataset.way === 'open' ? openProposal(el.dataset.slug, el.dataset.source || null) : openSpecs()),
535
620
  'proposal-focus': (el) => focusChange(el.dataset.kind, el.dataset.key),
536
621
  };
537
622
 
@@ -543,12 +628,63 @@ function onClick(e) {
543
628
  if (moreOpen() && !(target && target.dataset.action === 'toggle-proposal-more')) closeMore(!!(target && target.closest('#proposal-more-menu')));
544
629
  // Any click outside the picker closes it
545
630
  const wrap = $('proposal-wrap');
546
- if (menuOpen() && wrap && !wrap.contains(e.target)) closeMenu();
631
+ if (menuOpen() && wrap && !wrap.contains(e.target) && !(target && target.dataset.action === 'proposal-way')) closeMenu(); // (a bad link's Specs list opens it from outside)
632
+ }
633
+
634
+ /** A bad link's way on: the Work panel's Specs tab when there is one, else the header's Proposals menu */
635
+ function openSpecs() {
636
+ if (hooks.openSpecs) { hooks.openSpecs(); return; }
637
+ if (!menuOpen()) toggleMenu();
547
638
  }
548
639
 
549
640
  function onKey(e) {
550
641
  if (e.key === 'Escape' && menuOpen()) closeMenu();
551
642
  onMoreKey(e);
643
+ // Escape inside the list of changes folds it back onto its chip
644
+ const list = $('proposal-changes');
645
+ if (e.key === 'Escape' && !e.defaultPrevented && list && !list.hidden && list.contains(document.activeElement)) { e.preventDefault(); toggleChanges(true); }
646
+ if (e.key === 'Tab' && !e.defaultPrevented && !e.ctrlKey && !e.metaKey && !e.altKey) tabThroughList(e);
647
+ }
648
+
649
+ /** The lists the toolbar opens, each after the button that opens it: the changes (the counts) and the scenarios (Play) */
650
+ const OPENERS = [['proposal-chip', 'proposal-changes'], ['proposal-play', 'proposal-scenarios']];
651
+ const TABBABLE = 'button, a[href], input, select, textarea, summary, [tabindex]';
652
+ const canTab = (el) => el.tabIndex >= 0 && !el.disabled && !el.closest('[hidden]') && (typeof el.checkVisibility !== 'function' || el.checkVisibility());
653
+ const tabbables = (root) => [...root.querySelectorAll(TABBABLE)].filter(canTab);
654
+
655
+ /**
656
+ * An open list sits in the page under the whole toolbar, so Tab would reach it only after Approve and ⋯ (WCAG 2.4.3). The bar's Tab order is
657
+ * the page's with each open list moved to right after the button that opened it: Tab goes from the button into the list, from its last row on
658
+ * to the toolbar's next control, and Shift+Tab the same way back. Where that order and the page's agree, the browser moves the focus itself.
659
+ */
660
+ function tabThroughList(e) {
661
+ const bar = $('proposal-bar');
662
+ if (!bar || bar.hidden) return;
663
+ const open = OPENERS.map(([b, l]) => [$(b), $(l)]).filter(([btn, list]) => btn && list && !list.hidden && bar.contains(list) && canTab(btn));
664
+ if (!open.length) return;
665
+ const all = tabbables(bar);
666
+ let order = all.filter((el) => !open.some(([, list]) => list.contains(el)));
667
+ for (const [btn, list] of open) {
668
+ const at = order.indexOf(btn);
669
+ if (at >= 0) order = [...order.slice(0, at + 1), ...all.filter((el) => list.contains(el)), ...order.slice(at + 1)];
670
+ }
671
+ const active = document.activeElement;
672
+ let to = null;
673
+ if (active && bar.contains(active)) {
674
+ const i = order.indexOf(active);
675
+ if (i < 0) return;
676
+ const next = order[i + (e.shiftKey ? -1 : 1)];
677
+ const natural = all[all.indexOf(active) + (e.shiftKey ? -1 : 1)];
678
+ if (next === natural) return;
679
+ if (next) to = next;
680
+ else if (!e.shiftKey) to = tabbables(document).find((el) => !bar.contains(el) && (bar.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING)) || null; // out of the bar, past the list's rows
681
+ } else if (e.shiftKey && active) {
682
+ // Coming back into the bar from after it: its last control in this order, not the last row of a list
683
+ const page = tabbables(document);
684
+ const prev = page[page.indexOf(active) - 1];
685
+ if (prev && bar.contains(prev) && prev !== order[order.length - 1]) to = order[order.length - 1];
686
+ }
687
+ if (to) { e.preventDefault(); to.focus(); }
552
688
  }
553
689
 
554
690
  /** The marks' colours for the legend and the panel (the --hx-mark-* variables), the same the map draws on this ground */
@@ -580,7 +716,12 @@ export async function initProposals() {
580
716
  renderBar();
581
717
 
582
718
  const asked = parseProposalQuery(location.search);
583
- if (!asked) return false;
719
+ if (!asked) {
720
+ // A link whose `proposal` is not a proposal's name: said plainly (the value as text, never markup or a link), with the Specs list
721
+ const bad = malformedLinkWords(location.search);
722
+ if (bad) setMessage(bad, true, [specsWay()]);
723
+ return false;
724
+ }
584
725
  const ok = await openProposal(asked.slug, asked.source);
585
726
  if (ok && asked.view) setProposalView(asked.view);
586
727
  return ok;
@@ -78,7 +78,7 @@ function mount() {
78
78
  </div>
79
79
  </div>
80
80
  <p class="hx-review-msg" data-review-msg role="alert" hidden></p>
81
- <p class="hx-review-line" data-review-hint role="status" hidden></p>
81
+ <p class="hx-review-line" id="review-hint" data-review-hint role="status" hidden></p>
82
82
  `;
83
83
  // The words are set as text and attributes, never parsed as HTML (a brand's `strings`, explorer/strings.js)
84
84
  q('.hx-review-label').textContent = t('reviewNoteLabel');
@@ -99,7 +99,13 @@ function paint() {
99
99
  const status = q('[data-review-status]');
100
100
  status.textContent = reviewWords(ui.review, now());
101
101
  status.hidden = !status.textContent;
102
- for (const btn of document.querySelectorAll('#proposal-bar [data-review]')) btn.disabled = ui.busy || !ui.reviewable;
102
+ // Off for good (not a spec PR's copy) is `disabled`, and the reason is the line next to it, which the buttons point at. While a review is being posted the button
103
+ // only says it is busy (`aria-disabled`): a `disabled` button drops the focus to the page.
104
+ for (const btn of document.querySelectorAll('#proposal-bar [data-review]')) {
105
+ btn.disabled = !ui.reviewable;
106
+ if (ui.busy) btn.setAttribute('aria-disabled', 'true'); else btn.removeAttribute('aria-disabled');
107
+ if (!ui.reviewable && ui.key) btn.setAttribute('aria-describedby', 'review-hint'); else btn.removeAttribute('aria-describedby');
108
+ }
103
109
  const approve = button('approved');
104
110
  if (approve) approve.textContent = t('approve');
105
111
  const sendBack = button('notes');
@@ -125,6 +131,9 @@ function openNote() {
125
131
  paint();
126
132
  if (isPhone()) expandSheet('proposal');
127
133
  q('#review-note').focus();
134
+ // On a phone the keyboard is about to take half the screen: the note and the button that sends it stay in view above it
135
+ const send = button('notes');
136
+ if (isPhone() && send && typeof send.scrollIntoView === 'function') send.scrollIntoView({ block: 'nearest' });
128
137
  }
129
138
 
130
139
  /** Cancel: the field closes, what was typed goes, and focus goes back to Send back */
@@ -223,7 +232,11 @@ export async function sendReview(verdict) {
223
232
  const wasNoting = ui.noting;
224
233
  ui.noting = false;
225
234
  paint();
226
- if (wasNoting && verdict === 'notes') { const sendBack = button('notes'); if (sendBack) sendBack.focus(); }
235
+ // The buttons were busy while it posted, not `disabled`, so the focus stayed where it was. Approve keeps it (the status line, a live region,
236
+ // says "Approved" once; moving the focus onto it would say it twice); when it was lost it goes back to Approve. Send back: the button that opened the note.
237
+ const lost = !document.activeElement || document.activeElement === document.body || !document.activeElement.isConnected;
238
+ if (verdict === 'approved') { if (lost) button('approved')?.focus(); }
239
+ else if (wasNoting || lost) button('notes')?.focus();
227
240
  refreshMockups(); // an approval covers the screens as they are now; a send back leaves them not reviewed
228
241
  if (verdict === 'notes') clearEdits(); // the edits went with the note; an approval keeps them, they are in the review
229
242
  return true;
@@ -24,9 +24,9 @@
24
24
  */
25
25
 
26
26
  import { state, touchScene, onSceneTouch } from './state.js';
27
- import { render, ensureFlowLoop, addFrameClient, isNodeVisible } from './render.js';
27
+ import { render, ensureFlowLoop, addFrameClient, isNodeVisible, getMinZoom } from './render.js';
28
28
  import { flowReduceMotion } from './flows.js';
29
- import { registerSheet, unregisterSheet, collapseAllSheets, measureCovered, onCoveredChange } from './sheets.js';
29
+ import { registerSheet, unregisterSheet, collapseAllSheets, visibleMapRect, onCoveredChange } from './sheets.js';
30
30
  import { createPlayer, cameraFor, parseSpeed, SPEED_CHOICES, SPEED_KEY } from './scenario.js';
31
31
  import { edgeKey } from '../core/proposal.js';
32
32
  import { checksVersion, closeChecks, decorateSnapshot, openChecks, paintChecks } from './check.js';
@@ -58,7 +58,10 @@ const $stage = () => (state.canvas ? state.canvas.parentElement : null);
58
58
  * @returns {ReturnType<typeof createPlayer>} the player, for a caller that wants to drive it
59
59
  */
60
60
  export function playScenario(scenario, opts = {}) {
61
+ const opener = openerOf();
62
+ const takeFocus = isKeyboardish(); // checked now: the list row that was pressed goes with the list
61
63
  clearScenario();
64
+ returnTo = opener;
62
65
  const speed = opts.stepMs ?? readSpeed();
63
66
  player = createPlayer(scenario, { stepMs: speed, maxFrameMs: MAX_FRAME_MS });
64
67
  showBar(speed);
@@ -68,9 +71,43 @@ export function playScenario(scenario, opts = {}) {
68
71
  sync(true);
69
72
  render();
70
73
  ensureFlowLoop();
74
+ // Whatever started it (a row of the list, which goes) is gone: focus goes to the player's play and pause button, the first control of what opened
75
+ if (opts.focus !== false && bar && takeFocus) {
76
+ const toggle = bar.querySelector('[data-action=scenario-toggle]');
77
+ if (toggle && !toggle.disabled) toggle.focus(); else bar.querySelector('[data-action=scenario-next]')?.focus();
78
+ }
71
79
  return player;
72
80
  }
73
81
 
82
+ /** What had the focus when a scenario started, to give it back when the scenario closes: the toolbar's Play button when the start came from it or its list */
83
+ let returnTo = null;
84
+ function openerOf() {
85
+ const active = document.activeElement;
86
+ const play = document.getElementById('proposal-play');
87
+ if (active && active !== document.body && (active === play || active.closest?.('#proposal-scenarios'))) return play;
88
+ if (active && active !== document.body && !active.closest?.('.hx-player') && active !== state.canvas) return active;
89
+ return null;
90
+ }
91
+
92
+ /** Whether the focus is on the page's controls (not on nothing, and not in a field): a scenario started by a script from outside takes none */
93
+ function isKeyboardish() {
94
+ const active = document.activeElement;
95
+ return !!active && active !== document.body && !typingIn(active);
96
+ }
97
+
98
+ /** Closing the player by the viewer's own act: the focus goes back to what started it (Play), else to Play, else to the map (on a phone Play is folded away in the peek) */
99
+ function giveFocusBack() {
100
+ const to = returnTo;
101
+ returnTo = null;
102
+ const took = (el) => {
103
+ if (!el || !el.isConnected || el.hidden || el.disabled || el.closest('[hidden]')) return false;
104
+ el.focus();
105
+ return document.activeElement === el; // a control the stylesheet hides takes no focus
106
+ };
107
+ if (took(to) || took(document.getElementById('proposal-play'))) return;
108
+ took(state.canvas);
109
+ }
110
+
74
111
  /**
75
112
  * An outage scenario (spec 0031 section 8) turns on the layers its blast radius is drawn on (containers and
76
113
  * machines start off), as a scenario that names a persona turns the People layer on (check.js).
@@ -105,9 +142,12 @@ export function clearScenario() {
105
142
  /** Ends the scenario and redraws the map without it */
106
143
  export function stopScenario() {
107
144
  if (!player && !state.scenario) return;
145
+ const hadFocus = !!bar && bar.contains(document.activeElement);
108
146
  clearScenario();
109
147
  touchScene();
110
148
  render();
149
+ if (hadFocus || document.activeElement === document.body) giveFocusBack(); // focus was in the player, which is gone
150
+ else returnTo = null;
111
151
  }
112
152
 
113
153
  /** Brings `state.scenario` up to date with the player; when a step, the play state or the step start moved, rebuilds the scene and follows the step with the camera */
@@ -133,13 +173,11 @@ function sync(force = false) {
133
173
  function followStep(snap) {
134
174
  const visible = new Map();
135
175
  state.nodes.forEach((n) => { if (isNodeVisible(n)) visible.set(n.id, n); });
136
- // The bar covers the bottom of the map: a step behind it is as good as off screen. On a phone the sheets
137
- // (the dock) cover it; the rest of the time it is the bar alone.
138
- const sheets = measureCovered();
139
- const covered = sheets > 0 ? sheets + 16 : bar ? bar.offsetHeight + 24 : 0;
140
- const target = cameraFor({ node: snap.current.node, edge: snap.current.edge, at: snap.current.at, text: snap.current.text }, state.camera, { width: state.width, height: Math.max(120, state.height - covered) }, visible);
176
+ // The step must be in the part of the map nothing covers: not under the proposal bar, the node panel, the player or (on a phone) the sheets
177
+ const rect = visibleMapRect();
178
+ const target = cameraFor({ node: snap.current.node, edge: snap.current.edge, at: snap.current.at, text: snap.current.text }, state.camera, rect, visible, 60, getMinZoom());
141
179
  if (!target) return;
142
- if (flowReduceMotion) { Object.assign(state.camera, target); glide = null; return; }
180
+ if (flowReduceMotion) { Object.assign(state.camera, target); glide = null; render(); return; } // reduced motion: jump, do not fly
143
181
  glide = { to: target, last: null };
144
182
  ensureFlowLoop();
145
183
  }
@@ -191,9 +229,9 @@ function showBar(speed) {
191
229
  </div>
192
230
  <p class="hx-player-text" aria-live="polite"><span class="hx-player-count"></span> · <span class="hx-player-step"></span></p>
193
231
  <div class="hx-player-controls">
194
- <button type="button" class="hx-btn" data-action="scenario-prev">◀ Previous</button>
195
- <button type="button" class="hx-btn hx-btn--active" data-action="scenario-toggle" data-corn-kind="primary"></button>
196
- <button type="button" class="hx-btn" data-action="scenario-next">Next ▶</button>
232
+ <button type="button" class="hx-btn" data-action="scenario-prev" data-peek-ok>◀ Previous</button>
233
+ <button type="button" class="hx-btn hx-btn--active" data-action="scenario-toggle" data-peek-ok data-corn-kind="primary"></button>
234
+ <button type="button" class="hx-btn" data-action="scenario-next" data-peek-ok>Next ▶</button>
197
235
  </div>
198
236
  <div class="hx-player-track" aria-hidden="true"><span class="hx-player-fill"></span></div>`;
199
237
  bar.addEventListener('click', (e) => {
@@ -270,6 +308,10 @@ function typingIn(target) {
270
308
  }
271
309
 
272
310
  function onKeydown(e) {
311
+ if (e.key === 'Escape' && !e.defaultPrevented && !e.ctrlKey && !e.metaKey && !e.altKey) {
312
+ if (player && !typingIn(e.target) && !otherPopupOpen()) { e.preventDefault(); stopScenario(); return; } // Escape closes the scenario; focus goes back to Play
313
+ if (!player && list && !list.hidden && list.contains(document.activeElement)) { e.preventDefault(); closeList(true); return; }
314
+ }
273
315
  if (!player || e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey || typingIn(e.target)) return;
274
316
  const action = e.key === ' ' || e.code === 'Space' ? 'scenario-toggle' : e.key === 'ArrowLeft' ? 'scenario-prev' : e.key === 'ArrowRight' ? 'scenario-next' : null;
275
317
  if (!action) return;
@@ -277,6 +319,11 @@ function onKeydown(e) {
277
319
  act(action);
278
320
  }
279
321
 
322
+ /** A menu or dialog that has its own Escape: the layers menu, the toolbar's ⋯ menu, a dialog */
323
+ function otherPopupOpen() {
324
+ return !!document.querySelector('#legend-dropdown:not([hidden]), #proposal-more-menu:not([hidden]), [data-corn="dialog-scrim"]:not([hidden]), .hx-mockup-dialog');
325
+ }
326
+
280
327
  /** Some browsers press a focused button on the key's release, so a space the player took must not reach it */
281
328
  function onKeyup(e) {
282
329
  if (player && (e.key === ' ' || e.code === 'Space') && !typingIn(e.target)) e.preventDefault();
@@ -322,10 +369,22 @@ function paintPlay(show) {
322
369
  btn.addEventListener('click', () => {
323
370
  const scenarios = proposalScenarios();
324
371
  if (scenarios.length === 1) playScenario(scenarios[0]);
325
- else if (list) { list.hidden = !list.hidden; btn.setAttribute('aria-expanded', String(!list.hidden)); }
372
+ else if (list) {
373
+ if (list.hidden) { list.hidden = false; btn.setAttribute('aria-expanded', 'true'); list.querySelector('button')?.focus(); } // the first row of what opened
374
+ else closeList(false);
375
+ }
326
376
  });
327
377
  }
328
378
 
379
+ /** Folds the scenario list back onto Play; `refocus` gives Play the focus (Escape from inside the list) */
380
+ function closeList(refocus) {
381
+ if (list) list.hidden = true;
382
+ const btn = document.getElementById('proposal-play');
383
+ if (!btn) return;
384
+ btn.setAttribute('aria-expanded', 'false');
385
+ if (refocus) btn.focus();
386
+ }
387
+
329
388
  /** Shows or hides the Play button and its list to match the open proposal's scenarios (and hides them while one plays: the player is the control then) */
330
389
  export function refreshList() {
331
390
  const stage = $stage();
@@ -52,6 +52,7 @@
52
52
  */
53
53
 
54
54
  import { edgeKey } from '../core/proposal.js';
55
+ import { frameNodes, allInside, READ_ZOOM, ZOOM_MIN } from './camera.js';
55
56
 
56
57
  export const DEFAULT_STEP_MS = 5000;
57
58
  /** Where the viewer's speed is kept (localStorage); scenario-ui.js reads and writes it */
@@ -70,8 +71,6 @@ export function parseSpeed(raw) {
70
71
  if (!choice) return DEFAULT_STEP_MS;
71
72
  return choice.value === 'manual' ? 'manual' : Number(choice.value);
72
73
  }
73
- /** The zoom fit-to-screen never goes below (render.js `fitGraphToViewport`) */
74
- export const MIN_FIT_ZOOM = 0.18;
75
74
 
76
75
  /** How long a step plays: its own `ms` when that is a positive number, else `fallback` */
77
76
  export function stepDuration(step, fallback = DEFAULT_STEP_MS) {
@@ -223,39 +222,32 @@ export function createPlayer(scenario, opts = {}) {
223
222
  }
224
223
 
225
224
  /**
226
- * Where the camera should go so a step is on screen, or null when it already is (or the step points
227
- * at something that is not in the map). A node off screen is centred at the same zoom; an edge is
228
- * centred and, if its two ends do not fit, zoomed out to fit (never below MIN_FIT_ZOOM, never in).
229
- * A step's `at` is kept in view with it when it is on the map, and ignored when it is not (a live id with no live layer).
225
+ * Where the camera should go so a step is on screen and readable, or null when it already is (or the step points at something that
226
+ * is not in the map). The step's node, or both ends of its edge, must be inside `viewport` (the part of the map nothing covers) at a zoom
227
+ * where the label reads (READ_ZOOM, about 11px): a node step zooms in to it, an edge step fits both ends (and no closer than READ_ZOOM).
228
+ * It never goes under `minZoom` (the map's floor, render.js `getMinZoom()`), so an edge too long even for that is shown as close as it allows.
229
+ * A step already shown well enough is left alone, so a walk does not wobble. A step's `at` is kept in view with it when it is on the map,
230
+ * and ignored when it is not (a live id with no live layer).
230
231
  * @param {Step} step
231
232
  * @param {{ x: number, y: number, zoom: number }} camera
232
- * @param {{ width: number, height: number }} viewport CSS px
233
+ * @param {{ width: number, height: number, x?: number, y?: number }} viewport CSS px (the free rect: `x` and `y` default to 0)
233
234
  * @param {Map<string, { x: number, y: number, r?: number }>} nodes by id
234
- * @param {number} [margin] px kept clear at the screen's edge
235
+ * @param {number} [margin] px kept clear at the viewport's edge
236
+ * @param {number} [minZoom] the lowest zoom it may go to
235
237
  * @returns {{ x: number, y: number, zoom: number } | null}
236
238
  */
237
- export function cameraFor(step, camera, viewport, nodes, margin = 60) {
239
+ export function cameraFor(step, camera, viewport, nodes, margin = 60, minZoom = ZOOM_MIN) {
238
240
  if (!viewport.width || !viewport.height) return null;
239
241
  const ids = step.node !== undefined ? [step.node] : step.edge ? [step.edge.from, step.edge.to] : [];
240
242
  const ends = ids.map((id) => nodes.get(id));
241
243
  if (ends.length === 0 || ends.some((n) => !n)) return null;
242
244
  if (step.at !== undefined && nodes.has(step.at) && !ids.includes(step.at)) ends.push(nodes.get(step.at));
243
245
 
244
- const onScreen = ends.every((n) => {
245
- const sx = camera.x + n.x * camera.zoom;
246
- const sy = camera.y + n.y * camera.zoom;
247
- return sx >= margin && sx <= viewport.width - margin && sy >= margin && sy <= viewport.height - margin;
248
- });
249
- if (onScreen) return null;
250
-
251
- const r = (n) => n.r || 18;
252
- const minX = Math.min(...ends.map((n) => n.x - r(n)));
253
- const maxX = Math.max(...ends.map((n) => n.x + r(n)));
254
- const minY = Math.min(...ends.map((n) => n.y - r(n)));
255
- const maxY = Math.max(...ends.map((n) => n.y + r(n)));
256
- const fit = Math.min((viewport.width - margin * 2) / (maxX - minX), (viewport.height - margin * 2) / (maxY - minY));
257
- const zoom = Math.max(MIN_FIT_ZOOM, Math.min(camera.zoom, fit));
258
- return { x: viewport.width / 2 - ((minX + maxX) / 2) * zoom, y: viewport.height / 2 - ((minY + maxY) / 2) * zoom, zoom };
246
+ const rect = { x: viewport.x || 0, y: viewport.y || 0, width: viewport.width, height: viewport.height };
247
+ const target = frameNodes(ends, rect, { padding: margin, maxZoom: Math.max(READ_ZOOM, camera.zoom), minZoom });
248
+ const edge = Math.min(margin, rect.width / 4, rect.height / 4);
249
+ if (allInside(ends, camera, rect, edge) && camera.zoom >= target.zoom - 0.001) return null;
250
+ return target;
259
251
  }
260
252
 
261
253
  /**
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { state } from './state.js';
17
17
  import { createSheetModel } from './sheet-model.js';
18
+ import { freeRect } from './camera.js';
18
19
 
19
20
  /** The width below which the sheets apply (matches the CSS) */
20
21
  export const PHONE_QUERY = '(max-width: 767px)';
@@ -92,6 +93,31 @@ export function measureCovered() {
92
93
  return covered;
93
94
  }
94
95
 
96
+ /**
97
+ * The part of the map nothing covers, in the canvas's own CSS px: what the camera should frame a node into.
98
+ * 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.
100
+ * @returns {{ x: number, y: number, width: number, height: number }}
101
+ */
102
+ export function visibleMapRect() {
103
+ const covers = { top: 0, bottom: 0, left: 0, right: 0 };
104
+ const canvas = state.canvas;
105
+ const shown = (el) => !!el && !el.hidden && el.isConnected;
106
+ if (isPhone()) covers.bottom = measureCovered() + 8;
107
+ else if (canvas && typeof canvas.getBoundingClientRect === 'function') {
108
+ const c = canvas.getBoundingClientRect();
109
+ const bar = $('proposal-bar');
110
+ if (shown(bar)) covers.top = Math.max(0, bar.getBoundingClientRect().bottom - c.top) + 8;
111
+ const drawer = $('spec-drawer');
112
+ if (shown(drawer) && drawer.classList.contains('drawer-open')) covers.right = drawer.offsetWidth; // its width, not its box: it slides in
113
+ const forge = $('forge-panel');
114
+ if (shown(forge) && forge.classList.contains('forge-open')) covers.left = forge.offsetWidth;
115
+ const player = document.querySelector('.hx-player');
116
+ if (shown(player)) covers.bottom = Math.max(0, c.bottom - player.getBoundingClientRect().top) + 8;
117
+ }
118
+ return freeRect(state.width || 0, state.height || 0, covers);
119
+ }
120
+
95
121
  // ---------------------------------------------------------------------------
96
122
  // Registering and changing sheets
97
123
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.34.1",
3
+ "version": "0.34.2",
4
4
  "description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
5
5
  "license": "MIT",
6
6
  "author": "popcorn245 (https://github.com/popcorn245)",