create-pmos 0.320.0 → 0.322.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,477 @@
1
+ /* pm/premium-vw-doc.js — a markdown document as a page in the premium viewer (initiative premium-viewer, S2; planning/prd/premium-viewer-prd.md R2).
2
+ * One document, one page: read it, edit it in place (or as Markdown), and see an agent's proposed change applied and highlighted, with one Keep and one
3
+ * Undo all. Built on the viewer frame (premium-viewer.js) and the existing /api/doc-sheet routes: log and at to read, edit to save, proposals, accept and
4
+ * reject for an agent's edit, ask to request one. Nothing here is stored anywhere else. The pure half is premium-vw-doc-model.js. */
5
+ import { pmPost } from './http.js';
6
+ import { vwOpen, vwStyle, vwConfirm } from './premium-viewer.js';
7
+ import { $, $$, esc, toast, AI, CHECK } from './premium-shell.js';
8
+ import { editBody, acceptBody, rejectBody, askBody, askLine, relationsOf, copyKindOf, copyView } from './premium-doc-edit.js';
9
+ import { bodyHtml, pageHead, propHtml, splitDoc, overlay, overlayLine, mergeEdit, readMinutes, dayOf, PANELS } from './premium-vw-doc-model.js';
10
+
11
+ const I = (d) => `<svg class="i" viewBox="0 0 24 24" aria-hidden="true">${d}</svg>`;
12
+ const IC = {
13
+ dot: I('<circle cx="12" cy="12" r="4"/>'), chev: I('<path d="M9 6l6 6-6 6"/>'),
14
+ doc: I('<path d="M7 3h7l5 5v13H7z"/><path d="M14 3v5h5"/>'), pen: I('<path d="M4 20h4L19 9l-4-4L4 16z"/>'), md: I('<path d="M3 6h18v12H3z"/><path d="M6 15V9l3 3 3-3v6M16 9v6M14 13l2 2 2-2"/>'),
15
+ undo: I('<path d="M9 14L4 9l5-5"/><path d="M4 9h11a5 5 0 010 10h-3"/>'), redo: I('<path d="M15 14l5-5-5-5"/><path d="M20 9H9a5 5 0 000 10h3"/>'),
16
+ ul: I('<path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4.5" cy="6" r="1"/><circle cx="4.5" cy="12" r="1"/><circle cx="4.5" cy="18" r="1"/>'), ol: I('<path d="M10 6h10M10 12h10M10 18h10M4 5h1v4M4 14h2l-2 3h2"/>'),
17
+ task: I('<path d="M4 5h5v5H4zM4 14h5v5H4z"/><path d="M12 7h8M12 16h8"/>'), link: I('<path d="M10 14a4 4 0 005.7 0l3-3a4 4 0 00-5.7-5.7l-1 1M14 10a4 4 0 00-5.7 0l-3 3a4 4 0 005.7 5.7l1-1"/>'),
18
+ tbl: I('<path d="M3 5h18v14H3zM3 10h18M9 10v9M15 10v9"/>'), info: I('<circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8v.01"/>'), code: I('<path d="M8 8l-4 4 4 4M16 8l4 4-4 4"/>'), plus: I('<path d="M12 5v14M5 12h14"/>'),
19
+ };
20
+ const whoOf = (r) => (r.git && r.git.author) || (r.text_by === 'agent' || r.by === 'agent' ? 'The agent' : r.by === 'pm' ? 'You' : r.by === 'baseline' || r.via === 'first' ? 'Before the sheet' : r.via === 'outside' ? 'Outside PMOS' : String(r.by || ''));
21
+ async function getJson(url, init) { try { const r = await fetch(url, Object.assign({ credentials: 'same-origin' }, init || {})); return await r.json(); } catch { return null; } }
22
+
23
+ /* ── page body → markdown, so a saved page stays a plain .md file ── */
24
+ function inlineMd(n) {
25
+ return [...n.childNodes].map((c) => {
26
+ if (c.nodeType === 3) return c.textContent.replace(/ /g, ' ').replace(/​/g, '');
27
+ if (c.nodeType !== 1) return '';
28
+ if (c.matches('.lz')) return `:status[${c.textContent.trim()}]`;
29
+ if (c.matches('.dt')) return c.dataset.dt;
30
+ if (c.matches('.chk,.pi')) return '';
31
+ const s = inlineMd(c), t = c.tagName;
32
+ if (t === 'STRONG' || t === 'B') return s.trim() ? `**${s}**` : s;
33
+ if (t === 'EM' || t === 'I') return s.trim() ? `_${s}_` : s;
34
+ if (t === 'S' || t === 'STRIKE' || t === 'DEL') return s.trim() ? `~~${s}~~` : s;
35
+ if (t === 'CODE') return '`' + c.textContent + '`';
36
+ if (t === 'A') return `[${s}](${c.getAttribute('href') || ''})`;
37
+ if (t === 'BR') return ' ';
38
+ return s;
39
+ }).join('');
40
+ }
41
+ export function domToMd(root) {
42
+ const B = [];
43
+ for (const c of root.children) {
44
+ const t = c.tagName, cl = c.classList;
45
+ if (cl.contains('vwchg')) { if (!c.dataset.hidden) { const inner = $('.vwcb', c); if (inner) B.push(domToMd(inner)); } continue; }
46
+ if (cl.contains('vwbefore') || cl.contains('vwcl')) continue;
47
+ if (cl.contains('pnl')) B.push(`> [!${String(c.dataset.k || 'note').toUpperCase()}]\n` + [...$('.pc', c).children].map((x) => '> ' + inlineMd(x).trim()).join('\n>\n'));
48
+ else if (cl.contains('tw') || t === 'TABLE') {
49
+ const rows = [...c.querySelectorAll('tr')].map((r) => '| ' + [...r.children].map((x) => inlineMd(x).trim().replace(/\|/g, '\\|')).join(' | ') + ' |');
50
+ if (rows.length) { const n = c.querySelector('tr').children.length; rows.splice(1, 0, '|' + Array(n).fill('---').join('|') + '|'); B.push(rows.join('\n')); }
51
+ } else if (cl.contains('cb')) B.push('```' + (c.dataset.lang || '') + '\n' + ($('pre', c) || c).textContent.replace(/\n$/, '') + '\n```');
52
+ else if (/^H[1-6]$/.test(t)) B.push('#'.repeat(+(c.dataset.md || Math.max(2, +t[1]))) + ' ' + inlineMd(c).trim());
53
+ else if (t === 'UL' && cl.contains('tasks')) B.push([...c.children].map((li) => `- [${li.dataset.done === 'true' ? 'x' : ' '}] ${inlineMd(li).trim()}`).join('\n'));
54
+ else if (t === 'UL' || t === 'OL') B.push([...c.children].map((li, k) => `${t === 'OL' ? k + 1 + '.' : '-'} ${inlineMd(li).trim()}`).join('\n'));
55
+ else if (t === 'BLOCKQUOTE') B.push('> ' + inlineMd(c).trim());
56
+ else if (t === 'HR') B.push('---');
57
+ else if (t === 'DETAILS') { const sm = $('summary', c); B.push(`<details><summary>${sm ? sm.textContent.trim() : 'Details'}</summary>\n\n${domToMd($('div', c) || c)}\n\n</details>`); }
58
+ else if (t === 'DIV') { const s = domToMd(c); if (s.trim()) B.push(s); }
59
+ else { const s = inlineMd(c).trim(); if (s) B.push(s); }
60
+ }
61
+ return B.join('\n\n');
62
+ }
63
+
64
+ /* ── the editor's blocks ── */
65
+ const BLOCKS = [
66
+ { k: 'p', t: 'Normal text', g: 'Aa' }, { k: 'h2', t: 'Heading 1', g: 'H1', kbd: '##' }, { k: 'h3', t: 'Heading 2', g: 'H2', kbd: '###' }, { k: 'h4', t: 'Heading 3', g: 'H3', kbd: '####' },
67
+ { k: 'ul', t: 'Bulleted list', ic: 'ul', kbd: '-' }, { k: 'ol', t: 'Numbered list', ic: 'ol', kbd: '1.' }, { k: 'task', t: 'Task list', ic: 'task', kbd: '[]' }, { k: 'quote', t: 'Quote', g: '“', kbd: '>' },
68
+ { k: 'table', t: 'Table', ic: 'tbl' }, { k: 'info', t: 'Info panel', ic: 'info' }, { k: 'note', t: 'Note panel', ic: 'info' }, { k: 'warning', t: 'Warning panel', ic: 'info' }, { k: 'success', t: 'Success panel', ic: 'info' }, { k: 'decision', t: 'Decision', ic: 'info' },
69
+ { k: 'status', t: 'Status label', ic: 'dot' }, { k: 'code', t: 'Code block', ic: 'code', kbd: '```' }, { k: 'expand', t: 'Expand', ic: 'chev' }, { k: 'hr', t: 'Divider', g: '—', kbd: '---' },
70
+ ];
71
+ const STATUSES = ['To do', 'In progress', 'In review', 'Done', 'Blocked'];
72
+ const tb = (c, label, icon) => `<button type="button" class="vwtb" data-c="${c}" title="${label}" aria-label="${label}">${IC[icon] || icon}</button>`;
73
+
74
+ /** Open a markdown file as a page in the viewer. `d` is { path, title }; `ctx` gives { ws(), onWrite() } — onWrite runs after the file or a proposal changed,
75
+ * so the page that opened it can read again. */
76
+ export function openDocPage(d, ctx = {}) {
77
+ if (!d || !d.path) return null;
78
+ vwStyle('doc');
79
+ const id = 'doc:' + d.path, prior = OPEN.get(id);
80
+ if (prior) return prior.show(ctx); // the same document opened again: show its tab and read it again; what is typed and not saved stays
81
+ return makePage(d, ctx);
82
+ }
83
+ const OPEN = new Map();
84
+ function makePage(d, ctx) {
85
+ const id = 'doc:' + d.path;
86
+ const ws = () => (ctx.ws ? ctx.ws() : '') || '';
87
+ const wsq = () => (ws() ? '&ws=' + encodeURIComponent(ws()) : '');
88
+ // work: the text being edited and not saved yet (null when nothing is); base: the page serialized as drawn, so a save writes back only what was typed
89
+ const P = { d, more: null, health: null, lib: undefined, copies: null, cpUrl: '', cpMsg: '', checkRun: null, text: null, log: null, props: null, kept: null, mode: 'read', busy: false, msg: '', why: '', err: null, base: null, work: null, ask: null, askOpen: false, askText: '', pop: null };
90
+ let el = null;
91
+ const v = () => ((P.log && P.log.revisions) || []).length;
92
+ const openProp = () => (P.props || []).filter((p) => p.state === 'proposed').slice(-1)[0] || null;
93
+
94
+ async function load() {
95
+ const p = encodeURIComponent(d.path);
96
+ P.err = null;
97
+ const [lg, pr] = await Promise.all([getJson('/api/doc-sheet/log?path=' + p + wsq()), getJson('/api/doc-sheet/proposals?path=' + p + wsq())]);
98
+ P.log = lg && lg.ok ? lg : null;
99
+ P.props = pr && pr.ok ? pr.proposals || [] : [];
100
+ const revs = P.log ? P.log.revisions || [] : [];
101
+ const at = revs.length ? await getJson('/api/doc-sheet/at?path=' + p + '&rev=' + revs[revs.length - 1].rev + wsq()) : null;
102
+ if (at && at.ok) P.text = at.text; else { P.text = null; P.err = (at && at.error) || (lg && lg.error) || 'The file could not be read.'; }
103
+ P.kept = null; draw();
104
+ loadHealth(); loadCopies(); if (P.more === 'links') loadLib();
105
+ }
106
+ /* ── Health, Links and Copies: the sheet's own reads (POST /api/doc-health/check, GET /api/docs/library, GET /api/docs), drawn under the bar ── */
107
+ async function loadHealth() {
108
+ const h = await getJson('/api/doc-health/check', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path: d.path, ws: ws() }) });
109
+ P.health = h && h.ok !== false && h.health ? h.health : { err: (h && h.error) || 'The health check could not run.' }; draw();
110
+ }
111
+ async function loadLib() {
112
+ P.lib = null; draw();
113
+ const j = await getJson('/api/docs/library?' + wsq().slice(1));
114
+ P.lib = j && j.ok ? j : { err: (j && j.error) || 'The document graph could not be read.' }; draw();
115
+ }
116
+ async function loadCopies() {
117
+ const j = await getJson('/api/docs?' + wsq().slice(1));
118
+ if (!j || j.ok === false) { P.copies = P.copies || []; P.cpMsg = (j && j.error) || 'The copies could not be read.'; }
119
+ else { const x = (j.docs || []).find((r) => r.path === d.path); P.copies = x ? x.links || [] : []; P.checkRun = j.session || j.open || null; }
120
+ draw();
121
+ }
122
+ function moreBar() {
123
+ const hc = P.health && !P.health.err && P.health.total ? `${P.health.passed} of ${P.health.total}` : '';
124
+ const R = P.lib && !P.lib.err ? relationsOf(P.lib, d.path, d.iniName) : null;
125
+ const cps = (P.copies || []).map(copyView);
126
+ const b = (k, label, n, tone) => `<button type="button" class="vwchip${tone ? ' ' + tone : ''}" data-vd="more:${k}" aria-expanded="${P.more === k}">${label}${n ? ` <em>${esc(n)}</em>` : ''}</button>`;
127
+ return `<div class="vwmore" role="group" aria-label="About this document">${b('health', 'Health', hc, hc ? (P.health.passed === P.health.total ? 'ok' : 'warn') : '')}${b('links', 'Links', R ? String(R.count) : '')}${b('copies', 'Copies', P.copies ? String(cps.length) : '', cps.some((c) => c.tone === 'warn') ? 'warn' : '')}</div>`
128
+ + (P.more ? `<div class="vwmp" role="region" aria-label="${esc({ health: 'Health', links: 'Links', copies: 'Copies' }[P.more])}">${P.more === 'health' ? healthHtml() : P.more === 'links' ? linksHtml(R) : copiesHtml(cps)}</div>` : '');
129
+ }
130
+ function healthHtml() {
131
+ const h = P.health;
132
+ if (!h) return '<p class="vwmut">Checking the document.</p>';
133
+ if (h.err) return `<p class="vwmut">${esc(h.err)}</p>`;
134
+ return `<p class="vwmut">${h.passed} of ${h.total} checks that had the input they need passed. A check with no input is not counted.</p>`
135
+ + `<div class="vwck">${(h.checks || []).map((c) => `<div class="vwckr ${c.pass === true ? 'ok' : c.pass === false ? 'no' : 'na'}"><i class="ckdot" aria-hidden="true"></i><b>${esc(c.id)}</b><span>${c.pass === true ? 'Passed' : c.pass === false ? 'Not passed' : 'No input'}</span>${c.reason ? `<small>${esc(c.reason)}</small>` : ''}</div>`).join('')}</div>`;
136
+ }
137
+ function linksHtml(R) {
138
+ if (P.lib === null || P.lib === undefined) return '<p class="vwmut">Reading the document graph.</p>';
139
+ if (P.lib.err) return `<p class="vwmut">${esc(P.lib.err)}</p>`;
140
+ const ST = { drift: 'Out of step', conflict: 'Conflict', missing: 'Missing', ahead: 'PMOS ahead' };
141
+ const grp = (h, list) => (list.length ? `<div class="vwlg"><p class="vwlab">${h} · ${list.length}</p>${list.map((n) => `<div class="vwli">${n.open ? `<button type="button" data-vd="open:${esc(n.path)}" title="Open ${esc(n.name)}">${IC.doc}<span><b>${esc(n.name)}</b><small>${esc(n.sub)}</small></span></button>` : `<span>${IC.doc}<span><b>${esc(n.name)}</b><small>${esc(n.sub)}</small></span></span>`}${n.st && n.st !== 'ok' ? `<span class="lz ${n.st === 'drift' ? 'y' : 'r'}">${esc(ST[n.st] || n.st)}</span>` : ''}</div>`).join('')}</div>` : '');
142
+ return R && (R.sources.length || R.goals.length || R.used.length) ? `<div class="vwlinks">${grp('Built from', R.sources)}${grp('Belongs to', R.goals)}${grp('Used by', R.used)}</div><p class="vwmut">A document opens as a page beside this one.</p>` : '<p class="vwmut">No link is recorded for this document.</p>';
143
+ }
144
+ function copiesHtml(cps) {
145
+ if (!P.copies) return '<p class="vwmut">Reading the copies.</p>';
146
+ const rows = cps.map((c) => `<div class="vwcp"><span><b>${esc(c.title)}</b><small>${esc([c.tool, c.target].filter(Boolean).join(' · '))}</small></span><span class="lz ${c.tone === 'ok' ? 'g' : c.tone === 'warn' ? 'y' : 'n'}">${esc(c.state)}</span><p class="vwmut">${esc(c.words)}${c.checked ? ' Last checked ' + esc(dayOf(c.checked)) + '.' : ' Not checked yet.'}</p>${c.url ? `<a href="${esc(c.url)}" target="_blank" rel="noopener">Open in ${esc(c.tool)}</a>` : ''}</div>`).join('');
147
+ return (rows || '<p class="vwmut">This document has no copy in Confluence or Google Docs yet. Link one to see whether it is in step.</p>')
148
+ + `<div class="vwrow"><input id="vwCpUrl" class="vwin" type="text" placeholder="Paste a Confluence page or Google Doc link" aria-label="Address of the copy" value="${esc(P.cpUrl || '')}"><button type="button" class="vwbtn pri" data-vd="cplink">Link</button>${cps.length ? `<button type="button" class="vwbtn" data-vd="cpcheck"${P.checkRun ? ' disabled' : ''}>${P.checkRun ? 'Checking' : 'Check now'}</button>` : ''}</div>`
149
+ + (P.cpMsg ? `<p class="vwerr" role="alert">${esc(P.cpMsg)}</p>` : '')
150
+ + '<p class="vwmut">PMOS never writes to a copy from here. Check now starts one agent session that reads the copies with your connectors. Updating a copy is in the console.</p>';
151
+ }
152
+
153
+ /* ── drawing ── */
154
+ function headHtml(h) {
155
+ const revs = (P.log && P.log.revisions) || [], last = revs[revs.length - 1];
156
+ const by = last ? `Last change by ${esc(whoOf(last))}${last.at ? ' · ' + esc(dayOf(last.at)) : ''}` : 'No change is recorded';
157
+ const ttl = h.title || String(d.path).split('/').pop();
158
+ return `<header class="cfh"><h1 class="cft"${P.mode === 'edit' && h.titleEdits ? ' contenteditable="true" spellcheck="true" aria-label="Title"' : ''}>${esc(ttl)}</h1>`
159
+ + `<div class="cfby"><span class="av avdot" aria-hidden="true">${esc((last ? whoOf(last)[0] : 'D') || 'D')}</span><span>${by}${v() ? ` · v${v()}` : ''} · ${readMinutes(P.text)} min read</span></div>`
160
+ + (h.labels.length ? `<div class="cflb">${h.labels.map((l) => `<span>${esc(l)}</span>`).join('')}</div>` : '')
161
+ + (h.props.length ? `<table class="cfpr" aria-label="Properties">${h.props.map(([k, val]) => `<tr><th scope="row">${esc(k)}</th><td>${propHtml(k, val)}</td></tr>`).join('')}</table>` : '')
162
+ + '</header>';
163
+ }
164
+ const stripH1 = (md, h) => (h.h1 ? md.replace(/^#\s+.*(\n|$)/, '') : md);
165
+ function readBody(h, text) {
166
+ const sd = splitDoc(text), parts = [sd.pre, ...sd.sections.map((s, n) => (n === 0 && h.h1 ? s.body : s.head + '\n' + s.body))];
167
+ return bodyHtml(parts.join('\n')).html;
168
+ }
169
+ function overlayBody(h, o) {
170
+ let start = 0, stripped = false;
171
+ const h1Head = h.h1 ? splitDoc(P.text).sections[0].head : null;
172
+ return o.blocks.map((b, n) => {
173
+ let md = b.md;
174
+ if (h1Head && !stripped && md.startsWith(h1Head + '\n')) { md = stripH1(md, h); stripped = true; }
175
+ const r = bodyHtml(md, { start }); start += r.heads.length;
176
+ if (!b.chg) return r.html;
177
+ const c = b.chg, open = P.pop === c.name;
178
+ const before = c.kind === 'added' ? '<p class="vwmut">This section is new. It was not in the document before.</p>' : bodyHtml(stripH1(c.before, h), { start: 900 + n }).html;
179
+ const words = c.kind === 'added' ? 'Added by the agent' : c.kind === 'removed' ? 'The agent removes this section' : 'Changed by the agent';
180
+ return `<div class="vwchg ${c.kind}${c.on ? '' : ' off'}" data-sec="${esc(c.name)}"${b.hide ? ' data-hidden="1"' : ''}>`
181
+ + `<button type="button" class="vwcl" data-vd="pop:${esc(c.name)}" aria-expanded="${open}">${AI}<span>${c.on ? words : 'Put back as it was'}</span><em>${open ? 'Hide' : c.kind === 'added' ? 'What is new' : 'What it said before'}</em></button>`
182
+ + (b.hide ? '' : `<div class="vwcb">${r.html}</div>`)
183
+ + (open ? `<div class="vwbefore" role="region" aria-label="Before the agent's edit"><p class="vwlab">${c.kind === 'added' ? 'Before' : 'What it said before'}</p>${before}<div class="vwrow"><button type="button" class="vwbtn" data-vd="${c.on ? 'back' : 'again'}:${esc(c.name)}">${c.on ? (c.kind === 'added' ? 'Take it out' : 'Put it back') : 'Apply the agent\'s edit'}</button></div></div>` : '')
184
+ + '</div>';
185
+ }).join('');
186
+ }
187
+ function agentBar(p, o) {
188
+ if (!p) return '';
189
+ const line = overlayLine(o, v());
190
+ return `<div class="vwag" role="status"><span class="vwagt">${AI}<span><b>${esc(p.prompt ? 'Asked: ' + p.prompt.slice(0, 140) : 'An agent edit')}</b><span id="vwAgN">${esc(line)}</span></span></span>`
191
+ + `<span class="vwaga"><button type="button" class="vwbtn" data-vd="undoall"${P.busy ? ' disabled' : ''}>Undo all</button><button type="button" class="vwbtn pri" data-vd="keep"${P.busy || !o.applied ? ' disabled' : ''}>Keep as v${v() + 1}</button></span></div>`;
192
+ }
193
+ function toolsHtml(p) {
194
+ const lock = p ? ' disabled title="Keep or undo the agent\'s edit first"' : '';
195
+ const seg = (m, label, icon) => `<button type="button" class="vwseg" data-vd="mode:${m}" aria-pressed="${P.mode === m}"${m !== 'read' ? lock : ''}>${IC[icon]}${label}</button>`;
196
+ return `<div class="vwdt" role="toolbar" aria-label="Document"><span class="vwsg">${seg('read', 'Page', 'doc')}${seg('edit', 'Edit', 'pen')}${seg('md', 'Markdown', 'md')}</span><span class="gap"></span>`
197
+ + (P.mode === 'read' ? extrasHtml() : '')
198
+ + (P.mode === 'read' && !p ? `<button type="button" class="vwbtn" data-vd="askt" aria-expanded="${P.askOpen}">${AI}Ask the agent</button>` : '') + '</div>'
199
+ + (P.mode === 'read' && P.askOpen && !p ? `<div class="vwask"><textarea id="vwAsk" rows="2" placeholder="Tell the agent what to change, for example: tighten the Goal section" aria-label="Tell the agent what to change">${esc(P.askText)}</textarea><div class="vwrow"><span class="vwmut">The agent edits the page; nothing is kept until you press Keep.</span><button type="button" class="vwbtn pri" data-vd="ask"${P.busy || (P.ask && P.ask.state === 'working') ? ' disabled' : ''}>Ask</button></div></div>` : '')
200
+ + (P.ask && P.ask.state !== 'proposed' ? `<p class="vwmut vwline" role="status">${esc(askLine(P.ask))}</p>` : '');
201
+ }
202
+ /** The opener's own buttons on the read bar, such as a report's Present, Print and Download (ctx.extras). A button with a menu lists links or presses. */
203
+ function extrasHtml() {
204
+ const X = (ctx.extras && ctx.extras()) || [];
205
+ return X.map((x) => {
206
+ if (!x.menu) return `<button type="button" class="vwbtn" data-vwx="${esc(x.k)}">${x.icon || ''}${esc(x.label)}</button>`;
207
+ const on = P.xm === x.k;
208
+ return `<span class="vwxm"><button type="button" class="vwbtn" data-vd="xm:${esc(x.k)}" aria-haspopup="menu" aria-expanded="${on}">${x.icon || ''}${esc(x.label)}</button>${on ? `<div class="vwpop vwxmn" role="menu" aria-label="${esc(x.label)}">${x.menu.map((m) => (m.href
209
+ ? `<a role="menuitem" href="${esc(m.href)}"${m.download ? ' download' : ''} data-vwx-done="1"><span class="ki">${m.icon || ''}</span><span>${esc(m.label)}${m.sub ? `<small>${esc(m.sub)}</small>` : ''}</span><span></span></a>`
210
+ : `<button type="button" role="menuitem" data-vwx="${esc(m.k)}"><span class="ki">${m.icon || ''}</span><span>${esc(m.label)}${m.sub ? `<small>${esc(m.sub)}</small>` : ''}</span><span></span></button>`)).join('')}${x.note ? `<p class="vwmut">${esc(x.note)}</p>` : ''}</div>` : ''}</span>`;
211
+ }).join('');
212
+ }
213
+ function editBar() {
214
+ return `<div class="vwetb" role="toolbar" aria-label="Format the page">${tb('undo', 'Undo', 'undo')}${tb('redo', 'Redo', 'redo')}<span class="sp"></span>`
215
+ + `<button type="button" class="vwtb dd" data-c="style" aria-label="Text style" aria-haspopup="menu"><span class="styL">Normal text</span></button><span class="sp"></span>`
216
+ + `<button type="button" class="vwtb fx" data-c="bold" title="Bold (Ctrl+B)" aria-label="Bold"><b>B</b></button><button type="button" class="vwtb fx" data-c="italic" title="Italic (Ctrl+I)" aria-label="Italic"><i>I</i></button><button type="button" class="vwtb fx" data-c="strikeThrough" title="Strikethrough" aria-label="Strikethrough"><s>S</s></button>${tb('icode', 'Inline code', 'code')}<span class="sp"></span>`
217
+ + `${tb('insertUnorderedList', 'Bulleted list', 'ul')}${tb('insertOrderedList', 'Numbered list', 'ol')}${tb('task', 'Task list', 'task')}<span class="sp"></span>${tb('link', 'Link', 'link')}${tb('table', 'Table', 'tbl')}`
218
+ + `<button type="button" class="vwtb dd" data-c="insert" aria-label="Insert a block" aria-haspopup="menu">${IC.plus}<span class="tl">Insert</span></button></div>`;
219
+ }
220
+ function saveRow() {
221
+ return `<div class="vwsave"><input id="vwWhy" class="vwin" placeholder="Why are you changing it? Kept in the Edit log." aria-label="Why are you changing it" value="${esc(P.why)}">`
222
+ + `<p class="vwerr" id="vwErr" role="alert">${esc(P.msg)}</p><div class="vwrow"><span class="vwmut" id="vwSv">${P.mode === 'edit' ? 'Type straight into the page. Press / for a block.' : 'The file as it is on disk.'}</span>`
223
+ + `<button type="button" class="vwbtn" data-vd="cancel">Cancel</button><button type="button" class="vwbtn pri" data-vd="save"${P.busy ? ' disabled' : ''}>Save as v${v() + 1}</button></div></div>`;
224
+ }
225
+ function pageHtml() {
226
+ if (P.err) return `<p class="vwempty">${esc(P.err)}</p>`;
227
+ if (P.text == null) return '<p class="vwempty">Reading the file.</p>';
228
+ const h = pageHead(P.text), p = openProp();
229
+ const o = p ? overlay(P.text, p, P.kept) : null;
230
+ if (P.mode === 'md') return toolsHtml(p) + `<textarea id="vwMd" class="vwmd" spellcheck="false" aria-label="The file as Markdown">${esc(P.work != null ? P.work : P.text)}</textarea>` + saveRow();
231
+ const body = o ? overlayBody(h, o) : readBody(h, P.mode === 'edit' && P.work != null ? P.work : P.text);
232
+ const unsaved = P.mode === 'read' && P.work != null && P.work !== P.text ? '<p class="vwmut vwline" role="status">You have changes that are not saved yet. Edit shows them again.</p>' : '';
233
+ return toolsHtml(p) + (P.mode === 'read' ? moreBar() : '') + unsaved + agentBar(p, o) + (P.mode === 'edit' ? editBar() : '')
234
+ + `<article class="cf${P.mode === 'edit' ? ' editing' : ''}">${headHtml(h)}<div class="cfb"${P.mode === 'edit' ? ' contenteditable="true" spellcheck="true" aria-label="The page" role="textbox" aria-multiline="true"' : ''}>${body || '<p class="vwmut">The file has no text yet.</p>'}</div>`
235
+ + `<footer class="cff"><span>${v() ? 'v' + v() + (p ? ' · edited by the agent, not kept yet' : '') : ''}</span><span class="gap"></span><code>${esc(d.path)}</code></footer></article>`
236
+ + (P.mode === 'edit' ? saveRow() : '');
237
+ }
238
+ function draw() {
239
+ if (!el || !el.isConnected) return;
240
+ const keepScroll = el.scrollTop;
241
+ el.innerHTML = `<div class="vwdoc">${pageHtml()}</div>`;
242
+ el.scrollTop = keepScroll;
243
+ if (P.mode === 'edit') startEdit();
244
+ }
245
+
246
+ /* ── editing in place ── */
247
+ let menu = null;
248
+ const closeMenu = () => { if (menu) { menu.remove(); menu = null; } };
249
+ function serialize() {
250
+ const art = $('.cf', el), src = P.work != null ? P.work : P.text, h = pageHead(src), t = $('.cft', art);
251
+ const body = domToMd($('.cfb', art));
252
+ return splitDoc(src).fmRaw + (h.h1 ? (h.titleEdits && t ? '# ' + t.textContent.trim() : h.h1Head) + '\n\n' : '') + body + '\n';
253
+ }
254
+ function startEdit() {
255
+ const body = $('.cfb', el); if (!body) return;
256
+ try { document.execCommand('defaultParagraphSeparator', false, 'p'); } catch { /* old engine */ }
257
+ if (P.base == null) P.base = serialize();
258
+ }
259
+ /** The text as it stands now in Edit or Markdown: the file with what was typed, and only that, changed. */
260
+ function current() {
261
+ if (P.mode === 'md') { const t = $('#vwMd', el); return t ? t.value : P.work != null ? P.work : P.text; }
262
+ if (P.mode === 'edit' && $('.cfb', el)) { const src = P.work != null ? P.work : P.text; return mergeEdit(src, P.base != null ? P.base : serialize(), serialize()); }
263
+ return P.work != null ? P.work : P.text;
264
+ }
265
+ function X(c, val) { const body = $('.cfb', el); const s = getSelection(); if (!s.rangeCount || !body.contains(s.anchorNode)) body.focus(); document.execCommand(c, false, val); syncBar(); }
266
+ function syncBar() {
267
+ const bar = $('.vwetb', el); if (!bar) return;
268
+ ['bold', 'italic', 'strikeThrough', 'insertUnorderedList', 'insertOrderedList'].forEach((c) => { const b = $(`[data-c="${c}"]`, bar); if (b) b.setAttribute('aria-pressed', String(document.queryCommandState(c))); });
269
+ const a = getSelection().anchorNode, blk = a && (a.nodeType === 3 ? a.parentElement : a).closest && (a.nodeType === 3 ? a.parentElement : a).closest('h2,h3,h4,blockquote');
270
+ $('.styL', bar).textContent = blk && $('.cfb', el).contains(blk) ? { H2: 'Heading 1', H3: 'Heading 2', H4: 'Heading 3', BLOCKQUOTE: 'Quote' }[blk.tagName] : 'Normal text';
271
+ }
272
+ function insertNew(html) {
273
+ X('insertHTML', html);
274
+ const n = $('.cfb [data-new]', el);
275
+ if (n) { const f = $('[data-f]', n) || n; n.removeAttribute('data-new'); f.removeAttribute('data-f'); const r = document.createRange(); r.selectNodeContents(f); const s = getSelection(); s.removeAllRanges(); s.addRange(r); }
276
+ }
277
+ function doBlock(k) {
278
+ if (['p', 'h2', 'h3', 'h4'].includes(k)) { X('formatBlock', k); const a = getSelection().anchorNode, hh = a && (a.nodeType === 3 ? a.parentElement : a).closest('h2,h3,h4'); if (hh) hh.dataset.md = String(+hh.tagName[1]); return; }
279
+ if (k === 'quote') return X('formatBlock', 'blockquote');
280
+ if (k === 'ul') return X('insertUnorderedList');
281
+ if (k === 'ol') return X('insertOrderedList');
282
+ if (PANELS.includes(k)) return insertNew(`<div class="pnl ${k}" data-k="${k}" data-new><span class="pi pidot" contenteditable="false" aria-hidden="true"></span><div class="pc"><p data-f>Type here.</p></div></div><p><br></p>`);
283
+ if (k === 'task') return insertNew('<ul class="tasks" data-new><li data-done="false"><span class="chk" contenteditable="false" role="checkbox" aria-checked="false" aria-label="Done"></span><span data-f>New task</span></li></ul><p><br></p>');
284
+ if (k === 'table') return insertNew('<div class="tw" data-new><table><thead><tr><th data-f>Heading</th><th>Heading</th><th>Heading</th></tr></thead><tbody><tr><td><br></td><td><br></td><td><br></td></tr><tr><td><br></td><td><br></td><td><br></td></tr></tbody></table></div><p><br></p>');
285
+ if (k === 'code') return insertNew('<div class="cb" data-lang="" data-new><div class="cbh" contenteditable="false"><span>text</span></div><pre data-f>code</pre></div><p><br></p>');
286
+ if (k === 'expand') return insertNew('<details class="xp" open data-new><summary>Click to see details</summary><div><p data-f>Hidden until someone opens it.</p></div></details><p><br></p>');
287
+ if (k === 'hr') return X('insertHTML', '<hr><p><br></p>');
288
+ if (k === 'status') { const r = getSelection().rangeCount ? getSelection().getRangeAt(0).cloneRange() : null; return showMenu(caretRect(), STATUSES.map((t) => ({ t, k: t })), (it) => { if (r) { const s = getSelection(); s.removeAllRanges(); s.addRange(r); } X('insertHTML', `<span class="lz" contenteditable="false" data-st>${esc(it.k)}</span>&nbsp;`); }); }
289
+ }
290
+ const caretRect = () => { const s = getSelection(); if (!s.rangeCount) return el.getBoundingClientRect(); const r = s.getRangeAt(0).cloneRange(); let rc = r.getBoundingClientRect(); if (!rc.width && !rc.height) { const n = r.startContainer; rc = (n.nodeType === 3 ? n.parentElement : n).getBoundingClientRect(); } return rc; };
291
+ /** A small menu of blocks next to a rect. Arrow keys move, Enter picks, Escape closes; `q` filters it (the / menu types into it). */
292
+ function showMenu(rect, items, onPick, opts = {}) {
293
+ closeMenu();
294
+ const m = document.createElement('div'); m.className = 'vwpop'; m.setAttribute('role', 'menu'); m.setAttribute('aria-label', opts.label || 'Blocks');
295
+ const st = { el: m, q: '', idx: 0, list: items, slash: !!opts.slash };
296
+ st.draw = () => {
297
+ const q = st.q.toLowerCase(); st.list = items.filter((x) => !q || (x.t + ' ' + (x.k || '')).toLowerCase().includes(q)); if (st.idx >= st.list.length) st.idx = 0;
298
+ m.innerHTML = st.list.length ? st.list.map((x, n) => `<button type="button" role="menuitem" data-n="${n}" aria-current="${n === st.idx}"><span class="ki">${x.ic ? IC[x.ic] : esc(x.g || '')}</span><span>${esc(x.t)}</span>${x.kbd ? `<kbd>${esc(x.kbd)}</kbd>` : '<span></span>'}</button>`).join('') : '<p class="vwmut">No block matches. Keep typing, or press Escape.</p>';
299
+ $$('button', m).forEach((b) => { b.onmousedown = (e) => e.preventDefault(); b.onclick = () => { const it = st.list[+b.dataset.n]; closeMenu(); onPick(it); }; });
300
+ };
301
+ st.move = (dlt) => { if (!st.list.length) return; st.idx = (st.idx + dlt + st.list.length) % st.list.length; st.draw(); };
302
+ st.draw(); el.appendChild(m);
303
+ const host = el.getBoundingClientRect(), w = m.offsetWidth, hgt = m.offsetHeight;
304
+ let top = rect.bottom - host.top + el.scrollTop + 6; if (rect.bottom + hgt > innerHeight - 8) top = Math.max(el.scrollTop + 8, rect.top - host.top + el.scrollTop - hgt - 6);
305
+ m.style.setProperty('--rp-px', Math.max(8, Math.min(rect.left - host.left, host.width - w - 8)) + 'px'); m.style.setProperty('--rp-py', top + 'px'); // run-time geometry: the menu sits at the caret
306
+ if (!opts.slash) { const f = $('button', m); if (f) f.focus(); }
307
+ menu = Object.assign(m, { st });
308
+ return st;
309
+ }
310
+ function linkPrompt() {
311
+ const s = getSelection(), body = $('.cfb', el);
312
+ if (s.isCollapsed || !body.contains(s.anchorNode)) { toast('Select the words to link first.'); return; }
313
+ const r = s.getRangeAt(0).cloneRange();
314
+ const st = showMenu(r.getBoundingClientRect(), [], () => {}, { label: 'Link' });
315
+ st.el.innerHTML = '<div class="vwrow"><input type="url" class="vwin" placeholder="Paste a link, then press Enter" aria-label="Link address"><button type="button" class="vwbtn pri">Apply</button></div>';
316
+ const inp = $('input', st.el), go = () => { const u = inp.value.trim(); closeMenu(); const ss = getSelection(); ss.removeAllRanges(); ss.addRange(r); if (u) X('createLink', u); };
317
+ $('button', st.el).onclick = go; inp.onkeydown = (e) => { if (e.key === 'Enter') { e.preventDefault(); go(); } if (e.key === 'Escape') { closeMenu(); } };
318
+ inp.focus();
319
+ }
320
+ let slash = null;
321
+ const delBack = (n) => { const s = getSelection(); for (let k = 0; k < n; k++) s.modify('extend', 'backward', 'character'); document.execCommand('delete'); };
322
+ const SHORT = { '# ': 'h2', '## ': 'h2', '### ': 'h3', '#### ': 'h4', '- ': 'ul', '* ': 'ul', '1. ': 'ol', '[] ': 'task', '> ': 'quote', '--- ': 'hr', '``` ': 'code' };
323
+
324
+ /* ── presses ── */
325
+ async function press(act) {
326
+ const fail = (m) => { P.busy = false; P.msg = m; draw(); const e = $('#vwErr', el); if (e) e.scrollIntoView({ block: 'nearest' }); };
327
+ const [k, arg] = [act.split(':')[0], act.slice(act.indexOf(':') + 1)];
328
+ const p = openProp();
329
+ if (k === 'mode') { if (P.mode === arg) return; if (P.mode !== 'read') { const t = current(); P.work = t !== P.text ? t : null; } P.mode = arg; P.msg = ''; P.base = null; draw(); return; }
330
+ if (k === 'more') { P.more = P.more === arg ? null : arg; draw(); if (P.more === 'links' && P.lib === undefined) loadLib(); return; }
331
+ if (k === 'open') { openDocPage({ path: arg, title: String(arg).split('/').pop() }, { ws: ctx.ws }); return; }
332
+ if (k === 'cplink') {
333
+ const t = String(($('#vwCpUrl', el) || {}).value || '').trim(), kind = copyKindOf(t); P.cpUrl = t;
334
+ if (!kind) { P.cpMsg = 'Paste a Confluence page or Google Doc link.'; draw(); const f = $('#vwCpUrl', el); if (f) f.focus(); return; }
335
+ const r = await pmPost('/api/docs/link', { ws: ws(), path: d.path, kind, target: t }).catch(() => null);
336
+ if (!r || r.ok !== true) { P.cpMsg = (r && r.error) || 'The copy was not linked.'; draw(); return; }
337
+ P.cpUrl = ''; P.cpMsg = ''; toast('Linked the copy. Check now reads it.'); await loadCopies(); return;
338
+ }
339
+ if (k === 'cpcheck') {
340
+ const r = await pmPost('/api/docs/check', { ws: ws() }).catch(() => null);
341
+ if (!r || r.ok !== true) { P.cpMsg = (r && r.error) || 'The check did not start.'; draw(); return; }
342
+ P.checkRun = { id: r.session }; P.cpMsg = ''; draw();
343
+ for (let i = 0; i < 120 && el && el.isConnected && P.checkRun; i++) { await new Promise((ok) => setTimeout(ok, 5000)); await loadCopies(); }
344
+ return;
345
+ }
346
+ if (k === 'xm') { P.xm = P.xm === arg ? null : arg; draw(); return; }
347
+ if (k === 'askt') { P.askOpen = !P.askOpen; draw(); const a = $('#vwAsk', el); if (a) a.focus(); return; }
348
+ if (k === 'pop') { P.pop = P.pop === arg ? null : arg; draw(); return; }
349
+ if (k === 'back' || k === 'again') {
350
+ const o = overlay(P.text, p, P.kept), cur = new Set(P.kept || o.live);
351
+ if (k === 'back') cur.delete(arg); else cur.add(arg);
352
+ P.kept = o.live.filter((n) => cur.has(n)); draw(); return;
353
+ }
354
+ if (k === 'cancel') { P.mode = 'read'; P.work = null; P.base = null; P.why = ''; P.msg = ''; draw(); return; }
355
+ if (k === 'save') {
356
+ const why = ($('#vwWhy', el) || {}).value || '';
357
+ const text = current();
358
+ P.why = why; P.work = text !== P.text ? text : null;
359
+ const r = editBody(d.path, P.text, text, why); if (r.error) return fail(r.error);
360
+ P.busy = true; P.msg = ''; draw();
361
+ const res = await pmPost('/api/doc-sheet/edit' + (ws() ? '?ws=' + encodeURIComponent(ws()) : ''), r.body).catch(() => null);
362
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The document could not be saved.');
363
+ toast(`Saved as v${v() + 1}. The reason is in the Edit log.`);
364
+ P.busy = false; P.mode = 'read'; P.base = null; P.work = null; P.why = '';
365
+ await load(); if (ctx.onWrite) ctx.onWrite(); return;
366
+ }
367
+ if (k === 'ask') {
368
+ const r = askBody(d.path, ($('#vwAsk', el) || {}).value || P.askText); if (r.error) { P.ask = { state: 'failed', error: r.error }; draw(); return; }
369
+ P.busy = true; draw();
370
+ const res = await pmPost('/api/doc-sheet/ask' + (ws() ? '?ws=' + encodeURIComponent(ws()) : ''), r.body).catch(() => null);
371
+ P.busy = false;
372
+ if (!res || res.ok !== true || !res.id) { P.ask = { state: 'failed', error: (res && res.error) || 'The agent could not be asked.' }; draw(); return; }
373
+ P.askText = ''; P.askOpen = false; P.ask = { state: 'working', id: res.id }; draw(); pollAsk(res.id); return;
374
+ }
375
+ if (!p) return;
376
+ if (k === 'keep') {
377
+ const o = overlay(P.text, p, P.kept);
378
+ const r = acceptBody(d.path, p, P.kept || o.live); if (r.error) return fail(r.error);
379
+ P.busy = true; draw();
380
+ const res = await pmPost('/api/doc-sheet/accept' + (ws() ? '?ws=' + encodeURIComponent(ws()) : ''), r.body).catch(() => null);
381
+ if (!res || res.ok !== true) { P.busy = false; await load(); toast((res && res.error) || 'The edit could not be kept.'); return; }
382
+ const nv = v() + 1; P.busy = false; P.pop = null;
383
+ toast(`Kept as v${nv}. v${nv - 1} stays in the Edit log.`);
384
+ await load(); if (ctx.onWrite) ctx.onWrite(); return;
385
+ }
386
+ if (k === 'undoall') {
387
+ const o = overlay(P.text, p, P.kept);
388
+ const n = o.total || o.stale.length;
389
+ const yes = await vwConfirm(el, { text: `Undo all ${n} ${n === 1 ? 'edit' : 'edits'} by the agent? The file stays as v${v()}.`, yes: 'Undo all', no: 'Cancel' });
390
+ if (!yes) return;
391
+ const r = rejectBody(d.path, p, 'Undone with Undo all in the viewer.'); if (r.error) return fail(r.error);
392
+ P.busy = true; draw();
393
+ const res = await pmPost('/api/doc-sheet/reject' + (ws() ? '?ws=' + encodeURIComponent(ws()) : ''), r.body).catch(() => null);
394
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The edit could not be undone.');
395
+ P.busy = false; P.pop = null; P.kept = null;
396
+ toast(`Undone. The file is as it was, v${v()}.`);
397
+ await load(); if (ctx.onWrite) ctx.onWrite();
398
+ }
399
+ }
400
+ async function pollAsk(id) {
401
+ for (let i = 0; i < 400 && el && el.isConnected; i++) {
402
+ await new Promise((r) => setTimeout(r, 2000));
403
+ const a = await getJson('/api/doc-sheet/ask?id=' + encodeURIComponent(id) + wsq());
404
+ if (!a || a.ok === false) { P.ask = { state: 'failed', error: (a && a.error) || 'The answer could not be read.' }; draw(); return; }
405
+ P.ask = a;
406
+ if (a.state !== 'working') { await load(); return; }
407
+ }
408
+ }
409
+
410
+ function wire(pane) {
411
+ el = pane;
412
+ pane.onclick = (e) => { // delegated: every control in the page is a real button with data-vd, data-c or data-vwx
413
+ if (menu && !e.target.closest('.vwpop')) closeMenu();
414
+ const xv = e.target.closest('[data-vwx]');
415
+ if (xv) { P.xm = null; draw(); if (ctx.onExtra) ctx.onExtra(xv.dataset.vwx, { text: P.text }); return; }
416
+ if (e.target.closest('[data-vwx-done]')) { P.xm = null; setTimeout(draw, 0); return; }
417
+ if (P.xm && !e.target.closest('.vwxm')) { P.xm = null; draw(); }
418
+ const b = e.target.closest('[data-vd]'); if (b && !b.disabled) { press(b.dataset.vd); return; }
419
+ const c = e.target.closest('[data-c]');
420
+ if (c && P.mode === 'edit') {
421
+ const cmd = c.dataset.c, rc = c.getBoundingClientRect();
422
+ if (['undo', 'redo', 'bold', 'italic', 'strikeThrough', 'insertUnorderedList', 'insertOrderedList'].includes(cmd)) return X(cmd);
423
+ if (cmd === 'icode') { const s = getSelection(); if (!s.isCollapsed) X('insertHTML', `<code>${esc(String(s))}</code>`); else toast('Select some text first.'); return; }
424
+ if (cmd === 'task' || cmd === 'table') return doBlock(cmd);
425
+ if (cmd === 'link') return linkPrompt();
426
+ const r = getSelection().rangeCount ? getSelection().getRangeAt(0).cloneRange() : null;
427
+ const back = (fn) => (it) => { if (r) { const s = getSelection(); s.removeAllRanges(); s.addRange(r); } fn(it); };
428
+ if (cmd === 'style') return showMenu(rc, BLOCKS.filter((x) => ['p', 'h2', 'h3', 'h4', 'quote'].includes(x.k)), back((it) => doBlock(it.k)), { label: 'Text style' });
429
+ if (cmd === 'insert') return showMenu(rc, BLOCKS.filter((x) => !['p', 'h2', 'h3', 'h4'].includes(x.k)), back((it) => doBlock(it.k)), { label: 'Insert a block' });
430
+ }
431
+ const chk = e.target.closest('.cfb .chk');
432
+ if (chk && P.mode === 'edit') { const on = chk.getAttribute('aria-checked') !== 'true'; chk.setAttribute('aria-checked', String(on)); chk.parentElement.dataset.done = String(on); return; }
433
+ const lz = e.target.closest('.cfb .lz');
434
+ if (lz && P.mode === 'edit') { showMenu(lz.getBoundingClientRect(), STATUSES.map((t) => ({ t, k: t })), (it) => { lz.textContent = it.k; }, { label: 'Status' }); return; }
435
+ const a = e.target.closest('.cfb a');
436
+ if (a && P.mode === 'edit') e.preventDefault();
437
+ };
438
+ pane.onmousedown = (e) => { if (e.target.closest('.vwtb')) e.preventDefault(); }; // the toolbar keeps the editor's selection
439
+ pane.addEventListener('input', (e) => {
440
+ if (e.target.id === 'vwAsk') { P.askText = e.target.value; return; }
441
+ if (e.target.id === 'vwWhy') { P.why = e.target.value; return; }
442
+ if (e.target.id === 'vwMd') return;
443
+ if (e.target.id === 'vwCpUrl') { P.cpUrl = e.target.value; return; }
444
+ if (!e.target.closest || !e.target.closest('.cfb')) return;
445
+ if (e.inputType === 'insertText' && e.data === '/') { slash = { q: '' }; showMenu(caretRect(), BLOCKS, (it) => { const n = slash ? slash.q.length + 1 : 1; slash = null; delBack(n); doBlock(it.k); }, { slash: true }); }
446
+ else if (slash && menu) {
447
+ if (e.inputType === 'insertText') slash.q += e.data; else if (e.inputType === 'deleteContentBackward') { if (!slash.q) { slash = null; closeMenu(); return; } slash.q = slash.q.slice(0, -1); }
448
+ if (slash) { menu.st.q = slash.q; menu.st.idx = 0; menu.st.draw(); if (/\s$/.test(slash.q) || (!menu.st.list.length && slash.q.length > 14)) { closeMenu(); slash = null; } }
449
+ } else if (e.inputType === 'insertText' && e.data === ' ') {
450
+ const a = getSelection().anchorNode, blk = a && (a.nodeType === 3 ? a.parentElement : a).closest('p,h2,h3,h4,div');
451
+ if (blk && blk.closest('.cfb') && !blk.classList.contains('cfb')) { const t = blk.textContent.replace(/ /g, ' '), kk = SHORT[t]; if (kk) { delBack(t.length); doBlock(kk); } }
452
+ }
453
+ const sv = $('#vwSv', el); if (sv) sv.textContent = 'Changed. Save keeps it as a new version.';
454
+ });
455
+ pane.addEventListener('keydown', (e) => {
456
+ if (menu && menu.st) {
457
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); if (menu.st.slash) menu.st.move(e.key === 'ArrowDown' ? 1 : -1); else { const bs = $$('button', menu), i = bs.indexOf(document.activeElement); const nx = bs[(i + (e.key === 'ArrowDown' ? 1 : -1) + bs.length) % bs.length]; if (nx) nx.focus(); } return; }
458
+ if (menu.st.slash && (e.key === 'Enter' || e.key === 'Tab')) { e.preventDefault(); const n = slash ? slash.q.length + 1 : 1, it = menu.st.list[menu.st.idx]; closeMenu(); slash = null; if (it) { delBack(n); doBlock(it.k); } return; }
459
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeMenu(); slash = null; return; }
460
+ }
461
+ if (P.mode !== 'read' && (e.metaKey || e.ctrlKey) && e.key === 's') { e.preventDefault(); press('save'); }
462
+ if (e.target.classList && e.target.classList.contains('cft') && e.key === 'Enter') { e.preventDefault(); const b = $('.cfb', el); if (b) b.focus(); }
463
+ });
464
+ pane.addEventListener('keyup', () => { if (P.mode === 'edit') syncBar(); });
465
+ pane.addEventListener('mouseup', () => { if (P.mode === 'edit') setTimeout(syncBar, 0); });
466
+ }
467
+
468
+ const spec = { id, title: d.title || String(d.path).split('/').pop(), icon: 'doc', render(e) { el = e; draw(); }, wire(e) { if (WIRED.has(e)) return; WIRED.add(e); wire(e); } };
469
+ const api = { show(c2) { if (!el || !el.isConnected) { OPEN.delete(id); return makePage(d, c2 || ctx); } if (c2) ctx = c2; el = vwOpen(spec) || el; if (P.mode === 'read') load(); return el; } };
470
+ OPEN.set(id, api);
471
+ const pane = vwOpen(spec);
472
+ if (pane) el = pane;
473
+ load();
474
+ return pane;
475
+ }
476
+ const WIRED = new WeakSet();
477
+ export const __test = { domToMd, CHECK };