create-pmos 0.322.0 → 0.324.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,218 @@
1
+ /* pm/premium-deck.js — a deck as a markdown file (initiative premium-viewer, R-SL1). Pure: no DOM, so Node tests import it as it is.
2
+ * The file stays plain markdown. `# Title` is the title slide and each `## Heading` is one slide. Under a heading, a
3
+ * `<!-- pmos:slide {json} -->` comment holds what markdown cannot: the layout, the speaker notes, and the items (text, image, chart,
4
+ * table, shape) with their place on a 960 x 540 canvas. Below the comment the slide's text is written again as markdown, so the file
5
+ * reads on GitHub and an agent can propose a change to it. The block keeps a hash of that text: when the text no longer matches
6
+ * (someone edited the file by hand), the file's text wins and the slide is marked `changed`.
7
+ * parseDeck(md, fallbackTitle) -> { front, title, theme, slides: [{ l, notes, els, keep?, h1?, changed? }], blocks } blocks = slides that had a block;
8
+ * keep = the parts of the section the editor does not change (see KEEP)
9
+ * writeDeck(deck) -> md (the first slide is always the `# ` title slide of the file)
10
+ * mkLayout(l, c) the items of a layout, filled from c ({ title, body, body2, kicker, big, chart, img })
11
+ * cleanHtml(html, inline) the text html an item may hold: b, i, u, br, p, div, ul, ol, li, h3 (inline: b, i, u, br); no attributes
12
+ * htmlToMd(html) · mdToHtml(md) · cleanEl(e) · hash(s)
13
+ * Nothing here reads or writes a file: the editor (premium-vw-slides.js) reads through /api/doc and saves through /api/doc-sheet/edit. */
14
+
15
+ export const W = 960, H = 540;
16
+ export const LAYOUTS = [['title', 'Title'], ['content', 'Title and text'], ['two', 'Two columns'], ['chart', 'Chart and text'], ['big', 'Big number'], ['image', 'Image and text'], ['quote', 'Quote'], ['section', 'Section break']];
17
+ export const ROLES = [['title', 'Title'], ['heading', 'Heading'], ['body', 'Body'], ['small', 'Small'], ['kicker', 'Kicker'], ['big', 'Big number'], ['quote', 'Quote']];
18
+ export const THEMES = [['ember', 'Ember'], ['paper', 'Paper'], ['sky', 'Sky']];
19
+ export const COLORS = [['', 'Theme text'], ['acc', 'Accent'], ['mut', 'Muted']];
20
+ export const FILLS = [['acc', 'Accent'], ['fg', 'Text colour'], ['soft', 'Soft']];
21
+ const has = (list, k) => list.some((x) => x[0] === k);
22
+ /* Parts of a section the editor keeps as they are and never shows as slide text: a report's note (`<!-- pmos:note id -->` … `<!-- /pmos:note -->`),
23
+ * the drafter's `<!-- pmos:slides v1 … -->` block, and any other comment. They are written back after the slide's text. */
24
+ const KEEP = /<!-- pmos:note [^>]*-->[\s\S]*?<!-- \/pmos:note -->|<!--(?!\s*pmos:slide\s)[\s\S]*?-->/g;
25
+ const BLOCK = /^<!--\s*pmos:slide\s+(\{[\s\S]*?\})\s*-->\s*$/;
26
+
27
+ export const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
28
+ const unesc = (s) => String(s).replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&');
29
+ export function hash(s) { let h = 5381; const t = String(s); for (let i = 0; i < t.length; i++) h = ((h << 5) + h + t.charCodeAt(i)) >>> 0; return h.toString(36); }
30
+
31
+ /* ── text html: a small allow-list, no attributes ── */
32
+ const BLOCK_TAGS = ['b', 'i', 'u', 'br', 'p', 'div', 'ul', 'ol', 'li', 'h3'], INLINE_TAGS = ['b', 'i', 'u', 'br'];
33
+ const SYN = { strong: 'b', em: 'i' };
34
+ export function cleanHtml(html, inline) {
35
+ const ok = inline ? INLINE_TAGS : BLOCK_TAGS, keep = [];
36
+ let s = String(html == null ? '' : html).replace(/<!--[\s\S]*?-->/g, '').replace(/<(script|style|template|iframe|object|svg|math|textarea|title)\b[\s\S]*?<\/\1\s*>/gi, '');
37
+ s = s.replace(/<(\/?)([a-zA-Z][\w-]*)\b[^<>]*>/g, (m, close, tag) => {
38
+ let t = tag.toLowerCase(); t = SYN[t] || t;
39
+ if (!ok.includes(t) || (close && t === 'br')) return inline && !close && /^(p|div|li|h3)$/.test(t) && keep.length ? '\u0001' + (keep.push('<br>') - 1) + '\u0002' : '';
40
+ return '\u0001' + (keep.push(close ? `</${t}>` : `<${t}>`) - 1) + '\u0002';
41
+ });
42
+ s = s.replace(/[<>\u0001\u0002]/g, (c) => (c === '<' ? '&lt;' : c === '>' ? '&gt;' : c)).replace(/\u0001(\d+)\u0002/g, (m, n) => keep[+n]).replace(/[\u0001\u0002]/g, '');
43
+ return s.slice(0, 20000);
44
+ }
45
+ const inlineMd = (h) => unesc(String(h).replace(/<br>/g, ' ').replace(/<b>([\s\S]*?)<\/b>/g, '**$1**').replace(/<i>([\s\S]*?)<\/i>/g, '_$1_').replace(/<u>([\s\S]*?)<\/u>/g, '$1').replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ').trim();
46
+ /** Text html as markdown: paragraphs, bullets, numbered lists, ### subheads, bold and italic. */
47
+ export function htmlToMd(html) {
48
+ const s = cleanHtml(html), out = [];
49
+ const re = /<(ul|ol)>([\s\S]*?)<\/\1>|<h3>([\s\S]*?)<\/h3>|<(?:p|div)>([\s\S]*?)<\/(?:p|div)>|([^<]+|<(?:b|i|u|br)>|<\/(?:b|i|u)>)/g;
50
+ let run = '';
51
+ const flush = () => { const t = inlineMd(run); if (t) out.push(t); run = ''; };
52
+ for (const m of s.matchAll(re)) {
53
+ if (m[1]) { flush(); const items = [...m[2].matchAll(/<li>([\s\S]*?)<\/li>/g)].map((x) => inlineMd(x[1])).filter(Boolean); out.push(items.map((t, k) => (m[1] === 'ol' ? (k + 1) + '. ' : '- ') + t).join('\n')); }
54
+ else if (m[3] != null) { flush(); const t = inlineMd(m[3]); if (t) out.push('### ' + t); }
55
+ else if (m[4] != null) { flush(); const t = inlineMd(m[4]); if (t) out.push(t); }
56
+ else if (m[5] === '<br>') { flush(); }
57
+ else run += m[5] || '';
58
+ }
59
+ flush();
60
+ return out.join('\n\n');
61
+ }
62
+ const inlineHtml = (t) => esc(t).replace(/\*\*(.+?)\*\*/g, '<b>$1</b>').replace(/(^|[\s(])_(.+?)_(?=$|[\s).,;:!?])/g, '$1<i>$2</i>');
63
+ /** Markdown text as item html. A table or image line belongs to its own item and is left out here. */
64
+ export function mdToHtml(md) {
65
+ const out = []; let list = null;
66
+ const close = () => { if (list) { out.push(`</${list}>`); list = null; } };
67
+ for (const raw of String(md || '').split('\n')) {
68
+ const l = raw.trimEnd(); let m;
69
+ if (/^\s*\|/.test(l) || /^\s*<!--.*-->\s*$/.test(l) || /^!\[[^\]]*\]\([^)]*\)\s*$/.test(l.trim())) { close(); continue; }
70
+ if ((m = /^\s*[-*+] (.*)/.exec(l))) { if (list !== 'ul') { close(); out.push('<ul>'); list = 'ul'; } out.push(`<li>${inlineHtml(m[1])}</li>`); }
71
+ else if ((m = /^\s*\d+[.)] (.*)/.exec(l))) { if (list !== 'ol') { close(); out.push('<ol>'); list = 'ol'; } out.push(`<li>${inlineHtml(m[1])}</li>`); }
72
+ else if ((m = /^#{3,6} (.*)/.exec(l))) { close(); out.push(`<h3>${inlineHtml(m[1])}</h3>`); }
73
+ else if ((m = /^> ?(.*)/.exec(l))) { close(); if (m[1].trim()) out.push(`<p>${inlineHtml(m[1])}</p>`); }
74
+ else if (l.trim()) { close(); out.push(`<p>${inlineHtml(l.trim())}</p>`); }
75
+ else close();
76
+ }
77
+ close();
78
+ return out.join('');
79
+ }
80
+ const plain = (h) => inlineMd(String(h || '').replace(/<\/(p|div|li|h3)>/g, ' '));
81
+
82
+ /* ── items ── */
83
+ const num = (v, lo, hi, d) => { const n = Math.round(Number(v)); return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : d; };
84
+ const cell = (v) => cleanHtml(v, true).slice(0, 400);
85
+ /** An item as the file may hold it: known kinds and keys only, numbers on the canvas, text through the allow-list, an image path inside the workspace. Null when it cannot be one. */
86
+ export function cleanEl(e) {
87
+ if (!e || typeof e !== 'object') return null;
88
+ const g = { x: num(e.x, -W, 2 * W, 72), y: num(e.y, -H, 2 * H, 60), w: num(e.w, 20, 2 * W, 300), h: num(e.h, 20, 2 * H, 120) };
89
+ const k = typeof e.k === 'string' && /^(title|body|body2|kicker|big|chart|img)$/.test(e.k) ? { k: e.k } : {};
90
+ if (e.t === 'text') return { t: 'text', ...k, role: has(ROLES, e.role) ? e.role : 'body', ...g, html: cleanHtml(e.html), align: /^(left|center|right)$/.test(e.align) ? e.align : 'left', ...(has(COLORS, e.color) && e.color ? { color: e.color } : {}) };
91
+ if (e.t === 'shape') return { t: 'shape', ...g, fill: has(FILLS, e.fill) ? e.fill : 'acc', ...(e.round ? { round: true } : {}) };
92
+ if (e.t === 'img') { const src = okSrc(e.src) ? String(e.src) : ''; return { t: 'img', ...k, ...g, src, alt: String(e.alt || '').slice(0, 200) }; }
93
+ if (e.t === 'chart') {
94
+ const data = (Array.isArray(e.data) ? e.data : []).slice(0, 24).map((r) => [String((r && r[0]) == null ? '' : r[0]).slice(0, 40), Number.isFinite(Number(r && r[1])) ? Number(r[1]) : 0]);
95
+ return { t: 'chart', ...k, ...g, kind: e.kind === 'line' ? 'line' : 'bar', data: data.length ? data : [['', 0]] };
96
+ }
97
+ if (e.t === 'table') {
98
+ const rows = (Array.isArray(e.rows) ? e.rows : []).slice(0, 12).map((r) => (Array.isArray(r) ? r : []).slice(0, 8).map(cell));
99
+ const n = Math.max(1, ...rows.map((r) => r.length));
100
+ return rows.length ? { t: 'table', ...g, rows: rows.map((r) => r.concat(Array(n - r.length).fill(''))) } : null;
101
+ }
102
+ return null;
103
+ }
104
+ /** An image path the page may show through /api/asset: relative, inside the workspace, an image name. */
105
+ export const okSrc = (s) => typeof s === 'string' && s.length < 300 && /^[\w][\w./ -]*\.(png|jpe?g|gif|webp|svg|avif)$/i.test(s) && !/(^|\/)\.\.(\/|$)/.test(s);
106
+
107
+ export function mkLayout(l, c = {}) {
108
+ const T = (k, role, x, y, w, h, html, align) => ({ t: 'text', k, role, x, y, w, h, html, align: align || 'left' });
109
+ const ti = c.title != null ? c.title : '', bo = c.body != null ? c.body : '';
110
+ switch (l) {
111
+ case 'title': return [T('kicker', 'kicker', 72, 232, 816, 28, c.kicker || ''), T('title', 'title', 72, 272, 816, 140, ti), T('body', 'body', 72, 424, 816, 70, bo)];
112
+ case 'two': return [T('title', 'heading', 72, 60, 816, 56, ti), T('body', 'body', 72, 150, 390, 330, bo), T('body2', 'body', 498, 150, 390, 330, c.body2 || '')];
113
+ case 'chart': return [T('title', 'heading', 72, 60, 816, 56, ti), c.chart ? { ...c.chart, k: 'chart', x: 72, y: 150, w: 520, h: 320 } : { t: 'chart', k: 'chart', x: 72, y: 150, w: 520, h: 320, kind: 'bar', data: [['', 0]] }, T('body', 'body', 624, 160, 264, 310, bo)];
114
+ case 'big': return [T('big', 'big', 72, 96, 816, 170, c.big || ''), T('body', 'body', 72, 300, 700, 140, bo), ...(ti ? [T('title', 'small', 72, 470, 700, 40, ti)] : [])];
115
+ case 'image': return [c.img ? { ...c.img, k: 'img', x: 0, y: 0, w: 420, h: 540 } : { t: 'img', k: 'img', x: 0, y: 0, w: 420, h: 540, src: '', alt: '' }, T('title', 'heading', 476, 130, 420, 130, ti), T('body', 'body', 476, 290, 420, 200, bo)];
116
+ case 'quote': return [T('title', 'quote', 110, 140, 740, 220, ti), T('body', 'small', 110, 390, 740, 40, bo)];
117
+ case 'section': return [T('kicker', 'kicker', 72, 206, 816, 28, c.kicker || '', 'center'), T('title', 'title', 72, 246, 816, 130, ti, 'center')];
118
+ default: return [T('title', 'heading', 72, 60, 816, 56, ti), T('body', 'body', 72, 150, 816, 330, bo)];
119
+ }
120
+ }
121
+
122
+ /* ── the slide's text, as markdown ── */
123
+ const titleEl = (s) => s.els.find((e) => e.t === 'text' && e.k === 'title') || s.els.find((e) => e.t === 'text');
124
+ const mdTable = (rows) => rows.length ? [rows[0], rows[0].map(() => '---'), ...rows.slice(1)].map((r) => '| ' + r.map((c) => inlineMd(c).replace(/\|/g, '\\|') || ' ').join(' | ') + ' |').join('\n') : '';
125
+ /** The heading and the body a slide writes below its block. */
126
+ export function slideText(s) {
127
+ const t = titleEl(s), parts = [];
128
+ for (const e of s.els) {
129
+ if (e === t) continue;
130
+ if (e.t === 'text') { const m = htmlToMd(e.html); if (m) parts.push(m); }
131
+ else if (e.t === 'table') parts.push(mdTable(e.rows));
132
+ else if (e.t === 'chart') parts.push(mdTable([['Label', 'Value'], ...e.data.map((d) => [esc(d[0]), String(d[1])])]));
133
+ else if (e.t === 'img' && e.src) parts.push(`![${(e.alt || '').replace(/[[\]]/g, '')}](${e.src})`);
134
+ }
135
+ return { head: t ? plain(t.html) : '', body: parts.join('\n\n') };
136
+ }
137
+ const textHash = (head, body) => hash(head.trim() + '\n' + body.replace(/\s+$/g, '').trim());
138
+
139
+ /* ── reading ── */
140
+ function splitFront(md) {
141
+ const m = /^---\n([\s\S]*?)\n---\n?/.exec(md);
142
+ return m ? { front: m[1], rest: md.slice(m[0].length) } : { front: null, rest: md };
143
+ }
144
+ const frontVal = (front, key) => { const m = front && new RegExp('^' + key + ':\\s*"?([^"\\n]*)"?\\s*$', 'm').exec(front); return m ? m[1].trim() : ''; };
145
+ function parseTable(lines) {
146
+ const rows = lines.filter((l) => !/^\s*\|?\s*:?-{3,}/.test(l)).map((l) => l.trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map((c) => inlineHtml(c.trim().replace(/\\\|/g, '|'))));
147
+ return rows.length >= 1 ? rows : null;
148
+ }
149
+ /** A section with no block, as a slide: its first table becomes a table item and the rest is the text. */
150
+ function fromSection(head, body, l) {
151
+ const lines = body.split('\n'); let tbl = null, i0 = -1;
152
+ for (let i = 0; i < lines.length; i++) if (/^\s*\|/.test(lines[i])) { let j = i; while (j < lines.length && /^\s*\|/.test(lines[j])) j++; if (j - i >= 2) { tbl = parseTable(lines.slice(i, j)); i0 = i; } break; }
153
+ const text = i0 >= 0 ? lines.filter((x, k) => !(k >= i0 && /^\s*\|/.test(x))).join('\n') : body;
154
+ const els = mkLayout(l, { title: inlineHtml(head), body: mdToHtml(text) }).filter((e) => !(l === 'title' && e.k !== 'title' && !plain(e.html)));
155
+ if (tbl) { const b = els.find((e) => e.k === 'body'); if (b && plain(b.html)) { b.h = 120; } els.push({ t: 'table', x: 72, y: b && plain(b.html) ? 290 : 150, w: 816, h: 190, rows: tbl }); }
156
+ return { l, notes: '', els: els.map(cleanEl).filter(Boolean) };
157
+ }
158
+ /** The file as a deck. A file with no blocks (a report) is read as its title slide and one slide per section, as the report reader does. */
159
+ export function parseDeck(md, fallbackTitle) {
160
+ const { front, rest } = splitFront(String(md || '').replace(/\r\n/g, '\n'));
161
+ const theme = has(THEMES, frontVal(front, 'deck_theme')) ? frontVal(front, 'deck_theme') : 'ember';
162
+ const secs = []; let cur = null, pre = [];
163
+ for (const line of rest.split('\n')) {
164
+ const h1 = /^# (?!#)(.*)/.exec(line), h2 = /^## (?!#)(.*)/.exec(line);
165
+ if (h1 && !cur && !secs.length) { cur = { h1: true, head: h1[1].trim(), lines: [] }; secs.push(cur); continue; }
166
+ if (h2) { cur = { head: h2[1].trim(), lines: [] }; secs.push(cur); continue; }
167
+ if (cur) cur.lines.push(line); else pre.push(line);
168
+ }
169
+ const title = (secs[0] && secs[0].h1 ? secs[0].head : '') || frontVal(front, 'title') || fallbackTitle || 'Slides';
170
+ if (!secs.length || !secs[0].h1) { secs.unshift({ h1: true, head: title, lines: pre, synth: true }); pre = []; }
171
+ const lead = pre.join('\n').trim(); // text above the `# ` title stays where it is
172
+ let blocks = 0;
173
+ const slides = secs.map((s) => {
174
+ let blk = null; const lines = s.lines.slice(), keep = [];
175
+ const at = lines.findIndex((l) => l.trim());
176
+ if (at >= 0) { const m = BLOCK.exec(lines[at].trim()); if (m) { try { blk = JSON.parse(m[1]); } catch { blk = null; } if (!blk) keep.push(lines[at].trim()); lines.splice(at, 1); } } // a block that does not read is kept as it was
177
+ const body = lines.join('\n').replace(KEEP, (m) => { keep.push(m.trim()); return ''; }).replace(/\n{3,}/g, '\n\n').replace(/^\n+|\s+$/g, '');
178
+ const kept = keep.length ? { keep } : {};
179
+ if (!blk || !Array.isArray(blk.els)) return { ...fromSection(s.head, body, s.h1 ? 'title' : 'content'), ...kept, ...(s.h1 ? { h1: true } : {}), ...(s.synth ? { synth: true } : {}) };
180
+ blocks++;
181
+ const sl = { l: has(LAYOUTS, blk.l) ? blk.l : 'content', notes: String(blk.notes || '').slice(0, 4000), els: blk.els.map(cleanEl).filter(Boolean), ...kept, ...(s.h1 ? { h1: true } : {}) };
182
+ if (blk.md && blk.md !== textHash(s.head, body)) return { ...applyText(sl, s.head, body), changed: true };
183
+ return sl;
184
+ });
185
+ return { front, title, theme, slides, blocks, ...(lead ? { pre: lead } : {}) };
186
+ }
187
+ /** The file's text wins over the block's: the title item takes the heading and the text items give way to one body with the file's text. */
188
+ function applyText(sl, head, body) {
189
+ const els = sl.els.map((e) => ({ ...e }));
190
+ const t = titleEl({ els });
191
+ if (t) t.html = inlineHtml(head); else els.unshift(mkLayout('content', { title: inlineHtml(head) })[0]);
192
+ const texts = els.filter((e) => e.t === 'text' && e !== (t || els[0]));
193
+ const html = mdToHtml(body);
194
+ if (texts.length) { texts[0].html = html; for (const x of texts.slice(1)) x.html = ''; }
195
+ else if (plain(html)) els.push(mkLayout('content', { body: html })[1]);
196
+ return { ...sl, els: els.filter((e) => !(e.t === 'text' && e !== t && e !== texts[0] && !plain(e.html))) };
197
+ }
198
+
199
+ /* ── writing ── */
200
+ const blockJson = (o) => JSON.stringify(o).replace(/--/g, '-\\u002d');
201
+ function setFront(front, theme) {
202
+ if (front == null) return null;
203
+ return /^deck_theme:/m.test(front) ? front.replace(/^deck_theme:.*$/m, 'deck_theme: ' + theme) : front + '\ndeck_theme: ' + theme;
204
+ }
205
+ /** The deck as the file: front matter (with deck_theme), the title slide as `# `, every other slide as `## `, each with its block and its text. */
206
+ export function writeDeck(deck) {
207
+ const out = [];
208
+ const front = setFront(deck.front, deck.theme);
209
+ out.push(front != null ? '---\n' + front + '\n---\n' : '---\ndeck_theme: ' + deck.theme + '\n---\n');
210
+ if (deck.pre) out.push(deck.pre + '\n');
211
+ deck.slides.forEach((s, i) => {
212
+ const els = s.els.map(cleanEl).filter(Boolean), { head, body } = slideText({ els });
213
+ const h = (head || (i === 0 ? deck.title : '') || 'Slide ' + (i + 1)).replace(/\n/g, ' ');
214
+ const blk = { l: s.l, ...(s.notes ? { notes: s.notes } : {}), md: textHash(h, body), els };
215
+ out.push(`${i === 0 ? '#' : '##'} ${h}\n<!-- pmos:slide ${blockJson(blk)} -->\n` + (body ? '\n' + body + '\n' : '') + (s.keep && s.keep.length ? '\n' + s.keep.join('\n\n') + '\n' : ''));
216
+ });
217
+ return out.join('\n');
218
+ }
@@ -784,5 +784,5 @@ export function mountMeeting(d) {
784
784
  $('#tl').addEventListener('click', (e) => { const b = e.target.closest('.ev[data-w]'); if (!b) return; e.stopImmediatePropagation(); const r = rowOf(b.dataset.w); if (r) openRow(r, 'week'); }, true);
785
785
  readNotes().then(() => mark());
786
786
  { const want = new URLSearchParams(location.search).get('meeting'); if (want) { history.replaceState(null, '', location.pathname + location.search.replace(/[?&]meeting=[^&]*/, '').replace(/^&/, '?')); setTimeout(() => openNote(want), 600); } }
787
- return { mode: () => (other() ? 'day' : 'today'), draw, openToday, busy: () => busy, mark, openNote };
787
+ return { mode: () => (other() ? 'day' : 'today'), draw, openToday, busy: () => busy, mark, openNote, openRow: (row) => openRow(row, 'week') }; // openRow: the full calendar (premium-vw-cal.js)
788
788
  }
@@ -59,6 +59,7 @@ export function slideHtml(lines) {
59
59
  let list = [];
60
60
  const flush = () => { if (list.length) { out.push('<ul>' + list.map((x) => '<li>' + inline(x) + '</li>').join('') + '</ul>'); list = []; } };
61
61
  for (const l of lines || []) {
62
+ if (/^\s*<!--.*-->\s*$/.test(l)) continue; // a comment line (a slide block, a note marker) is not words
62
63
  const b = /^\s*[-*]\s+(.*)$/.exec(l), h = /^#{3,6}\s+(.*)$/.exec(l);
63
64
  if (b) { list.push(b[1]); continue; }
64
65
  flush();
@@ -150,7 +151,7 @@ function statusHtml() {
150
151
  function barHtml() {
151
152
  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>` : '';
152
153
  const item = (k, l, ico, on) => `<button type="button" role="menuitem" data-rr="${k}"${on === undefined ? '' : ` aria-current="${on}"`}>${ico}${l}${on ? CHK : ''}</button>`;
153
- return `<div class="dsvr rdbar">${mnuHtml('rm', 'Read', EYE, item('present', 'Present', PLAY) + item('print', 'Print or save as PDF', PRI))}`
154
+ return `<div class="dsvr rdbar">${mnuHtml('rm', 'Read', EYE, item('present', 'Present', PLAY) + item('slides', R.issued ? 'Open the slides' : 'Edit the slides', ICO('<path d="M4 5h16v11H4zM8 20h8M12 16v4"/>')) + item('print', 'Print or save as PDF', PRI))}`
154
155
  + `<span class="rdsp">${mnuHtml('fm', R.view === 'deck' ? 'Slide deck' : 'Document', ICO('<path d="M12 3 3 8l9 5 9-5-9-5zM3 13l9 5 9-5"/>'), item('view|deck', 'Slide deck', '', R.view === 'deck') + item('view|doc', 'Document', '', R.view === 'doc'))}`
155
156
  + `<span class="dsvw"><button type="button" class="dsvb" data-rr="dm" aria-haspopup="menu" aria-expanded="${!!R.dm}">${DLI}Download${CHV}</button>${dm}</span>`
156
157
  + (R.issued ? '' : `<button type="button" class="dsvb" data-rr="page" title="Read and edit the words as a page">${PEN}Edit</button>`) + '</span></div>';
@@ -234,6 +235,7 @@ async function act(a) {
234
235
  if (k === 'md') { R.dm = false; saveMd(); draw(); return; }
235
236
  if (k === 'print') { R.mn = ''; draw(); printIt(); return; }
236
237
  if (k === 'present') { R.mn = ''; draw(); present(true); return; }
238
+ if (k === 'slides') { R.mn = ''; draw(); openSlidesOf(R); return; }
237
239
  if (k === 'page') { openPage(); return; }
238
240
  if (k === 'pick') { const f = $('#rdFile'); if (f) f.click(); return; }
239
241
  if (k === 'ver') {
@@ -265,9 +267,9 @@ function openPage() {
265
267
  const me = R;
266
268
  openDocPage({ path: R.row.path, title: R.name + (R.row.slot ? ' · ' + R.row.slot : '') }, {
267
269
  ws: () => me.ws,
268
- extras: () => [{ k: 'present', label: 'Present', icon: PLAY }, { k: 'print', label: 'Print', icon: PRI },
270
+ extras: () => [{ k: 'present', label: 'Present', icon: PLAY }, { k: 'slides', label: me.issued ? 'Open the slides' : 'Edit the slides', icon: ICO('<path d="M4 5h16v11H4zM8 20h8M12 16v4"/>') }, { k: 'print', label: 'Print', icon: PRI },
269
271
  { k: 'dl', label: 'Download', icon: DLI, note: 'The files carry the words, not the look. Print or save as PDF keeps the look.', menu: DL.map(([f, l, sub]) => ({ label: l, sub, icon: DLI, download: true, href: '/api/report-export?' + q({ ws: me.ws, path: me.row.path, fmt: f }) })).concat([{ k: 'md', label: 'Markdown (.md)', sub: 'The file, as written.', icon: DLI }]) }],
270
- onExtra: (k) => { if (R !== me) return; if (k === 'present') { vwShow('main'); act(['present']); } else if (k === 'print') printIt(); else if (k === 'md') saveMd(); },
272
+ onExtra: (k) => { if (R !== me) return; if (k === 'present') { vwShow('main'); act(['present']); } else if (k === 'slides') openSlidesOf(me); else if (k === 'print') printIt(); else if (k === 'md') saveMd(); },
271
273
  onWrite: async () => { if (R !== me) return; try { R.text = await textOf('/api/doc?' + q({ ws: R.ws, path: R.row.path })); R.W = wordsOf(R.text, R.name); } catch { /* the reader keeps what it had */ } if (R === me) draw(); },
272
274
  });
273
275
  }
@@ -330,6 +332,12 @@ function printIt() {
330
332
  w.focus(); setTimeout(() => { try { w.print(); } catch { /* the PM prints from the window */ } }, 300);
331
333
  }
332
334
 
335
+ /* ── the slide editor (premium-viewer R-SL1): the same file, in a Slides tab of the viewer; a save reads the words again ── */
336
+ async function openSlidesOf(at) {
337
+ const m = await import('./premium-vw-slides.js');
338
+ m.openSlides({ ws: at.ws, path: at.row.path, title: at.name, readOnly: at.issued, onSaved: (text) => { if (R !== at) return; R.text = text; R.W = wordsOf(text, R.name); draw(); } });
339
+ }
340
+
333
341
  /* ── reading the cycle ── */
334
342
  async function readCycle() {
335
343
  const c = await Promise.resolve(pmGet('/api/report-design/cycle?' + q({ ws: R.ws, path: R.row.path }))).catch(() => null);
@@ -202,6 +202,7 @@ $('#dExpand').onclick = () => setFull(!$('#dlg').classList.contains('full'));
202
202
  $('#dTabs').addEventListener('click', (e) => { const b = e.target.closest('[data-t]'); if (b) setTab(b.dataset.t); });
203
203
  addEventListener('keydown', (e) => {
204
204
  if (e.key !== 'Escape' || !$('#dlg').classList.contains('on')) return;
205
+ if (document.querySelector('[data-esc-layer]')) return; // a layer open over the dialog (a viewer menu, Present) closes itself first
205
206
  if ($('#dlg').classList.contains('full')) { setFull(false); e.stopImmediatePropagation(); return; }
206
207
  closeDlg();
207
208
  }, true);
@@ -0,0 +1,96 @@
1
+ @font-face{font-family:"Space Grotesk";src:url(/vendor/space-grotesk-var.woff2) format("woff2");font-weight:300 700;font-display:swap}
2
+ @font-face{font-family:"IBM Plex Mono";src:url(/vendor/ibm-plex-mono-400.woff2) format("woff2");font-weight:400;font-display:swap}
3
+ @font-face{font-family:"IBM Plex Mono";src:url(/vendor/ibm-plex-mono-500.woff2) format("woff2");font-weight:500;font-display:swap}
4
+ @font-face{font-family:"IBM Plex Mono";src:url(/vendor/ibm-plex-mono-700.woff2) format("woff2");font-weight:600 700;font-display:swap}
5
+ :root{--fs-1:11px;--fs-2:12px;--fs-3:14px;--fs-4:16px;--fs-5:20px;--fs-6:28px}
6
+ /* pm/premium-vw-cal.css — the calendar grid in the premium viewer: Day, Week and Month (initiative premium-viewer, R8; premium-vw-cal.js).
7
+ * Loaded once by vwStyle('cal'). Sizes are only var(--fs-1..6), weights 400/500/600 (premium-console-type.test.js).
8
+ * The pane's own width picks the layout: the timeline from 560px, the day list below it (the mockup's Week and Agenda). */
9
+ .vc-open{width:36px;height:36px;border-radius:6px;display:grid;place-items:center;background:var(--well);color:var(--ink-2);flex:none}
10
+ .vc-open .i{width:16px;height:16px}
11
+ .vc{container-type:inline-size}
12
+ .vc .vc-w{background:var(--card-solid);border:1px solid var(--hair);border-radius:8px;box-shadow:var(--card-shadow);overflow:hidden}
13
+ .vc .vc-h{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--hair);flex-wrap:wrap}
14
+ .vc .vc-t{font-size:var(--fs-3);font-weight:600;color:var(--ink)}
15
+ .vc .vc-cap{flex:1;min-width:0;font:400 var(--fs-2) var(--mono);color:var(--ink-3)}
16
+ .vc .vc-ib{width:36px;height:36px;border-radius:6px;display:grid;place-items:center;background:var(--well);color:var(--ink)}
17
+ .vc .vc-ib .i{width:16px;height:16px}
18
+ .vc .vc-tdy{min-height:36px;padding:0 12px;border-radius:6px;border:1px solid var(--hair);font-size:var(--fs-2);font-weight:500;color:var(--ink)}
19
+ .vc .vc-seg{display:flex;gap:2px;padding:3px;border-radius:8px;background:var(--well)}
20
+ .vc .vc-seg button{min-height:32px;padding:0 12px;border-radius:6px;font-size:var(--fs-2);font-weight:500;color:var(--ink-2)}
21
+ .vc .vc-seg button[aria-pressed="true"]{background:var(--solid);color:var(--on-solid)}
22
+ .vc button:focus-visible{outline:2px solid var(--ember);outline-offset:2px}
23
+ .vc .vc-empty{margin:0;padding:12px 14px;font-size:var(--fs-2);color:var(--ink-3);border-bottom:1px solid var(--hair)}
24
+ .vc .vc-w>.vc-empty:last-child{border-bottom:0}
25
+ /* the timeline (Day and Week) */
26
+ .vc .vc-g{display:grid;grid-template-columns:48px repeat(var(--tl-n),minmax(0,1fr))}
27
+ .vc .vc-dh{padding:8px 6px 6px;font-size:var(--fs-2);color:var(--ink-3);border-left:1px solid var(--hair);text-align:center}
28
+ .vc .vc-dh b{display:grid;place-items:center;margin:2px auto 0;width:30px;height:30px;border-radius:6px;font-size:var(--fs-4);font-weight:600;color:var(--ink)}
29
+ .vc .vc-dh.now b{background:var(--solid);color:var(--on-solid)}
30
+ .vc .vc-adl{border-top:1px solid var(--hair);font:400 var(--fs-1) var(--mono);color:var(--ink-3);padding:6px 4px 0;text-align:right}
31
+ .vc .vc-adc{min-height:28px;border-left:1px solid var(--hair);border-top:1px solid var(--hair);padding:3px;display:grid;gap:2px;align-content:start}
32
+ .vc .vc-ad{display:block;min-width:0;border-radius:6px;padding:1px 6px;font-size:var(--fs-1);font-weight:500;line-height:1.5;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:left;
33
+ border-left:3px solid var(--ec,var(--ember));background:color-mix(in oklab,var(--ec,var(--ember)) 12%,transparent);color:var(--ink)}
34
+ .vc .vc-ad.meet{--ec:var(--sky)}
35
+ .vc .vc-ad.t-warn{--ec:var(--ember)}.vc .vc-ad.t-bad{--ec:var(--bad)}.vc .vc-ad.t-ok{--ec:var(--ok)}
36
+ .vc .vc-gut{border-top:1px solid var(--hair);font:400 var(--fs-1) var(--mono);color:var(--ink-3)}
37
+ .vc .vc-gut i{display:block;height:44px;font-style:normal;text-align:right;padding-right:6px;transform:translateY(-7px)}
38
+ .vc .vc-gut i:first-child{visibility:hidden}
39
+ .vc .vc-day{position:relative;height:var(--tl-hh);border-left:1px solid var(--hair);border-top:1px solid var(--hair);background:repeating-linear-gradient(to bottom,transparent 0 43px,var(--hair) 43px 44px)}
40
+ .vc .vc-day.past{background-color:color-mix(in oklab,var(--well) 40%,transparent)}
41
+ .vc .vc-ev{position:absolute;top:var(--tl-t);height:var(--tl-h);left:calc(var(--tl-l) + 3px);width:calc(var(--tl-w) - 6px);border-radius:6px;padding:3px 7px;font-size:var(--fs-1);line-height:1.3;overflow:hidden;text-align:left;
42
+ border-left:3px solid var(--sky);background:color-mix(in oklab,var(--sky) 14%,var(--card-solid));color:var(--ink);z-index:1}
43
+ .vc .vc-ev b{display:block;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
44
+ .vc .vc-ev small{display:block;font-size:var(--fs-1);color:var(--ink-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
45
+ .vc .vc-ev.sh{padding:0 7px;display:flex;align-items:center}.vc .vc-ev.sh small{display:none}
46
+ .vc .vc-ev.past{opacity:.7}
47
+ .vc .vc-now{position:absolute;top:var(--tl-t);left:0;right:0;height:2px;background:var(--bad);z-index:2;pointer-events:none}
48
+ .vc .vc-now::before{content:"";position:absolute;left:-4px;top:-3px;width:8px;height:8px;border-radius:6px;background:var(--bad)}
49
+ /* the day list (Day and Week in a narrow pane) */
50
+ .vc .vc-ag{display:none}
51
+ .vc .vc-ag h4{margin:0;padding:10px 14px 4px;font-size:var(--fs-2);font-weight:600;color:var(--ink-3);border-top:1px solid var(--hair)}
52
+ .vc .vc-ag h4:first-child{border-top:0}
53
+ .vc .vc-ag h4.now{color:var(--ember-ink)}
54
+ .vc .vc-ag>.vc-ad{margin:2px 10px}
55
+ .vc .vc-ar{display:flex;gap:10px;align-items:baseline;width:calc(100% - 20px);min-height:44px;margin:3px 10px;padding:8px 10px;border-radius:8px;text-align:left;
56
+ border-left:3px solid var(--sky);background:color-mix(in oklab,var(--sky) 12%,transparent);color:var(--ink);font-size:var(--fs-3)}
57
+ .vc .vc-ar time{width:48px;flex:none;font:400 var(--fs-2) var(--mono);color:var(--ink-2)}
58
+ .vc .vc-ar span{min-width:0}
59
+ .vc .vc-ar b{display:block;font-weight:500}
60
+ .vc .vc-ar small{display:block;font-size:var(--fs-2);color:var(--ink-3)}
61
+ .vc .vc-ar.past{opacity:.7}
62
+ .vc .vc-none{margin:0;padding:4px 14px 10px;font-size:var(--fs-2);color:var(--ink-3)}
63
+ @container (max-width:559px){.vc .vc-g{display:none}.vc .vc-ag{display:block;padding-bottom:8px}}
64
+ /* the month */
65
+ .vc .vc-mh{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));border-bottom:1px solid var(--hair)}
66
+ .vc .vc-mh span{padding:6px 8px;font:400 var(--fs-1) var(--mono);text-transform:uppercase;letter-spacing:.06em;color:var(--ink-3)}
67
+ .vc .vc-mb{display:grid;grid-template-columns:repeat(7,minmax(0,1fr))}
68
+ .vc .vc-md{min-width:0;min-height:96px;padding:4px;border-left:1px solid var(--hair);border-top:1px solid var(--hair);display:flex;flex-direction:column;gap:2px}
69
+ .vc .vc-md:nth-child(7n+1){border-left:0}
70
+ .vc .vc-md:nth-child(-n+7){border-top:0}
71
+ .vc .vc-md.out{background:color-mix(in oklab,var(--well) 50%,transparent)}
72
+ .vc .vc-md.out .vc-dn b{color:var(--ink-3)}
73
+ .vc .vc-dn{display:flex;align-items:center;gap:6px;min-height:28px;padding:0 4px;border-radius:6px;text-align:left}
74
+ .vc .vc-dn b{display:grid;place-items:center;min-width:24px;height:24px;border-radius:6px;font-size:var(--fs-2);font-weight:600;color:var(--ink)}
75
+ .vc .vc-md.now .vc-dn b{background:var(--solid);color:var(--on-solid)}
76
+ .vc .vc-dn i{display:none;font-style:normal;font:500 var(--fs-1) var(--mono);color:var(--ink-3)}
77
+ .vc .vc-me{display:block;min-width:0;border-radius:6px;padding:2px 6px;font-size:var(--fs-1);line-height:1.4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:left;color:var(--ink);
78
+ background:color-mix(in oklab,var(--sky) 12%,transparent)}
79
+ .vc .vc-me time{font:400 var(--fs-1) var(--mono);color:var(--ink-2);margin-right:4px}
80
+ .vc .vc-md>.vc-ad{font-size:var(--fs-1)}
81
+ .vc .vc-more{align-self:flex-start;padding:1px 6px;border-radius:6px;font-size:var(--fs-1);font-weight:500;color:var(--ink-3)}
82
+ @container (max-width:559px){
83
+ .vc .vc-md{min-height:48px;padding:2px}
84
+ .vc .vc-md>.vc-me,.vc .vc-md>.vc-more,.vc .vc-md>.vc-ad{display:none}
85
+ .vc .vc-dn{flex:1;flex-direction:column;justify-content:center;gap:2px;min-height:44px;padding:0}
86
+ .vc .vc-dn i{display:block}
87
+ .vc .vc-mh span{padding:6px 2px;text-align:center}
88
+ }
89
+ @media (max-width:640px){.vc-open,.vc .vc-ib{width:44px;height:44px}.vc .vc-tdy,.vc .vc-seg button{min-height:44px}}
90
+ @media (hover:hover){
91
+ .vc-open:hover{color:var(--ink)}
92
+ .vc .vc-ev:hover{background:color-mix(in oklab,var(--sky) 24%,var(--card-solid))}
93
+ .vc .vc-dn:hover{background:var(--well)}
94
+ .vc .vc-me:hover{background:color-mix(in oklab,var(--sky) 22%,transparent)}
95
+ .vc .vc-more:hover{color:var(--ink);background:var(--well)}
96
+ }
@@ -0,0 +1,197 @@
1
+ /* pm/premium-vw-cal.js — the calendar grid in the premium viewer: Day, Week and Month (initiative premium-viewer, R8).
2
+ * Reads GET /api/calendar-views?view=day|week|month&date=YYYY-MM-DD only, the same answer the console's Calendar draws (pm/calendar-views.js).
3
+ * Meetings come from the answer's cells; the all-day row also carries the answer's dated layers (an initiative's promised date, a plan item,
4
+ * a release, a report, your own due items). Nothing is invented: a range with no meeting says so, and a calendar that did not answer says why.
5
+ * Pressing a meeting opens its detail (premium-meeting.js openRow, the meeting dialog of slice S3) with the calendar as a tab beside it.
6
+ * The mockup is the iteration-3 calendar of prototype/premium-conversation-shell/index.html (.calw, .cg, .ev, .agd).
7
+ * calModel(r, view, date, today) pure · calHtml(M, esc) pure · mountCal(el, st, d) · openCalendar(d, st?) */
8
+ import { weekView } from './premium-meeting.js';
9
+ import { vwOpen, vwShow, vwStyle } from './premium-viewer.js';
10
+
11
+ export const VIEWS = [['day', 'Day'], ['week', 'Week'], ['month', 'Month']];
12
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
13
+ const MONTH = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
14
+ const DOW = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
15
+ const pad = (n) => String(n).padStart(2, '0');
16
+ const parts = (k) => k.split('-').map(Number);
17
+ const keyOf = (t) => `${t.getUTCFullYear()}-${pad(t.getUTCMonth() + 1)}-${pad(t.getUTCDate())}`;
18
+ const addDays = (k, n) => { const [y, m, d] = parts(k); return keyOf(new Date(Date.UTC(y, m - 1, d + n))); };
19
+ const wd = (k) => { const [y, m, d] = parts(k); return (new Date(Date.UTC(y, m - 1, d)).getUTCDay() + 6) % 7; }; // Monday is 0
20
+ const hasTime = (s) => /T\d{2}:\d{2}/.test(String(s || ''));
21
+ const minOf = (s) => Number(String(s).slice(11, 13)) * 60 + Number(String(s).slice(14, 16)); // the wall clock as written, like premium-meeting.js hhmm
22
+ const hh = (m) => `${pad(Math.floor(m / 60))}:${pad(m % 60)}`;
23
+ export const todayKey = () => { const t = new Date(); return `${t.getFullYear()}-${pad(t.getMonth() + 1)}-${pad(t.getDate())}`; };
24
+
25
+ /** The date one step before (-1) or after (1) `date` in `view`. */
26
+ export function shift(view, date, dir) {
27
+ const [y, m, d] = parts(date);
28
+ if (view === 'day') return addDays(date, dir);
29
+ if (view === 'week') return addDays(date, 7 * dir);
30
+ return keyOf(new Date(Date.UTC(y, m - 1 + dir, 1)));
31
+ }
32
+
33
+ /** The range's name: "Mon 19 Oct 2026", "19 – 25 Oct 2026" (or "28 Sep – 4 Oct 2026"), "October 2026". */
34
+ export function titleOf(view, range) {
35
+ const [y1, m1, d1] = parts(range.start), [y2, m2, d2] = parts(range.end);
36
+ if (view === 'month') return `${MONTH[m1 - 1]} ${y1}`;
37
+ if (view === 'day') return `${DOW[wd(range.start)]} ${d1} ${MON[m1 - 1]} ${y1}`;
38
+ if (y1 !== y2) return `${d1} ${MON[m1 - 1]} ${y1} – ${d2} ${MON[m2 - 1]} ${y2}`;
39
+ return m1 === m2 ? `${d1} – ${d2} ${MON[m2 - 1]} ${y2}` : `${d1} ${MON[m1 - 1]} – ${d2} ${MON[m2 - 1]} ${y2}`;
40
+ }
41
+
42
+ /** Side by side lanes for meetings that overlap on one day. Mutates each block with lane and lanes. */
43
+ function lanes(blocks) {
44
+ blocks.sort((a, b) => a.s - b.s || b.e - a.e);
45
+ let group = [], end = -1;
46
+ const close = () => { const n = Math.max(1, ...group.map((b) => b.lane + 1)); group.forEach((b) => { b.lanes = n; }); group = []; };
47
+ for (const b of blocks) {
48
+ if (b.s >= end && group.length) close();
49
+ const taken = new Set(group.filter((g) => g.e > b.s).map((g) => g.lane));
50
+ let l = 0; while (taken.has(l)) l++;
51
+ b.lane = l; group.push(b); end = Math.max(end, b.e);
52
+ }
53
+ if (group.length) close();
54
+ return blocks;
55
+ }
56
+
57
+ /** The grid as drawn. `r` is the answer of GET /api/calendar-views for `view`, or { ok:false, error }. Every block is a meeting row of
58
+ * weekView (premium-meeting.js), so pressing it opens the same meeting dialog the Briefing's card opens. */
59
+ export function calModel(r, view, date, today) {
60
+ const W = weekView(r, today);
61
+ const range = (r && r.range) || { start: date, end: date };
62
+ const base = { view, date, today, title: r && r.range ? titleOf(view, r.range) : '' };
63
+ if (W.state !== 'ok') return { ...base, state: 'error', reason: W.reason, days: [], total: 0, caption: 'Calendar not read' };
64
+ const layers = Array.isArray(r.layers) ? r.layers.filter((x) => x && x.title && /^\d{4}-\d{2}-\d{2}/.test(String(x.date))) : [];
65
+ const byKey = new Map(W.days.map((x) => [x.key, x]));
66
+ let from = 8 * 60, to = 18 * 60;
67
+ const dayOf = (key) => {
68
+ const src = byKey.get(key), rows = src ? src.rows : [];
69
+ const timed = [], allday = [];
70
+ rows.forEach((row, i) => {
71
+ const ref = key + '|' + i;
72
+ if (hasTime(row.at) && String(row.at).slice(0, 10) === key) {
73
+ const s = minOf(row.at), endSame = row.end && hasTime(row.end) && String(row.end).slice(0, 10) === key;
74
+ const e = Math.max(s + 15, endSame ? minOf(row.end) : row.end ? 24 * 60 : s + 30);
75
+ from = Math.min(from, Math.floor(s / 60) * 60); to = Math.max(to, Math.min(24 * 60, Math.ceil(e / 60) * 60));
76
+ timed.push({ ref, s, e, title: row.title, time: `${hh(s)}–${hh(e)}`, sub: row.sub, about: row.about, past: row.past, row });
77
+ } else allday.push({ ref, title: row.title, sub: row.sub, kind: 'meet', row });
78
+ });
79
+ for (const x of layers) {
80
+ const a = String(x.date).slice(0, 10), b = x.end && /^\d{4}-\d{2}-\d{2}/.test(String(x.end)) ? String(x.end).slice(0, 10) : a;
81
+ if (a <= key && key <= b) allday.push({ title: x.title, kind: x.kind || x.layer || 'mark', tone: x.tone || null });
82
+ }
83
+ const [, m, d] = parts(key);
84
+ return { key, dow: DOW[wd(key)], n: d, mon: MON[m - 1], label: `${DOW[wd(key)]} ${d} ${MON[m - 1]}`, today: key === today, past: key < today,
85
+ inRange: key >= range.start && key <= range.end, timed: lanes(timed), allday, meetings: rows.length };
86
+ };
87
+ let keys = [];
88
+ if (view === 'month') {
89
+ const first = addDays(range.start, -wd(range.start)), last = addDays(range.end, 6 - wd(range.end));
90
+ for (let k = first; k <= last; k = addDays(k, 1)) keys.push(k);
91
+ } else for (let k = range.start; k <= range.end; k = addDays(k, 1)) keys.push(k);
92
+ let days = keys.map(dayOf);
93
+ // the week shows Saturday and Sunday only when they hold something, or one is today
94
+ if (view === 'week') days = days.filter((x) => wd(x.key) < 5 || x.today || x.meetings || x.allday.length);
95
+ const total = days.filter((x) => x.inRange).reduce((s, x) => s + x.meetings, 0);
96
+ const none = r.events_source === 'none' ? 'PMOS holds no calendar to read.' : `No meetings ${view === 'day' ? 'on this day' : 'in this ' + view}.`;
97
+ return { ...base, state: 'ok', days, from, to, total, caption: total ? `${total} ${total === 1 ? 'meeting' : 'meetings'}` : 'No meetings', empty: total ? '' : none };
98
+ }
99
+
100
+ const ICON = {
101
+ back: 'M15 6l-6 6 6 6', next: 'M9 6l6 6-6 6',
102
+ };
103
+ const ic = (k) => `<svg class="i" viewBox="0 0 24 24"><path d="${ICON[k]}"/></svg>`;
104
+
105
+ /** The grid's markup. Both the timeline and the list are drawn for Day and Week; the pane's width picks one (premium-vw-cal.css). */
106
+ export function calHtml(M, esc, nowMin = null) {
107
+ const H = 44, top = (m) => ((m - M.from) / 60) * H;
108
+ const seg = `<div class="vc-seg" role="group" aria-label="Calendar view">${VIEWS.map(([k, l]) => `<button type="button" data-cv="${k}" aria-pressed="${M.view === k}">${l}</button>`).join('')}</div>`;
109
+ const step = M.view === 'day' ? 'day' : M.view === 'week' ? 'week' : 'month';
110
+ const head = `<div class="vc-h"><button type="button" class="vc-ib" data-cn="-1" aria-label="Previous ${step}">${ic('back')}</button><button type="button" class="vc-ib" data-cn="1" aria-label="Next ${step}">${ic('next')}</button><button type="button" class="vc-tdy" data-cn="0">Today</button><b class="vc-t">${esc(M.title)}</b><small class="vc-cap">${esc(M.caption)}</small>${seg}</div>`;
111
+ if (M.state !== 'ok') return `<div class="vc-w">${head}<p class="vc-empty" role="status">Calendar not read. ${esc(M.reason)}</p></div>`;
112
+ const chip = (a) => a.row ? `<button type="button" class="vc-ad meet" data-ev="${esc(a.ref)}" title="${esc(a.title)}">${esc(a.title)}</button>` : `<span class="vc-ad ${esc(a.kind)}${a.tone ? ' t-' + esc(a.tone) : ''}" title="${esc(a.title)}">${esc(a.title)}</span>`;
113
+ const empty = M.empty ? `<p class="vc-empty" role="status">${esc(M.empty)}</p>` : '';
114
+ if (M.view === 'month') {
115
+ const cells = M.days.map((x) => {
116
+ const ev = [...x.allday.filter((a) => a.row), ...x.timed].sort((a, b) => (a.s || 0) - (b.s || 0));
117
+ const say = `${x.label}${x.today ? ', today' : ''}: ${x.meetings ? x.meetings + (x.meetings === 1 ? ' meeting' : ' meetings') : 'no meetings'}`;
118
+ return `<div class="vc-md${x.inRange ? '' : ' out'}${x.today ? ' now' : ''}${x.past ? ' past' : ''}"><button type="button" class="vc-dn" data-day="${x.key}" aria-label="${esc(say)}"><b>${x.n}</b>${x.meetings ? `<i>${x.meetings}</i>` : ''}</button>${x.allday.filter((a) => !a.row).slice(0, 1).map(chip).join('')}${ev.slice(0, 3).map((e) => `<button type="button" class="vc-me" data-ev="${esc(e.ref)}" title="${esc(e.title)}">${e.s != null ? `<time>${hh(e.s)}</time>` : ''}${esc(e.title)}</button>`).join('')}${ev.length > 3 ? `<button type="button" class="vc-more" data-day="${x.key}">${ev.length - 3} more</button>` : ''}</div>`;
119
+ }).join('');
120
+ return `<div class="vc-w">${head}<div class="vc-mg"><div class="vc-mh">${DOW.map((d) => `<span>${d}</span>`).join('')}</div><div class="vc-mb">${cells}</div></div>${empty}</div>`;
121
+ }
122
+ const n = M.days.length, hours = [];
123
+ for (let m = M.from; m < M.to; m += 60) hours.push(m);
124
+ const blk = (e) => `<button type="button" class="vc-ev${e.past ? ' past' : ''}${e.e - e.s < 30 ? ' sh' : ''}" data-ev="${esc(e.ref)}" data-tl="${top(e.s) + 1}px ${Math.max(14, ((e.e - e.s) / 60) * H - 3)}px ${(e.lane / e.lanes) * 100}% ${100 / e.lanes}%" title="${esc(e.title + ' · ' + e.time)}"><b>${esc(e.title)}</b><small>${e.time}</small></button>`;
125
+ const grid = `<div class="vc-g" data-tl="${n}"><div class="vc-c"></div>${M.days.map((x) => `<div class="vc-dh${x.today ? ' now' : ''}">${x.dow}<b>${x.n}</b></div>`).join('')}<div class="vc-adl">all day</div>${M.days.map((x) => `<div class="vc-adc">${x.allday.map(chip).join('')}</div>`).join('')}<div class="vc-gut">${hours.map((m) => `<i>${hh(m)}</i>`).join('')}</div>${M.days.map((x) => `<div class="vc-day${x.past ? ' past' : ''}" data-tl="${hours.length * H}px">${x.today && nowMin != null && nowMin >= M.from && nowMin <= M.to ? `<span class="vc-now" data-tl="${top(nowMin)}px" aria-hidden="true"></span>` : ''}${x.timed.map(blk).join('')}</div>`).join('')}</div>`;
126
+ const list = `<div class="vc-ag">${M.days.map((x) => { const rows = [...x.allday.filter((a) => a.row), ...x.timed]; return `<h4${x.today ? ' class="now"' : ''}>${x.label}${x.today ? ' · today' : ''}</h4>${x.allday.filter((a) => !a.row).map(chip).join('')}${rows.length ? rows.map((e) => `<button type="button" class="vc-ar${e.past ? ' past' : ''}" data-ev="${esc(e.ref)}"><time>${e.s != null ? hh(e.s) : 'All day'}</time><span><b>${esc(e.title)}</b>${e.sub || e.about ? `<small>${esc([e.sub, e.about].filter(Boolean).join(' · '))}</small>` : ''}</span></button>`).join('') : '<p class="vc-none">No meetings</p>'}`; }).join('')}</div>`;
127
+ return `<div class="vc-w">${head}${empty}${grid}${list}</div>`;
128
+ }
129
+
130
+ /** The run-time geometry of the timeline: data-tl on a block is "top height left width", on the grid its column count, on a day its height. */
131
+ export function placeAll(el) {
132
+ el.querySelectorAll('[data-tl]').forEach((n) => {
133
+ const v = n.dataset.tl.split(' ');
134
+ if (n.classList.contains('vc-ev')) ['--tl-t', '--tl-h', '--tl-l', '--tl-w'].forEach((k, i) => n.style.setProperty(k, v[i]));
135
+ else if (n.classList.contains('vc-g')) n.style.setProperty('--tl-n', v[0]);
136
+ else if (n.classList.contains('vc-day')) n.style.setProperty('--tl-hh', v[0]);
137
+ else n.style.setProperty('--tl-t', v[0]);
138
+ });
139
+ }
140
+
141
+ const S = new WeakMap(); // host -> { st, M, seq }
142
+
143
+ /** Draws the grid in `el` and keeps it live. st = { view, date }. d = { pmGet, esc, ws(), openRow(row) } */
144
+ export function mountCal(el, st, d) {
145
+ vwStyle('cal');
146
+ const me = { st: { view: (st && st.view) || 'week', date: (st && st.date) || todayKey() }, M: null, seq: 0 };
147
+ S.set(el, me); el.classList.add('vc');
148
+ const nowMin = () => { const t = new Date(); return t.getHours() * 60 + t.getMinutes(); };
149
+ const paint = () => { el.innerHTML = me.M ? calHtml(me.M, d.esc, nowMin()) : `<div class="vc-w"><p class="vc-empty" role="status">Reading the calendar PMOS holds.</p></div>`; placeAll(el); };
150
+ const read = async () => {
151
+ const n = ++me.seq, { view, date } = me.st, w = d.ws && d.ws();
152
+ const res = await d.pmGet(`/api/calendar-views?view=${view}&date=${date}${w ? '&ws=' + encodeURIComponent(w) : ''}`);
153
+ if (n !== me.seq || !el.isConnected) return;
154
+ me.M = calModel(res, view, date, todayKey()); paint();
155
+ };
156
+ const go = (view, date, focus) => { me.st = { view, date }; read().then(() => { if (!focus) return; const b = el.querySelector(focus); if (b) b.focus(); }); };
157
+ el.onclick = (e) => { // delegated: every control of the grid is a button inside el
158
+ const b = e.target.closest('button'); if (!b || !el.contains(b)) return;
159
+ if (b.dataset.cv) return go(b.dataset.cv, me.st.date, `[data-cv="${b.dataset.cv}"]`);
160
+ if (b.dataset.cn != null) { const dir = +b.dataset.cn; return go(me.st.view, dir ? shift(me.st.view, me.st.date, dir) : todayKey(), `[data-cn="${b.dataset.cn}"]`); }
161
+ if (b.dataset.day) return go('day', b.dataset.day, '[data-cv="day"]');
162
+ if (b.dataset.ev) {
163
+ const [k, i] = b.dataset.ev.split('|'), x = me.M && me.M.days.find((y) => y.key === k);
164
+ const hit = x && [...x.timed, ...x.allday].find((y) => y.ref === k + '|' + i);
165
+ if (hit && hit.row && d.openRow) d.openRow(hit.row, { ...me.st });
166
+ }
167
+ };
168
+ paint(); read();
169
+ return { state: () => ({ ...me.st }), reload: read };
170
+ }
171
+
172
+ /** The calendar on its own: a dialog whose detail is the grid. d = { openDlg, turnA, ptx, $, pmGet, esc, ws(), openRow(row) } where openRow
173
+ * opens the meeting dialog. After a meeting opens, the grid comes back as a tab beside it at the same view and date. */
174
+ export function openCalendar(d, st) {
175
+ const open = (row, at) => {
176
+ d.openRow(row); // openDlg runs at once inside, so the tab below belongs to the meeting's dialog
177
+ vwOpen({ id: 'cal', title: 'Calendar', icon: 'cal', render: (el) => { el.classList.add('vc'); mountCal(el, at, { ...d, openRow: open }); } });
178
+ vwShow('main');
179
+ };
180
+ d.openDlg({ eye: 'Calendar · real data', title: 'Calendar', stream: d.turnA(d.ptx('This is the calendar PMOS holds. Press a meeting to open its detail; the calendar stays as a tab beside it.')),
181
+ pane: '<div class="vc" id="vcMain"></div>', label: 'Calendar' });
182
+ const f = d.$('#askF'); if (f) f.hidden = true;
183
+ return mountCal(d.$('#vcMain'), st || { view: 'week', date: todayKey() }, { ...d, openRow: open });
184
+ }
185
+
186
+ /** The Briefing's Calendar card gets a button that opens the full calendar. */
187
+ export function mountCalEntry(card, d) {
188
+ if (!card || card.querySelector('.vc-open')) return;
189
+ vwStyle('cal');
190
+ const b = document.createElement('button'); b.type = 'button'; b.className = 'vc-open'; b.setAttribute('aria-label', 'Open the calendar'); b.title = 'Open the calendar';
191
+ b.innerHTML = '<svg class="i" viewBox="0 0 24 24"><path d="M14 4h6v6M10 20H4v-6M20 4l-7 7M4 20l7-7"/></svg>';
192
+ const h = card.querySelector('.ch'), fold = h && h.querySelector('.foldb');
193
+ if (fold) fold.before(b); else if (h) h.append(b);
194
+ b.onclick = () => openCalendar(d);
195
+ }
196
+
197
+ if (typeof window !== 'undefined') window.__premiumCal = { calModel, openCalendar };