cornfield 0.37.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.
@@ -58,10 +58,10 @@ const slugOf = () => state.proposalSlug || null;
58
58
  const keyOf = () => (state.proposal && slugOf() ? `${state.proposalSource || ''}/${slugOf()}` : null);
59
59
  const reviewUrl = () => `/proposals/${encodeURIComponent(slugOf())}/review${state.proposalSource ? `?source=${encodeURIComponent(state.proposalSource)}` : ''}`;
60
60
  const q = (sel) => (root ? root.querySelector(sel) : null);
61
- /** The toolbar's own buttons: Send back and Approve (index.html) */
62
- const button = (verdict) => document.querySelector(`#proposal-bar [data-review="${verdict}"]`);
61
+ /** The decision's buttons, in the review column's foot: Send back and Approve (index.html) */
62
+ const button = (verdict) => document.querySelector(`#review-decision [data-review="${verdict}"]`);
63
63
 
64
- /** The status line, the note field and the lines under them; added to the toolbar once, just before Send back and Approve, so Tab goes from the note to Cancel and then to "Send back with this note" (on a phone it sits under the counts, above the two buttons; from 768px CSS gives it a row under the toolbar) */
64
+ /** The status line, the note field and the lines under them; added to the decision (the review column's foot) once, just before Send back and Approve, so Tab goes from the note to Cancel and then to "Send back with this note" */
65
65
  function mount() {
66
66
  const body = $('proposal-body');
67
67
  if (!body) return null;
@@ -86,10 +86,10 @@ function mount() {
86
86
  // The words are set as text and attributes, never parsed as HTML (a brand's `strings`, explorer/strings.js)
87
87
  q('.hx-review-label').textContent = t('reviewNoteLabel');
88
88
  q('#review-note').setAttribute('placeholder', t('reviewNotePlaceholder'));
89
- const actions = body.querySelector('.hx-proposal-actions');
89
+ // In the decision, the column's foot: the status and the note above Send back and Approve
90
+ const actions = document.querySelector('#review-decision .hx-proposal-actions');
90
91
  if (actions) actions.before(root); else body.prepend(root);
91
- const bar = $('proposal-bar');
92
- (bar || root).addEventListener('click', onClick);
92
+ ($('review-decision') || $('proposal-bar') || root).addEventListener('click', onClick);
93
93
  root.addEventListener('input', () => { if (ui.message) { ui.message = ''; paint(); } });
94
94
  root.addEventListener('keydown', (e) => { if (e.key === 'Escape' && ui.noting) { e.stopPropagation(); closeNote(); } });
95
95
  }
@@ -112,7 +112,7 @@ function paint() {
112
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.` : '';
113
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
114
114
  // only says it is busy (`aria-disabled`): a `disabled` button drops the focus to the page.
115
- for (const btn of document.querySelectorAll('#proposal-bar [data-review]')) {
115
+ for (const btn of document.querySelectorAll('#review-decision [data-review]')) {
116
116
  btn.disabled = !ui.reviewable;
117
117
  if (ui.busy) btn.setAttribute('aria-disabled', 'true'); else btn.removeAttribute('aria-disabled');
118
118
  if (!ui.reviewable && ui.key) btn.setAttribute('aria-describedby', 'review-hint'); else btn.removeAttribute('aria-describedby');
@@ -280,6 +280,7 @@ export async function sendReview(verdict) {
280
280
  const lost = !document.activeElement || document.activeElement === document.body || !document.activeElement.isConnected;
281
281
  if (verdict === 'approved') { if (lost) button('approved')?.focus(); }
282
282
  else if (wasNoting || lost) button('notes')?.focus();
283
+ if (hooks.reviewed) hooks.reviewed(); // what waits on you changed: the count is read again (spec 0010)
283
284
  refreshMockups(); // an approval covers the screens as they are now; a send back leaves them not reviewed
284
285
  if (verdict === 'notes') clearEdits(); // the edits went with the note; an approval keeps them, they are in the review
285
286
  return true;
@@ -9,9 +9,11 @@
9
9
  */
10
10
 
11
11
  import { relativeTime } from './review-model.js';
12
- import { runTone, canRetry, aboutWords, runName, statusWords, statusWhy, runMeta, canStop, canAnswer, groupRuns, compareTitle, limitRows, checksWords, timelineWords, nodeLabels, collisionWords, answerWords } from './runs-model.js';
12
+ import { runTone, canRetry, aboutWords, runName, statusWords, statusWhy, runMeta, canStop, canAnswer, compareTitle, limitRows, checksWords, timelineWords, nodeLabels, collisionWords, answerWords } from './runs-model.js';
13
13
  import { cornState, cornStateAttr, stateIconHtml } from './corn-state.js';
14
14
  import { t } from './strings.js';
15
+ import { runGroups } from './waiting-model.js';
16
+ import { runGroupHeadingHtml } from './waiting-view.js';
15
17
 
16
18
 
17
19
  /**
@@ -174,17 +176,18 @@ export function runHtml(ctx, run, all) {
174
176
  }
175
177
 
176
178
  /**
177
- * The list: runs on their own and compares, as the items of the list.
179
+ * The list, in groups (spec 0010 D6): Needs you (oldest question first), In motion, Finished (each newest first), each starting with a heading that
180
+ * says how many; runs on their own and compares are the items. The headings are items of the one flat list, so a run's card is never moved into a section.
178
181
  * @param {ViewContext} ctx
179
182
  * @param {object[]} runs
180
183
  */
181
184
  export function runsHtml(ctx, runs) {
182
- return groupRuns(runs).map((g) => {
185
+ return runGroups(runs).map((group) => runGroupHeadingHtml(group) + group.items.map((g) => {
183
186
  if (g.kind === 'run') return runHtml(ctx, g.run, runs);
184
187
  const id = `cmp-${g.runs[0].runId}`;
185
188
  return `<li class="hx-run-group" data-key="${ctx.esc(id)}"><section class="hx-run-compare" aria-labelledby="${ctx.esc(id)}">
186
189
  <h4 class="hx-run-compare-title" id="${ctx.esc(id)}">${ctx.esc(compareTitle(g.runs))}</h4>
187
190
  <p class="hx-forge-meta hx-faint">The same request under each profile, side by side.</p>
188
191
  <ul class="hx-run-columns" aria-label="${ctx.esc(g.runs.length)} profiles compared">${g.runs.map((r) => runHtml(ctx, r, runs)).join('')}</ul></section></li>`;
189
- }).join('');
192
+ }).join('')).join('');
190
193
  }
@@ -0,0 +1,301 @@
1
+ /**
2
+ * @module explorer/scenario-list-model
3
+ *
4
+ * The review column's two lists, the pure half (spec 0006, D1, D2, D4; no DOM, no storage of its own, tested in Node).
5
+ *
6
+ * - `changeRows(nodes, edges, proposal)`: the list of changes, one row for each marked node and each edge the proposal
7
+ * names (the ownership edge a `parent` adds, and the edges of a removed node, are consequences: not rows).
8
+ * - `buildScenarioList({ scenarios, nodes, edges, proposal, verdicts, seen })`: the scenarios grouped by who acts in them.
9
+ *
10
+ * "Applies to" means "acts in" (D2): a scenario is under a persona when that persona is its `actor` or the `actor` of
11
+ * any of its steps; a step's own `actor` wins over the scenario's. A scenario with no actor anywhere is under **Anyone**,
12
+ * the last group. The groups follow the order of the personas on the map (the personas file's order). A scenario that
13
+ * several personas act in is listed under each of them.
14
+ *
15
+ * Everything here is data from a project's files (persona labels, scenario titles, step text): it comes out as plain
16
+ * strings, and the page puts them in with `textContent` or escapes them. Anything that becomes an element id or a
17
+ * `data-*` value is made safe first (`safeKey`).
18
+ *
19
+ * The record of what was seen (a tick per scenario: "Read" once its steps were opened, "Played" once it played to the end)
20
+ * is kept by the browser only (`seenKey`, `readSeen`, `writeSeen`): information, never a gate, never part of a review.
21
+ */
22
+
23
+ import { edgeKey } from '../core/proposal.js';
24
+ import { MARK_WORDS, MARKS } from './proposal-model.js';
25
+
26
+ const asList = (v) => (Array.isArray(v) ? v : []);
27
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
28
+
29
+ /** A value as a token that is safe in an element id or a `data-*` attribute: letters, digits, dashes and underscores */
30
+ export const safeKey = (value) => String(value ?? '').replace(/[^A-Za-z0-9_-]+/g, '_') || '_';
31
+
32
+ const personaId = (node) => String(node.id).replace(/^persona-/, '');
33
+ /** A persona's label without the live count ("Adult", not "Adult · 2 people") */
34
+ const personaName = (node) => node.codeLabel || node.label || personaId(node);
35
+
36
+ /**
37
+ * The rows of the changes list: every marked node, then the proposal's own marked edges, by mark.
38
+ * @param {{ id: string, label?: string, type?: string, mark?: string }[]} nodes the map as the proposal draws it
39
+ * @param {{ from: string, to: string, kind?: string, mark?: string }[]} edges
40
+ * @param {{ edges?: { add?: any[], change?: any[], remove?: any[] } } | null} proposal
41
+ * @returns {{ kind: 'node' | 'edge', key: string, mark: string, word: string, name: string, type: string }[]}
42
+ */
43
+ export function changeRows(nodes, edges, proposal) {
44
+ const said = new Set(['add', 'change', 'remove'].flatMap((op) => asList(proposal?.edges?.[op]).map(edgeKey)));
45
+ const label = (id) => (nodes.find((n) => n.id === id) || { label: id }).label || id;
46
+ const rows = [];
47
+ for (const mark of [...MARKS, 'edit']) {
48
+ for (const n of nodes.filter((x) => x.mark === mark)) {
49
+ rows.push({ kind: 'node', key: n.id, mark, word: MARK_WORDS[mark], name: String(n.label ?? n.id), type: String(n.type ?? '') });
50
+ }
51
+ for (const e of edges.filter((x) => x.mark === mark && said.has(edgeKey(x)))) {
52
+ rows.push({ kind: 'edge', key: edgeKey(e), mark, word: MARK_WORDS[mark], name: `${label(e.from)} → ${label(e.to)}`, type: String(e.kind || 'ownership') });
53
+ }
54
+ }
55
+ return rows;
56
+ }
57
+
58
+ /**
59
+ * The personas that act in a scenario (D2): its own `actor` and the `actor` of any of its steps.
60
+ * @returns {string[]} the distinct persona ids, in the order they first act
61
+ */
62
+ export function actorsOf(scenario) {
63
+ const out = [];
64
+ const add = (id) => { if (typeof id === 'string' && id && !out.includes(id)) out.push(id); };
65
+ add(scenario?.actor);
66
+ for (const step of asList(scenario?.steps)) add(step?.actor);
67
+ return out;
68
+ }
69
+
70
+ /**
71
+ * A step's verdict in words, for the list (D4): "Allowed", "Refused: <reason>", "Expected refused, was allowed",
72
+ * "Not checked: <why>"; nothing for a step with no actor.
73
+ * @param {{ state: string, mismatch?: boolean, expect?: string, reason?: string, why?: string } | null | undefined} v a check-model Verdict
74
+ * @returns {{ words: string, state: 'success' | 'failure' | '', tone: string } | null}
75
+ */
76
+ export function stepVerdictWords(v, words = {}) {
77
+ const notChecked = words.notChecked || 'Not checked';
78
+ if (!v || v.state === 'none') return null;
79
+ if (v.state === 'pending') return { words: 'Checking…', state: '', tone: 'pending' };
80
+ if (v.state === 'unchecked') return { words: `${notChecked}: ${v.why || 'nothing to ask'}`, state: '', tone: 'unchecked' };
81
+ if (v.state === 'unavailable') return { words: `${notChecked}: the checker did not answer${v.why ? ` (${v.why})` : ''}`, state: '', tone: 'unavailable' };
82
+ if (v.mismatch) {
83
+ const words = v.state === 'refused' ? `Expected allowed, was refused${v.reason ? `: ${v.reason}` : ''}` : 'Expected refused, was allowed';
84
+ return { words, state: 'failure', tone: 'mismatch' };
85
+ }
86
+ if (v.state === 'refused') return { words: `Refused: ${v.reason || 'no reason given'}`, state: v.expect === 'refused' ? 'success' : 'failure', tone: 'refused' };
87
+ return { words: 'Allowed', state: 'success', tone: 'allowed' };
88
+ }
89
+
90
+ /**
91
+ * The scenario's steps as rows: number, who acts, the node it touches, the node's mark, the text and the verdict.
92
+ * @param {object} scenario
93
+ * @param {{ nodes: any[], edges: any[], changeKeys: Set<string>, verdicts?: any[] | null, words?: { notChecked?: string }, label: (id: string) => string, personaLabel: (id: string) => string }} ctx
94
+ */
95
+ function stepRows(scenario, ctx) {
96
+ return asList(scenario.steps).map((step, i) => {
97
+ const actor = (step && step.actor) || scenario.actor || null;
98
+ let where = '';
99
+ let mark = '';
100
+ let touched = [];
101
+ if (step && step.edge) {
102
+ where = `${ctx.label(step.edge.from)} → ${ctx.label(step.edge.to)}`;
103
+ touched = [`edge:${edgeKey(step.edge)}`, `node:${step.edge.from}`, `node:${step.edge.to}`];
104
+ const e = ctx.edges.find((x) => edgeKey(x) === edgeKey(step.edge));
105
+ if (e && e.mark && e.mark !== 'none' && ctx.changeKeys.has(`edge:${edgeKey(e)}`)) mark = e.mark;
106
+ } else if (step && step.node !== undefined) {
107
+ where = ctx.label(step.node);
108
+ touched = [`node:${step.node}`];
109
+ const n = ctx.nodes.find((x) => x.id === step.node);
110
+ if (n && n.mark && n.mark !== 'none') mark = n.mark;
111
+ }
112
+ const v = ctx.verdicts ? stepVerdictWords(ctx.verdicts[i], ctx.words) : null;
113
+ // a node it names is on a layer that is off (#212): the list says so; playing the scenario turns the layer on
114
+ const layerOff = !!ctx.hidden && touched.some((k) => k.startsWith('node:') && ctx.hidden(k.slice(5)));
115
+ return {
116
+ index: i,
117
+ number: i + 1,
118
+ actor,
119
+ actorLabel: actor ? ctx.personaLabel(actor) : '',
120
+ where,
121
+ mark,
122
+ markWord: mark ? MARK_WORDS[mark] || '' : '',
123
+ text: String((step && step.text) ?? ''),
124
+ verdict: actor ? v : null,
125
+ layerOff,
126
+ touched,
127
+ };
128
+ });
129
+ }
130
+
131
+ /** The sentence a screen reader gets for a step: "Step 2 of 3, as Adult: checkout page, Added. You pay. Allowed." */
132
+ export function stepSentence(step, total) {
133
+ const where = [step.where, step.markWord, step.layerOff ? 'on a layer that is off' : ''].filter(Boolean).join(', ');
134
+ const head = `Step ${step.number} of ${total}${step.actorLabel ? `, as ${step.actorLabel}` : ''}${where ? `: ${where}` : ''}.`;
135
+ return [head, step.text, step.verdict ? `${step.verdict.words}${/[.!?…]$/.test(step.verdict.words) ? '' : '.'}` : ''].filter(Boolean).join(' ');
136
+ }
137
+
138
+ /**
139
+ * The sentence the player says for the step it is on (D5), the same words the list uses: "Step 2 of 3, as Adult: checkout page, Added. You pay. Allowed."
140
+ * @param {{ snap: { index: number, total: number, current: { node?: string, edge?: { from: string, to: string, kind?: string, flow?: string }, text?: string, actor?: string }, verdict?: any }, nodes: any[], edges: any[], words?: { notChecked?: string } }} input
141
+ */
142
+ export function currentStepSentence({ snap, nodes, edges, words = {} }) {
143
+ const cur = snap.current || {};
144
+ const label = (id) => String((nodes.find((n) => n.id === id) || { label: id }).label ?? id);
145
+ const persona = cur.actor ? nodes.find((n) => n.type === 'persona' && (n.id === `persona-${cur.actor}` || n.id === cur.actor)) : null;
146
+ let where = '';
147
+ let mark = '';
148
+ if (cur.edge) {
149
+ where = `${label(cur.edge.from)} → ${label(cur.edge.to)}`;
150
+ const e = edges.find((x) => edgeKey(x) === edgeKey(cur.edge));
151
+ if (e && e.mark && e.mark !== 'none') mark = e.mark;
152
+ } else if (cur.node !== undefined) {
153
+ where = label(cur.node);
154
+ const n = nodes.find((x) => x.id === cur.node);
155
+ if (n && n.mark && n.mark !== 'none') mark = n.mark;
156
+ }
157
+ const verdict = cur.actor ? stepVerdictWords(snap.verdict, words) : null;
158
+ const step = {
159
+ number: snap.index + 1, actorLabel: cur.actor ? (persona ? personaName(persona) : String(cur.actor)) : '', where,
160
+ markWord: mark ? MARK_WORDS[mark] || '' : '', text: String(cur.text ?? ''), verdict,
161
+ };
162
+ return stepSentence(step, snap.total);
163
+ }
164
+
165
+ /** "Allowed", "Refused" counts for a row once its checks are in: "3 allowed · 1 refused" ('' before) */
166
+ function verdictSummary(rows) {
167
+ const count = (state) => rows.filter((r) => r.verdict && r.verdict.tone === state).length;
168
+ const parts = [[count('allowed'), 'allowed'], [count('refused'), 'refused'], [count('mismatch'), 'not as expected']].filter(([n]) => n > 0).map(([n, w]) => `${n} ${w}`);
169
+ return parts.join(' · ');
170
+ }
171
+
172
+ /**
173
+ * The scenarios grouped by persona.
174
+ * @param {object} input
175
+ * @param {object[]} input.scenarios the open proposal's scenarios (with what-if edits in)
176
+ * @param {any[]} input.nodes the map as drawn (personas are nodes of type `persona`; marks on the changed ones)
177
+ * @param {any[]} input.edges
178
+ * @param {object | null} [input.proposal] for the list of changes it counts "walks 3 of 9 changes" against
179
+ * @param {Map<string, any[]> | null} [input.verdicts] scenario id -> its steps' check-model verdicts, for the scenarios that were checked
180
+ * @param {{ played?: string[], read?: string[] } | null} [input.seen] what this browser has seen
181
+ * @param {{ notChecked?: string }} [input.words] the project's own words (`strings`)
182
+ * @param {((nodeId: string) => boolean) | null} [input.hidden] whether a node is on a layer that is off (#212)
183
+ * @returns {{
184
+ * total: number,
185
+ * personaCount: number,
186
+ * groups: { key: string, persona: string | null, label: string, anyone: boolean, heading: string, scenarios: any[] }[],
187
+ * notInAny: string[],
188
+ * coverage: string,
189
+ * playedLine: string,
190
+ * }}
191
+ */
192
+ export function buildScenarioList({ scenarios, nodes, edges, proposal = null, verdicts = null, seen = null, words = {}, hidden = null }) {
193
+ const list = asList(scenarios);
194
+ const personas = nodes.filter((n) => n.type === 'persona');
195
+ const byPersona = new Map(personas.map((n) => [personaId(n), n]));
196
+ const label = (id) => String((nodes.find((n) => n.id === id) || { label: id }).label ?? id);
197
+ const personaLabel = (id) => (byPersona.has(id) ? personaName(byPersona.get(id)) : String(id));
198
+ const rows = changeRows(nodes, edges, proposal);
199
+ const changeKeys = new Set(rows.map((r) => `${r.kind}:${r.key}`));
200
+ const played = new Set(asList(seen?.played));
201
+ const read = new Set(asList(seen?.read));
202
+
203
+ const built = list.map((s, index) => {
204
+ const checked = verdicts && verdicts.get(s.id);
205
+ const steps = stepRows(s, { nodes, edges, changeKeys, verdicts: checked || null, words, label, personaLabel, hidden });
206
+ const walked = new Set(steps.flatMap((st) => st.touched).filter((k) => changeKeys.has(k)));
207
+ const count = steps.length;
208
+ const parts = [plural(count, 'step')];
209
+ if (changeKeys.size > 0) parts.push(`walks ${walked.size} of ${plural(changeKeys.size, 'change')}`);
210
+ const done = verdictSummary(steps);
211
+ return {
212
+ index,
213
+ id: String(s.id ?? ''),
214
+ key: `${index}-${safeKey(s.id)}`,
215
+ title: String(s.title ?? s.id ?? ''),
216
+ actors: actorsOf(s),
217
+ steps,
218
+ stepCount: count,
219
+ summary: parts.join(' · '),
220
+ verdictSummary: done,
221
+ seen: played.has(String(s.id)) ? 'played' : read.has(String(s.id)) ? 'read' : '',
222
+ };
223
+ });
224
+
225
+ // Personas in the personas file's order, then an actor the map has no persona for (a proposal that is wrong about it), then Anyone
226
+ const order = [...byPersona.keys()];
227
+ for (const sc of built) for (const a of sc.actors) if (!order.includes(a)) order.push(a);
228
+ const groups = [];
229
+ for (const id of order) {
230
+ const mine = built.filter((sc) => sc.actors.includes(id));
231
+ if (!mine.length) continue;
232
+ const name = personaLabel(id);
233
+ groups.push({ key: safeKey(id), persona: id, label: name, anyone: false, heading: `${name} · ${plural(mine.length, 'scenario')}`, scenarios: mine });
234
+ }
235
+ const anyone = built.filter((sc) => sc.actors.length === 0);
236
+ if (anyone.length) groups.push({ key: 'anyone', persona: null, label: 'Anyone', anyone: true, heading: `Anyone · ${plural(anyone.length, 'scenario')}`, scenarios: anyone });
237
+
238
+ const acting = new Set(built.flatMap((sc) => sc.actors));
239
+ const notInAny = built.length ? personas.filter((n) => !acting.has(personaId(n))).map(personaName) : [];
240
+ const playedN = built.filter((sc) => sc.seen === 'played').length;
241
+ return {
242
+ total: built.length,
243
+ personaCount: groups.filter((g) => !g.anyone).length,
244
+ groups,
245
+ notInAny,
246
+ coverage: notInAny.length ? `Not in any scenario: ${notInAny.join(', ')}` : '',
247
+ playedLine: built.length && playedN ? `${playedN} of ${built.length} ${built.length === 1 ? 'scenario' : 'scenarios'} played` : '',
248
+ };
249
+ }
250
+
251
+ /** The proposal's one-line facts for the phone's peek and the opening announcement: "6 changes · 3 scenarios for 2 personas" */
252
+ export function reviewCounts(changeCount, list) {
253
+ const parts = [plural(changeCount, 'change')];
254
+ if (list.total > 0) parts.push(`${plural(list.total, 'scenario')}${list.personaCount > 0 ? ` for ${plural(list.personaCount, 'persona')}` : ''}`);
255
+ return parts.join(' · ');
256
+ }
257
+
258
+ /** What the page says when a proposal opens (D5): "Opened Checkout: 6 changes, 3 scenarios for 2 personas." */
259
+ export function reviewOpenedWords(title, changeCount, list) {
260
+ return `Opened ${title}: ${reviewCounts(changeCount, list).replace(' · ', ', ')}.`;
261
+ }
262
+
263
+ // ---------------------------------------------------------------------------
264
+ // What was seen: a record in the browser, never a gate
265
+ // ---------------------------------------------------------------------------
266
+
267
+ /** The browser key one proposal's record is kept under: its source, its name and the PR head it was read at ('' when not known) */
268
+ export const seenKey = (source, slug, head = '') => `cornfield.seen.${source || 'checkout'}/${slug || ''}@${head || ''}`;
269
+
270
+ /**
271
+ * What this browser saw of a proposal. A blocked, missing or garbled store reads as nothing seen.
272
+ * @param {{ getItem(key: string): string | null } | null} storage
273
+ * @returns {{ played: string[], read: string[] }}
274
+ */
275
+ export function readSeen(storage, key) {
276
+ const none = { played: [], read: [] };
277
+ try {
278
+ const raw = storage && storage.getItem(key);
279
+ if (!raw) return none;
280
+ const v = JSON.parse(raw);
281
+ const ids = (x) => (Array.isArray(x) ? x.filter((s) => typeof s === 'string').slice(0, 200) : []);
282
+ return { played: ids(v && v.played), read: ids(v && v.read) };
283
+ } catch { return none; }
284
+ }
285
+
286
+ /**
287
+ * Adds a scenario to the record and keeps it. Played includes read.
288
+ * @param {{ getItem(key: string): string | null, setItem(key: string, value: string): void } | null} storage
289
+ * @param {string} key
290
+ * @param {string} scenarioId
291
+ * @param {'read' | 'played'} how
292
+ * @param {{ played: string[], read: string[] } | null} [current] the record to add to, in place of the stored one (a record held in memory, with no storage)
293
+ * @returns {{ played: string[], read: string[] }} the record now, kept or not
294
+ */
295
+ export function writeSeen(storage, key, scenarioId, how, current = null) {
296
+ const now = current ? { played: [...asList(current.played)], read: [...asList(current.read)] } : readSeen(storage, key);
297
+ const id = String(scenarioId);
298
+ if (how === 'played') { if (!now.played.includes(id)) now.played.push(id); now.read = now.read.filter((x) => x !== id); } else if (!now.read.includes(id) && !now.played.includes(id)) now.read.push(id);
299
+ try { if (storage) storage.setItem(key, JSON.stringify(now)); } catch { /* storage blocked or full: it counts for this visit only */ }
300
+ return now;
301
+ }