@tolokoban/impress 0.0.0-stage → 0.1.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.
- package/LICENSE +674 -0
- package/README.md +386 -2
- package/dist/impress.js +1515 -0
- package/dist/styles.js +411 -0
- package/package.json +50 -5
package/dist/impress.js
ADDED
|
@@ -0,0 +1,1515 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Convert teaching markdown files into LibreOffice Impress presentations.
|
|
4
|
+
*
|
|
5
|
+
* Usage: node scripts/impress/impress.ts file1.md [file2.md ...]
|
|
6
|
+
*
|
|
7
|
+
* Each `foo.md` produces `foo.odp` in the same folder, styled by `foo.style.json`
|
|
8
|
+
* (created with the default style of `styles.ts` if missing, merged over it otherwise).
|
|
9
|
+
*
|
|
10
|
+
* Markdown conventions:
|
|
11
|
+
* # / ## / ### ... sections and slides
|
|
12
|
+
* @hint ... layout hint: stored verbatim in the .odp (alt-text
|
|
13
|
+
* description of the slide title), never displayed
|
|
14
|
+
* @note ... speaker note
|
|
15
|
+
* @note begin / @note end multi-line speaker note
|
|
16
|
+
* @layout grid 3x2 the next 6 sections (starting at the next heading) on one
|
|
17
|
+
* slide, in a grid of 3 columns and 2 rows
|
|
18
|
+
* @layout columns 1fr 2fr auto
|
|
19
|
+
* the next 3 sections on one slide, in columns sized by
|
|
20
|
+
* fractions of the free width or by their content (auto)
|
|
21
|
+
* @graph diagram.dot Graphviz diagram converted into native, editable shapes
|
|
22
|
+
* ```prompt ... ``` chat prompt bubble
|
|
23
|
+
*/
|
|
24
|
+
import { existsSync, readFileSync, writeFileSync, statSync } from "node:fs";
|
|
25
|
+
import { basename, dirname, extname, resolve } from "node:path";
|
|
26
|
+
import { crc32, deflateRawSync } from "node:zlib";
|
|
27
|
+
import { defaultStyle } from "./styles.js";
|
|
28
|
+
const PT = 0.03528; // cm per point
|
|
29
|
+
// Style of the file being converted (see `useStyle()`).
|
|
30
|
+
let style = defaultStyle;
|
|
31
|
+
let sizes = style.theme.sizes;
|
|
32
|
+
let SLIDE_W = 0;
|
|
33
|
+
let SLIDE_H = 0;
|
|
34
|
+
let X0 = 0;
|
|
35
|
+
let Y0 = 0;
|
|
36
|
+
let W = 0;
|
|
37
|
+
let H = 0;
|
|
38
|
+
let GAP = 0;
|
|
39
|
+
function useStyle(config) {
|
|
40
|
+
style = config;
|
|
41
|
+
sizes = config.theme.sizes;
|
|
42
|
+
SLIDE_W = config.theme.slide.width;
|
|
43
|
+
SLIDE_H = config.theme.slide.height;
|
|
44
|
+
({ x: X0, y: Y0, width: W, height: H, gap: GAP } = config.theme.content);
|
|
45
|
+
}
|
|
46
|
+
function isObject(v) {
|
|
47
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
48
|
+
}
|
|
49
|
+
/** Objects are merged recursively; arrays and scalars of `over` replace those of `base`. */
|
|
50
|
+
function deepMerge(base, over) {
|
|
51
|
+
if (!isObject(base) || !isObject(over))
|
|
52
|
+
return (over === undefined ? base : over);
|
|
53
|
+
const out = { ...base };
|
|
54
|
+
for (const [k, v] of Object.entries(over))
|
|
55
|
+
out[k] = k in base ? deepMerge(base[k], v) : v;
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* `foo.md` uses `foo.style.json`, merged over the default style.
|
|
60
|
+
* If that file does not exist, it is created with the default style.
|
|
61
|
+
*/
|
|
62
|
+
function loadStyle(src) {
|
|
63
|
+
const path = src.replace(/\.md$/i, ".style.json");
|
|
64
|
+
if (!existsSync(path)) {
|
|
65
|
+
writeFileSync(path, JSON.stringify(defaultStyle, null, 4) + "\n");
|
|
66
|
+
return { config: defaultStyle, path, created: true };
|
|
67
|
+
}
|
|
68
|
+
let json;
|
|
69
|
+
try {
|
|
70
|
+
json = JSON.parse(readFileSync(path, "utf8"));
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
throw new Error(`Invalid JSON in ${path}: ${err instanceof Error ? err.message : err}`);
|
|
74
|
+
}
|
|
75
|
+
if (!isObject(json))
|
|
76
|
+
throw new Error(`${path} must contain a JSON object`);
|
|
77
|
+
return { config: deepMerge(defaultStyle, json), path, created: false };
|
|
78
|
+
}
|
|
79
|
+
/** Replace "{colors.primary}"-like placeholders with values from the theme. */
|
|
80
|
+
function resolveValue(value, where) {
|
|
81
|
+
return value.replace(/\{([\w.]+)\}/g, (_, path) => {
|
|
82
|
+
let v = style.theme;
|
|
83
|
+
for (const key of path.split("."))
|
|
84
|
+
v = isObject(v) || Array.isArray(v) ? v[key] : undefined;
|
|
85
|
+
if (typeof v !== "string" && typeof v !== "number")
|
|
86
|
+
throw new Error(`Unknown theme value "{${path}}" in ${where}`);
|
|
87
|
+
return String(v);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function cellCount(layout) {
|
|
91
|
+
return layout.kind === "grid" ? layout.columns * layout.rows : layout.widths.length;
|
|
92
|
+
}
|
|
93
|
+
function parseLayout(spec, where) {
|
|
94
|
+
const source = `@layout ${spec}`;
|
|
95
|
+
const [kind, ...args] = spec.split(/\s+/).filter(Boolean);
|
|
96
|
+
if (kind === "grid") {
|
|
97
|
+
const m = args.join("").match(/^(\d+)[x×](\d+)$/i);
|
|
98
|
+
if (!m || args.length !== 1 || Number(m[1]) < 1 || Number(m[2]) < 1)
|
|
99
|
+
throw new Error(`${where}: expected "@layout grid <columns>x<rows>", got "${source}"`);
|
|
100
|
+
return { kind, columns: Number(m[1]), rows: Number(m[2]), source };
|
|
101
|
+
}
|
|
102
|
+
if (kind === "columns") {
|
|
103
|
+
if (!args.length)
|
|
104
|
+
throw new Error(`${where}: "@layout columns" needs at least one size (e.g. 1fr 2fr auto)`);
|
|
105
|
+
const widths = args.map(a => {
|
|
106
|
+
if (a === "auto")
|
|
107
|
+
return "auto";
|
|
108
|
+
const m = a.match(/^(\d+(?:\.\d+)?)fr$/);
|
|
109
|
+
if (!m || Number(m[1]) <= 0)
|
|
110
|
+
throw new Error(`${where}: invalid column size "${a}" (only fractions like "2fr" and "auto" are allowed)`);
|
|
111
|
+
return Number(m[1]);
|
|
112
|
+
});
|
|
113
|
+
return { kind, widths, source };
|
|
114
|
+
}
|
|
115
|
+
throw new Error(`${where}: unknown layout "${kind ?? ""}" (expected "grid" or "columns")`);
|
|
116
|
+
}
|
|
117
|
+
class Section {
|
|
118
|
+
level;
|
|
119
|
+
title;
|
|
120
|
+
parent;
|
|
121
|
+
blocks = [];
|
|
122
|
+
hints = [];
|
|
123
|
+
children = [];
|
|
124
|
+
/** Set on the first section of a group laid out on a single slide. */
|
|
125
|
+
layout = null;
|
|
126
|
+
/** Folder of the markdown file, for relative image paths. */
|
|
127
|
+
source;
|
|
128
|
+
constructor(level, title, parent = null, source = "") {
|
|
129
|
+
this.source = source;
|
|
130
|
+
this.level = level;
|
|
131
|
+
this.title = title;
|
|
132
|
+
this.parent = parent;
|
|
133
|
+
}
|
|
134
|
+
path() {
|
|
135
|
+
const out = [];
|
|
136
|
+
for (let s = this; s && s.level > 0; s = s.parent)
|
|
137
|
+
out.unshift(s.title);
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function stripMd(s) {
|
|
142
|
+
return s
|
|
143
|
+
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
|
|
144
|
+
.replaceAll("**", "")
|
|
145
|
+
.replaceAll("__", "")
|
|
146
|
+
.replace(/(?<![\p{L}\p{N}_])\*(.+?)\*(?![\p{L}\p{N}_])/gu, "$1")
|
|
147
|
+
.trim();
|
|
148
|
+
}
|
|
149
|
+
const LIST_RE = /^(\s*)[*-]\s+(.*)$/;
|
|
150
|
+
const IMG_RE = /^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/;
|
|
151
|
+
const HEAD_RE = /^(#{1,6})\s+(.*)$/;
|
|
152
|
+
function parse(md, file) {
|
|
153
|
+
const root = new Section(0, "", null, dirname(file));
|
|
154
|
+
let cur = root;
|
|
155
|
+
const lines = md.split("\n");
|
|
156
|
+
let para = [];
|
|
157
|
+
let list = null;
|
|
158
|
+
let layout = null;
|
|
159
|
+
const flushPara = () => {
|
|
160
|
+
if (!para.length)
|
|
161
|
+
return;
|
|
162
|
+
let text = "";
|
|
163
|
+
para.forEach((l, j) => {
|
|
164
|
+
text += l.trim();
|
|
165
|
+
if (j < para.length - 1)
|
|
166
|
+
text += l.endsWith(" ") ? "\n" : " ";
|
|
167
|
+
});
|
|
168
|
+
cur.blocks.push({ t: "para", text });
|
|
169
|
+
para = [];
|
|
170
|
+
};
|
|
171
|
+
const flushList = () => {
|
|
172
|
+
if (list)
|
|
173
|
+
cur.blocks.push(list);
|
|
174
|
+
list = null;
|
|
175
|
+
};
|
|
176
|
+
const flush = () => {
|
|
177
|
+
flushPara();
|
|
178
|
+
flushList();
|
|
179
|
+
};
|
|
180
|
+
for (let i = 0; i < lines.length; i++) {
|
|
181
|
+
const line = lines[i];
|
|
182
|
+
const s = line.trim();
|
|
183
|
+
let m;
|
|
184
|
+
if ((m = line.match(HEAD_RE))) {
|
|
185
|
+
flush();
|
|
186
|
+
const level = m[1].length;
|
|
187
|
+
while (cur.level >= level)
|
|
188
|
+
cur = cur.parent;
|
|
189
|
+
const sec = new Section(level, stripMd(m[2]), cur, root.source);
|
|
190
|
+
sec.layout = layout;
|
|
191
|
+
layout = null;
|
|
192
|
+
cur.children.push(sec);
|
|
193
|
+
cur = sec;
|
|
194
|
+
}
|
|
195
|
+
else if (s.startsWith("@layout")) {
|
|
196
|
+
flush();
|
|
197
|
+
layout = parseLayout(s.slice(7).trim(), `${file}:${i + 1}`);
|
|
198
|
+
}
|
|
199
|
+
else if (s.startsWith("@graph")) {
|
|
200
|
+
flush();
|
|
201
|
+
const src = s.slice(6).trim();
|
|
202
|
+
const where = `${file}:${i + 1}`;
|
|
203
|
+
if (!src.toLowerCase().endsWith(".dot"))
|
|
204
|
+
throw new Error(`${where}: expected "@graph <relative path of a .dot file>", got "${s}"`);
|
|
205
|
+
if (!existsSync(resolve(dirname(file), src)))
|
|
206
|
+
throw new Error(`${where}: file not found: ${src}`);
|
|
207
|
+
cur.blocks.push({ t: "image", alt: "", src });
|
|
208
|
+
}
|
|
209
|
+
else if (s.startsWith("@hint")) {
|
|
210
|
+
flush();
|
|
211
|
+
cur.hints.push(s);
|
|
212
|
+
}
|
|
213
|
+
else if (s === "@note begin") {
|
|
214
|
+
flush();
|
|
215
|
+
const buf = [];
|
|
216
|
+
for (i++; i < lines.length && lines[i].trim() !== "@note end"; i++)
|
|
217
|
+
buf.push(lines[i]);
|
|
218
|
+
cur.blocks.push({ t: "note", text: buf.join("\n").trim() });
|
|
219
|
+
}
|
|
220
|
+
else if (s.startsWith("@note")) {
|
|
221
|
+
flush();
|
|
222
|
+
cur.blocks.push({ t: "note", text: s.slice(5).trim() });
|
|
223
|
+
}
|
|
224
|
+
else if (s.startsWith("```")) {
|
|
225
|
+
flush();
|
|
226
|
+
const lang = s.slice(3).trim();
|
|
227
|
+
const buf = [];
|
|
228
|
+
for (i++; i < lines.length && !lines[i].trim().startsWith("```"); i++)
|
|
229
|
+
buf.push(lines[i]);
|
|
230
|
+
cur.blocks.push({ t: lang === "prompt" ? "prompt" : "code", lines: buf });
|
|
231
|
+
}
|
|
232
|
+
else if (s.startsWith("|")) {
|
|
233
|
+
flush();
|
|
234
|
+
const rows = [];
|
|
235
|
+
for (; i < lines.length && lines[i].trim().startsWith("|"); i++) {
|
|
236
|
+
const row = lines[i].trim().replace(/^\|/, "").replace(/\|$/, "");
|
|
237
|
+
rows.push(row.split("|").map(c => c.trim()));
|
|
238
|
+
}
|
|
239
|
+
i--;
|
|
240
|
+
let header = rows[0];
|
|
241
|
+
const body = rows.slice(1).filter(r => !/^[\s:\-|]*$/.test(r.join("")));
|
|
242
|
+
if (header.every(c => c === "" || c === "."))
|
|
243
|
+
header = null;
|
|
244
|
+
cur.blocks.push({ t: "table", header, rows: body });
|
|
245
|
+
}
|
|
246
|
+
else if (s.startsWith(">")) {
|
|
247
|
+
flush();
|
|
248
|
+
const buf = [];
|
|
249
|
+
for (; i < lines.length && lines[i].trim().startsWith(">"); i++)
|
|
250
|
+
buf.push(lines[i].trim().slice(1).trim());
|
|
251
|
+
i--;
|
|
252
|
+
cur.blocks.push({ t: "quote", text: buf.join(" ") });
|
|
253
|
+
}
|
|
254
|
+
else if ((m = line.match(IMG_RE))) {
|
|
255
|
+
flush();
|
|
256
|
+
cur.blocks.push({ t: "image", alt: m[1], src: m[2] });
|
|
257
|
+
}
|
|
258
|
+
else if ((m = line.match(LIST_RE))) {
|
|
259
|
+
flushPara();
|
|
260
|
+
list ??= { t: "list", items: [] };
|
|
261
|
+
list.items.push([Math.floor(m[1].length / 2), m[2].trim()]);
|
|
262
|
+
}
|
|
263
|
+
else if (s === "") {
|
|
264
|
+
flushPara();
|
|
265
|
+
// A blank line ends a list unless the next non-blank line is a list item.
|
|
266
|
+
let j = i + 1;
|
|
267
|
+
while (j < lines.length && lines[j].trim() === "")
|
|
268
|
+
j++;
|
|
269
|
+
if (list && !(j < lines.length && LIST_RE.test(lines[j])))
|
|
270
|
+
flushList();
|
|
271
|
+
}
|
|
272
|
+
else if (list && line.startsWith(" ")) {
|
|
273
|
+
const items = list.items;
|
|
274
|
+
items[items.length - 1][1] += " " + s;
|
|
275
|
+
}
|
|
276
|
+
else {
|
|
277
|
+
flushList();
|
|
278
|
+
para.push(line);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
flush();
|
|
282
|
+
if (layout)
|
|
283
|
+
console.warn(` ! ${file}: "${layout.source}" is not followed by any section`);
|
|
284
|
+
return root;
|
|
285
|
+
}
|
|
286
|
+
const INLINE_PATTERNS = [
|
|
287
|
+
["link", /\[([^\]]+)\]\(([^)]+)\)/],
|
|
288
|
+
["auto", /<(https?:\/\/[^>]+)>/],
|
|
289
|
+
["bi", /\*\*\*(.+?)\*\*\*/s],
|
|
290
|
+
["b", /\*\*(.+?)\*\*/s],
|
|
291
|
+
["i", /(?<![\p{L}\p{N}_*])\*(?!\s)(.+?)(?<!\s)\*(?![\p{L}\p{N}_*])/su],
|
|
292
|
+
["code", /`([^`]+)`/],
|
|
293
|
+
];
|
|
294
|
+
function inline(s, fmt = new Set(), href = null) {
|
|
295
|
+
s = s.replace("$\\text{XX}^\\text{e}$", "XXᵉ");
|
|
296
|
+
const runs = [];
|
|
297
|
+
while (s) {
|
|
298
|
+
let best = null;
|
|
299
|
+
for (const [kind, rx] of INLINE_PATTERNS) {
|
|
300
|
+
const m = rx.exec(s);
|
|
301
|
+
if (m && (!best || m.index < best[1].index))
|
|
302
|
+
best = [kind, m];
|
|
303
|
+
}
|
|
304
|
+
if (!best) {
|
|
305
|
+
runs.push({ text: s, fmt, href });
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
const [kind, m] = best;
|
|
309
|
+
if (m.index)
|
|
310
|
+
runs.push({ text: s.slice(0, m.index), fmt, href });
|
|
311
|
+
const add = (...k) => new Set([...fmt, ...k]);
|
|
312
|
+
if (kind === "link")
|
|
313
|
+
runs.push(...inline(m[1], fmt, m[2]));
|
|
314
|
+
else if (kind === "auto")
|
|
315
|
+
runs.push({ text: m[1], fmt, href: m[1] });
|
|
316
|
+
else if (kind === "bi")
|
|
317
|
+
runs.push(...inline(m[1], add("b", "i"), href));
|
|
318
|
+
else if (kind === "code")
|
|
319
|
+
runs.push({ text: m[1], fmt: add("code"), href });
|
|
320
|
+
else
|
|
321
|
+
runs.push(...inline(m[1], add(kind), href));
|
|
322
|
+
s = s.slice(m.index + m[0].length);
|
|
323
|
+
}
|
|
324
|
+
return runs;
|
|
325
|
+
}
|
|
326
|
+
function esc(s) {
|
|
327
|
+
return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
328
|
+
}
|
|
329
|
+
/** Escape text for ODF, preserving consecutive spaces, tabs and line breaks. */
|
|
330
|
+
function xmlText(s) {
|
|
331
|
+
return s
|
|
332
|
+
.split("\n")
|
|
333
|
+
.map(line => esc(line)
|
|
334
|
+
.replace(/ {2,}|^ +/g, (m, offset) => {
|
|
335
|
+
if (offset === 0)
|
|
336
|
+
return `<text:s text:c="${m.length}"/>`;
|
|
337
|
+
return " " + (m.length > 1 ? `<text:s text:c="${m.length - 1}"/>` : "");
|
|
338
|
+
})
|
|
339
|
+
.replaceAll("\t", "<text:tab/>"))
|
|
340
|
+
.join("<text:line-break/>");
|
|
341
|
+
}
|
|
342
|
+
function spanStyle(fmt) {
|
|
343
|
+
if (fmt.has("code"))
|
|
344
|
+
return "T_code";
|
|
345
|
+
if (fmt.has("b") && fmt.has("i"))
|
|
346
|
+
return "T_bi";
|
|
347
|
+
if (fmt.has("b"))
|
|
348
|
+
return "T_b";
|
|
349
|
+
if (fmt.has("i"))
|
|
350
|
+
return "T_i";
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
function runsXml(text) {
|
|
354
|
+
return inline(text)
|
|
355
|
+
.map(({ text, fmt, href }) => {
|
|
356
|
+
let x = xmlText(text);
|
|
357
|
+
const st = spanStyle(fmt);
|
|
358
|
+
if (st)
|
|
359
|
+
x = `<text:span text:style-name="${st}">${x}</text:span>`;
|
|
360
|
+
if (href)
|
|
361
|
+
x = `<text:a xlink:type="simple" xlink:href="${esc(href)}">${x}</text:a>`;
|
|
362
|
+
return x;
|
|
363
|
+
})
|
|
364
|
+
.join("");
|
|
365
|
+
}
|
|
366
|
+
function plainLen(text) {
|
|
367
|
+
return inline(text).reduce((n, r) => n + r.text.length, 0);
|
|
368
|
+
}
|
|
369
|
+
// ---------------------------------------------------------------- measuring
|
|
370
|
+
function textH(nChars, width, pt, lh = 1.25) {
|
|
371
|
+
const cpl = Math.max(1, width / (pt * PT * 0.5));
|
|
372
|
+
return Math.max(1, Math.ceil(nChars / cpl)) * pt * PT * lh;
|
|
373
|
+
}
|
|
374
|
+
function paraH(text, width, pt = sizes.text) {
|
|
375
|
+
return text.split("\n").reduce((h, p) => h + textH(plainLen(p), width, pt), 0) + 0.25;
|
|
376
|
+
}
|
|
377
|
+
function listH(items, width) {
|
|
378
|
+
let h = 0;
|
|
379
|
+
for (const [lvl, txt] of items)
|
|
380
|
+
h += textH(plainLen(txt), width - 0.9 * (lvl + 1), sizes.list[Math.min(lvl, 8)]) + 0.3;
|
|
381
|
+
return h + 0.1;
|
|
382
|
+
}
|
|
383
|
+
function promptSize(lines, width) {
|
|
384
|
+
const pt = sizes.prompt;
|
|
385
|
+
const longest = Math.max(10, ...lines.map(l => l.length));
|
|
386
|
+
const w = Math.min(width, Math.max(8, longest * pt * PT * 0.5 + 1.4));
|
|
387
|
+
const h = lines.reduce((acc, l) => acc + textH(l.length, w - 1, pt), 0) + 0.9;
|
|
388
|
+
return [w, h];
|
|
389
|
+
}
|
|
390
|
+
function tableCols(header, rows, width) {
|
|
391
|
+
const all = header ? [header, ...rows] : rows;
|
|
392
|
+
const ncol = Math.max(...all.map(r => r.length));
|
|
393
|
+
const lens = new Array(ncol).fill(0);
|
|
394
|
+
for (const r of all)
|
|
395
|
+
r.forEach((cell, c) => (lens[c] = Math.max(lens[c], Math.min(plainLen(cell), 45) + 4)));
|
|
396
|
+
const tot = lens.reduce((a, b) => a + b, 0);
|
|
397
|
+
return lens.map(l => (width * l) / tot);
|
|
398
|
+
}
|
|
399
|
+
function rowH(r, cols, pt) {
|
|
400
|
+
return Math.max(...r.map((c, i) => textH(plainLen(c), cols[i] - 0.4, pt))) + 0.35;
|
|
401
|
+
}
|
|
402
|
+
function tableH(header, rows, width, pt, cols) {
|
|
403
|
+
cols ??= tableCols(header, rows, width);
|
|
404
|
+
return (header ? [header, ...rows] : rows).reduce((h, r) => h + rowH(r, cols, pt), 0);
|
|
405
|
+
}
|
|
406
|
+
function blockH(b, width) {
|
|
407
|
+
switch (b.t) {
|
|
408
|
+
case "para":
|
|
409
|
+
return paraH(b.text, width);
|
|
410
|
+
case "list":
|
|
411
|
+
return listH(b.items, width);
|
|
412
|
+
case "quote":
|
|
413
|
+
return paraH(b.text, width - 1.2, sizes.quote) + 0.8;
|
|
414
|
+
case "prompt":
|
|
415
|
+
case "code":
|
|
416
|
+
return promptSize(b.lines, width)[1];
|
|
417
|
+
case "table":
|
|
418
|
+
return tableH(b.header, b.rows, width, sizes.table);
|
|
419
|
+
default:
|
|
420
|
+
return 0;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
function imageSize(path) {
|
|
424
|
+
const ext = extname(path).toLowerCase();
|
|
425
|
+
if (ext === ".dot")
|
|
426
|
+
return graphLayout(path).size;
|
|
427
|
+
const data = readFileSync(path);
|
|
428
|
+
if (ext === ".svg") {
|
|
429
|
+
const head = data.subarray(0, 4000).toString("utf8");
|
|
430
|
+
const vb = head.match(/viewBox="[\d.\s-]+?\s([\d.]+)\s([\d.]+)"/);
|
|
431
|
+
if (vb)
|
|
432
|
+
return [Number(vb[1]), Number(vb[2])];
|
|
433
|
+
const w = head.match(/width="([\d.]+)/);
|
|
434
|
+
const h = head.match(/height="([\d.]+)/);
|
|
435
|
+
return [Number(w?.[1] ?? 100), Number(h?.[1] ?? 100)];
|
|
436
|
+
}
|
|
437
|
+
if (ext === ".png")
|
|
438
|
+
return [data.readUInt32BE(16), data.readUInt32BE(20)];
|
|
439
|
+
if (ext === ".webp") {
|
|
440
|
+
const chunk = data.toString("ascii", 12, 16);
|
|
441
|
+
if (chunk === "VP8 ")
|
|
442
|
+
return [data.readUInt16LE(26) & 0x3fff, data.readUInt16LE(28) & 0x3fff];
|
|
443
|
+
if (chunk === "VP8L") {
|
|
444
|
+
const [b0, b1, b2, b3] = data.subarray(21, 25);
|
|
445
|
+
return [1 + (b0 | ((b1 & 0x3f) << 8)), 1 + ((b1 >> 6) | (b2 << 2) | ((b3 & 0xf) << 10))];
|
|
446
|
+
}
|
|
447
|
+
if (chunk === "VP8X")
|
|
448
|
+
return [1 + data.readUIntLE(24, 3), 1 + data.readUIntLE(27, 3)];
|
|
449
|
+
}
|
|
450
|
+
if (ext === ".jpg" || ext === ".jpeg") {
|
|
451
|
+
for (let i = 2; i < data.length - 9;) {
|
|
452
|
+
const marker = data[i + 1];
|
|
453
|
+
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker))
|
|
454
|
+
return [data.readUInt16BE(i + 7), data.readUInt16BE(i + 5)];
|
|
455
|
+
i += 2 + data.readUInt16BE(i + 2);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
throw new Error(`Unsupported image: ${path}`);
|
|
459
|
+
}
|
|
460
|
+
function fit(iw, ih, bw, bh) {
|
|
461
|
+
const r = Math.min(bw / iw, bh / ih);
|
|
462
|
+
return [iw * r, ih * r];
|
|
463
|
+
}
|
|
464
|
+
// ---------------------------------------------------------------- graphviz
|
|
465
|
+
const CM_PER_POINT = 2.54 / 72;
|
|
466
|
+
const graphCache = new Map();
|
|
467
|
+
/** Graphviz compiled to WebAssembly (`@hpcc-js/wasm-graphviz`), loaded by `loadGraphviz()`. */
|
|
468
|
+
let graphviz = null;
|
|
469
|
+
let graphvizError = "";
|
|
470
|
+
async function loadGraphviz() {
|
|
471
|
+
try {
|
|
472
|
+
const lib = await import("@hpcc-js/wasm-graphviz");
|
|
473
|
+
graphviz = await lib.Graphviz.load();
|
|
474
|
+
}
|
|
475
|
+
catch (err) {
|
|
476
|
+
graphvizError = err instanceof Error ? err.message : String(err);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Lay out a .dot file with Graphviz, using the fonts of the current style.
|
|
481
|
+
* The fonts are inserted as default attributes after the opening brace, so
|
|
482
|
+
* attributes set in the .dot file still take precedence.
|
|
483
|
+
*/
|
|
484
|
+
function graphLayout(path) {
|
|
485
|
+
if (!graphviz)
|
|
486
|
+
throw new Error(`Graphviz is not available (run "pnpm install" in scripts/impress): ${graphvizError}`);
|
|
487
|
+
const font = style.theme.fonts.sans.replace(/'/g, "");
|
|
488
|
+
const defaults = `graph [fontname="${font}", fontsize=${sizes.graphEdgeText}]; ` +
|
|
489
|
+
`node [fontname="${font}", fontsize=${sizes.graphText}]; ` +
|
|
490
|
+
`edge [fontname="${font}", fontsize=${sizes.graphEdgeText}]; `;
|
|
491
|
+
const source = readFileSync(path, "utf8");
|
|
492
|
+
const head = source.match(/\b(?:strict\s+)?(?:di)?graph\b[^{]*\{/i);
|
|
493
|
+
if (!head || head.index === undefined)
|
|
494
|
+
throw new Error(`${path}: no "graph { ... }" or "digraph { ... }" found`);
|
|
495
|
+
const at = head.index + head[0].length;
|
|
496
|
+
const dot = source.slice(0, at) + defaults + source.slice(at);
|
|
497
|
+
let layout = graphCache.get(dot);
|
|
498
|
+
if (layout)
|
|
499
|
+
return layout;
|
|
500
|
+
let json;
|
|
501
|
+
try {
|
|
502
|
+
json = graphviz.layout(dot, "json", "dot");
|
|
503
|
+
}
|
|
504
|
+
catch (err) {
|
|
505
|
+
throw new Error(`Graphviz failed on ${path}: ${err instanceof Error ? err.message : err}`);
|
|
506
|
+
}
|
|
507
|
+
const g = JSON.parse(json);
|
|
508
|
+
const bb = String(g.bb ?? "0,0,0,0").split(",").map(Number);
|
|
509
|
+
layout = {
|
|
510
|
+
name: g.name ?? "",
|
|
511
|
+
directed: g.directed !== false,
|
|
512
|
+
bb,
|
|
513
|
+
size: [Math.max(bb[2] - bb[0], 1) * CM_PER_POINT, Math.max(bb[3] - bb[1], 1) * CM_PER_POINT],
|
|
514
|
+
objects: g.objects ?? [],
|
|
515
|
+
edges: g.edges ?? [],
|
|
516
|
+
attrs: g,
|
|
517
|
+
};
|
|
518
|
+
graphCache.set(dot, layout);
|
|
519
|
+
return layout;
|
|
520
|
+
}
|
|
521
|
+
/** Graphviz node shapes and their Impress preset geometry. */
|
|
522
|
+
const NODE_SHAPES = {
|
|
523
|
+
box: "rectangle",
|
|
524
|
+
rect: "rectangle",
|
|
525
|
+
rectangle: "rectangle",
|
|
526
|
+
square: "rectangle",
|
|
527
|
+
record: "rectangle",
|
|
528
|
+
Mrecord: "round-rectangle",
|
|
529
|
+
ellipse: "ellipse",
|
|
530
|
+
oval: "ellipse",
|
|
531
|
+
circle: "ellipse",
|
|
532
|
+
doublecircle: "ellipse",
|
|
533
|
+
point: "ellipse",
|
|
534
|
+
diamond: "diamond",
|
|
535
|
+
Mdiamond: "diamond",
|
|
536
|
+
parallelogram: "parallelogram",
|
|
537
|
+
trapezium: "trapezoid",
|
|
538
|
+
hexagon: "hexagon",
|
|
539
|
+
octagon: "octagon",
|
|
540
|
+
triangle: "isosceles-triangle",
|
|
541
|
+
cylinder: "flowchart-magnetic-disk",
|
|
542
|
+
note: "flowchart-document",
|
|
543
|
+
folder: "flowchart-card",
|
|
544
|
+
star: "star5",
|
|
545
|
+
};
|
|
546
|
+
const COLOR_NAMES = {
|
|
547
|
+
black: "#000000",
|
|
548
|
+
white: "#FFFFFF",
|
|
549
|
+
red: "#FF0000",
|
|
550
|
+
green: "#00A000",
|
|
551
|
+
blue: "#0000FF",
|
|
552
|
+
yellow: "#FFFF00",
|
|
553
|
+
orange: "#FFA500",
|
|
554
|
+
purple: "#800080",
|
|
555
|
+
pink: "#FFC0CB",
|
|
556
|
+
brown: "#A52A2A",
|
|
557
|
+
gray: "#808080",
|
|
558
|
+
grey: "#808080",
|
|
559
|
+
lightgray: "#D3D3D3",
|
|
560
|
+
lightgrey: "#D3D3D3",
|
|
561
|
+
darkgray: "#A9A9A9",
|
|
562
|
+
lightblue: "#ADD8E6",
|
|
563
|
+
lightyellow: "#FFFFE0",
|
|
564
|
+
lightgreen: "#90EE90",
|
|
565
|
+
lightpink: "#FFB6C1",
|
|
566
|
+
gold: "#FFD700",
|
|
567
|
+
navy: "#000080",
|
|
568
|
+
cyan: "#00FFFF",
|
|
569
|
+
magenta: "#FF00FF",
|
|
570
|
+
darkgreen: "#006400",
|
|
571
|
+
darkblue: "#00008B",
|
|
572
|
+
darkred: "#8B0000",
|
|
573
|
+
};
|
|
574
|
+
function gvColor(value) {
|
|
575
|
+
if (typeof value !== "string" || !value)
|
|
576
|
+
return null;
|
|
577
|
+
const v = value.split(":")[0].trim();
|
|
578
|
+
if (/^#[0-9a-f]{6}$/i.test(v))
|
|
579
|
+
return v.toUpperCase();
|
|
580
|
+
if (/^#[0-9a-f]{8}$/i.test(v))
|
|
581
|
+
return v.slice(0, 7).toUpperCase();
|
|
582
|
+
return COLOR_NAMES[v.toLowerCase()] ?? null;
|
|
583
|
+
}
|
|
584
|
+
/** Text of a Graphviz label, with "\n" for line breaks. */
|
|
585
|
+
function gvLabel(raw, name, graphName, record = false) {
|
|
586
|
+
let label = typeof raw === "string" ? raw : "\\N";
|
|
587
|
+
if (label.startsWith("<") && label.endsWith(">")) {
|
|
588
|
+
label = label
|
|
589
|
+
.slice(1, -1)
|
|
590
|
+
.replace(/<br\s*\/?>/gi, "\n")
|
|
591
|
+
.replace(/<[^>]+>/g, "");
|
|
592
|
+
}
|
|
593
|
+
label = label.replaceAll("\\N", name).replaceAll("\\G", graphName);
|
|
594
|
+
if (record)
|
|
595
|
+
label = label.replace(/[{}]/g, "").replace(/\s*\|\s*/g, "\n");
|
|
596
|
+
return label
|
|
597
|
+
.replace(/\\[nlr]/g, "\n")
|
|
598
|
+
.replace(/\n$/, "")
|
|
599
|
+
.replace(/\\(.)/g, "$1");
|
|
600
|
+
}
|
|
601
|
+
/** Stroke properties for Graphviz `style=dashed` or `style=dotted`. */
|
|
602
|
+
function dashed(gvStyle) {
|
|
603
|
+
const dash = Object.keys(style.dashes)[0];
|
|
604
|
+
return dash && /\b(dashed|dotted)\b/.test(String(gvStyle ?? "")) ? { "draw:stroke": "dash", "draw:stroke-dash": dash } : {};
|
|
605
|
+
}
|
|
606
|
+
function gvPoint(s) {
|
|
607
|
+
const [x, y] = s.split(",").map(Number);
|
|
608
|
+
return [x, y];
|
|
609
|
+
}
|
|
610
|
+
// ---------------------------------------------------------------- layout
|
|
611
|
+
const MIME = {
|
|
612
|
+
".png": "image/png",
|
|
613
|
+
".svg": "image/svg+xml",
|
|
614
|
+
".webp": "image/webp",
|
|
615
|
+
".jpg": "image/jpeg",
|
|
616
|
+
".jpeg": "image/jpeg",
|
|
617
|
+
};
|
|
618
|
+
const f2 = (n) => n.toFixed(2);
|
|
619
|
+
class Builder {
|
|
620
|
+
base;
|
|
621
|
+
pictures = new Map();
|
|
622
|
+
pages = [];
|
|
623
|
+
colStyles = new Map();
|
|
624
|
+
rowStyles = new Map();
|
|
625
|
+
/** Hints waiting to be attached to the next slide title. */
|
|
626
|
+
pendingHints = [];
|
|
627
|
+
/** Automatic graphic styles (Graphviz colors), keyed by their properties. */
|
|
628
|
+
autoStyles = new Map();
|
|
629
|
+
/** Automatic paragraph styles (text size and color in diagrams). */
|
|
630
|
+
paraStyles = new Map();
|
|
631
|
+
graphCount = 0;
|
|
632
|
+
constructor(base) {
|
|
633
|
+
this.base = base;
|
|
634
|
+
}
|
|
635
|
+
// -- resources
|
|
636
|
+
picture(src) {
|
|
637
|
+
let pic = this.pictures.get(src);
|
|
638
|
+
if (!pic) {
|
|
639
|
+
const path = resolve(this.base, src);
|
|
640
|
+
let name = basename(src);
|
|
641
|
+
while ([...this.pictures.values()].some(p => p.href === `Pictures/${name}`))
|
|
642
|
+
name = `_${name}`;
|
|
643
|
+
pic = { href: `Pictures/${name}`, data: readFileSync(path), size: imageSize(path) };
|
|
644
|
+
this.pictures.set(src, pic);
|
|
645
|
+
}
|
|
646
|
+
return pic;
|
|
647
|
+
}
|
|
648
|
+
colStyle(w) {
|
|
649
|
+
const key = f2(w);
|
|
650
|
+
if (!this.colStyles.has(key))
|
|
651
|
+
this.colStyles.set(key, `co${this.colStyles.size + 1}`);
|
|
652
|
+
return this.colStyles.get(key);
|
|
653
|
+
}
|
|
654
|
+
rowStyle(h) {
|
|
655
|
+
const key = f2(h);
|
|
656
|
+
if (!this.rowStyles.has(key))
|
|
657
|
+
this.rowStyles.set(key, `ro${this.rowStyles.size + 1}`);
|
|
658
|
+
return this.rowStyles.get(key);
|
|
659
|
+
}
|
|
660
|
+
// -- shapes
|
|
661
|
+
static geom(x, y, w, h) {
|
|
662
|
+
return `svg:x="${f2(x)}cm" svg:y="${f2(y)}cm" svg:width="${f2(w)}cm" svg:height="${f2(h)}cm"`;
|
|
663
|
+
}
|
|
664
|
+
frame(style, x, y, w, h, inner, pres, desc = "") {
|
|
665
|
+
const attrs = pres
|
|
666
|
+
? `presentation:style-name="${style}" presentation:class="${pres}" presentation:user-transformed="true"`
|
|
667
|
+
: `draw:style-name="${style}"`;
|
|
668
|
+
return `<draw:frame ${attrs} ${Builder.geom(x, y, w, h)}><draw:text-box>${inner}</draw:text-box>${desc}</draw:frame>`;
|
|
669
|
+
}
|
|
670
|
+
/** Alt-text description carrying the pending `@hint` lines, invisible on the slide. */
|
|
671
|
+
takeHints() {
|
|
672
|
+
if (!this.pendingHints.length)
|
|
673
|
+
return "";
|
|
674
|
+
const desc = `<svg:desc>${esc(this.pendingHints.join("\n"))}</svg:desc>`;
|
|
675
|
+
this.pendingHints = [];
|
|
676
|
+
return desc;
|
|
677
|
+
}
|
|
678
|
+
listXml(items) {
|
|
679
|
+
const out = [];
|
|
680
|
+
let depth = 0;
|
|
681
|
+
for (const [lvl, txt] of items) {
|
|
682
|
+
while (depth > lvl + 1) {
|
|
683
|
+
out.push("</text:list-item></text:list>");
|
|
684
|
+
depth--;
|
|
685
|
+
}
|
|
686
|
+
if (depth === lvl + 1)
|
|
687
|
+
out.push("</text:list-item><text:list-item>");
|
|
688
|
+
while (depth < lvl + 1) {
|
|
689
|
+
out.push("<text:list><text:list-item>");
|
|
690
|
+
depth++;
|
|
691
|
+
}
|
|
692
|
+
out.push(`<text:p>${runsXml(txt)}</text:p>`);
|
|
693
|
+
}
|
|
694
|
+
while (depth-- > 0)
|
|
695
|
+
out.push("</text:list-item></text:list>");
|
|
696
|
+
return out.join("");
|
|
697
|
+
}
|
|
698
|
+
tableXml(header, rows, x, y, width, pt, small = false, cols) {
|
|
699
|
+
cols ??= tableCols(header, rows, width);
|
|
700
|
+
const prefix = small ? "Tableau-petit" : "Tableau";
|
|
701
|
+
const parts = [
|
|
702
|
+
`<draw:frame draw:style-name="Tableau-cadre" ${Builder.geom(x, y, width, tableH(header, rows, width, pt, cols))}>`,
|
|
703
|
+
`<table:table table:template-name="${prefix}" table:use-first-row-styles="${header ? "true" : "false"}" table:use-banding-rows-styles="true">`,
|
|
704
|
+
...cols.map(cw => `<table:table-column table:style-name="${this.colStyle(cw)}"/>`),
|
|
705
|
+
];
|
|
706
|
+
const all = [
|
|
707
|
+
...(header ? [["entete", header]] : []),
|
|
708
|
+
...rows.map((r, i) => [i % 2 === 0 ? "cellule" : "cellule-alt", r]),
|
|
709
|
+
];
|
|
710
|
+
for (const [kind, r] of all) {
|
|
711
|
+
parts.push(`<table:table-row table:style-name="${this.rowStyle(rowH(r, cols, pt))}">`);
|
|
712
|
+
cols.forEach((_, i) => {
|
|
713
|
+
parts.push(`<table:table-cell table:style-name="${prefix}-${kind}"><text:p>${runsXml(r[i] ?? "")}</text:p></table:table-cell>`);
|
|
714
|
+
});
|
|
715
|
+
parts.push("</table:table-row>");
|
|
716
|
+
}
|
|
717
|
+
parts.push("</table:table></draw:frame>");
|
|
718
|
+
return parts.join("");
|
|
719
|
+
}
|
|
720
|
+
imageXml(src, x, y, w, h) {
|
|
721
|
+
if (extname(src).toLowerCase() === ".dot")
|
|
722
|
+
return this.graphXml(resolve(this.base, src), x, y, w, h);
|
|
723
|
+
const { href } = this.picture(src);
|
|
724
|
+
const mime = href.endsWith(".svg") ? ' draw:mime-type="image/svg+xml"' : "";
|
|
725
|
+
return (`<draw:frame draw:style-name="Image" ${Builder.geom(x, y, w, h)}>` +
|
|
726
|
+
`<draw:image xlink:href="${esc(href)}" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"${mime}/>` +
|
|
727
|
+
`</draw:frame>`);
|
|
728
|
+
}
|
|
729
|
+
/** Automatic style deriving from a named style, for colors set in a .dot file. */
|
|
730
|
+
autoStyle(parent, graphic) {
|
|
731
|
+
if (!Object.keys(graphic).length)
|
|
732
|
+
return parent;
|
|
733
|
+
const key = JSON.stringify([parent, graphic]);
|
|
734
|
+
let entry = this.autoStyles.get(key);
|
|
735
|
+
if (!entry) {
|
|
736
|
+
entry = { name: `gr${this.autoStyles.size + 1}`, parent, graphic };
|
|
737
|
+
this.autoStyles.set(key, entry);
|
|
738
|
+
}
|
|
739
|
+
return entry.name;
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* A paragraph with text properties of its own. LibreOffice ignores text
|
|
743
|
+
* properties in automatic graphic styles, so they go on the paragraph.
|
|
744
|
+
*/
|
|
745
|
+
para(text, props) {
|
|
746
|
+
if (!text)
|
|
747
|
+
return "";
|
|
748
|
+
const key = JSON.stringify(props);
|
|
749
|
+
let entry = this.paraStyles.get(key);
|
|
750
|
+
if (!entry) {
|
|
751
|
+
entry = { name: `Pg${this.paraStyles.size + 1}`, text: props };
|
|
752
|
+
this.paraStyles.set(key, entry);
|
|
753
|
+
}
|
|
754
|
+
return `<text:p text:style-name="${entry.name}">${xmlText(text)}</text:p>`;
|
|
755
|
+
}
|
|
756
|
+
/** A Graphviz diagram as a group of native shapes linked by connectors. */
|
|
757
|
+
graphXml(path, x, y, w, h) {
|
|
758
|
+
const g = graphLayout(path);
|
|
759
|
+
// Do not blow small diagrams up: text keeps its size, shapes would not.
|
|
760
|
+
const maxScale = style.theme.graph.maxScale;
|
|
761
|
+
if (w > g.size[0] * maxScale) {
|
|
762
|
+
const [fw, fh] = fit(g.size[0], g.size[1], g.size[0] * maxScale, g.size[1] * maxScale);
|
|
763
|
+
x += (w - fw) / 2;
|
|
764
|
+
y += (h - fh) / 2;
|
|
765
|
+
w = fw;
|
|
766
|
+
h = fh;
|
|
767
|
+
}
|
|
768
|
+
const scale = (w / g.size[0]) * CM_PER_POINT;
|
|
769
|
+
// Text follows the diagram scale, starting from the font sizes of the .dot file.
|
|
770
|
+
const textProps = (fontsize, fallback, color) => {
|
|
771
|
+
const pt = Math.max(4, Math.round(Number(fontsize ?? fallback) * (scale / CM_PER_POINT) * 2) / 2);
|
|
772
|
+
const c = gvColor(color);
|
|
773
|
+
return { "fo:font-size": `${pt}pt`, ...(c ? { "fo:color": c } : {}) };
|
|
774
|
+
};
|
|
775
|
+
const [bx0, , , by1] = g.bb;
|
|
776
|
+
const px = (p) => x + (p - bx0) * scale;
|
|
777
|
+
const py = (p) => y + (by1 - p) * scale;
|
|
778
|
+
const id = (gvid) => `g${this.graphCount}n${gvid}`;
|
|
779
|
+
this.graphCount++;
|
|
780
|
+
const out = [`<draw:g>`];
|
|
781
|
+
const title = gvLabel(g.attrs.label ?? "", g.name, g.name);
|
|
782
|
+
if (title && typeof g.attrs.lp === "string") {
|
|
783
|
+
const [lx, ly] = gvPoint(g.attrs.lp);
|
|
784
|
+
const lw = Number(g.attrs.lwidth ?? 1) * 72 * scale + 0.4;
|
|
785
|
+
const lh = Number(g.attrs.lheight ?? 0.3) * 72 * scale + 0.2;
|
|
786
|
+
const text = this.para(title, textProps(g.attrs.fontsize, sizes.graphEdgeText, g.attrs.fontcolor));
|
|
787
|
+
out.push(this.frame("Graphe-titre", px(lx) - lw / 2, py(ly) - lh / 2, lw, lh, text));
|
|
788
|
+
}
|
|
789
|
+
// Clusters first, so they stay behind the nodes.
|
|
790
|
+
for (const o of g.objects) {
|
|
791
|
+
if (typeof o.bb !== "string" || !o.name.startsWith("cluster"))
|
|
792
|
+
continue;
|
|
793
|
+
const [x0, y0, x1, y1] = o.bb.split(",").map(Number);
|
|
794
|
+
const fill = gvColor(o.fillcolor) ?? (String(o.style ?? "").includes("filled") ? gvColor(o.color) : null);
|
|
795
|
+
const stroke = gvColor(o.pencolor) ?? gvColor(o.color);
|
|
796
|
+
const st = this.autoStyle("Graphe-groupe", { ...(fill ? { "draw:fill-color": fill } : {}), ...(stroke ? { "svg:stroke-color": stroke } : {}), ...dashed(o.style) });
|
|
797
|
+
const label = gvLabel(o.label ?? "", o.name, g.name);
|
|
798
|
+
out.push(`<draw:rect draw:style-name="${st}" ${Builder.geom(px(x0), py(y1), (x1 - x0) * scale, (y1 - y0) * scale)}>` +
|
|
799
|
+
this.para(label, textProps(o.fontsize, sizes.graphEdgeText, o.fontcolor)) +
|
|
800
|
+
`</draw:rect>`);
|
|
801
|
+
}
|
|
802
|
+
for (const o of g.objects) {
|
|
803
|
+
if (typeof o.pos !== "string")
|
|
804
|
+
continue;
|
|
805
|
+
const [cx, cy] = gvPoint(o.pos);
|
|
806
|
+
const nw = Number(o.width ?? 0.75) * 72 * scale;
|
|
807
|
+
const nh = Number(o.height ?? 0.5) * 72 * scale;
|
|
808
|
+
const shape = String(o.shape ?? "ellipse");
|
|
809
|
+
const styles = String(o.style ?? "");
|
|
810
|
+
const plain = ["plaintext", "plain", "none", "underline"].includes(shape) || styles.includes("invis");
|
|
811
|
+
let geometry = NODE_SHAPES[shape] ?? "rectangle";
|
|
812
|
+
if (geometry === "rectangle" && styles.includes("rounded"))
|
|
813
|
+
geometry = "round-rectangle";
|
|
814
|
+
const fill = styles.includes("filled") ? (gvColor(o.fillcolor) ?? gvColor(o.color)) : null;
|
|
815
|
+
const stroke = gvColor(o.color);
|
|
816
|
+
const st = this.autoStyle(plain ? "Graphe-texte" : "Graphe-noeud", { ...(fill ? { "draw:fill-color": fill } : {}), ...(stroke && !plain ? { "svg:stroke-color": stroke } : {}), ...(plain ? {} : dashed(o.style)) });
|
|
817
|
+
const label = shape === "point" ? "" : gvLabel(o.label, o.name, g.name, shape.endsWith("record"));
|
|
818
|
+
const nid = id(o._gvid);
|
|
819
|
+
out.push(`<draw:custom-shape draw:style-name="${st}" draw:id="${nid}" xml:id="${nid}" ${Builder.geom(px(cx) - nw / 2, py(cy) - nh / 2, nw, nh)}>` +
|
|
820
|
+
this.para(label, textProps(o.fontsize, sizes.graphText, o.fontcolor)) +
|
|
821
|
+
`<draw:enhanced-geometry svg:viewBox="0 0 21600 21600" draw:type="${geometry}"/>` +
|
|
822
|
+
`</draw:custom-shape>`);
|
|
823
|
+
}
|
|
824
|
+
const kind = style.theme.graph.connector;
|
|
825
|
+
for (const e of g.edges) {
|
|
826
|
+
const tokens = String(e.pos ?? "").split(/\s+/).filter(Boolean);
|
|
827
|
+
const points = tokens.filter(t => !/^[se],/.test(t)).map(gvPoint);
|
|
828
|
+
const startTip = tokens.find(t => t.startsWith("s,"));
|
|
829
|
+
const endTip = tokens.find(t => t.startsWith("e,"));
|
|
830
|
+
let start = startTip ? gvPoint(startTip.slice(2)) : (points[0] ?? [0, 0]);
|
|
831
|
+
let end = endTip ? gvPoint(endTip.slice(2)) : (points[points.length - 1] ?? [0, 0]);
|
|
832
|
+
let [tail, head] = [e.tail, e.head];
|
|
833
|
+
const dir = String(e.dir ?? (g.directed ? "forward" : "none"));
|
|
834
|
+
if (dir === "back") {
|
|
835
|
+
;
|
|
836
|
+
[tail, head] = [head, tail];
|
|
837
|
+
[start, end] = [end, start];
|
|
838
|
+
}
|
|
839
|
+
const parent = dir === "none" ? "Graphe-lien-simple" : dir === "both" ? "Graphe-lien-double" : "Graphe-lien";
|
|
840
|
+
const stroke = gvColor(e.color);
|
|
841
|
+
const st = this.autoStyle(parent, { ...(stroke ? { "svg:stroke-color": stroke } : {}), ...dashed(e.style) });
|
|
842
|
+
const label = gvLabel(e.label ?? "", "", g.name);
|
|
843
|
+
out.push(`<draw:connector draw:style-name="${st}" draw:type="${esc(kind)}" ` +
|
|
844
|
+
`svg:x1="${f2(px(start[0]))}cm" svg:y1="${f2(py(start[1]))}cm" svg:x2="${f2(px(end[0]))}cm" svg:y2="${f2(py(end[1]))}cm" ` +
|
|
845
|
+
`draw:start-shape="${id(tail)}" draw:end-shape="${id(head)}">` +
|
|
846
|
+
this.para(label, textProps(e.fontsize, sizes.graphEdgeText, e.fontcolor)) +
|
|
847
|
+
`</draw:connector>`);
|
|
848
|
+
}
|
|
849
|
+
out.push("</draw:g>");
|
|
850
|
+
return out.join("");
|
|
851
|
+
}
|
|
852
|
+
promptXml(lines, x, y, w, h, style = "Prompt") {
|
|
853
|
+
const paras = lines.map(l => `<text:p>${xmlText(l)}</text:p>`).join("");
|
|
854
|
+
return (`<draw:custom-shape draw:style-name="${style}" ${Builder.geom(x, y, w, h)}>${paras}` +
|
|
855
|
+
`<draw:enhanced-geometry svg:viewBox="0 0 21600 21600" draw:type="round-rectangle" draw:modifiers="1800"/>` +
|
|
856
|
+
`</draw:custom-shape>`);
|
|
857
|
+
}
|
|
858
|
+
blockXml(b, x, y, w, h) {
|
|
859
|
+
switch (b.t) {
|
|
860
|
+
case "para":
|
|
861
|
+
return this.frame("Texte", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
|
|
862
|
+
case "list":
|
|
863
|
+
return this.frame("Greta-outline1", x, y, w, h, this.listXml(b.items), "outline");
|
|
864
|
+
case "quote":
|
|
865
|
+
return this.frame("Citation", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
|
|
866
|
+
case "prompt":
|
|
867
|
+
case "code": {
|
|
868
|
+
const [pw] = promptSize(b.lines, w);
|
|
869
|
+
return this.promptXml(b.lines, x + w - pw, y, pw, h, b.t === "prompt" ? "Prompt" : "Code");
|
|
870
|
+
}
|
|
871
|
+
case "table": {
|
|
872
|
+
const tw = Math.min(w, tableCols(b.header, b.rows, w).reduce((a, c) => a + c, 0));
|
|
873
|
+
return this.tableXml(b.header, b.rows, x, y, tw, sizes.table);
|
|
874
|
+
}
|
|
875
|
+
default:
|
|
876
|
+
throw new Error(`Unexpected block ${b.t}`);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
// -- slide-level layout
|
|
880
|
+
/** Return the required height and the shapes for the content blocks of one slide. */
|
|
881
|
+
layout(blocks) {
|
|
882
|
+
const imgs = blocks.filter(b => b.t === "image");
|
|
883
|
+
const texts = blocks.filter(b => b.t !== "image");
|
|
884
|
+
const shapes = [];
|
|
885
|
+
const stack = (bs, x, width) => {
|
|
886
|
+
let y = Y0;
|
|
887
|
+
for (const b of bs) {
|
|
888
|
+
const bh = blockH(b, width);
|
|
889
|
+
shapes.push(this.blockXml(b, x, y, width, Math.min(bh, Math.max(Y0 + H - y, 1.5))));
|
|
890
|
+
y += bh + GAP;
|
|
891
|
+
}
|
|
892
|
+
return y - Y0 - (bs.length ? GAP : 0);
|
|
893
|
+
};
|
|
894
|
+
const sumH = (width) => texts.reduce((h, b) => h + blockH(b, width), 0) + GAP * (texts.length - 1);
|
|
895
|
+
if (!imgs.length)
|
|
896
|
+
return [stack(texts, X0, W), shapes];
|
|
897
|
+
const src = imgs[0].src;
|
|
898
|
+
const [iw, ih] = imageSize(resolve(this.base, src));
|
|
899
|
+
if (!texts.length) {
|
|
900
|
+
const [w, h] = fit(iw, ih, W, H);
|
|
901
|
+
shapes.push(this.imageXml(src, X0 + (W - w) / 2, Y0 + (H - h) / 2, w, h));
|
|
902
|
+
return [0, shapes];
|
|
903
|
+
}
|
|
904
|
+
if (iw / ih >= 1.8 || (iw / ih >= 1.2 && sumH(W) < 2.5)) {
|
|
905
|
+
const th = stack(texts, X0, W);
|
|
906
|
+
const avail = Math.max(H - th - GAP, 4.5);
|
|
907
|
+
const [w, h] = fit(iw, ih, W, avail);
|
|
908
|
+
shapes.push(this.imageXml(src, X0 + (W - w) / 2, Y0 + th + GAP + (avail - h) / 2, w, h));
|
|
909
|
+
return [th + GAP + 4.5, shapes];
|
|
910
|
+
}
|
|
911
|
+
// Give the image more room when the text is short.
|
|
912
|
+
const tw = W * (sumH(W * 0.42) < H * 0.6 ? 0.42 : 0.58);
|
|
913
|
+
const th = stack(texts, X0, tw);
|
|
914
|
+
const bw = W - tw - 0.8;
|
|
915
|
+
const [w, h] = fit(iw, ih, bw, H);
|
|
916
|
+
shapes.push(this.imageXml(src, X0 + tw + 0.8 + (bw - w) / 2, Y0 + (H - h) / 2, w, h));
|
|
917
|
+
return [th, shapes];
|
|
918
|
+
}
|
|
919
|
+
/** Split blocks into slides: list of [content blocks, notes]. */
|
|
920
|
+
paginate(blocks) {
|
|
921
|
+
const slides = [[[], []]];
|
|
922
|
+
for (const b of blocks) {
|
|
923
|
+
if (b.t === "note") {
|
|
924
|
+
slides[slides.length - 1][1].push(b.text);
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
const cur = slides[slides.length - 1][0];
|
|
928
|
+
const hasImg = cur.some(x => x.t === "image");
|
|
929
|
+
if (cur.length && ((b.t === "image" && hasImg) || this.layout([...cur, b])[0] > H)) {
|
|
930
|
+
// Keep an introductory paragraph with what follows it.
|
|
931
|
+
const carry = cur.length > 1 && cur[cur.length - 1].t === "para" ? [cur.pop()] : [];
|
|
932
|
+
slides.push([[...carry, b], []]);
|
|
933
|
+
}
|
|
934
|
+
else {
|
|
935
|
+
cur.push(b);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
return slides.filter(([c, n]) => c.length || n.length);
|
|
939
|
+
}
|
|
940
|
+
// -- pages
|
|
941
|
+
page(master, shapes, notes = []) {
|
|
942
|
+
this.pages.push({ master, shapes, notes });
|
|
943
|
+
}
|
|
944
|
+
titleShapes(title, crumbs) {
|
|
945
|
+
const out = [];
|
|
946
|
+
if (crumbs.length)
|
|
947
|
+
out.push(this.frame("Fil-ariane", X0, 0.35, W, 0.6, `<text:p>${xmlText(crumbs.join(" › "))}</text:p>`));
|
|
948
|
+
out.push(this.frame("Greta-title", X0, 0.95, W, 1.6, `<text:p>${xmlText(title)}</text:p>`, "title", this.takeHints()));
|
|
949
|
+
return out;
|
|
950
|
+
}
|
|
951
|
+
sectionPage(sec) {
|
|
952
|
+
const crumbs = sec.path().slice(0, -1);
|
|
953
|
+
const shapes = [this.frame("Section-title", 2, 5, 24, 3.5, `<text:p>${xmlText(sec.title)}</text:p>`, "title", this.takeHints())];
|
|
954
|
+
if (crumbs.length)
|
|
955
|
+
shapes.push(this.frame("Section-subtitle", 2, 8.8, 24, 1.5, `<text:p>${xmlText(crumbs.join(" › "))}</text:p>`, "subtitle"));
|
|
956
|
+
const notes = sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : []));
|
|
957
|
+
this.page("Section", shapes, notes);
|
|
958
|
+
}
|
|
959
|
+
contentPages(title, crumbs, blocks) {
|
|
960
|
+
for (const [content, notes] of this.paginate(blocks)) {
|
|
961
|
+
const [, shapes] = this.layout(content);
|
|
962
|
+
this.page("Greta", [...this.titleShapes(title, crumbs), ...shapes], notes);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
/** A table whose rows appear one slide after the other. */
|
|
966
|
+
revealTable(sec, crumbs) {
|
|
967
|
+
const table = sec.blocks.find(b => b.t === "table");
|
|
968
|
+
if (!table || table.t !== "table")
|
|
969
|
+
return this.contentPages(sec.title, crumbs, sec.blocks);
|
|
970
|
+
const header = (table.header ?? []).map(stripMd);
|
|
971
|
+
const rows = table.rows;
|
|
972
|
+
const ncol = Math.max(header.length, ...rows.map(r => r.length));
|
|
973
|
+
const hasLogos = rows.some(r => /<img\s/.test(r[0] ?? ""));
|
|
974
|
+
const widths = tableCols(header, rows.map(r => (hasLogos ? ["Logo", ...r.slice(1)] : r)), Math.min(W, 4.5 * ncol));
|
|
975
|
+
const tw = widths.reduce((a, b) => a + b, 0);
|
|
976
|
+
const x = X0 + (W - tw) / 2;
|
|
977
|
+
const rh = 1.3;
|
|
978
|
+
const hh = 1.1;
|
|
979
|
+
for (let k = 0; k <= rows.length; k++) {
|
|
980
|
+
const parts = [
|
|
981
|
+
`<draw:frame draw:style-name="Tableau-cadre" ${Builder.geom(x, Y0, tw, hh + rh * rows.length)}>`,
|
|
982
|
+
'<table:table table:template-name="Tableau" table:use-first-row-styles="true" table:use-banding-rows-styles="true">',
|
|
983
|
+
...widths.map(cw => `<table:table-column table:style-name="${this.colStyle(cw)}"/>`),
|
|
984
|
+
`<table:table-row table:style-name="${this.rowStyle(hh)}">`,
|
|
985
|
+
...widths.map((_, c) => `<table:table-cell table:style-name="Tableau-entete"><text:p>${xmlText(header[c] ?? "")}</text:p></table:table-cell>`),
|
|
986
|
+
"</table:table-row>",
|
|
987
|
+
];
|
|
988
|
+
rows.forEach((r, i) => {
|
|
989
|
+
const st = i % 2 === 0 ? "Tableau-cellule" : "Tableau-cellule-alt";
|
|
990
|
+
parts.push(`<table:table-row table:style-name="${this.rowStyle(rh)}">`);
|
|
991
|
+
widths.forEach((_, c) => {
|
|
992
|
+
const cell = i < k && !(hasLogos && c === 0) ? (r[c] ?? "") : "";
|
|
993
|
+
parts.push(`<table:table-cell table:style-name="${st}"><text:p>${runsXml(cell)}</text:p></table:table-cell>`);
|
|
994
|
+
});
|
|
995
|
+
parts.push("</table:table-row>");
|
|
996
|
+
});
|
|
997
|
+
parts.push("</table:table></draw:frame>");
|
|
998
|
+
const shapes = [parts.join("")];
|
|
999
|
+
for (let i = 0; i < k; i++) {
|
|
1000
|
+
const m = (rows[i][0] ?? "").match(/src="([^"]+)"/);
|
|
1001
|
+
if (m) {
|
|
1002
|
+
const s = 1.0;
|
|
1003
|
+
shapes.push(this.imageXml(m[1], x + (widths[0] - s) / 2, Y0 + hh + rh * i + (rh - s) / 2, s, s));
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
const notes = k === 0 ? sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : [])) : [];
|
|
1007
|
+
this.page("Greta", [...this.titleShapes(sec.title, crumbs), ...shapes], notes);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
/** Height of a group of paragraphs/lists rendered at `pt` points. */
|
|
1011
|
+
static textGroupH(blocks, width, pt) {
|
|
1012
|
+
let h = 0.4;
|
|
1013
|
+
for (const b of blocks) {
|
|
1014
|
+
if (b.t === "para" || b.t === "quote")
|
|
1015
|
+
h += b.text.split("\n").reduce((a, p) => a + textH(plainLen(p), width - 0.6, pt), 0) + 0.15;
|
|
1016
|
+
else if (b.t === "list")
|
|
1017
|
+
for (const [lvl, txt] of b.items)
|
|
1018
|
+
h += textH(plainLen(txt), width - 0.6 - 0.9 * (lvl + 1), pt) + 0.12;
|
|
1019
|
+
}
|
|
1020
|
+
return h;
|
|
1021
|
+
}
|
|
1022
|
+
/** Preferred width of a cell content, used by `auto` columns. */
|
|
1023
|
+
static preferredWidth(sec, height, textPt) {
|
|
1024
|
+
const cw = (pt) => pt * PT * 0.5;
|
|
1025
|
+
let w = sec.title.length * cw(sizes.gridTitle) + 0.8;
|
|
1026
|
+
for (const b of sec.blocks) {
|
|
1027
|
+
if (b.t === "para" || b.t === "quote")
|
|
1028
|
+
w = Math.max(w, plainLen(b.text) * cw(textPt) + 0.8);
|
|
1029
|
+
else if (b.t === "list")
|
|
1030
|
+
w = Math.max(w, ...b.items.map(([lvl, txt]) => plainLen(txt) * cw(textPt) + 0.9 * (lvl + 1) + 0.8));
|
|
1031
|
+
else if (b.t === "table") {
|
|
1032
|
+
const all = b.header ? [b.header, ...b.rows] : b.rows;
|
|
1033
|
+
const ncol = Math.max(...all.map(r => r.length));
|
|
1034
|
+
let tw = 0;
|
|
1035
|
+
for (let c = 0; c < ncol; c++)
|
|
1036
|
+
tw += Math.max(...all.map(r => Math.min(plainLen(r[c] ?? ""), 30))) * cw(sizes.tableSmall) + 0.6;
|
|
1037
|
+
w = Math.max(w, tw);
|
|
1038
|
+
}
|
|
1039
|
+
else if (b.t === "image") {
|
|
1040
|
+
const [iw, ih] = imageSize(resolve(sec.source, b.src));
|
|
1041
|
+
w = Math.max(w, (iw / ih) * (height - 0.9));
|
|
1042
|
+
}
|
|
1043
|
+
else if (b.t === "prompt" || b.t === "code")
|
|
1044
|
+
w = Math.max(w, promptSize(b.lines, W)[0]);
|
|
1045
|
+
}
|
|
1046
|
+
return w;
|
|
1047
|
+
}
|
|
1048
|
+
/** Content of a section inside a cell of a grouped slide. */
|
|
1049
|
+
cellXml(sec, x, y, w, h, textStyle, textPt) {
|
|
1050
|
+
const items = [];
|
|
1051
|
+
for (const b of sec.blocks) {
|
|
1052
|
+
if (b.t === "note")
|
|
1053
|
+
continue;
|
|
1054
|
+
const last = items[items.length - 1];
|
|
1055
|
+
if (b.t === "para" || b.t === "list" || b.t === "quote") {
|
|
1056
|
+
if (last?.kind === "text")
|
|
1057
|
+
last.blocks.push(b);
|
|
1058
|
+
else
|
|
1059
|
+
items.push({ kind: "text", blocks: [b] });
|
|
1060
|
+
}
|
|
1061
|
+
else
|
|
1062
|
+
items.push({ kind: "block", block: b });
|
|
1063
|
+
}
|
|
1064
|
+
const gap = 0.2;
|
|
1065
|
+
const natural = items.map(it => {
|
|
1066
|
+
if (it.kind === "text")
|
|
1067
|
+
return Builder.textGroupH(it.blocks, w, textPt);
|
|
1068
|
+
const b = it.block;
|
|
1069
|
+
if (b.t === "table")
|
|
1070
|
+
return tableH(b.header, b.rows, w, sizes.tableSmall);
|
|
1071
|
+
if (b.t === "prompt" || b.t === "code")
|
|
1072
|
+
return promptSize(b.lines, w)[1];
|
|
1073
|
+
return 0;
|
|
1074
|
+
});
|
|
1075
|
+
const flexible = items.map(it => it.kind === "text" || (it.kind === "block" && it.block.t === "image"));
|
|
1076
|
+
const fixedH = natural.reduce((a, n, i) => a + (flexible[i] ? 0 : n), 0) + gap * Math.max(0, items.length - 1);
|
|
1077
|
+
const rem = Math.max(h - fixedH, 1.5);
|
|
1078
|
+
const heights = [...natural];
|
|
1079
|
+
const images = items.filter(it => it.kind === "block" && it.block.t === "image").length;
|
|
1080
|
+
const textTotal = natural.reduce((a, n, i) => a + (flexible[i] ? n : 0), 0);
|
|
1081
|
+
if (images) {
|
|
1082
|
+
const left = Math.max(rem - textTotal, 2 * images);
|
|
1083
|
+
items.forEach((it, i) => {
|
|
1084
|
+
if (it.kind === "block" && it.block.t === "image")
|
|
1085
|
+
heights[i] = left / images;
|
|
1086
|
+
else if (it.kind === "text")
|
|
1087
|
+
heights[i] = Math.min(natural[i], (natural[i] / Math.max(textTotal, 0.01)) * (rem - left));
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
else if (textTotal > rem) {
|
|
1091
|
+
items.forEach((it, i) => {
|
|
1092
|
+
if (it.kind === "text")
|
|
1093
|
+
heights[i] = (natural[i] / textTotal) * rem;
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
1096
|
+
else if (items[items.length - 1]?.kind === "text") {
|
|
1097
|
+
// A text frame ending the cell takes the free space, so its background fills the cell.
|
|
1098
|
+
heights[items.length - 1] += rem - textTotal;
|
|
1099
|
+
}
|
|
1100
|
+
const shapes = [];
|
|
1101
|
+
let cy = y;
|
|
1102
|
+
items.forEach((it, i) => {
|
|
1103
|
+
const ih = Math.max(0.5, Math.min(heights[i], y + h - cy));
|
|
1104
|
+
if (it.kind === "text") {
|
|
1105
|
+
const inner = it.blocks
|
|
1106
|
+
.map(b => (b.t === "list" ? this.listXml(b.items) : b.t === "para" || b.t === "quote" ? `<text:p>${runsXml(b.text)}</text:p>` : ""))
|
|
1107
|
+
.join("");
|
|
1108
|
+
shapes.push(this.frame(textStyle, x, cy, w, ih, inner));
|
|
1109
|
+
}
|
|
1110
|
+
else {
|
|
1111
|
+
const b = it.block;
|
|
1112
|
+
if (b.t === "table") {
|
|
1113
|
+
const header = b.header?.map(stripMd) ?? null;
|
|
1114
|
+
shapes.push(this.tableXml(header, b.rows, x, cy, w, sizes.tableSmall, true));
|
|
1115
|
+
}
|
|
1116
|
+
else if (b.t === "image") {
|
|
1117
|
+
const [iw, ihh] = imageSize(resolve(sec.source, b.src));
|
|
1118
|
+
const [fw, fh] = fit(iw, ihh, w, ih);
|
|
1119
|
+
shapes.push(this.imageXml(b.src, x + (w - fw) / 2, cy + (ih - fh) / 2, fw, fh));
|
|
1120
|
+
}
|
|
1121
|
+
else if (b.t === "prompt" || b.t === "code") {
|
|
1122
|
+
const [pw] = promptSize(b.lines, w);
|
|
1123
|
+
shapes.push(this.promptXml(b.lines, x + w - pw, cy, pw, ih, b.t === "prompt" ? "Prompt" : "Code"));
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
cy += heights[i] + gap;
|
|
1127
|
+
});
|
|
1128
|
+
return shapes;
|
|
1129
|
+
}
|
|
1130
|
+
/** Sections laid out on a single slide, following an `@layout` pragma. */
|
|
1131
|
+
layoutPage(parent, group, layout, notes) {
|
|
1132
|
+
const title = parent.level > 0 ? parent.title : group[0].title;
|
|
1133
|
+
const shapes = this.titleShapes(title, parent.path().slice(0, -1));
|
|
1134
|
+
const headH = 0.9;
|
|
1135
|
+
let cells;
|
|
1136
|
+
if (layout.kind === "grid") {
|
|
1137
|
+
const gx = 0.5;
|
|
1138
|
+
const gy = 0.4;
|
|
1139
|
+
const cw = (W - gx * (layout.columns - 1)) / layout.columns;
|
|
1140
|
+
const ch = (H - gy * (layout.rows - 1)) / layout.rows;
|
|
1141
|
+
cells = group.map((_, n) => ({
|
|
1142
|
+
x: X0 + (n % layout.columns) * (cw + gx),
|
|
1143
|
+
y: Y0 + Math.floor(n / layout.columns) * (ch + gy),
|
|
1144
|
+
w: cw,
|
|
1145
|
+
h: ch,
|
|
1146
|
+
}));
|
|
1147
|
+
}
|
|
1148
|
+
else {
|
|
1149
|
+
const gx = 0.4;
|
|
1150
|
+
const free = W - gx * (layout.widths.length - 1);
|
|
1151
|
+
const widths = layout.widths.map((spec, i) => spec === "auto" && group[i] ? Builder.preferredWidth(group[i], H, sizes.columnText) : 0);
|
|
1152
|
+
// Auto columns get their preferred width, but leave room for the fractions.
|
|
1153
|
+
const fractions = layout.widths.reduce((a, s) => a + (s === "auto" ? 0 : s), 0);
|
|
1154
|
+
const autoTotal = widths.reduce((a, b) => a + b, 0);
|
|
1155
|
+
const maxAuto = fractions ? free * 0.5 : free;
|
|
1156
|
+
const scale = autoTotal > maxAuto ? maxAuto / autoTotal : 1;
|
|
1157
|
+
const rest = free - autoTotal * scale;
|
|
1158
|
+
layout.widths.forEach((spec, i) => {
|
|
1159
|
+
widths[i] = spec === "auto" ? widths[i] * scale : (rest * spec) / fractions;
|
|
1160
|
+
});
|
|
1161
|
+
if (!fractions && autoTotal < free) {
|
|
1162
|
+
const extra = (free - autoTotal) / widths.length;
|
|
1163
|
+
widths.forEach((_, i) => (widths[i] += extra));
|
|
1164
|
+
}
|
|
1165
|
+
let x = X0;
|
|
1166
|
+
cells = widths.map(w => {
|
|
1167
|
+
const cell = { x, y: Y0, w, h: H };
|
|
1168
|
+
x += w + gx;
|
|
1169
|
+
return cell;
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
const colors = style.theme.colors.grid.length;
|
|
1173
|
+
group.forEach((sec, n) => {
|
|
1174
|
+
const { x, y, w, h } = cells[n];
|
|
1175
|
+
const [headStyle, textStyle, textPt] = layout.kind === "grid"
|
|
1176
|
+
? [`Grille-titre-${(n % colors) + 1}`, `Grille-texte-${(n % colors) + 1}`, sizes.gridText]
|
|
1177
|
+
: ["Colonne-titre", "Colonne-texte", sizes.columnText];
|
|
1178
|
+
shapes.push(this.frame(headStyle, x, y, w, headH, `<text:p>${xmlText(sec.title)}</text:p>`));
|
|
1179
|
+
shapes.push(...this.cellXml(sec, x, y + headH, w, h - headH, textStyle, textPt));
|
|
1180
|
+
notes.push(...sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : [])));
|
|
1181
|
+
});
|
|
1182
|
+
this.page("Greta", shapes, notes);
|
|
1183
|
+
}
|
|
1184
|
+
walk(sec) {
|
|
1185
|
+
this.pendingHints.push(...sec.hints);
|
|
1186
|
+
const crumbs = sec.path().slice(0, -1);
|
|
1187
|
+
const content = sec.blocks.filter(b => b.t !== "note");
|
|
1188
|
+
// A section whose only content is a grouped slide does not get its own divider slide.
|
|
1189
|
+
const groupedOnly = !content.length && sec.children[0]?.layout != null;
|
|
1190
|
+
if (sec.level === 1) {
|
|
1191
|
+
this.sectionPage(sec);
|
|
1192
|
+
if (content.length)
|
|
1193
|
+
this.contentPages(sec.title, [...crumbs, sec.title], sec.blocks);
|
|
1194
|
+
}
|
|
1195
|
+
else if (sec.hints.some(h => h.includes("revealed line by line"))) {
|
|
1196
|
+
this.revealTable(sec, crumbs);
|
|
1197
|
+
}
|
|
1198
|
+
else if (content.length) {
|
|
1199
|
+
this.contentPages(sec.title, crumbs, sec.blocks);
|
|
1200
|
+
}
|
|
1201
|
+
else if (sec.children.length && !groupedOnly) {
|
|
1202
|
+
this.sectionPage(sec);
|
|
1203
|
+
}
|
|
1204
|
+
const notes = groupedOnly && sec.level > 1 ? sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : [])) : [];
|
|
1205
|
+
this.walkChildren(sec, notes);
|
|
1206
|
+
}
|
|
1207
|
+
walkChildren(sec, notes = []) {
|
|
1208
|
+
const children = sec.children;
|
|
1209
|
+
for (let i = 0; i < children.length; i++) {
|
|
1210
|
+
const layout = children[i].layout;
|
|
1211
|
+
if (!layout) {
|
|
1212
|
+
this.walk(children[i]);
|
|
1213
|
+
continue;
|
|
1214
|
+
}
|
|
1215
|
+
const group = children.slice(i, i + cellCount(layout));
|
|
1216
|
+
for (const g of group)
|
|
1217
|
+
this.pendingHints.push(...g.hints);
|
|
1218
|
+
this.layoutPage(sec, group, layout, i === 0 ? notes : []);
|
|
1219
|
+
// Sub-sections of grouped sections still get their own slides.
|
|
1220
|
+
for (const g of group)
|
|
1221
|
+
this.walkChildren(g);
|
|
1222
|
+
i += group.length - 1;
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
// ---------------------------------------------------------------- XML documents
|
|
1227
|
+
const NS = [
|
|
1228
|
+
'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"',
|
|
1229
|
+
'xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"',
|
|
1230
|
+
'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"',
|
|
1231
|
+
'xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"',
|
|
1232
|
+
'xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"',
|
|
1233
|
+
'xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"',
|
|
1234
|
+
'xmlns:xlink="http://www.w3.org/1999/xlink"',
|
|
1235
|
+
'xmlns:dc="http://purl.org/dc/elements/1.1/"',
|
|
1236
|
+
'xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0"',
|
|
1237
|
+
'xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"',
|
|
1238
|
+
'xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"',
|
|
1239
|
+
'xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0"',
|
|
1240
|
+
'office:version="1.3"',
|
|
1241
|
+
].join(" ");
|
|
1242
|
+
function attrs(props = {}, where = "") {
|
|
1243
|
+
return Object.entries(props)
|
|
1244
|
+
.map(([k, v]) => `${k}="${esc(resolveValue(String(v), where))}"`)
|
|
1245
|
+
.join(" ");
|
|
1246
|
+
}
|
|
1247
|
+
function bulletsXml(def, name) {
|
|
1248
|
+
const color = esc(resolveValue(def.color, `bullets of style "${name}"`));
|
|
1249
|
+
const size = esc(resolveValue(def.size, `bullets of style "${name}"`));
|
|
1250
|
+
const levels = def.chars.map((char, i) => `<text:list-level-style-bullet text:level="${i + 1}" text:bullet-char="${esc(char)}">` +
|
|
1251
|
+
`<style:list-level-properties text:space-before="${f2(def.indent * i)}cm" text:min-label-width="0.8cm"/>` +
|
|
1252
|
+
`<style:text-properties fo:font-family="OpenSymbol" style:use-window-font-color="false" fo:color="${color}" fo:font-size="${size}"/>` +
|
|
1253
|
+
`</text:list-level-style-bullet>`);
|
|
1254
|
+
return `<text:list-style style:name="${esc(name)}-list">${levels.join("")}</text:list-style>`;
|
|
1255
|
+
}
|
|
1256
|
+
function styleXml(name, s) {
|
|
1257
|
+
const parent = s.parent ? ` style:parent-style-name="${esc(s.parent)}"` : "";
|
|
1258
|
+
const list = s.bullets ? bulletsXml(s.bullets, name) : "";
|
|
1259
|
+
const where = `style "${name}"`;
|
|
1260
|
+
return (`<style:style style:name="${esc(name)}" style:family="${s.family}"${parent}>` +
|
|
1261
|
+
`<style:graphic-properties ${attrs(s.graphic, where)}>${list}</style:graphic-properties>` +
|
|
1262
|
+
`<style:paragraph-properties ${attrs(s.paragraph, where)}/>` +
|
|
1263
|
+
`<style:text-properties ${attrs(s.text, where)}/></style:style>`);
|
|
1264
|
+
}
|
|
1265
|
+
function stylesXml() {
|
|
1266
|
+
const templates = style.tableTemplates.map(t => `<table:table-template table:name="${esc(t.name)}">` +
|
|
1267
|
+
`<table:first-row table:style-name="${esc(t.header)}"/>` +
|
|
1268
|
+
`<table:body table:style-name="${esc(t.body)}"/>` +
|
|
1269
|
+
`<table:odd-rows table:style-name="${esc(t.bandedRows)}"/>` +
|
|
1270
|
+
`</table:table-template>`);
|
|
1271
|
+
const markers = [
|
|
1272
|
+
...Object.entries(style.markers).map(([name, m]) => `<draw:marker draw:name="${esc(name)}" svg:viewBox="${esc(m.viewBox)}" svg:d="${esc(m.d)}"/>`),
|
|
1273
|
+
...Object.entries(style.dashes).map(([name, props]) => `<draw:stroke-dash draw:name="${esc(name)}" ${attrs(props)}/>`),
|
|
1274
|
+
];
|
|
1275
|
+
const auto = [
|
|
1276
|
+
`<style:page-layout style:name="PM1"><style:page-layout-properties fo:margin-top="0cm" fo:margin-bottom="0cm" fo:margin-left="0cm" fo:margin-right="0cm" fo:page-width="${SLIDE_W}cm" fo:page-height="${SLIDE_H}cm" style:print-orientation="landscape"/></style:page-layout>`,
|
|
1277
|
+
`<style:page-layout style:name="PM2"><style:page-layout-properties fo:margin-top="0cm" fo:margin-bottom="0cm" fo:margin-left="0cm" fo:margin-right="0cm" fo:page-width="21cm" fo:page-height="29.7cm" style:print-orientation="portrait"/></style:page-layout>`,
|
|
1278
|
+
`<style:style style:name="Mdp1" style:family="drawing-page"><style:drawing-page-properties draw:background-size="full" draw:fill="solid" draw:fill-color="#FFFFFF"/></style:style>`,
|
|
1279
|
+
];
|
|
1280
|
+
const notes = (m) => `<presentation:notes style:page-layout-name="PM2">` +
|
|
1281
|
+
`<draw:page-thumbnail presentation:style-name="${m}-title" presentation:class="page" svg:x="1.5cm" svg:y="1.5cm" svg:width="18cm" svg:height="10.13cm"/>` +
|
|
1282
|
+
`<draw:frame presentation:style-name="${m}-notes" presentation:class="notes" presentation:placeholder="true" svg:x="1.5cm" svg:y="12.5cm" svg:width="18cm" svg:height="15cm"><draw:text-box/></draw:frame>` +
|
|
1283
|
+
`</presentation:notes>`;
|
|
1284
|
+
const placeholder = (styleName, cls, x, y, w, h) => `<draw:frame presentation:style-name="${styleName}" presentation:class="${cls}" presentation:placeholder="true" ${Builder.geom(x, y, w, h)}><draw:text-box/></draw:frame>`;
|
|
1285
|
+
const masters = [
|
|
1286
|
+
`<style:master-page style:name="Greta" style:page-layout-name="PM1" draw:style-name="Mdp1">` +
|
|
1287
|
+
`<draw:rect draw:style-name="Decor" ${Builder.geom(0, 0, 0.4, SLIDE_H)}/>` +
|
|
1288
|
+
`<draw:line draw:style-name="Decor-ligne" svg:x1="${X0}cm" svg:y1="2.7cm" svg:x2="${X0 + W}cm" svg:y2="2.7cm"/>` +
|
|
1289
|
+
placeholder("Greta-title", "title", X0, 0.95, W, 1.6) +
|
|
1290
|
+
placeholder("Greta-outline1", "outline", X0, Y0, W, H) +
|
|
1291
|
+
`${notes("Greta")}</style:master-page>`,
|
|
1292
|
+
`<style:master-page style:name="Section" style:page-layout-name="PM1" draw:style-name="Mdp1">` +
|
|
1293
|
+
`<draw:rect draw:style-name="Section-fond" ${Builder.geom(0, 0, SLIDE_W, SLIDE_H)}/>` +
|
|
1294
|
+
`<draw:rect draw:style-name="Decor" ${Builder.geom(0, 8.55, SLIDE_W, 0.12)}/>` +
|
|
1295
|
+
placeholder("Section-title", "title", 2, 5, 24, 3.5) +
|
|
1296
|
+
placeholder("Section-subtitle", "subtitle", 2, 8.8, 24, 1.5) +
|
|
1297
|
+
`${notes("Section")}</style:master-page>`,
|
|
1298
|
+
];
|
|
1299
|
+
return (`<?xml version="1.0" encoding="UTF-8"?><office:document-styles ${NS}>` +
|
|
1300
|
+
`<office:styles>${Object.entries(style.styles).map(([name, s]) => styleXml(name, s)).join("")}${templates.join("")}${markers.join("")}</office:styles>` +
|
|
1301
|
+
`<office:automatic-styles>${auto.join("")}</office:automatic-styles>` +
|
|
1302
|
+
`<office:master-styles>${masters.join("")}</office:master-styles></office:document-styles>`);
|
|
1303
|
+
}
|
|
1304
|
+
function contentXml(b) {
|
|
1305
|
+
const auto = Object.entries(style.spanStyles).map(([name, props]) => `<style:style style:name="${esc(name)}" style:family="text"><style:text-properties ${attrs(props, `span style "${name}"`)}/></style:style>`);
|
|
1306
|
+
for (const [key, name] of b.colStyles)
|
|
1307
|
+
auto.push(`<style:style style:name="${name}" style:family="table-column"><style:table-column-properties style:column-width="${key}cm"/></style:style>`);
|
|
1308
|
+
for (const { name, parent, graphic } of b.autoStyles.values())
|
|
1309
|
+
auto.push(`<style:style style:name="${name}" style:family="graphic" style:parent-style-name="${esc(parent)}">` +
|
|
1310
|
+
`<style:graphic-properties ${attrs(graphic)}/></style:style>`);
|
|
1311
|
+
for (const { name, text } of b.paraStyles.values())
|
|
1312
|
+
auto.push(`<style:style style:name="${name}" style:family="paragraph"><style:text-properties ${attrs(text)}/></style:style>`);
|
|
1313
|
+
for (const [key, name] of b.rowStyles)
|
|
1314
|
+
auto.push(`<style:style style:name="${name}" style:family="table-row"><style:table-row-properties style:row-height="${key}cm"/></style:style>`);
|
|
1315
|
+
const pages = b.pages.map(({ master, shapes, notes }, i) => {
|
|
1316
|
+
const n = i + 1;
|
|
1317
|
+
const noteXml = notes.map(t => `<text:p>${xmlText(t)}</text:p>`).join("");
|
|
1318
|
+
return (`<draw:page draw:name="page${n}" draw:master-page-name="${master}">${shapes.join("")}` +
|
|
1319
|
+
`<presentation:notes><draw:page-thumbnail presentation:style-name="${master}-title" presentation:class="page" draw:page-number="${n}" svg:x="1.5cm" svg:y="1.5cm" svg:width="18cm" svg:height="10.13cm"/>` +
|
|
1320
|
+
`<draw:frame presentation:style-name="${master}-notes" presentation:class="notes" svg:x="1.5cm" svg:y="12.5cm" svg:width="18cm" svg:height="15cm"><draw:text-box>${noteXml}</draw:text-box></draw:frame>` +
|
|
1321
|
+
`</presentation:notes></draw:page>`);
|
|
1322
|
+
});
|
|
1323
|
+
return (`<?xml version="1.0" encoding="UTF-8"?><office:document-content ${NS}>` +
|
|
1324
|
+
`<office:automatic-styles>${auto.join("")}</office:automatic-styles>` +
|
|
1325
|
+
`<office:body><office:presentation>${pages.join("")}</office:presentation></office:body></office:document-content>`);
|
|
1326
|
+
}
|
|
1327
|
+
// ---------------------------------------------------------------- ZIP
|
|
1328
|
+
/** Minimal ZIP writer: enough for ODF packages. */
|
|
1329
|
+
function zip(entries) {
|
|
1330
|
+
const locals = [];
|
|
1331
|
+
const centrals = [];
|
|
1332
|
+
let offset = 0;
|
|
1333
|
+
for (const { name, data, store } of entries) {
|
|
1334
|
+
const nameBuf = Buffer.from(name, "utf8");
|
|
1335
|
+
const body = store ? data : deflateRawSync(data);
|
|
1336
|
+
const crc = crc32(data);
|
|
1337
|
+
const method = store ? 0 : 8;
|
|
1338
|
+
const local = Buffer.alloc(30);
|
|
1339
|
+
local.writeUInt32LE(0x04034b50, 0);
|
|
1340
|
+
local.writeUInt16LE(20, 4);
|
|
1341
|
+
local.writeUInt16LE(0x0800, 6); // UTF-8 names
|
|
1342
|
+
local.writeUInt16LE(method, 8);
|
|
1343
|
+
local.writeUInt16LE(0, 10);
|
|
1344
|
+
local.writeUInt16LE(0x21, 12); // 1980-01-01
|
|
1345
|
+
local.writeUInt32LE(crc, 14);
|
|
1346
|
+
local.writeUInt32LE(body.length, 18);
|
|
1347
|
+
local.writeUInt32LE(data.length, 22);
|
|
1348
|
+
local.writeUInt16LE(nameBuf.length, 26);
|
|
1349
|
+
local.writeUInt16LE(0, 28);
|
|
1350
|
+
const central = Buffer.alloc(46);
|
|
1351
|
+
central.writeUInt32LE(0x02014b50, 0);
|
|
1352
|
+
central.writeUInt16LE(20, 4);
|
|
1353
|
+
central.writeUInt16LE(20, 6);
|
|
1354
|
+
central.writeUInt16LE(0x0800, 8);
|
|
1355
|
+
central.writeUInt16LE(method, 10);
|
|
1356
|
+
central.writeUInt16LE(0, 12);
|
|
1357
|
+
central.writeUInt16LE(0x21, 14);
|
|
1358
|
+
central.writeUInt32LE(crc, 16);
|
|
1359
|
+
central.writeUInt32LE(body.length, 20);
|
|
1360
|
+
central.writeUInt32LE(data.length, 24);
|
|
1361
|
+
central.writeUInt16LE(nameBuf.length, 28);
|
|
1362
|
+
central.writeUInt32LE(offset, 42);
|
|
1363
|
+
locals.push(local, nameBuf, body);
|
|
1364
|
+
centrals.push(central, nameBuf);
|
|
1365
|
+
offset += local.length + nameBuf.length + body.length;
|
|
1366
|
+
}
|
|
1367
|
+
const cd = Buffer.concat(centrals);
|
|
1368
|
+
const end = Buffer.alloc(22);
|
|
1369
|
+
end.writeUInt32LE(0x06054b50, 0);
|
|
1370
|
+
end.writeUInt16LE(entries.length, 8);
|
|
1371
|
+
end.writeUInt16LE(entries.length, 10);
|
|
1372
|
+
end.writeUInt32LE(cd.length, 12);
|
|
1373
|
+
end.writeUInt32LE(offset, 16);
|
|
1374
|
+
return Buffer.concat([...locals, cd, end]);
|
|
1375
|
+
}
|
|
1376
|
+
function writeOdp(b, out, title) {
|
|
1377
|
+
const pics = [...b.pictures.values()];
|
|
1378
|
+
const manifest = '<?xml version="1.0" encoding="UTF-8"?><manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3">' +
|
|
1379
|
+
'<manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.presentation"/>' +
|
|
1380
|
+
'<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>' +
|
|
1381
|
+
'<manifest:file-entry manifest:full-path="styles.xml" manifest:media-type="text/xml"/>' +
|
|
1382
|
+
'<manifest:file-entry manifest:full-path="meta.xml" manifest:media-type="text/xml"/>' +
|
|
1383
|
+
pics.map(p => `<manifest:file-entry manifest:full-path="${esc(p.href)}" manifest:media-type="${MIME[extname(p.href).toLowerCase()]}"/>`).join("") +
|
|
1384
|
+
"</manifest:manifest>";
|
|
1385
|
+
const meta = `<?xml version="1.0" encoding="UTF-8"?><office:document-meta ${NS}><office:meta>` +
|
|
1386
|
+
`<dc:title>${esc(title)}</dc:title><meta:generator>impress.ts</meta:generator></office:meta></office:document-meta>`;
|
|
1387
|
+
const text = (s) => Buffer.from(s, "utf8");
|
|
1388
|
+
writeFileSync(out, zip([
|
|
1389
|
+
{ name: "mimetype", data: text("application/vnd.oasis.opendocument.presentation"), store: true },
|
|
1390
|
+
{ name: "META-INF/manifest.xml", data: text(manifest) },
|
|
1391
|
+
{ name: "meta.xml", data: text(meta) },
|
|
1392
|
+
{ name: "styles.xml", data: text(stylesXml()) },
|
|
1393
|
+
{ name: "content.xml", data: text(contentXml(b)) },
|
|
1394
|
+
...pics.map(p => ({ name: p.href, data: p.data, store: true })),
|
|
1395
|
+
]));
|
|
1396
|
+
}
|
|
1397
|
+
// ---------------------------------------------------------------- main
|
|
1398
|
+
function humanSize(bytes) {
|
|
1399
|
+
const units = ["B", "KB", "MB", "GB"];
|
|
1400
|
+
let n = bytes;
|
|
1401
|
+
let u = 0;
|
|
1402
|
+
while (n >= 1024 && u < units.length - 1) {
|
|
1403
|
+
n /= 1024;
|
|
1404
|
+
u++;
|
|
1405
|
+
}
|
|
1406
|
+
return `${u ? n.toFixed(1) : n} ${units[u]}`;
|
|
1407
|
+
}
|
|
1408
|
+
function countHints(sec) {
|
|
1409
|
+
return sec.hints.length + sec.children.reduce((n, c) => n + countHints(c), 0);
|
|
1410
|
+
}
|
|
1411
|
+
function convert(src, config) {
|
|
1412
|
+
useStyle(config);
|
|
1413
|
+
const root = parse(readFileSync(src, "utf8"), src);
|
|
1414
|
+
const b = new Builder(dirname(src));
|
|
1415
|
+
b.walkChildren(root);
|
|
1416
|
+
const out = src.replace(/\.md$/i, ".odp");
|
|
1417
|
+
writeOdp(b, out, basename(src, extname(src)));
|
|
1418
|
+
return { out, hints: countHints(root) };
|
|
1419
|
+
}
|
|
1420
|
+
/** A ready-to-paste prompt asking an AI agent to apply the `@hint` pragmas of the given presentations. */
|
|
1421
|
+
function aiPrompt(files) {
|
|
1422
|
+
const rule = "-".repeat(72);
|
|
1423
|
+
return [
|
|
1424
|
+
rule,
|
|
1425
|
+
`Refine ${files.length > 1 ? "these LibreOffice Impress presentations" : "this LibreOffice Impress presentation"}:`,
|
|
1426
|
+
...files.map(f => ` - ${f}`),
|
|
1427
|
+
"",
|
|
1428
|
+
"An .odp file is a ZIP archive. In its content.xml, some slide titles carry",
|
|
1429
|
+
"layout instructions in their alt-text description: <svg:desc> elements whose",
|
|
1430
|
+
"lines start with \"@hint\". Each hint describes how its slide (and the following",
|
|
1431
|
+
"slides of the same section) should be transformed.",
|
|
1432
|
+
"",
|
|
1433
|
+
"For each hint:",
|
|
1434
|
+
" 1. Find the slide(s) it applies to and apply the requested change",
|
|
1435
|
+
" (layout, splitting or merging slides, animations, ...).",
|
|
1436
|
+
" 2. Reuse the existing styles from styles.xml (drawing, presentation and",
|
|
1437
|
+
" table-cell styles) instead of adding direct formatting.",
|
|
1438
|
+
" 3. Keep the speaker notes and every <svg:desc> hint verbatim, so the",
|
|
1439
|
+
" file can be refined again later.",
|
|
1440
|
+
"",
|
|
1441
|
+
"Rebuild each archive with \"mimetype\" as its first entry, stored uncompressed,",
|
|
1442
|
+
"and check that LibreOffice still opens it, e.g.:",
|
|
1443
|
+
" soffice --headless --convert-to pdf <file>.odp",
|
|
1444
|
+
"Then summarize, hint by hint, what you changed.",
|
|
1445
|
+
rule,
|
|
1446
|
+
].join("\n");
|
|
1447
|
+
}
|
|
1448
|
+
const PRAGMAS = [
|
|
1449
|
+
["@note <text>", "Speaker note of the current slide (seen by the teacher only)."],
|
|
1450
|
+
["@note begin ... @note end", "Multi-line speaker note."],
|
|
1451
|
+
["@hint <text>", "Instruction for an AI: stored verbatim in the .odp (alt-text of the slide title), never displayed."],
|
|
1452
|
+
["@layout grid <C>x<R>", "Put the next C×R sections (starting at the next heading) on one slide, in a grid."],
|
|
1453
|
+
["@layout columns <sizes>", 'Put the next sections on one slide, in columns sized "1fr", "2fr"... or "auto" (one size per section).'],
|
|
1454
|
+
["@graph <file.dot>", "Insert a Graphviz diagram (path relative to the .md) as native shapes editable in Impress."],
|
|
1455
|
+
["```prompt ... ```", "Not a pragma: a code block shown as a chat prompt bubble."],
|
|
1456
|
+
];
|
|
1457
|
+
function printHelp() {
|
|
1458
|
+
console.log([
|
|
1459
|
+
"Convert markdown files into LibreOffice Impress presentations.",
|
|
1460
|
+
"",
|
|
1461
|
+
"Usage: node scripts/impress/impress.ts <file.md> [<file.md> ...]",
|
|
1462
|
+
"",
|
|
1463
|
+
"Each foo.md produces foo.odp in the same folder. Headings become section and",
|
|
1464
|
+
"content slides. The styles come from foo.style.json, created with the default",
|
|
1465
|
+
"styles if missing (edit it, then run again to restyle the presentation).",
|
|
1466
|
+
].join("\n"));
|
|
1467
|
+
console.log("\nPragmas (at the start of a line in the .md file):");
|
|
1468
|
+
const width = Math.max(...PRAGMAS.map(([p]) => p.length));
|
|
1469
|
+
for (const [pragma, text] of PRAGMAS)
|
|
1470
|
+
console.log(` ${pragma.padEnd(width)} ${text}`);
|
|
1471
|
+
}
|
|
1472
|
+
async function main(args) {
|
|
1473
|
+
if (!args.length) {
|
|
1474
|
+
printHelp();
|
|
1475
|
+
return;
|
|
1476
|
+
}
|
|
1477
|
+
const files = args.filter(f => f.toLowerCase().endsWith(".md"));
|
|
1478
|
+
for (const f of args)
|
|
1479
|
+
if (!files.includes(f))
|
|
1480
|
+
console.warn(`Ignoring ${f}: not a .md file`);
|
|
1481
|
+
if (!files.length) {
|
|
1482
|
+
console.error("No .md file given. Run without arguments for help.");
|
|
1483
|
+
process.exit(1);
|
|
1484
|
+
}
|
|
1485
|
+
await loadGraphviz();
|
|
1486
|
+
const withHints = [];
|
|
1487
|
+
let failed = false;
|
|
1488
|
+
for (const file of files) {
|
|
1489
|
+
const src = resolve(file);
|
|
1490
|
+
console.log(`Processing ${src}`);
|
|
1491
|
+
try {
|
|
1492
|
+
const { config, path, created } = loadStyle(src);
|
|
1493
|
+
console.log(created ? ` + ${path} (created with the default style)` : ` ⚙ ${path}`);
|
|
1494
|
+
const { out, hints } = convert(src, config);
|
|
1495
|
+
console.log(` → ${out} (${humanSize(statSync(out).size)})`);
|
|
1496
|
+
if (hints)
|
|
1497
|
+
withHints.push([out, hints]);
|
|
1498
|
+
}
|
|
1499
|
+
catch (err) {
|
|
1500
|
+
failed = true;
|
|
1501
|
+
console.error(` ✗ ${err instanceof Error ? err.message : err}`);
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
if (withHints.length) {
|
|
1505
|
+
console.log("\nThese presentations contain @hint pragmas (stored in the slide titles' alt-text descriptions)");
|
|
1506
|
+
console.log("and can be refined with AI:");
|
|
1507
|
+
for (const [out, n] of withHints)
|
|
1508
|
+
console.log(` - ${out} (${n} hint${n > 1 ? "s" : ""})`);
|
|
1509
|
+
console.log("\nExample of prompt to give to an AI agent able to read and write files:\n");
|
|
1510
|
+
console.log(aiPrompt(withHints.map(([out]) => out)));
|
|
1511
|
+
}
|
|
1512
|
+
if (failed)
|
|
1513
|
+
process.exit(1);
|
|
1514
|
+
}
|
|
1515
|
+
await main(process.argv.slice(2));
|