@popcorn245/cornfield 0.34.3 → 0.36.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.
@@ -13,6 +13,9 @@
13
13
  * --corn-map-selected|match the halo of the selected node, and of a search hit
14
14
  * --corn-map-lit the lines of the focus: the links the selection (or a walk's step) lights
15
15
  * --corn-map-collision the collision mark of two runs on one node (a DOM mark: explorer.css reads it)
16
+ * --corn-map-font the font list of every label on the map (a list of families, `auto` for the map's own)
17
+ * --corn-map-edge-width the width of an ordinary line, in map px (`auto` keeps each line's own; the focus's and the marks' keep their proportion)
18
+ * --corn-map-glow the soft glow round nodes, lines and packets: a factor (`0` none, `1` as drawn, `auto` as drawn)
16
19
  *
17
20
  * `auto` (the default of every one of them but the width and the collision) means "keep what the map draws without a theme": the
18
21
  * node's own colour from the topology, deepened for the light ground by theme-model.js, and every other colour as scene.js has
@@ -46,6 +49,17 @@ export const STROKE_WIDTH_TOKEN = '--corn-map-stroke-width';
46
49
  export const LABEL_TOKEN = '--corn-map-label';
47
50
  export const LABEL_HALO_TOKEN = '--corn-map-label-halo';
48
51
  export const COLLISION_TOKEN = '--corn-map-collision';
52
+ export const FONT_TOKEN = '--corn-map-font';
53
+ export const EDGE_WIDTH_TOKEN = '--corn-map-edge-width';
54
+ export const GLOW_TOKEN = '--corn-map-glow';
55
+ /** The width an ordinary line has with no theme (scene.js `flowEdge`): the `--corn-map-edge-width` scales every line by its ratio to this */
56
+ export const BASE_EDGE_WIDTH = 1.6;
57
+ /** The most a font list may hold: the families, and the characters */
58
+ export const MAX_FONT_FAMILIES = 8;
59
+ export const MAX_FONT_CHARS = 200;
60
+ /** The widest a line may be set, and the largest glow factor: a typo cannot draw a map of paint */
61
+ export const MAX_EDGE_WIDTH = 12;
62
+ export const MAX_GLOW = 4;
49
63
  /** The width of an outline when the token is not a length (px, world units) */
50
64
  export const DEFAULT_STROKE_WIDTH = 1.5;
51
65
  /** An icon is drawn this many radii across (a square, so it fits inside the circle) */
@@ -70,7 +84,7 @@ export const MAP_COLOR_TOKENS = Object.freeze([
70
84
  ...MAP_STATES.map(stateToken),
71
85
  ]);
72
86
  /** Every map token */
73
- export const mapTokenNames = () => [...MAP_COLOR_TOKENS, STROKE_WIDTH_TOKEN, COLLISION_TOKEN];
87
+ export const mapTokenNames = () => [...MAP_COLOR_TOKENS, STROKE_WIDTH_TOKEN, COLLISION_TOKEN, FONT_TOKEN, EDGE_WIDTH_TOKEN, GLOW_TOKEN];
74
88
 
75
89
  // ---------------------------------------------------------------------------
76
90
  // Reading a token
@@ -153,10 +167,56 @@ export function withAlphaOf(token, original) {
153
167
  return rgbaText(r, g, b, a * oa);
154
168
  }
155
169
 
170
+ const GENERIC_FAMILY = /^(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-serif|ui-sans-serif|ui-monospace|ui-rounded|emoji|math|fangsong)$/i;
171
+ const SYSTEM_FONT_KEYWORD = /^(?:-apple-system|BlinkMacSystemFont)$/;
172
+
173
+ /**
174
+ * A font list the canvas may be given, or null (`auto`, empty, or anything that is not a plain list of families). Each family is a name in
175
+ * quotes, or bare words (`Nunito`, `ui-rounded`, `sans-serif`); nothing that can carry a URL or script (no parentheses, slashes, colons,
176
+ * semicolons, braces, angle brackets, `@`, backslashes, `url`, `var`, `expression`) and no more than MAX_FONT_FAMILIES of them.
177
+ * Returned with each name quoted, so a name with a space is one family.
178
+ * @param {unknown} value
179
+ * @returns {string | null}
180
+ */
181
+ export function cssFontList(value) {
182
+ const s = typeof value === 'string' ? value.trim() : '';
183
+ if (!s || s.length > MAX_FONT_CHARS || s.toLowerCase() === 'auto') return null;
184
+ if (/[();:{}<>@\\/\u0000-\u001f\u007f]|\burl\b|\bvar\b|\bexpression\b|\bimport\b/i.test(s)) return null;
185
+ const parts = s.split(',').map((p) => p.trim());
186
+ if (parts.length > MAX_FONT_FAMILIES) return null;
187
+ const out = [];
188
+ for (const part of parts) {
189
+ const quoted = /^"([A-Za-z0-9 ._+-]{1,60})"$|^'([A-Za-z0-9 ._+-]{1,60})'$/.exec(part);
190
+ // A bare name may start with one hyphen (`-apple-system`, in cornfield's own --corn-font), never two (a custom property's name)
191
+ const name = quoted ? (quoted[1] ?? quoted[2]).trim() : /^-?[A-Za-z][A-Za-z0-9 _-]{0,59}$/.test(part) ? part.replace(/\s+/g, ' ') : null;
192
+ if (!name) return null;
193
+ // Generic families and the two system-font keywords stay bare (quoted, they would name a font called that); every other name is quoted
194
+ out.push(GENERIC_FAMILY.test(name) ? name.toLowerCase() : SYSTEM_FONT_KEYWORD.test(name) ? name : `"${name}"`);
195
+ }
196
+ return out.join(', ');
197
+ }
198
+
199
+ /** A length in px (`2px`, `2`) over 0 and at most max, or null for `auto` and anything else (a canvas ignores a line width of 0) */
200
+ function pxOf(value, max) {
201
+ const m = /^\s*(\d*\.?\d+)(?:px)?\s*$/i.exec(String(value ?? ''));
202
+ const n = m ? parseFloat(m[1]) : NaN;
203
+ return Number.isFinite(n) && n > 0 && n <= max ? n : null;
204
+ }
205
+
206
+ /** The glow factor: a number (`0` for none, `1` as drawn, up to MAX_GLOW; `0px` reads as 0), or null for `auto` and anything else */
207
+ function factorOf(value) {
208
+ const m = /^\s*(\d*\.?\d+)(px)?\s*$/i.exec(String(value ?? ''));
209
+ if (!m) return null;
210
+ const n = parseFloat(m[1]);
211
+ if (m[2] && n !== 0) return null; // a length is not a factor, only zero is the same in both
212
+ return Number.isFinite(n) && n >= 0 && n <= MAX_GLOW ? n : null;
213
+ }
214
+
156
215
  /**
157
216
  * The tokens as the page computes them.
158
217
  * @param {(name: string) => string} read the value of a custom property
159
- * @returns {{values: Record<string, string>, strokeWidth: number}} `values` holds only the tokens that are a colour (not `auto`)
218
+ * @returns {{values: Record<string, string>, strokeWidth: number, font: string | null, edgeWidth: number | null, glow: number | null}}
219
+ * `values` holds only the tokens that are a colour (not `auto`); `font`, `edgeWidth` and `glow` are null at `auto` or when the value is not one
160
220
  */
161
221
  export function readMapTokens(read) {
162
222
  const values = {};
@@ -165,7 +225,13 @@ export function readMapTokens(read) {
165
225
  if (c) values[name] = c;
166
226
  }
167
227
  const w = parseFloat(String(read(STROKE_WIDTH_TOKEN) ?? ''));
168
- return { values, strokeWidth: Number.isFinite(w) && w >= 0 ? w : DEFAULT_STROKE_WIDTH };
228
+ return {
229
+ values,
230
+ strokeWidth: Number.isFinite(w) && w >= 0 ? w : DEFAULT_STROKE_WIDTH,
231
+ font: cssFontList(read(FONT_TOKEN)),
232
+ edgeWidth: pxOf(read(EDGE_WIDTH_TOKEN), MAX_EDGE_WIDTH),
233
+ glow: factorOf(read(GLOW_TOKEN)),
234
+ };
169
235
  }
170
236
 
171
237
  /** A reader of the page's computed custom properties, or null where there is no page */
@@ -230,12 +296,16 @@ export function createIconStore(urls, { load = loadImage, onChange = () => {}, w
230
296
  * @property {number} version changes whenever anything below does: a renderer draws again when it differs from the one it drew
231
297
  * @property {Record<string, string>} values the tokens that are a colour, by name (those at `auto` are absent)
232
298
  * @property {number} strokeWidth px, world units
299
+ * @property {string | null} font the label font list (`--corn-map-font`), null at `auto`
300
+ * @property {number | null} edgeWidth an ordinary line's width in px (`--corn-map-edge-width`), null at `auto`
301
+ * @property {number | null} glow the glow factor (`--corn-map-glow`), null at `auto`
233
302
  * @property {ReturnType<typeof createIconStore> | null} icons
234
303
  * @property {boolean} pixelated sample icons without smoothing
235
304
  * @property {boolean} plain nothing to apply: no colour set, no icon loaded (the scene is drawn as it is)
236
305
  */
237
306
 
238
- let tokens = { values: {}, strokeWidth: DEFAULT_STROKE_WIDTH };
307
+ const NO_TOKENS = { values: {}, strokeWidth: DEFAULT_STROKE_WIDTH, font: null, edgeWidth: null, glow: null };
308
+ let tokens = NO_TOKENS;
239
309
  let icons = null;
240
310
  let pixelated = false;
241
311
  let version = 0;
@@ -243,8 +313,8 @@ let current = compose();
243
313
  const listeners = new Set();
244
314
 
245
315
  function compose() {
246
- const plain = !Object.keys(tokens.values).length && !(icons && icons.anyReady());
247
- return Object.freeze({ version, values: tokens.values, strokeWidth: tokens.strokeWidth, icons, pixelated, plain });
316
+ const plain = !Object.keys(tokens.values).length && !(icons && icons.anyReady()) && tokens.font === null && tokens.edgeWidth === null && tokens.glow === null;
317
+ return Object.freeze({ version, values: tokens.values, strokeWidth: tokens.strokeWidth, font: tokens.font, edgeWidth: tokens.edgeWidth, glow: tokens.glow, icons, pixelated, plain });
248
318
  }
249
319
 
250
320
  function changed() {
@@ -269,12 +339,14 @@ export function onMapStyleChange(fn) {
269
339
  export function refreshMapStyle(read = pageReader()) {
270
340
  if (!read) return false;
271
341
  const next = readMapTokens(read);
272
- const same = next.strokeWidth === tokens.strokeWidth
342
+ const same = next.strokeWidth === tokens.strokeWidth && next.font === tokens.font && next.edgeWidth === tokens.edgeWidth && next.glow === tokens.glow
273
343
  && Object.keys(next.values).length === Object.keys(tokens.values).length
274
344
  && Object.entries(next.values).every(([k, v]) => tokens.values[k] === v);
275
345
  if (same) return false;
276
346
  tokens = next;
277
347
  changed();
348
+ // A web font the labels name is fetched when something asks for it, and a canvas does not wait for one: ask now, and draw again when it is in
349
+ try { if (next.font && typeof document !== 'undefined' && document.fonts && document.fonts.load) document.fonts.load(`12px ${next.font}`).catch(() => {}); } catch { /* no font loading here */ }
278
350
  return true;
279
351
  }
280
352
 
@@ -304,7 +376,7 @@ export function applyMapTheme(doc, theme, opts = {}) {
304
376
 
305
377
  /** Back to nothing set (for tests) */
306
378
  export function resetMapStyle() {
307
- tokens = { values: {}, strokeWidth: DEFAULT_STROKE_WIDTH };
379
+ tokens = NO_TOKENS;
308
380
  icons = null;
309
381
  pixelated = false;
310
382
  changed();
@@ -332,6 +404,12 @@ export function watchMapStyle(doc) {
332
404
  if (media.addEventListener) { media.addEventListener('change', refresh); stops.push(() => media.removeEventListener('change', refresh)); }
333
405
  else if (media.addListener) { media.addListener(refresh); stops.push(() => media.removeListener(refresh)); }
334
406
  }
407
+ const fonts = doc.fonts;
408
+ if (fonts && fonts.addEventListener) {
409
+ const again = () => { if (tokens.font) changed(); }; // the label font arrived: the canvas draws again with it
410
+ fonts.addEventListener('loadingdone', again);
411
+ stops.push(() => fonts.removeEventListener('loadingdone', again));
412
+ }
335
413
  refresh();
336
414
  return () => stops.forEach((fn) => fn());
337
415
  }
@@ -342,20 +420,30 @@ export function watchMapStyle(doc) {
342
420
 
343
421
  const firstOf = (values, names) => { for (const n of names) if (values[n]) return values[n]; return null; };
344
422
 
345
- function styleEdge(e, values, painted) {
423
+ /** A line's shape in the theme: its width scaled to `--corn-map-edge-width`, its glow and its packet's by `--corn-map-glow` (nothing at `auto`) */
424
+ function shapeEdge(e, style) {
425
+ const scale = style.edgeWidth == null ? 1 : style.edgeWidth / BASE_EDGE_WIDTH;
426
+ const glow = style.glow == null ? 1 : style.glow;
427
+ if (scale === 1 && glow === 1) return e;
428
+ const out = { ...e, width: e.width * scale, glow: e.glow * glow };
429
+ if (e.packet) out.packet = { ...e.packet, glow: e.packet.glow * glow };
430
+ return out;
431
+ }
432
+
433
+ function styleEdge(e, style, painted) {
434
+ const { values } = style;
346
435
  if (e.mark && e.mark !== 'none') {
347
436
  const c = values[stateToken(e.mark)];
348
- if (!c) return e;
349
- return { ...e, color: c, glowColor: e.glowColor ? c : e.glowColor };
437
+ return shapeEdge(c ? { ...e, color: c, glowColor: e.glowColor ? c : e.glowColor } : e, style);
350
438
  }
351
- if (painted.has(e.key)) return e;
439
+ if (painted.has(e.key)) return shapeEdge(e, style);
352
440
  const lit = !e.curve && e.glow > 0 && !e.arrow; // a straight link the focus lights
353
441
  const c = (lit && values[stateToken('lit')]) || values[edgeToken(e.kind)];
354
- if (!c) return e;
442
+ if (!c) return shapeEdge(e, style);
355
443
  const out = { ...e, color: withAlphaOf(c, e.color) };
356
444
  if (e.glowColor) out.glowColor = withAlphaOf(c, e.glowColor);
357
445
  if (e.packet) out.packet = { ...e.packet, glowColor: withAlphaOf(c, e.packet.glowColor) };
358
- return out;
446
+ return shapeEdge(out, style);
359
447
  }
360
448
 
361
449
  function compute(scene, style) {
@@ -366,15 +454,18 @@ function compute(scene, style) {
366
454
  const nodes = scene.nodes.map((n) => {
367
455
  const fill = !painted.nodes.has(n.id) && firstOf(values, [nodeToken(n.type), groupToken(n.group || n.type)]);
368
456
  const icon = style.icons && style.icons.get(n.type) ? n.type : null;
369
- if (!fill && !label && !stroke && !icon) return n;
457
+ const glows = style.glow != null && style.glow !== 1 && n.glow > 0;
458
+ if (!fill && !label && !stroke && !icon && !glows) return n;
370
459
  const out = { ...n };
460
+ if (glows) out.glow = n.glow * style.glow;
371
461
  if (fill) out.color = fill;
372
462
  if (label) out.labelColor = withAlphaOf(label, n.labelColor);
373
463
  if (stroke && style.strokeWidth > 0) out.stroke = { color: stroke, width: style.strokeWidth };
374
464
  if (icon) out.icon = icon;
375
465
  return out;
376
466
  });
377
- const out = { ...scene, nodes, edges: scene.edges.map((e) => styleEdge(e, values, painted.edges)) };
467
+ const out = { ...scene, nodes, edges: scene.edges.map((e) => styleEdge(e, style, painted.edges)) };
468
+ if (style.font) out.labelFont = style.font; // every label's font list (labels.js reads `scene.labelFont`)
378
469
  const halo = values[LABEL_HALO_TOKEN];
379
470
  if (halo) { // the outline under the labels, at the widths it has (labels.js reads `scene.labelOutline` before the ground's own)
380
471
  const { node, edge } = looksFor(scene.theme).labelOutline;
@@ -19,7 +19,9 @@ import { cloudPanelHtml } from './cloud-model.js';
19
19
  import { t } from './strings.js';
20
20
  import { fileUrl } from './file-url.js';
21
21
  import { capped, toggleCapped } from './capped.js';
22
+ import { dismissHint } from './hint.js';
22
23
  import { canStartAgent, openProposalStart } from './forge-panel.js';
24
+ import { sayResult, clearResult, showResultIn, RESULT_MS } from './feedback.js';
23
25
 
24
26
  const $ = (id) => document.getElementById(id);
25
27
 
@@ -225,6 +227,7 @@ export async function selectNode(node) {
225
227
  if (!node) return;
226
228
  const token = ++selectToken;
227
229
  clearScenario();
230
+ dismissHint(); // a node has been picked: the hint's job is done for this session
228
231
  state.selectedNode = node;
229
232
  state.selectedEdge = null;
230
233
  touchScene();
@@ -311,15 +314,20 @@ export function closeDrawer() {
311
314
  render();
312
315
  }
313
316
 
314
- /** Copies the selected node as JSON; the button says so for a moment */
317
+ let copyTimer = 0;
318
+ /** Copies the selected node as JSON; the result is said under the button and to a screen reader, and stays a few seconds */
315
319
  export async function copySpec(button) {
316
320
  if (!state.selectedNode) return;
317
321
  const text = JSON.stringify({ node: state.selectedNode }, null, 2);
322
+ clearTimeout(copyTimer);
323
+ clearResult('copy-spec');
324
+ const where = $('copy-spec-result');
318
325
  try {
319
326
  await navigator.clipboard.writeText(text);
320
- button.textContent = 'Copied ✓';
327
+ sayResult('copy-spec', `Copied the spec of ${state.selectedNode.label || state.selectedNode.id} to the clipboard.`, true);
321
328
  } catch {
322
- button.textContent = 'Copy blocked';
329
+ sayResult('copy-spec', 'The browser did not allow copying, so nothing was copied. Allow clipboard access for this page, then press Copy Spec again.', false);
323
330
  }
324
- setTimeout(() => { button.textContent = t('copySpec'); }, 1500);
331
+ showResultIn(where, 'copy-spec');
332
+ copyTimer = setTimeout(() => { clearResult('copy-spec'); showResultIn(where, 'copy-spec'); }, RESULT_MS);
325
333
  }
@@ -23,7 +23,17 @@ export const NO_SOURCE = Object.freeze({
23
23
  name: 'no live source',
24
24
  async load() {
25
25
  const err = new Error('no live source is configured');
26
- Object.assign(err, { reason: 'unavailable', hint: 'no live source is set in cornfield.config.js (sources)' });
26
+ Object.assign(err, { reason: 'unavailable', notConfigured: true, hint: 'no live source is set in cornfield.config.js (sources)' });
27
+ throw err;
28
+ },
29
+ });
30
+
31
+ /** What the live layer shows when the repo names a live, house or devices source and none of them loaded: an error, not "none set" */
32
+ export const failedSource = (slots) => Object.freeze({
33
+ name: 'live source that did not load',
34
+ async load() {
35
+ const err = new Error('the live source did not load');
36
+ Object.assign(err, { reason: 'unavailable', hint: `the ${slots.join(' and ')} source in cornfield.config.js did not load (the browser console says why)` });
27
37
  throw err;
28
38
  },
29
39
  });
@@ -188,12 +198,14 @@ export function combineSources(sources) {
188
198
  * Loads the sources a config names.
189
199
  * @param {{ sources?: Record<string, { module: string, options?: object } | null> }} config
190
200
  * @param {(url: string) => Promise<any>} [importer]
191
- * @returns {Promise<{ liveSource: object, floorRenderer: object|null, checker: object|null }>}
201
+ * @returns {Promise<{ houseSource: boolean, liveSource: object, floorRenderer: object|null, checker: object|null }>}
192
202
  */
193
203
  export async function loadSources(config, importer = (url) => import(url)) {
194
204
  const loaded = {};
205
+ const named = []; // the live, house and devices slots the config names: a house can come from any of them
195
206
  for (const [slot, s] of Object.entries((config && config.sources) || {})) {
196
207
  if (!s || typeof s.module !== 'string' || !s.module.startsWith('/')) continue;
208
+ if (['live', 'house', 'devices'].includes(slot)) named.push(slot);
197
209
  try {
198
210
  const mod = await importer(s.module);
199
211
  loaded[slot] = typeof mod.create === 'function' ? (await mod.create(s.options || {})) || {} : mod;
@@ -204,7 +216,10 @@ export async function loadSources(config, importer = (url) => import(url)) {
204
216
  const pick = (key, order) => order.map((slot) => loaded[slot] && loaded[slot][key]).find(Boolean) || null;
205
217
  const lives = ['live', 'house', 'devices'].map((slot) => loaded[slot] && loaded[slot].liveSource).filter(Boolean);
206
218
  return {
207
- liveSource: lives.length ? combineSources(lives) : NO_SOURCE,
219
+ // The config names a source that can answer for a house: the House view is offered (house-model.js `houseOffered`), even when the
220
+ // source did not load, so its failure shows as one (the live chip's error) rather than as a House button gone missing
221
+ houseSource: named.length > 0,
222
+ liveSource: lives.length ? combineSources(lives) : named.length ? failedSource(named) : NO_SOURCE,
208
223
  floorRenderer: pick('floorRenderer', ['house', 'live', 'devices']),
209
224
  checker: pick('checker', ['checker', 'live', 'house', 'devices']),
210
225
  };
@@ -223,10 +223,39 @@ export function proposalPanelHtml(item) {
223
223
  /** What a listing entry's state pill says: its spec PR's state, or "Local" for a proposal that is only in a checkout or a worktree */
224
224
  export const specState = (entry) => (entry.pull ? (entry.pull.draft ? 'Draft' : 'Open') : 'Local');
225
225
 
226
- /** Where a listing entry is, as a line of meta: "PR #11", or the checkout or worktree it is in */
226
+ /** Where a listing entry is, as a line of meta: "PR #11", or the checkout or worktree it is in; a proposal that is also somewhere else says so ("PR #11, and a copy in the checkout") */
227
227
  export function specWhere(entry) {
228
- if (entry.pull) return `PR #${entry.pull.number}`;
229
- return entry.source === 'checkout' ? 'in the checkout' : `in worktree ${entry.source}`;
228
+ const place = (source) => (source === 'checkout' ? 'the checkout' : `worktree ${source}`);
229
+ const copies = Array.isArray(entry.also) ? entry.also : [];
230
+ if (entry.pull) return `PR #${entry.pull.number}${copies.length ? `, and a copy in ${copies.map(place).join(' and ')}` : ''}`;
231
+ return `in ${place(entry.source)}${copies.length ? `, and in ${copies.map(place).join(' and ')}` : ''}`;
232
+ }
233
+
234
+ /**
235
+ * One row for each proposal. A proposal that is a draft in a checkout or a worktree and also on a spec PR is listed twice by the server (the two
236
+ * are different sources); here it is one row, the PR's (the one that can be reviewed), which says there is a local copy too (`also`: the sources
237
+ * of the copies). Local copies only (a checkout and a worktree) are one row as well. An entry that could not be read is never hidden behind
238
+ * another: its row stays and says why. Spec PRs come first (open, then draft), then local drafts; within each, the listing's order.
239
+ * @template T
240
+ * @param {T[]} entries the server's listing
241
+ * @returns {T[]}
242
+ */
243
+ export function mergeSpecs(entries) {
244
+ const groups = new Map();
245
+ for (const entry of entries || []) groups.set(entry.slug, [...(groups.get(entry.slug) || []), entry]);
246
+ const out = [];
247
+ for (const group of groups.values()) {
248
+ const read = group.filter((e) => !e.error);
249
+ const prs = read.filter((e) => e.pull);
250
+ const locals = read.filter((e) => !e.pull);
251
+ const also = (list) => (list.length ? { also: list.map((e) => e.source) } : {});
252
+ if (prs.length) out.push({ ...prs[0], ...also(locals) }, ...prs.slice(1));
253
+ else if (locals.length) out.push({ ...locals[0], ...also(locals.slice(1)) });
254
+ out.push(...group.filter((e) => e.error)); // a copy that could not be read keeps its own row, with why
255
+ }
256
+ // The ones a maintainer can review come first: open spec PRs, then draft ones, then the drafts in a checkout (in the listing's order within each)
257
+ const rank = (e) => (e.pull ? (e.pull.draft ? 1 : 0) : 2);
258
+ return out.map((e, i) => [e, i]).sort((a, b) => rank(a[0]) - rank(b[0]) || a[1] - b[1]).map(([e]) => e);
230
259
  }
231
260
 
232
261
  /**
@@ -241,7 +270,7 @@ export function specRowHtml(entry, { current = null } = {}) {
241
270
  return `<li class="hx-forge-item"><div class="hx-forge-row hx-forge-spec" data-corn="row">${head}<span class="hx-forge-sum hx-error-text">${escHtml(entry.error)}</span><span class="hx-forge-meta">${escHtml(specWhere(entry))}</span></div></li>`;
242
271
  }
243
272
  const state = specState(entry);
244
- const tone = state === 'Local' ? '' : ` data-corn-state="${state === 'Draft' ? 'draft' : 'open'}"`;
273
+ const tone = ` data-corn-state="${state === 'Open' ? 'open' : 'draft'}"`; // a proposal only in a checkout is a draft too, as a branch with no pull request is
245
274
  const c = entry.counts || {};
246
275
  const meta = [
247
276
  entry.spec ? `<span>spec ${escHtml(entry.spec)}</span>` : '',
@@ -252,7 +281,7 @@ export function specRowHtml(entry, { current = null } = {}) {
252
281
  c.scenarios ? `<span>${c.scenarios} ${c.scenarios === 1 ? 'scenario' : 'scenarios'}</span>` : '',
253
282
  entry.errors ? `<span class="hx-warn">${entry.errors} ${entry.errors === 1 ? 'problem' : 'problems'}</span>` : '',
254
283
  ].filter(Boolean).join('');
255
- const mine = !!current && current.slug === entry.slug && current.source === entry.source;
284
+ const mine = !!current && current.slug === entry.slug && (current.source === entry.source || (Array.isArray(entry.also) && entry.also.includes(current.source)));
256
285
  return `<li class="hx-forge-item"><button type="button" class="hx-forge-row hx-forge-spec" data-action="open-proposal" data-slug="${escHtml(entry.slug)}" data-source="${escHtml(entry.source)}" aria-pressed="${mine}" data-corn="row">`
257
286
  + `<span class="hx-forge-line">${head}<span class="hx-forge-state hx-forge-state--${state === 'Draft' ? 'draft' : state === 'Open' ? 'open' : 'neutral'}" data-corn="state-pill"${tone}>${state}</span></span>`
258
287
  + `${entry.summary ? `<span class="hx-forge-sum">${escHtml(entry.summary)}</span>` : ''}<span class="hx-forge-meta hx-forge-facts">${meta}</span></button></li>`;
@@ -35,6 +35,7 @@ import { reviewWords } from './review-model.js';
35
35
  import { collapseSheet, visibleMapRect, isPhone } from './sheets.js';
36
36
  import { announce } from './keyboard.js';
37
37
  import { t } from './strings.js';
38
+ import { isOffline } from './connection.js';
38
39
 
39
40
  const $ = (id) => document.getElementById(id);
40
41
 
@@ -76,10 +77,12 @@ export function onProposalListing(fn) {
76
77
  /** Asks the server for the proposals it can serve */
77
78
  export async function loadProposalList() {
78
79
  try {
79
- const res = await fetch('/proposals', { cache: 'no-store' });
80
- if (!res.ok) throw new Error(`GET /proposals answered ${res.status}`);
81
- const body = await res.json();
82
- if (!Array.isArray(body)) throw new Error('GET /proposals did not answer with a list');
80
+ let res;
81
+ try { res = await fetch('/proposals', { cache: 'no-store' }); } catch { throw new Error(isOffline() ? 'You are offline.' : 'cornfield could not be reached. Check that it is still running.'); }
82
+ if (!res.ok) throw new Error(`The server could not list them (error ${res.status}).`);
83
+ let body;
84
+ try { body = await res.json(); } catch { throw new Error('cornfield sent a list this page could not read.'); }
85
+ if (!Array.isArray(body)) throw new Error('cornfield sent something that is not a list of proposals.');
83
86
  listing = body;
84
87
  listingProblem = null;
85
88
  const said = res.headers.get('X-Proposals-Forge-Error');
@@ -87,7 +90,7 @@ export async function loadProposalList() {
87
90
  } catch (err) {
88
91
  listing = null;
89
92
  forgeProblem = null;
90
- listingProblem = err.message || String(err);
93
+ listingProblem = err.message || 'cornfield did not answer.'; // always a plain sentence made above, never a parser's or a runtime's own words
91
94
  }
92
95
  listingAt = Date.now();
93
96
  renderMenu();
@@ -104,23 +107,27 @@ export async function openProposal(slug, source = null) {
104
107
  const token = ++openToken;
105
108
  setMessage(`Opening ${slug} …`);
106
109
  try {
107
- const res = await fetch(`/proposals/${encodeURIComponent(slug)}.json${source ? `?source=${encodeURIComponent(source)}` : ''}`, { cache: 'no-store' });
110
+ let res;
111
+ try { res = await fetch(`/proposals/${encodeURIComponent(slug)}.json${source ? `?source=${encodeURIComponent(source)}` : ''}`, { cache: 'no-store' }); } catch { throw new Error(isOffline() ? `${slug} could not be opened: you are offline.` : `${slug} could not be opened: cornfield could not be reached.`); }
108
112
  if (!res.ok) {
109
113
  let why = '';
110
114
  try { why = (await res.json()).error || ''; } catch { /* no body */ }
111
- const err = new Error(res.status === 404 ? notFoundWords(slug, source) : why || `The server answered ${res.status}.`);
115
+ const err = new Error(res.status === 404 ? notFoundWords(slug, source) : `${slug} could not be opened: ${why || `the server had a problem (error ${res.status}).`}`);
112
116
  err.notFound = res.status === 404;
113
117
  throw err;
114
118
  }
115
119
  const found = res.headers.get('X-Proposal-Source');
116
- showProposal(await res.json(), { slug, source: source || (found ? decodeURIComponent(found) : null), pinSource: !!source, view: 'diff', fit: true });
120
+ let item;
121
+ try { item = await res.json(); } catch { throw new Error(`${slug} could not be opened: cornfield sent a file this page could not read.`); }
122
+ showProposal(item, { slug, source: source || (found ? decodeURIComponent(found) : null), pinSource: !!source, view: 'diff', fit: true });
117
123
  // said once, here: a proposal opens on a person's asking, never on a background refresh
118
124
  announce(openedWords($('proposal-title').textContent, summarize(state.proposal), state.proposalView));
119
125
  return true;
120
126
  } catch (err) {
121
127
  console.error('Opening the proposal failed', err);
122
128
  // Said plainly, with the ways on: the Specs list, and the same name under another source when the list has one
123
- setMessage(err.message || String(err), true, err.notFound ? [specsWay()] : []);
129
+ // (a failure that is not "no such proposal" can be asked for again, or let go of: Retry and Close)
130
+ setMessage(err.message || `${slug} could not be opened.`, true, err.notFound ? [specsWay()] : [{ label: 'Retry', way: 'retry', slug, source }, { label: 'Close', way: 'close' }]);
124
131
  if (err.notFound && token === openToken) {
125
132
  await loadProposalList();
126
133
  const sources = new Set((Array.isArray(listing) ? listing : []).map((e) => e && e.source));
@@ -621,7 +628,7 @@ const ACTIONS = {
621
628
  'toggle-proposal-mode': () => toggleMode(),
622
629
  'toggle-proposal-more': () => (moreOpen() ? closeMore() : openMore()),
623
630
  'toggle-proposal-changes': () => toggleChanges(),
624
- 'proposal-way': (el) => (el.dataset.way === 'open' ? openProposal(el.dataset.slug, el.dataset.source || null) : openSpecs()),
631
+ 'proposal-way': (el) => (el.dataset.way === 'open' ? openProposal(el.dataset.slug, el.dataset.source || null) : el.dataset.way === 'retry' ? retryOpen(el.dataset.slug, el.dataset.source || null) : el.dataset.way === 'close' ? closeAfterFailure() : openSpecs()),
625
632
  'proposal-focus': (el) => focusChange(el.dataset.kind, el.dataset.key),
626
633
  };
627
634
 
@@ -636,6 +643,22 @@ function onClick(e) {
636
643
  if (menuOpen() && wrap && !wrap.contains(e.target) && !(target && target.dataset.action === 'proposal-way')) closeMenu(); // (a bad link's Specs list opens it from outside)
637
644
  }
638
645
 
646
+ /** Retry, after a proposal failed to open: the bar is drawn anew either way, so the focus goes somewhere stated, the proposal's name once it opened or the new Retry if it failed again */
647
+ async function retryOpen(slug, source) {
648
+ const opened = await openProposal(slug, source);
649
+ const to = opened ? $('proposal-title') : document.querySelector('#proposal-ways [data-way="retry"]');
650
+ if (!to) return;
651
+ if (opened) to.tabIndex = -1;
652
+ to.focus();
653
+ }
654
+
655
+ /** Close, after a proposal failed to open: the bar goes, and the focus goes to the map, never the page */
656
+ function closeAfterFailure() {
657
+ closeProposal();
658
+ const map = $('graph-canvas');
659
+ if (map) map.focus();
660
+ }
661
+
639
662
  /** A bad link's way on: the Work panel's Specs tab when there is one, else the header's Proposals menu */
640
663
  function openSpecs() {
641
664
  if (hooks.openSpecs) { hooks.openSpecs(); return; }
@@ -30,6 +30,7 @@ import { refreshMockups } from './mockups.js';
30
30
  import { getEdits, clearEdits } from './whatif.js';
31
31
  import { reviewParts, sendBackProblem, reviewBody, editsHint, isReviewable, NOT_ON_A_PR } from './review-model.js';
32
32
  import { t } from './strings.js';
33
+ import { isOffline, notSentWords } from './connection.js';
33
34
 
34
35
  const $ = (id) => document.getElementById(id);
35
36
 
@@ -40,6 +41,7 @@ const ui = {
40
41
  key: null, // `${source}/${slug}` of the proposal the review below belongs to
41
42
  reviewable: false, // whether it is on a spec PR
42
43
  review: null, // { verdict, at } | null: the last review of it
44
+ loadFailed: false, // the past reviews could not be read: the bar must not look as if there were none
43
45
  busy: false,
44
46
  noting: false, // the note field is open (Send back was pressed)
45
47
  message: '', // an inline refusal or failure
@@ -77,6 +79,7 @@ function mount() {
77
79
  <button type="button" class="hx-btn hx-btn--quiet" data-review-cancel data-corn-kind="quiet">Cancel</button>
78
80
  </div>
79
81
  </div>
82
+ <p class="hx-review-msg" data-review-loadfail role="alert" hidden data-corn="message" data-corn-state="failure"><span data-review-loadfail-text></span> <button type="button" class="hx-btn hx-btn--quiet" data-review-retry data-corn-kind="quiet">Retry</button></p>
80
83
  <p class="hx-review-msg" data-review-msg role="alert" hidden></p>
81
84
  <p class="hx-review-line" id="review-hint" data-review-hint role="status" hidden></p>
82
85
  `;
@@ -103,6 +106,10 @@ function paint() {
103
106
  if (said.textContent !== verdict) said.textContent = verdict;
104
107
  q('[data-review-when]').textContent = when ? ` ${when}` : '';
105
108
  status.hidden = !verdict;
109
+ // A failed read of the past reviews says so: an approved proposal must not look as if nobody had reviewed it
110
+ const failed = q('[data-review-loadfail]');
111
+ failed.hidden = !ui.loadFailed;
112
+ q('[data-review-loadfail-text]').textContent = ui.loadFailed ? `Could not load this proposal's reviews.${isOffline() ? ' You are offline.' : ''} It may already be approved or sent back; try again before you decide.` : '';
106
113
  // 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
107
114
  // only says it is busy (`aria-disabled`): a `disabled` button drops the focus to the page.
108
115
  for (const btn of document.querySelectorAll('#proposal-bar [data-review]')) {
@@ -159,6 +166,7 @@ function onBar(open) {
159
166
  ui.key = key;
160
167
  ui.reviewable = !!key && isReviewable(state.proposalSource);
161
168
  ui.review = null;
169
+ ui.loadFailed = false;
162
170
  ui.busy = false;
163
171
  ui.noting = false;
164
172
  ui.message = ui.hint = '';
@@ -169,20 +177,41 @@ function onBar(open) {
169
177
  }
170
178
 
171
179
  /** The latest admin review on the proposal's PR, as the server reads it from the comments (none yet is a 404) */
180
+ /** The reviews were read: the failure line goes, and Retry, if it had the focus, hands it to the proposal's name (the status line is a live region: it says the review itself, and is not a place for the focus) */
181
+ function readAgain() {
182
+ const retried = !!root && root.contains(document.activeElement) && document.activeElement.matches('[data-review-retry]');
183
+ ui.loadFailed = false;
184
+ paint();
185
+ const title = $('proposal-title');
186
+ if (!retried || !title) return;
187
+ title.tabIndex = -1;
188
+ title.focus();
189
+ }
190
+
191
+ function readOnline() {
192
+ if (ui.loadFailed && ui.key) loadReview(ui.key);
193
+ }
194
+
172
195
  async function loadReview(key) {
173
196
  try {
174
197
  const res = await fetch(reviewUrl(), { cache: 'no-store' });
175
- if (!res.ok) return;
198
+ if (key !== ui.key) return; // another proposal has opened since
199
+ if (res.status === 404) { readAgain(); return; } // none yet: the server says so with a 404
200
+ if (!res.ok) throw new Error(`The server answered ${res.status}.`);
176
201
  const found = await res.json();
177
- if (key !== ui.key || !found || typeof found.verdict !== 'string') return; // none, or another proposal has opened since
178
- ui.review = { verdict: found.verdict, at: found.at };
179
- paint();
180
- } catch { /* the server is not there: no review shown */ }
202
+ if (key !== ui.key) return;
203
+ if (found && typeof found.verdict === 'string') ui.review = { verdict: found.verdict, at: found.at };
204
+ readAgain();
205
+ } catch {
206
+ // Not "no review": the read failed, so the bar says it could not look (with Retry), and the buttons stay as they were
207
+ if (key === ui.key) { ui.loadFailed = true; paint(); }
208
+ }
181
209
  }
182
210
 
183
211
  function onClick(e) {
184
212
  if (ui.busy || !e.target.closest) return;
185
213
  if (e.target.closest('[data-review-cancel]')) { closeNote(); return; }
214
+ if (e.target.closest('[data-review-retry]')) { q('[data-review-loadfail-text]').textContent = 'Reading the reviews again …'; loadReview(ui.key); return; }
186
215
  const btn = e.target.closest('[data-review]');
187
216
  if (!btn || btn.disabled) return;
188
217
  if (btn.dataset.review === 'notes' && !ui.noting) openNote(); // the first press opens the field, the second sends
@@ -216,8 +245,18 @@ export async function sendReview(verdict) {
216
245
  const key = ui.key;
217
246
  const body = reviewBody(verdict, note, getEdits());
218
247
  let saved;
248
+ const what = verdict === 'approved' ? 'Your approval' : 'Your send back';
249
+ let res;
250
+ try {
251
+ res = await fetch(reviewUrl(), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
252
+ } catch {
253
+ // No answer at all: offline, or the server is not there. Said so, not as a server's error; the note and the edits are kept, and it says it was not sent
254
+ ui.busy = false;
255
+ ui.message = notSentWords(what);
256
+ paint();
257
+ return false;
258
+ }
219
259
  try {
220
- const res = await fetch(reviewUrl(), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
221
260
  let answer = null;
222
261
  try { answer = await res.json(); } catch { /* no body */ }
223
262
  if (!res.ok) throw new Error((answer && answer.error) || `The server answered ${res.status}.`);
@@ -258,6 +297,8 @@ export function initReview() {
258
297
  if (barBefore) barBefore(open);
259
298
  onBar(open);
260
299
  };
300
+ // Back online after a failed read: the reviews are read again (the same function each time, so it is added once)
301
+ if (typeof window !== 'undefined') window.addEventListener('online', readOnline);
261
302
  // "3 minutes ago" moves on without the bar being drawn again
262
303
  timer = setInterval(() => { if (ui.review) paint(); }, TICK_MS);
263
304
  onBar(!!state.proposal);
@@ -271,5 +312,5 @@ export function resetReviewForTests(clock = () => Date.now()) {
271
312
  wired = false;
272
313
  root = null;
273
314
  now = clock;
274
- Object.assign(ui, { key: null, reviewable: false, review: null, busy: false, noting: false, message: '', hint: '' });
315
+ Object.assign(ui, { key: null, reviewable: false, review: null, loadFailed: false, busy: false, noting: false, message: '', hint: '' });
275
316
  }