@popcorn245/cornfield 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,9 +27,10 @@ import { edgePoint, looksFor } from './scene.js';
27
27
  import { onThemeChange } from './theme.js';
28
28
  import { looksWith, onMapStyleChange } from './map-style.js';
29
29
  import {
30
- PROPOSAL_VIEWS, MARKS, MARK_WORDS, chipText, barCounts, parseProposalQuery, proposalPanelHtml, touchedIds, viewWords, openedWords, jumpWords,
30
+ PROPOSAL_VIEWS, MARK_WORDS, chipText, barCounts, parseProposalQuery, proposalPanelHtml, touchedIds, viewWords, jumpWords,
31
31
  sourceChip, pullNumberOf, notFoundWords, otherCopies, malformedLinkWords,
32
32
  } from './proposal-model.js';
33
+ import { renderReviewColumn, reviewOpenedLine, showSection, setPullHead } from './review-column.js';
33
34
  import { applyProposal, edgeKey, proposalProblems, summarize } from '../core/proposal.js';
34
35
  import { reviewWords } from './review-model.js';
35
36
  import { collapseSheet, visibleMapRect, isPhone } from './sheets.js';
@@ -123,7 +124,7 @@ export async function openProposal(slug, source = null) {
123
124
  try { item = await res.json(); } catch { throw new Error(`${slug} could not be opened: cornfield sent a file this page could not read.`); }
124
125
  showProposal(item, { slug, source: source || (found ? decodeURIComponent(found) : null), pinSource: !!source, view: 'diff', fit: true });
125
126
  // said once, here: a proposal opens on a person's asking, never on a background refresh
126
- announce(openedWords($('proposal-title').textContent, summarize(state.proposal), state.proposalView));
127
+ announce(reviewOpenedLine($('proposal-title').textContent));
127
128
  return true;
128
129
  } catch (err) {
129
130
  console.error('Opening the proposal failed', err);
@@ -235,7 +236,7 @@ function swapMap(nodes, edges) {
235
236
 
236
237
  /**
237
238
  * 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
238
- * 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
239
+ * map nothing covers (the bar, the review column, 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
239
240
  * 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,
240
241
  * 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.
241
242
  */
@@ -326,6 +327,7 @@ async function loadPullInfo(n) {
326
327
  const res = await fetch(`/api/forge/pulls/${n}`);
327
328
  const body = res.ok ? await res.json() : null;
328
329
  if (body && body.ok !== false && body.pull) pullInfo.set(n, { pull: body.pull, checks: Array.isArray(body.checks) ? body.checks : null });
330
+ if (body && body.pull && pullNumberOf(state.proposalSource) === n) setPullHead(body.pull.head && typeof body.pull.head.sha === 'string' ? body.pull.head.sha : ''); // what was seen is kept per PR head
329
331
  } catch { /* no forge, or not signed in: the chip keeps what it has */ }
330
332
  if (state.proposal && pullNumberOf(state.proposalSource) === n) paintSource();
331
333
  }
@@ -347,7 +349,7 @@ export function renderBar() {
347
349
  bar.hidden = !open;
348
350
  const legend = $('proposal-legend');
349
351
  if (legend) legend.hidden = !open;
350
- if (!open) { closeMore(); toggleMode(false); collapseSheet('proposal'); if (hooks.bar) hooks.bar(false); return; }
352
+ if (!open) { closeMore(); toggleMode(false); collapseSheet('proposal'); renderReviewColumn(); if (hooks.bar) hooks.bar(false); return; }
351
353
 
352
354
  bar.classList.remove('is-error');
353
355
  $('proposal-message').hidden = true;
@@ -357,14 +359,18 @@ export function renderBar() {
357
359
  paintSource();
358
360
  const summary = $('proposal-summary');
359
361
  summary.textContent = (p && typeof p.summary === 'string' && p.summary) || '';
360
- const title = $('proposal-title');
361
- title.title = summary.textContent; // the toolbar stays one row: the summary is the title's tooltip, and shows above the list of changes
362
- summary.hidden = !summary.textContent || $('proposal-changes').hidden;
362
+ summary.hidden = !summary.textContent;
363
+ $('proposal-title').title = summary.textContent; // the bar stays one row: the summary is also the title's tooltip, and leads the review column
363
364
 
364
365
  const counts = summarize(p);
365
366
  const chip = $('proposal-chip');
366
- chip.innerHTML = barCounts(counts).map((c) => `${c.mark ? `<span class="hx-mark-dot hx-mark-dot--${c.mark}" data-corn="mark-dot"${markStateAttr(c.mark)} aria-hidden="true"></span>` : ''}${escHtml(c.text)}`).join('<span class="hx-proposal-sep" aria-hidden="true"> · </span>');
367
- chip.title = 'Click for the list of changes.';
367
+ // The counts name their lists: the changes part shows the Changes section, "5 scenarios" the Scenarios section (the review column, review-column.js)
368
+ const parts = barCounts(counts);
369
+ chip.innerHTML = parts.map((c) => {
370
+ const dot = c.mark ? `<span class="hx-mark-dot hx-mark-dot--${c.mark}" data-corn="mark-dot"${markStateAttr(c.mark)} aria-hidden="true"></span>` : '';
371
+ if (!c.mark && /scenarios?$/.test(c.text)) return `<button type="button" class="hx-proposal-count" data-action="review-show-scenarios" data-corn-kind="quiet" title="Show the personas and their scenarios">${escHtml(c.text)}</button>`;
372
+ return `<button type="button" class="hx-proposal-count" data-action="review-show-changes" data-corn-kind="quiet" title="Show the list of changes">${dot}${escHtml(c.text)}</button>`;
373
+ }).join('<span class="hx-proposal-sep" aria-hidden="true"> · </span>');
368
374
  $('proposal-mode').textContent = t(state.proposalView);
369
375
 
370
376
  for (const btn of bar.querySelectorAll('[data-action="proposal-view"]')) {
@@ -380,40 +386,12 @@ export function renderBar() {
380
386
  $('proposal-errors-count').textContent = `${plural(errors.length, 'problem')} in this proposal`;
381
387
  $('proposal-errors-list').innerHTML = problemsHtml(errors);
382
388
  }
383
- renderChanges();
389
+ renderReviewColumn();
384
390
  if (hooks.bar) hooks.bar(true);
385
391
  }
386
392
 
387
- /** The list behind the chip: every marked node and edge, one row each, to pick one without finding it on the map */
388
- function renderChanges() {
389
- const list = $('proposal-changes');
390
- if (!list) return;
391
- // The ownership edge a `parent` adds, and the edges of a removed node, are consequences: the list holds what the proposal says
392
- const said = new Set(['add', 'change', 'remove'].flatMap((op) => asList((state.effectiveProposal || state.proposal)?.edges?.[op]).map(edgeKey)));
393
- const rows = [];
394
- for (const mark of [...MARKS, 'edit']) {
395
- for (const n of state.nodes.filter((x) => x.mark === mark)) {
396
- rows.push(`<button type="button" class="hx-change-row" data-action="proposal-focus" data-kind="node" data-key="${escHtml(n.id)}" data-corn="row"><span class="hx-mark-dot hx-mark-dot--${mark}" data-corn="mark-dot"${markStateAttr(mark)}></span><span class="hx-change-what">${escHtml(MARK_WORDS[mark])}</span><span class="hx-name">${escHtml(n.label)}</span><span class="hx-faint">${escHtml(n.type)}</span></button>`);
397
- }
398
- for (const e of state.edges.filter((x) => x.mark === mark && said.has(edgeKey(x)))) {
399
- rows.push(`<button type="button" class="hx-change-row" data-action="proposal-focus" data-kind="edge" data-key="${escHtml(edgeKey(e))}" data-corn="row"><span class="hx-mark-dot hx-mark-dot--${mark}" data-corn="mark-dot"${markStateAttr(mark)}></span><span class="hx-change-what">${escHtml(MARK_WORDS[mark])}</span><span class="hx-name">${escHtml(nameOf(e.from))} → ${escHtml(nameOf(e.to))}</span><span class="hx-faint">${escHtml(e.kind || 'ownership')}</span></button>`);
400
- }
401
- }
402
- list.innerHTML = rows.join('') || '<p class="hx-faint">This proposal changes nothing on the map.</p>';
403
- }
404
-
405
- function toggleChanges(refocus = false) {
406
- const list = $('proposal-changes');
407
- if (!list) return;
408
- list.hidden = !list.hidden;
409
- $('proposal-summary').hidden = list.hidden || !$('proposal-summary').textContent;
410
- $('proposal-chip').setAttribute('aria-expanded', String(!list.hidden));
411
- // 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
412
- if (!list.hidden) { if (!isPhone()) list.querySelector('button')?.focus(); } else if (refocus) $('proposal-chip').focus();
413
- }
414
-
415
393
  /**
416
- * 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,
394
+ * Picks a row of the changes list: select it, centre it in the part of the map the review column, the node panel and (on a phone) the sheets leave free,
417
395
  * at a zoom where its label reads, and make sure the current view shows it
418
396
  */
419
397
  function focusChange(kind, key) {
@@ -629,7 +607,8 @@ const ACTIONS = {
629
607
  'proposal-view': (el) => { setProposalView(el.dataset.view); toggleMode(false); },
630
608
  'toggle-proposal-mode': () => toggleMode(),
631
609
  'toggle-proposal-more': () => (moreOpen() ? closeMore() : openMore()),
632
- 'toggle-proposal-changes': () => toggleChanges(),
610
+ 'review-show-changes': () => showSection('changes'),
611
+ 'review-show-scenarios': () => showSection('scenarios'),
633
612
  '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()),
634
613
  'proposal-focus': (el) => focusChange(el.dataset.kind, el.dataset.key),
635
614
  };
@@ -670,51 +649,6 @@ function openSpecs() {
670
649
  function onKey(e) {
671
650
  if (e.key === 'Escape' && menuOpen()) closeMenu();
672
651
  onMoreKey(e);
673
- // Escape inside the list of changes folds it back onto its chip
674
- const list = $('proposal-changes');
675
- if (e.key === 'Escape' && !e.defaultPrevented && list && !list.hidden && list.contains(document.activeElement)) { e.preventDefault(); toggleChanges(true); }
676
- if (e.key === 'Tab' && !e.defaultPrevented && !e.ctrlKey && !e.metaKey && !e.altKey) tabThroughList(e);
677
- }
678
-
679
- /** The lists the toolbar opens, each after the button that opens it: the changes (the counts) and the scenarios (Play) */
680
- const OPENERS = [['proposal-chip', 'proposal-changes'], ['proposal-play', 'proposal-scenarios']];
681
- const TABBABLE = 'button, a[href], input, select, textarea, summary, [tabindex]';
682
- const canTab = (el) => el.tabIndex >= 0 && !el.disabled && !el.closest('[hidden]') && (typeof el.checkVisibility !== 'function' || el.checkVisibility());
683
- const tabbables = (root) => [...root.querySelectorAll(TABBABLE)].filter(canTab);
684
-
685
- /**
686
- * 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
687
- * 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
688
- * 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.
689
- */
690
- function tabThroughList(e) {
691
- const bar = $('proposal-bar');
692
- if (!bar || bar.hidden) return;
693
- const open = OPENERS.map(([b, l]) => [$(b), $(l)]).filter(([btn, list]) => btn && list && !list.hidden && bar.contains(list) && canTab(btn));
694
- if (!open.length) return;
695
- const all = tabbables(bar);
696
- let order = all.filter((el) => !open.some(([, list]) => list.contains(el)));
697
- for (const [btn, list] of open) {
698
- const at = order.indexOf(btn);
699
- if (at >= 0) order = [...order.slice(0, at + 1), ...all.filter((el) => list.contains(el)), ...order.slice(at + 1)];
700
- }
701
- const active = document.activeElement;
702
- let to = null;
703
- if (active && bar.contains(active)) {
704
- const i = order.indexOf(active);
705
- if (i < 0) return;
706
- const next = order[i + (e.shiftKey ? -1 : 1)];
707
- const natural = all[all.indexOf(active) + (e.shiftKey ? -1 : 1)];
708
- if (next === natural) return;
709
- if (next) to = next;
710
- 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
711
- } else if (e.shiftKey && active) {
712
- // Coming back into the bar from after it: its last control in this order, not the last row of a list
713
- const page = tabbables(document);
714
- const prev = page[page.indexOf(active) - 1];
715
- if (prev && bar.contains(prev) && prev !== order[order.length - 1]) to = order[order.length - 1];
716
- }
717
- if (to) { e.preventDefault(); to.focus(); }
718
652
  }
719
653
 
720
654
  /** The marks' colours for the legend and the panel (the --hx-mark-* variables), the same the map draws on this ground */
@@ -753,7 +687,7 @@ export async function initProposals() {
753
687
  return false;
754
688
  }
755
689
  const ok = await openProposal(asked.slug, asked.source);
756
- if (ok && asked.view) { setProposalView(asked.view, { quiet: true }); announce(openedWords($('proposal-title').textContent, summarize(state.proposal), state.proposalView)); }
690
+ if (ok && asked.view) { setProposalView(asked.view, { quiet: true }); announce(`${reviewOpenedLine($('proposal-title').textContent)} ${viewWords(state.proposalView)}.`); }
757
691
  return ok;
758
692
  }
759
693
 
@@ -0,0 +1,430 @@
1
+ /**
2
+ * @module explorer/review-column
3
+ *
4
+ * The review column (spec 0006 D1, D2, D4, D5): while a proposal is open, one panel that holds what the proposal changes and, persona
5
+ * by persona, the scenarios that apply to them, so neither is behind a button. From 768px it is docked on the left of the map,
6
+ * below the proposal bar (400px wide, 320px under 1024), the two lists one under the other; on a phone it is the expanded proposal
7
+ * sheet's body, with a two-part switch at its top (Changes | Scenarios). Its foot, `#review-decision`, is the decision: Send back and
8
+ * Approve (review.js) and, in spec 0007, the line that says what Approve does. Nothing about the decision is decided here.
9
+ *
10
+ * Changes · 6 one row for each marked node and edge: a button that selects it and frames it (proposal.js `proposal-focus`)
11
+ * Personas and scenarios · 3 an h4 for each persona, then its scenarios; a scenario is a disclosure
12
+ * Adult · 1 scenario
13
+ * ▾ An adult pays for the basket its steps as a numbered list: who acts, the node, its mark, the text, the verdict
14
+ * Not in any scenario: Child the personas on the map that act in no scenario of this proposal
15
+ *
16
+ * Choosing a step opens the player (scenario-ui.js) paused on it, and the camera goes to the step's node in the part of the map the
17
+ * column leaves free (sheets.js `visibleMapRect`). The list follows the player: its current step is `aria-current="step"`.
18
+ * Focus never falls to the page: a repaint puts it back on the same control, and closing the player gives it to the step it was on.
19
+ *
20
+ * The lists are drawn from `scenario-list-model.js` (pure, tested in Node). Every word a project's files supplied (persona labels,
21
+ * scenario titles, step text) is escaped on the way in; an id that reaches an element id or a `data-*` value is made safe first.
22
+ * What was seen (a tick per scenario) is kept in the browser's storage, per proposal and PR head: information only, never in the review.
23
+ */
24
+
25
+ import { state, escHtml } from './state.js';
26
+ import { t } from './strings.js';
27
+ import { markStateAttr } from './corn-state.js';
28
+ import { isPhone, expandSheet, PHONE_QUERY } from './sheets.js';
29
+ import { pullNumberOf } from './proposal-model.js';
30
+ import { closeDrawer } from './panels.js';
31
+ import { onLayersChange } from './layers.js';
32
+ import { playScenario, getPlayer, onPlayerChange, setCloseFocus, setNextScenario, setKeepChecksOnClose, layersHiding } from './scenario-ui.js';
33
+ import { openChecks, closeChecks, scenarioVerdicts, checkedScenarioId } from './check.js';
34
+ import { buildScenarioList, changeRows, stepSentence, reviewCounts, reviewOpenedWords, seenKey, readSeen, writeSeen } from './scenario-list-model.js';
35
+
36
+ const $ = (id) => document.getElementById(id);
37
+ const TAB_KEY = 'cornfield.reviewTab';
38
+ /** The narrowest map area that holds the column (400px), the player bar and the node panel (480px) side by side */
39
+ const PLAYER_BESIDE_PANEL = 1360;
40
+
41
+ /** What the column shows apart from the proposal: the scenario whose steps are open, the phone's tab, the PR head the record is keyed by */
42
+ const ui = { checks: 0, open: null, tab: null, tabNow: null, tabFor: '', openFor: '', head: '', headFor: '', current: null, lastStep: null, seen: { played: [], read: [] }, seenFor: '', pending: [] };
43
+ let wiredRoot = null;
44
+
45
+ const asList = (v) => (Array.isArray(v) ? v : []);
46
+ const storage = () => { try { return window.localStorage; } catch { return null; } };
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // What is shown, from the open proposal
50
+ // ---------------------------------------------------------------------------
51
+
52
+ /** The open proposal's scenarios, with the maintainer's what-if edits in */
53
+ const scenariosNow = () => {
54
+ const p = state.effectiveProposal || state.proposal;
55
+ return p && Array.isArray(p.scenarios) ? p.scenarios : [];
56
+ };
57
+
58
+ /** The open proposal, as the record and the phone's tab know it: its source and its name */
59
+ const proposalKey = () => `${state.proposalSource || ''}/${state.proposalSlug || ''}`;
60
+
61
+ /**
62
+ * The browser key the open proposal's record is kept under, or null while it cannot be known: a PR's copy is kept per PR head,
63
+ * and until the PR has been read its head is not known (what is seen meanwhile is held in memory, then kept under the head)
64
+ */
65
+ function recordKey() {
66
+ if (pullNumberOf(state.proposalSource)) return ui.headFor === proposalKey() && ui.head ? seenKey(state.proposalSource, state.proposalSlug, ui.head) : null;
67
+ return seenKey(state.proposalSource, state.proposalSlug, '');
68
+ }
69
+
70
+ /** The record of what this browser saw, read again when the proposal (or its PR head) is another */
71
+ function refreshSeen() {
72
+ const key = recordKey();
73
+ const id = key || `pending:${proposalKey()}`;
74
+ if (ui.seenFor === id) return;
75
+ const was = ui.seenFor;
76
+ ui.seenFor = id;
77
+ if (!key) { ui.seen = { played: [], read: [] }; ui.pending = []; return; }
78
+ ui.seen = readSeen(storage(), key);
79
+ // what was seen of this proposal before its PR head was known is kept under the head now
80
+ if (was === `pending:${proposalKey()}`) for (const [scenario, how] of ui.pending) ui.seen = writeSeen(storage(), key, scenario, how);
81
+ ui.pending = [];
82
+ }
83
+
84
+ /** Adds a scenario to the record: kept in the browser once the key is known, held in memory until then */
85
+ function markSeen(scenarioId, how) {
86
+ refreshSeen();
87
+ if (ui.seenFor.startsWith('pending:')) {
88
+ ui.pending.push([String(scenarioId), how]);
89
+ ui.seen = writeSeen(null, '', scenarioId, how, ui.seen);
90
+ } else ui.seen = writeSeen(storage(), ui.seenFor, scenarioId, how);
91
+ }
92
+
93
+ /** The PR head the record is keyed by: proposal.js hands it over when it has read the open proposal's PR */
94
+ export function setPullHead(sha) {
95
+ const head = typeof sha === 'string' ? sha : '';
96
+ if (head === ui.head && ui.headFor === proposalKey()) return;
97
+ ui.head = head;
98
+ ui.headFor = proposalKey();
99
+ if (state.proposal) repaint();
100
+ }
101
+
102
+ function model() {
103
+ refreshSeen();
104
+ const verdicts = new Map();
105
+ const id = checkedScenarioId();
106
+ if (id !== null) verdicts.set(id, scenarioVerdicts());
107
+ const proposal = state.effectiveProposal || state.proposal;
108
+ const words = { notChecked: t('notChecked') };
109
+ const byId = new Map(state.nodes.map((n) => [n.id, n]));
110
+ const hidden = (id) => byId.has(id) && layersHiding(byId.get(id)).length > 0;
111
+ return buildScenarioList({ scenarios: scenariosNow(), nodes: state.nodes, edges: state.edges, proposal, verdicts, seen: ui.seen, words, hidden });
112
+ }
113
+
114
+ /** What opening a proposal says: "Opened Checkout: 6 changes, 3 scenarios for 2 personas." */
115
+ export function reviewOpenedLine(title) {
116
+ const proposal = state.effectiveProposal || state.proposal;
117
+ return reviewOpenedWords(title, changeRows(state.nodes, state.edges, proposal).length, model());
118
+ }
119
+
120
+ /** The phone's peek line: "6 changes · 3 scenarios for 2 personas" */
121
+ export function reviewPeekLine() {
122
+ const proposal = state.effectiveProposal || state.proposal;
123
+ return reviewCounts(changeRows(state.nodes, state.edges, proposal).length, model());
124
+ }
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // Markup
128
+ // ---------------------------------------------------------------------------
129
+
130
+ /** "Changes · 6": a dot for the eye and a comma for a screen reader, so the heading reads "Changes, 6" */
131
+ const countHeading = (label, n) => `${escHtml(label)}<span aria-hidden="true"> · </span><span class="hx-sr-only">, </span><span data-corn="count">${n}</span>`;
132
+
133
+ function changeRowHtml(r) {
134
+ const label = `${r.word} ${r.name}, ${r.type}`;
135
+ return `<li><button type="button" class="hx-change-row" data-action="proposal-focus" data-kind="${r.kind}" data-key="${escHtml(r.key)}" data-focus-key="ch:${escHtml(r.kind)}:${escHtml(r.key)}" data-corn="row" aria-label="${escHtml(label)}"><span class="hx-mark-dot hx-mark-dot--${r.mark}" data-corn="mark-dot"${markStateAttr(r.mark)} aria-hidden="true"></span><span class="hx-change-what">${escHtml(r.word)}</span><span class="hx-name">${escHtml(r.name)}</span><span class="hx-faint">${escHtml(r.type)}</span></button></li>`;
136
+ }
137
+
138
+ function stepHtml(sc, step, group, total) {
139
+ const current = ui.current && ui.current.index === sc.index && ui.current.step === step.index && ui.current.id === sc.id;
140
+ const pill = step.verdict ? `<span class="hx-step-verdict" data-corn="state-pill" data-tone="${escHtml(step.verdict.tone)}"${step.verdict.state ? ` data-corn-state="${step.verdict.state}"` : ''}>${escHtml(step.verdict.words)}</span>` : '';
141
+ const mark = step.mark ? `<span class="hx-step-mark"><span class="hx-mark-dot hx-mark-dot--${step.mark}" data-corn="mark-dot"${markStateAttr(step.mark)} aria-hidden="true"></span>${escHtml(step.markWord)}</span>` : '';
142
+ const who = step.actorLabel ? `<span class="hx-step-who">As ${escHtml(step.actorLabel)}</span>` : '';
143
+ return `<li><button type="button" class="hx-step" data-corn="step" data-action="scenario-step" data-scenario-index="${sc.index}" data-step-index="${step.index}" data-focus-key="st:${group.key}:${sc.key}:${step.index}" aria-label="${escHtml(stepSentence(step, total))}"${current ? ' aria-current="step"' : ''}>`
144
+ + `<span class="hx-step-n" aria-hidden="true">${step.number}</span><span class="hx-step-body"><span class="hx-step-line">${who}<span class="hx-step-where">${escHtml(step.where)}</span>${mark}${step.layerOff ? '<span class="hx-step-off">Layer off: shown when played</span>' : ''}</span>`
145
+ + `<span class="hx-step-text">${escHtml(step.text)}</span></span>${pill}</button></li>`;
146
+ }
147
+
148
+ function scenarioHtml(sc, group) {
149
+ const open = ui.open === sc.id;
150
+ const stepsId = `rc-steps-${group.key}-${sc.key}`;
151
+ const tick = sc.seen ? `<span class="hx-sc-seen" data-seen="${sc.seen}">${sc.seen === 'played' ? '✓ Played' : '✓ Read'}</span>` : '';
152
+ const done = sc.verdictSummary ? ` · ${escHtml(sc.verdictSummary)}` : '';
153
+ // its checks are asked when it is opened, but while another scenario plays the checks are that one's: say so rather than show steps with no verdict
154
+ const waits = open && playingOther(sc.id) && sc.steps.some((st) => st.actor) ? `<p class="hx-faint hx-rc-note hx-sc-waits" data-corn="notice">Not checked while another scenario plays. Close the player, or choose a step here to play this one.</p>` : '';
155
+ return `<li class="hx-sc" data-open="${open}"><button type="button" class="hx-sc-row" data-corn="row" data-action="scenario-open" data-scenario-index="${sc.index}" data-focus-key="sc:${group.key}:${sc.key}" aria-expanded="${open}" aria-controls="${stepsId}">`
156
+ + `<span class="hx-sc-caret" aria-hidden="true">${open ? '▾' : '▸'}</span><span class="hx-sc-main"><span class="hx-sc-title">${escHtml(sc.title)}</span><span class="hx-sc-meta">${escHtml(sc.summary)}${done}</span></span>${tick}</button>${waits}`
157
+ + `<ol class="hx-steps" id="${stepsId}" data-corn="step-list" aria-label="${escHtml(t('steps'))}: ${escHtml(sc.title)}"${open ? '' : ' hidden'}>${open ? sc.steps.map((s) => stepHtml(sc, s, group, sc.steps.length)).join('') : ''}</ol></li>`;
158
+ }
159
+
160
+ function groupHtml(g) {
161
+ const n = g.scenarios.length;
162
+ const name = g.anyone ? t('anyone') : g.label;
163
+ const heading = `${escHtml(name)}<span aria-hidden="true"> · </span><span class="hx-sr-only">, </span>${n} ${n === 1 ? 'scenario' : 'scenarios'}`;
164
+ return `<div class="hx-persona" data-corn="persona-group" data-persona="${escHtml(g.key)}"><h4 class="hx-persona-name">${heading}</h4><ul class="hx-sc-list">${g.scenarios.map((sc) => scenarioHtml(sc, g)).join('')}</ul></div>`;
165
+ }
166
+
167
+ /** Everything the two lists say, as markup (the foot is static in index.html) */
168
+ function listsHtml() {
169
+ const proposal = state.effectiveProposal || state.proposal;
170
+ const rows = changeRows(state.nodes, state.edges, proposal);
171
+ const list = model();
172
+ const phone = isPhone();
173
+ // the phone's tab: the reviewer's last choice, or Scenarios when there are any; a proposal with none opens on its changes
174
+ if (ui.tabFor !== proposalKey()) { ui.tabFor = proposalKey(); ui.tabNow = list.total ? (ui.tab || 'scenarios') : 'changes'; }
175
+ const tab = ui.tabNow || 'changes';
176
+ const personas = state.nodes.some((n) => n.type === 'persona');
177
+
178
+ const tabs = `<div class="hx-rc-tabs" role="tablist" aria-label="Review" data-corn="tabs"${phone ? '' : ' hidden'}>`
179
+ + `<button type="button" role="tab" id="rc-tab-changes" class="hx-rc-tab" data-corn="tab" data-action="review-tab" data-tab="changes" aria-selected="${tab === 'changes'}" aria-controls="rc-changes" tabindex="${tab === 'changes' ? 0 : -1}">${escHtml(t('changes'))} · ${rows.length}</button>`
180
+ + `<button type="button" role="tab" id="rc-tab-scenarios" class="hx-rc-tab" data-corn="tab" data-action="review-tab" data-tab="scenarios" aria-selected="${tab === 'scenarios'}" aria-controls="rc-scenarios" tabindex="${tab === 'scenarios' ? 0 : -1}">${escHtml(t('scenarios'))} · ${list.total}</button></div>`;
181
+
182
+ const changes = `<section id="rc-changes" class="hx-rc-section" data-corn="proposal-changes"${phone ? ` role="tabpanel" aria-labelledby="rc-tab-changes"${tab === 'changes' ? '' : ' hidden'}` : ' aria-labelledby="rc-changes-h"'}>`
183
+ + `<h3 id="rc-changes-h" class="hx-rc-h" tabindex="-1">${countHeading(t('changes'), rows.length)}</h3>`
184
+ + (rows.length ? `<ul class="hx-change-list">${rows.map(changeRowHtml).join('')}</ul>` : '<p class="hx-faint hx-rc-empty">This proposal changes nothing on the map.</p>')
185
+ + '</section>';
186
+
187
+ let body;
188
+ if (!list.total) body = '<p class="hx-faint hx-rc-empty">This proposal has no scenarios: there is nothing to walk through, and its changes are all it shows.</p>';
189
+ else {
190
+ body = list.groups.map(groupHtml).join('');
191
+ if (!personas) body += `<p class="hx-faint hx-rc-note">This map has no personas (topology.personas.json), so every scenario is listed under ${escHtml(t('anyone'))}.</p>`;
192
+ if (list.coverage) body += `<p class="hx-rc-coverage" data-corn="notice">${escHtml(t('notInAnyScenario'))}: ${list.notInAny.map(escHtml).join(', ')}</p>`;
193
+ if (list.playedLine) body += `<p class="hx-faint hx-rc-note" data-corn="notice">${escHtml(list.playedLine)}</p>`;
194
+ }
195
+ const scenarios = `<section id="rc-scenarios" class="hx-rc-section" data-corn="scenario-list"${phone ? ` role="tabpanel" aria-labelledby="rc-tab-scenarios"${tab === 'scenarios' ? '' : ' hidden'}` : ' aria-labelledby="rc-scenarios-h"'}>`
196
+ + `<h3 id="rc-scenarios-h" class="hx-rc-h" tabindex="-1">${countHeading(t('personasAndScenarios'), list.total)}</h3><div class="hx-rc-sbody">${body}</div></section>`;
197
+ return `${tabs}${changes}${scenarios}`;
198
+ }
199
+
200
+ // ---------------------------------------------------------------------------
201
+ // Painting: focus and scroll survive it
202
+ // ---------------------------------------------------------------------------
203
+
204
+ /** Where the column goes: after the proposal bar in the dock from 768px, at the end of the sheet's body on a phone */
205
+ function mountColumn() {
206
+ const col = $('review-column');
207
+ if (!col) return null;
208
+ const dock = $('sheet-dock');
209
+ const body = $('proposal-body');
210
+ if (isPhone() && body) { if (col.parentElement !== body) body.appendChild(col); } else if (dock) {
211
+ const bar = $('proposal-bar');
212
+ if (bar && col.parentElement !== dock) bar.after(col);
213
+ }
214
+ return col;
215
+ }
216
+
217
+ /** The column starts under the bar, whatever height the bar has (the counts wrap, the edit controls open): from 768px; a phone's has no place of its own */
218
+ function placeColumn() {
219
+ const col = $('review-column');
220
+ const bar = $('proposal-bar');
221
+ if (!col || !bar || isPhone() || bar.hidden) return;
222
+ col.style.setProperty('--hx-column-top', `${Math.round(bar.offsetTop + bar.offsetHeight + 8)}px`);
223
+ }
224
+
225
+ /** Draws the column for the open proposal, or hides it when none is open */
226
+ export function renderReviewColumn() {
227
+ const col = mountColumn();
228
+ if (!col) return;
229
+ const open = !!state.proposal;
230
+ col.hidden = !open;
231
+ if (!open) { ui.open = null; ui.current = null; ui.lastStep = null; closeChecksIfIdle(); const lists = $('review-lists'); if (lists) lists.innerHTML = ''; return; }
232
+ wire(col);
233
+ repaint();
234
+ placeColumn();
235
+ }
236
+
237
+ /**
238
+ * From 768px both lists share the column's height. The changes take what they need, up to 40% while the scenarios need the rest;
239
+ * when the scenarios are few, the changes take the room they leave (no gap under a short list while the changes scroll). Measured,
240
+ * because the split depends on how tall the scenario list is: the result is two CSS variables on the column.
241
+ */
242
+ export function shareRoom() {
243
+ const col = $('review-column');
244
+ const lists = $('review-lists');
245
+ const sc = $('rc-scenarios');
246
+ if (!col || !lists || !sc || col.hidden || isPhone()) return;
247
+ const h = lists.clientHeight;
248
+ if (!h) return;
249
+ const gap = parseFloat(getComputedStyle(lists).rowGap) || 0;
250
+ const head = sc.querySelector('.hx-rc-h');
251
+ const body = sc.querySelector('.hx-rc-sbody');
252
+ const need = Math.ceil((head ? head.offsetHeight + (parseFloat(getComputedStyle(head).marginBottom) || 0) : 0) + (body ? body.scrollHeight : 0));
253
+ col.style.setProperty('--hx-scenarios-need', `${need}px`);
254
+ col.style.setProperty('--hx-changes-max', `${Math.floor(Math.max(0.4 * h, h - need - gap))}px`);
255
+ }
256
+
257
+ function repaint() {
258
+ const lists = $('review-lists');
259
+ const col = $('review-column');
260
+ if (!lists || !col || !state.proposal) return;
261
+ // another proposal: nothing of the last one's list is open (two proposals may name a scenario alike)
262
+ if (ui.openFor !== proposalKey()) { ui.openFor = proposalKey(); if (!getPlayer()) { ui.open = null; ui.current = null; ui.lastStep = null; } }
263
+ // a scenario that is no longer in the proposal (a what-if edit deleted it) is not open any more
264
+ if (ui.open !== null && !scenariosNow().some((s) => s.id === ui.open)) ui.open = null;
265
+ // an edit to the open scenario (what-if) plans its checks again: the verdicts are of the steps it has now
266
+ const openScenario = ui.open !== null && !getPlayer() ? scenariosNow().find((s) => s.id === ui.open) : null;
267
+ if (openScenario && checkedScenarioId() === openScenario.id) openChecks(openScenario, () => repaint());
268
+ const active = document.activeElement;
269
+ const key = active && lists.contains(active) && active.getAttribute ? active.getAttribute('data-focus-key') : null;
270
+ const scroll = lists.scrollTop;
271
+ lists.innerHTML = listsHtml();
272
+ lists.scrollTop = scroll;
273
+ const peek = $('proposal-peek');
274
+ if (peek) peek.textContent = reviewPeekLine();
275
+ if (key) {
276
+ const again = [...lists.querySelectorAll('[data-focus-key]')].find((el) => el.getAttribute('data-focus-key') === key);
277
+ if (again) again.focus();
278
+ }
279
+ shareRoom();
280
+ }
281
+
282
+ // ---------------------------------------------------------------------------
283
+ // Doing things
284
+ // ---------------------------------------------------------------------------
285
+
286
+ const scenarioAt = (el) => scenariosNow()[Number(el.dataset.scenarioIndex)] || null;
287
+
288
+ /** Whether a player plays a scenario other than the one a disclosure would check (the checks are the player's then) */
289
+ const playingOther = (id) => { const p = getPlayer(); return !!p && p.scenario().id !== id; };
290
+
291
+ function closeChecksIfIdle() { if (!getPlayer()) closeChecks(); }
292
+
293
+ /** A scenario's disclosure: opens its steps (asking its checks, once, as one batch) or folds them; one is open at a time */
294
+ function toggleScenario(sc) {
295
+ if (ui.open === sc.id) {
296
+ ui.open = null;
297
+ if (!getPlayer()) closeChecks();
298
+ } else {
299
+ ui.open = sc.id;
300
+ markSeen(sc.id, 'read');
301
+ if (!playingOther(sc.id)) openChecks(sc, () => repaint());
302
+ }
303
+ repaint();
304
+ }
305
+
306
+ /** A step was chosen: the player opens paused on it, the list stays open and the focus stays on the step (on a phone the sheet folds, so the player takes it) */
307
+ function chooseStep(sc, index) {
308
+ ui.open = sc.id;
309
+ // Under 1360px the column, the node panel and the player bar do not fit side by side: the node panel closes, the player takes its room
310
+ const drawer = $('spec-drawer');
311
+ const stage = state.canvas && state.canvas.parentElement;
312
+ if (!isPhone() && drawer && drawer.classList.contains('drawer-open') && stage && stage.clientWidth < PLAYER_BESIDE_PANEL) closeDrawer();
313
+ playScenario(sc, { autoplay: false, step: index, focus: isPhone() });
314
+ repaint();
315
+ }
316
+
317
+ function showTab(tab, { focus = false } = {}) {
318
+ ui.tab = tab;
319
+ ui.tabNow = tab;
320
+ ui.tabFor = proposalKey();
321
+ try { storage()?.setItem(TAB_KEY, tab); } catch { /* the choice is a convenience */ }
322
+ repaint();
323
+ if (focus) $(`rc-tab-${tab}`)?.focus();
324
+ }
325
+
326
+ /** The counts' parts open their section: the switch moves to it on a phone; from 768px it scrolls into view and takes the focus */
327
+ export function showSection(which) {
328
+ if (!state.proposal) return;
329
+ if (isPhone()) { showTab(which); expandSheet('proposal'); }
330
+ const section = $(which === 'scenarios' ? 'rc-scenarios' : 'rc-changes');
331
+ const heading = $(which === 'scenarios' ? 'rc-scenarios-h' : 'rc-changes-h');
332
+ if (section && typeof section.scrollIntoView === 'function') section.scrollIntoView({ block: 'start' });
333
+ if (heading) heading.focus();
334
+ }
335
+
336
+ function onClick(e) {
337
+ const el = e.target.closest ? e.target.closest('[data-action]') : null;
338
+ if (!el) return;
339
+ const action = el.dataset.action;
340
+ if (action === 'scenario-open') { const sc = scenarioAt(el); if (sc) toggleScenario(sc); } else if (action === 'scenario-step') { const sc = scenarioAt(el); if (sc) chooseStep(sc, Number(el.dataset.stepIndex)); } else if (action === 'review-tab') showTab(el.dataset.tab, { focus: false });
341
+ }
342
+
343
+ /** Arrow keys move between the phone's two tabs */
344
+ function onKey(e) {
345
+ const tab = e.target.closest ? e.target.closest('[role="tab"]') : null;
346
+ if (!tab || !['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) return;
347
+ e.preventDefault();
348
+ showTab(tab.dataset.tab === 'changes' ? 'scenarios' : 'changes', { focus: true });
349
+ }
350
+
351
+ // ---------------------------------------------------------------------------
352
+ // The player and the list follow each other
353
+ // ---------------------------------------------------------------------------
354
+
355
+ /** Called with each change of the player: the step it is on (null when closed), whether it reached the end */
356
+ function onPlayer(snap) {
357
+ if (!snap) {
358
+ // closed: the list keeps the scenario open, without a current step, and its steps keep their verdicts (the checks are the list's again)
359
+ const sc = ui.open !== null && state.proposal && ui.openFor === proposalKey() ? scenariosNow().find((s) => s.id === ui.open) : null;
360
+ if (sc) openChecks(sc, () => repaint());
361
+ if (ui.current || sc) { ui.current = null; repaint(); }
362
+ return;
363
+ }
364
+ const scenarios = scenariosNow();
365
+ const index = scenarios.findIndex((s) => s.id === snap.id);
366
+ const next = { id: snap.id, index, step: Math.min(snap.index, Math.max(snap.total - 1, 0)) };
367
+ ui.lastStep = next;
368
+ if (snap.done) {
369
+ refreshSeen();
370
+ if (!ui.seen.played.includes(snap.id)) markSeen(snap.id, 'played');
371
+ }
372
+ const same = ui.current && ui.current.id === next.id && ui.current.step === next.step;
373
+ ui.current = next;
374
+ if (ui.open !== snap.id) ui.open = snap.id; // playing a scenario opens its list
375
+ if (!same || snap.done || snap.checks !== ui.checks) { ui.checks = snap.checks; repaint(); }
376
+ }
377
+
378
+ /** The step button the player was on, to give the focus back when it closes (a phone's sheet opens again first) */
379
+ function stepToFocus() {
380
+ const at = ui.lastStep;
381
+ if (!at) return null;
382
+ if (isPhone()) expandSheet('proposal');
383
+ const lists = $('review-lists');
384
+ return lists ? lists.querySelector(`[data-action="scenario-step"][data-scenario-index="${at.index}"][data-step-index="${at.step}"]`) : null;
385
+ }
386
+
387
+ /** The scenario after `id` in the order the list reads (the personas' order, each scenario once), or null at the end of the list */
388
+ function nextScenarioAfter(id) {
389
+ const order = [];
390
+ for (const g of model().groups) for (const sc of g.scenarios) if (!order.includes(sc.id)) order.push(sc.id);
391
+ const at = order.indexOf(id);
392
+ const next = at >= 0 ? order[at + 1] : undefined;
393
+ return next === undefined ? null : scenariosNow().find((s) => String(s.id) === next) || null;
394
+ }
395
+
396
+ function wire(col) {
397
+ if (wiredRoot === col) return;
398
+ wiredRoot = col;
399
+ col.addEventListener('click', onClick);
400
+ col.addEventListener('keydown', onKey);
401
+ }
402
+
403
+ let started = false;
404
+ /** Wires the column to the player and the viewport (main.js calls this once, after the page's markup is there) */
405
+ export function initReviewColumn() {
406
+ if (started) return;
407
+ started = true;
408
+ try { const saved = storage()?.getItem(TAB_KEY); if (saved === 'changes' || saved === 'scenarios') ui.tab = saved; } catch { /* no remembered tab */ }
409
+ onPlayerChange(onPlayer);
410
+ onLayersChange(() => { if (state.proposal) repaint(); }); // a step's "Layer off" follows the Layers menu
411
+ const bar = $('proposal-bar');
412
+ if (bar && typeof ResizeObserver === 'function') new ResizeObserver(() => { placeColumn(); }).observe(bar);
413
+ const col = $('review-column');
414
+ if (col && typeof ResizeObserver === 'function') new ResizeObserver(() => shareRoom()).observe(col); // the window's height changed
415
+ setCloseFocus(stepToFocus);
416
+ setNextScenario(nextScenarioAfter);
417
+ setKeepChecksOnClose((id) => ui.open === id && !!state.proposal);
418
+ if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
419
+ const mq = window.matchMedia(PHONE_QUERY);
420
+ if (mq && mq.addEventListener) mq.addEventListener('change', () => { if (state.proposal) renderReviewColumn(); });
421
+ }
422
+ renderReviewColumn();
423
+ }
424
+
425
+ /** For tests: forget what the column remembered */
426
+ export function resetReviewColumnForTests() {
427
+ Object.assign(ui, { checks: 0, open: null, tab: null, tabNow: null, tabFor: '', openFor: '', head: '', headFor: '', current: null, lastStep: null, seen: { played: [], read: [] }, seenFor: '', pending: [] });
428
+ wiredRoot = null;
429
+ started = false;
430
+ }