create-pmos 0.271.0 → 0.273.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.
@@ -3,11 +3,13 @@
3
3
  * line, what stands out), the Reports card, the dock and the standard dialog.
4
4
  * briefing-premium-reports adds the PM's presses, each through pmPost and so behind the launch nonce: a saved dashboard (POST /api/premium-dashboards/save,
5
5
  * PRD D2 to D6) and the report presses of the console's Reports workspace (POST /api/report-setups/ask | change | cancel | setup | dismiss | pause | resume |
6
- * draft, PRD R2 to R4). premium-studio-chart adds a saved chart (POST /api/premium-charts/save, PRD C1, C10) and its four forms (C3). Nothing else posts, and
7
- * nothing is sent outward. */
6
+ * draft, PRD R2 to R4). premium-studio-chart adds a saved chart (POST /api/premium-charts/save, PRD C1, C10) and its four forms (C3). premium-studio-report
7
+ * adds New report and Shape it in the Studio, whose presses are POST /api/report-setups/setup | from-dashboard and POST /api/report-structure/turn | remove |
8
+ * revert | accept (PRD R5 to R8). Nothing else posts, and nothing is sent outward. */
8
9
  import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv } from './premium-shell.js';
9
- import { pmPost } from './http.js';
10
+ import { pmPost, pmGet } from './http.js';
10
11
  import { openStudio } from './premium-studio.js';
12
+ import { openReport } from './premium-report-read.js';
11
13
 
12
14
  let M = null; // the model
13
15
  let dash = 'all'; // the dashboard on screen
@@ -164,10 +166,17 @@ $('#dashBar').addEventListener('click', (e) => { if (e.target.closest('#pdEdit')
164
166
  /* ── a dashboard is made and edited in the Insight Studio (initiative premium-studio-dashboard). Its one press posts POST /api/premium-dashboards/save. ── */
165
167
  async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
166
168
  async function saveChart(body) { return pmPost('/api/premium-charts/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
167
- const studioOf = (o) => openStudio(Object.assign({ M, tile: tileHtml, derive: deriveChart, save: saveDash, saveChart, done: async (id) => { dash = id || dash; if (!M.dashboards.some((d) => d.id === dash)) dash = 'all'; await load(); } }, o));
169
+ const structure = {
170
+ get: (id) => pmGet('/api/report-structure?ws=' + encodeURIComponent(M.board.ws || '') + '&id=' + encodeURIComponent(id)),
171
+ post: (sub, id, body) => pmPost('/api/report-structure/' + sub, Object.assign({ ws: M.board.ws, id }, body)),
172
+ };
173
+ const studioOf = (o) => openStudio(Object.assign({ M, tile: tileHtml, derive: deriveChart, save: saveDash, saveChart, setup: (sub, body) => repPost(sub, body), structure, reportsChanged: () => load(),
174
+ done: async (id) => { dash = id || dash; if (!M.dashboards.some((d) => d.id === dash)) dash = 'all'; await load(); } }, o));
168
175
  function openDashEdit(D) { studioOf({ mode: 'dash', D, done: async (id) => { dash = id || 'all'; await load(); } }); }
169
176
  /* A chart is made and edited in the Studio's Chart mode (initiative premium-studio-chart). Save posts POST /api/premium-charts/save. */
170
177
  function openChartEdit(id) { studioOf({ mode: 'chart', C: id ? (M.mineSaved || []).find((x) => x.id === id) || null : null }); }
178
+ /* A report is set up and shaped in the Studio's Report mode (initiative premium-studio-report). */
179
+ function openReportEdit(s) { studioOf({ mode: 'rep', R: s || null }); }
171
180
  $('#dashBody').addEventListener('click', (e) => { const o = e.target.closest('[data-open]'); if (o) { openChart(byKey(o.dataset.open)); return; } const ed = e.target.closest('[data-ced]'); if (ed) openChartEdit(ed.dataset.ced); });
172
181
  $('#dashBody').addEventListener('keydown', (e) => {
173
182
  const t = e.target.closest && e.target.closest('.mch'); if (!t || !/^Arrow(Left|Right)$/.test(e.key)) return;
@@ -186,7 +195,7 @@ let askTimer = 0;
186
195
  const dismissing = new Map(); // finding id → timer: "Not a report" waits 5 s for an Undo before it is sent
187
196
  const ASKST = { running: ['Working', 'draft'], ready: ['Ready to review', 'issued'], failed: ['Failed', 'none'] };
188
197
  function repRow(r) {
189
- return `<div class="dmr ${esc(r.state)}" role="listitem"><button class="dmo" data-rep="1" title="Opens in the console's Reports tab"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(r.cadence)} · ${esc(r.date || r.slot)}</b><small>${esc(r.path)}</small><span class="dmm"><span class="s ${esc(r.state === 'issued' ? 'issued' : 'draft')}">${esc(r.stateLabel)}</span><span>Opens in the console</span></span></span></button></div>`;
198
+ return `<div class="dmr ${esc(r.state)}" role="listitem"><button class="dmo" data-rep="${esc(r.key)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(r.cadence)} · ${esc(r.date || r.slot)}</b><small>${esc(r.path)}</small><span class="dmm"><span class="s ${esc(r.state === 'issued' ? 'issued' : 'draft')}">${esc(r.stateLabel)}</span><span>Deck, present, download, print</span></span></span></button></div>`;
190
199
  }
191
200
  const foundRow = (f) => `<div class="dmr" role="listitem"><button class="dmo" data-found="${esc(f.id)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(AIC)}</span><span class="dmn"><b>${esc(f.name)}</b><small>${esc(f.why)}</small><span class="dmm">${f.confidence ? `<span>${esc(f.confidence)}</span>` : ''}<span>${f.evidence.length} ${f.evidence.length === 1 ? 'sign' : 'signs'} in your work</span></span></span></button></div>`;
192
201
  const askRow = (a) => `<div class="dmr" role="listitem"><button class="dmo" data-ask="${esc(a.id)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(AIC)}</span><span class="dmn"><b>${esc(a.proposal && a.proposal.name ? a.proposal.name : a.text)}</b><small>You asked: ${esc(a.text)}</small><span class="dmm"><span class="s ${ASKST[a.state][1]}">${ASKST[a.state][0]}</span>${a.changed ? '<span>Changed once</span>' : ''}</span></span></button></div>`;
@@ -196,6 +205,7 @@ function drawReps() {
196
205
  $('#repCap').textContent = R.rows.length ? String(R.rows.length) : '';
197
206
  const group = (id, label, L, row) => L.length ? `<div class="dmg ngrp" id="${id}" role="list"><p class="label">${esc(label)} · ${L.length}</p>${L.map(row).join('')}</div>` : '';
198
207
  $('#repBody').innerHTML = `<p class="mhint">A report is a file in the repository. PMOS drafts it, you read it. <b>Nothing is sent from here.</b></p>`
208
+ + '<div class="nact"><button class="dmcta" id="repNew" aria-haspopup="dialog">New report</button></div>'
199
209
  + `<form class="nask" id="repAsk"><input id="repAskIn" maxlength="500" autocomplete="off" placeholder="Ask PMOS to set up a report" aria-label="Ask PMOS to set up a report"><button class="dmcta" id="repAskGo" type="submit">Ask</button></form>`
200
210
  + '<p class="note nask-n">This starts a background run that only proposes a report. Nothing is set up until you press Set it up.</p>'
201
211
  + (R.setupsOk === false ? '<div class="nempty"><p><b>The report setups could not be read</b>, so what PMOS found and what you set up are not listed.</p></div>'
@@ -203,12 +213,15 @@ function drawReps() {
203
213
  + (R.missing ? '<div class="nempty"><p><b>The report files could not be read</b>, so none is listed.</p></div>'
204
214
  : R.rows.length ? `<div class="dmg ngrp" id="repDocs" role="list"><p class="label">Documents · <b>${R.counts.draft}</b> ${R.counts.draft === 1 ? 'draft' : 'drafts'} · <b>${R.counts.issued}</b> issued</p>${R.rows.map(repRow).join('')}</div>`
205
215
  : '<div class="nempty"><p><b>No report file is on record.</b> Set one up above, or ask PMOS for one.</p></div>')
206
- + `<p class="nsch"><button class="lk" id="repOpen">Open the Reports tab</button> to read, edit or issue a document.</p>`;
216
+ + `<p class="nsch"><button class="lk" id="repOpen">Open the Reports tab</button> to edit or issue a document.</p>`;
207
217
  clearTimeout(askTimer);
208
218
  if (asks.some((a) => a.state === 'running')) askTimer = setTimeout(load, 5000);
209
219
  }
210
220
  $('#repBody').addEventListener('click', (e) => {
211
- if (e.target.closest('[data-rep]') || e.target.closest('#repOpen')) { location.assign('/c3.html?tab=rep'); return; }
221
+ const rp = e.target.closest('[data-rep]');
222
+ if (rp) { const row = M.reports.rows.find((x) => x.key === rp.dataset.rep), su = row && (M.reports.setups || []).find((x) => x.id === row.cadence); openReport(row, { ws: M.board.ws, name: su ? su.name : null }); return; }
223
+ if (e.target.closest('#repOpen')) { location.assign('/c3.html?tab=rep'); return; }
224
+ if (e.target.closest('#repNew')) { openReportEdit(null); return; }
212
225
  const f = e.target.closest('[data-found]'), a = e.target.closest('[data-ask]'), s = e.target.closest('[data-setup]');
213
226
  if (f) openFound((M.reports.found || []).find((x) => x.id === f.dataset.found));
214
227
  else if (a) openAsk((M.reports.asks || []).find((x) => x.id === a.dataset.ask));
@@ -292,12 +305,14 @@ function openSetup(s) {
292
305
  const rows = [['Schedule', s.label], ['Status', s.paused ? 'Paused' : 'Active'], ['Next draft', s.paused ? '' : s.next], ['Last issued', s.lastIssued], ['Audience', s.audience], ['Output', s.output], ['Documents', String(s.cycles)], ['Purpose', s.purpose]];
293
306
  const acts = [s.paused ? ['resume', 'Resume'] : ['pause', 'Pause', 1]];
294
307
  if (s.fromWork && !s.paused) acts.unshift(['draft', 'Draft it now']);
308
+ if (s.fromWork) acts.push(['studio', 'Shape it in the Studio', 1]);
295
309
  repDlg({ eye: 'Set-up report', title: s.name, say: s.paused ? 'This report is paused. Resume it to draft it on its schedule again.' : 'This report is drafted on its schedule. You can draft the next cycle now or pause it.',
296
310
  html: kv(rows) + `<p class="note">${s.fromWork ? (s.structured ? 'Draft it now starts a background run that follows the saved structure.' : 'Draft it now writes the next cycle as a file at once.') : 'This report is drafted from its dashboard on its day.'} Pause and Resume record a line in the report ledger. Nothing is sent.</p>`,
297
311
  acts, on: {
298
312
  draft: press('draft', { id: s.id }, (res) => res.drafting ? 'Drafting started. The draft follows the saved structure.' : 'Drafted: ' + ((res.drafted && res.drafted.path) || 'the next cycle') + '.'),
299
313
  pause: press('pause', { id: s.id }, 'Paused. It is not drafted until you resume it.'),
300
314
  resume: press('resume', { id: s.id }, 'Resumed. It is drafted on its schedule again.'),
315
+ studio: () => { openReportEdit(s); return 'keep-off'; },
301
316
  } });
302
317
  }
303
318
 
@@ -0,0 +1,9 @@
1
+ /* pm/premium-report-print.css — the print page of a report's words (initiative premium-report-read; premium-report-read.js printHtml).
2
+ One slide to a 1280 x 720 page in Deck view (c3-report-frame.css sets the page), the page as written in Document view. Colours are the slide tokens. */
3
+ body.pmos-print { margin: 0; font-family: var(--sans); color: var(--slide-fg); background: var(--slide-bg); }
4
+ body.pmos-print-deck > .pmos-slide { padding: 72px 96px; display: flex; flex-direction: column; justify-content: center; gap: 24px; }
5
+ .rp-slide__h { margin: 0; font-size: 24px; font-weight: 700; }
6
+ .rp-slide__t p, .rp-slide__t li { margin: 0; font-size: 16px; line-height: 1.45; }
7
+ .rp-slide__t ul { margin: 0; display: grid; gap: 12px; }
8
+ body.pmos-print-doc { padding: 48px; }
9
+ body.pmos-print-doc h2 { margin: 24px 0 8px; font-size: 20px; }
@@ -0,0 +1,358 @@
1
+ /* pm/premium-report-read.js — a report document read on the premium Insights page (initiative premium-report-read; planning/prd/premium-report-read-prd.md).
2
+ * The mockup's report sheet (prototype/premium-ux-concept/build-src/rep.js.txt): the deck or the page, Present, Download, Print, and the design row
3
+ * (versions, samples, This is it). It opens in the page's dialog; the conversation on the left shapes the look.
4
+ *
5
+ * openReport(row, hand) row = a Reports card document { cadence, slot, date, path, state }; hand = { ws, name (the set-up report's name, or null) }
6
+ * wordsOf(md, fallback) the document as { title, sections: [{ h, lines }] } (pure)
7
+ * slideHtml(lines) a section's lines as html: paragraphs and lists, as written (pure)
8
+ *
9
+ * READS: GET /api/doc (the words), GET /api/report-design/cycle and cycle-html (a cycle drawn to the saved design), GET /api/report-design and
10
+ * version (the design and its versions), GET /api/report-export (the files). PDF is the browser's print. Every render is HTML the server sanitized,
11
+ * shown in a frame with an empty sandbox: nothing in it runs.
12
+ * WRITES: only the report-design describe, sample, turn, accept and revert routes, each a press on the page (pmPost, behind the launch nonce). An
13
+ * issued cycle is frozen: no design row and no turn. Editing, issuing and the copies in other tools stay in the console. */
14
+ import { $, esc, openDlg, toast, turnA, turnU, ptx, setFull } from './premium-shell.js';
15
+ import { pmGet, pmPost } from './http.js';
16
+
17
+ const ICO = (p) => `<svg class="i" viewBox="0 0 24 24">${p}</svg>`;
18
+ const PREV = ICO('<path d="m15 6-6 6 6 6"/>'), NEXT = ICO('<path d="m9 6 6 6-6 6"/>'), CHV = ICO('<path d="M6 9l6 6 6-6"/>'), XI = ICO('<path d="M6 6l12 12M18 6 6 18"/>');
19
+ const DLI = ICO('<path d="M12 4v11M7 10l5 5 5-5M5 20h14"/>'), PRI = ICO('<path d="M7 9V4h10v5M7 17H5v-6h14v6h-2M8 14h8v6H8z"/>'), PLAY = ICO('<path d="M8 5v14l11-7z"/>');
20
+ const CHK = ICO('<path d="M5 12.5l4.5 4.5L19 7.5"/>'), PLUS = ICO('<path d="M12 5v14M5 12h14"/>'), SEND = ICO('<path d="M5 12h14M13 6l6 6-6 6"/>');
21
+ const W = 1280;
22
+ const POLL_MS = 800, POLL_MAX = 240000;
23
+ const DL = [['pptx', 'PowerPoint (.pptx)', 'A title slide, then one slide for each section.'], ['docx', 'Word (.docx)', 'Headings, paragraphs and lists.'],
24
+ ['xlsx', 'Excel (.xlsx)', 'The tables and lists of the document, one sheet each.'], ['csv', 'CSV (.csv)', 'The rows of the document as plain text.']];
25
+ const KINDS = { pdf: 'pdf', pptx: 'pptx', docx: 'docx', png: 'image', jpg: 'image', jpeg: 'image' };
26
+
27
+ let R = null; // the open reader
28
+
29
+ const q = (o) => Object.entries(o).filter(([, v]) => v != null && v !== '').map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');
30
+ const inline = (s) => esc(s).replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>').replace(/`([^`]+)`/g, '<code>$1</code>');
31
+
32
+ /** The document as a title and its sections, as written. A `## ` heading starts a section; the text before the first one is the lead. */
33
+ export function wordsOf(md, fallback) {
34
+ const lines = String(md || '').replace(/\r/g, '').split('\n');
35
+ let i = 0, title = '';
36
+ if (lines[0] === '---') { const e = lines.indexOf('---', 1); if (e > 0) { for (const l of lines.slice(1, e)) { const m = /^title:\s*(.*)$/.exec(l); if (m) title = m[1].replace(/^["'](.*)["']$/, '$1').trim(); } i = e + 1; } }
37
+ const sections = [], lead = [];
38
+ let cur = null;
39
+ for (; i < lines.length; i++) {
40
+ const l = lines[i];
41
+ const h1 = /^#\s+(.*)$/.exec(l), h2 = /^##\s+(.*)$/.exec(l);
42
+ if (h1) { if (!title) title = h1[1].trim(); continue; }
43
+ if (h2) { cur = { h: h2[1].trim(), lines: [] }; sections.push(cur); continue; }
44
+ (cur ? cur.lines : lead).push(l);
45
+ }
46
+ if (lead.some((l) => l.trim())) sections.unshift({ h: 'Summary', lines: lead });
47
+ return { title: title || fallback || 'Report', sections };
48
+ }
49
+
50
+ /** A section's lines as html: a list for each run of bullets, a sub-heading in bold, every other line a paragraph. */
51
+ export function slideHtml(lines) {
52
+ const out = [];
53
+ let list = [];
54
+ const flush = () => { if (list.length) { out.push('<ul>' + list.map((x) => '<li>' + inline(x) + '</li>').join('') + '</ul>'); list = []; } };
55
+ for (const l of lines || []) {
56
+ const b = /^\s*[-*]\s+(.*)$/.exec(l), h = /^#{3,6}\s+(.*)$/.exec(l);
57
+ if (b) { list.push(b[1]); continue; }
58
+ flush();
59
+ if (h) out.push('<p><b>' + inline(h[1]) + '</b></p>');
60
+ else if (l.trim()) out.push('<p>' + inline(l.trim()) + '</p>');
61
+ }
62
+ flush();
63
+ return out.join('') || '<p>This section is empty.</p>';
64
+ }
65
+
66
+ /* ── a sanitized render: its style, its slides and its body (DOMParser; nothing of it runs) ── */
67
+ function splitRender(html) {
68
+ const d = new DOMParser().parseFromString(String(html || ''), 'text/html');
69
+ d.querySelectorAll('script,iframe,object,embed,link,meta,base').forEach((n) => n.remove());
70
+ d.querySelectorAll('*').forEach((n) => { for (const a of [...n.attributes]) if (/^on/i.test(a.name) || /^\s*javascript:/i.test(a.value)) n.removeAttribute(a.name); });
71
+ const style = [...d.querySelectorAll('style')].map((s) => s.textContent).join('\n');
72
+ d.querySelectorAll('style').forEach((s) => s.remove());
73
+ const slides = [...d.querySelectorAll('section.pmos-slide')].map((s, i) => ({ h: s.getAttribute('data-title') || 'Slide ' + (i + 1), html: s.outerHTML }));
74
+ return { style, slides, body: d.body.innerHTML };
75
+ }
76
+ const href = (f) => new URL('./' + f, import.meta.url).href;
77
+ function frameDoc(style, inner, cls) {
78
+ return '<!doctype html><html lang="en"><head><meta charset="utf-8"><link rel="stylesheet" href="' + esc(href('tokens.css')) + '"><link rel="stylesheet" href="' + esc(href('c3-report-frame.css')) + '">'
79
+ + '<style>' + String(style || '').replace(/<\/style/gi, '<\\/style') + '</style></head><body class="pmos-frame ' + cls + '">' + String(inner || '') + '</body></html>';
80
+ }
81
+ const frame = (style, inner, cls, title) => `<iframe class="rdif" sandbox="" tabindex="-1" title="${esc(title)}" srcdoc="${esc(frameDoc(style, inner, cls))}"></iframe>`;
82
+
83
+ /* ── what is shown: the cycle (its words, or its designed render) or a design version ── */
84
+ function source() {
85
+ if (R.show !== 'cycle') return { kind: 'ver', n: R.show, X: R.ver.get(R.show) || null };
86
+ return R.cyc ? { kind: 'cycle', X: R.cyc } : { kind: 'words' };
87
+ }
88
+ function slides() {
89
+ const s = source();
90
+ if (s.kind === 'words') {
91
+ const w = R.W || { title: R.name, sections: [] };
92
+ return [{ k: 'title', h: w.title, t: [R.name, R.row.date || R.row.slot, R.issued ? 'Issued' : 'Draft'].filter(Boolean).join(' · ') }].concat(w.sections.map((x) => ({ k: 'text', h: x.h, html: slideHtml(x.lines) })));
93
+ }
94
+ return s.X ? s.X.slides.map((x) => ({ k: 'frame', h: x.h, html: x.html, css: s.X.style })) : [];
95
+ }
96
+ function sourceLine() {
97
+ const s = source(), d = R.design;
98
+ if (s.kind === 'words') return R.err ? 'The document could not be read: ' + R.err : 'The words of the document, as written. ' + (d && d.saved ? 'This cycle is not drawn to the design yet.' : 'No design is saved for this report yet.');
99
+ if (s.kind === 'cycle') return 'This cycle, drawn to the saved design' + (R.cycle && R.cycle.design_version ? ' D' + R.cycle.design_version : '') + '.';
100
+ if (!s.X) return 'Reading D' + s.n + '.';
101
+ return 'Design version D' + s.n + (d && d.saved && d.saved.version === s.n ? ', the saved design.' : ', not saved. Press This is it to keep it.');
102
+ }
103
+
104
+ /* ── drawing ── */
105
+ function slideCard(s, mini) {
106
+ if (s.k === 'frame') return `<div class="rdfc${mini ? ' mini' : ''}">${frame(s.css, s.html, 'pmos-one', s.h)}</div>`;
107
+ if (s.k === 'title') return `<div class="rds title${mini ? ' mini' : ''}"><h3>${esc(s.h)}</h3>${mini ? '' : `<p>${esc(s.t)}</p>`}</div>`;
108
+ return `<div class="rds${mini ? ' mini' : ''}"><h3>${esc(s.h)}</h3>${mini ? '' : s.html}</div>`;
109
+ }
110
+ function deckHtml() {
111
+ const L = slides();
112
+ if (!L.length) return '<p class="note">This version has no slides. Read it as a page.</p>';
113
+ const i = R.i = Math.max(0, Math.min(R.i, L.length - 1));
114
+ return `<div class="rdk"><div class="rdbig" id="rdSlide" tabindex="0" role="group" aria-roledescription="slide" aria-label="Slide ${i + 1} of ${L.length}: ${esc(L[i].h)}. Use the arrow keys to change slide.">${slideCard(L[i])}</div>`
115
+ + `<div class="rdnv"><button data-rr="prev" aria-label="Previous slide"${i === 0 ? ' disabled' : ''}>${PREV}</button><span id="rdN">${i + 1} / ${L.length}</span><button data-rr="next" aria-label="Next slide"${i === L.length - 1 ? ' disabled' : ''}>${NEXT}</button></div>`
116
+ + `<div class="rdt" role="group" aria-label="Slides">${L.map((x, j) => `<button data-rr="go|${j}"${j === i ? ' aria-current="true"' : ''} aria-label="Slide ${j + 1}: ${esc(x.h)}"><span>${esc(x.h)}</span><i>${j + 1}</i></button>`).join('')}</div></div>`;
117
+ }
118
+ function pageHtml() {
119
+ const s = source();
120
+ if (s.kind === 'words') {
121
+ const w = R.W || { title: R.name, sections: [] };
122
+ return `<article class="paper doc rdpg"><h2>${esc(w.title)}</h2>${w.sections.map((x) => `<h3 class="d2">${esc(x.h)}</h3>${slideHtml(x.lines)}`).join('')}</article>`;
123
+ }
124
+ if (!s.X) return '<p class="note">Reading the render.</p>';
125
+ return `<div class="rdpf">${frame(s.X.style, s.X.body, '', 'The report as a page')}</div>`;
126
+ }
127
+ function designHtml() {
128
+ if (R.issued) return '<div class="rdz"><span class="label">Design</span><span class="rds2">This cycle is issued, so it is frozen with the look it was issued with.</span></div>';
129
+ const d = R.design;
130
+ if (!d) return `<div class="rdz"><span class="label">Design</span><span class="rds2">${R.dErr ? esc(R.dErr) : 'Reading the design.'}</span></div>`;
131
+ const vs = d.versions || [], shown = R.show, saved = d.saved ? d.saved.version : null;
132
+ const smp = (d.samples || []).length ? 'Follows ' + d.samples.map((x) => `<em>${esc(x.name)}</em>`).join(', ') : 'No sample yet.';
133
+ const keep = shown === 'cycle' ? '' : saved === shown ? `<span class="s issued">${CHK}Saved as the design</span>` : `<button class="dmcta alt" data-rr="keep"${R.busy ? ' disabled' : ''}>This is it</button>`;
134
+ return `<div class="rdz"><span class="label">Design</span><span class="rdv" role="group" aria-label="Design versions"><button data-rr="ver|cycle" aria-pressed="${shown === 'cycle'}">This cycle</button>${vs.map((v) => `<button data-rr="ver|${v.n}" aria-pressed="${shown === v.n}"${R.busy ? ' disabled' : ''} title="${esc(v.turn || '')}">D${v.n}</button>`).join('')}</span>`
135
+ + `<span class="rds2">${smp}${d.running || R.busy ? ' <b>PMOS is working on it.</b>' : ''}</span><button class="dlink" data-rr="pick">${PLUS}Add a sample</button><input type="file" id="rdFile" hidden accept=".pdf,.pptx,.docx,.png,.jpg,.jpeg">${keep}</div>`;
136
+ }
137
+ function barHtml() {
138
+ const dm = R.dm ? `<div class="dsmn rpm" role="menu" aria-label="Download"><p class="label">Download a file</p>${DL.map(([k, l, s]) => `<a role="menuitem" data-rr="dl|${k}" href="/api/report-export?${esc(q({ ws: R.ws, path: R.row.path, fmt: k }))}" download>${DLI}<span>${esc(l)}<small>${esc(s)}</small></span></a>`).join('')}<button role="menuitem" data-rr="md">${DLI}<span>Markdown (.md)<small>The file, as written.</small></span></button><p class="note rpmn">The files carry the words, not the look. Print or save as PDF keeps the look.</p></div>` : '';
139
+ return `<div class="rdbar"><div class="seg rdvw" role="group" aria-label="View"><button data-rr="view|deck" aria-pressed="${R.view === 'deck'}">Deck</button><button data-rr="view|doc" aria-pressed="${R.view === 'doc'}">Document</button></div>`
140
+ + `<button class="dsvb" data-rr="present">${PLAY}Present</button><span class="dsvw"><button class="dsvb" data-rr="dm" aria-haspopup="menu" aria-expanded="${!!R.dm}">${DLI}Download${CHV}</button>${dm}</span><button class="dsvb" data-rr="print">${PRI}Print or save as PDF</button></div>`;
141
+ }
142
+ function draw() {
143
+ if (!R) return;
144
+ const m = $('#oMain');
145
+ const keep = document.activeElement && document.activeElement.closest && document.activeElement.closest('#oMain') ? document.activeElement.getAttribute('data-rr') : null;
146
+ m.innerHTML = `<div class="rdr" id="rdR">${barHtml()}<p class="note rdsrc" id="rdSrc">${esc(sourceLine())}</p>${designHtml()}${R.view === 'deck' ? deckHtml() : pageHtml()}<p class="note rdcon"><a class="lk" href="/c3.html?tab=rep">Open in the console</a> to edit or issue this document.</p></div>`;
147
+ fit(m);
148
+ if (keep) { const b = m.querySelector(`[data-rr="${keep}"]`); if (b) b.focus(); }
149
+ }
150
+ /* a 1280 x 720 frame scales to its card's width */
151
+ const RO = typeof ResizeObserver === 'function' ? new ResizeObserver((es) => { for (const e of es) scaleOf(e.target, e.contentRect.width); }) : null;
152
+ function scaleOf(card, w) { if (w) card.style.setProperty('--rp-scale', String(Math.round((w / W) * 10000) / 10000)); }
153
+ function fit(root) { root.querySelectorAll('.rdfc').forEach((c) => { if (RO) RO.observe(c); scaleOf(c, c.getBoundingClientRect().width); }); }
154
+
155
+ /* ── the conversation ── */
156
+ const stream = () => $('#dBody .stream');
157
+ function sayA(t) { const s = stream(); if (!s) return null; s.insertAdjacentHTML('beforeend', turnA(ptx(t))); s.scrollTop = s.scrollHeight; const a = s.querySelectorAll('.turn.a .tt'); return a[a.length - 1]; }
158
+ function sayU(t) { const s = stream(); if (s) s.insertAdjacentHTML('beforeend', turnU(t)); }
159
+ async function onSay(e) {
160
+ e.preventDefault();
161
+ const inp = $('#rdIn'), t = inp.value.trim();
162
+ if (!t || !R) return;
163
+ inp.value = ''; sayU(t);
164
+ if (R.issued) { sayA('This cycle is issued, so its look is frozen. Nothing changed.'); return; }
165
+ if (R.busy || (R.design && R.design.running)) { sayA('PMOS is still working on the last change. Wait for its answer, then try again.'); return; }
166
+ const line = sayA('PMOS is working on it.');
167
+ R.busy = true; draw();
168
+ if (R.design && !R.design.description) { const d = await pmPost('/api/report-design/describe', { ws: R.ws, id: R.id, text: t }).catch((x) => ({ ok: false, error: String(x && x.message || x) })); if (!d || d.ok !== true) return answer(line, (d && d.error) || 'The description could not be saved.'); }
169
+ const r = await pmPost('/api/report-design/turn', { ws: R.ws, id: R.id, text: t }).catch((x) => ({ ok: false, error: String(x && x.message || x) }));
170
+ if (!r || r.ok !== true) return answer(line, 'Nothing changed: ' + ((r && r.error) || 'the change could not start.'));
171
+ const before = (R.design && R.design.log || []).length;
172
+ const d = await settle();
173
+ if (!d) return answer(line, 'PMOS did not answer in time. The design is read again when you open the report.');
174
+ const L = (d.log || []).slice(before).filter((x) => x.kind === 'version' || x.kind === 'error');
175
+ const last = L[L.length - 1];
176
+ if (last && last.kind === 'version' && last.version) { await showVersion(last.version); return answer(line, last.text + ' This is D' + last.version + '. Press This is it to keep it as the design.'); }
177
+ return answer(line, last ? 'The change did not work: ' + last.text : 'PMOS ended without a new version.');
178
+ }
179
+ function answer(line, t) { R.busy = false; if (line) line.textContent = t; else sayA(t); draw(); }
180
+ /* read the design again until no job runs */
181
+ async function settle() {
182
+ const t0 = Date.now();
183
+ for (;;) {
184
+ const d = await readDesign();
185
+ if (!R) return null;
186
+ if (d && !d.running) return d;
187
+ if (Date.now() - t0 > POLL_MAX) return null;
188
+ await new Promise((ok) => setTimeout(ok, POLL_MS));
189
+ }
190
+ }
191
+ async function readDesign() {
192
+ const j = await Promise.resolve(pmGet('/api/report-design?' + q({ ws: R.ws, id: R.id }))).catch(() => null);
193
+ if (!R) return null;
194
+ if (j && j.ok) { R.design = j.design; R.dErr = ''; } else { R.design = null; R.dErr = (j && j.error) || 'The design of this report could not be read.'; }
195
+ return R.design;
196
+ }
197
+ async function textOf(url) {
198
+ const r = await fetch(url, { credentials: 'same-origin' });
199
+ if (!r.ok) throw new Error((await r.text().catch(() => '')) || 'the workspace did not answer');
200
+ return r.text();
201
+ }
202
+ async function showVersion(n) {
203
+ R.show = n;
204
+ if (!R.ver.has(n)) { try { R.ver.set(n, splitRender(await textOf('/api/report-design/version?' + q({ ws: R.ws, id: R.id, n })))); } catch (x) { toast('D' + n + ' could not be read.'); R.show = 'cycle'; } }
205
+ if (R.view === 'deck' && !slides().length) R.view = 'doc';
206
+ R.i = 0; draw();
207
+ }
208
+
209
+ /* ── the presses ── */
210
+ async function act(a) {
211
+ const [k, v] = a;
212
+ if (k === 'view') { R.view = v; draw(); return; }
213
+ if (k === 'prev' || k === 'next') { R.i += k === 'next' ? 1 : -1; draw(); return; }
214
+ if (k === 'go') { R.i = +v; draw(); return; }
215
+ if (k === 'dm') { R.dm = !R.dm; draw(); return; }
216
+ if (k === 'dl') { R.dm = false; setTimeout(draw, 0); return; }
217
+ if (k === 'md') { R.dm = false; saveMd(); draw(); return; }
218
+ if (k === 'print') { printIt(); return; }
219
+ if (k === 'present') { present(true); return; }
220
+ if (k === 'pick') { const f = $('#rdFile'); if (f) f.click(); return; }
221
+ if (k === 'ver') {
222
+ if (v === 'cycle') { R.show = 'cycle'; R.i = 0; draw(); return; }
223
+ const n = +v;
224
+ if (R.design && R.design.current !== n) {
225
+ const r = await pmPost('/api/report-design/revert', { ws: R.ws, id: R.id, n }).catch(() => null);
226
+ if (!r || r.ok !== true) { toast((r && r.error) || 'D' + n + ' could not be picked.'); return; }
227
+ R.design = r.design;
228
+ sayA('Back to D' + n + '. The next change builds on it.');
229
+ }
230
+ await showVersion(n);
231
+ return;
232
+ }
233
+ if (k === 'keep') {
234
+ const n = R.show;
235
+ R.busy = true; draw();
236
+ const r = await pmPost('/api/report-design/accept', { ws: R.ws, id: R.id, n }).catch(() => null);
237
+ R.busy = false;
238
+ if (!r || r.ok !== true) { draw(); toast((r && r.error) || 'The design could not be saved.'); return; }
239
+ R.design = r.design;
240
+ sayA('Saved D' + n + ' as the design of this report. ' + (r.redraw && r.redraw.started ? 'PMOS is drawing this cycle to match it.' : 'Each new cycle is drawn to match it.') + ' Nothing is sent.');
241
+ draw();
242
+ if (r.redraw && r.redraw.started) { await settle(); await readCycle(); draw(); }
243
+ }
244
+ }
245
+ function saveMd() {
246
+ const name = (R.row.path.split('/').slice(-2).join('-') || 'report.md');
247
+ const u = URL.createObjectURL(new Blob([R.text || ''], { type: 'text/markdown' })), a = document.createElement('a');
248
+ a.href = u; a.download = name; a.setAttribute('data-rr-md', name); document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(u), 3000);
249
+ toast('Saved ' + name + '.');
250
+ }
251
+ async function addSample(file) {
252
+ const ext = (/\.([a-z0-9]+)$/i.exec(file.name) || [])[1], kind = KINDS[String(ext || '').toLowerCase()];
253
+ if (!kind) { toast('A sample is a PDF, PowerPoint, Word, PNG or JPG file.'); return; }
254
+ const data = await new Promise((ok) => { const r = new FileReader(); r.onload = () => ok(String(r.result || '')); r.onerror = () => ok(''); r.readAsDataURL(file); });
255
+ if (!data) { toast('The file could not be read.'); return; }
256
+ const r = await pmPost('/api/report-design/sample', { ws: R.ws, id: R.id, name: file.name, kind, data }).catch((x) => ({ ok: false, error: String(x && x.message || x) }));
257
+ if (!r || r.ok !== true) { sayA('The sample was not added: ' + ((r && r.error) || 'the press did not go through.')); return; }
258
+ await readDesign(); draw();
259
+ sayA('Added "' + file.name + '". Tell me what to take from it, and I make the next version follow it.');
260
+ }
261
+
262
+ /* ── Present: the current slide on the whole screen ── */
263
+ function presHtml() {
264
+ const L = slides(), i = R.i;
265
+ return `<div class="rdpbox">${L.length ? slideCard(L[i]) : ''}</div><div class="rdpn"><button data-rp="prev" aria-label="Previous slide"${i === 0 ? ' disabled' : ''}>${PREV}</button><span>${i + 1} / ${L.length}</span><button data-rp="next" aria-label="Next slide"${i >= L.length - 1 ? ' disabled' : ''}>${NEXT}</button><button data-rp="end" aria-label="Stop presenting">${XI}</button></div>`;
266
+ }
267
+ function present(on) {
268
+ let p = $('#rdPres');
269
+ if (!on) { if (p) p.remove(); if (document.fullscreenElement) document.exitFullscreen().catch(() => {}); setFull(!R.unfull); R.unfull = false; draw(); const b = $('#oMain [data-rr="present"]'); if (b) b.focus(); return; }
270
+ if (R.view !== 'deck' || !slides().length) { R.view = 'deck'; if (!slides().length) { toast('This version has no slides to present.'); return; } }
271
+ if (!$('#dlg').classList.contains('full')) { R.unfull = true; setFull(true); }
272
+ if (!p) { p = document.createElement('div'); p.id = 'rdPres'; p.className = 'rdpres'; p.setAttribute('role', 'dialog'); p.setAttribute('aria-modal', 'true'); p.setAttribute('aria-label', 'Presenting ' + R.name); p.tabIndex = -1; document.body.appendChild(p); }
273
+ p.innerHTML = presHtml(); fit(p);
274
+ if (p.requestFullscreen && !document.fullscreenElement) p.requestFullscreen().catch(() => {});
275
+ p.focus();
276
+ }
277
+ document.addEventListener('click', (e) => {
278
+ const b = e.target.closest && e.target.closest('#rdPres [data-rp]');
279
+ if (!b || b.disabled || !R) return;
280
+ const k = b.dataset.rp;
281
+ if (k === 'end') { present(false); return; }
282
+ R.i += k === 'next' ? 1 : -1; present(true);
283
+ });
284
+ document.addEventListener('fullscreenchange', () => { if (!document.fullscreenElement && $('#rdPres')) present(false); });
285
+
286
+ /* ── Print: one slide to a page, or the page ── */
287
+ function printHtml() {
288
+ const s = source(), t = esc(R.name + ' ' + (R.row.slot || ''));
289
+ if (s.kind !== 'words' && s.X) return frameDoc(s.X.style, R.view === 'deck' && s.X.slides.length ? s.X.slides.map((x) => x.html).join('') : s.X.body, R.view === 'deck' && s.X.slides.length ? 'pmos-print pmos-print-deck' : 'pmos-print pmos-print-doc').replace('<head>', '<head><title>' + t + '</title>');
290
+ const css = '<link rel="stylesheet" href="' + esc(href('premium-report-print.css')) + '">';
291
+ const w = R.W || { title: R.name, sections: [] };
292
+ const inner = R.view === 'deck'
293
+ ? slides().map((x) => `<section class="pmos-slide"><h2 class="rp-slide__h">${esc(x.h)}</h2><div class="rp-slide__t">${x.k === 'title' ? `<p>${esc(x.t)}</p>` : x.html}</div></section>`).join('')
294
+ : `<h1>${esc(w.title)}</h1>` + w.sections.map((x) => `<h2>${esc(x.h)}</h2>${slideHtml(x.lines)}`).join('');
295
+ return frameDoc('', inner, R.view === 'deck' ? 'pmos-print pmos-print-deck' : 'pmos-print pmos-print-doc').replace('<head>', '<head><title>' + t + '</title>').replace('</head>', css + '</head>');
296
+ }
297
+ function printIt() {
298
+ const w = window.open('', '_blank');
299
+ if (!w) { toast('The browser blocked the print window. Allow pop-ups for this page, then press Print again.'); return; }
300
+ w.document.open(); w.document.write(printHtml()); w.document.close();
301
+ w.focus(); setTimeout(() => { try { w.print(); } catch { /* the PM prints from the window */ } }, 300);
302
+ }
303
+
304
+ /* ── reading the cycle ── */
305
+ async function readCycle() {
306
+ const c = await Promise.resolve(pmGet('/api/report-design/cycle?' + q({ ws: R.ws, path: R.row.path }))).catch(() => null);
307
+ if (!R) return;
308
+ R.cycle = c && c.ok ? c : null;
309
+ R.cyc = null;
310
+ if (R.cycle && R.cycle.designed) { try { R.cyc = splitRender(await textOf('/api/report-design/cycle-html?' + q({ ws: R.ws, path: R.row.path }))); } catch { R.cyc = null; } }
311
+ }
312
+
313
+ export async function openReport(row, hand) {
314
+ if (!row || !row.path) return;
315
+ R = { row, ws: hand.ws, id: row.cadence, name: hand.name || row.cadence, issued: row.state === 'issued', text: '', err: '', W: null, view: 'deck', i: 0, cycle: null, cyc: null, show: 'cycle', ver: new Map(), design: null, dErr: '', dm: false, busy: false };
316
+ const when = row.date || row.slot;
317
+ const say = R.issued
318
+ ? 'This is the ' + when + ' cycle of "' + R.name + '". It is issued, so it is frozen. Read it as a deck or a page, present it, download it or print it. Nothing is sent from here.'
319
+ : 'This is the ' + when + ' cycle of "' + R.name + '". Read it as a deck or a page, present it, download it or print it. To change how it looks, add a sample or tell me what to change, then press This is it on the version you want. Nothing is sent from here.';
320
+ openDlg({ eye: 'Report · ' + (R.issued ? 'issued' : 'draft'), title: R.name, sub: when + ' · ' + row.path, stream: turnA(ptx(say)), noteKey: null, pane: '<p class="note">Reading the document.</p>', label: 'Report' });
321
+ $('#dlg').classList.add('rdrd');
322
+ $('#askF').hidden = true; const an = $('#askNote'); if (an) an.hidden = true;
323
+ if (!R.issued) $('#dBody').insertAdjacentHTML('beforeend', `<form class="askbar" id="rdF"><input id="rdIn" placeholder="Say how it should look" maxlength="4000" autocomplete="off" aria-label="Say how the report should look"><button type="submit" aria-label="Send" title="Send">${SEND}</button></form><p class="fine2">A change starts a design run that writes only a new version of the look. The document's words do not change.</p>`);
324
+ const f = $('#rdF'); if (f) f.onsubmit = onSay;
325
+ if (innerWidth >= 1000) setFull(true);
326
+ const me = R;
327
+ try { R.text = await textOf('/api/doc?' + q({ ws: R.ws, path: row.path })); R.W = wordsOf(R.text, R.name); } catch (x) { R.err = String((x && x.message) || x); }
328
+ if (R !== me) return;
329
+ await Promise.all([readCycle(), R.issued ? null : readDesign()]);
330
+ if (R !== me) return;
331
+ draw();
332
+ }
333
+
334
+ /* The reader's presses. The dialog is shared, so each listener first asks whether the reader is what it holds. */
335
+ const inReader = (e) => R && $('#dlg').classList.contains('rdrd') && $('#dlg').classList.contains('on') && e.target.closest && e.target.closest('#oMain');
336
+ document.addEventListener('click', (e) => {
337
+ if (!inReader(e)) return;
338
+ const t = e.target.closest('[data-rr]');
339
+ if (t && !t.disabled) { act(t.dataset.rr.split('|')); return; }
340
+ if (R.dm && !e.target.closest('.dsvw')) { R.dm = false; draw(); }
341
+ });
342
+ document.addEventListener('change', (e) => { if (inReader(e) && e.target.id === 'rdFile' && e.target.files && e.target.files[0]) addSample(e.target.files[0]); });
343
+ document.addEventListener('keydown', (e) => {
344
+ if (!R) return;
345
+ if ($('#rdPres')) {
346
+ if (e.key === 'Escape') { e.preventDefault(); e.stopImmediatePropagation(); present(false); return; }
347
+ if (/^Arrow(Left|Right)$/.test(e.key)) { e.preventDefault(); const L = slides().length; const j = R.i + (e.key === 'ArrowRight' ? 1 : -1); if (j >= 0 && j < L) { R.i = j; present(true); } }
348
+ return;
349
+ }
350
+ if (!inReader(e) || !/^Arrow(Left|Right)$/.test(e.key) || !e.target.closest('.rdk')) return;
351
+ const L = slides().length, j = R.i + (e.key === 'ArrowRight' ? 1 : -1);
352
+ if (j < 0 || j >= L) return;
353
+ e.preventDefault(); R.i = j; draw(); const s = $('#rdSlide'); if (s) s.focus();
354
+ }, true);
355
+ /* Another dialog of the page opens without the reader's class; closing the dialog closes the reader. */
356
+ /* While presenting, the page's Escape takes the dialog out of full screen first (premium-shell.js): that is the reader's sign to stop presenting. */
357
+ new MutationObserver(() => { const d = $('#dlg'); if (R && $('#rdPres') && d.classList.contains('on') && !d.classList.contains('full')) present(false); }).observe($('#dlg'), { attributes: true, attributeFilter: ['class'] });
358
+ new MutationObserver(() => { const d = $('#dlg'); if (d && !d.classList.contains('on') && d.classList.contains('rdrd')) { d.classList.remove('rdrd'); const p = $('#rdPres'); if (p) p.remove(); R = null; } }).observe($('#dlg'), { attributes: true, attributeFilter: ['class'] });