create-pmos 0.286.0 → 0.287.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.
@@ -77,24 +77,71 @@ export function issueBody(ws, scope, key, slot, unsaved) {
77
77
  return { body: { ws, scope, key, slot } };
78
78
  }
79
79
 
80
- /** The Read tab's text as html with its outline and front matter. Pure: the page puts the html in the sheet. */
81
- export function mdHtml(text) {
82
- const lines = String(text || '').replace(/\r/g, '').split('\n'), out = [], outline = [];
80
+ /** One line of text as html: bold, italic, inline code and https links. The text is escaped first, so nothing the file holds becomes markup. */
81
+ export function inlineHtml(t) {
82
+ let h = esc(t);
83
+ h = h.replace(/`([^`]+)`/g, '<code>$1</code>');
84
+ h = h.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/(^|[\s(])\*([^*\s][^*]*)\*(?=$|[\s).,;:])/g, '$1<em>$2</em>');
85
+ h = h.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
86
+ return h;
87
+ }
88
+ const cells = (l) => l.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
89
+
90
+ /** The Read tab's text as html with its outline and front matter. Pure: the page puts the html in the sheet. `outline` holds the heading texts, `levels` their depth (1 to 4). */
91
+ export function mdHtml(text, opts) {
92
+ const lines = String(text || '').replace(/\r/g, '').split('\n'), out = [], outline = [], levels = [];
83
93
  let i = 0, fm = [];
84
94
  if (lines[0] === '---') { const e = lines.indexOf('---', 1); if (e > 0) { fm = lines.slice(1, e).map((l) => /^([A-Za-z_][\w -]*):\s*(.*)$/.exec(l)).filter(Boolean).slice(0, 10).map((m) => [m[1], m[2].replace(/^"(.*)"$/, '$1')]); i = e + 1; } }
85
- let para = [], list = [];
86
- const flushP = () => { if (para.length) { out.push(`<p>${esc(para.join(' '))}</p>`); para = []; } };
87
- const flushL = () => { if (list.length) { out.push(`<ul>${list.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>`); list = []; } };
95
+ let para = [], list = [], ord = false;
96
+ const flushP = () => { if (para.length) { out.push(`<p>${inlineHtml(para.join(' '))}</p>`); para = []; } };
97
+ const flushL = () => { if (list.length) { out.push(`<${ord ? 'ol' : 'ul'}>${list.map((x) => `<li>${inlineHtml(x)}</li>`).join('')}</${ord ? 'ol' : 'ul'}>`); list = []; } };
88
98
  for (; i < lines.length; i++) {
89
99
  const l = lines[i];
90
100
  if (/^```/.test(l)) { flushP(); flushL(); const buf = []; for (i++; i < lines.length && !/^```/.test(lines[i]); i++) buf.push(lines[i]); out.push(`<pre class="mdp">${esc(buf.join('\n'))}</pre>`); continue; }
91
101
  const h = /^(#{1,4})\s+(.*)$/.exec(l);
92
- if (h) { flushP(); flushL(); const n = outline.length; outline.push(h[2]); out.push(`<h3 class="d2" id="ds-h${n}">${esc(h[2])}</h3>`); continue; }
93
- if (/^\s*[-*]\s+/.test(l)) { flushP(); list.push(l.replace(/^\s*[-*]\s+/, '')); continue; }
94
- if (/^\|/.test(l)) { flushP(); flushL(); const buf = [l]; while (i + 1 < lines.length && /^\|/.test(lines[i + 1])) buf.push(lines[++i]); out.push(`<pre class="mdp">${esc(buf.join('\n'))}</pre>`); continue; }
102
+ if (h) { flushP(); flushL(); const n = outline.length; outline.push(h[2].replace(/[*`]/g, '')); levels.push(h[1].length); out.push(`<h3 class="d2" id="ds-h${n}">${inlineHtml(h[2])}</h3>`); const at = opts && opts.attr && opts.attr[n]; if (at) out.push(`<p class="dsat"><i>${esc(at.initial)}</i>${esc(at.who)} · ${esc(at.rev)}${at.date ? ' · ' + esc(at.date) : ''}</p>`); continue; }
103
+ const ul = /^\s*[-*]\s+(.*)$/.exec(l), ol = /^\s*\d+[.)]\s+(.*)$/.exec(l);
104
+ if (ul || ol) { flushP(); if (list.length && ord !== !!ol) flushL(); ord = !!ol; list.push((ul || ol)[1]); continue; }
105
+ if (/^\|/.test(l)) {
106
+ flushP(); flushL(); const buf = [l]; while (i + 1 < lines.length && /^\|/.test(lines[i + 1])) buf.push(lines[++i]);
107
+ if (buf.length >= 2 && /^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(buf[1])) {
108
+ const head = cells(buf[0]), rows = buf.slice(2).map(cells);
109
+ out.push(`<div class="mdt"><table><thead><tr>${head.map((c) => `<th>${inlineHtml(c)}</th>`).join('')}</tr></thead><tbody>${rows.map((r) => `<tr>${head.map((_, k) => `<td>${inlineHtml(r[k] || '')}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`);
110
+ } else out.push(`<pre class="mdp">${esc(buf.join('\n'))}</pre>`);
111
+ continue;
112
+ }
95
113
  if (!l.trim()) { flushP(); flushL(); continue; }
96
114
  flushL(); para.push(l.trim());
97
115
  }
98
116
  flushP(); flushL();
99
- return { html: out.join(''), outline, fm };
117
+ return { html: out.join(''), outline, levels, fm };
118
+ }
119
+
120
+ /** The text of each section of a document, in order: [{ name, text }] where a section runs from a heading to the next. A name used twice carries its count. */
121
+ export function sectionsOf(text) {
122
+ const lines = String(text || '').replace(/\r/g, '').split('\n'), out = [], seen = {};
123
+ let i = 0; if (lines[0] === '---') { const e = lines.indexOf('---', 1); if (e > 0) i = e + 1; }
124
+ let cur = null;
125
+ for (; i < lines.length; i++) {
126
+ const h = /^(#{1,4})\s+(.*)$/.exec(lines[i]);
127
+ if (h) { const nm = h[2].replace(/[*`]/g, ''); seen[nm] = (seen[nm] || 0) + 1; cur = { name: nm + (seen[nm] > 1 ? '#' + seen[nm] : ''), lines: [] }; out.push(cur); } else if (cur) cur.lines.push(lines[i]);
128
+ }
129
+ return out.map((x) => ({ name: x.name, text: x.lines.join('\n').trim() }));
130
+ }
131
+
132
+ /** Who last changed each section: `revs` are the log's revisions (oldest first), `texts` the text at each, in the same order. Returns, per heading index of the newest text,
133
+ * the newest revision whose text for that section differs from the revision before (the first revision counts as writing every section). */
134
+ export function sectionAttribution(revs, texts) {
135
+ if (!revs.length || revs.length !== texts.length || texts.some((t) => t == null)) return {};
136
+ const secs = texts.map(sectionsOf), last = secs[secs.length - 1], out = {};
137
+ last.forEach((sec, n) => {
138
+ let hit = 0;
139
+ for (let k = secs.length - 1; k >= 1; k--) {
140
+ const was = secs[k - 1].find((x) => x.name === sec.name), now = secs[k].find((x) => x.name === sec.name);
141
+ if (!now) continue;
142
+ if (!was || was.text !== now.text) { hit = k; break; }
143
+ }
144
+ out[n] = hit;
145
+ });
146
+ return out;
100
147
  }
@@ -0,0 +1,236 @@
1
+ /* pm/premium-doc-sheet.js — the premium document sheet, shared by the Board page and the initiative page (initiative briefing-premium-doc-edit, then premium-doc-sheet).
2
+ * A document row with a file opens the sheet in the standard dialog beside the read-only agent: Read, Edit, Proposals, Edit log and Health, from the existing
3
+ * /api/doc-sheet routes and POST /api/doc-health/check. A draft has Issue it (POST /api/core-docs/issue) and, where the page asks for it, Draft it again.
4
+ * The caller gives the page's own facts: { ws(), scope(), rows(), reload(), noteKey(d), sub(), again }. */
5
+ import { pmPost } from './http.js';
6
+ import { proposalsModel, editBody, acceptBody, rejectBody, askBody, askLine, issueBody, mdHtml, sectionAttribution } from './premium-doc-edit.js';
7
+ import { $, $$, esc, openDlg, closeDlg, toast, loadThread, logHtml, turnA, ptx, kv, CHECK, CHEV, AI } from './premium-shell.js';
8
+
9
+ const when = (iso) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(iso || '')); if (!m) return ''; return +m[3] + ' ' + ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][+m[2] - 1]; };
10
+
11
+ export function mountDocSheet(ctx) {
12
+ let sheet = null; // { d, tab, text, log, health, props, draft, why, ask, askText, picked, busy, msg, err }
13
+ const TABS = [['read', 'Read'], ['edit', 'Edit'], ['props', 'Proposals'], ['log', 'Edit log'], ['health', 'Health']];
14
+ const wsq = () => (ctx.ws() ? '&ws=' + encodeURIComponent(ctx.ws()) : '');
15
+ const propsM = (s) => proposalsModel(s.props || []);
16
+ /** The bar above a draft (core document Issue, initiative premium-core-doc-issue). The words are fixed; the state is the row's own. */
17
+ function issueBar(s) {
18
+ const d = s.d;
19
+ if (s.issued && d.st !== 'draft') return `<div class="dsiss dsok" data-issue-bar="done" role="status"><span>${CHECK}Issued. Nothing was sent to anyone. The row now reads ${esc(d.state)}.</span></div>`;
20
+ if (d.st !== 'draft' || !d.slot) return '';
21
+ return `<div class="dsiss" data-issue-bar="draft"><span>${AI}PMOS drafted this from its sources. Nothing is sent. ${ctx.again ? 'Read it, then issue it, or draft it again.' : 'Read it, change what you like, then issue it.'}</span><span class="dsa"><button class="dmcta dark" data-ds="issue"${s.busy ? ' disabled' : ''}>Issue it</button>${ctx.again ? `<button class="dmcta alt" data-ds="again"${s.busy ? ' disabled' : ''}>Draft it again</button>` : ''}</span></div>`
22
+ + (s.msg && s.tab === 'read' ? `<p class="note" id="dsErr" role="alert" style="margin:-4px 0 10px;color:var(--ember-ink)">${esc(s.msg)}</p>` : '');
23
+ }
24
+ 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 || ''));
25
+ /** Who last changed each section, read once the Read view has its text: the text at each revision (the newest 12), compared section by section. */
26
+ async function loadAttr() {
27
+ const s = sheet; if (!s || s.attr || s.text == null || !s.log || !s.log.ok) return;
28
+ const revs = (s.log.revisions || []).slice(-12); if (revs.length < 1) return;
29
+ const p = encodeURIComponent(s.d.path), ws = ctx.ws() ? '&ws=' + encodeURIComponent(ctx.ws()) : '';
30
+ const texts = await Promise.all(revs.map((r) => getJson('/api/doc-sheet/at?path=' + p + '&rev=' + r.rev + ws).then((a) => (a && a.ok ? a.text : null))));
31
+ if (sheet !== s) return;
32
+ const hit = sectionAttribution(revs, texts), attr = {};
33
+ Object.keys(hit).forEach((n) => { const r = revs[hit[n]], w = whoOf(r); attr[n] = { who: w, initial: (w[0] || '?').toUpperCase(), rev: 'rev ' + r.rev, date: when(r.at) }; });
34
+ s.attr = attr; s.md = null; if (s.tab === 'read') drawSheet();
35
+ }
36
+ /** The outline's rows: each heading at its own depth, filtered by the Find a heading box, with a dot on a heading an open proposal touches. */
37
+ function olItems(s, m) {
38
+ const q = String(s.olq || '').trim().toLowerCase(), lo = Math.min(...m.levels), mk = s.props ? propsM(s).marked : new Set();
39
+ const rows = m.outline.map((t, n) => ({ t, n, l: Math.min(3, m.levels[n] - lo + 1) })).filter((x) => !q || x.t.toLowerCase().includes(q));
40
+ return rows.length ? rows.map((x) => `<button type="button" data-go="${x.n}" class="l${x.l}${s.cur === x.n ? ' on' : ''}">${esc(x.t)}${mk.has(x.t) ? '<i></i>' : ''}</button>`).join('') : '<p class="note">No heading matches.</p>';
41
+ }
42
+ function sheetPane() {
43
+ const s = sheet, d = s.d;
44
+ const cnt = (k) => (k === 'props' && s.props && propsM(s).count ? ` <em>${propsM(s).count}</em>` : '');
45
+ const EYE = '<svg class="i" viewBox="0 0 24 24"><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>';
46
+ const revs = (s.log && s.log.revisions) || [], last = revs[revs.length - 1], m0 = s.md || (s.text != null ? (s.md = mdHtml(s.text, { attr: s.attr })) : null);
47
+ const menu = `<div class="dsvr" id="shT"><span class="dsvw"><button type="button" class="dsvb" id="shV" aria-haspopup="menu" aria-expanded="${!!s.vm}">${EYE}${esc(TABS.find((t) => t[0] === s.tab)[1])}${cnt(s.tab)}${CHEV}</button>${s.vm ? `<div class="dsmn" role="menu" aria-label="Document views">${TABS.map(([k, n]) => `<button type="button" role="menuitem" data-sh="${k}" aria-current="${s.tab === k}">${n}${cnt(k)}${s.tab === k ? CHECK : ''}</button>`).join('')}</div>` : ''}</span>${s.tab === 'read' && m0 && m0.outline.length > 2 ? `<button type="button" class="dsvb ol" data-ds="olt" aria-pressed="${!s.olHide}">${s.olHide ? 'Show the outline' : 'Hide the outline'}</button>` : ''}</div>`;
48
+ const chk = s.health && s.health.total ? `<button type="button" class="chp lk ${s.health.passed === s.health.total ? 'ok' : 'warn'}" data-sh="health"><i></i>${s.health.passed} of ${s.health.total} checks</button>` : '';
49
+ const file = String(d.path).split('/').pop();
50
+ const head = `<div class="dsm2"><span class="chp ${d.st === 'ok' ? 'ok' : d.st === 'draft' ? 'warn' : ''}"><i></i>${esc(d.state)}</span>${revs.length ? `<span class="chp mono">v${revs.length}</span>` : ''}${chk}<button type="button" class="chp lk" data-ds="meta" aria-expanded="${!!s.meta}" title="${esc(d.path)}">${esc(file)}</button>${last ? `<span class="chp"><span>Last change: <b>${esc(whoOf(last))}</b>${last.at ? ', ' + esc(when(last.at)) : ''}</span></span>` : ''}${d.when && !last ? `<span class="chp">updated ${esc(d.when)}</span>` : ''}</div>${s.meta ? `<div class="dsmeta"><p class="dpath">${esc(d.path)}</p>${m0 && m0.fm.length ? kv(m0.fm) : '<p class="note">The file has no front matter.</p>'}</div>` : ''}`;
51
+ let body = '';
52
+ if (s.err) body = `<p class="empty3 plain">${esc(s.err)}</p>`;
53
+ else if (s.tab === 'read') {
54
+ if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
55
+ else {
56
+ const m = s.md || (s.md = mdHtml(s.text, { attr: s.attr })), has = m.outline.length > 2 && !s.olHide;
57
+ const nav = `<nav class="dso" aria-label="Outline"><p class="label">Outline <em>${m.outline.length} headings</em></p>${m.outline.length > 12 ? `<input id="dsOlq" class="dsfind" type="search" placeholder="Find a heading" aria-label="Find a heading" autocomplete="off" value="${esc(s.olq || '')}">` : ''}<div id="dsOlItems">${olItems(s, m)}</div></nav>`;
58
+ body = issueBar(s) + `<div class="dsrd${has ? '' : ' no'}">${has ? nav : ''}<div class="dsbody">${m.html}</div></div>`;
59
+ }
60
+ } else if (s.tab === 'edit') {
61
+ if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
62
+ else {
63
+ const cur = s.draft == null ? s.text : s.draft, nv = ((s.log && s.log.revisions) || []).length + 1;
64
+ body = `<textarea id="dsEd" class="dsed" spellcheck="true" aria-label="Edit the document">${esc(cur)}</textarea>`
65
+ + `<p class="note" id="dsNote" style="margin:8px 0">${cur === s.text ? 'No changes yet.' : 'Changed. Health checks the document again after you save.'}</p>`
66
+ + `<input id="dsWhy" class="dsy" placeholder="Why are you changing it? Kept in the edit log." aria-label="Why are you changing it" value="${esc(s.why || '')}">`
67
+ + `<p class="note" id="dsErr" role="alert" style="margin:6px 0 0;color:var(--ember-ink)">${esc(s.msg || '')}</p>`
68
+ + `<div class="dsfoot"><span class="note">Saved by you as v${nv}</span><span><button class="dmcta alt" data-ds="discard">Cancel</button><button class="dmcta dark" id="dsSave" data-ds="save"${s.busy || cur === s.text ? ' disabled' : ''}>Save as v${nv}</button></span></div>`;
69
+ }
70
+ } else if (s.tab === 'props') {
71
+ if (!s.props) body = '<p class="empty3 plain">Reading the proposals.</p>';
72
+ else {
73
+ const m = propsM(s), line = askLine(s.ask);
74
+ body = `<div class="dsask2"><p class="label">${AI}Ask the agent</p><textarea id="dsAsk" rows="3" placeholder="Tell the agent what to change, for example: add a one-paragraph summary at the top" aria-label="Tell the agent what to change">${esc(s.askText || '')}</textarea><div class="dsrow"><button class="dmcta alt" data-ds="ask"${s.busy || (s.ask && s.ask.state === 'working') ? ' disabled' : ''}>${AI}Ask the agent</button></div><p class="note" style="margin:8px 0 0">The agent drafts a proposal and can only read. Nothing in the document changes until you accept it, and your request is kept in the edit log.</p>${line ? `<p class="note" role="status" style="margin:6px 0 0">${esc(line)}</p>` : ''}</div>`
75
+ + `<p class="label" style="margin:18px 0 8px">Open proposals · ${m.count}</p>`
76
+ + (m.count ? m.open.map((p) => propHtml(s, p)).join('') : `<div class="dsnone">${CHECK}No open proposals.</div>`)
77
+ + (m.closed.length ? `<p class="label" style="margin:18px 0 8px">Closed · ${m.closed.length}</p>${m.closed.map((p) => `<div class="dsp ${esc(p.state)}"><div><b>${esc(p.who)}</b><span>${esc(p.request)}</span>${p.why ? `<q>${esc(p.why)}</q>` : ''}</div><span class="dst2">${esc(p.label)}</span></div>`).join('')}` : '')
78
+ + `<p class="note" id="dsErr" role="alert" style="margin:10px 0 0;color:var(--ember-ink)">${esc(s.msg || '')}</p>`;
79
+ }
80
+ } else if (s.tab === 'log') {
81
+ if (!s.log) body = '<p class="empty3 plain">Reading the log.</p>';
82
+ else {
83
+ const R = (s.log.revisions || []).slice().reverse(), E = (s.log.events || []).slice().reverse();
84
+ body = (R.length ? `<div class="evl">${R.map((r) => `<div class="hsr"><time>${esc(when(r.at))}</time><span><b>v${esc(r.rev)}</b> ${esc(r.why || (r.by === 'baseline' ? 'The file as the sheet first saw it' : 'No reason recorded'))}${r.by ? ' · ' + esc(r.by) : ''}</span></div>`).join('')}</div>` : '<p class="mut">No revision is recorded.</p>')
85
+ + (E.length ? `<p class="label" style="margin:18px 0 8px">Other entries</p><div class="evl">${E.map((e) => `<div class="hsr"><time>${esc(when(e.at))}</time><span><b>${esc(e.kind)}</b> ${esc(e.prompt || e.why || '')}</span></div>`).join('')}</div>` : '');
86
+ }
87
+ } else if (s.tab === 'health') {
88
+ if (!s.health) body = '<p class="empty3 plain">Checking the document.</p>';
89
+ else body = `<p class="note" style="margin:0 0 10px">${s.health.passed} of ${s.health.total} checks that had the input they need passed. A check with no input is not counted.</p><div class="ckl">${s.health.checks.map((c) => `<div class="ckr ${c.pass === true ? 'done' : c.pass === false ? 'blocked' : 'skipped'}"><i></i><b>${esc(c.id)}</b><span>${c.pass === true ? 'Passed' : c.pass === false ? 'Not passed' : 'No input'}</span><small>${esc(c.reason || '')}</small></div>`).join('')}</div>`;
90
+ }
91
+ return `<article class="paper doc">${head}${menu}<div id="shBody">${body}</div><p class="xn">Every change is kept in the Edit log with its reason. The file changes only when you press Save or Accept.</p></article>`;
92
+ }
93
+ function propHtml(s, p) {
94
+ const picked = s.picked && s.picked[p.id], on = (n) => (picked ? picked.includes(n) : true);
95
+ const secs = p.sections.map((x) => `<div class="dsdf">${p.sections.length > 1 && !x.stale ? `<label><input type="checkbox" data-pk="${esc(p.id)}" value="${esc(x.name)}"${on(x.name) ? ' checked' : ''}> ` : ''}<b>${esc(x.name)}</b>${p.sections.length > 1 && !x.stale ? '</label>' : ''} ${x.stale ? '<span class="dst2">Changed since this was proposed</span>' : `<ins>+ ${esc(x.add)}</ins>`}</div>`).join('');
96
+ return `<div class="dsp"><div><b>${esc(p.who)}</b><span>${esc(p.request)}</span>${secs}${p.staleAll ? '<q>The document changed since this was proposed, so it cannot be accepted. Ask again.</q>' : ''}</div><div class="dsa">${p.canAccept ? `<button class="dmcta dark" data-ds="acc:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Accept</button>` : ''}<button class="dmcta alt" data-ds="rej:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Reject</button></div>${s.rejecting === p.id ? `<div class="dsrow" style="grid-column:1/-1"><input id="dsRj" class="dsy" placeholder="Why are you rejecting it? Kept in the edit log." aria-label="Why are you rejecting it" value="${esc(s.rejWhy || '')}"><button class="dmcta dark" data-ds="rejgo:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Reject it</button><button class="dmcta alt" data-ds="rejno">Cancel</button></div>` : ''}</div>`;
97
+ }
98
+ function drawSheet() { $('#oMain').innerHTML = sheetPane(); }
99
+ async function getJson(url, init) { try { const r = await fetch(url, Object.assign({ credentials: 'same-origin' }, init || {})); return await r.json(); } catch { return null; } }
100
+ async function loadTab(tab) {
101
+ const s = sheet, p = encodeURIComponent(s.d.path), ws = ctx.ws() ? '&ws=' + encodeURIComponent(ctx.ws()) : '';
102
+ if (tab !== 'props' && tab !== 'log' && tab !== 'health' && !s.props) {
103
+ const pr = await getJson('/api/doc-sheet/proposals?path=' + p + ws);
104
+ if (sheet !== s) return;
105
+ if (pr && pr.ok) s.props = pr.proposals || [];
106
+ }
107
+ if ((tab === 'read' || tab === 'edit') && s.text == null) {
108
+ const lg = s.log || (s.log = await getJson('/api/doc-sheet/log?path=' + p + ws));
109
+ if (sheet !== s) return;
110
+ const revs = lg && lg.ok ? lg.revisions || [] : [];
111
+ const at = revs.length ? await getJson('/api/doc-sheet/at?path=' + p + '&rev=' + revs[revs.length - 1].rev + ws) : null;
112
+ if (sheet !== s) return;
113
+ if (at && at.ok) s.text = at.text; else s.err = (at && at.error) || (lg && lg.error) || 'The file could not be read.';
114
+ } else if (tab === 'props' && !s.props) {
115
+ const pr = await getJson('/api/doc-sheet/proposals?path=' + p + ws);
116
+ if (sheet !== s) return;
117
+ if (!pr || pr.ok === false) s.err = (pr && pr.error) || 'The proposals could not be read.'; else s.props = pr.proposals || [];
118
+ } else if (tab === 'log' && !s.log) {
119
+ s.log = await getJson('/api/doc-sheet/log?path=' + p + ws);
120
+ if (sheet !== s) return;
121
+ if (!s.log || s.log.ok === false) { s.err = (s.log && s.log.error) || 'The edit log could not be read.'; s.log = null; }
122
+ } else if (tab === 'health' && !s.health) {
123
+ const h = await getJson('/api/doc-health/check', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path: s.d.path, ws: ctx.ws() }) });
124
+ if (sheet !== s) return;
125
+ if (!h || h.ok === false) s.err = (h && h.error) || 'The health check could not run.'; else s.health = h.health;
126
+ }
127
+ if (sheet === s && s.tab === tab) drawSheet();
128
+ if (tab === 'read' && s.text != null) loadAttr();
129
+ }
130
+ /** The checks chip of the status line: the same health check the Health view runs, read once when the sheet opens. */
131
+ async function loadChip() {
132
+ const s = sheet, h = await getJson('/api/doc-health/check', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path: s.d.path, ws: ctx.ws() }) });
133
+ if (sheet !== s || !h || h.ok === false || !h.health) return;
134
+ s.health = h.health; if (s.tab === 'read') drawSheet();
135
+ }
136
+ function openSheet(d) {
137
+ if (!d || !d.path) return;
138
+ sheet = { d, tab: 'read', text: null, log: null, health: null, props: null, draft: null, why: '', ask: null, askText: '', picked: {}, busy: false, msg: '', err: null };
139
+ const key = ctx.noteKey(d), say = d.title + ' is ' + d.state.toLowerCase() + (d.by ? '. ' + d.by + '.' : '.') + ' I can read the file with you and answer questions. I change nothing; only you change the file, with Save or Accept.';
140
+ openDlg({ eye: 'Document · real data', title: d.title, sub: ctx.sub(), say, stream: turnA(logHtml({ logTitle: 'Read from the repository', log: ['Found the file ' + d.path, 'Read its revisions from the document sheet', 'Left the file as it is'] })) + turnA(ptx(say)), noteKey: key, pane: '', label: 'Document' });
141
+ drawSheet(); loadThread(key); loadTab('read'); loadChip();
142
+ }
143
+ $('#oMain').addEventListener('click', (e) => {
144
+ if (sheet && sheet.vm && !e.target.closest('.dsvw')) { sheet.vm = false; drawSheet(); }
145
+ if (sheet && e.target.closest('#shV')) { keepDraft(); sheet.vm = !sheet.vm; drawSheet(); return; }
146
+ const t = e.target.closest('[data-sh]');
147
+ if (t && sheet) { keepDraft(); sheet.vm = false; sheet.tab = t.dataset.sh; sheet.err = null; sheet.msg = ''; drawSheet(); loadTab(sheet.tab); return; }
148
+ const b = e.target.closest('[data-ds]'); if (b && sheet) { sheetPress(b.dataset.ds); return; }
149
+ const g = e.target.closest('[data-go]'); if (g) { if (sheet) sheet.cur = +g.dataset.go; $$('#dsOlItems [data-go]').forEach((x) => x.classList.toggle('on', x === g)); const h = $('#ds-h' + g.dataset.go); if (h) h.scrollIntoView({ block: 'start', behavior: 'smooth' }); }
150
+ });
151
+ $('#oMain').addEventListener('change', (e) => { const c = e.target.closest('[data-pk]'); if (c && sheet) sheet.picked[c.dataset.pk] = $$('[data-pk]', $('#oMain')).filter((x) => x.dataset.pk === c.dataset.pk && x.checked).map((x) => x.value); });
152
+ $('#oMain').addEventListener('input', (e) => {
153
+ if (!sheet) return;
154
+ if (e.target.id === 'dsEd') { sheet.draft = e.target.value; const ch = sheet.draft !== sheet.text; $('#dsSave').disabled = !ch || sheet.busy; $('#dsNote').textContent = ch ? 'Changed. Health checks the document again after you save.' : 'No changes yet.'; }
155
+ else if (e.target.id === 'dsWhy') sheet.why = e.target.value;
156
+ else if (e.target.id === 'dsAsk') sheet.askText = e.target.value;
157
+ else if (e.target.id === 'dsOlq') { sheet.olq = e.target.value; const it = $('#dsOlItems'); if (it && sheet.md) it.innerHTML = olItems(sheet, sheet.md); }
158
+ else if (e.target.id === 'dsRj') sheet.rejWhy = e.target.value;
159
+ });
160
+ function keepDraft() { if (!sheet) return; const ed = $('#dsEd'), w = $('#dsWhy'), a = $('#dsAsk'), rj = $('#dsRj'); if (rj) sheet.rejWhy = rj.value; if (ed) sheet.draft = ed.value; if (w) sheet.why = w.value; if (a) sheet.askText = a.value; }
161
+ /* the sheet's presses: each posts to one existing /api/doc-sheet route (ws in the query, as the routes read it) and then reads the routes again */
162
+ const dsPost = (route, body) => pmPost('/api/doc-sheet/' + route + (ctx.ws() ? '?ws=' + encodeURIComponent(ctx.ws()) : ''), body);
163
+ async function reloadSheet(s) {
164
+ s.text = null; s.md = null; s.attr = null; s.log = null; s.health = null; s.props = null; s.draft = null; s.why = ''; s.rejecting = null;
165
+ await loadTab(s.tab);
166
+ if (sheet === s) { s.busy = false; drawSheet(); }
167
+ }
168
+ async function sheetPress(act) {
169
+ const s = sheet; keepDraft();
170
+ const fail = (m) => { s.busy = false; s.msg = m; drawSheet(); };
171
+ if (act === 'meta') { s.meta = !s.meta; drawSheet(); return; }
172
+ if (act === 'olt') { s.olHide = !s.olHide; drawSheet(); return; }
173
+ if (act === 'rejno') { s.rejecting = null; s.msg = ''; drawSheet(); return; }
174
+ if (act === 'discard') { s.draft = null; s.why = ''; s.msg = ''; drawSheet(); return; }
175
+ if (act === 'again') {
176
+ s.busy = true; s.msg = ''; drawSheet();
177
+ const res = await pmPost('/api/core-docs/draft', { ws: ctx.ws(), scope: ctx.scope(), key: s.d.key }); if (sheet !== s) return;
178
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The draft could not be started.');
179
+ toast('The agent is drafting “' + s.d.title + '” again. The new draft replaces this one when it is ready, and it sends nothing.');
180
+ s.busy = false; closeDlg(); await ctx.reload(); return;
181
+ }
182
+ if (act === 'issue') {
183
+ const r = issueBody(ctx.ws(), ctx.scope(), s.d.key, s.d.slot, s.draft != null && s.draft !== s.text); if (r.error) return fail(r.error);
184
+ s.busy = true; s.msg = ''; drawSheet();
185
+ const res = await pmPost('/api/core-docs/issue', r.body); if (sheet !== s) return;
186
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The document could not be issued.');
187
+ toast('Issued. Nothing was sent to anyone.');
188
+ s.issued = true; await ctx.reload(); if (sheet !== s) return;
189
+ s.d = ctx.rows().find((x) => x.key === s.d.key) || s.d;
190
+ return reloadSheet(s);
191
+ }
192
+ if (act === 'save') {
193
+ const r = editBody(s.d.path, s.text, s.draft == null ? s.text : s.draft, s.why); if (r.error) return fail(r.error);
194
+ s.busy = true; s.msg = ''; drawSheet();
195
+ const res = await dsPost('edit', r.body); if (sheet !== s) return;
196
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The document could not be saved.');
197
+ toast('Saved. The reason is in the Edit log.'); return reloadSheet(s);
198
+ }
199
+ if (act === 'ask') {
200
+ const r = askBody(s.d.path, s.askText); if (r.error) return fail(r.error);
201
+ s.busy = true; s.msg = ''; drawSheet();
202
+ const res = await dsPost('ask', r.body); if (sheet !== s) return;
203
+ s.busy = false;
204
+ if (!res || res.ok !== true || !res.id) return fail((res && res.error) || 'The agent could not be asked.');
205
+ s.askText = ''; s.ask = { state: 'working', id: res.id }; drawSheet(); return pollAsk(s, res.id);
206
+ }
207
+ const [kind, id] = [act.split(':')[0], act.slice(act.indexOf(':') + 1)];
208
+ const p = propsM(s).open.find((x) => x.id === id); if (!p) return;
209
+ if (kind === 'acc') {
210
+ const r = acceptBody(s.d.path, p, s.picked[id] || p.sections.filter((x) => !x.stale).map((x) => x.name)); if (r.error) return fail(r.error);
211
+ s.busy = true; s.msg = ''; drawSheet();
212
+ const res = await dsPost('accept', r.body); if (sheet !== s) return;
213
+ if (!res || res.ok !== true) { await reloadSheet(s); return fail((res && res.error) || 'The proposal could not be accepted.'); }
214
+ toast('Accepted. The file changed and the request is in the Edit log.'); return reloadSheet(s);
215
+ }
216
+ if (kind === 'rej') { s.rejecting = id; s.rejWhy = ''; s.msg = ''; drawSheet(); const f = $('#dsRj'); if (f) f.focus(); return; }
217
+ if (kind === 'rejgo') {
218
+ const r = rejectBody(s.d.path, p, s.rejWhy); if (r.error) return fail(r.error);
219
+ s.busy = true; s.msg = ''; drawSheet();
220
+ const res = await dsPost('reject', r.body); if (sheet !== s) return;
221
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The proposal could not be rejected.');
222
+ toast('Rejected. The file is as it was.'); return reloadSheet(s);
223
+ }
224
+ }
225
+ async function pollAsk(s, id) {
226
+ for (let i = 0; i < 400 && sheet === s; i++) {
227
+ await new Promise((r) => setTimeout(r, 2000));
228
+ const a = await getJson('/api/doc-sheet/ask?id=' + encodeURIComponent(id) + wsq()); if (sheet !== s) return;
229
+ if (!a || a.ok === false) { s.ask = { state: 'failed', error: (a && a.error) || 'The answer could not be read.' }; drawSheet(); return; }
230
+ s.ask = a;
231
+ if (a.state !== 'working') { s.props = null; await loadTab('props'); if (sheet === s) drawSheet(); return; }
232
+ if (s.tab === 'props') drawSheet();
233
+ }
234
+ }
235
+ return { open: openSheet };
236
+ }
@@ -5,7 +5,7 @@
5
5
  * existing /api/doc-sheet routes, initiative briefing-premium-doc-edit), Add a task and a task's status, and the bar under the stages (initiative
6
6
  * premium-board-actions, pm/premium-acts.js): move to the next stage or back, hold, cancel, archive, resume, reopen and restore, each with Undo. Nothing here issues a document. */
7
7
  import { pmPost } from './http.js';
8
- import { proposalsModel, editBody, acceptBody, rejectBody, askBody, askLine, issueBody, mdHtml } from './premium-doc-edit.js';
8
+ import { mountDocSheet } from './premium-doc-sheet.js';
9
9
  import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, CHEV, crumbHtml, wireCrumb, AI, openAddDoc } from './premium-shell.js';
10
10
  import { barHtml, onBar, closeMenu } from './premium-acts.js';
11
11
 
@@ -14,6 +14,7 @@ let taskView = 'list';
14
14
  const DAY = 86400000;
15
15
  let docFilter = 'all', docQuery = '';
16
16
  let readTimer = null;
17
+ const docSheet = mountDocSheet({ ws: () => M.board.ws, scope: () => M.docs.scope, rows: () => M.docs.rows, reload: () => load(), noteKey: (d) => 'doc:' + M.id + ':' + d.key, sub: () => M.title, again: false });
17
18
  wireRail('init');
18
19
  const ICO = (p) => `<svg class="i" viewBox="0 0 24 24">${p}</svg>`;
19
20
  const DOCI = '<path d="M6 3h9l4 4v14H6z"/><path d="M14 3v5h5M9 13h6M9 17h4"/>';
@@ -114,7 +115,7 @@ $('#iMain').addEventListener('click', (e) => {
114
115
  const f = e.target.closest('[data-dmf]'); if (f) { docFilter = f.dataset.dmf; drawDocList(); return; }
115
116
  const d = e.target.closest('[data-draft]'); if (d && !d.disabled) { draft(d); return; }
116
117
  const all = e.target.closest('[data-draftall]'); if (all && !all.disabled) { draftAll(all); return; }
117
- const o = e.target.closest('[data-doc]'); if (o) { openSheet(M.docs.rows.find((x) => x.key === o.dataset.doc)); }
118
+ const o = e.target.closest('[data-doc]'); if (o) { docSheet.open(M.docs.rows.find((x) => x.key === o.dataset.doc)); }
118
119
  });
119
120
  const STATES = ['To do', 'In progress', 'In review', 'Done'];
120
121
  function openTask(t) {
@@ -219,187 +220,6 @@ function openAsk(q) {
219
220
  }
220
221
 
221
222
  /* ── the document sheet: Read, Edit, Proposals, Edit log, Health. ─────────────────────────────────────────────── */
222
- let sheet = null; // { d, tab, text, log, health, props, draft, why, ask, askText, picked, busy, msg, err }
223
- const TABS = [['read', 'Read'], ['edit', 'Edit'], ['props', 'Proposals'], ['log', 'Edit log'], ['health', 'Health']];
224
- const wsq = () => (M.board.ws ? '&ws=' + encodeURIComponent(M.board.ws) : '');
225
- const propsM = (s) => proposalsModel(s.props || []);
226
- /** The bar above a draft (core document Issue, initiative premium-core-doc-issue). The words are fixed; the state is the row's own. */
227
- function issueBar(s) {
228
- const d = s.d;
229
- if (s.issued && d.st !== 'draft') return `<div class="dsiss dsok" data-issue-bar="done" role="status"><span>${CHECK}Issued. Nothing was sent to anyone. The row now reads ${esc(d.state)}.</span></div>`;
230
- if (d.st !== 'draft' || !d.slot) return '';
231
- return `<div class="dsiss" data-issue-bar="draft"><span>${AI}PMOS drafted this from its sources. Nothing is sent. Read it, change what you like, then issue it.</span><button class="dmcta dark" data-ds="issue"${s.busy ? ' disabled' : ''}>Issue it</button></div>`
232
- + (s.msg && s.tab === 'read' ? `<p class="note" id="dsErr" role="alert" style="margin:-4px 0 10px;color:var(--ember-ink)">${esc(s.msg)}</p>` : '');
233
- }
234
- function sheetPane() {
235
- const s = sheet, d = s.d;
236
- const cnt = (k) => (k === 'props' && s.props && propsM(s).count ? ` <em>${propsM(s).count}</em>` : '');
237
- const EYE = '<svg class="i" viewBox="0 0 24 24"><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>';
238
- const menu = `<div class="dsvr" id="shT"><span class="dsvw"><button type="button" class="dsvb" id="shV" aria-haspopup="menu" aria-expanded="${!!s.vm}">${EYE}${esc(TABS.find((t) => t[0] === s.tab)[1])}${cnt(s.tab)}${CHEV}</button>${s.vm ? `<div class="dsmn" role="menu" aria-label="Document views">${TABS.map(([k, n]) => `<button type="button" role="menuitem" data-sh="${k}" aria-current="${s.tab === k}">${n}${cnt(k)}${s.tab === k ? CHECK : ''}</button>`).join('')}</div>` : ''}</span></div>`;
239
- const head = `<p class="dpath">${esc(d.path)}</p><div class="dsm"><span class="${d.st === 'ok' ? 'ok' : d.st === 'draft' ? 'warn' : 'mut'}">${esc(d.state)}</span>${d.when ? `<span>updated ${esc(d.when)}</span>` : ''}${d.by ? `<span>${esc(d.by)}</span>` : ''}</div>`;
240
- let body = '';
241
- if (s.err) body = `<p class="empty3 plain">${esc(s.err)}</p>`;
242
- else if (s.tab === 'read') {
243
- if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
244
- else { const m = s.md || (s.md = mdHtml(s.text)); body = issueBar(s) + (m.fm.length ? kv(m.fm) : '') + `<div class="dsrd${m.outline.length > 2 ? '' : ' no'}">${m.outline.length > 2 ? `<nav class="dso" aria-label="Outline"><p class="label">Outline <em>${m.outline.length} headings</em></p>${m.outline.map((t, n) => `<button data-go="${n}">${esc(t)}${s.props && propsM(s).marked.has(t) ? '<i></i>' : ''}</button>`).join('')}</nav>` : ''}<div class="dsbody">${m.html}</div></div>`; }
245
- } else if (s.tab === 'edit') {
246
- if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
247
- else {
248
- const cur = s.draft == null ? s.text : s.draft, nv = ((s.log && s.log.revisions) || []).length + 1;
249
- body = `<textarea id="dsEd" class="dsed" spellcheck="true" aria-label="Edit the document">${esc(cur)}</textarea>`
250
- + `<p class="note" id="dsNote" style="margin:8px 0">${cur === s.text ? 'No changes yet.' : 'Changed. Health checks the document again after you save.'}</p>`
251
- + `<input id="dsWhy" class="dsy" placeholder="Why are you changing it? Kept in the edit log." aria-label="Why are you changing it" value="${esc(s.why || '')}">`
252
- + `<p class="note" id="dsErr" role="alert" style="margin:6px 0 0;color:var(--ember-ink)">${esc(s.msg || '')}</p>`
253
- + `<div class="dsfoot"><span class="note">Saved by you as v${nv}</span><span><button class="dmcta alt" data-ds="discard">Cancel</button><button class="dmcta dark" id="dsSave" data-ds="save"${s.busy || cur === s.text ? ' disabled' : ''}>Save as v${nv}</button></span></div>`;
254
- }
255
- } else if (s.tab === 'props') {
256
- if (!s.props) body = '<p class="empty3 plain">Reading the proposals.</p>';
257
- else {
258
- const m = propsM(s), line = askLine(s.ask);
259
- body = `<div class="dsask2"><p class="label">${AI}Ask the agent</p><textarea id="dsAsk" rows="3" placeholder="Tell the agent what to change, for example: add a one-paragraph summary at the top" aria-label="Tell the agent what to change">${esc(s.askText || '')}</textarea><div class="dsrow"><button class="dmcta alt" data-ds="ask"${s.busy || (s.ask && s.ask.state === 'working') ? ' disabled' : ''}>${AI}Ask the agent</button></div><p class="note" style="margin:8px 0 0">The agent drafts a proposal and can only read. Nothing in the document changes until you accept it, and your request is kept in the edit log.</p>${line ? `<p class="note" role="status" style="margin:6px 0 0">${esc(line)}</p>` : ''}</div>`
260
- + `<p class="label" style="margin:18px 0 8px">Open proposals · ${m.count}</p>`
261
- + (m.count ? m.open.map((p) => propHtml(s, p)).join('') : `<div class="dsnone">${CHECK}No open proposals.</div>`)
262
- + (m.closed.length ? `<p class="label" style="margin:18px 0 8px">Closed · ${m.closed.length}</p>${m.closed.map((p) => `<div class="dsp ${esc(p.state)}"><div><b>${esc(p.who)}</b><span>${esc(p.request)}</span>${p.why ? `<q>${esc(p.why)}</q>` : ''}</div><span class="dst2">${esc(p.label)}</span></div>`).join('')}` : '')
263
- + `<p class="note" id="dsErr" role="alert" style="margin:10px 0 0;color:var(--ember-ink)">${esc(s.msg || '')}</p>`;
264
- }
265
- } else if (s.tab === 'log') {
266
- if (!s.log) body = '<p class="empty3 plain">Reading the log.</p>';
267
- else {
268
- const R = (s.log.revisions || []).slice().reverse(), E = (s.log.events || []).slice().reverse();
269
- body = (R.length ? `<div class="evl">${R.map((r) => `<div class="hsr"><time>${esc(when(r.at))}</time><span><b>v${esc(r.rev)}</b> ${esc(r.why || (r.by === 'baseline' ? 'The file as the sheet first saw it' : 'No reason recorded'))}${r.by ? ' · ' + esc(r.by) : ''}</span></div>`).join('')}</div>` : '<p class="mut">No revision is recorded.</p>')
270
- + (E.length ? `<p class="label" style="margin:18px 0 8px">Other entries</p><div class="evl">${E.map((e) => `<div class="hsr"><time>${esc(when(e.at))}</time><span><b>${esc(e.kind)}</b> ${esc(e.prompt || e.why || '')}</span></div>`).join('')}</div>` : '');
271
- }
272
- } else if (s.tab === 'health') {
273
- if (!s.health) body = '<p class="empty3 plain">Checking the document.</p>';
274
- else body = `<p class="note" style="margin:0 0 10px">${s.health.passed} of ${s.health.total} checks that had the input they need passed. A check with no input is not counted.</p><div class="ckl">${s.health.checks.map((c) => `<div class="ckr ${c.pass === true ? 'done' : c.pass === false ? 'blocked' : 'skipped'}"><i></i><b>${esc(c.id)}</b><span>${c.pass === true ? 'Passed' : c.pass === false ? 'Not passed' : 'No input'}</span><small>${esc(c.reason || '')}</small></div>`).join('')}</div>`;
275
- }
276
- return `<article class="paper doc">${head}${menu}<div id="shBody">${body}</div><p class="xn">Every change is kept in the Edit log with its reason. The file changes only when you press Save or Accept.</p></article>`;
277
- }
278
- function propHtml(s, p) {
279
- const picked = s.picked && s.picked[p.id], on = (n) => (picked ? picked.includes(n) : true);
280
- const secs = p.sections.map((x) => `<div class="dsdf">${p.sections.length > 1 && !x.stale ? `<label><input type="checkbox" data-pk="${esc(p.id)}" value="${esc(x.name)}"${on(x.name) ? ' checked' : ''}> ` : ''}<b>${esc(x.name)}</b>${p.sections.length > 1 && !x.stale ? '</label>' : ''} ${x.stale ? '<span class="dst2">Changed since this was proposed</span>' : `<ins>+ ${esc(x.add)}</ins>`}</div>`).join('');
281
- return `<div class="dsp"><div><b>${esc(p.who)}</b><span>${esc(p.request)}</span>${secs}${p.staleAll ? '<q>The document changed since this was proposed, so it cannot be accepted. Ask again.</q>' : ''}</div><div class="dsa">${p.canAccept ? `<button class="dmcta dark" data-ds="acc:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Accept</button>` : ''}<button class="dmcta alt" data-ds="rej:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Reject</button></div>${s.rejecting === p.id ? `<div class="dsrow" style="grid-column:1/-1"><input id="dsRj" class="dsy" placeholder="Why are you rejecting it? Kept in the edit log." aria-label="Why are you rejecting it" value="${esc(s.rejWhy || '')}"><button class="dmcta dark" data-ds="rejgo:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Reject it</button><button class="dmcta alt" data-ds="rejno">Cancel</button></div>` : ''}</div>`;
282
- }
283
- function drawSheet() { $('#oMain').innerHTML = sheetPane(); }
284
- async function getJson(url, init) { try { const r = await fetch(url, Object.assign({ credentials: 'same-origin' }, init || {})); return await r.json(); } catch { return null; } }
285
- async function loadTab(tab) {
286
- const s = sheet, p = encodeURIComponent(s.d.path), ws = M.board.ws ? '&ws=' + encodeURIComponent(M.board.ws) : '';
287
- if (tab !== 'props' && tab !== 'log' && tab !== 'health' && !s.props) {
288
- const pr = await getJson('/api/doc-sheet/proposals?path=' + p + ws);
289
- if (sheet !== s) return;
290
- if (pr && pr.ok) s.props = pr.proposals || [];
291
- }
292
- if ((tab === 'read' || tab === 'edit') && s.text == null) {
293
- const lg = s.log || (s.log = await getJson('/api/doc-sheet/log?path=' + p + ws));
294
- if (sheet !== s) return;
295
- const revs = lg && lg.ok ? lg.revisions || [] : [];
296
- const at = revs.length ? await getJson('/api/doc-sheet/at?path=' + p + '&rev=' + revs[revs.length - 1].rev + ws) : null;
297
- if (sheet !== s) return;
298
- if (at && at.ok) s.text = at.text; else s.err = (at && at.error) || (lg && lg.error) || 'The file could not be read.';
299
- } else if (tab === 'props' && !s.props) {
300
- const pr = await getJson('/api/doc-sheet/proposals?path=' + p + ws);
301
- if (sheet !== s) return;
302
- if (!pr || pr.ok === false) s.err = (pr && pr.error) || 'The proposals could not be read.'; else s.props = pr.proposals || [];
303
- } else if (tab === 'log' && !s.log) {
304
- s.log = await getJson('/api/doc-sheet/log?path=' + p + ws);
305
- if (sheet !== s) return;
306
- if (!s.log || s.log.ok === false) { s.err = (s.log && s.log.error) || 'The edit log could not be read.'; s.log = null; }
307
- } else if (tab === 'health' && !s.health) {
308
- const h = await getJson('/api/doc-health/check', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path: s.d.path, ws: M.board.ws }) });
309
- if (sheet !== s) return;
310
- if (!h || h.ok === false) s.err = (h && h.error) || 'The health check could not run.'; else s.health = h.health;
311
- }
312
- if (sheet === s && s.tab === tab) drawSheet();
313
- }
314
- function openSheet(d) {
315
- if (!d || !d.path) return;
316
- sheet = { d, tab: 'read', text: null, log: null, health: null, props: null, draft: null, why: '', ask: null, askText: '', picked: {}, busy: false, msg: '', err: null };
317
- const key = 'doc:' + M.id + ':' + d.key, say = d.title + ' is ' + d.state.toLowerCase() + (d.by ? '. ' + d.by + '.' : '.') + ' I can read the file with you and answer questions. I change nothing; only you change the file, with Save or Accept.';
318
- openDlg({ eye: 'Document · real data', title: d.title, sub: M.title, say, stream: turnA(logHtml({ logTitle: 'Read from the repository', log: ['Found the file ' + d.path, 'Read its revisions from the document sheet', 'Left the file as it is'] })) + turnA(ptx(say)), noteKey: key, pane: '', label: 'Document' });
319
- drawSheet(); loadThread(key); loadTab('read');
320
- }
321
- $('#oMain').addEventListener('click', (e) => {
322
- if (sheet && sheet.vm && !e.target.closest('.dsvw')) { sheet.vm = false; drawSheet(); }
323
- if (sheet && e.target.closest('#shV')) { keepDraft(); sheet.vm = !sheet.vm; drawSheet(); return; }
324
- const t = e.target.closest('[data-sh]');
325
- if (t && sheet) { keepDraft(); sheet.vm = false; sheet.tab = t.dataset.sh; sheet.err = null; sheet.msg = ''; drawSheet(); loadTab(sheet.tab); return; }
326
- const b = e.target.closest('[data-ds]'); if (b && sheet) { sheetPress(b.dataset.ds); return; }
327
- const g = e.target.closest('[data-go]'); if (g) { const h = $('#ds-h' + g.dataset.go); if (h) h.scrollIntoView({ block: 'start', behavior: 'smooth' }); }
328
- });
329
- $('#oMain').addEventListener('change', (e) => { const c = e.target.closest('[data-pk]'); if (c && sheet) sheet.picked[c.dataset.pk] = $$('[data-pk]', $('#oMain')).filter((x) => x.dataset.pk === c.dataset.pk && x.checked).map((x) => x.value); });
330
- $('#oMain').addEventListener('input', (e) => {
331
- if (!sheet) return;
332
- if (e.target.id === 'dsEd') { sheet.draft = e.target.value; const ch = sheet.draft !== sheet.text; $('#dsSave').disabled = !ch || sheet.busy; $('#dsNote').textContent = ch ? 'Changed. Health checks the document again after you save.' : 'No changes yet.'; }
333
- else if (e.target.id === 'dsWhy') sheet.why = e.target.value;
334
- else if (e.target.id === 'dsAsk') sheet.askText = e.target.value;
335
- else if (e.target.id === 'dsRj') sheet.rejWhy = e.target.value;
336
- });
337
- function keepDraft() { if (!sheet) return; const ed = $('#dsEd'), w = $('#dsWhy'), a = $('#dsAsk'), rj = $('#dsRj'); if (rj) sheet.rejWhy = rj.value; if (ed) sheet.draft = ed.value; if (w) sheet.why = w.value; if (a) sheet.askText = a.value; }
338
- /* the sheet's presses: each posts to one existing /api/doc-sheet route (ws in the query, as the routes read it) and then reads the routes again */
339
- const dsPost = (route, body) => pmPost('/api/doc-sheet/' + route + (M.board.ws ? '?ws=' + encodeURIComponent(M.board.ws) : ''), body);
340
- async function reloadSheet(s) {
341
- s.text = null; s.md = null; s.log = null; s.health = null; s.props = null; s.draft = null; s.why = ''; s.rejecting = null;
342
- await loadTab(s.tab);
343
- if (sheet === s) { s.busy = false; drawSheet(); }
344
- }
345
- async function sheetPress(act) {
346
- const s = sheet; keepDraft();
347
- const fail = (m) => { s.busy = false; s.msg = m; drawSheet(); };
348
- if (act === 'rejno') { s.rejecting = null; s.msg = ''; drawSheet(); return; }
349
- if (act === 'discard') { s.draft = null; s.why = ''; s.msg = ''; drawSheet(); return; }
350
- if (act === 'issue') {
351
- const r = issueBody(M.board.ws, M.docs.scope, s.d.key, s.d.slot, s.draft != null && s.draft !== s.text); if (r.error) return fail(r.error);
352
- s.busy = true; s.msg = ''; drawSheet();
353
- const res = await pmPost('/api/core-docs/issue', r.body); if (sheet !== s) return;
354
- if (!res || res.ok !== true) return fail((res && res.error) || 'The document could not be issued.');
355
- toast('Issued. Nothing was sent to anyone.');
356
- s.issued = true; await load(); if (sheet !== s) return;
357
- s.d = M.docs.rows.find((x) => x.key === s.d.key) || s.d;
358
- return reloadSheet(s);
359
- }
360
- if (act === 'save') {
361
- const r = editBody(s.d.path, s.text, s.draft == null ? s.text : s.draft, s.why); if (r.error) return fail(r.error);
362
- s.busy = true; s.msg = ''; drawSheet();
363
- const res = await dsPost('edit', r.body); if (sheet !== s) return;
364
- if (!res || res.ok !== true) return fail((res && res.error) || 'The document could not be saved.');
365
- toast('Saved. The reason is in the Edit log.'); return reloadSheet(s);
366
- }
367
- if (act === 'ask') {
368
- const r = askBody(s.d.path, s.askText); if (r.error) return fail(r.error);
369
- s.busy = true; s.msg = ''; drawSheet();
370
- const res = await dsPost('ask', r.body); if (sheet !== s) return;
371
- s.busy = false;
372
- if (!res || res.ok !== true || !res.id) return fail((res && res.error) || 'The agent could not be asked.');
373
- s.askText = ''; s.ask = { state: 'working', id: res.id }; drawSheet(); return pollAsk(s, res.id);
374
- }
375
- const [kind, id] = [act.split(':')[0], act.slice(act.indexOf(':') + 1)];
376
- const p = propsM(s).open.find((x) => x.id === id); if (!p) return;
377
- if (kind === 'acc') {
378
- const r = acceptBody(s.d.path, p, s.picked[id] || p.sections.filter((x) => !x.stale).map((x) => x.name)); if (r.error) return fail(r.error);
379
- s.busy = true; s.msg = ''; drawSheet();
380
- const res = await dsPost('accept', r.body); if (sheet !== s) return;
381
- if (!res || res.ok !== true) { await reloadSheet(s); return fail((res && res.error) || 'The proposal could not be accepted.'); }
382
- toast('Accepted. The file changed and the request is in the Edit log.'); return reloadSheet(s);
383
- }
384
- if (kind === 'rej') { s.rejecting = id; s.rejWhy = ''; s.msg = ''; drawSheet(); const f = $('#dsRj'); if (f) f.focus(); return; }
385
- if (kind === 'rejgo') {
386
- const r = rejectBody(s.d.path, p, s.rejWhy); if (r.error) return fail(r.error);
387
- s.busy = true; s.msg = ''; drawSheet();
388
- const res = await dsPost('reject', r.body); if (sheet !== s) return;
389
- if (!res || res.ok !== true) return fail((res && res.error) || 'The proposal could not be rejected.');
390
- toast('Rejected. The file is as it was.'); return reloadSheet(s);
391
- }
392
- }
393
- async function pollAsk(s, id) {
394
- for (let i = 0; i < 400 && sheet === s; i++) {
395
- await new Promise((r) => setTimeout(r, 2000));
396
- const a = await getJson('/api/doc-sheet/ask?id=' + encodeURIComponent(id) + wsq()); if (sheet !== s) return;
397
- if (!a || a.ok === false) { s.ask = { state: 'failed', error: (a && a.error) || 'The answer could not be read.' }; drawSheet(); return; }
398
- s.ask = a;
399
- if (a.state !== 'working') { s.props = null; await loadTab('props'); if (sheet === s) drawSheet(); return; }
400
- if (s.tab === 'props') drawSheet();
401
- }
402
- }
403
223
  $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
404
224
 
405
225
  /* ── load: the routes derive the initiatives in the background, so the first answers are "reading" ────────── */