cornfield 0.48.0 → 0.49.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.
@@ -0,0 +1,502 @@
1
+ /**
2
+ * @module explorer/pieces/changes
3
+ *
4
+ * The review column as a piece (spec 0011 D3, D4: `corn-changes`), with the scenario player and its checks (spec 0006 D1, D2, D4, D5): while a proposal
5
+ * is open, one panel that holds what the proposal changes and, persona by persona, the scenarios that apply to them, so neither is behind a button. From
6
+ * 768px it is docked on the left of the map, below the proposal bar (400px wide, 320px under 1024), the two lists one under the other; on a phone it is
7
+ * the expanded proposal sheet's body, with a two-part switch at its top (Changes | Scenarios). The decision (pieces/decision.js) is its foot, where the
8
+ * host puts it: the markup keeps a place for it (`<!--corn-piece:decision/foot-->`).
9
+ *
10
+ * Changes · 6 one row for each marked node and edge: a button that selects it and frames it
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 (engine/player.js) paused on it, and the camera goes to the step's node in the part of the map the column leaves free
17
+ * (engine/sheets.js `visibleMapRect`). The list follows the player: its current step is `aria-current="step"`. Focus never falls to the page: a repaint puts
18
+ * 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, scenario titles, step
21
+ * text) is escaped on the way in; an id that reaches an element id or a `data-*` value is made safe first. What was seen (a tick per scenario) is kept in the
22
+ * browser's storage, per proposal and PR head: information only, never in the review.
23
+ *
24
+ * mount(root, inst, options) -> { update, destroy, ... }
25
+ *
26
+ * What it tells: `changes:peek` (the phone's peek line: "6 changes · 3 scenarios for 2 personas", for the proposal's bar to show). What it follows: `proposal:draw` (the column draws), `proposal:pull-head` (the PR head the record is keyed by), `changes:show` ('changes' | 'scenarios'),
27
+ * `layers` (a step's "Layer off"), `scenario:clear`. What it answers: `changes:opened-line` (title -> "Opened X: 6 changes, 3 scenarios for 2 personas."),
28
+ * `changes:played-line` (-> "2 of 3 scenarios played"). What it says: `changes:paint` (the lists were drawn again: the decision line follows what was
29
+ * played) and `scenario:player` (engine/player.js).
30
+ *
31
+ * @param {ParentNode} root where the column goes when `options.slots` names no place
32
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst the instance; its map must be made (engine/render.js)
33
+ * @param {{ slots?: { column?: Node }, checker?: object | null }} [options] `checker`: a plugin's checker for the scenarios' permission checks (none: "Not checked")
34
+ * @returns {{ update: (props?: { checker?: object | null }) => void, destroy: () => void, playScenario: Function, stopScenario: Function, getPlayer: Function, elements: Element[] }}
35
+ * `update({ checker })` hands over the checker; `update()` draws the lists again.
36
+ */
37
+
38
+ import { escapeHtml as escHtml } from '../../core/text.js';
39
+ import { t } from '../engine/strings.js';
40
+ import { markStateAttr } from '../corn-state.js';
41
+ import { isPhone, expandSheet, PHONE_QUERY, visibleMapRect } from '../engine/sheets.js';
42
+ import { pullNumberOf } from '../proposal-model.js';
43
+ import { clearSelection } from '../engine/selection.js';
44
+ import { onLayersChange } from '../engine/layers.js';
45
+ import { createChecks } from '../engine/checks.js';
46
+ import { createScenarioPlayer, layersHiding } from '../engine/player.js';
47
+ import { buildScenarioList, changeRows, stepSentence, reviewCounts, reviewOpenedWords, seenKey, readSeen, writeSeen } from '../scenario-list-model.js';
48
+ import { focusChange } from '../engine/proposal.js';
49
+ import { scopeOf, place, addParts } from '../engine/piece.js';
50
+
51
+ const TAB_KEY = 'cornfield.reviewTab';
52
+ /** The narrowest map area that holds the column (400px), the player bar and the node panel (480px) side by side */
53
+ const PLAYER_BESIDE_PANEL = 1360;
54
+
55
+ const asList = (v) => (Array.isArray(v) ? v : []);
56
+
57
+ /** The markup of the piece: the column. `column` is its one place; it keeps a place of its own for the decision's foot */
58
+ export const markup = () => ({
59
+ column: '<aside id="review-column" class="hx-review-column glass" aria-label="Review" data-corn="review-column" hidden>'
60
+ + '<div class="hx-rc-scroll">'
61
+ + '<p id="proposal-summary" class="hx-proposal-summary" hidden></p>'
62
+ + '<div id="review-lists" class="hx-rc-lists"></div>'
63
+ + '</div>'
64
+ + '<!--corn-piece:decision/foot-->'
65
+ + '</aside>',
66
+ });
67
+
68
+ /** "Changes · 6": a dot for the eye and a comma for a screen reader, so the heading reads "Changes, 6" */
69
+ const countHeading = (label, n) => `${escHtml(label)}<span aria-hidden="true"> · </span><span class="hx-sr-only">, </span><span data-corn="count">${n}</span>`;
70
+
71
+ function changeRowHtml(r) {
72
+ const label = `${r.word} ${r.name}, ${r.type}`;
73
+ 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>`;
74
+ }
75
+
76
+ /** Mounts the review column and the player; see the top of this file */
77
+ export function mount(root, inst, options = {}) {
78
+ const { state } = inst;
79
+ const scope = scopeOf(inst);
80
+ const made = place(inst, root, markup().column, options.slots, 'column');
81
+ /** An element of this piece by id */
82
+ const own = (id) => {
83
+ for (const el of made) {
84
+ if (el.id === id) return el;
85
+ const found = el.querySelector(`[id="${id}"]`);
86
+ if (found) return found;
87
+ }
88
+ return null;
89
+ };
90
+ scope.keepParts(...made);
91
+ const col = own('review-column');
92
+ let gone = false;
93
+
94
+ const checks = createChecks(inst, { checker: options.checker });
95
+ const player = createScenarioPlayer(inst, scope, checks);
96
+ scope.own(() => checks.close());
97
+
98
+ /** 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 */
99
+ const ui = { checks: 0, open: null, tab: null, tabNow: null, tabFor: '', openFor: '', head: '', headFor: '', current: null, lastStep: null, seen: { played: [], read: [] }, seenFor: '', pending: [] };
100
+ const storage = { getItem: (k) => inst.store.get(k), setItem: (k, v) => inst.store.set(k, v) };
101
+ const saved = inst.store.get(TAB_KEY);
102
+ if (saved === 'changes' || saved === 'scenarios') ui.tab = saved;
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // What is shown, from the open proposal
106
+ // ---------------------------------------------------------------------------
107
+ /** The open proposal's scenarios, with the maintainer's what-if edits in */
108
+ const scenariosNow = () => {
109
+ const p = state.effectiveProposal || state.proposal;
110
+ return p && Array.isArray(p.scenarios) ? p.scenarios : [];
111
+ };
112
+
113
+ /** The open proposal, as the record and the phone's tab know it: its source and its name */
114
+ const proposalKey = () => `${state.proposalSource || ''}/${state.proposalSlug || ''}`;
115
+
116
+ /**
117
+ * 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,
118
+ * 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)
119
+ */
120
+ function recordKey() {
121
+ if (pullNumberOf(state.proposalSource)) return ui.headFor === proposalKey() && ui.head ? seenKey(state.proposalSource, state.proposalSlug, ui.head) : null;
122
+ return seenKey(state.proposalSource, state.proposalSlug, '');
123
+ }
124
+
125
+ /** The record of what this browser saw, read again when the proposal (or its PR head) is another */
126
+ function refreshSeen() {
127
+ const key = recordKey();
128
+ const id = key || `pending:${proposalKey()}`;
129
+ if (ui.seenFor === id) return;
130
+ const was = ui.seenFor;
131
+ ui.seenFor = id;
132
+ if (!key) { ui.seen = { played: [], read: [] }; ui.pending = []; return; }
133
+ ui.seen = readSeen(storage, key);
134
+ // what was seen of this proposal before its PR head was known is kept under the head now
135
+ if (was === `pending:${proposalKey()}`) for (const [scenario, how] of ui.pending) ui.seen = writeSeen(storage, key, scenario, how);
136
+ ui.pending = [];
137
+ }
138
+
139
+ /** Adds a scenario to the record: kept in the browser once the key is known, held in memory until then */
140
+ function markSeen(scenarioId, how) {
141
+ refreshSeen();
142
+ if (ui.seenFor.startsWith('pending:')) {
143
+ ui.pending.push([String(scenarioId), how]);
144
+ ui.seen = writeSeen(null, '', scenarioId, how, ui.seen);
145
+ } else ui.seen = writeSeen(storage, ui.seenFor, scenarioId, how);
146
+ }
147
+
148
+ /** The PR head the record is keyed by: the bar hands it over when it has read the open proposal's PR */
149
+ function setPullHead(sha) {
150
+ const head = typeof sha === 'string' ? sha : '';
151
+ if (head === ui.head && ui.headFor === proposalKey()) return;
152
+ ui.head = head;
153
+ ui.headFor = proposalKey();
154
+ if (state.proposal) repaint();
155
+ }
156
+
157
+ function model() {
158
+ refreshSeen();
159
+ const verdicts = new Map();
160
+ const id = checks.checkedScenarioId();
161
+ if (id !== null) verdicts.set(id, checks.verdicts());
162
+ const proposal = state.effectiveProposal || state.proposal;
163
+ const words = { notChecked: t(inst, 'notChecked') };
164
+ const byId = new Map(state.nodes.map((n) => [n.id, n]));
165
+ const hidden = (nodeId) => byId.has(nodeId) && layersHiding(inst, byId.get(nodeId)).length > 0;
166
+ return buildScenarioList({ scenarios: scenariosNow(), nodes: state.nodes, edges: state.edges, proposal, verdicts, seen: ui.seen, words, hidden });
167
+ }
168
+
169
+ /** The proposal's own changes: the reviewer's what-if edits are a group of their own (spec 0007 D5), never counted into them */
170
+ const theirRows = (proposal) => changeRows(state.nodes, state.edges, proposal).filter((r) => r.mark !== 'edit');
171
+
172
+ /** What opening a proposal says: "Opened Checkout: 6 changes, 3 scenarios for 2 personas." */
173
+ function openedLine(title) {
174
+ const proposal = state.effectiveProposal || state.proposal;
175
+ return reviewOpenedWords(title, theirRows(proposal).length, model());
176
+ }
177
+
178
+ /** The phone's peek line: "6 changes · 3 scenarios for 2 personas" */
179
+ function peekLine() {
180
+ const proposal = state.effectiveProposal || state.proposal;
181
+ return reviewCounts(theirRows(proposal).length, model());
182
+ }
183
+
184
+ // ---------------------------------------------------------------------------
185
+ // Markup
186
+ // ---------------------------------------------------------------------------
187
+ function stepHtml(sc, step, group, total) {
188
+ const current = ui.current && ui.current.index === sc.index && ui.current.step === step.index && ui.current.id === sc.id;
189
+ 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>` : '';
190
+ 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>` : '';
191
+ const who = step.actorLabel ? `<span class="hx-step-who">As ${escHtml(step.actorLabel)}</span>` : '';
192
+ 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"' : ''}>`
193
+ + `<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>`
194
+ + `<span class="hx-step-text">${escHtml(step.text)}</span></span>${pill}</button></li>`;
195
+ }
196
+
197
+ function scenarioHtml(sc, group) {
198
+ const open = ui.open === sc.id;
199
+ const stepsId = `rc-steps-${group.key}-${sc.key}`;
200
+ const tick = sc.seen ? `<span class="hx-sc-seen" data-seen="${sc.seen}">${sc.seen === 'played' ? '✓ Played' : '✓ Read'}</span>` : '';
201
+ const done = sc.verdictSummary ? ` · ${escHtml(sc.verdictSummary)}` : '';
202
+ // 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
203
+ 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>' : '';
204
+ 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}">`
205
+ + `<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}`
206
+ + `<ol class="hx-steps" id="${stepsId}" data-corn="step-list" aria-label="${escHtml(t(inst, 'steps'))}: ${escHtml(sc.title)}"${open ? '' : ' hidden'}>${open ? sc.steps.map((s) => stepHtml(sc, s, group, sc.steps.length)).join('') : ''}</ol></li>`;
207
+ }
208
+
209
+ function groupHtml(g) {
210
+ const n = g.scenarios.length;
211
+ const name = g.anyone ? t(inst, 'anyone') : g.label;
212
+ const heading = `${escHtml(name)}<span aria-hidden="true"> · </span><span class="hx-sr-only">, </span>${n} ${n === 1 ? 'scenario' : 'scenarios'}`;
213
+ 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>`;
214
+ }
215
+
216
+ /** Everything the two lists say, as markup (the foot is the decision's) */
217
+ function listsHtml() {
218
+ const proposal = state.effectiveProposal || state.proposal;
219
+ const everyRow = changeRows(state.nodes, state.edges, proposal);
220
+ const rows = everyRow.filter((r) => r.mark !== 'edit');
221
+ const mine = everyRow.filter((r) => r.mark === 'edit'); // "Your edits · 1": the first group, not the last row
222
+ const list = model();
223
+ const phone = isPhone(inst);
224
+ // the phone's tab: the reviewer's last choice, or Scenarios when there are any; a proposal with none opens on its changes
225
+ if (ui.tabFor !== proposalKey()) { ui.tabFor = proposalKey(); ui.tabNow = list.total ? (ui.tab || 'scenarios') : 'changes'; }
226
+ const tab = ui.tabNow || 'changes';
227
+ const personas = state.nodes.some((n) => n.type === 'persona');
228
+
229
+ const tabs = `<div class="hx-rc-tabs" role="tablist" aria-label="Review" data-corn="tabs"${phone ? '' : ' hidden'}>`
230
+ + `<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(inst, 'changes'))} · ${rows.length}</button>`
231
+ + `<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(inst, 'scenarios'))} · ${list.total}</button></div>`;
232
+
233
+ 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"'}>`
234
+ + `<h3 id="rc-changes-h" class="hx-rc-h" tabindex="-1">${countHeading(t(inst, 'changes'), rows.length)}</h3>`
235
+ + (mine.length ? `<h4 class="hx-rc-sub">${countHeading(t(inst, 'yourEdits'), mine.length)}</h4><ul class="hx-change-list">${mine.map(changeRowHtml).join('')}</ul>` : '')
236
+ + (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>')
237
+ + '</section>';
238
+
239
+ let body;
240
+ 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>';
241
+ else {
242
+ body = list.groups.map(groupHtml).join('');
243
+ 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(inst, 'anyone'))}.</p>`;
244
+ if (list.coverage) body += `<p class="hx-rc-coverage" data-corn="notice">${escHtml(t(inst, 'notInAnyScenario'))}: ${list.notInAny.map(escHtml).join(', ')}</p>`;
245
+ }
246
+ 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"'}>`
247
+ + `<h3 id="rc-scenarios-h" class="hx-rc-h" tabindex="-1">${countHeading(t(inst, 'personasAndScenarios'), list.total)}</h3><div class="hx-rc-sbody">${body}</div></section>`;
248
+ return `${tabs}${changes}${scenarios}`;
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // Painting: focus and scroll survive it
253
+ // ---------------------------------------------------------------------------
254
+ /** Where the column goes: after the proposal bar in the dock from 768px, at the end of the sheet's body on a phone */
255
+ function mountColumn() {
256
+ const dock = inst.el('sheet-dock');
257
+ const body = inst.el('proposal-body');
258
+ if (isPhone(inst) && body) { if (col.parentElement !== body) body.appendChild(col); } else if (dock) {
259
+ const bar = inst.el('proposal-bar');
260
+ if (bar && col.parentElement !== dock) bar.after(col);
261
+ }
262
+ return col;
263
+ }
264
+
265
+ /** 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 */
266
+ function placeColumn() {
267
+ const bar = inst.el('proposal-bar');
268
+ if (!bar || isPhone(inst) || bar.hidden) return;
269
+ col.style.setProperty('--hx-column-top', `${Math.round(bar.offsetTop + bar.offsetHeight + 8)}px`);
270
+ }
271
+
272
+ /** Draws the column for the open proposal, or hides it when none is open */
273
+ function renderColumn() {
274
+ if (gone) return;
275
+ mountColumn();
276
+ const open = !!state.proposal;
277
+ col.hidden = !open;
278
+ if (!open) { ui.open = null; ui.current = null; ui.lastStep = null; closeChecksIfIdle(); const lists = own('review-lists'); if (lists) lists.innerHTML = ''; return; }
279
+ repaint();
280
+ placeColumn();
281
+ }
282
+
283
+ /**
284
+ * From 768px both lists share the column's height. The changes take what they need, up to 40% while the scenarios need the rest;
285
+ * when the scenarios are few, the changes take the room they leave (no gap under a short list while the changes scroll). Measured,
286
+ * because the split depends on how tall the scenario list is: the result is two CSS variables on the column.
287
+ */
288
+ function shareRoom() {
289
+ const lists = own('review-lists');
290
+ const sc = own('rc-scenarios');
291
+ if (!lists || !sc || col.hidden || isPhone(inst)) return;
292
+ const h = lists.clientHeight;
293
+ if (!h) return;
294
+ const gap = parseFloat(inst.win.getComputedStyle(lists).rowGap) || 0;
295
+ const head = sc.querySelector('.hx-rc-h');
296
+ const body = sc.querySelector('.hx-rc-sbody');
297
+ const need = Math.ceil((head ? head.offsetHeight + (parseFloat(inst.win.getComputedStyle(head).marginBottom) || 0) : 0) + (body ? body.scrollHeight : 0));
298
+ col.style.setProperty('--hx-scenarios-need', `${need}px`);
299
+ col.style.setProperty('--hx-changes-max', `${Math.floor(Math.max(0.4 * h, h - need - gap))}px`);
300
+ }
301
+
302
+ function repaint() {
303
+ const lists = own('review-lists');
304
+ if (gone || !lists || !state.proposal) return;
305
+ // another proposal: nothing of the last one's list is open (two proposals may name a scenario alike)
306
+ if (ui.openFor !== proposalKey()) { ui.openFor = proposalKey(); if (!player.getPlayer()) { ui.open = null; ui.current = null; ui.lastStep = null; } }
307
+ // a scenario that is no longer in the proposal (a what-if edit deleted it) is not open any more
308
+ if (ui.open !== null && !scenariosNow().some((s) => s.id === ui.open)) ui.open = null;
309
+ // an edit to the open scenario (what-if) plans its checks again: the verdicts are of the steps it has now
310
+ const openScenario = ui.open !== null && !player.getPlayer() ? scenariosNow().find((s) => s.id === ui.open) : null;
311
+ if (openScenario && checks.checkedScenarioId() === openScenario.id) checks.open(openScenario, () => repaint());
312
+ const active = inst.active();
313
+ const key = active && lists.contains(active) && active.getAttribute ? active.getAttribute('data-focus-key') : null;
314
+ const scroll = lists.scrollTop;
315
+ lists.innerHTML = listsHtml();
316
+ addParts(lists);
317
+ // the summary leads the column (the bar has it as the title's tooltip)
318
+ const p = state.proposal;
319
+ const summary = own('proposal-summary');
320
+ summary.textContent = (p && typeof p.summary === 'string' && p.summary) || '';
321
+ summary.hidden = !summary.textContent;
322
+ lists.scrollTop = scroll;
323
+ inst.emit('changes:peek', peekLine()); // the phone's one line under the counts, which the proposal's bar shows
324
+ if (key) {
325
+ const again = [...lists.querySelectorAll('[data-focus-key]')].find((el) => el.getAttribute('data-focus-key') === key);
326
+ if (again) again.focus();
327
+ }
328
+ shareRoom();
329
+ inst.emit('changes:paint');
330
+ }
331
+
332
+ // ---------------------------------------------------------------------------
333
+ // Doing things
334
+ // ---------------------------------------------------------------------------
335
+ const scenarioAt = (el) => scenariosNow()[Number(el.dataset.scenarioIndex)] || null;
336
+
337
+ /** Whether a player plays a scenario other than the one a disclosure would check (the checks are the player's then) */
338
+ const playingOther = (id) => { const p = player.getPlayer(); return !!p && p.scenario().id !== id; };
339
+
340
+ function closeChecksIfIdle() { if (!player.getPlayer()) checks.close(); }
341
+
342
+ /** A scenario's disclosure: opens its steps (asking its checks, once, as one batch) or folds them; one is open at a time */
343
+ function toggleScenario(sc) {
344
+ if (ui.open === sc.id) {
345
+ ui.open = null;
346
+ if (!player.getPlayer()) checks.close();
347
+ } else {
348
+ ui.open = sc.id;
349
+ markSeen(sc.id, 'read');
350
+ if (!playingOther(sc.id)) checks.open(sc, () => repaint());
351
+ }
352
+ repaint();
353
+ }
354
+
355
+ /** 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) */
356
+ function chooseStep(sc, index) {
357
+ ui.open = sc.id;
358
+ // 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
359
+ const drawer = inst.el('spec-drawer');
360
+ const stage = state.canvas && state.canvas.parentElement;
361
+ if (!isPhone(inst) && drawer && drawer.classList.contains('drawer-open') && stage && stage.clientWidth < PLAYER_BESIDE_PANEL) clearSelection(inst, { source: 'api' });
362
+ player.play(sc, { autoplay: false, step: index, focus: isPhone(inst) });
363
+ repaint();
364
+ }
365
+
366
+ function showTab(tab, { focus = false } = {}) {
367
+ ui.tab = tab;
368
+ ui.tabNow = tab;
369
+ ui.tabFor = proposalKey();
370
+ inst.store.set(TAB_KEY, tab);
371
+ repaint();
372
+ if (focus) own(`rc-tab-${tab}`)?.focus();
373
+ }
374
+
375
+ /** The counts' parts open their section: the switch moves to it on a phone; from 768px it scrolls into view and takes the focus */
376
+ function showSection(which) {
377
+ if (!state.proposal) return;
378
+ if (isPhone(inst)) { showTab(which); expandSheet(inst, 'proposal'); }
379
+ const section = own(which === 'scenarios' ? 'rc-scenarios' : 'rc-changes');
380
+ const heading = own(which === 'scenarios' ? 'rc-scenarios-h' : 'rc-changes-h');
381
+ if (section && typeof section.scrollIntoView === 'function') section.scrollIntoView({ block: 'start' });
382
+ if (heading) heading.focus();
383
+ }
384
+
385
+ scope.listen(col, 'click', (e) => {
386
+ const el = e.target.closest ? e.target.closest('[data-action]') : null;
387
+ if (!el) return;
388
+ const action = el.dataset.action;
389
+ 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 }); else if (action === 'proposal-focus') focusChange(inst, el.dataset.kind, el.dataset.key);
390
+ });
391
+ /** Arrow keys move between the phone's two tabs */
392
+ scope.listen(col, 'keydown', (e) => {
393
+ const tab = e.target.closest ? e.target.closest('[role="tab"]') : null;
394
+ if (!tab || !['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) return;
395
+ e.preventDefault();
396
+ showTab(tab.dataset.tab === 'changes' ? 'scenarios' : 'changes', { focus: true });
397
+ });
398
+
399
+ // ---------------------------------------------------------------------------
400
+ // The player and the list follow each other
401
+ // ---------------------------------------------------------------------------
402
+ /** Called with each change of the player: the step it is on (null when closed), whether it reached the end */
403
+ function onPlayer(snap) {
404
+ if (!snap) {
405
+ // closed: the list keeps the scenario open, without a current step, and its steps keep their verdicts (the checks are the list's again)
406
+ const sc = ui.open !== null && state.proposal && ui.openFor === proposalKey() ? scenariosNow().find((s) => s.id === ui.open) : null;
407
+ if (sc) checks.open(sc, () => repaint());
408
+ if (ui.current || sc) { ui.current = null; repaint(); }
409
+ return;
410
+ }
411
+ const scenarios = scenariosNow();
412
+ const index = scenarios.findIndex((s) => s.id === snap.id);
413
+ const next = { id: snap.id, index, step: Math.min(snap.index, Math.max(snap.total - 1, 0)) };
414
+ ui.lastStep = next;
415
+ if (snap.done) {
416
+ refreshSeen();
417
+ if (!ui.seen.played.includes(snap.id)) markSeen(snap.id, 'played');
418
+ }
419
+ const same = ui.current && ui.current.id === next.id && ui.current.step === next.step;
420
+ ui.current = next;
421
+ if (ui.open !== snap.id) ui.open = snap.id; // playing a scenario opens its list
422
+ if (!same || snap.done || snap.checks !== ui.checks) { ui.checks = snap.checks; repaint(); }
423
+ }
424
+
425
+ /** The step button the player was on, to give the focus back when it closes (a phone's sheet opens again first) */
426
+ function stepToFocus() {
427
+ const at = ui.lastStep;
428
+ if (!at) return null;
429
+ if (isPhone(inst)) expandSheet(inst, 'proposal');
430
+ const lists = own('review-lists');
431
+ return lists ? lists.querySelector(`[data-action="scenario-step"][data-scenario-index="${at.index}"][data-step-index="${at.step}"]`) : null;
432
+ }
433
+
434
+ /** The scenario after `id` in the order the list reads (the personas' order, each scenario once), or null at the end of the list */
435
+ function nextScenarioAfter(id) {
436
+ const order = [];
437
+ for (const g of model().groups) for (const sc of g.scenarios) if (!order.includes(sc.id)) order.push(sc.id);
438
+ const at = order.indexOf(id);
439
+ const next = at >= 0 ? order[at + 1] : undefined;
440
+ return next === undefined ? null : scenariosNow().find((s) => String(s.id) === next) || null;
441
+ }
442
+
443
+ scope.own(player.onChange(onPlayer));
444
+ player.setCloseFocus(stepToFocus);
445
+ player.setNextScenario(nextScenarioAfter);
446
+ player.setKeepChecksOnClose((id) => ui.open === id && !!state.proposal);
447
+ scope.own(onLayersChange(inst, () => { if (state.proposal) repaint(); })); // a step's "Layer off" follows the Layers menu
448
+
449
+ scope.on('proposal:draw', () => renderColumn());
450
+ scope.on('proposal:pull-head', (sha) => setPullHead(sha));
451
+ scope.on('changes:show', (which) => showSection(which));
452
+ const RO = inst.win && inst.win.ResizeObserver;
453
+ const watch = (el, fn) => { if (el && typeof RO === 'function') { const ro = new RO(fn); ro.observe(el); scope.own(() => ro.disconnect()); } };
454
+ watch(inst.el('proposal-bar'), () => placeColumn());
455
+ watch(col, () => shareRoom()); // the window's height changed
456
+ if (inst.win && typeof inst.win.matchMedia === 'function') {
457
+ const mq = inst.win.matchMedia(PHONE_QUERY);
458
+ if (mq && mq.addEventListener) {
459
+ const onPhone = () => { if (state.proposal) renderColumn(); };
460
+ mq.addEventListener('change', onPhone);
461
+ scope.own(() => mq.removeEventListener('change', onPhone));
462
+ }
463
+ }
464
+
465
+ scope.own(() => {
466
+ gone = true;
467
+ made.forEach((el) => el.remove());
468
+ });
469
+
470
+ renderColumn();
471
+
472
+ // The answers the neighbours ask for: the bar's announcement and the decision's line
473
+ scope.on('changes:opened-line', (title) => (state.proposal ? openedLine(title) : undefined));
474
+ scope.on('changes:played-line', () => (state.proposal ? model().playedLine : ''));
475
+
476
+ return {
477
+ elements: made,
478
+ playScenario: player.play,
479
+ stopScenario: player.stop,
480
+ clearScenario: player.clear,
481
+ playOutage: player.playOutage,
482
+ getPlayer: player.getPlayer,
483
+ wantsFrames: player.wantsFrames,
484
+ setCloseFocus: player.setCloseFocus,
485
+ setNextScenario: player.setNextScenario,
486
+ setKeepChecksOnClose: player.setKeepChecksOnClose,
487
+ tickScenario: player.tick,
488
+ demo: player.demo,
489
+ layersHiding: (node) => layersHiding(inst, node),
490
+ checks,
491
+ renderColumn,
492
+ shareRoom,
493
+ setPullHead,
494
+ openedLine,
495
+ peekLine,
496
+ update(props) {
497
+ if (props && 'checker' in props) checks.setChecker(props.checker);
498
+ if (state.proposal) repaint();
499
+ },
500
+ destroy: () => scope.destroy(),
501
+ };
502
+ }