cornfield 0.38.0 → 0.40.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,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
+ }