@tolokoban/impress 0.1.0 → 0.13.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/README.md +99 -30
- package/dist/impress.js +911 -407
- package/dist/styles.js +46 -71
- package/package.json +4 -4
package/dist/impress.js
CHANGED
|
@@ -18,14 +18,35 @@
|
|
|
18
18
|
* @layout columns 1fr 2fr auto
|
|
19
19
|
* the next 3 sections on one slide, in columns sized by
|
|
20
20
|
* fractions of the free width or by their content (auto)
|
|
21
|
-
*
|
|
21
|
+
* Not followed by a heading, a layout takes the next blocks
|
|
22
|
+
* (paragraph, list, image...) of the section instead, one per cell
|
|
23
|
+
* @graph diagram.dot Graphviz diagram, rendered as a PNG image by the "dot" tool
|
|
24
|
+
*
|
|
25
|
+
* Every embedded image (graphs included) is stored as WebP (see `theme.images`).
|
|
26
|
+
* @next start a new slide with the same title as the current one
|
|
27
|
+
* @compact the next table is shrunk to fit on one slide instead of being split
|
|
28
|
+
* @reveal C1,3 R1-4 the rows of the next table appear one slide after the other; the
|
|
29
|
+
* columns (C) and rows (R) listed, both optional, are always visible
|
|
22
30
|
* ```prompt ... ``` chat prompt bubble
|
|
23
31
|
*/
|
|
24
32
|
import { existsSync, readFileSync, writeFileSync, statSync } from "node:fs";
|
|
25
|
-
import { basename, dirname, extname, resolve } from "node:path";
|
|
33
|
+
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
26
34
|
import { crc32, deflateRawSync } from "node:zlib";
|
|
35
|
+
import { spawnSync } from "node:child_process";
|
|
36
|
+
import { createInterface } from "node:readline/promises";
|
|
37
|
+
import sharp from "sharp";
|
|
27
38
|
import { defaultStyle } from "./styles.js";
|
|
28
39
|
const PT = 0.03528; // cm per point
|
|
40
|
+
// ---------------------------------------------------------------- terminal colors
|
|
41
|
+
/** ANSI styles, only when writing to a terminal and NO_COLOR is not set. */
|
|
42
|
+
const COLOR = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
|
|
43
|
+
const ansi = (on, off) => (text) => (COLOR ? `\x1b[${on}m${text}\x1b[${off}m` : text);
|
|
44
|
+
/** File names. Ends with "normal intensity" only, so it can be nested in a colored text. */
|
|
45
|
+
const bold = ansi("1", "22");
|
|
46
|
+
/** Example of prompt for an AI agent. */
|
|
47
|
+
const cyan = ansi("36", "39");
|
|
48
|
+
/** Questions waiting for an answer. */
|
|
49
|
+
const yellow = ansi("93", "39");
|
|
29
50
|
// Style of the file being converted (see `useStyle()`).
|
|
30
51
|
let style = defaultStyle;
|
|
31
52
|
let sizes = style.theme.sizes;
|
|
@@ -36,12 +57,14 @@ let Y0 = 0;
|
|
|
36
57
|
let W = 0;
|
|
37
58
|
let H = 0;
|
|
38
59
|
let GAP = 0;
|
|
60
|
+
let CENTER = false;
|
|
39
61
|
function useStyle(config) {
|
|
40
62
|
style = config;
|
|
41
63
|
sizes = config.theme.sizes;
|
|
42
64
|
SLIDE_W = config.theme.slide.width;
|
|
43
65
|
SLIDE_H = config.theme.slide.height;
|
|
44
66
|
({ x: X0, y: Y0, width: W, height: H, gap: GAP } = config.theme.content);
|
|
67
|
+
CENTER = config.theme.content.align === "center";
|
|
45
68
|
}
|
|
46
69
|
function isObject(v) {
|
|
47
70
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -87,6 +110,23 @@ function resolveValue(value, where) {
|
|
|
87
110
|
return String(v);
|
|
88
111
|
});
|
|
89
112
|
}
|
|
113
|
+
/** Is this cell hidden until its row is revealed? */
|
|
114
|
+
function isHidden(b, row, col) {
|
|
115
|
+
return !!b.reveal && !!b.shown && !b.shown.has(row) && !b.reveal.rows.has(row) && !b.reveal.cols.has(col);
|
|
116
|
+
}
|
|
117
|
+
/** `1,3`, `1-4`, `2,5-7`: 1-based numbers, returned 0-based. */
|
|
118
|
+
function parseNumbers(spec, where) {
|
|
119
|
+
const out = [];
|
|
120
|
+
for (const part of spec.split(",")) {
|
|
121
|
+
const m = part.match(/^(\d+)(?:-(\d+))?$/);
|
|
122
|
+
const [a, b] = m ? [Number(m[1]), Number(m[2] ?? m[1])] : [0, 0];
|
|
123
|
+
if (!m || a < 1 || b < a)
|
|
124
|
+
throw new Error(`${where}: invalid list "${spec}" (expected numbers or ranges, e.g. 1,3 or 1-4)`);
|
|
125
|
+
for (let n = a; n <= b; n++)
|
|
126
|
+
out.push(n - 1);
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
90
130
|
function cellCount(layout) {
|
|
91
131
|
return layout.kind === "grid" ? layout.columns * layout.rows : layout.widths.length;
|
|
92
132
|
}
|
|
@@ -123,6 +163,8 @@ class Section {
|
|
|
123
163
|
children = [];
|
|
124
164
|
/** Set on the first section of a group laid out on a single slide. */
|
|
125
165
|
layout = null;
|
|
166
|
+
/** Created by `@next`: continues the previous section on a new slide. */
|
|
167
|
+
continued = false;
|
|
126
168
|
/** Folder of the markdown file, for relative image paths. */
|
|
127
169
|
source;
|
|
128
170
|
constructor(level, title, parent = null, source = "") {
|
|
@@ -146,7 +188,8 @@ function stripMd(s) {
|
|
|
146
188
|
.replace(/(?<![\p{L}\p{N}_])\*(.+?)\*(?![\p{L}\p{N}_])/gu, "$1")
|
|
147
189
|
.trim();
|
|
148
190
|
}
|
|
149
|
-
|
|
191
|
+
/** `- item`, `* item`, `1. item` or `1) item`: [indent, number (ordered only), text]. */
|
|
192
|
+
const LIST_RE = /^(\s*)(?:[*-]|(\d+)[.)])\s+(.*)$/;
|
|
150
193
|
const IMG_RE = /^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/;
|
|
151
194
|
const HEAD_RE = /^(#{1,6})\s+(.*)$/;
|
|
152
195
|
function parse(md, file) {
|
|
@@ -156,6 +199,36 @@ function parse(md, file) {
|
|
|
156
199
|
let para = [];
|
|
157
200
|
let list = null;
|
|
158
201
|
let layout = null;
|
|
202
|
+
// `@layout` followed by content instead of a heading: the next blocks fill its cells.
|
|
203
|
+
let grouped = null;
|
|
204
|
+
// Line number of an `@compact` waiting for its table (0 if none).
|
|
205
|
+
let compact = 0;
|
|
206
|
+
const dropCompact = () => {
|
|
207
|
+
if (compact)
|
|
208
|
+
console.warn(` ! ${bold(file)}:${compact}: "@compact" is not followed by a table`);
|
|
209
|
+
compact = 0;
|
|
210
|
+
};
|
|
211
|
+
// `@reveal` waiting for its table: line number, always visible columns and rows (0-based).
|
|
212
|
+
let reveal = null;
|
|
213
|
+
const dropReveal = () => {
|
|
214
|
+
if (reveal)
|
|
215
|
+
console.warn(` ! ${bold(file)}:${reveal.line}: "@reveal" is not followed by a table`);
|
|
216
|
+
reveal = null;
|
|
217
|
+
};
|
|
218
|
+
const push = (b) => {
|
|
219
|
+
if (!grouped)
|
|
220
|
+
return void cur.blocks.push(b);
|
|
221
|
+
const cells = grouped.cells;
|
|
222
|
+
if (b.t === "note")
|
|
223
|
+
return void (cells.length ? cells[cells.length - 1].blocks : cur.blocks).push(b);
|
|
224
|
+
if (cells.length === cellCount(grouped.layout)) {
|
|
225
|
+
grouped = null;
|
|
226
|
+
return void cur.blocks.push(b);
|
|
227
|
+
}
|
|
228
|
+
const cell = new Section(cur.level + 1, "", cur, root.source);
|
|
229
|
+
cell.blocks.push(b);
|
|
230
|
+
cells.push(cell);
|
|
231
|
+
};
|
|
159
232
|
const flushPara = () => {
|
|
160
233
|
if (!para.length)
|
|
161
234
|
return;
|
|
@@ -165,12 +238,12 @@ function parse(md, file) {
|
|
|
165
238
|
if (j < para.length - 1)
|
|
166
239
|
text += l.endsWith(" ") ? "\n" : " ";
|
|
167
240
|
});
|
|
168
|
-
|
|
241
|
+
push({ t: "para", text });
|
|
169
242
|
para = [];
|
|
170
243
|
};
|
|
171
244
|
const flushList = () => {
|
|
172
245
|
if (list)
|
|
173
|
-
|
|
246
|
+
push(list);
|
|
174
247
|
list = null;
|
|
175
248
|
};
|
|
176
249
|
const flush = () => {
|
|
@@ -183,6 +256,8 @@ function parse(md, file) {
|
|
|
183
256
|
let m;
|
|
184
257
|
if ((m = line.match(HEAD_RE))) {
|
|
185
258
|
flush();
|
|
259
|
+
dropCompact();
|
|
260
|
+
grouped = null;
|
|
186
261
|
const level = m[1].length;
|
|
187
262
|
while (cur.level >= level)
|
|
188
263
|
cur = cur.parent;
|
|
@@ -194,7 +269,50 @@ function parse(md, file) {
|
|
|
194
269
|
}
|
|
195
270
|
else if (s.startsWith("@layout")) {
|
|
196
271
|
flush();
|
|
197
|
-
|
|
272
|
+
grouped = null;
|
|
273
|
+
const spec = parseLayout(s.slice(7).trim(), `${file}:${i + 1}`);
|
|
274
|
+
let j = i + 1;
|
|
275
|
+
while (j < lines.length && lines[j].trim() === "")
|
|
276
|
+
j++;
|
|
277
|
+
if (j < lines.length && HEAD_RE.test(lines[j]))
|
|
278
|
+
layout = spec;
|
|
279
|
+
else {
|
|
280
|
+
grouped = { t: "layout", layout: spec, cells: [] };
|
|
281
|
+
cur.blocks.push(grouped);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
else if (s === "@next") {
|
|
285
|
+
flush();
|
|
286
|
+
grouped = null;
|
|
287
|
+
// A heading right after `@next` starts the new slide by itself.
|
|
288
|
+
let j = i + 1;
|
|
289
|
+
while (j < lines.length && lines[j].trim() === "")
|
|
290
|
+
j++;
|
|
291
|
+
if (j < lines.length && HEAD_RE.test(lines[j]))
|
|
292
|
+
continue;
|
|
293
|
+
if (!cur.parent)
|
|
294
|
+
throw new Error(`${file}:${i + 1}: "@next" needs a previous heading`);
|
|
295
|
+
const sec = new Section(cur.level, cur.title, cur.parent, root.source);
|
|
296
|
+
sec.continued = true;
|
|
297
|
+
cur.parent.children.push(sec);
|
|
298
|
+
cur = sec;
|
|
299
|
+
}
|
|
300
|
+
else if (s === "@compact") {
|
|
301
|
+
flush();
|
|
302
|
+
dropCompact();
|
|
303
|
+
compact = i + 1;
|
|
304
|
+
}
|
|
305
|
+
else if (s === "@reveal" || s.startsWith("@reveal ")) {
|
|
306
|
+
flush();
|
|
307
|
+
dropReveal();
|
|
308
|
+
const where = `${file}:${i + 1}`;
|
|
309
|
+
reveal = { line: i + 1, cols: [], rows: [] };
|
|
310
|
+
for (const arg of s.slice(7).trim().split(/\s+/).filter(Boolean)) {
|
|
311
|
+
const m = arg.match(/^([CR])(.+)$/i);
|
|
312
|
+
if (!m)
|
|
313
|
+
throw new Error(`${where}: expected "@reveal [C<columns>] [R<rows>]" (e.g. "@reveal C1,3 R1-4"), got "${s}"`);
|
|
314
|
+
reveal[m[1].toUpperCase() === "C" ? "cols" : "rows"].push(...parseNumbers(m[2], where));
|
|
315
|
+
}
|
|
198
316
|
}
|
|
199
317
|
else if (s.startsWith("@graph")) {
|
|
200
318
|
flush();
|
|
@@ -204,7 +322,7 @@ function parse(md, file) {
|
|
|
204
322
|
throw new Error(`${where}: expected "@graph <relative path of a .dot file>", got "${s}"`);
|
|
205
323
|
if (!existsSync(resolve(dirname(file), src)))
|
|
206
324
|
throw new Error(`${where}: file not found: ${src}`);
|
|
207
|
-
|
|
325
|
+
push({ t: "image", alt: "", src });
|
|
208
326
|
}
|
|
209
327
|
else if (s.startsWith("@hint")) {
|
|
210
328
|
flush();
|
|
@@ -215,11 +333,11 @@ function parse(md, file) {
|
|
|
215
333
|
const buf = [];
|
|
216
334
|
for (i++; i < lines.length && lines[i].trim() !== "@note end"; i++)
|
|
217
335
|
buf.push(lines[i]);
|
|
218
|
-
|
|
336
|
+
push({ t: "note", text: buf.join("\n").trim() });
|
|
219
337
|
}
|
|
220
338
|
else if (s.startsWith("@note")) {
|
|
221
339
|
flush();
|
|
222
|
-
|
|
340
|
+
push({ t: "note", text: s.slice(5).trim() });
|
|
223
341
|
}
|
|
224
342
|
else if (s.startsWith("```")) {
|
|
225
343
|
flush();
|
|
@@ -227,7 +345,7 @@ function parse(md, file) {
|
|
|
227
345
|
const buf = [];
|
|
228
346
|
for (i++; i < lines.length && !lines[i].trim().startsWith("```"); i++)
|
|
229
347
|
buf.push(lines[i]);
|
|
230
|
-
|
|
348
|
+
push({ t: lang === "prompt" ? "prompt" : "code", lines: buf });
|
|
231
349
|
}
|
|
232
350
|
else if (s.startsWith("|")) {
|
|
233
351
|
flush();
|
|
@@ -241,7 +359,16 @@ function parse(md, file) {
|
|
|
241
359
|
const body = rows.slice(1).filter(r => !/^[\s:\-|]*$/.test(r.join("")));
|
|
242
360
|
if (header.every(c => c === "" || c === "."))
|
|
243
361
|
header = null;
|
|
244
|
-
|
|
362
|
+
const table = { t: "table", header, rows: body };
|
|
363
|
+
if (compact)
|
|
364
|
+
table.compact = true;
|
|
365
|
+
compact = 0;
|
|
366
|
+
if (reveal) {
|
|
367
|
+
const { cols, rows: fixed } = reveal;
|
|
368
|
+
table.reveal = { cols: new Set(cols), rows: new Set(fixed.flatMap(n => (body[n] ? [body[n]] : []))) };
|
|
369
|
+
reveal = null;
|
|
370
|
+
}
|
|
371
|
+
push(table);
|
|
245
372
|
}
|
|
246
373
|
else if (s.startsWith(">")) {
|
|
247
374
|
flush();
|
|
@@ -249,16 +376,19 @@ function parse(md, file) {
|
|
|
249
376
|
for (; i < lines.length && lines[i].trim().startsWith(">"); i++)
|
|
250
377
|
buf.push(lines[i].trim().slice(1).trim());
|
|
251
378
|
i--;
|
|
252
|
-
|
|
379
|
+
push({ t: "quote", text: buf.join(" ") });
|
|
253
380
|
}
|
|
254
381
|
else if ((m = line.match(IMG_RE))) {
|
|
255
382
|
flush();
|
|
256
|
-
|
|
383
|
+
push({ t: "image", alt: m[1], src: m[2] });
|
|
257
384
|
}
|
|
258
385
|
else if ((m = line.match(LIST_RE))) {
|
|
259
386
|
flushPara();
|
|
260
387
|
list ??= { t: "list", items: [] };
|
|
261
|
-
|
|
388
|
+
const item = [Math.floor(m[1].length / 2), m[3].trim()];
|
|
389
|
+
if (m[2] !== undefined)
|
|
390
|
+
item.push(Number(m[2]));
|
|
391
|
+
list.items.push(item);
|
|
262
392
|
}
|
|
263
393
|
else if (s === "") {
|
|
264
394
|
flushPara();
|
|
@@ -279,8 +409,10 @@ function parse(md, file) {
|
|
|
279
409
|
}
|
|
280
410
|
}
|
|
281
411
|
flush();
|
|
412
|
+
dropCompact();
|
|
413
|
+
dropReveal();
|
|
282
414
|
if (layout)
|
|
283
|
-
console.warn(` ! ${file}: "${layout.source}" is not followed by any section`);
|
|
415
|
+
console.warn(` ! ${bold(file)}: "${layout.source}" is not followed by any section`);
|
|
284
416
|
return root;
|
|
285
417
|
}
|
|
286
418
|
const INLINE_PATTERNS = [
|
|
@@ -387,22 +519,169 @@ function promptSize(lines, width) {
|
|
|
387
519
|
const h = lines.reduce((acc, l) => acc + textH(l.length, w - 1, pt), 0) + 0.9;
|
|
388
520
|
return [w, h];
|
|
389
521
|
}
|
|
522
|
+
// ---------------------------------------------------------------- images in table cells
|
|
523
|
+
/** Folder of the markdown file being converted, for the relative paths of cell images. */
|
|
524
|
+
let mdDir = ".";
|
|
525
|
+
/** `<img src="..." width="48" height="48">` or ``. */
|
|
526
|
+
const CELL_IMG_RE = /<img\s[^>]*>|!\[([^\]]*)\]\(([^)\s]+)\)/gi;
|
|
527
|
+
/** Pixels per em: the HTML sizes of the markdown assume a 16px font. */
|
|
528
|
+
const PX_PER_EM = 16;
|
|
529
|
+
/** Height (in em) of a cell image without any size. */
|
|
530
|
+
const DEFAULT_IMG_EM = 2;
|
|
531
|
+
/** Horizontal gap (in em) between the images of a cell, and between them and the text. */
|
|
532
|
+
const IMG_GAP_EM = 0.3;
|
|
533
|
+
/** Horizontal padding of the table cells (both sides), in cm. */
|
|
534
|
+
const CELL_PAD_X = 0.4;
|
|
535
|
+
const cellCache = new Map();
|
|
536
|
+
function htmlAttr(tag, name) {
|
|
537
|
+
const m = tag.match(new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
|
|
538
|
+
return m ? (m[1] ?? m[2] ?? m[3]) : undefined;
|
|
539
|
+
}
|
|
540
|
+
/** Split a table cell into its text and its images (HTML `<img>` or markdown `![]()`). */
|
|
541
|
+
function cell(s) {
|
|
542
|
+
let c = cellCache.get(s);
|
|
543
|
+
if (c)
|
|
544
|
+
return c;
|
|
545
|
+
const imgs = [];
|
|
546
|
+
const text = s
|
|
547
|
+
.replace(CELL_IMG_RE, (tag, mdAlt, mdSrc) => {
|
|
548
|
+
const src = mdSrc ?? htmlAttr(tag, "src");
|
|
549
|
+
if (!src)
|
|
550
|
+
return tag;
|
|
551
|
+
const px = (name) => {
|
|
552
|
+
const v = mdSrc ? undefined : htmlAttr(tag, name);
|
|
553
|
+
const n = v === undefined ? NaN : parseFloat(v);
|
|
554
|
+
return n > 0 ? n / PX_PER_EM : undefined;
|
|
555
|
+
};
|
|
556
|
+
let w = px("width");
|
|
557
|
+
let h = px("height");
|
|
558
|
+
if (w === undefined || h === undefined) {
|
|
559
|
+
const [iw, ih] = imageSize(resolve(mdDir, src));
|
|
560
|
+
if (w !== undefined)
|
|
561
|
+
h = (w * ih) / iw;
|
|
562
|
+
else if (h !== undefined)
|
|
563
|
+
w = (h * iw) / ih;
|
|
564
|
+
else
|
|
565
|
+
[w, h] = [(DEFAULT_IMG_EM * iw) / ih, DEFAULT_IMG_EM];
|
|
566
|
+
}
|
|
567
|
+
imgs.push({ src, alt: mdAlt ?? htmlAttr(tag, "alt") ?? "", w: w, h: h });
|
|
568
|
+
return " ";
|
|
569
|
+
})
|
|
570
|
+
.replace(/\s+/g, " ")
|
|
571
|
+
.trim();
|
|
572
|
+
c = { text, imgs };
|
|
573
|
+
cellCache.set(s, c);
|
|
574
|
+
return c;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Size (in cm) of the images of a cell at `pt` points, side by side: [scale, width, height].
|
|
578
|
+
* They are shrunk to fit in the column if needed (`scale` < 1).
|
|
579
|
+
*/
|
|
580
|
+
function cellImgBox(c, colW, pt) {
|
|
581
|
+
if (!c.imgs.length)
|
|
582
|
+
return [1, 0, 0];
|
|
583
|
+
const em = pt * PT;
|
|
584
|
+
const w = (c.imgs.reduce((a, i) => a + i.w, 0) + IMG_GAP_EM * (c.imgs.length - 1)) * em;
|
|
585
|
+
const h = Math.max(...c.imgs.map(i => i.h)) * em;
|
|
586
|
+
const room = Math.max(colW - CELL_PAD_X - (c.text ? 2 * em : 0), 0.1);
|
|
587
|
+
const scale = Math.min(1, room / w);
|
|
588
|
+
return [scale, w * scale, h * scale];
|
|
589
|
+
}
|
|
590
|
+
/** Width (in cm) taken by the images of a cell before its text, gap included. */
|
|
591
|
+
function cellTextIndent(c, colW, pt) {
|
|
592
|
+
const [, w] = cellImgBox(c, colW, pt);
|
|
593
|
+
return w && c.text ? w + IMG_GAP_EM * pt * PT : 0;
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Advance widths (in 1/1000 em) of the printable ASCII characters, from space to "~", in
|
|
597
|
+
* Liberation Sans Bold (the metrics of Arial Bold): the font of the table headers.
|
|
598
|
+
*/
|
|
599
|
+
const BOLD_WIDTHS = [
|
|
600
|
+
278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556,
|
|
601
|
+
556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778,
|
|
602
|
+
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611,
|
|
603
|
+
611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584,
|
|
604
|
+
];
|
|
605
|
+
/** Width (in cm) of a word in bold at `pt` points, a bit overestimated to be safe. */
|
|
606
|
+
function boldWordW(word, pt) {
|
|
607
|
+
let units = 0;
|
|
608
|
+
for (const ch of word) {
|
|
609
|
+
// Accented letters are as wide as their base letter.
|
|
610
|
+
const code = ch.normalize("NFD").charCodeAt(0);
|
|
611
|
+
units += code >= 32 && code <= 126 ? BOLD_WIDTHS[code - 32] : 650;
|
|
612
|
+
}
|
|
613
|
+
return (units / 1000) * pt * PT * 1.05;
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Do the words of the header of a `@compact` or `@reveal` table fit in their columns, at the
|
|
617
|
+
* size of the table, on a slide of full width? Several words may wrap, but no word is cut.
|
|
618
|
+
*/
|
|
619
|
+
function headerFits(b) {
|
|
620
|
+
if (!b.header)
|
|
621
|
+
return true;
|
|
622
|
+
const pt = b.pt ?? sizes.table;
|
|
623
|
+
const cols = tableBlockCols(b, W);
|
|
624
|
+
return b.header.every((s, i) => {
|
|
625
|
+
const c = cell(s);
|
|
626
|
+
const room = cols[i] - CELL_PAD_X - cellTextIndent(c, cols[i], pt);
|
|
627
|
+
const words = inline(c.text)
|
|
628
|
+
.map(r => r.text)
|
|
629
|
+
.join("")
|
|
630
|
+
.split(/\s+/)
|
|
631
|
+
.filter(Boolean);
|
|
632
|
+
return words.every(w => boldWordW(w, pt) <= room);
|
|
633
|
+
});
|
|
634
|
+
}
|
|
390
635
|
function tableCols(header, rows, width) {
|
|
391
636
|
const all = header ? [header, ...rows] : rows;
|
|
392
637
|
const ncol = Math.max(...all.map(r => r.length));
|
|
393
638
|
const lens = new Array(ncol).fill(0);
|
|
394
639
|
for (const r of all)
|
|
395
|
-
r.forEach((
|
|
640
|
+
r.forEach((s, c) => {
|
|
641
|
+
const { text, imgs } = cell(s);
|
|
642
|
+
// An em is about two characters (see `textH()`).
|
|
643
|
+
const imgLen = imgs.length ? 2 * (imgs.reduce((a, i) => a + i.w, 0) + IMG_GAP_EM * imgs.length) : 0;
|
|
644
|
+
lens[c] = Math.max(lens[c], Math.min(plainLen(text), 45) + imgLen + 4);
|
|
645
|
+
});
|
|
396
646
|
const tot = lens.reduce((a, b) => a + b, 0);
|
|
397
647
|
return lens.map(l => (width * l) / tot);
|
|
398
648
|
}
|
|
399
649
|
function rowH(r, cols, pt) {
|
|
400
|
-
|
|
650
|
+
// Below the size of small tables (`@compact`), the room around the text shrinks too, down to the cell padding.
|
|
651
|
+
const pad = pt >= sizes.tableSmall ? 0.35 : 0.2 + (0.15 * pt) / sizes.tableSmall;
|
|
652
|
+
return (Math.max(...r.map((s, i) => {
|
|
653
|
+
const c = cell(s);
|
|
654
|
+
const th = c.text ? textH(plainLen(c.text), cols[i] - CELL_PAD_X - cellTextIndent(c, cols[i], pt), pt) : 0;
|
|
655
|
+
return Math.max(th, cellImgBox(c, cols[i], pt)[2]);
|
|
656
|
+
})) + pad);
|
|
401
657
|
}
|
|
402
658
|
function tableH(header, rows, width, pt, cols) {
|
|
403
659
|
cols ??= tableCols(header, rows, width);
|
|
404
660
|
return (header ? [header, ...rows] : rows).reduce((h, r) => h + rowH(r, cols, pt), 0);
|
|
405
661
|
}
|
|
662
|
+
/** Horizontal gap between the side-by-side parts of a table. */
|
|
663
|
+
const TABLE_GAP = 0.6;
|
|
664
|
+
/** Rows of each side-by-side part of a table block. */
|
|
665
|
+
function tableParts(b) {
|
|
666
|
+
const n = b.columns ?? 1;
|
|
667
|
+
if (n <= 1)
|
|
668
|
+
return [b.rows];
|
|
669
|
+
const per = Math.ceil(b.rows.length / n);
|
|
670
|
+
return Array.from({ length: n }, (_, i) => b.rows.slice(i * per, (i + 1) * per)).filter(p => p.length);
|
|
671
|
+
}
|
|
672
|
+
function tablePartW(b, width) {
|
|
673
|
+
const n = b.columns ?? 1;
|
|
674
|
+
return (width - TABLE_GAP * (n - 1)) / n;
|
|
675
|
+
}
|
|
676
|
+
/** Column widths of each part, the same for all the parts of a table. */
|
|
677
|
+
function tableBlockCols(b, width) {
|
|
678
|
+
return tableCols(b.header, b.ref ?? b.rows, tablePartW(b, width));
|
|
679
|
+
}
|
|
680
|
+
function tableBlockH(b, width) {
|
|
681
|
+
const cols = tableBlockCols(b, width);
|
|
682
|
+
const pw = tablePartW(b, width);
|
|
683
|
+
return Math.max(...tableParts(b).map(rows => tableH(b.header, rows, pw, b.pt ?? sizes.table, cols)));
|
|
684
|
+
}
|
|
406
685
|
function blockH(b, width) {
|
|
407
686
|
switch (b.t) {
|
|
408
687
|
case "para":
|
|
@@ -415,7 +694,7 @@ function blockH(b, width) {
|
|
|
415
694
|
case "code":
|
|
416
695
|
return promptSize(b.lines, width)[1];
|
|
417
696
|
case "table":
|
|
418
|
-
return
|
|
697
|
+
return tableBlockH(b, width);
|
|
419
698
|
default:
|
|
420
699
|
return 0;
|
|
421
700
|
}
|
|
@@ -423,7 +702,7 @@ function blockH(b, width) {
|
|
|
423
702
|
function imageSize(path) {
|
|
424
703
|
const ext = extname(path).toLowerCase();
|
|
425
704
|
if (ext === ".dot")
|
|
426
|
-
return
|
|
705
|
+
return graphPng(path).size;
|
|
427
706
|
const data = readFileSync(path);
|
|
428
707
|
if (ext === ".svg") {
|
|
429
708
|
const head = data.subarray(0, 4000).toString("utf8");
|
|
@@ -461,151 +740,227 @@ function fit(iw, ih, bw, bh) {
|
|
|
461
740
|
const r = Math.min(bw / iw, bh / ih);
|
|
462
741
|
return [iw * r, ih * r];
|
|
463
742
|
}
|
|
464
|
-
|
|
465
|
-
const CM_PER_POINT = 2.54 / 72;
|
|
743
|
+
/** Rendered diagrams, keyed by the arguments of `dot` (which include the theme). */
|
|
466
744
|
const graphCache = new Map();
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
let
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
745
|
+
const IS_WINDOWS = process.platform === "win32";
|
|
746
|
+
/** Path of the Graphviz `dot` executable: `undefined` until searched, `null` if not found. */
|
|
747
|
+
let dotPath;
|
|
748
|
+
function hasCommand(cmd) {
|
|
749
|
+
const r = IS_WINDOWS
|
|
750
|
+
? spawnSync("where", [cmd], { stdio: "ignore" })
|
|
751
|
+
: spawnSync("sh", ["-c", `command -v ${cmd}`], { stdio: "ignore" });
|
|
752
|
+
return r.status === 0;
|
|
753
|
+
}
|
|
754
|
+
/** `dot` from the PATH, or from the usual install folders (a fresh install may not be in the PATH yet). */
|
|
755
|
+
function findDot() {
|
|
756
|
+
if (hasCommand("dot"))
|
|
757
|
+
return "dot";
|
|
758
|
+
const candidates = IS_WINDOWS
|
|
759
|
+
? [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "Programs")]
|
|
760
|
+
.filter((d) => !!d)
|
|
761
|
+
.map(d => join(d, "Graphviz", "bin", "dot.exe"))
|
|
762
|
+
: ["/opt/homebrew/bin/dot", "/usr/local/bin/dot", "/opt/local/bin/dot", "/usr/bin/dot"];
|
|
763
|
+
return candidates.find(p => existsSync(p)) ?? null;
|
|
764
|
+
}
|
|
765
|
+
/** The command installing Graphviz on this system, if a known package manager is available. */
|
|
766
|
+
function installCommand() {
|
|
767
|
+
const sudo = !IS_WINDOWS && process.getuid?.() !== 0 && hasCommand("sudo") ? ["sudo"] : [];
|
|
768
|
+
const managers = process.platform === "darwin"
|
|
769
|
+
? [
|
|
770
|
+
["brew", ["brew", "install", "graphviz"]],
|
|
771
|
+
["port", [...sudo, "port", "install", "graphviz"]],
|
|
772
|
+
]
|
|
773
|
+
: IS_WINDOWS
|
|
774
|
+
? [
|
|
775
|
+
["winget", ["winget", "install", "--id", "Graphviz.Graphviz", "-e", "--accept-package-agreements", "--accept-source-agreements"]],
|
|
776
|
+
["choco", ["choco", "install", "graphviz", "-y"]],
|
|
777
|
+
["scoop", ["scoop", "install", "graphviz"]],
|
|
778
|
+
]
|
|
779
|
+
: [
|
|
780
|
+
["apt-get", [...sudo, "apt-get", "install", "-y", "graphviz"]],
|
|
781
|
+
["dnf", [...sudo, "dnf", "install", "-y", "graphviz"]],
|
|
782
|
+
["yum", [...sudo, "yum", "install", "-y", "graphviz"]],
|
|
783
|
+
["pacman", [...sudo, "pacman", "-S", "--noconfirm", "graphviz"]],
|
|
784
|
+
["zypper", [...sudo, "zypper", "install", "-y", "graphviz"]],
|
|
785
|
+
["apk", [...sudo, "apk", "add", "graphviz"]],
|
|
786
|
+
["brew", ["brew", "install", "graphviz"]],
|
|
787
|
+
];
|
|
788
|
+
return managers.find(([cmd]) => hasCommand(cmd))?.[1] ?? null;
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Make sure the Graphviz `dot` tool is available, offering to install it if it is not.
|
|
792
|
+
* Searched once per run; `graphPng()` fails with an explanation if it is still missing.
|
|
793
|
+
*/
|
|
794
|
+
async function ensureDot() {
|
|
795
|
+
if (dotPath !== undefined)
|
|
796
|
+
return;
|
|
797
|
+
dotPath = findDot();
|
|
798
|
+
if (dotPath)
|
|
799
|
+
return;
|
|
800
|
+
console.log(" ! @graph needs the Graphviz \"dot\" tool, which is not installed on this machine.");
|
|
801
|
+
const cmd = installCommand();
|
|
802
|
+
if (!cmd) {
|
|
803
|
+
console.log(" Install Graphviz (https://graphviz.org/download/), then run again.");
|
|
804
|
+
return;
|
|
474
805
|
}
|
|
475
|
-
|
|
476
|
-
|
|
806
|
+
const shown = cmd.join(" ");
|
|
807
|
+
if (!process.stdin.isTTY) {
|
|
808
|
+
console.log(` Install it with: ${shown}`);
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
812
|
+
const answer = (await rl.question(yellow(` Install it now with "${shown}"? [Y/n] `))).trim().toLowerCase();
|
|
813
|
+
rl.close();
|
|
814
|
+
if (answer && !["y", "yes", "o", "oui"].includes(answer))
|
|
815
|
+
return;
|
|
816
|
+
const r = spawnSync(cmd[0], cmd.slice(1), { stdio: "inherit", shell: IS_WINDOWS });
|
|
817
|
+
if (r.status !== 0)
|
|
818
|
+
console.log(` Installation failed${r.error ? `: ${r.error.message}` : ""}.`);
|
|
819
|
+
dotPath = findDot();
|
|
820
|
+
if (dotPath)
|
|
821
|
+
console.log(` Graphviz installed (${dotPath}).`);
|
|
822
|
+
else if (r.status === 0)
|
|
823
|
+
console.log(" Graphviz is installed, but \"dot\" is not found yet: open a new terminal and run again.");
|
|
824
|
+
}
|
|
825
|
+
/** Does this markdown use `@graph` (outside code blocks)? */
|
|
826
|
+
function usesGraph(src) {
|
|
827
|
+
let fenced = false;
|
|
828
|
+
for (const line of readFileSync(src, "utf8").split(/\r?\n/)) {
|
|
829
|
+
const s = line.trim();
|
|
830
|
+
if (s.startsWith("```"))
|
|
831
|
+
fenced = !fenced;
|
|
832
|
+
else if (!fenced && s.startsWith("@graph"))
|
|
833
|
+
return true;
|
|
477
834
|
}
|
|
835
|
+
return false;
|
|
836
|
+
}
|
|
837
|
+
/** An argument as typed in a shell, quoted when needed. */
|
|
838
|
+
function shellArg(arg) {
|
|
839
|
+
return /^[\w@%+=:,./#-]+$/.test(arg) ? arg : `"${arg.replace(/(["\\$`])/g, "\\$1")}"`;
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Index just after the `{` opening the body of the root graph of a DOT source
|
|
843
|
+
* (skipping comments and quoted strings), or -1 if there is none.
|
|
844
|
+
*/
|
|
845
|
+
function dotBodyStart(dot) {
|
|
846
|
+
let i = 0;
|
|
847
|
+
let lineStart = true;
|
|
848
|
+
while (i < dot.length) {
|
|
849
|
+
const c = dot[i];
|
|
850
|
+
if (lineStart && c === "#") {
|
|
851
|
+
// Preprocessor-like line, ignored by Graphviz.
|
|
852
|
+
const end = dot.indexOf("\n", i);
|
|
853
|
+
i = end < 0 ? dot.length : end;
|
|
854
|
+
continue;
|
|
855
|
+
}
|
|
856
|
+
if (c === "\n")
|
|
857
|
+
lineStart = true;
|
|
858
|
+
else if (!/\s/.test(c))
|
|
859
|
+
lineStart = false;
|
|
860
|
+
if (c === "/" && dot[i + 1] === "/") {
|
|
861
|
+
const end = dot.indexOf("\n", i);
|
|
862
|
+
i = end < 0 ? dot.length : end;
|
|
863
|
+
continue;
|
|
864
|
+
}
|
|
865
|
+
if (c === "/" && dot[i + 1] === "*") {
|
|
866
|
+
const end = dot.indexOf("*/", i + 2);
|
|
867
|
+
i = end < 0 ? dot.length : end + 2;
|
|
868
|
+
continue;
|
|
869
|
+
}
|
|
870
|
+
if (c === '"') {
|
|
871
|
+
i++;
|
|
872
|
+
while (i < dot.length && dot[i] !== '"')
|
|
873
|
+
i += dot[i] === "\\" ? 2 : 1;
|
|
874
|
+
i++;
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
if (c === "<") {
|
|
878
|
+
// HTML-like ID: balanced angle brackets.
|
|
879
|
+
let depth = 0;
|
|
880
|
+
do {
|
|
881
|
+
if (dot[i] === "<")
|
|
882
|
+
depth++;
|
|
883
|
+
else if (dot[i] === ">")
|
|
884
|
+
depth--;
|
|
885
|
+
i++;
|
|
886
|
+
} while (i < dot.length && depth > 0);
|
|
887
|
+
continue;
|
|
888
|
+
}
|
|
889
|
+
if (c === "{")
|
|
890
|
+
return i + 1;
|
|
891
|
+
i++;
|
|
892
|
+
}
|
|
893
|
+
return -1;
|
|
894
|
+
}
|
|
895
|
+
/** A DOT attribute list: `[a="x", b="y"]`. */
|
|
896
|
+
function dotAttrs(attrs) {
|
|
897
|
+
return `[${Object.entries(attrs)
|
|
898
|
+
.map(([k, v]) => `${k}="${String(v).replace(/(["\\])/g, "\\$1")}"`)
|
|
899
|
+
.join(", ")}]`;
|
|
478
900
|
}
|
|
479
901
|
/**
|
|
480
|
-
*
|
|
481
|
-
*
|
|
482
|
-
*
|
|
902
|
+
* Render a .dot file as PNG with Graphviz (its own Cairo renderer, as in DOT viewers:
|
|
903
|
+
* LibreOffice's SVG import changes the look of Graphviz SVGs), using the fonts and colors of the
|
|
904
|
+
* current style. They are inserted as `graph`/`node`/`edge` default statements at the very
|
|
905
|
+
* beginning of the root graph body, so every attribute set in the .dot file (including its own
|
|
906
|
+
* `node [...]` / `edge [...]` defaults) still takes precedence. They are NOT given on the command
|
|
907
|
+
* line: Graphviz's `-N`/`-E` options override the defaults declared in the file.
|
|
908
|
+
* The resolution is `theme.graph.dpi`.
|
|
483
909
|
*/
|
|
484
|
-
function
|
|
485
|
-
if (!
|
|
486
|
-
throw new Error(
|
|
910
|
+
function graphPng(path) {
|
|
911
|
+
if (!dotPath)
|
|
912
|
+
throw new Error(`${path}: the Graphviz "dot" tool is required by @graph (https://graphviz.org/download/)`);
|
|
487
913
|
const font = style.theme.fonts.sans.replace(/'/g, "");
|
|
488
|
-
const
|
|
489
|
-
|
|
490
|
-
`edge [fontname="${font}", fontsize=${sizes.graphEdgeText}]; `;
|
|
914
|
+
const { colors } = style.theme;
|
|
915
|
+
const dpi = style.theme.graph.dpi;
|
|
491
916
|
const source = readFileSync(path, "utf8");
|
|
492
|
-
const
|
|
493
|
-
if (
|
|
494
|
-
throw new Error(`${path}: no "graph { ... }" or "digraph { ... }"
|
|
495
|
-
const
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
917
|
+
const at = dotBodyStart(source);
|
|
918
|
+
if (at < 0)
|
|
919
|
+
throw new Error(`${path}: no graph body found (expected "graph { ... }" or "digraph { ... }")`);
|
|
920
|
+
const defaults = [
|
|
921
|
+
`graph ${dotAttrs({
|
|
922
|
+
bgcolor: "transparent",
|
|
923
|
+
fontname: font,
|
|
924
|
+
fontsize: sizes.graphEdgeText,
|
|
925
|
+
fontcolor: colors.primary,
|
|
926
|
+
style: "filled",
|
|
927
|
+
fillcolor: colors.graphCluster,
|
|
928
|
+
pencolor: colors.muted,
|
|
929
|
+
})};`,
|
|
930
|
+
`node ${dotAttrs({
|
|
931
|
+
fontname: font,
|
|
932
|
+
fontsize: sizes.graphText,
|
|
933
|
+
fontcolor: colors.ink,
|
|
934
|
+
style: "filled",
|
|
935
|
+
fillcolor: colors.graphNode,
|
|
936
|
+
color: colors.primary,
|
|
937
|
+
})};`,
|
|
938
|
+
`edge ${dotAttrs({
|
|
939
|
+
fontname: font,
|
|
940
|
+
fontsize: sizes.graphEdgeText,
|
|
941
|
+
fontcolor: colors.ink,
|
|
942
|
+
color: colors.ink,
|
|
943
|
+
})};`,
|
|
944
|
+
].join(" ");
|
|
945
|
+
const input = `${source.slice(0, at)} ${defaults}\n${source.slice(at)}`;
|
|
946
|
+
// The dpi stays on the command line: it is not a matter of style, the file must not change it.
|
|
947
|
+
const args = ["-Tpng", `-Gdpi=${dpi}`];
|
|
948
|
+
const key = [...args, input].join("\0");
|
|
949
|
+
let graph = graphCache.get(key);
|
|
950
|
+
if (graph)
|
|
951
|
+
return graph;
|
|
952
|
+
console.log(` ${bold(cyan("> "))}${bold([dotPath, ...args].map(shellArg).join(" "))} < ${shellArg(path)} ${cyan("(with the theme defaults)")}`);
|
|
953
|
+
const r = spawnSync(dotPath, args, { input, maxBuffer: 256 * 1024 * 1024 });
|
|
954
|
+
if (r.error || r.status !== 0) {
|
|
955
|
+
throw new Error(`Graphviz failed on ${path}: ${r.error?.message ?? r.stderr.toString("utf8").trim()}`);
|
|
506
956
|
}
|
|
507
|
-
const
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
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];
|
|
957
|
+
const png = r.stdout;
|
|
958
|
+
if (png.length < 24 || png.readUInt32BE(0) !== 0x89504e47)
|
|
959
|
+
throw new Error(`Graphviz did not produce a PNG for ${path}`);
|
|
960
|
+
const cmPerPixel = 2.54 / dpi;
|
|
961
|
+
graph = { png, size: [png.readUInt32BE(16) * cmPerPixel, png.readUInt32BE(20) * cmPerPixel] };
|
|
962
|
+
graphCache.set(key, graph);
|
|
963
|
+
return graph;
|
|
609
964
|
}
|
|
610
965
|
// ---------------------------------------------------------------- layout
|
|
611
966
|
const MIME = {
|
|
@@ -615,32 +970,74 @@ const MIME = {
|
|
|
615
970
|
".jpg": "image/jpeg",
|
|
616
971
|
".jpeg": "image/jpeg",
|
|
617
972
|
};
|
|
973
|
+
/**
|
|
974
|
+
* Encode the pictures as WebP (`theme.images.quality`), shrunk so that their longest side
|
|
975
|
+
* is at most `theme.images.maxSize` pixels. SVG images are rasterized at that size too.
|
|
976
|
+
* A WebP already small enough is kept as is, to avoid losing quality twice.
|
|
977
|
+
*/
|
|
978
|
+
async function encodePictures(pics) {
|
|
979
|
+
const { quality, maxSize } = style.theme.images;
|
|
980
|
+
await Promise.all(pics.map(async (pic) => {
|
|
981
|
+
const input = pic.data;
|
|
982
|
+
const isSvg = /^\s*(<\?xml|<svg|<!--|<!DOCTYPE)/i.test(input.subarray(0, 256).toString("utf8"));
|
|
983
|
+
let density;
|
|
984
|
+
if (isSvg) {
|
|
985
|
+
// Rasterize at maxSize pixels for the longest side (72 dpi = 1 SVG unit per pixel).
|
|
986
|
+
const longest = Math.max(pic.size[0], pic.size[1], 1);
|
|
987
|
+
density = Math.min(Math.max((72 * maxSize) / longest, 1), 100000);
|
|
988
|
+
}
|
|
989
|
+
const img = sharp(input, { density, limitInputPixels: false });
|
|
990
|
+
const meta = await img.metadata();
|
|
991
|
+
const big = Math.max(meta.width ?? 0, meta.height ?? 0) > maxSize;
|
|
992
|
+
if (meta.format === "webp" && !big)
|
|
993
|
+
return;
|
|
994
|
+
pic.data = await img
|
|
995
|
+
.rotate() // apply the EXIF orientation of photos
|
|
996
|
+
.resize({ width: maxSize, height: maxSize, fit: "inside", withoutEnlargement: true })
|
|
997
|
+
.webp({ quality })
|
|
998
|
+
.toBuffer();
|
|
999
|
+
}));
|
|
1000
|
+
}
|
|
618
1001
|
const f2 = (n) => n.toFixed(2);
|
|
1002
|
+
/**
|
|
1003
|
+
* The content of one slide, once per step of its `@reveal` tables: the first step shows their
|
|
1004
|
+
* header and their always visible cells, each following step reveals one more row (tables in
|
|
1005
|
+
* the order of the slide, rows in reading order). Rows with nothing to reveal are skipped.
|
|
1006
|
+
*/
|
|
1007
|
+
function revealSteps(content) {
|
|
1008
|
+
const order = content.flatMap(b => b.t === "table" && b.reveal ? b.rows.filter(r => !b.reveal.rows.has(r) && r.some((c, i) => c !== "" && !b.reveal.cols.has(i))) : []);
|
|
1009
|
+
if (!content.some(b => b.t === "table" && b.reveal))
|
|
1010
|
+
return [content];
|
|
1011
|
+
return Array.from({ length: order.length + 1 }, (_, k) => {
|
|
1012
|
+
const shown = new Set(order.slice(0, k));
|
|
1013
|
+
return content.map(b => (b.t === "table" && b.reveal ? { ...b, shown } : b));
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
619
1016
|
class Builder {
|
|
620
1017
|
base;
|
|
621
1018
|
pictures = new Map();
|
|
622
1019
|
pages = [];
|
|
623
1020
|
colStyles = new Map();
|
|
624
1021
|
rowStyles = new Map();
|
|
1022
|
+
paraStyles = new Map();
|
|
625
1023
|
/** Hints waiting to be attached to the next slide title. */
|
|
626
1024
|
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
1025
|
constructor(base) {
|
|
633
1026
|
this.base = base;
|
|
1027
|
+
mdDir = base;
|
|
1028
|
+
cellCache.clear();
|
|
634
1029
|
}
|
|
635
1030
|
// -- resources
|
|
636
1031
|
picture(src) {
|
|
637
1032
|
let pic = this.pictures.get(src);
|
|
638
1033
|
if (!pic) {
|
|
639
1034
|
const path = resolve(this.base, src);
|
|
640
|
-
|
|
1035
|
+
const isGraph = extname(src).toLowerCase() === ".dot";
|
|
1036
|
+
let name = `${basename(src, extname(src))}.webp`;
|
|
641
1037
|
while ([...this.pictures.values()].some(p => p.href === `Pictures/${name}`))
|
|
642
1038
|
name = `_${name}`;
|
|
643
|
-
|
|
1039
|
+
const graph = isGraph ? graphPng(path) : null;
|
|
1040
|
+
pic = { href: `Pictures/${name}`, data: graph ? graph.png : readFileSync(path), size: graph ? graph.size : imageSize(path) };
|
|
644
1041
|
this.pictures.set(src, pic);
|
|
645
1042
|
}
|
|
646
1043
|
return pic;
|
|
@@ -651,6 +1048,16 @@ class Builder {
|
|
|
651
1048
|
this.colStyles.set(key, `co${this.colStyles.size + 1}`);
|
|
652
1049
|
return this.colStyles.get(key);
|
|
653
1050
|
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Automatic paragraph style setting the font size (in points) of a `@compact` table,
|
|
1053
|
+
* and the left margin (in cm) leaving room for the images of a cell.
|
|
1054
|
+
*/
|
|
1055
|
+
paraStyle(pt, indent = 0) {
|
|
1056
|
+
const key = indent ? `${f2(pt)}/${f2(indent)}` : f2(pt);
|
|
1057
|
+
if (!this.paraStyles.has(key))
|
|
1058
|
+
this.paraStyles.set(key, `Pt${this.paraStyles.size + 1}`);
|
|
1059
|
+
return this.paraStyles.get(key);
|
|
1060
|
+
}
|
|
654
1061
|
rowStyle(h) {
|
|
655
1062
|
const key = f2(h);
|
|
656
1063
|
if (!this.rowStyles.has(key))
|
|
@@ -675,29 +1082,51 @@ class Builder {
|
|
|
675
1082
|
this.pendingHints = [];
|
|
676
1083
|
return desc;
|
|
677
1084
|
}
|
|
678
|
-
|
|
1085
|
+
/**
|
|
1086
|
+
* Lists of a frame using the style `frameStyle`. Bullet-only lists take their bullets from that
|
|
1087
|
+
* style. Lists with numbered items name the list styles `<frameStyle>-numbers` and
|
|
1088
|
+
* `<frameStyle>-bullets` (see `listStylesXml()`) on every nested list.
|
|
1089
|
+
*/
|
|
1090
|
+
listXml(items, frameStyle) {
|
|
1091
|
+
const holder = listStyleHolder(frameStyle);
|
|
1092
|
+
const styled = holder !== null && items.some(it => it[2] !== undefined);
|
|
679
1093
|
const out = [];
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
1094
|
+
// For each open list: is it numbered?
|
|
1095
|
+
const open = [];
|
|
1096
|
+
const close = () => {
|
|
1097
|
+
out.push("</text:list-item></text:list>");
|
|
1098
|
+
open.pop();
|
|
1099
|
+
};
|
|
1100
|
+
for (const [lvl, txt, num] of items) {
|
|
1101
|
+
const ordered = num !== undefined;
|
|
1102
|
+
while (open.length > lvl + 1)
|
|
1103
|
+
close();
|
|
1104
|
+
if (open.length === lvl + 1) {
|
|
1105
|
+
if (open[lvl] === ordered)
|
|
1106
|
+
out.push("</text:list-item><text:list-item>");
|
|
1107
|
+
else
|
|
1108
|
+
close();
|
|
685
1109
|
}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
out.push(
|
|
690
|
-
|
|
1110
|
+
while (open.length < lvl + 1) {
|
|
1111
|
+
const name = styled ? ` text:style-name="${esc(holder)}-${ordered ? "numbers" : "bullets"}"` : "";
|
|
1112
|
+
const start = ordered && open.length === lvl && num !== 1 ? ` text:start-value="${num}"` : "";
|
|
1113
|
+
out.push(`<text:list${name}><text:list-item${start}>`);
|
|
1114
|
+
open.push(ordered);
|
|
691
1115
|
}
|
|
692
1116
|
out.push(`<text:p>${runsXml(txt)}</text:p>`);
|
|
693
1117
|
}
|
|
694
|
-
while (
|
|
695
|
-
|
|
1118
|
+
while (open.length)
|
|
1119
|
+
close();
|
|
696
1120
|
return out.join("");
|
|
697
1121
|
}
|
|
698
|
-
tableXml(header, rows, x, y, width, pt, small = false, cols) {
|
|
1122
|
+
tableXml(header, rows, x, y, width, pt, small = false, cols, hidden = () => false) {
|
|
699
1123
|
cols ??= tableCols(header, rows, width);
|
|
700
1124
|
const prefix = small ? "Tableau-petit" : "Tableau";
|
|
1125
|
+
// A size other than the one of the cell styles (`@compact`) needs a paragraph style.
|
|
1126
|
+
const defaultPt = pt === (small ? sizes.tableSmall : sizes.table);
|
|
1127
|
+
const para = (indent) => (defaultPt && !indent ? "" : ` text:style-name="${this.paraStyle(pt, indent)}"`);
|
|
1128
|
+
// Images of the cells, drawn over the table: a table cell of Impress only holds text.
|
|
1129
|
+
const overlays = [];
|
|
701
1130
|
const parts = [
|
|
702
1131
|
`<draw:frame draw:style-name="Tableau-cadre" ${Builder.geom(x, y, width, tableH(header, rows, width, pt, cols))}>`,
|
|
703
1132
|
`<table:table table:template-name="${prefix}" table:use-first-row-styles="${header ? "true" : "false"}" table:use-banding-rows-styles="true">`,
|
|
@@ -707,147 +1136,50 @@ class Builder {
|
|
|
707
1136
|
...(header ? [["entete", header]] : []),
|
|
708
1137
|
...rows.map((r, i) => [i % 2 === 0 ? "cellule" : "cellule-alt", r]),
|
|
709
1138
|
];
|
|
1139
|
+
let cy = y;
|
|
710
1140
|
for (const [kind, r] of all) {
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
1141
|
+
const rh = rowH(r, cols, pt);
|
|
1142
|
+
parts.push(`<table:table-row table:style-name="${this.rowStyle(rh)}">`);
|
|
1143
|
+
let cx = x;
|
|
1144
|
+
cols.forEach((cw, i) => {
|
|
1145
|
+
// A hidden cell keeps the size of its content, so the table does not move when it shows up.
|
|
1146
|
+
const c = kind !== "entete" && hidden(r, i) ? { text: "", imgs: [] } : cell(r[i] ?? "");
|
|
1147
|
+
const indent = cellTextIndent(c, cw, pt);
|
|
1148
|
+
parts.push(`<table:table-cell table:style-name="${prefix}-${kind}"><text:p${para(indent)}>${runsXml(c.text)}</text:p></table:table-cell>`);
|
|
1149
|
+
if (c.imgs.length) {
|
|
1150
|
+
const [scale, iw] = cellImgBox(c, cw, pt);
|
|
1151
|
+
const em = pt * PT * scale;
|
|
1152
|
+
// Alone in its cell, an image is centered; otherwise it comes before the text.
|
|
1153
|
+
let ix = c.text ? cx + CELL_PAD_X / 2 : cx + (cw - iw) / 2;
|
|
1154
|
+
for (const img of c.imgs) {
|
|
1155
|
+
const [w, h] = [img.w * em, img.h * em];
|
|
1156
|
+
overlays.push(this.imageXml(img.src, ix, cy + (rh - h) / 2, w, h, img.alt));
|
|
1157
|
+
ix += w + IMG_GAP_EM * em;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
cx += cw;
|
|
714
1161
|
});
|
|
715
1162
|
parts.push("</table:table-row>");
|
|
1163
|
+
cy += rh;
|
|
716
1164
|
}
|
|
717
1165
|
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>`;
|
|
1166
|
+
return parts.join("") + overlays.join("");
|
|
755
1167
|
}
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
// Do not blow small diagrams up: text keeps its size, shapes would not.
|
|
1168
|
+
imageXml(src, x, y, w, h, alt = "") {
|
|
1169
|
+
const { href, size } = this.picture(src);
|
|
1170
|
+
// Do not blow small diagrams up: their text would become huge.
|
|
760
1171
|
const maxScale = style.theme.graph.maxScale;
|
|
761
|
-
if (w >
|
|
762
|
-
const [fw, fh] = fit(
|
|
1172
|
+
if (extname(src).toLowerCase() === ".dot" && w > size[0] * maxScale) {
|
|
1173
|
+
const [fw, fh] = fit(size[0], size[1], size[0] * maxScale, size[1] * maxScale);
|
|
763
1174
|
x += (w - fw) / 2;
|
|
764
1175
|
y += (h - fh) / 2;
|
|
765
1176
|
w = fw;
|
|
766
1177
|
h = fh;
|
|
767
1178
|
}
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
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("");
|
|
1179
|
+
return (`<draw:frame draw:style-name="Image" ${Builder.geom(x, y, w, h)}>` +
|
|
1180
|
+
`<draw:image xlink:href="${esc(href)}" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>` +
|
|
1181
|
+
(alt ? `<svg:title>${esc(alt)}</svg:title>` : "") +
|
|
1182
|
+
`</draw:frame>`);
|
|
851
1183
|
}
|
|
852
1184
|
promptXml(lines, x, y, w, h, style = "Prompt") {
|
|
853
1185
|
const paras = lines.map(l => `<text:p>${xmlText(l)}</text:p>`).join("");
|
|
@@ -860,7 +1192,7 @@ class Builder {
|
|
|
860
1192
|
case "para":
|
|
861
1193
|
return this.frame("Texte", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
|
|
862
1194
|
case "list":
|
|
863
|
-
return this.frame("
|
|
1195
|
+
return this.frame("Master-outline1", x, y, w, h, this.listXml(b.items, "Master-outline1"), "outline");
|
|
864
1196
|
case "quote":
|
|
865
1197
|
return this.frame("Citation", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
|
|
866
1198
|
case "prompt":
|
|
@@ -869,8 +1201,11 @@ class Builder {
|
|
|
869
1201
|
return this.promptXml(b.lines, x + w - pw, y, pw, h, b.t === "prompt" ? "Prompt" : "Code");
|
|
870
1202
|
}
|
|
871
1203
|
case "table": {
|
|
872
|
-
const
|
|
873
|
-
|
|
1204
|
+
const pw = tablePartW(b, w);
|
|
1205
|
+
const cols = tableBlockCols(b, w);
|
|
1206
|
+
return tableParts(b)
|
|
1207
|
+
.map((rows, i) => this.tableXml(b.header, rows, x + i * (pw + TABLE_GAP), y, pw, b.pt ?? sizes.table, false, cols, (r, c) => isHidden(b, r, c)))
|
|
1208
|
+
.join("");
|
|
874
1209
|
}
|
|
875
1210
|
default:
|
|
876
1211
|
throw new Error(`Unexpected block ${b.t}`);
|
|
@@ -882,16 +1217,17 @@ class Builder {
|
|
|
882
1217
|
const imgs = blocks.filter(b => b.t === "image");
|
|
883
1218
|
const texts = blocks.filter(b => b.t !== "image");
|
|
884
1219
|
const shapes = [];
|
|
885
|
-
const
|
|
886
|
-
|
|
1220
|
+
const sumH = (width) => texts.reduce((h, b) => h + blockH(b, width), 0) + GAP * (texts.length - 1);
|
|
1221
|
+
const stack = (bs, x, width, center = CENTER) => {
|
|
1222
|
+
const top = center ? Y0 + Math.max(0, (H - sumH(width)) / 2) : Y0;
|
|
1223
|
+
let y = top;
|
|
887
1224
|
for (const b of bs) {
|
|
888
1225
|
const bh = blockH(b, width);
|
|
889
1226
|
shapes.push(this.blockXml(b, x, y, width, Math.min(bh, Math.max(Y0 + H - y, 1.5))));
|
|
890
1227
|
y += bh + GAP;
|
|
891
1228
|
}
|
|
892
|
-
return y -
|
|
1229
|
+
return y - top - (bs.length ? GAP : 0);
|
|
893
1230
|
};
|
|
894
|
-
const sumH = (width) => texts.reduce((h, b) => h + blockH(b, width), 0) + GAP * (texts.length - 1);
|
|
895
1231
|
if (!imgs.length)
|
|
896
1232
|
return [stack(texts, X0, W), shapes];
|
|
897
1233
|
const src = imgs[0].src;
|
|
@@ -902,7 +1238,8 @@ class Builder {
|
|
|
902
1238
|
return [0, shapes];
|
|
903
1239
|
}
|
|
904
1240
|
if (iw / ih >= 1.8 || (iw / ih >= 1.2 && sumH(W) < 2.5)) {
|
|
905
|
-
|
|
1241
|
+
// The image below the text takes the free height.
|
|
1242
|
+
const th = stack(texts, X0, W, false);
|
|
906
1243
|
const avail = Math.max(H - th - GAP, 4.5);
|
|
907
1244
|
const [w, h] = fit(iw, ih, W, avail);
|
|
908
1245
|
shapes.push(this.imageXml(src, X0 + (W - w) / 2, Y0 + th + GAP + (avail - h) / 2, w, h));
|
|
@@ -924,12 +1261,20 @@ class Builder {
|
|
|
924
1261
|
slides[slides.length - 1][1].push(b.text);
|
|
925
1262
|
continue;
|
|
926
1263
|
}
|
|
1264
|
+
if (b.t === "table" && (!this.fits([b]) || ((b.compact || b.reveal) && !headerFits(b)))) {
|
|
1265
|
+
// A revealed table must stay on one slide: on two side-by-side tables, or else shrunk.
|
|
1266
|
+
if (b.reveal)
|
|
1267
|
+
this.twoColumns(b, slides) || this.compactTable(b, slides);
|
|
1268
|
+
else if (b.compact)
|
|
1269
|
+
this.compactTable(b, slides);
|
|
1270
|
+
else
|
|
1271
|
+
this.splitTable(b, slides);
|
|
1272
|
+
continue;
|
|
1273
|
+
}
|
|
927
1274
|
const cur = slides[slides.length - 1][0];
|
|
928
1275
|
const hasImg = cur.some(x => x.t === "image");
|
|
929
|
-
if (cur.length && ((b.t === "image" && hasImg) || this.
|
|
930
|
-
|
|
931
|
-
const carry = cur.length > 1 && cur[cur.length - 1].t === "para" ? [cur.pop()] : [];
|
|
932
|
-
slides.push([[...carry, b], []]);
|
|
1276
|
+
if (cur.length && ((b.t === "image" && hasImg) || !this.fits([...cur, b]))) {
|
|
1277
|
+
slides.push([[...this.carry(cur, b), b], []]);
|
|
933
1278
|
}
|
|
934
1279
|
else {
|
|
935
1280
|
cur.push(b);
|
|
@@ -937,6 +1282,111 @@ class Builder {
|
|
|
937
1282
|
}
|
|
938
1283
|
return slides.filter(([c, n]) => c.length || n.length);
|
|
939
1284
|
}
|
|
1285
|
+
/** Do these blocks fit on one slide? */
|
|
1286
|
+
fits(blocks) {
|
|
1287
|
+
// `layout()` registers the automatic styles of the shapes it builds: forget those of this trial.
|
|
1288
|
+
const saved = [new Map(this.colStyles), new Map(this.rowStyles), new Map(this.paraStyles)];
|
|
1289
|
+
const ok = this.layout(blocks)[0] <= H;
|
|
1290
|
+
[this.colStyles, this.rowStyles, this.paraStyles] = saved;
|
|
1291
|
+
return ok;
|
|
1292
|
+
}
|
|
1293
|
+
/**
|
|
1294
|
+
* Keep an introductory paragraph with the block `next` that starts a new slide:
|
|
1295
|
+
* the last paragraph of `cur`, removed from it, if it fits with `next`.
|
|
1296
|
+
*/
|
|
1297
|
+
carry(cur, next) {
|
|
1298
|
+
const last = cur[cur.length - 1];
|
|
1299
|
+
return cur.length > 1 && last.t === "para" && this.fits([last, next]) ? [cur.pop()] : [];
|
|
1300
|
+
}
|
|
1301
|
+
/**
|
|
1302
|
+
* A `@compact` table too long for one slide: its text is shrunk (by steps of half a point)
|
|
1303
|
+
* until it fits on a slide with the paragraph introducing it, if any. It stays on the current
|
|
1304
|
+
* slide if it fits there at that size, otherwise it starts a new one with its introduction.
|
|
1305
|
+
*/
|
|
1306
|
+
compactTable(b, slides) {
|
|
1307
|
+
const MIN_PT = 4;
|
|
1308
|
+
const cur = slides[slides.length - 1][0];
|
|
1309
|
+
const last = cur[cur.length - 1];
|
|
1310
|
+
const intro = last?.t === "para" ? [last] : [];
|
|
1311
|
+
const shrink = (t) => {
|
|
1312
|
+
let small = t;
|
|
1313
|
+
for (let pt = sizes.table - 0.5; pt >= MIN_PT; pt -= 0.5) {
|
|
1314
|
+
small = { ...t, pt };
|
|
1315
|
+
if (this.fits([...intro, small]) && headerFits(small))
|
|
1316
|
+
break;
|
|
1317
|
+
}
|
|
1318
|
+
return small;
|
|
1319
|
+
};
|
|
1320
|
+
let small = shrink(b);
|
|
1321
|
+
// A revealed table can also be spread over two side-by-side tables, if its text stays bigger.
|
|
1322
|
+
if (b.reveal && b.rows.length > 1) {
|
|
1323
|
+
const two = shrink({ ...b, columns: 2 });
|
|
1324
|
+
const ok = (t) => this.fits([t]) && headerFits(t);
|
|
1325
|
+
if ((two.pt ?? sizes.table) > (small.pt ?? sizes.table) || !ok(small))
|
|
1326
|
+
small = two;
|
|
1327
|
+
}
|
|
1328
|
+
const pragma = b.reveal ? "@reveal" : "@compact";
|
|
1329
|
+
if (!this.fits([small]))
|
|
1330
|
+
console.warn(` ! a ${pragma} table is still too long at ${MIN_PT}pt: it overflows its slide`);
|
|
1331
|
+
else if (!headerFits(small))
|
|
1332
|
+
console.warn(` ! a ${pragma} table still has header words too long for their column at ${MIN_PT}pt`);
|
|
1333
|
+
if (!cur.length || this.fits([...cur, small]))
|
|
1334
|
+
return void cur.push(small);
|
|
1335
|
+
const carry = cur.length > 1 && intro.length && this.fits([...intro, small]) ? [cur.pop()] : [];
|
|
1336
|
+
slides.push([[...carry, small], []]);
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* Spread the rows of a table over two side-by-side tables, if they fit on one slide: on the
|
|
1340
|
+
* current slide if there is room, otherwise on a new one. Return false if they do not fit.
|
|
1341
|
+
*/
|
|
1342
|
+
twoColumns(b, slides) {
|
|
1343
|
+
if (b.rows.length < 2)
|
|
1344
|
+
return false;
|
|
1345
|
+
const cur = slides[slides.length - 1][0];
|
|
1346
|
+
const two = { ...b, columns: 2 };
|
|
1347
|
+
// Narrower columns must not cut the words of the header of a `@compact` or `@reveal` table.
|
|
1348
|
+
if ((b.compact || b.reveal) && !headerFits(two))
|
|
1349
|
+
return false;
|
|
1350
|
+
if (cur.length && this.fits([...cur, two]))
|
|
1351
|
+
cur.push(two);
|
|
1352
|
+
else if (!this.fits([two]))
|
|
1353
|
+
return false;
|
|
1354
|
+
else if (!cur.length)
|
|
1355
|
+
cur.push(two);
|
|
1356
|
+
else
|
|
1357
|
+
slides.push([[...this.carry(cur, two), two], []]);
|
|
1358
|
+
return true;
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* A table too long for one slide: its rows are spread over two side-by-side tables if they fit
|
|
1362
|
+
* on one slide, otherwise over several slides. The header is repeated on each part.
|
|
1363
|
+
*/
|
|
1364
|
+
splitTable(b, slides) {
|
|
1365
|
+
if (this.twoColumns(b, slides))
|
|
1366
|
+
return;
|
|
1367
|
+
const cur = () => slides[slides.length - 1][0];
|
|
1368
|
+
const ref = b.rows;
|
|
1369
|
+
let rest = b.rows;
|
|
1370
|
+
while (rest.length) {
|
|
1371
|
+
const part = (k) => ({ ...b, rows: rest.slice(0, k), ref });
|
|
1372
|
+
const c = cur();
|
|
1373
|
+
let k = 0;
|
|
1374
|
+
while (k < rest.length && this.fits([...c, part(k + 1)]))
|
|
1375
|
+
k++;
|
|
1376
|
+
if (!k && c.length) {
|
|
1377
|
+
// Not even one row fits under the current content: start on a new slide.
|
|
1378
|
+
const last = c[c.length - 1];
|
|
1379
|
+
slides.push([c.length > 1 && last.t === "para" ? [c.pop()] : [], []]);
|
|
1380
|
+
continue;
|
|
1381
|
+
}
|
|
1382
|
+
// A single row taller than the slide still has to go somewhere.
|
|
1383
|
+
k = Math.max(k, 1);
|
|
1384
|
+
c.push(part(k));
|
|
1385
|
+
rest = rest.slice(k);
|
|
1386
|
+
if (rest.length)
|
|
1387
|
+
slides.push([[], []]);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
940
1390
|
// -- pages
|
|
941
1391
|
page(master, shapes, notes = []) {
|
|
942
1392
|
this.pages.push({ master, shapes, notes });
|
|
@@ -945,67 +1395,48 @@ class Builder {
|
|
|
945
1395
|
const out = [];
|
|
946
1396
|
if (crumbs.length)
|
|
947
1397
|
out.push(this.frame("Fil-ariane", X0, 0.35, W, 0.6, `<text:p>${xmlText(crumbs.join(" › "))}</text:p>`));
|
|
948
|
-
out.push(this.frame("
|
|
1398
|
+
out.push(this.frame("Master-title", X0, 0.95, W, 1.6, `<text:p>${xmlText(title)}</text:p>`, "title", this.takeHints()));
|
|
949
1399
|
return out;
|
|
950
1400
|
}
|
|
951
1401
|
sectionPage(sec) {
|
|
952
|
-
|
|
953
|
-
const
|
|
954
|
-
|
|
955
|
-
|
|
1402
|
+
// The big title is always the top-level (`#`) heading; deeper headings go in the subtitle.
|
|
1403
|
+
const [title, ...rest] = sec.path();
|
|
1404
|
+
const shapes = [this.frame("Section-title", 2, 5, 24, 3.5, `<text:p>${xmlText(title)}</text:p>`, "title", this.takeHints())];
|
|
1405
|
+
if (rest.length)
|
|
1406
|
+
shapes.push(this.frame("Section-subtitle", 2, 8.8, 24, 1.5, `<text:p>${xmlText(rest.join(" › "))}</text:p>`, "subtitle"));
|
|
956
1407
|
const notes = sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : []));
|
|
957
1408
|
this.page("Section", shapes, notes);
|
|
958
1409
|
}
|
|
959
1410
|
contentPages(title, crumbs, blocks) {
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
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));
|
|
1411
|
+
// Notes not attached to a slide yet: they go to the next one.
|
|
1412
|
+
const pending = [];
|
|
1413
|
+
let run = [];
|
|
1414
|
+
const flush = () => {
|
|
1415
|
+
for (const [content, notes] of this.paginate(run)) {
|
|
1416
|
+
if (!content.length) {
|
|
1417
|
+
pending.push(...notes);
|
|
1418
|
+
continue;
|
|
1419
|
+
}
|
|
1420
|
+
const allNotes = [...pending.splice(0), ...notes];
|
|
1421
|
+
for (const step of revealSteps(content)) {
|
|
1422
|
+
const [, shapes] = this.layout(step);
|
|
1423
|
+
this.page("Master", [...this.titleShapes(title, crumbs), ...shapes], [...allNotes]);
|
|
1004
1424
|
}
|
|
1005
1425
|
}
|
|
1006
|
-
|
|
1007
|
-
|
|
1426
|
+
run = [];
|
|
1427
|
+
};
|
|
1428
|
+
// An `@layout` of blocks gets its own slide, between the slides of the blocks around it.
|
|
1429
|
+
for (const b of blocks) {
|
|
1430
|
+
if (b.t !== "layout")
|
|
1431
|
+
run.push(b);
|
|
1432
|
+
else if (b.cells.length) {
|
|
1433
|
+
flush();
|
|
1434
|
+
this.layoutPage(title, crumbs, b.cells, b.layout, pending.splice(0));
|
|
1435
|
+
}
|
|
1008
1436
|
}
|
|
1437
|
+
flush();
|
|
1438
|
+
if (pending.length)
|
|
1439
|
+
this.pages[this.pages.length - 1].notes.push(...pending);
|
|
1009
1440
|
}
|
|
1010
1441
|
/** Height of a group of paragraphs/lists rendered at `pt` points. */
|
|
1011
1442
|
static textGroupH(blocks, width, pt) {
|
|
@@ -1033,7 +1464,7 @@ class Builder {
|
|
|
1033
1464
|
const ncol = Math.max(...all.map(r => r.length));
|
|
1034
1465
|
let tw = 0;
|
|
1035
1466
|
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;
|
|
1467
|
+
tw += Math.max(...all.map(r => Math.min(plainLen(cell(r[c] ?? "").text), 30))) * cw(sizes.tableSmall) + 0.6;
|
|
1037
1468
|
w = Math.max(w, tw);
|
|
1038
1469
|
}
|
|
1039
1470
|
else if (b.t === "image") {
|
|
@@ -1049,7 +1480,7 @@ class Builder {
|
|
|
1049
1480
|
cellXml(sec, x, y, w, h, textStyle, textPt) {
|
|
1050
1481
|
const items = [];
|
|
1051
1482
|
for (const b of sec.blocks) {
|
|
1052
|
-
if (b.t === "note")
|
|
1483
|
+
if (b.t === "note" || b.t === "layout")
|
|
1053
1484
|
continue;
|
|
1054
1485
|
const last = items[items.length - 1];
|
|
1055
1486
|
if (b.t === "para" || b.t === "list" || b.t === "quote") {
|
|
@@ -1103,7 +1534,7 @@ class Builder {
|
|
|
1103
1534
|
const ih = Math.max(0.5, Math.min(heights[i], y + h - cy));
|
|
1104
1535
|
if (it.kind === "text") {
|
|
1105
1536
|
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>` : ""))
|
|
1537
|
+
.map(b => (b.t === "list" ? this.listXml(b.items, textStyle) : b.t === "para" || b.t === "quote" ? `<text:p>${runsXml(b.text)}</text:p>` : ""))
|
|
1107
1538
|
.join("");
|
|
1108
1539
|
shapes.push(this.frame(textStyle, x, cy, w, ih, inner));
|
|
1109
1540
|
}
|
|
@@ -1128,9 +1559,8 @@ class Builder {
|
|
|
1128
1559
|
return shapes;
|
|
1129
1560
|
}
|
|
1130
1561
|
/** Sections laid out on a single slide, following an `@layout` pragma. */
|
|
1131
|
-
layoutPage(
|
|
1132
|
-
const
|
|
1133
|
-
const shapes = this.titleShapes(title, parent.path().slice(0, -1));
|
|
1562
|
+
layoutPage(title, crumbs, group, layout, notes) {
|
|
1563
|
+
const shapes = this.titleShapes(title, crumbs);
|
|
1134
1564
|
const headH = 0.9;
|
|
1135
1565
|
let cells;
|
|
1136
1566
|
if (layout.kind === "grid") {
|
|
@@ -1175,11 +1605,14 @@ class Builder {
|
|
|
1175
1605
|
const [headStyle, textStyle, textPt] = layout.kind === "grid"
|
|
1176
1606
|
? [`Grille-titre-${(n % colors) + 1}`, `Grille-texte-${(n % colors) + 1}`, sizes.gridText]
|
|
1177
1607
|
: ["Colonne-titre", "Colonne-texte", sizes.columnText];
|
|
1178
|
-
|
|
1179
|
-
|
|
1608
|
+
// Cells of an `@layout` of blocks have no heading.
|
|
1609
|
+
const hh = sec.title ? headH : 0;
|
|
1610
|
+
if (sec.title)
|
|
1611
|
+
shapes.push(this.frame(headStyle, x, y, w, hh, `<text:p>${xmlText(sec.title)}</text:p>`));
|
|
1612
|
+
shapes.push(...this.cellXml(sec, x, y + hh, w, h - hh, textStyle, textPt));
|
|
1180
1613
|
notes.push(...sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : [])));
|
|
1181
1614
|
});
|
|
1182
|
-
this.page("
|
|
1615
|
+
this.page("Master", shapes, notes);
|
|
1183
1616
|
}
|
|
1184
1617
|
walk(sec) {
|
|
1185
1618
|
this.pendingHints.push(...sec.hints);
|
|
@@ -1187,14 +1620,11 @@ class Builder {
|
|
|
1187
1620
|
const content = sec.blocks.filter(b => b.t !== "note");
|
|
1188
1621
|
// A section whose only content is a grouped slide does not get its own divider slide.
|
|
1189
1622
|
const groupedOnly = !content.length && sec.children[0]?.layout != null;
|
|
1190
|
-
if (sec.level === 1) {
|
|
1623
|
+
if (sec.level === 1 && !sec.continued) {
|
|
1191
1624
|
this.sectionPage(sec);
|
|
1192
1625
|
if (content.length)
|
|
1193
1626
|
this.contentPages(sec.title, [...crumbs, sec.title], sec.blocks);
|
|
1194
1627
|
}
|
|
1195
|
-
else if (sec.hints.some(h => h.includes("revealed line by line"))) {
|
|
1196
|
-
this.revealTable(sec, crumbs);
|
|
1197
|
-
}
|
|
1198
1628
|
else if (content.length) {
|
|
1199
1629
|
this.contentPages(sec.title, crumbs, sec.blocks);
|
|
1200
1630
|
}
|
|
@@ -1215,7 +1645,8 @@ class Builder {
|
|
|
1215
1645
|
const group = children.slice(i, i + cellCount(layout));
|
|
1216
1646
|
for (const g of group)
|
|
1217
1647
|
this.pendingHints.push(...g.hints);
|
|
1218
|
-
|
|
1648
|
+
const title = sec.level > 0 ? sec.title : group[0].title;
|
|
1649
|
+
this.layoutPage(title, sec.path().slice(0, -1), group, layout, i === 0 ? notes : []);
|
|
1219
1650
|
// Sub-sections of grouped sections still get their own slides.
|
|
1220
1651
|
for (const g of group)
|
|
1221
1652
|
this.walkChildren(g);
|
|
@@ -1253,6 +1684,35 @@ function bulletsXml(def, name) {
|
|
|
1253
1684
|
`</text:list-level-style-bullet>`);
|
|
1254
1685
|
return `<text:list-style style:name="${esc(name)}-list">${levels.join("")}</text:list-style>`;
|
|
1255
1686
|
}
|
|
1687
|
+
/** `name` or its nearest parent style defining both `bullets` and `numbers`, if any. */
|
|
1688
|
+
function listStyleHolder(name) {
|
|
1689
|
+
for (let n = name, depth = 0; n && depth < 20; depth++) {
|
|
1690
|
+
const s = style.styles[n];
|
|
1691
|
+
if (s?.bullets && s.numbers)
|
|
1692
|
+
return n;
|
|
1693
|
+
n = s?.parent;
|
|
1694
|
+
}
|
|
1695
|
+
return null;
|
|
1696
|
+
}
|
|
1697
|
+
/** Level of a numbered list style: `1.`, `a.`, `i.`... */
|
|
1698
|
+
function numbersXml(def, name) {
|
|
1699
|
+
const where = `numbers of style "${name}"`;
|
|
1700
|
+
const levels = def.formats.map((format, i) => `<text:list-level-style-number text:level="${i + 1}" style:num-format="${esc(format)}" style:num-suffix="${esc(def.suffix)}">` +
|
|
1701
|
+
`<style:list-level-properties text:space-before="${f2(def.indent * i)}cm" text:min-label-width="${f2(def.width)}cm"/>` +
|
|
1702
|
+
`<style:text-properties style:use-window-font-color="false" fo:color="${esc(resolveValue(def.color, where))}" ` +
|
|
1703
|
+
`fo:font-size="${esc(resolveValue(def.size, where))}" fo:font-weight="${esc(resolveValue(def.weight, where))}"/>` +
|
|
1704
|
+
`</text:list-level-style-number>`);
|
|
1705
|
+
return `<text:list-style style:name="${esc(name)}-numbers">${levels.join("")}</text:list-style>`;
|
|
1706
|
+
}
|
|
1707
|
+
/**
|
|
1708
|
+
* Named list styles `<name>-bullets` and `<name>-numbers` of a style holding numbered lists:
|
|
1709
|
+
* lists mixing bullets and numbers name them explicitly (see `Builder.listXml()`).
|
|
1710
|
+
*/
|
|
1711
|
+
function listStylesXml(name, s) {
|
|
1712
|
+
if (!s.bullets || !s.numbers)
|
|
1713
|
+
return "";
|
|
1714
|
+
return bulletsXml(s.bullets, name).replace(`style:name="${esc(name)}-list"`, `style:name="${esc(name)}-bullets"`) + numbersXml(s.numbers, name);
|
|
1715
|
+
}
|
|
1256
1716
|
function styleXml(name, s) {
|
|
1257
1717
|
const parent = s.parent ? ` style:parent-style-name="${esc(s.parent)}"` : "";
|
|
1258
1718
|
const list = s.bullets ? bulletsXml(s.bullets, name) : "";
|
|
@@ -1262,7 +1722,35 @@ function styleXml(name, s) {
|
|
|
1262
1722
|
`<style:paragraph-properties ${attrs(s.paragraph, where)}/>` +
|
|
1263
1723
|
`<style:text-properties ${attrs(s.text, where)}/></style:style>`);
|
|
1264
1724
|
}
|
|
1265
|
-
|
|
1725
|
+
const backgroundStyle = (master) => `M${master}-image`;
|
|
1726
|
+
/**
|
|
1727
|
+
* LibreOffice ignores image adjustments (`draw:image-opacity`, `draw:color-mode`...) inherited
|
|
1728
|
+
* from a named style, so the master images get an automatic style repeating them.
|
|
1729
|
+
*/
|
|
1730
|
+
function backgroundStyleXml(master) {
|
|
1731
|
+
const name = `${master}-image`;
|
|
1732
|
+
return (`<style:style style:name="${backgroundStyle(master)}" style:family="graphic" style:parent-style-name="${name}">` +
|
|
1733
|
+
`<style:graphic-properties ${attrs(style.styles[name]?.graphic, `style "${name}"`)}/></style:style>`);
|
|
1734
|
+
}
|
|
1735
|
+
/** Frame of the image of a master page (see `theme.backgrounds`), or "" if it has none. */
|
|
1736
|
+
function backgroundXml(b, master) {
|
|
1737
|
+
const bg = style.theme.backgrounds[master];
|
|
1738
|
+
if (!bg.image)
|
|
1739
|
+
return "";
|
|
1740
|
+
const { href, size } = b.picture(bg.image);
|
|
1741
|
+
let { x = 0, y = 0, width: w = SLIDE_W, height: h = SLIDE_H } = bg;
|
|
1742
|
+
if (bg.fit === "contain") {
|
|
1743
|
+
const scale = Math.min(w / size[0], h / size[1]);
|
|
1744
|
+
x += (w - size[0] * scale) / 2;
|
|
1745
|
+
y += (h - size[1] * scale) / 2;
|
|
1746
|
+
w = size[0] * scale;
|
|
1747
|
+
h = size[1] * scale;
|
|
1748
|
+
}
|
|
1749
|
+
return (`<draw:frame draw:style-name="${backgroundStyle(master)}" ${Builder.geom(x, y, w, h)}>` +
|
|
1750
|
+
`<draw:image xlink:href="${esc(href)}" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>` +
|
|
1751
|
+
`</draw:frame>`);
|
|
1752
|
+
}
|
|
1753
|
+
function stylesXml(b) {
|
|
1266
1754
|
const templates = style.tableTemplates.map(t => `<table:table-template table:name="${esc(t.name)}">` +
|
|
1267
1755
|
`<table:first-row table:style-name="${esc(t.header)}"/>` +
|
|
1268
1756
|
`<table:body table:style-name="${esc(t.body)}"/>` +
|
|
@@ -1276,6 +1764,8 @@ function stylesXml() {
|
|
|
1276
1764
|
`<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
1765
|
`<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
1766
|
`<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>`,
|
|
1767
|
+
backgroundStyleXml("Master"),
|
|
1768
|
+
backgroundStyleXml("Section"),
|
|
1279
1769
|
];
|
|
1280
1770
|
const notes = (m) => `<presentation:notes style:page-layout-name="PM2">` +
|
|
1281
1771
|
`<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"/>` +
|
|
@@ -1283,14 +1773,16 @@ function stylesXml() {
|
|
|
1283
1773
|
`</presentation:notes>`;
|
|
1284
1774
|
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
1775
|
const masters = [
|
|
1286
|
-
`<style:master-page style:name="
|
|
1776
|
+
`<style:master-page style:name="Master" style:page-layout-name="PM1" draw:style-name="Mdp1">` +
|
|
1777
|
+
backgroundXml(b, "Master") +
|
|
1287
1778
|
`<draw:rect draw:style-name="Decor" ${Builder.geom(0, 0, 0.4, SLIDE_H)}/>` +
|
|
1288
1779
|
`<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("
|
|
1290
|
-
placeholder("
|
|
1291
|
-
`${notes("
|
|
1780
|
+
placeholder("Master-title", "title", X0, 0.95, W, 1.6) +
|
|
1781
|
+
placeholder("Master-outline1", "outline", X0, Y0, W, H) +
|
|
1782
|
+
`${notes("Master")}</style:master-page>`,
|
|
1292
1783
|
`<style:master-page style:name="Section" style:page-layout-name="PM1" draw:style-name="Mdp1">` +
|
|
1293
1784
|
`<draw:rect draw:style-name="Section-fond" ${Builder.geom(0, 0, SLIDE_W, SLIDE_H)}/>` +
|
|
1785
|
+
backgroundXml(b, "Section") +
|
|
1294
1786
|
`<draw:rect draw:style-name="Decor" ${Builder.geom(0, 8.55, SLIDE_W, 0.12)}/>` +
|
|
1295
1787
|
placeholder("Section-title", "title", 2, 5, 24, 3.5) +
|
|
1296
1788
|
placeholder("Section-subtitle", "subtitle", 2, 8.8, 24, 1.5) +
|
|
@@ -1303,13 +1795,16 @@ function stylesXml() {
|
|
|
1303
1795
|
}
|
|
1304
1796
|
function contentXml(b) {
|
|
1305
1797
|
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>`);
|
|
1798
|
+
// Impress only finds the list styles named by `<text:list>` among the automatic styles.
|
|
1799
|
+
for (const [name, s] of Object.entries(style.styles))
|
|
1800
|
+
auto.push(listStylesXml(name, s));
|
|
1306
1801
|
for (const [key, name] of b.colStyles)
|
|
1307
1802
|
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
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1803
|
+
for (const [key, name] of b.paraStyles) {
|
|
1804
|
+
const [pt, indent] = key.split("/");
|
|
1805
|
+
const para = indent ? `<style:paragraph-properties fo:margin-left="${indent}cm"/>` : "";
|
|
1806
|
+
auto.push(`<style:style style:name="${name}" style:family="paragraph">${para}<style:text-properties fo:font-size="${pt}pt"/></style:style>`);
|
|
1807
|
+
}
|
|
1313
1808
|
for (const [key, name] of b.rowStyles)
|
|
1314
1809
|
auto.push(`<style:style style:name="${name}" style:family="table-row"><style:table-row-properties style:row-height="${key}cm"/></style:style>`);
|
|
1315
1810
|
const pages = b.pages.map(({ master, shapes, notes }, i) => {
|
|
@@ -1373,8 +1868,12 @@ function zip(entries) {
|
|
|
1373
1868
|
end.writeUInt32LE(offset, 16);
|
|
1374
1869
|
return Buffer.concat([...locals, cd, end]);
|
|
1375
1870
|
}
|
|
1376
|
-
function writeOdp(b, out, title) {
|
|
1871
|
+
async function writeOdp(b, out, title) {
|
|
1872
|
+
// Before listing the pictures: the master pages can add some.
|
|
1873
|
+
const styles = stylesXml(b);
|
|
1874
|
+
const content = contentXml(b);
|
|
1377
1875
|
const pics = [...b.pictures.values()];
|
|
1876
|
+
await encodePictures(pics);
|
|
1378
1877
|
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
1878
|
'<manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.presentation"/>' +
|
|
1380
1879
|
'<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>' +
|
|
@@ -1389,8 +1888,8 @@ function writeOdp(b, out, title) {
|
|
|
1389
1888
|
{ name: "mimetype", data: text("application/vnd.oasis.opendocument.presentation"), store: true },
|
|
1390
1889
|
{ name: "META-INF/manifest.xml", data: text(manifest) },
|
|
1391
1890
|
{ name: "meta.xml", data: text(meta) },
|
|
1392
|
-
{ name: "styles.xml", data: text(
|
|
1393
|
-
{ name: "content.xml", data: text(
|
|
1891
|
+
{ name: "styles.xml", data: text(styles) },
|
|
1892
|
+
{ name: "content.xml", data: text(content) },
|
|
1394
1893
|
...pics.map(p => ({ name: p.href, data: p.data, store: true })),
|
|
1395
1894
|
]));
|
|
1396
1895
|
}
|
|
@@ -1408,13 +1907,13 @@ function humanSize(bytes) {
|
|
|
1408
1907
|
function countHints(sec) {
|
|
1409
1908
|
return sec.hints.length + sec.children.reduce((n, c) => n + countHints(c), 0);
|
|
1410
1909
|
}
|
|
1411
|
-
function convert(src, config) {
|
|
1910
|
+
async function convert(src, config) {
|
|
1412
1911
|
useStyle(config);
|
|
1413
1912
|
const root = parse(readFileSync(src, "utf8"), src);
|
|
1414
1913
|
const b = new Builder(dirname(src));
|
|
1415
1914
|
b.walkChildren(root);
|
|
1416
1915
|
const out = src.replace(/\.md$/i, ".odp");
|
|
1417
|
-
writeOdp(b, out, basename(src, extname(src)));
|
|
1916
|
+
await writeOdp(b, out, basename(src, extname(src)));
|
|
1418
1917
|
return { out, hints: countHints(root) };
|
|
1419
1918
|
}
|
|
1420
1919
|
/** A ready-to-paste prompt asking an AI agent to apply the `@hint` pragmas of the given presentations. */
|
|
@@ -1423,7 +1922,7 @@ function aiPrompt(files) {
|
|
|
1423
1922
|
return [
|
|
1424
1923
|
rule,
|
|
1425
1924
|
`Refine ${files.length > 1 ? "these LibreOffice Impress presentations" : "this LibreOffice Impress presentation"}:`,
|
|
1426
|
-
...files.map(f => ` - ${f}`),
|
|
1925
|
+
...files.map(f => ` - ${bold(f)}`),
|
|
1427
1926
|
"",
|
|
1428
1927
|
"An .odp file is a ZIP archive. In its content.xml, some slide titles carry",
|
|
1429
1928
|
"layout instructions in their alt-text description: <svg:desc> elements whose",
|
|
@@ -1451,7 +1950,11 @@ const PRAGMAS = [
|
|
|
1451
1950
|
["@hint <text>", "Instruction for an AI: stored verbatim in the .odp (alt-text of the slide title), never displayed."],
|
|
1452
1951
|
["@layout grid <C>x<R>", "Put the next C×R sections (starting at the next heading) on one slide, in a grid."],
|
|
1453
1952
|
["@layout columns <sizes>", 'Put the next sections on one slide, in columns sized "1fr", "2fr"... or "auto" (one size per section).'],
|
|
1454
|
-
["@
|
|
1953
|
+
["@layout ... (no heading after)", "Put the next blocks (paragraph, list, image...) of the section on one slide, one per cell, without headings."],
|
|
1954
|
+
["@graph <file.dot>", "Insert a Graphviz diagram (path relative to the .md), rendered as a PNG image by dot."],
|
|
1955
|
+
["@next", "Start a new slide with the same title as the current one (unless a heading follows)."],
|
|
1956
|
+
["@compact", "Shrink the next table so that it fits on one slide, instead of splitting it."],
|
|
1957
|
+
["@reveal [C<cols>] [R<rows>]", 'Reveal the rows of the next table one slide after the other; "C1,3 R1-4" keeps columns 1 and 3 and rows 1 to 4 always visible.'],
|
|
1455
1958
|
["```prompt ... ```", "Not a pragma: a code block shown as a chat prompt bubble."],
|
|
1456
1959
|
];
|
|
1457
1960
|
function printHelp() {
|
|
@@ -1477,22 +1980,23 @@ async function main(args) {
|
|
|
1477
1980
|
const files = args.filter(f => f.toLowerCase().endsWith(".md"));
|
|
1478
1981
|
for (const f of args)
|
|
1479
1982
|
if (!files.includes(f))
|
|
1480
|
-
console.warn(`Ignoring ${f}: not a .md file`);
|
|
1983
|
+
console.warn(`Ignoring ${bold(f)}: not a .md file`);
|
|
1481
1984
|
if (!files.length) {
|
|
1482
1985
|
console.error("No .md file given. Run without arguments for help.");
|
|
1483
1986
|
process.exit(1);
|
|
1484
1987
|
}
|
|
1485
|
-
await loadGraphviz();
|
|
1486
1988
|
const withHints = [];
|
|
1487
1989
|
let failed = false;
|
|
1488
1990
|
for (const file of files) {
|
|
1489
1991
|
const src = resolve(file);
|
|
1490
|
-
console.log(`Processing ${src}`);
|
|
1992
|
+
console.log(`Processing ${bold(src)}`);
|
|
1491
1993
|
try {
|
|
1994
|
+
if (existsSync(src) && usesGraph(src))
|
|
1995
|
+
await ensureDot();
|
|
1492
1996
|
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)})`);
|
|
1997
|
+
console.log(created ? ` + ${bold(path)} (created with the default style)` : ` ⚙ ${bold(path)}`);
|
|
1998
|
+
const { out, hints } = await convert(src, config);
|
|
1999
|
+
console.log(` → ${bold(out)} (${humanSize(statSync(out).size)})`);
|
|
1496
2000
|
if (hints)
|
|
1497
2001
|
withHints.push([out, hints]);
|
|
1498
2002
|
}
|
|
@@ -1505,9 +2009,9 @@ async function main(args) {
|
|
|
1505
2009
|
console.log("\nThese presentations contain @hint pragmas (stored in the slide titles' alt-text descriptions)");
|
|
1506
2010
|
console.log("and can be refined with AI:");
|
|
1507
2011
|
for (const [out, n] of withHints)
|
|
1508
|
-
console.log(` - ${out} (${n} hint${n > 1 ? "s" : ""})`);
|
|
2012
|
+
console.log(` - ${bold(out)} (${n} hint${n > 1 ? "s" : ""})`);
|
|
1509
2013
|
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)));
|
|
2014
|
+
console.log(cyan(aiPrompt(withHints.map(([out]) => out))));
|
|
1511
2015
|
}
|
|
1512
2016
|
if (failed)
|
|
1513
2017
|
process.exit(1);
|