create-pmos 0.591.0 → 0.593.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,474 @@
1
+ /* pm/cozy-proto.js — Prototype by chatting: the Viewer as ONE canvas (initiative live-round-iterative; design
2
+ * https://claude.ai/artifact/9fxuukKr3XixwkGFMTfeba, main canvas boards PbcChat, PbcPoint, PbcLanes, PbcDesk, PbcPlay; Wawan "Agreed"
3
+ * 2026-11-17). The initiative chat sits on the left; this draws the right side for a live round (lib/live-round.js), from the compare view
4
+ * pm/cozy-lab.js reads (GET /api/lab/compare: the version's file and its companions as data, lib/live-round.js partsAt).
5
+ *
6
+ * The toolbar: Point (S), Comment (C), Draw (D) · Page copy (a side panel, closed by default: Wawan 2026-11-18) · Phone, Desktop · Version n of N (‹ ›, Back to latest, Continue from version n) · zoom
7
+ * −, +, fit · Play. Icon-only presses with aria-labels.
8
+ * The cards, which update together: the prototype in a phone or desktop frame (Tweaks under it for the element pointed at, the comments,
9
+ * the ✦ test-link suggestion); the flow (screens as cards, decisions as diamonds, drawn as SVG from flow.json: a screen shows that moment
10
+ * on the prototype, a branch plays its scenario); the page copy, in its side panel (copy.json, edited in place: the prototype changes as the PM types and
11
+ * the edit is kept with the version, POST /api/lab/edit); who does what (lanes.json as a swimlane with arrows: a step shows its screen).
12
+ * A card the version changed says Updated (compare.updated).
13
+ * Three ways (a round with several versions): a tray; a press previews one; ✓ keeps it, ✕ closes the round.
14
+ * Play: the prototype full size through a scenario of flow.json; a tap where the user would tap moves on, a miss shows the hotspots.
15
+ * The chat (pm/home-chat.js) hears 'pmos:point', 'pmos:from' and 'pmos:say' (window events, detail.ini names the initiative); it says
16
+ * 'pmos:version' when the PM taps a Version n tag.
17
+ * The frame is the sandboxed specimen with the canvas runtime (GET /api/lab/specimen?rt=1, lib/proto-runtime.js): it cannot reach PMOS,
18
+ * and it talks to this page only through postMessage.
19
+ *
20
+ * draw(body, compare, { at, H, history? }) draws or updates the canvas in the Viewer's body (pm/cozy-lab.js calls it for a live round)
21
+ * openVersion({ ws, board?, ini, n }) shows version n of the initiative's newest round (the chat's Version n tag)
22
+ * flowLayout(flow) · lanesLayout(lanes) PURE: where the SVG puts each node and arrow (exported for the source check) */
23
+ import { pmGet, pmPost, pmHeaders } from './http.js';
24
+
25
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
26
+ const SVG = (d, w = 16, sw = 2) => `<svg aria-hidden="true" width="${w}" height="${w}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${sw}" stroke-linecap="round" stroke-linejoin="round"><path d="${d}"/></svg>`;
27
+ const I = {
28
+ point: 'M5 3l14 7-6 2-2 6z', comment: 'M4 5h16v11H9l-5 4z', draw: 'M4 20l4-1 11-11-3-3L5 16zM14 6l3 3',
29
+ phone: 'M8 3h8a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zM11 18h2', desk: 'M3 5h18v11H3zM8 20h8M12 16v4',
30
+ minus: 'M6 12h12', plus: 'M12 6v12M6 12h12', fit: 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5', play: 'M7 5l12 7-12 7z',
31
+ prev: 'M15 6l-6 6 6 6', next: 'M9 6l6 6-6 6', latest: 'M5 12h14M13 6l6 6-6 6', cont: 'M4 12a8 8 0 1 0 2.3-5.6L4 9M4 4v5h5',
32
+ restart: 'M4 12a8 8 0 1 0 2.3-5.6L4 9M4 4v5h5', x: 'M6 6l12 12M18 6L6 18', check: 'M5 12l5 5 9-10', send: 'M12 19V5M6 11l6-6 6 6',
33
+ keep: 'M6 4h12v16l-6-4-6 4z', link: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1',
34
+ text: 'M4 7V5h16v2M12 5v14M9 19h6',
35
+ attach: 'M20 11l-8.5 8.5a5 5 0 0 1-7-7L13 4a3.5 3.5 0 0 1 5 5l-8.5 8.5a2 2 0 0 1-3-3L14 7', star: 'M12 3l2.2 6.3H21l-5.4 4 2 6.4L12 15.8 6.4 19.7l2-6.4L3 9.3h6.8z',
36
+ };
37
+ const ib = (attr, label, icon, cls = '') => `<button type="button" class="pc-ib${cls ? ' ' + cls : ''}" ${attr} aria-label="${esc(label)}" title="${esc(label)}">${SVG(icon, 16)}</button>`;
38
+ const store = { get: (k) => { try { return localStorage.getItem(k); } catch { return null; } }, set: (k, v) => { try { if (v == null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* private window */ } } };
39
+ const human = (k) => String(k || '').replace(/[-_.]+/g, ' ').replace(/^./, (c) => c.toUpperCase());
40
+ /** A label in two lines of about n characters each (the second one cut with …), as SVG tspans. */
41
+ function lines(text, x, y, n, dy = 14) {
42
+ const w = String(text || '').split(/\s+/), out = ['', ''];
43
+ let i = 0;
44
+ for (const word of w) { if (i === 0 && out[0] && (out[0] + ' ' + word).length > n) i = 1; out[i] = out[i] ? out[i] + ' ' + word : word; }
45
+ if (out[1].length > n) out[1] = out[1].slice(0, n - 1).trimEnd() + '…';
46
+ if (out[0].length > n) out[0] = out[0].slice(0, n - 1) + '…';
47
+ return out.filter(Boolean).map((t, k) => `<tspan x="${x}" y="${y + k * dy}">${esc(t)}</tspan>`).join('');
48
+ }
49
+ const fire = (name, detail) => { try { window.dispatchEvent(new CustomEvent(name, { detail })); } catch { /* old browser */ } };
50
+
51
+ // the look, loaded once (cozy-proto.css)
52
+ if (typeof document !== 'undefined' && typeof document.createElement === 'function' && document.head && !document.querySelector('link[data-proto-css]')) {
53
+ const l = document.createElement('link'); l.rel = 'stylesheet'; l.href = new URL('./cozy-proto.css', import.meta.url).href; l.dataset.protoCss = '1'; document.head.appendChild(l);
54
+ }
55
+
56
+ /* ── layout (PURE) ── */
57
+ const SW = 132, SH = 58, DH = 70, GX = 76, GY = 34, PAD = 16, CH = 18;
58
+ /** The width of a decision diamond: wide enough for its words in two lines inside the shape (2026-11-18: "What does th" was cut). */
59
+ const diaW = (t) => Math.max(120, Math.min(200, Math.ceil(String(t || '').length / 2) * 6.4 / 0.55 + 16));
60
+ /** PURE. flow → { w, h, nodes: [{ id, kind, title, x, y, w, h, main, chars }], edges: [{ from, to, label, d, lx, ly, main, anchor }] }.
61
+ * Columns by the shortest path from the first screen. The main scenario is ONE row; side branches sit in rows below their column. A line
62
+ * going back runs in its own channel: above the main row when it leaves the main row, under everything when it leaves a branch, so lines
63
+ * never run through a box or cross a label (Wawan 2026-11-18: "too many overlapping components and lines"). */
64
+ export function flowLayout(flow) {
65
+ const f = flow || {}, nodes = [...(f.screens || []).map((s) => ({ ...s, kind: 'screen' })), ...(f.decisions || []).map((d) => ({ ...d, kind: 'decision' }))];
66
+ if (!nodes.length) return { w: 0, h: 0, nodes: [], edges: [] };
67
+ const by = new Map(nodes.map((n) => [n.id, n])), out = new Map(nodes.map((n) => [n.id, []]));
68
+ for (const e of f.edges || []) if (by.has(e.from) && by.has(e.to)) out.get(e.from).push(e);
69
+ const col = new Map(), q = [nodes[0].id]; col.set(nodes[0].id, 0);
70
+ while (q.length) { const u = q.shift(); for (const e of out.get(u)) if (!col.has(e.to)) { col.set(e.to, col.get(u) + 1); q.push(e.to); } }
71
+ let extra = Math.max(0, ...col.values()) + 1;
72
+ for (const n of nodes) if (!col.has(n.id)) col.set(n.id, extra++);
73
+ const steps = new Set(((f.scenarios || [])[0] || { steps: [] }).steps.map((s) => s.screen));
74
+ // the main row: the first scenario's screens and the decisions between them (no scenario: the first node of each column)
75
+ const onMain = new Set();
76
+ if (steps.size) {
77
+ for (const n of nodes) if (steps.has(n.id)) onMain.add(n.id);
78
+ for (const n of nodes) if (n.kind === 'decision' && [...out.get(n.id)].some((e) => steps.has(e.to)) && (f.edges || []).some((e) => e.to === n.id && steps.has(e.from))) onMain.add(n.id);
79
+ }
80
+ const rowsUsed = new Map(); // column → next free row
81
+ const taken = new Set();
82
+ for (const n of [...nodes].sort((x, y) => (onMain.has(y.id) ? 1 : 0) - (onMain.has(x.id) ? 1 : 0))) {
83
+ const c = col.get(n.id);
84
+ let r = onMain.has(n.id) || (!steps.size && !taken.has(c + ':0')) ? 0 : Math.max(1, rowsUsed.get(c) || 1);
85
+ while (taken.has(c + ':' + r)) r += 1;
86
+ taken.add(c + ':' + r); rowsUsed.set(c, Math.max(rowsUsed.get(c) || 1, r + 1));
87
+ n.c = c; n.r = r;
88
+ }
89
+ for (const n of nodes) { n.w = n.kind === 'decision' ? diaW(n.title) : SW; n.h = n.kind === 'decision' ? DH : SH; }
90
+ const nc = Math.max(...nodes.map((n) => n.c)) + 1, cw = [];
91
+ for (let c = 0; c < nc; c += 1) cw[c] = Math.max(SW, ...nodes.filter((n) => n.c === c).map((n) => n.w));
92
+ const cx = []; let acc = PAD; for (let c = 0; c < nc; c += 1) { cx[c] = acc; acc += cw[c] + GX; }
93
+ // the back lines that leave the main row run in channels above it; the others under everything
94
+ const raw = (f.edges || []).map((e) => ({ e, a: by.get(e.from), b: by.get(e.to) })).filter((x) => x.a && x.b);
95
+ const back = (x) => x.b.c <= x.a.c && x.a !== x.b;
96
+ const up = raw.filter((x) => back(x) && x.a.r === 0), down = raw.filter((x) => back(x) && x.a.r > 0);
97
+ const top = PAD + up.length * CH + (up.length ? 6 : 0), rh = Math.max(SH, DH) + GY;
98
+ for (const n of nodes) { n.x = cx[n.c] + (cw[n.c] - n.w) / 2; n.y = top + n.r * rh + (Math.max(SH, DH) - n.h) / 2; n.main = n.kind === 'decision' ? onMain.has(n.id) || !steps.size : !steps.size || steps.has(n.id); }
99
+ const bottom = Math.max(...nodes.map((n) => n.y + n.h));
100
+ const edges = [];
101
+ raw.forEach((x) => {
102
+ const { e, a, b } = x;
103
+ let d, lx, ly, anchor = 'middle';
104
+ if (back(x)) {
105
+ // its own channel: k-th line above or under, entering and leaving at a quarter of the box so two lines do not share a segment
106
+ const i = up.includes(x) ? up.indexOf(x) : down.indexOf(x), isUp = up.includes(x);
107
+ const x1 = a.x + a.w * (isUp ? 0.7 : 0.5), x2 = b.x + b.w * 0.3;
108
+ if (isUp) { const yc = PAD + i * CH + 4; d = `M${x1} ${a.y}V${yc}H${x2}V${b.y - 2}`; ly = yc - 4; }
109
+ else { const yc = bottom + 16 + i * CH, y2 = b.y + b.h; d = `M${x1} ${a.y + a.h}V${yc}H${x2}V${y2 + 2}`; ly = yc - 4; }
110
+ lx = (x1 + x2) / 2;
111
+ } else if (a.r === b.r) {
112
+ const x1 = a.x + a.w, y1 = a.y + a.h / 2, x2 = b.x, y2 = b.y + b.h / 2;
113
+ d = `M${x1} ${y1}H${(x1 + x2) / 2}V${y2}H${x2 - 2}`; lx = (x1 + x2) / 2; ly = Math.min(y1, y2) - 7;
114
+ } else if (b.r > a.r) {
115
+ // down to a side branch: out of the bottom of the box, then across, the label beside the drop
116
+ const x1 = a.x + a.w / 2, y1 = a.y + a.h, y2 = b.y + b.h / 2;
117
+ d = `M${x1} ${y1}V${y2}H${b.x - 2}`; lx = x1 + 6; ly = y1 + (y2 - y1) / 2 + 3; anchor = 'start';
118
+ } else {
119
+ // up from a branch to a later main box: across the gap, then up into its bottom
120
+ const x1 = a.x + a.w, y1 = a.y + a.h / 2, x2 = b.x + b.w / 2;
121
+ d = `M${x1} ${y1}H${x2}V${b.y + b.h + 2}`; lx = x1 + (x2 - x1) / 2; ly = y1 - 7;
122
+ }
123
+ edges.push({ from: e.from, to: e.to, label: e.label || '', d, lx, ly, anchor, main: a.main && b.main });
124
+ });
125
+ const w = Math.max(...nodes.map((n) => n.x + n.w)) + PAD, h = bottom + (down.length ? 16 + down.length * CH : 0) + PAD;
126
+ return { w, h, nodes: nodes.map(({ id, kind, title, x, y, w: nw, h: nh, main: m }) => ({ id, kind, title, x, y, w: nw, h: nh, main: m, chars: kind === 'decision' ? Math.floor((nw * 0.55) / 6.4) : 21 })), edges };
127
+ }
128
+ const LW = 110, LH = 68, BW = 136, BH = 44, BG = 26;
129
+ /** PURE. lanes → { w, h, lanes: [{ id, name, y }], boxes: [{ n, title, screen, x, y, lane }], arrows: [{ d }] }: one column per step, in
130
+ * the order of n; an arrow from each step to the next. */
131
+ export function lanesLayout(lanes) {
132
+ const L = (lanes && lanes.lanes) || [];
133
+ const steps = [];
134
+ L.forEach((l, i) => { for (const s of l.steps || []) steps.push({ ...s, lane: i }); });
135
+ steps.sort((a, b) => a.n - b.n);
136
+ const boxes = steps.map((s, c) => ({ n: s.n, title: s.title, screen: s.screen || '', lane: s.lane, x: LW + 14 + c * (BW + BG), y: s.lane * LH + (LH - BH) / 2 }));
137
+ const arrows = [];
138
+ for (let i = 0; i + 1 < boxes.length; i += 1) {
139
+ const a = boxes[i], b = boxes[i + 1], x1 = a.x + BW, y1 = a.y + BH / 2, x2 = b.x, y2 = b.y + BH / 2, mx = x1 + BG / 2;
140
+ arrows.push({ d: a.lane === b.lane ? `M${x1} ${y1}H${x2 - 2}` : `M${x1} ${y1}H${mx}V${y2}H${x2 - 2}` });
141
+ }
142
+ return { w: LW + 14 + boxes.length * (BW + BG) + 6, h: L.length * LH, lanes: L.map((l, i) => ({ id: l.id, name: l.name, y: i * LH })), boxes, arrows };
143
+ }
144
+
145
+ /* ── state ── */
146
+ const V = { body: null, c: null, at: null, H: null, last: null, mode: 'view', device: store.get('pmos.pc.device') || 'phone', zoom: Number(store.get('pmos.pc.zoom')) || 0,
147
+ sel: null, screen: '', frameUrl: '', ready: null, edits: { copy: {}, vars: {} }, pend: null, saveT: null, draft: null, drawing: false, strokes: 0,
148
+ play: null, sig: '', copy: false };
149
+ const ARROW = '<marker id="pcArr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="currentColor"/></marker>';
150
+ const frameUrl = (c) => (c && c.url ? c.url + '&rt=1' : '');
151
+ const toFrame = (m, f) => { const fr = f || (V.body && V.body.querySelector('.pc-frame iframe')); if (fr && fr.contentWindow) fr.contentWindow.postMessage({ pmos: 1, ...m }, '*'); };
152
+ const say = (m, u) => { if (V.H && V.H.toast) V.H.toast(m, u); };
153
+
154
+ /** The version shown: the compare itself, or (while the next version is being made) the last one that rendered, with a note. */
155
+ function shown(c) {
156
+ if (c && c.file) return { v: c, making: c.working && !c.file };
157
+ if (V.last && c && V.last.ini === c.ini) return { v: V.last, making: true };
158
+ return { v: c, making: true };
159
+ }
160
+
161
+ /* ── the parts ── */
162
+ function barHtml(c, v) {
163
+ const H = (c.history || []).filter((h) => h.round), N = H.length ? Math.max(...H.map((h) => h.round)) : 1;
164
+ const at = H.findIndex((h) => h.current), newest = H[0];
165
+ const older = at >= 0 && at + 1 < H.length ? H[at + 1] : null, newer = at > 0 ? H[at - 1] : null;
166
+ const old = at > 0 && newest;
167
+ const tool = (m, label, icon, key) => `<button type="button" class="pc-ib" data-pc-mode="${m}" aria-pressed="${V.mode === m}" aria-label="${esc(label + ' (' + key + ')')}" title="${esc(label + ' (' + key + ')')}">${SVG(icon, 16)}</button>`;
168
+ const dev = (d, label, icon) => `<button type="button" class="pc-ib" data-pc-dev="${d}" aria-pressed="${V.device === d}" aria-label="${esc(label)}" title="${esc(label)}">${SVG(icon, 16)}</button>`;
169
+ const ver = H.length > 1 ? `<span class="pc-ver">${ib(`data-lab-round="${esc(older ? older.id : '')}"${older ? '' : ' disabled'}`, 'Earlier version', I.prev)}<b>Version ${c.round} of ${N}</b>${ib(`data-lab-round="${esc(newer ? newer.id : '')}"${newer ? '' : ' disabled'}`, 'Later version', I.next)}`
170
+ + (old ? ib(`data-lab-round="${esc(newest.id)}"`, 'Back to latest', I.latest) + ib(`data-pc-from="${c.round}"`, 'Continue from version ' + c.round, I.cont) : '') + '</span>'
171
+ : `<span class="pc-ver"><b>Version ${c.round || 1}</b></span>`;
172
+ const z = Math.round((V.zoom || 1) * 100);
173
+ return `<div class="pc-bar" role="toolbar" aria-label="Prototype tools"><span class="pc-grp">${tool('point', 'Point at an element', I.point, 'S')}${tool('comment', 'Comment', I.comment, 'C')}${tool('draw', 'Draw a sketch', I.draw, 'D')}</span>`
174
+ // the page copy sits behind its own press (Wawan 2026-11-18: a 40-row table pushed the canvas down), closed by default
175
+ + `<span class="pc-grp">${ib(`data-pc-copyp aria-pressed="${V.copy}"`, 'Page copy', I.text, (c.updated || {}).copy ? 'upd' : '')}</span>`
176
+ + `<span class="pc-grp">${dev('phone', 'Phone', I.phone)}${dev('desktop', 'Desktop', I.desk)}</span>${ver}<span class="pc-sp"></span>`
177
+ + `<span class="pc-grp">${ib('data-pc-zoom="-1"', 'Zoom out', I.minus)}<span class="pc-z" aria-live="polite">${z}%</span>${ib('data-pc-zoom="1"', 'Zoom in', I.plus)}${ib('data-pc-zoom="0"', 'Fit to the Viewer', I.fit)}</span>`
178
+ + `${ib('data-pc-play', 'Play the prototype', I.play, 'blue')}</div>`;
179
+ }
180
+ function trayHtml(c) {
181
+ const cols = (c.columns || []).filter((x) => /^[A-C]$/.test(x.id));
182
+ if (cols.length < 2) return '';
183
+ return `<div class="pc-tray" role="group" aria-label="${cols.length} ways"><span class="pc-tl">${cols.length} ways · tap one to preview it</span>`
184
+ + cols.map((x) => (x.file ? `<button type="button" class="pc-th" data-lab-key="${esc(x.id)}" aria-pressed="${x.id === c.key}" aria-label="${esc('Preview ' + x.title)}"><span class="pc-thf" aria-hidden="true"><iframe src="${esc(x.url)}" sandbox="allow-scripts" loading="lazy" tabindex="-1" title="${esc(x.title)}"></iframe></span><b>${esc(x.id)}</b></button>`
185
+ : `<span class="pc-th wk"><span class="pc-thf" aria-hidden="true"></span><b>${esc(x.id)}</b><small>${esc(x.left || '')}</small></span>`)).join('')
186
+ + `<span class="pc-tacts">${c.state === 'open' && !c.working ? ib('data-pc-tray="keep"', 'Keep ' + c.key, I.check, 'blue') : ''}${ib('data-pc-tray="close"', 'Close these ways', I.x)}</span></div>`;
187
+ }
188
+ const upd = (c, k) => (c.updated && c.updated[k] ? '<span class="pc-upd">Updated</span>' : '');
189
+ function protoCard(c, v, making) {
190
+ const data = v.data || {}, tw = ((data.tweaks && data.tweaks.tweaks) || []).filter((t) => !t.el || (V.sel && t.el === V.sel.el));
191
+ const tweaks = tw.length ? `<div class="pc-tw" aria-label="Tweaks">${tw.map((t) => { const val = parseFloat(V.edits.vars[t.var]) || t.value; return `<label><span>${esc(t.label)}</span><input type="range" min="${t.min}" max="${t.max}" step="${t.step}" value="${val}" data-pc-var="${esc(t.var)}" data-pc-unit="${esc(t.unit)}"><em>${esc(val + t.unit)}</em></label>`; }).join('')}</div>` : '';
192
+ const sel = V.sel ? `<p class="pc-sel">${SVG(I.point, 14)}<b>${esc(V.sel.label || V.sel.el)}</b> is in the chat box: say the change.${ib('data-pc-unsel', 'Clear the element', I.x)}</p>` : '';
193
+ const cm = (c.comments || []).filter((x) => !x.send);
194
+ const draft = V.draft ? `<div class="pc-cdraft"><label for="pcCm">Comment${V.draft.label ? ' on ' + esc(V.draft.label) : ''}</label><textarea id="pcCm" rows="2" maxlength="500" placeholder="Say what should change"></textarea><span>${ib('data-pc-cm="send"', 'Send to PMOS as the next change', I.send, 'blue')}${ib('data-pc-cm="keep"', 'Keep for the team', I.keep)}${ib('data-pc-cm="x"', 'Cancel', I.x)}</span></div>` : '';
195
+ const list = cm.length ? `<ol class="pc-cms">${cm.map((x, i) => `<li><span class="pc-pin">${i + 1}</span><span class="w">${x.label ? `<small>on ${esc(x.label)}</small>` : ''}${esc(x.text)}</span>${ib(`data-pc-make="${esc(x.id)}"`, 'Make this change', I.star)}</li>`).join('')}</ol>` : '';
196
+ const sug = suggestion(c);
197
+ const draw = V.mode === 'draw' ? `<canvas class="pc-ink" aria-label="Sketch over the prototype"></canvas><span class="pc-inkacts">${ib('data-pc-ink="attach"', 'Attach the sketch to your next message', I.attach, 'blue')}${ib('data-pc-ink="clear"', 'Clear the sketch', I.x)}</span>` : '';
198
+ return `<section class="pc-card pc-proto" aria-label="The prototype">${making ? `<p class="pc-making"><i></i><i></i><i></i> PMOS is making version ${c.round}${c.working ? '' : ''}.</p>` : ''}`
199
+ + `<div class="pc-dev ${V.device}"><div class="pc-frame" data-pc-frame>${v.url ? '' : '<p class="pc-none">PMOS is making it.</p>'}</div>${draw}</div>${sel}${tweaks}${draft}${list}${sug}</section>`;
200
+ }
201
+ function suggestion(c) {
202
+ // the design sprint runs silently: PMOS recommends good practice as ONE ✦ (canvas PbcChat), here: test it with people once it settles
203
+ const H = (c.history || []).filter((h) => h.round), N = H.length;
204
+ const root = H[H.length - 1], key = 'pmos.pc.sug.' + (root ? root.id : c.id);
205
+ if (N < 3 || c.working || store.get(key)) return '';
206
+ return `<div class="pc-sug"><span class="pc-star" aria-hidden="true">✦</span><p>Version ${c.round} answers the brief. Try it on 3 to 5 people it is for before more polish.</p>${ib(`data-pc-sug="link" data-pc-sugk="${esc(key)}"`, 'Get a test link', I.link, 'blue')}${ib(`data-pc-sug="no" data-pc-sugk="${esc(key)}"`, 'Not now', I.x)}</div>`;
207
+ }
208
+ function flowCard(c, v) {
209
+ const f = (v.data || {}).flow, st = (c.parts || {}).flow;
210
+ if (!f) return `<section class="pc-card pc-flowc" aria-label="The flow"><h3>The flow</h3><p class="pc-none">${esc(st === 'working' ? 'PMOS is drawing it.' : st && st !== 'ok' ? 'Not made this time: ' + st.replace(/^not made: /, '') : 'No flow for this version.')}</p></section>`;
211
+ const L = flowLayout(f), scen = f.scenarios || [];
212
+ const branchOf = (to) => { for (let i = 1; i < scen.length; i += 1) if (scen[i].steps.some((s) => s.screen === to)) return scen[i].id; return ''; };
213
+ const nodes = L.nodes.map((n) => n.kind === 'decision'
214
+ ? `<g class="pc-dn"><path d="M${n.x + n.w / 2} ${n.y}L${n.x + n.w} ${n.y + n.h / 2}L${n.x + n.w / 2} ${n.y + n.h}L${n.x} ${n.y + n.h / 2}Z"/><text text-anchor="middle">${lines(n.title, n.x + n.w / 2, n.y + n.h / 2 + (String(n.title).length > n.chars ? -2 : 4), n.chars, 12)}</text></g>`
215
+ : `<g class="pc-sn${n.main ? '' : ' br'}${V.screen === n.id ? ' on' : ''}" data-pc-screen="${esc(n.id)}" role="button" tabindex="0" aria-label="${esc('Show ' + n.title + ' on the prototype')}"><rect x="${n.x}" y="${n.y}" width="${n.w}" height="${n.h}" rx="8"/><text x="${n.x + 10}" y="${n.y + 15}" class="k">SCREEN</text><text>${lines(n.title, n.x + 10, n.y + 31, 21)}</text></g>`).join('');
216
+ const edges = L.edges.map((e) => { const sc = e.main ? '' : branchOf(e.to); return `<g class="pc-e${e.main ? '' : ' br'}"${sc ? ` data-pc-scen="${esc(sc)}" role="button" tabindex="0" aria-label="${esc('Play ' + (scen.find((x) => x.id === sc) || {}).name)}"` : ''}><path d="${e.d}" marker-end="url(#pcArr)"/>${sc ? `<path class="hit" d="${e.d}"/>` : ''}${e.label ? `<text x="${e.lx}" y="${e.ly}" text-anchor="${e.anchor || 'middle'}">${esc(e.label)}</text>` : ''}</g>`; }).join('');
217
+ const chips = scen.length ? `<div class="pc-scens">${scen.map((s, i) => `<button type="button" class="pc-chip" data-pc-scen="${esc(s.id)}" title="${esc(s.description || '')}">${SVG(I.play, 12)}${esc(i === 0 ? s.name : s.name)}</button>`).join('')}</div>` : '';
218
+ return `<section class="pc-card pc-flowc" aria-label="The flow"><h3>The flow ${upd(c, 'flow')}</h3><div class="pc-svgw"><svg class="pc-flow" width="100%" style="max-width:${L.w}px" viewBox="0 0 ${L.w} ${L.h}" preserveAspectRatio="xMinYMin meet"><defs>${ARROW}</defs>${edges}${nodes}</svg></div>`
219
+ + `<p class="pc-hint">Tap a screen to see it on the prototype. Tap a side branch to play that scenario.</p>${chips}</section>`;
220
+ }
221
+ function copyCard(c, v) {
222
+ if (!V.copy) return '';
223
+ const close = ib('data-pc-copyp', 'Close the page copy', I.x);
224
+ const copy = (v.data || {}).copy || {}, keys = Object.keys(copy);
225
+ if (!keys.length) return `<section class="pc-card pc-copyc pc-side" aria-label="Page copy"><h3>Page copy ${close}</h3><p class="pc-none">${esc(v.url ? 'This version has no editable copy.' : 'PMOS is writing it.')}</p></section>`;
226
+ const changed = new Set((c.updated && c.updated.keys) || []);
227
+ return `<section class="pc-card pc-copyc pc-side" aria-label="Page copy"><h3>Page copy ${upd(c, 'copy')}${close}</h3><div class="pc-copy" role="table">${keys.map((k) => `<div class="pc-cr${changed.has(k) ? ' ch' : ''}" role="row"><span role="rowheader">${esc(human(k))}</span><span role="cell" contenteditable="plaintext-only" spellcheck="true" data-pc-copy="${esc(k)}" aria-label="${esc(human(k))}">${esc(k in V.edits.copy ? V.edits.copy[k] : copy[k])}</span></div>`).join('')}</div>`
228
+ + '<p class="pc-hint">Edit any line: the prototype changes as you type, and the next version keeps it.</p></section>';
229
+ }
230
+ function lanesCard(c, v) {
231
+ const l = (v.data || {}).lanes, st = (c.parts || {}).lanes;
232
+ if (!l) return `<section class="pc-card pc-lanesc" aria-label="Who does what"><h3>Who does what</h3><p class="pc-none">${esc(st === 'working' ? 'PMOS is drawing it.' : st && st !== 'ok' ? 'Not made this time: ' + st.replace(/^not made: /, '') : 'No swimlane for this version.')}</p></section>`;
233
+ const L = lanesLayout(l), chg = new Set((c.updated && c.updated.steps) || []);
234
+ const lanes = L.lanes.map((x, i) => `<g class="pc-ln${i % 2 ? ' alt' : ''}"><rect x="0" y="${x.y}" width="${L.w}" height="${LH}"/><text x="12" y="${x.y + LH / 2 + 4}">${esc(x.name.slice(0, 14))}</text></g>`).join('');
235
+ const boxes = L.boxes.map((b) => `<g class="pc-bx${chg.has(b.n) ? ' ch' : ''}${b.screen ? '' : ' ns'}"${b.screen ? ` data-pc-screen="${esc(b.screen)}" role="button" tabindex="0" aria-label="${esc('Show step ' + b.n + ' on the prototype')}"` : ''}><rect x="${b.x}" y="${b.y}" width="${BW}" height="${BH}" rx="8"/><text text-anchor="middle">${lines(b.title, b.x + BW / 2, b.y + (b.title.length > 21 ? 17 : 24), 21, 12)}</text><circle cx="${b.x}" cy="${b.y}" r="9"/><text class="n" x="${b.x}" y="${b.y + 3.5}" text-anchor="middle">${b.n}</text></g>`).join('');
236
+ const arrows = L.arrows.map((a) => `<path class="pc-ar" d="${a.d}" marker-end="url(#pcArr)"/>`).join('');
237
+ return `<section class="pc-card pc-lanesc" aria-label="Who does what"><h3>Who does what ${upd(c, 'lanes')}</h3><div class="pc-svgw"><svg class="pc-lanes" width="100%" style="max-width:${L.w}px" viewBox="0 0 ${L.w} ${L.h}" preserveAspectRatio="xMinYMin meet"><defs>${ARROW}</defs>${lanes}${arrows}${boxes}</svg></div><p class="pc-hint">Tap a step to see it on the prototype.</p></section>`;
238
+ }
239
+
240
+ /* ── draw ── */
241
+ /** Draw or update the canvas. body: the Viewer's body; c: GET /api/lab/compare's compare (live); o: { at, H } */
242
+ export function draw(body, c, o = {}) {
243
+ if (!body || !c) return;
244
+ Object.assign(V, { at: o.at || V.at || {}, H: o.H || V.H });
245
+ if (c.file && c.data) V.last = c;
246
+ const { v, making } = shown(c), prevFile = V.v && V.v.file;
247
+ // a new version: its own edits, nothing pointed at
248
+ if (prevFile !== v.file) { V.edits = (v.data && v.data.edits) ? { copy: { ...v.data.edits.copy }, vars: { ...v.data.edits.vars } } : { copy: {}, vars: {} }; V.sel = null; V.ready = null; }
249
+ V.c = c; V.v = v;
250
+ let root = body.querySelector(':scope > .pc');
251
+ if (!root) { body.innerHTML = '<div class="pc"></div>'; root = body.querySelector('.pc'); wire(root); }
252
+ V.body = body;
253
+ // keep the frame (and what the PM typed) while the canvas reads again every 2 seconds
254
+ const sig = JSON.stringify([c.id, c.key, c.round, c.file, v.file, c.working, c.updated, c.parts, (c.comments || []).length, V.mode, V.device, V.sel && V.sel.el, !!V.draft, (c.history || []).length, c.state, V.copy]);
255
+ const focus = document.activeElement && root.contains(document.activeElement) && document.activeElement.matches('[data-pc-copy],textarea,input');
256
+ if (sig === V.sig && root.firstChild) return;
257
+ if (focus && prevFile === v.file) return; // the PM is typing in this version: draw on a later read
258
+ V.sig = sig;
259
+ const frame = root.querySelector('.pc-frame iframe'), keepFrame = frame && V.frameUrl === frameUrl(v);
260
+ const draftText = root.querySelector('#pcCm') ? root.querySelector('#pcCm').value : '';
261
+ if (keepFrame) frame.remove();
262
+ root.innerHTML = barHtml(c, v) + trayHtml(c) + `<div class="pc-vp"><div class="pc-board">${protoCard(c, v, making)}<div class="pc-col">${flowCard(c, v)}</div>${lanesCard(c, v)}</div></div>` + copyCard(c, v) + (V.play ? playHtml(v) : '');
263
+ const slot = root.querySelector('[data-pc-frame]');
264
+ if (slot && v.url) {
265
+ if (keepFrame) slot.appendChild(frame);
266
+ else { V.frameUrl = frameUrl(v); V.ready = null; slot.innerHTML = `<iframe src="${esc(V.frameUrl)}" sandbox="allow-scripts" title="${esc('The prototype, version ' + (v.round || 1))}"></iframe>`; }
267
+ }
268
+ if (draftText && root.querySelector('#pcCm')) root.querySelector('#pcCm').value = draftText;
269
+ applyZoom(root);
270
+ if (V.mode === 'draw') ink(root);
271
+ if (keepFrame) { toFrame({ t: 'mode', mode: V.play ? 'view' : V.mode === 'draw' ? 'view' : V.mode }); pins(); }
272
+ if (V.play) startPlay(V.play.id, V.play.i);
273
+ if (V.draft && root.querySelector('#pcCm')) root.querySelector('#pcCm').focus();
274
+ }
275
+ function applyZoom(root) {
276
+ const b = root.querySelector('.pc-board'), vp = root.querySelector('.pc-vp'); if (!b || !vp) return;
277
+ let z = V.zoom;
278
+ if (!z) { b.style.zoom = 1; z = Math.max(0.4, Math.min(1, (vp.clientWidth - 24) / Math.max(1, b.scrollWidth))); }
279
+ b.style.zoom = z;
280
+ const zl = root.querySelector('.pc-z'); if (zl) zl.textContent = Math.round(z * 100) + '%';
281
+ }
282
+ function pins() {
283
+ const cm = ((V.c && V.c.comments) || []).filter((x) => !x.send);
284
+ toFrame({ t: 'pins', pins: cm.map((x, i) => ({ n: i + 1, el: x.el, x: x.x, y: x.y })) });
285
+ }
286
+
287
+ /* ── the frame talks back ── */
288
+ if (typeof window !== 'undefined') window.addEventListener('message', (e) => {
289
+ const m = e.data; if (!m || m.pmos !== 1 || !V.body) return;
290
+ const fr = V.body.querySelector('.pc-frame iframe'), pf = V.body.querySelector('.pc-pframe iframe');
291
+ if (pf && e.source === pf.contentWindow) return playMsg(m, pf);
292
+ if (!fr || e.source !== fr.contentWindow) return;
293
+ if (m.t === 'ready') {
294
+ V.ready = m;
295
+ if (Object.keys(V.edits.copy).length) toFrame({ t: 'copyAll', copy: V.edits.copy });
296
+ if (Object.keys(V.edits.vars).length) toFrame({ t: 'vars', vars: V.edits.vars });
297
+ toFrame({ t: 'mode', mode: V.mode === 'draw' ? 'view' : V.mode });
298
+ if (V.screen) toFrame({ t: 'screen', id: V.screen });
299
+ if (V.sel) toFrame({ t: 'sel', el: V.sel.el });
300
+ pins();
301
+ } else if (m.t === 'screen') {
302
+ V.screen = String(m.id || '');
303
+ V.body.querySelectorAll('.pc-sn').forEach((g) => g.classList.toggle('on', g.dataset.pcScreen === V.screen));
304
+ } else if (m.t === 'point') {
305
+ // Point, then say (canvas PbcPoint): the element becomes a chip in the chat box, with Tweaks for it here
306
+ V.sel = { el: String(m.el || ''), label: String(m.label || '').slice(0, 80) };
307
+ fire('pmos:point', { ini: V.c && V.c.ini, ...V.sel });
308
+ V.sig = ''; draw(V.body, V.c);
309
+ } else if (m.t === 'pin') {
310
+ V.draft = { el: String(m.el || ''), label: String(m.label || '').slice(0, 80), x: m.x, y: m.y };
311
+ V.sig = ''; draw(V.body, V.c);
312
+ }
313
+ });
314
+
315
+ /* ── presses ── */
316
+ function wire(root) {
317
+ root.addEventListener('click', (e) => {
318
+ const b = e.target.closest('button, [data-pc-screen], [data-pc-scen]'); if (!b || !root.contains(b)) return;
319
+ const d = b.dataset;
320
+ if (d.pcMode) { setMode(V.mode === d.pcMode ? 'view' : d.pcMode); return; }
321
+ if ('pcCopyp' in d) { V.copy = !V.copy; V.sig = ''; draw(V.body, V.c); return; }
322
+ if (d.pcDev) { V.device = d.pcDev; store.set('pmos.pc.device', V.device); V.sig = ''; draw(V.body, V.c); return; }
323
+ if (d.pcZoom != null) { const k = Number(d.pcZoom); V.zoom = k === 0 ? 0 : Math.max(0.4, Math.min(1.6, Math.round(((V.zoom || currentZoom()) + k * 0.1) * 10) / 10)); store.set('pmos.pc.zoom', V.zoom ? String(V.zoom) : null); applyZoom(root); return; }
324
+ if ('pcPlay' in d) { const sc = ((V.v.data || {}).flow || {}).scenarios || []; startPlay(sc.length ? sc[0].id : '', 0, true); return; }
325
+ if (d.pcFrom) { fire('pmos:from', { ini: V.c.ini, n: Number(d.pcFrom) }); say('The next change you send continues from version ' + d.pcFrom + '.'); return; }
326
+ if (d.pcScreen) { V.screen = d.pcScreen; toFrame({ t: 'screen', id: d.pcScreen }); return; }
327
+ if (d.pcScen) { startPlay(d.pcScen, 0, true); return; }
328
+ if ('pcUnsel' in d) { V.sel = null; toFrame({ t: 'sel', el: '' }); fire('pmos:point', { ini: V.c.ini, el: '', label: '' }); V.sig = ''; draw(V.body, V.c); return; }
329
+ if (d.pcCm) { comment(d.pcCm); return; }
330
+ if (d.pcMake) { const x = (V.c.comments || []).find((y) => y.id === d.pcMake); if (x) fire('pmos:say', { ini: V.c.ini, text: (x.label || x.el ? `[On: ${x.label || x.el}${x.el ? ' · ' + x.el : ''}] ` : '') + x.text }); return; }
331
+ if (d.pcSug) { if (d.pcSug === 'link') testLink(); store.set(d.pcSugk, '1'); V.sig = ''; draw(V.body, V.c); return; }
332
+ if (d.pcInk) { if (d.pcInk === 'clear') clearInk(); else attachInk(); return; }
333
+ if (d.pcTray) { tray(d.pcTray); return; }
334
+ if (d.pcPlayx) { if (d.pcPlayx === 'close') { V.play = null; const p = root.querySelector('.pc-play'); if (p) p.remove(); } else startPlay(V.play.id, 0); return; }
335
+ if (d.pcPlaysc) { startPlay(d.pcPlaysc, 0, true); }
336
+ });
337
+ root.addEventListener('keydown', (e) => { if ((e.key === 'Enter' || e.key === ' ') && e.target.matches('[data-pc-screen],[data-pc-scen]') && e.target.tagName !== 'BUTTON') { e.preventDefault(); e.target.dispatchEvent(new MouseEvent('click', { bubbles: true })); } });
338
+ root.addEventListener('input', (e) => {
339
+ const t = e.target;
340
+ if (t.matches('[data-pc-copy]')) { const k = t.dataset.pcCopy, text = t.textContent; V.edits.copy[k] = text; toFrame({ t: 'copy', key: k, text }); save({ copy: { [k]: text } }); }
341
+ else if (t.matches('[data-pc-var]')) { const val = t.value + (t.dataset.pcUnit || ''); V.edits.vars[t.dataset.pcVar] = val; toFrame({ t: 'vars', vars: { [t.dataset.pcVar]: val } }); const em = t.parentElement.querySelector('em'); if (em) em.textContent = val; save({ vars: { [t.dataset.pcVar]: val } }); }
342
+ });
343
+ }
344
+ const currentZoom = () => { const b = V.body && V.body.querySelector('.pc-board'); return (b && Number(b.style.zoom)) || 1; };
345
+ function setMode(m) {
346
+ V.mode = m; if (m !== 'comment') V.draft = null;
347
+ toFrame({ t: 'mode', mode: m === 'draw' ? 'view' : m });
348
+ V.sig = ''; draw(V.body, V.c);
349
+ }
350
+ // the PM's copy edits and tweaks are kept with the version (edits.json), so the next version reads them
351
+ function save(part) {
352
+ V.pend = { copy: { ...((V.pend && V.pend.copy) || {}), ...(part.copy || {}) }, vars: { ...((V.pend && V.pend.vars) || {}), ...(part.vars || {}) } };
353
+ clearTimeout(V.saveT);
354
+ const file = V.v && V.v.file;
355
+ V.saveT = setTimeout(async () => {
356
+ const body = V.pend; V.pend = null; if (!file) return;
357
+ const r = await pmPost('/api/lab/edit', { ws: (V.at || {}).ws, file, ...body }).catch(() => null);
358
+ if (!r || r.ok === false) say((r && r.error) || 'The edit was not saved.');
359
+ }, 700);
360
+ }
361
+ async function comment(how) {
362
+ const ta = V.body.querySelector('#pcCm'), text = ta ? ta.value.trim() : '', dft = V.draft;
363
+ if (how === 'x' || !dft) { V.draft = null; V.sig = ''; draw(V.body, V.c); return; }
364
+ if (!text) { say('Say what should change first.'); return; }
365
+ const r = await pmPost('/api/lab/comment', { ws: (V.at || {}).ws, ini: V.c.ini, file: V.v.file, el: dft.el, label: dft.label, x: dft.x, y: dft.y, text, send: how === 'send' }).catch(() => null);
366
+ if (!r || r.ok === false) { say((r && r.error) || 'The comment was not saved.'); return; }
367
+ V.draft = null;
368
+ // Send to PMOS: the comment is the next change, said in the chat about that element
369
+ if (how === 'send') fire('pmos:say', { ini: V.c.ini, text: (dft.label || dft.el ? `[On: ${dft.label || dft.el}${dft.el ? ' · ' + dft.el : ''}] ` : '') + text });
370
+ else say('Kept for the team.');
371
+ V.c.comments = [...(V.c.comments || []), { id: r.id, el: dft.el, label: dft.label, text, x: dft.x, y: dft.y, send: how === 'send' }];
372
+ V.sig = ''; draw(V.body, V.c);
373
+ }
374
+ async function testLink() {
375
+ const at = V.at || {}, url = location.origin + '/pm/present?ws=' + encodeURIComponent(at.ws || '') + '&board=' + encodeURIComponent(at.board || V.c.board || '') + '&id=' + encodeURIComponent(V.c.id);
376
+ try { await navigator.clipboard.writeText(url); say('The test link is copied. It opens the prototype on a clean screen.'); } catch { say('Test link: ' + url); }
377
+ }
378
+ async function tray(a) {
379
+ const at = V.at || {}, c = V.c;
380
+ if (a === 'keep') {
381
+ const r = await pmPost('/api/proposals/keep', { ws: at.ws, board: at.board || c.board, initiative: c.ini, ids: [c.id], choices: { [c.id]: c.key } }).catch(() => null);
382
+ say(r && r.ok !== false ? (r.said || 'Kept ' + c.key + '.') : (r && r.error) || 'Nothing was kept.');
383
+ } else {
384
+ const r = await pmPost('/api/proposals/drop', { ws: at.ws, board: at.board || c.board, initiative: c.ini, sig: c.sig }).catch(() => null);
385
+ say(r && r.ok !== false ? 'Closed these ways.' : (r && r.error) || 'Nothing was changed.');
386
+ }
387
+ if (V.H && V.H.reload) V.H.reload();
388
+ if (V.H && V.H.load) V.H.load();
389
+ }
390
+
391
+ /* ── Draw: a sketch goes with the next message as the reference ── */
392
+ function ink(root) {
393
+ const cv = root.querySelector('.pc-ink'); if (!cv) return;
394
+ const box = cv.parentElement.getBoundingClientRect(), z = currentZoom();
395
+ cv.width = Math.round(box.width / z); cv.height = Math.round(box.height / z);
396
+ const g = cv.getContext('2d'); g.lineWidth = 3; g.lineCap = 'round'; g.lineJoin = 'round'; g.strokeStyle = getComputedStyle(cv).getPropertyValue('--cz-red').trim() || 'red';
397
+ let on = false;
398
+ const pt = (e) => { const r = cv.getBoundingClientRect(); return [(e.clientX - r.left) * cv.width / r.width, (e.clientY - r.top) * cv.height / r.height]; };
399
+ cv.onpointerdown = (e) => { on = true; cv.setPointerCapture(e.pointerId); const [x, y] = pt(e); g.beginPath(); g.moveTo(x, y); };
400
+ cv.onpointermove = (e) => { if (!on) return; const [x, y] = pt(e); g.lineTo(x, y); g.stroke(); V.strokes += 1; };
401
+ cv.onpointerup = () => { on = false; };
402
+ }
403
+ function clearInk() { const cv = V.body.querySelector('.pc-ink'); if (cv) cv.getContext('2d').clearRect(0, 0, cv.width, cv.height); V.strokes = 0; }
404
+ async function attachInk() {
405
+ const cv = V.body.querySelector('.pc-ink'); if (!cv || !V.strokes) { say('Draw on the prototype first.'); return; }
406
+ const out = document.createElement('canvas'); out.width = cv.width; out.height = cv.height;
407
+ const g = out.getContext('2d'); g.fillStyle = getComputedStyle(cv).getPropertyValue('--cz-onsolid').trim() || 'white'; g.fillRect(0, 0, out.width, out.height); g.drawImage(cv, 0, 0);
408
+ const blob = await new Promise((r) => out.toBlob(r, 'image/png'));
409
+ const name = 'sketch-' + Date.now().toString(36) + '.png';
410
+ const res = await fetch('/api/chat-file?key=' + encodeURIComponent('init:' + V.c.ini) + '&name=' + encodeURIComponent(name), { method: 'POST', credentials: 'same-origin', headers: { ...pmHeaders(), 'Content-Type': 'application/octet-stream' }, body: blob }).then((x) => x.json()).catch(() => null);
411
+ if (!res || !res.ok) { say((res && res.error) || 'The sketch was not attached.'); return; }
412
+ const M = await import('./premium-attach.js');
413
+ M.attachSaved({ name, size: blob.size, saved: res.name, path: res.path });
414
+ say('The sketch goes with your next message as the reference.');
415
+ clearInk(); setMode('view');
416
+ }
417
+
418
+ /* ── Play (canvas PbcPlay) ── */
419
+ function playHtml(v) {
420
+ const sc = ((v.data || {}).flow || {}).scenarios || [], p = V.play, s = sc.find((x) => x.id === p.id), step = s ? s.steps[Math.min(p.i, s.steps.length - 1)] : null;
421
+ const done = s && p.i >= s.steps.length - 1;
422
+ return `<div class="pc-play" role="dialog" aria-label="Play the prototype"><div class="pc-pbar">${sc.map((x) => `<button type="button" class="pc-chip" data-pc-playsc="${esc(x.id)}" aria-pressed="${x.id === p.id}">${esc(x.name)}</button>`).join('')}<span class="pc-sp"></span>`
423
+ + `${ib('data-pc-playx="restart"', 'Restart', I.restart)}${ib('data-pc-playx="close"', 'Close Play', I.x)}</div>`
424
+ + `<p class="pc-pstep">${s ? (done ? `<b>Done:</b> ${esc(s.name)}. ${esc(step && step.say ? step.say : '')}` : `<b>Step ${p.i + 1} of ${s.steps.length}</b> ${esc(step && step.say ? step.say : 'Tap where the user would tap.')}`) : 'This version has no scenarios yet. Ask for one in the chat.'}</p>`
425
+ + `<div class="pc-pframe ${V.device}">${v.url ? `<iframe src="${esc(frameUrl(v))}" sandbox="allow-scripts" title="Play the prototype"></iframe>` : ''}</div></div>`;
426
+ }
427
+ function startPlay(id, i = 0, fresh = false) {
428
+ const root = V.body && V.body.querySelector('.pc'); if (!root) return;
429
+ const keep = !fresh && V.play && V.play.id === id ? root.querySelector('.pc-pframe iframe') : null;
430
+ V.play = { id, i };
431
+ const old = root.querySelector('.pc-play'); if (old) { if (keep) keep.remove(); old.remove(); }
432
+ root.insertAdjacentHTML('beforeend', playHtml(V.v));
433
+ if (keep) { const slot = root.querySelector('.pc-pframe'); slot.innerHTML = ''; slot.appendChild(keep); playGo(keep); }
434
+ }
435
+ function playGo(fr) {
436
+ const sc = ((V.v.data || {}).flow || {}).scenarios || [], s = sc.find((x) => x.id === (V.play || {}).id);
437
+ toFrame({ t: 'mode', mode: 'play' }, fr);
438
+ if (s) toFrame({ t: 'screen', id: s.steps[Math.min(V.play.i, s.steps.length - 1)].screen }, fr);
439
+ if (Object.keys(V.edits.copy).length) toFrame({ t: 'copyAll', copy: V.edits.copy }, fr);
440
+ if (Object.keys(V.edits.vars).length) toFrame({ t: 'vars', vars: V.edits.vars }, fr);
441
+ }
442
+ function playMsg(m, fr) {
443
+ if (!V.play) return;
444
+ if (m.t === 'ready') { playGo(fr); return; }
445
+ if (m.t !== 'tap') return;
446
+ const sc = ((V.v.data || {}).flow || {}).scenarios || [], s = sc.find((x) => x.id === V.play.id); if (!s) return;
447
+ const step = s.steps[V.play.i]; if (!step || V.play.i >= s.steps.length - 1) return;
448
+ const next = s.steps[V.play.i + 1];
449
+ // a tap on the hotspot this step needs moves on; a tap that goes to the next screen counts too; a miss shows the hotspots
450
+ if ((step.tap && m.el === step.tap) || (!step.tap && m.go === next.screen) || (m.go && m.go === next.screen)) { V.play.i += 1; startPlay(V.play.id, V.play.i); }
451
+ else toFrame({ t: 'hint', els: step.tap ? [step.tap] : [] }, fr);
452
+ }
453
+
454
+ /* ── the chat's Version n tag ── */
455
+ /** Show version n of the initiative's newest round (pm/home-chat.js, a tap on a Version n tag). */
456
+ export async function openVersion({ ws, board = '', ini, n }) {
457
+ const r = await pmGet('/api/lab/rounds?ws=' + encodeURIComponent(ws || '') + '&initiative=' + encodeURIComponent(ini)).catch(() => null);
458
+ const root = r && r.ok && (r.rounds || [])[0]; if (!root) { say('That version is no longer here.'); return; }
459
+ const c = await pmGet('/api/lab/compare?ws=' + encodeURIComponent(ws || '') + '&board=' + encodeURIComponent(board) + '&id=' + encodeURIComponent(root.id)).catch(() => null);
460
+ const h = c && c.ok ? (c.compare.history || []).find((x) => x.round === Number(n)) : null;
461
+ const LC = await import('./cozy-lab.js');
462
+ LC.openCompare({ where: { ws, board }, id: h ? h.id : root.id, H: V.H });
463
+ }
464
+ if (typeof window !== 'undefined') {
465
+ window.addEventListener('keydown', (e) => {
466
+ if (!V.body || !V.body.isConnected || !V.body.querySelector('.pc') || e.metaKey || e.ctrlKey || e.altKey) return;
467
+ const t = e.target; if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
468
+ const k = e.key.toLowerCase();
469
+ if (k === 's') setMode(V.mode === 'point' ? 'view' : 'point');
470
+ else if (k === 'c') setMode(V.mode === 'comment' ? 'view' : 'comment');
471
+ else if (k === 'd') setMode(V.mode === 'draw' ? 'view' : 'draw');
472
+ else if (k === 'escape' && (V.mode !== 'view' || V.play)) { if (V.play) { V.play = null; const p = V.body.querySelector('.pc-play'); if (p) p.remove(); } else setMode('view'); }
473
+ });
474
+ }
@@ -1142,6 +1142,8 @@ function iniTarget(id) {
1142
1142
  const h = S.H || {};
1143
1143
  return { key: 'init:' + id, ini: id, ws: (otherIni(id) || {}).ws || WS || undefined, title: iniTitle(id), about: iniTitle(id), newChat: () => newIn(id), sub: (S.IMid === id && h.stage) || '', scope: scopeOf(id), rich: true, placeholder: 'Message PMOS about ' + iniTitle(id),
1144
1144
  empty: 'Ask about ' + iniTitle(id) + '. PMOS reads its records and works in a real Claude Code session.', also: alsoOf(id),
1145
+ // a prototype the sentence started (lib/routes-briefing-premium.js liveAsk): the Viewer opens it beside the chat, and shows it as it renders
1146
+ onSent: (r) => { if (r && r.live && r.live.id) import('./cozy-lab.js').then((LC) => LC.openCompare({ where: { ws: r.live.ws || WS, board: r.live.board || '' }, id: r.live.id, H: { toast } })).catch(() => {}); },
1145
1147
  // the initiative's conversation opens on where it stands (AgInitYou), until it has messages of its own
1146
1148
  intro: S.IMid === id && h.cur ? { role: CLAUDE, onlyEmpty: true, text: h.cur + '. ' + h.doneOf + '.' + (h.rest.length ? ' Waiting: ' + h.rest.map((x) => x.label).join(', ') + '.' : ''), pills: [{ label: h.cta, primary: true, go: () => cta() }, { label: 'Discuss', go: () => chat.focus() }] } : undefined, context: h.payoff ? 'Initiative ' + id + ': ' + (h.stage || '') + '. ' + (h.time || '') : undefined };
1147
1149
  }