@tolokoban/impress 0.3.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 +69 -22
- package/dist/impress.js +850 -400
- package/dist/styles.js +28 -70
- package/package.json +4 -4
package/dist/impress.js
CHANGED
|
@@ -18,15 +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`).
|
|
22
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
|
|
23
30
|
* ```prompt ... ``` chat prompt bubble
|
|
24
31
|
*/
|
|
25
32
|
import { existsSync, readFileSync, writeFileSync, statSync } from "node:fs";
|
|
26
|
-
import { basename, dirname, extname, resolve } from "node:path";
|
|
33
|
+
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
27
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";
|
|
28
38
|
import { defaultStyle } from "./styles.js";
|
|
29
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");
|
|
30
50
|
// Style of the file being converted (see `useStyle()`).
|
|
31
51
|
let style = defaultStyle;
|
|
32
52
|
let sizes = style.theme.sizes;
|
|
@@ -37,12 +57,14 @@ let Y0 = 0;
|
|
|
37
57
|
let W = 0;
|
|
38
58
|
let H = 0;
|
|
39
59
|
let GAP = 0;
|
|
60
|
+
let CENTER = false;
|
|
40
61
|
function useStyle(config) {
|
|
41
62
|
style = config;
|
|
42
63
|
sizes = config.theme.sizes;
|
|
43
64
|
SLIDE_W = config.theme.slide.width;
|
|
44
65
|
SLIDE_H = config.theme.slide.height;
|
|
45
66
|
({ x: X0, y: Y0, width: W, height: H, gap: GAP } = config.theme.content);
|
|
67
|
+
CENTER = config.theme.content.align === "center";
|
|
46
68
|
}
|
|
47
69
|
function isObject(v) {
|
|
48
70
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -88,6 +110,23 @@ function resolveValue(value, where) {
|
|
|
88
110
|
return String(v);
|
|
89
111
|
});
|
|
90
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
|
+
}
|
|
91
130
|
function cellCount(layout) {
|
|
92
131
|
return layout.kind === "grid" ? layout.columns * layout.rows : layout.widths.length;
|
|
93
132
|
}
|
|
@@ -149,7 +188,8 @@ function stripMd(s) {
|
|
|
149
188
|
.replace(/(?<![\p{L}\p{N}_])\*(.+?)\*(?![\p{L}\p{N}_])/gu, "$1")
|
|
150
189
|
.trim();
|
|
151
190
|
}
|
|
152
|
-
|
|
191
|
+
/** `- item`, `* item`, `1. item` or `1) item`: [indent, number (ordered only), text]. */
|
|
192
|
+
const LIST_RE = /^(\s*)(?:[*-]|(\d+)[.)])\s+(.*)$/;
|
|
153
193
|
const IMG_RE = /^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/;
|
|
154
194
|
const HEAD_RE = /^(#{1,6})\s+(.*)$/;
|
|
155
195
|
function parse(md, file) {
|
|
@@ -159,6 +199,36 @@ function parse(md, file) {
|
|
|
159
199
|
let para = [];
|
|
160
200
|
let list = null;
|
|
161
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
|
+
};
|
|
162
232
|
const flushPara = () => {
|
|
163
233
|
if (!para.length)
|
|
164
234
|
return;
|
|
@@ -168,12 +238,12 @@ function parse(md, file) {
|
|
|
168
238
|
if (j < para.length - 1)
|
|
169
239
|
text += l.endsWith(" ") ? "\n" : " ";
|
|
170
240
|
});
|
|
171
|
-
|
|
241
|
+
push({ t: "para", text });
|
|
172
242
|
para = [];
|
|
173
243
|
};
|
|
174
244
|
const flushList = () => {
|
|
175
245
|
if (list)
|
|
176
|
-
|
|
246
|
+
push(list);
|
|
177
247
|
list = null;
|
|
178
248
|
};
|
|
179
249
|
const flush = () => {
|
|
@@ -186,6 +256,8 @@ function parse(md, file) {
|
|
|
186
256
|
let m;
|
|
187
257
|
if ((m = line.match(HEAD_RE))) {
|
|
188
258
|
flush();
|
|
259
|
+
dropCompact();
|
|
260
|
+
grouped = null;
|
|
189
261
|
const level = m[1].length;
|
|
190
262
|
while (cur.level >= level)
|
|
191
263
|
cur = cur.parent;
|
|
@@ -197,10 +269,21 @@ function parse(md, file) {
|
|
|
197
269
|
}
|
|
198
270
|
else if (s.startsWith("@layout")) {
|
|
199
271
|
flush();
|
|
200
|
-
|
|
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
|
+
}
|
|
201
283
|
}
|
|
202
284
|
else if (s === "@next") {
|
|
203
285
|
flush();
|
|
286
|
+
grouped = null;
|
|
204
287
|
// A heading right after `@next` starts the new slide by itself.
|
|
205
288
|
let j = i + 1;
|
|
206
289
|
while (j < lines.length && lines[j].trim() === "")
|
|
@@ -214,6 +297,23 @@ function parse(md, file) {
|
|
|
214
297
|
cur.parent.children.push(sec);
|
|
215
298
|
cur = sec;
|
|
216
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
|
+
}
|
|
316
|
+
}
|
|
217
317
|
else if (s.startsWith("@graph")) {
|
|
218
318
|
flush();
|
|
219
319
|
const src = s.slice(6).trim();
|
|
@@ -222,7 +322,7 @@ function parse(md, file) {
|
|
|
222
322
|
throw new Error(`${where}: expected "@graph <relative path of a .dot file>", got "${s}"`);
|
|
223
323
|
if (!existsSync(resolve(dirname(file), src)))
|
|
224
324
|
throw new Error(`${where}: file not found: ${src}`);
|
|
225
|
-
|
|
325
|
+
push({ t: "image", alt: "", src });
|
|
226
326
|
}
|
|
227
327
|
else if (s.startsWith("@hint")) {
|
|
228
328
|
flush();
|
|
@@ -233,11 +333,11 @@ function parse(md, file) {
|
|
|
233
333
|
const buf = [];
|
|
234
334
|
for (i++; i < lines.length && lines[i].trim() !== "@note end"; i++)
|
|
235
335
|
buf.push(lines[i]);
|
|
236
|
-
|
|
336
|
+
push({ t: "note", text: buf.join("\n").trim() });
|
|
237
337
|
}
|
|
238
338
|
else if (s.startsWith("@note")) {
|
|
239
339
|
flush();
|
|
240
|
-
|
|
340
|
+
push({ t: "note", text: s.slice(5).trim() });
|
|
241
341
|
}
|
|
242
342
|
else if (s.startsWith("```")) {
|
|
243
343
|
flush();
|
|
@@ -245,7 +345,7 @@ function parse(md, file) {
|
|
|
245
345
|
const buf = [];
|
|
246
346
|
for (i++; i < lines.length && !lines[i].trim().startsWith("```"); i++)
|
|
247
347
|
buf.push(lines[i]);
|
|
248
|
-
|
|
348
|
+
push({ t: lang === "prompt" ? "prompt" : "code", lines: buf });
|
|
249
349
|
}
|
|
250
350
|
else if (s.startsWith("|")) {
|
|
251
351
|
flush();
|
|
@@ -259,7 +359,16 @@ function parse(md, file) {
|
|
|
259
359
|
const body = rows.slice(1).filter(r => !/^[\s:\-|]*$/.test(r.join("")));
|
|
260
360
|
if (header.every(c => c === "" || c === "."))
|
|
261
361
|
header = null;
|
|
262
|
-
|
|
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);
|
|
263
372
|
}
|
|
264
373
|
else if (s.startsWith(">")) {
|
|
265
374
|
flush();
|
|
@@ -267,16 +376,19 @@ function parse(md, file) {
|
|
|
267
376
|
for (; i < lines.length && lines[i].trim().startsWith(">"); i++)
|
|
268
377
|
buf.push(lines[i].trim().slice(1).trim());
|
|
269
378
|
i--;
|
|
270
|
-
|
|
379
|
+
push({ t: "quote", text: buf.join(" ") });
|
|
271
380
|
}
|
|
272
381
|
else if ((m = line.match(IMG_RE))) {
|
|
273
382
|
flush();
|
|
274
|
-
|
|
383
|
+
push({ t: "image", alt: m[1], src: m[2] });
|
|
275
384
|
}
|
|
276
385
|
else if ((m = line.match(LIST_RE))) {
|
|
277
386
|
flushPara();
|
|
278
387
|
list ??= { t: "list", items: [] };
|
|
279
|
-
|
|
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);
|
|
280
392
|
}
|
|
281
393
|
else if (s === "") {
|
|
282
394
|
flushPara();
|
|
@@ -297,8 +409,10 @@ function parse(md, file) {
|
|
|
297
409
|
}
|
|
298
410
|
}
|
|
299
411
|
flush();
|
|
412
|
+
dropCompact();
|
|
413
|
+
dropReveal();
|
|
300
414
|
if (layout)
|
|
301
|
-
console.warn(` ! ${file}: "${layout.source}" is not followed by any section`);
|
|
415
|
+
console.warn(` ! ${bold(file)}: "${layout.source}" is not followed by any section`);
|
|
302
416
|
return root;
|
|
303
417
|
}
|
|
304
418
|
const INLINE_PATTERNS = [
|
|
@@ -405,22 +519,169 @@ function promptSize(lines, width) {
|
|
|
405
519
|
const h = lines.reduce((acc, l) => acc + textH(l.length, w - 1, pt), 0) + 0.9;
|
|
406
520
|
return [w, h];
|
|
407
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
|
+
}
|
|
408
635
|
function tableCols(header, rows, width) {
|
|
409
636
|
const all = header ? [header, ...rows] : rows;
|
|
410
637
|
const ncol = Math.max(...all.map(r => r.length));
|
|
411
638
|
const lens = new Array(ncol).fill(0);
|
|
412
639
|
for (const r of all)
|
|
413
|
-
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
|
+
});
|
|
414
646
|
const tot = lens.reduce((a, b) => a + b, 0);
|
|
415
647
|
return lens.map(l => (width * l) / tot);
|
|
416
648
|
}
|
|
417
649
|
function rowH(r, cols, pt) {
|
|
418
|
-
|
|
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);
|
|
419
657
|
}
|
|
420
658
|
function tableH(header, rows, width, pt, cols) {
|
|
421
659
|
cols ??= tableCols(header, rows, width);
|
|
422
660
|
return (header ? [header, ...rows] : rows).reduce((h, r) => h + rowH(r, cols, pt), 0);
|
|
423
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
|
+
}
|
|
424
685
|
function blockH(b, width) {
|
|
425
686
|
switch (b.t) {
|
|
426
687
|
case "para":
|
|
@@ -433,7 +694,7 @@ function blockH(b, width) {
|
|
|
433
694
|
case "code":
|
|
434
695
|
return promptSize(b.lines, width)[1];
|
|
435
696
|
case "table":
|
|
436
|
-
return
|
|
697
|
+
return tableBlockH(b, width);
|
|
437
698
|
default:
|
|
438
699
|
return 0;
|
|
439
700
|
}
|
|
@@ -441,7 +702,7 @@ function blockH(b, width) {
|
|
|
441
702
|
function imageSize(path) {
|
|
442
703
|
const ext = extname(path).toLowerCase();
|
|
443
704
|
if (ext === ".dot")
|
|
444
|
-
return
|
|
705
|
+
return graphPng(path).size;
|
|
445
706
|
const data = readFileSync(path);
|
|
446
707
|
if (ext === ".svg") {
|
|
447
708
|
const head = data.subarray(0, 4000).toString("utf8");
|
|
@@ -479,151 +740,227 @@ function fit(iw, ih, bw, bh) {
|
|
|
479
740
|
const r = Math.min(bw / iw, bh / ih);
|
|
480
741
|
return [iw * r, ih * r];
|
|
481
742
|
}
|
|
482
|
-
|
|
483
|
-
const CM_PER_POINT = 2.54 / 72;
|
|
743
|
+
/** Rendered diagrams, keyed by the arguments of `dot` (which include the theme). */
|
|
484
744
|
const graphCache = new Map();
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
let
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
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;
|
|
492
805
|
}
|
|
493
|
-
|
|
494
|
-
|
|
806
|
+
const shown = cmd.join(" ");
|
|
807
|
+
if (!process.stdin.isTTY) {
|
|
808
|
+
console.log(` Install it with: ${shown}`);
|
|
809
|
+
return;
|
|
495
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;
|
|
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")}"`;
|
|
496
840
|
}
|
|
497
841
|
/**
|
|
498
|
-
*
|
|
499
|
-
*
|
|
500
|
-
* attributes set in the .dot file still take precedence.
|
|
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.
|
|
501
844
|
*/
|
|
502
|
-
function
|
|
503
|
-
|
|
504
|
-
|
|
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(", ")}]`;
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
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`.
|
|
909
|
+
*/
|
|
910
|
+
function graphPng(path) {
|
|
911
|
+
if (!dotPath)
|
|
912
|
+
throw new Error(`${path}: the Graphviz "dot" tool is required by @graph (https://graphviz.org/download/)`);
|
|
505
913
|
const font = style.theme.fonts.sans.replace(/'/g, "");
|
|
506
|
-
const
|
|
507
|
-
|
|
508
|
-
`edge [fontname="${font}", fontsize=${sizes.graphEdgeText}]; `;
|
|
914
|
+
const { colors } = style.theme;
|
|
915
|
+
const dpi = style.theme.graph.dpi;
|
|
509
916
|
const source = readFileSync(path, "utf8");
|
|
510
|
-
const
|
|
511
|
-
if (
|
|
512
|
-
throw new Error(`${path}: no "graph { ... }" or "digraph { ... }"
|
|
513
|
-
const
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
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()}`);
|
|
521
956
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
const
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
directed: g.directed !== false,
|
|
530
|
-
bb,
|
|
531
|
-
size: [Math.max(bb[2] - bb[0], 1) * CM_PER_POINT, Math.max(bb[3] - bb[1], 1) * CM_PER_POINT],
|
|
532
|
-
objects: g.objects ?? [],
|
|
533
|
-
edges: g.edges ?? [],
|
|
534
|
-
attrs: g,
|
|
535
|
-
};
|
|
536
|
-
graphCache.set(dot, layout);
|
|
537
|
-
return layout;
|
|
538
|
-
}
|
|
539
|
-
/** Graphviz node shapes and their Impress preset geometry. */
|
|
540
|
-
const NODE_SHAPES = {
|
|
541
|
-
box: "rectangle",
|
|
542
|
-
rect: "rectangle",
|
|
543
|
-
rectangle: "rectangle",
|
|
544
|
-
square: "rectangle",
|
|
545
|
-
record: "rectangle",
|
|
546
|
-
Mrecord: "round-rectangle",
|
|
547
|
-
ellipse: "ellipse",
|
|
548
|
-
oval: "ellipse",
|
|
549
|
-
circle: "ellipse",
|
|
550
|
-
doublecircle: "ellipse",
|
|
551
|
-
point: "ellipse",
|
|
552
|
-
diamond: "diamond",
|
|
553
|
-
Mdiamond: "diamond",
|
|
554
|
-
parallelogram: "parallelogram",
|
|
555
|
-
trapezium: "trapezoid",
|
|
556
|
-
hexagon: "hexagon",
|
|
557
|
-
octagon: "octagon",
|
|
558
|
-
triangle: "isosceles-triangle",
|
|
559
|
-
cylinder: "flowchart-magnetic-disk",
|
|
560
|
-
note: "flowchart-document",
|
|
561
|
-
folder: "flowchart-card",
|
|
562
|
-
star: "star5",
|
|
563
|
-
};
|
|
564
|
-
const COLOR_NAMES = {
|
|
565
|
-
black: "#000000",
|
|
566
|
-
white: "#FFFFFF",
|
|
567
|
-
red: "#FF0000",
|
|
568
|
-
green: "#00A000",
|
|
569
|
-
blue: "#0000FF",
|
|
570
|
-
yellow: "#FFFF00",
|
|
571
|
-
orange: "#FFA500",
|
|
572
|
-
purple: "#800080",
|
|
573
|
-
pink: "#FFC0CB",
|
|
574
|
-
brown: "#A52A2A",
|
|
575
|
-
gray: "#808080",
|
|
576
|
-
grey: "#808080",
|
|
577
|
-
lightgray: "#D3D3D3",
|
|
578
|
-
lightgrey: "#D3D3D3",
|
|
579
|
-
darkgray: "#A9A9A9",
|
|
580
|
-
lightblue: "#ADD8E6",
|
|
581
|
-
lightyellow: "#FFFFE0",
|
|
582
|
-
lightgreen: "#90EE90",
|
|
583
|
-
lightpink: "#FFB6C1",
|
|
584
|
-
gold: "#FFD700",
|
|
585
|
-
navy: "#000080",
|
|
586
|
-
cyan: "#00FFFF",
|
|
587
|
-
magenta: "#FF00FF",
|
|
588
|
-
darkgreen: "#006400",
|
|
589
|
-
darkblue: "#00008B",
|
|
590
|
-
darkred: "#8B0000",
|
|
591
|
-
};
|
|
592
|
-
function gvColor(value) {
|
|
593
|
-
if (typeof value !== "string" || !value)
|
|
594
|
-
return null;
|
|
595
|
-
const v = value.split(":")[0].trim();
|
|
596
|
-
if (/^#[0-9a-f]{6}$/i.test(v))
|
|
597
|
-
return v.toUpperCase();
|
|
598
|
-
if (/^#[0-9a-f]{8}$/i.test(v))
|
|
599
|
-
return v.slice(0, 7).toUpperCase();
|
|
600
|
-
return COLOR_NAMES[v.toLowerCase()] ?? null;
|
|
601
|
-
}
|
|
602
|
-
/** Text of a Graphviz label, with "\n" for line breaks. */
|
|
603
|
-
function gvLabel(raw, name, graphName, record = false) {
|
|
604
|
-
let label = typeof raw === "string" ? raw : "\\N";
|
|
605
|
-
if (label.startsWith("<") && label.endsWith(">")) {
|
|
606
|
-
label = label
|
|
607
|
-
.slice(1, -1)
|
|
608
|
-
.replace(/<br\s*\/?>/gi, "\n")
|
|
609
|
-
.replace(/<[^>]+>/g, "");
|
|
610
|
-
}
|
|
611
|
-
label = label.replaceAll("\\N", name).replaceAll("\\G", graphName);
|
|
612
|
-
if (record)
|
|
613
|
-
label = label.replace(/[{}]/g, "").replace(/\s*\|\s*/g, "\n");
|
|
614
|
-
return label
|
|
615
|
-
.replace(/\\[nlr]/g, "\n")
|
|
616
|
-
.replace(/\n$/, "")
|
|
617
|
-
.replace(/\\(.)/g, "$1");
|
|
618
|
-
}
|
|
619
|
-
/** Stroke properties for Graphviz `style=dashed` or `style=dotted`. */
|
|
620
|
-
function dashed(gvStyle) {
|
|
621
|
-
const dash = Object.keys(style.dashes)[0];
|
|
622
|
-
return dash && /\b(dashed|dotted)\b/.test(String(gvStyle ?? "")) ? { "draw:stroke": "dash", "draw:stroke-dash": dash } : {};
|
|
623
|
-
}
|
|
624
|
-
function gvPoint(s) {
|
|
625
|
-
const [x, y] = s.split(",").map(Number);
|
|
626
|
-
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;
|
|
627
964
|
}
|
|
628
965
|
// ---------------------------------------------------------------- layout
|
|
629
966
|
const MIME = {
|
|
@@ -633,32 +970,74 @@ const MIME = {
|
|
|
633
970
|
".jpg": "image/jpeg",
|
|
634
971
|
".jpeg": "image/jpeg",
|
|
635
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
|
+
}
|
|
636
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
|
+
}
|
|
637
1016
|
class Builder {
|
|
638
1017
|
base;
|
|
639
1018
|
pictures = new Map();
|
|
640
1019
|
pages = [];
|
|
641
1020
|
colStyles = new Map();
|
|
642
1021
|
rowStyles = new Map();
|
|
1022
|
+
paraStyles = new Map();
|
|
643
1023
|
/** Hints waiting to be attached to the next slide title. */
|
|
644
1024
|
pendingHints = [];
|
|
645
|
-
/** Automatic graphic styles (Graphviz colors), keyed by their properties. */
|
|
646
|
-
autoStyles = new Map();
|
|
647
|
-
/** Automatic paragraph styles (text size and color in diagrams). */
|
|
648
|
-
paraStyles = new Map();
|
|
649
|
-
graphCount = 0;
|
|
650
1025
|
constructor(base) {
|
|
651
1026
|
this.base = base;
|
|
1027
|
+
mdDir = base;
|
|
1028
|
+
cellCache.clear();
|
|
652
1029
|
}
|
|
653
1030
|
// -- resources
|
|
654
1031
|
picture(src) {
|
|
655
1032
|
let pic = this.pictures.get(src);
|
|
656
1033
|
if (!pic) {
|
|
657
1034
|
const path = resolve(this.base, src);
|
|
658
|
-
|
|
1035
|
+
const isGraph = extname(src).toLowerCase() === ".dot";
|
|
1036
|
+
let name = `${basename(src, extname(src))}.webp`;
|
|
659
1037
|
while ([...this.pictures.values()].some(p => p.href === `Pictures/${name}`))
|
|
660
1038
|
name = `_${name}`;
|
|
661
|
-
|
|
1039
|
+
const graph = isGraph ? graphPng(path) : null;
|
|
1040
|
+
pic = { href: `Pictures/${name}`, data: graph ? graph.png : readFileSync(path), size: graph ? graph.size : imageSize(path) };
|
|
662
1041
|
this.pictures.set(src, pic);
|
|
663
1042
|
}
|
|
664
1043
|
return pic;
|
|
@@ -669,6 +1048,16 @@ class Builder {
|
|
|
669
1048
|
this.colStyles.set(key, `co${this.colStyles.size + 1}`);
|
|
670
1049
|
return this.colStyles.get(key);
|
|
671
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
|
+
}
|
|
672
1061
|
rowStyle(h) {
|
|
673
1062
|
const key = f2(h);
|
|
674
1063
|
if (!this.rowStyles.has(key))
|
|
@@ -693,29 +1082,51 @@ class Builder {
|
|
|
693
1082
|
this.pendingHints = [];
|
|
694
1083
|
return desc;
|
|
695
1084
|
}
|
|
696
|
-
|
|
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);
|
|
697
1093
|
const out = [];
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
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();
|
|
703
1109
|
}
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
out.push(
|
|
708
|
-
|
|
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);
|
|
709
1115
|
}
|
|
710
1116
|
out.push(`<text:p>${runsXml(txt)}</text:p>`);
|
|
711
1117
|
}
|
|
712
|
-
while (
|
|
713
|
-
|
|
1118
|
+
while (open.length)
|
|
1119
|
+
close();
|
|
714
1120
|
return out.join("");
|
|
715
1121
|
}
|
|
716
|
-
tableXml(header, rows, x, y, width, pt, small = false, cols) {
|
|
1122
|
+
tableXml(header, rows, x, y, width, pt, small = false, cols, hidden = () => false) {
|
|
717
1123
|
cols ??= tableCols(header, rows, width);
|
|
718
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 = [];
|
|
719
1130
|
const parts = [
|
|
720
1131
|
`<draw:frame draw:style-name="Tableau-cadre" ${Builder.geom(x, y, width, tableH(header, rows, width, pt, cols))}>`,
|
|
721
1132
|
`<table:table table:template-name="${prefix}" table:use-first-row-styles="${header ? "true" : "false"}" table:use-banding-rows-styles="true">`,
|
|
@@ -725,147 +1136,50 @@ class Builder {
|
|
|
725
1136
|
...(header ? [["entete", header]] : []),
|
|
726
1137
|
...rows.map((r, i) => [i % 2 === 0 ? "cellule" : "cellule-alt", r]),
|
|
727
1138
|
];
|
|
1139
|
+
let cy = y;
|
|
728
1140
|
for (const [kind, r] of all) {
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
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;
|
|
732
1161
|
});
|
|
733
1162
|
parts.push("</table:table-row>");
|
|
1163
|
+
cy += rh;
|
|
734
1164
|
}
|
|
735
1165
|
parts.push("</table:table></draw:frame>");
|
|
736
|
-
return parts.join("");
|
|
1166
|
+
return parts.join("") + overlays.join("");
|
|
737
1167
|
}
|
|
738
|
-
imageXml(src, x, y, w, h) {
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
const { href } = this.picture(src);
|
|
742
|
-
const mime = href.endsWith(".svg") ? ' draw:mime-type="image/svg+xml"' : "";
|
|
743
|
-
return (`<draw:frame draw:style-name="Image" ${Builder.geom(x, y, w, h)}>` +
|
|
744
|
-
`<draw:image xlink:href="${esc(href)}" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"${mime}/>` +
|
|
745
|
-
`</draw:frame>`);
|
|
746
|
-
}
|
|
747
|
-
/** Automatic style deriving from a named style, for colors set in a .dot file. */
|
|
748
|
-
autoStyle(parent, graphic) {
|
|
749
|
-
if (!Object.keys(graphic).length)
|
|
750
|
-
return parent;
|
|
751
|
-
const key = JSON.stringify([parent, graphic]);
|
|
752
|
-
let entry = this.autoStyles.get(key);
|
|
753
|
-
if (!entry) {
|
|
754
|
-
entry = { name: `gr${this.autoStyles.size + 1}`, parent, graphic };
|
|
755
|
-
this.autoStyles.set(key, entry);
|
|
756
|
-
}
|
|
757
|
-
return entry.name;
|
|
758
|
-
}
|
|
759
|
-
/**
|
|
760
|
-
* A paragraph with text properties of its own. LibreOffice ignores text
|
|
761
|
-
* properties in automatic graphic styles, so they go on the paragraph.
|
|
762
|
-
*/
|
|
763
|
-
para(text, props) {
|
|
764
|
-
if (!text)
|
|
765
|
-
return "";
|
|
766
|
-
const key = JSON.stringify(props);
|
|
767
|
-
let entry = this.paraStyles.get(key);
|
|
768
|
-
if (!entry) {
|
|
769
|
-
entry = { name: `Pg${this.paraStyles.size + 1}`, text: props };
|
|
770
|
-
this.paraStyles.set(key, entry);
|
|
771
|
-
}
|
|
772
|
-
return `<text:p text:style-name="${entry.name}">${xmlText(text)}</text:p>`;
|
|
773
|
-
}
|
|
774
|
-
/** A Graphviz diagram as a group of native shapes linked by connectors. */
|
|
775
|
-
graphXml(path, x, y, w, h) {
|
|
776
|
-
const g = graphLayout(path);
|
|
777
|
-
// 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.
|
|
778
1171
|
const maxScale = style.theme.graph.maxScale;
|
|
779
|
-
if (w >
|
|
780
|
-
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);
|
|
781
1174
|
x += (w - fw) / 2;
|
|
782
1175
|
y += (h - fh) / 2;
|
|
783
1176
|
w = fw;
|
|
784
1177
|
h = fh;
|
|
785
1178
|
}
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
const c = gvColor(color);
|
|
791
|
-
return { "fo:font-size": `${pt}pt`, ...(c ? { "fo:color": c } : {}) };
|
|
792
|
-
};
|
|
793
|
-
const [bx0, , , by1] = g.bb;
|
|
794
|
-
const px = (p) => x + (p - bx0) * scale;
|
|
795
|
-
const py = (p) => y + (by1 - p) * scale;
|
|
796
|
-
const id = (gvid) => `g${this.graphCount}n${gvid}`;
|
|
797
|
-
this.graphCount++;
|
|
798
|
-
const out = [`<draw:g>`];
|
|
799
|
-
const title = gvLabel(g.attrs.label ?? "", g.name, g.name);
|
|
800
|
-
if (title && typeof g.attrs.lp === "string") {
|
|
801
|
-
const [lx, ly] = gvPoint(g.attrs.lp);
|
|
802
|
-
const lw = Number(g.attrs.lwidth ?? 1) * 72 * scale + 0.4;
|
|
803
|
-
const lh = Number(g.attrs.lheight ?? 0.3) * 72 * scale + 0.2;
|
|
804
|
-
const text = this.para(title, textProps(g.attrs.fontsize, sizes.graphEdgeText, g.attrs.fontcolor));
|
|
805
|
-
out.push(this.frame("Graphe-titre", px(lx) - lw / 2, py(ly) - lh / 2, lw, lh, text));
|
|
806
|
-
}
|
|
807
|
-
// Clusters first, so they stay behind the nodes.
|
|
808
|
-
for (const o of g.objects) {
|
|
809
|
-
if (typeof o.bb !== "string" || !o.name.startsWith("cluster"))
|
|
810
|
-
continue;
|
|
811
|
-
const [x0, y0, x1, y1] = o.bb.split(",").map(Number);
|
|
812
|
-
const fill = gvColor(o.fillcolor) ?? (String(o.style ?? "").includes("filled") ? gvColor(o.color) : null);
|
|
813
|
-
const stroke = gvColor(o.pencolor) ?? gvColor(o.color);
|
|
814
|
-
const st = this.autoStyle("Graphe-groupe", { ...(fill ? { "draw:fill-color": fill } : {}), ...(stroke ? { "svg:stroke-color": stroke } : {}), ...dashed(o.style) });
|
|
815
|
-
const label = gvLabel(o.label ?? "", o.name, g.name);
|
|
816
|
-
out.push(`<draw:rect draw:style-name="${st}" ${Builder.geom(px(x0), py(y1), (x1 - x0) * scale, (y1 - y0) * scale)}>` +
|
|
817
|
-
this.para(label, textProps(o.fontsize, sizes.graphEdgeText, o.fontcolor)) +
|
|
818
|
-
`</draw:rect>`);
|
|
819
|
-
}
|
|
820
|
-
for (const o of g.objects) {
|
|
821
|
-
if (typeof o.pos !== "string")
|
|
822
|
-
continue;
|
|
823
|
-
const [cx, cy] = gvPoint(o.pos);
|
|
824
|
-
const nw = Number(o.width ?? 0.75) * 72 * scale;
|
|
825
|
-
const nh = Number(o.height ?? 0.5) * 72 * scale;
|
|
826
|
-
const shape = String(o.shape ?? "ellipse");
|
|
827
|
-
const styles = String(o.style ?? "");
|
|
828
|
-
const plain = ["plaintext", "plain", "none", "underline"].includes(shape) || styles.includes("invis");
|
|
829
|
-
let geometry = NODE_SHAPES[shape] ?? "rectangle";
|
|
830
|
-
if (geometry === "rectangle" && styles.includes("rounded"))
|
|
831
|
-
geometry = "round-rectangle";
|
|
832
|
-
const fill = styles.includes("filled") ? (gvColor(o.fillcolor) ?? gvColor(o.color)) : null;
|
|
833
|
-
const stroke = gvColor(o.color);
|
|
834
|
-
const st = this.autoStyle(plain ? "Graphe-texte" : "Graphe-noeud", { ...(fill ? { "draw:fill-color": fill } : {}), ...(stroke && !plain ? { "svg:stroke-color": stroke } : {}), ...(plain ? {} : dashed(o.style)) });
|
|
835
|
-
const label = shape === "point" ? "" : gvLabel(o.label, o.name, g.name, shape.endsWith("record"));
|
|
836
|
-
const nid = id(o._gvid);
|
|
837
|
-
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)}>` +
|
|
838
|
-
this.para(label, textProps(o.fontsize, sizes.graphText, o.fontcolor)) +
|
|
839
|
-
`<draw:enhanced-geometry svg:viewBox="0 0 21600 21600" draw:type="${geometry}"/>` +
|
|
840
|
-
`</draw:custom-shape>`);
|
|
841
|
-
}
|
|
842
|
-
const kind = style.theme.graph.connector;
|
|
843
|
-
for (const e of g.edges) {
|
|
844
|
-
const tokens = String(e.pos ?? "").split(/\s+/).filter(Boolean);
|
|
845
|
-
const points = tokens.filter(t => !/^[se],/.test(t)).map(gvPoint);
|
|
846
|
-
const startTip = tokens.find(t => t.startsWith("s,"));
|
|
847
|
-
const endTip = tokens.find(t => t.startsWith("e,"));
|
|
848
|
-
let start = startTip ? gvPoint(startTip.slice(2)) : (points[0] ?? [0, 0]);
|
|
849
|
-
let end = endTip ? gvPoint(endTip.slice(2)) : (points[points.length - 1] ?? [0, 0]);
|
|
850
|
-
let [tail, head] = [e.tail, e.head];
|
|
851
|
-
const dir = String(e.dir ?? (g.directed ? "forward" : "none"));
|
|
852
|
-
if (dir === "back") {
|
|
853
|
-
;
|
|
854
|
-
[tail, head] = [head, tail];
|
|
855
|
-
[start, end] = [end, start];
|
|
856
|
-
}
|
|
857
|
-
const parent = dir === "none" ? "Graphe-lien-simple" : dir === "both" ? "Graphe-lien-double" : "Graphe-lien";
|
|
858
|
-
const stroke = gvColor(e.color);
|
|
859
|
-
const st = this.autoStyle(parent, { ...(stroke ? { "svg:stroke-color": stroke } : {}), ...dashed(e.style) });
|
|
860
|
-
const label = gvLabel(e.label ?? "", "", g.name);
|
|
861
|
-
out.push(`<draw:connector draw:style-name="${st}" draw:type="${esc(kind)}" ` +
|
|
862
|
-
`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" ` +
|
|
863
|
-
`draw:start-shape="${id(tail)}" draw:end-shape="${id(head)}">` +
|
|
864
|
-
this.para(label, textProps(e.fontsize, sizes.graphEdgeText, e.fontcolor)) +
|
|
865
|
-
`</draw:connector>`);
|
|
866
|
-
}
|
|
867
|
-
out.push("</draw:g>");
|
|
868
|
-
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>`);
|
|
869
1183
|
}
|
|
870
1184
|
promptXml(lines, x, y, w, h, style = "Prompt") {
|
|
871
1185
|
const paras = lines.map(l => `<text:p>${xmlText(l)}</text:p>`).join("");
|
|
@@ -878,7 +1192,7 @@ class Builder {
|
|
|
878
1192
|
case "para":
|
|
879
1193
|
return this.frame("Texte", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
|
|
880
1194
|
case "list":
|
|
881
|
-
return this.frame("Master-outline1", x, y, w, h, this.listXml(b.items), "outline");
|
|
1195
|
+
return this.frame("Master-outline1", x, y, w, h, this.listXml(b.items, "Master-outline1"), "outline");
|
|
882
1196
|
case "quote":
|
|
883
1197
|
return this.frame("Citation", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
|
|
884
1198
|
case "prompt":
|
|
@@ -887,8 +1201,11 @@ class Builder {
|
|
|
887
1201
|
return this.promptXml(b.lines, x + w - pw, y, pw, h, b.t === "prompt" ? "Prompt" : "Code");
|
|
888
1202
|
}
|
|
889
1203
|
case "table": {
|
|
890
|
-
const
|
|
891
|
-
|
|
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("");
|
|
892
1209
|
}
|
|
893
1210
|
default:
|
|
894
1211
|
throw new Error(`Unexpected block ${b.t}`);
|
|
@@ -900,16 +1217,17 @@ class Builder {
|
|
|
900
1217
|
const imgs = blocks.filter(b => b.t === "image");
|
|
901
1218
|
const texts = blocks.filter(b => b.t !== "image");
|
|
902
1219
|
const shapes = [];
|
|
903
|
-
const
|
|
904
|
-
|
|
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;
|
|
905
1224
|
for (const b of bs) {
|
|
906
1225
|
const bh = blockH(b, width);
|
|
907
1226
|
shapes.push(this.blockXml(b, x, y, width, Math.min(bh, Math.max(Y0 + H - y, 1.5))));
|
|
908
1227
|
y += bh + GAP;
|
|
909
1228
|
}
|
|
910
|
-
return y -
|
|
1229
|
+
return y - top - (bs.length ? GAP : 0);
|
|
911
1230
|
};
|
|
912
|
-
const sumH = (width) => texts.reduce((h, b) => h + blockH(b, width), 0) + GAP * (texts.length - 1);
|
|
913
1231
|
if (!imgs.length)
|
|
914
1232
|
return [stack(texts, X0, W), shapes];
|
|
915
1233
|
const src = imgs[0].src;
|
|
@@ -920,7 +1238,8 @@ class Builder {
|
|
|
920
1238
|
return [0, shapes];
|
|
921
1239
|
}
|
|
922
1240
|
if (iw / ih >= 1.8 || (iw / ih >= 1.2 && sumH(W) < 2.5)) {
|
|
923
|
-
|
|
1241
|
+
// The image below the text takes the free height.
|
|
1242
|
+
const th = stack(texts, X0, W, false);
|
|
924
1243
|
const avail = Math.max(H - th - GAP, 4.5);
|
|
925
1244
|
const [w, h] = fit(iw, ih, W, avail);
|
|
926
1245
|
shapes.push(this.imageXml(src, X0 + (W - w) / 2, Y0 + th + GAP + (avail - h) / 2, w, h));
|
|
@@ -942,12 +1261,20 @@ class Builder {
|
|
|
942
1261
|
slides[slides.length - 1][1].push(b.text);
|
|
943
1262
|
continue;
|
|
944
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
|
+
}
|
|
945
1274
|
const cur = slides[slides.length - 1][0];
|
|
946
1275
|
const hasImg = cur.some(x => x.t === "image");
|
|
947
|
-
if (cur.length && ((b.t === "image" && hasImg) || this.
|
|
948
|
-
|
|
949
|
-
const carry = cur.length > 1 && cur[cur.length - 1].t === "para" ? [cur.pop()] : [];
|
|
950
|
-
slides.push([[...carry, b], []]);
|
|
1276
|
+
if (cur.length && ((b.t === "image" && hasImg) || !this.fits([...cur, b]))) {
|
|
1277
|
+
slides.push([[...this.carry(cur, b), b], []]);
|
|
951
1278
|
}
|
|
952
1279
|
else {
|
|
953
1280
|
cur.push(b);
|
|
@@ -955,6 +1282,111 @@ class Builder {
|
|
|
955
1282
|
}
|
|
956
1283
|
return slides.filter(([c, n]) => c.length || n.length);
|
|
957
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
|
+
}
|
|
958
1390
|
// -- pages
|
|
959
1391
|
page(master, shapes, notes = []) {
|
|
960
1392
|
this.pages.push({ master, shapes, notes });
|
|
@@ -967,63 +1399,44 @@ class Builder {
|
|
|
967
1399
|
return out;
|
|
968
1400
|
}
|
|
969
1401
|
sectionPage(sec) {
|
|
970
|
-
|
|
971
|
-
const
|
|
972
|
-
|
|
973
|
-
|
|
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"));
|
|
974
1407
|
const notes = sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : []));
|
|
975
1408
|
this.page("Section", shapes, notes);
|
|
976
1409
|
}
|
|
977
1410
|
contentPages(title, crumbs, blocks) {
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
const hasLogos = rows.some(r => /<img\s/.test(r[0] ?? ""));
|
|
992
|
-
const widths = tableCols(header, rows.map(r => (hasLogos ? ["Logo", ...r.slice(1)] : r)), Math.min(W, 4.5 * ncol));
|
|
993
|
-
const tw = widths.reduce((a, b) => a + b, 0);
|
|
994
|
-
const x = X0 + (W - tw) / 2;
|
|
995
|
-
const rh = 1.3;
|
|
996
|
-
const hh = 1.1;
|
|
997
|
-
for (let k = 0; k <= rows.length; k++) {
|
|
998
|
-
const parts = [
|
|
999
|
-
`<draw:frame draw:style-name="Tableau-cadre" ${Builder.geom(x, Y0, tw, hh + rh * rows.length)}>`,
|
|
1000
|
-
'<table:table table:template-name="Tableau" table:use-first-row-styles="true" table:use-banding-rows-styles="true">',
|
|
1001
|
-
...widths.map(cw => `<table:table-column table:style-name="${this.colStyle(cw)}"/>`),
|
|
1002
|
-
`<table:table-row table:style-name="${this.rowStyle(hh)}">`,
|
|
1003
|
-
...widths.map((_, c) => `<table:table-cell table:style-name="Tableau-entete"><text:p>${xmlText(header[c] ?? "")}</text:p></table:table-cell>`),
|
|
1004
|
-
"</table:table-row>",
|
|
1005
|
-
];
|
|
1006
|
-
rows.forEach((r, i) => {
|
|
1007
|
-
const st = i % 2 === 0 ? "Tableau-cellule" : "Tableau-cellule-alt";
|
|
1008
|
-
parts.push(`<table:table-row table:style-name="${this.rowStyle(rh)}">`);
|
|
1009
|
-
widths.forEach((_, c) => {
|
|
1010
|
-
const cell = i < k && !(hasLogos && c === 0) ? (r[c] ?? "") : "";
|
|
1011
|
-
parts.push(`<table:table-cell table:style-name="${st}"><text:p>${runsXml(cell)}</text:p></table:table-cell>`);
|
|
1012
|
-
});
|
|
1013
|
-
parts.push("</table:table-row>");
|
|
1014
|
-
});
|
|
1015
|
-
parts.push("</table:table></draw:frame>");
|
|
1016
|
-
const shapes = [parts.join("")];
|
|
1017
|
-
for (let i = 0; i < k; i++) {
|
|
1018
|
-
const m = (rows[i][0] ?? "").match(/src="([^"]+)"/);
|
|
1019
|
-
if (m) {
|
|
1020
|
-
const s = 1.0;
|
|
1021
|
-
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]);
|
|
1022
1424
|
}
|
|
1023
1425
|
}
|
|
1024
|
-
|
|
1025
|
-
|
|
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
|
+
}
|
|
1026
1436
|
}
|
|
1437
|
+
flush();
|
|
1438
|
+
if (pending.length)
|
|
1439
|
+
this.pages[this.pages.length - 1].notes.push(...pending);
|
|
1027
1440
|
}
|
|
1028
1441
|
/** Height of a group of paragraphs/lists rendered at `pt` points. */
|
|
1029
1442
|
static textGroupH(blocks, width, pt) {
|
|
@@ -1051,7 +1464,7 @@ class Builder {
|
|
|
1051
1464
|
const ncol = Math.max(...all.map(r => r.length));
|
|
1052
1465
|
let tw = 0;
|
|
1053
1466
|
for (let c = 0; c < ncol; c++)
|
|
1054
|
-
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;
|
|
1055
1468
|
w = Math.max(w, tw);
|
|
1056
1469
|
}
|
|
1057
1470
|
else if (b.t === "image") {
|
|
@@ -1067,7 +1480,7 @@ class Builder {
|
|
|
1067
1480
|
cellXml(sec, x, y, w, h, textStyle, textPt) {
|
|
1068
1481
|
const items = [];
|
|
1069
1482
|
for (const b of sec.blocks) {
|
|
1070
|
-
if (b.t === "note")
|
|
1483
|
+
if (b.t === "note" || b.t === "layout")
|
|
1071
1484
|
continue;
|
|
1072
1485
|
const last = items[items.length - 1];
|
|
1073
1486
|
if (b.t === "para" || b.t === "list" || b.t === "quote") {
|
|
@@ -1121,7 +1534,7 @@ class Builder {
|
|
|
1121
1534
|
const ih = Math.max(0.5, Math.min(heights[i], y + h - cy));
|
|
1122
1535
|
if (it.kind === "text") {
|
|
1123
1536
|
const inner = it.blocks
|
|
1124
|
-
.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>` : ""))
|
|
1125
1538
|
.join("");
|
|
1126
1539
|
shapes.push(this.frame(textStyle, x, cy, w, ih, inner));
|
|
1127
1540
|
}
|
|
@@ -1146,9 +1559,8 @@ class Builder {
|
|
|
1146
1559
|
return shapes;
|
|
1147
1560
|
}
|
|
1148
1561
|
/** Sections laid out on a single slide, following an `@layout` pragma. */
|
|
1149
|
-
layoutPage(
|
|
1150
|
-
const
|
|
1151
|
-
const shapes = this.titleShapes(title, parent.path().slice(0, -1));
|
|
1562
|
+
layoutPage(title, crumbs, group, layout, notes) {
|
|
1563
|
+
const shapes = this.titleShapes(title, crumbs);
|
|
1152
1564
|
const headH = 0.9;
|
|
1153
1565
|
let cells;
|
|
1154
1566
|
if (layout.kind === "grid") {
|
|
@@ -1193,8 +1605,11 @@ class Builder {
|
|
|
1193
1605
|
const [headStyle, textStyle, textPt] = layout.kind === "grid"
|
|
1194
1606
|
? [`Grille-titre-${(n % colors) + 1}`, `Grille-texte-${(n % colors) + 1}`, sizes.gridText]
|
|
1195
1607
|
: ["Colonne-titre", "Colonne-texte", sizes.columnText];
|
|
1196
|
-
|
|
1197
|
-
|
|
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));
|
|
1198
1613
|
notes.push(...sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : [])));
|
|
1199
1614
|
});
|
|
1200
1615
|
this.page("Master", shapes, notes);
|
|
@@ -1210,9 +1625,6 @@ class Builder {
|
|
|
1210
1625
|
if (content.length)
|
|
1211
1626
|
this.contentPages(sec.title, [...crumbs, sec.title], sec.blocks);
|
|
1212
1627
|
}
|
|
1213
|
-
else if (sec.hints.some(h => h.includes("revealed line by line"))) {
|
|
1214
|
-
this.revealTable(sec, crumbs);
|
|
1215
|
-
}
|
|
1216
1628
|
else if (content.length) {
|
|
1217
1629
|
this.contentPages(sec.title, crumbs, sec.blocks);
|
|
1218
1630
|
}
|
|
@@ -1233,7 +1645,8 @@ class Builder {
|
|
|
1233
1645
|
const group = children.slice(i, i + cellCount(layout));
|
|
1234
1646
|
for (const g of group)
|
|
1235
1647
|
this.pendingHints.push(...g.hints);
|
|
1236
|
-
|
|
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 : []);
|
|
1237
1650
|
// Sub-sections of grouped sections still get their own slides.
|
|
1238
1651
|
for (const g of group)
|
|
1239
1652
|
this.walkChildren(g);
|
|
@@ -1271,6 +1684,35 @@ function bulletsXml(def, name) {
|
|
|
1271
1684
|
`</text:list-level-style-bullet>`);
|
|
1272
1685
|
return `<text:list-style style:name="${esc(name)}-list">${levels.join("")}</text:list-style>`;
|
|
1273
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
|
+
}
|
|
1274
1716
|
function styleXml(name, s) {
|
|
1275
1717
|
const parent = s.parent ? ` style:parent-style-name="${esc(s.parent)}"` : "";
|
|
1276
1718
|
const list = s.bullets ? bulletsXml(s.bullets, name) : "";
|
|
@@ -1304,9 +1746,8 @@ function backgroundXml(b, master) {
|
|
|
1304
1746
|
w = size[0] * scale;
|
|
1305
1747
|
h = size[1] * scale;
|
|
1306
1748
|
}
|
|
1307
|
-
const mime = href.endsWith(".svg") ? ' draw:mime-type="image/svg+xml"' : "";
|
|
1308
1749
|
return (`<draw:frame draw:style-name="${backgroundStyle(master)}" ${Builder.geom(x, y, w, h)}>` +
|
|
1309
|
-
`<draw:image xlink:href="${esc(href)}" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"
|
|
1750
|
+
`<draw:image xlink:href="${esc(href)}" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>` +
|
|
1310
1751
|
`</draw:frame>`);
|
|
1311
1752
|
}
|
|
1312
1753
|
function stylesXml(b) {
|
|
@@ -1354,13 +1795,16 @@ function stylesXml(b) {
|
|
|
1354
1795
|
}
|
|
1355
1796
|
function contentXml(b) {
|
|
1356
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));
|
|
1357
1801
|
for (const [key, name] of b.colStyles)
|
|
1358
1802
|
auto.push(`<style:style style:name="${name}" style:family="table-column"><style:table-column-properties style:column-width="${key}cm"/></style:style>`);
|
|
1359
|
-
for (const
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
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
|
+
}
|
|
1364
1808
|
for (const [key, name] of b.rowStyles)
|
|
1365
1809
|
auto.push(`<style:style style:name="${name}" style:family="table-row"><style:table-row-properties style:row-height="${key}cm"/></style:style>`);
|
|
1366
1810
|
const pages = b.pages.map(({ master, shapes, notes }, i) => {
|
|
@@ -1424,10 +1868,12 @@ function zip(entries) {
|
|
|
1424
1868
|
end.writeUInt32LE(offset, 16);
|
|
1425
1869
|
return Buffer.concat([...locals, cd, end]);
|
|
1426
1870
|
}
|
|
1427
|
-
function writeOdp(b, out, title) {
|
|
1871
|
+
async function writeOdp(b, out, title) {
|
|
1428
1872
|
// Before listing the pictures: the master pages can add some.
|
|
1429
1873
|
const styles = stylesXml(b);
|
|
1874
|
+
const content = contentXml(b);
|
|
1430
1875
|
const pics = [...b.pictures.values()];
|
|
1876
|
+
await encodePictures(pics);
|
|
1431
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">' +
|
|
1432
1878
|
'<manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.presentation"/>' +
|
|
1433
1879
|
'<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>' +
|
|
@@ -1443,7 +1889,7 @@ function writeOdp(b, out, title) {
|
|
|
1443
1889
|
{ name: "META-INF/manifest.xml", data: text(manifest) },
|
|
1444
1890
|
{ name: "meta.xml", data: text(meta) },
|
|
1445
1891
|
{ name: "styles.xml", data: text(styles) },
|
|
1446
|
-
{ name: "content.xml", data: text(
|
|
1892
|
+
{ name: "content.xml", data: text(content) },
|
|
1447
1893
|
...pics.map(p => ({ name: p.href, data: p.data, store: true })),
|
|
1448
1894
|
]));
|
|
1449
1895
|
}
|
|
@@ -1461,13 +1907,13 @@ function humanSize(bytes) {
|
|
|
1461
1907
|
function countHints(sec) {
|
|
1462
1908
|
return sec.hints.length + sec.children.reduce((n, c) => n + countHints(c), 0);
|
|
1463
1909
|
}
|
|
1464
|
-
function convert(src, config) {
|
|
1910
|
+
async function convert(src, config) {
|
|
1465
1911
|
useStyle(config);
|
|
1466
1912
|
const root = parse(readFileSync(src, "utf8"), src);
|
|
1467
1913
|
const b = new Builder(dirname(src));
|
|
1468
1914
|
b.walkChildren(root);
|
|
1469
1915
|
const out = src.replace(/\.md$/i, ".odp");
|
|
1470
|
-
writeOdp(b, out, basename(src, extname(src)));
|
|
1916
|
+
await writeOdp(b, out, basename(src, extname(src)));
|
|
1471
1917
|
return { out, hints: countHints(root) };
|
|
1472
1918
|
}
|
|
1473
1919
|
/** A ready-to-paste prompt asking an AI agent to apply the `@hint` pragmas of the given presentations. */
|
|
@@ -1476,7 +1922,7 @@ function aiPrompt(files) {
|
|
|
1476
1922
|
return [
|
|
1477
1923
|
rule,
|
|
1478
1924
|
`Refine ${files.length > 1 ? "these LibreOffice Impress presentations" : "this LibreOffice Impress presentation"}:`,
|
|
1479
|
-
...files.map(f => ` - ${f}`),
|
|
1925
|
+
...files.map(f => ` - ${bold(f)}`),
|
|
1480
1926
|
"",
|
|
1481
1927
|
"An .odp file is a ZIP archive. In its content.xml, some slide titles carry",
|
|
1482
1928
|
"layout instructions in their alt-text description: <svg:desc> elements whose",
|
|
@@ -1504,8 +1950,11 @@ const PRAGMAS = [
|
|
|
1504
1950
|
["@hint <text>", "Instruction for an AI: stored verbatim in the .odp (alt-text of the slide title), never displayed."],
|
|
1505
1951
|
["@layout grid <C>x<R>", "Put the next C×R sections (starting at the next heading) on one slide, in a grid."],
|
|
1506
1952
|
["@layout columns <sizes>", 'Put the next sections on one slide, in columns sized "1fr", "2fr"... or "auto" (one size per section).'],
|
|
1507
|
-
["@
|
|
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."],
|
|
1508
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.'],
|
|
1509
1958
|
["```prompt ... ```", "Not a pragma: a code block shown as a chat prompt bubble."],
|
|
1510
1959
|
];
|
|
1511
1960
|
function printHelp() {
|
|
@@ -1531,22 +1980,23 @@ async function main(args) {
|
|
|
1531
1980
|
const files = args.filter(f => f.toLowerCase().endsWith(".md"));
|
|
1532
1981
|
for (const f of args)
|
|
1533
1982
|
if (!files.includes(f))
|
|
1534
|
-
console.warn(`Ignoring ${f}: not a .md file`);
|
|
1983
|
+
console.warn(`Ignoring ${bold(f)}: not a .md file`);
|
|
1535
1984
|
if (!files.length) {
|
|
1536
1985
|
console.error("No .md file given. Run without arguments for help.");
|
|
1537
1986
|
process.exit(1);
|
|
1538
1987
|
}
|
|
1539
|
-
await loadGraphviz();
|
|
1540
1988
|
const withHints = [];
|
|
1541
1989
|
let failed = false;
|
|
1542
1990
|
for (const file of files) {
|
|
1543
1991
|
const src = resolve(file);
|
|
1544
|
-
console.log(`Processing ${src}`);
|
|
1992
|
+
console.log(`Processing ${bold(src)}`);
|
|
1545
1993
|
try {
|
|
1994
|
+
if (existsSync(src) && usesGraph(src))
|
|
1995
|
+
await ensureDot();
|
|
1546
1996
|
const { config, path, created } = loadStyle(src);
|
|
1547
|
-
console.log(created ? ` + ${path} (created with the default style)` : ` ⚙ ${path}`);
|
|
1548
|
-
const { out, hints } = convert(src, config);
|
|
1549
|
-
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)})`);
|
|
1550
2000
|
if (hints)
|
|
1551
2001
|
withHints.push([out, hints]);
|
|
1552
2002
|
}
|
|
@@ -1559,9 +2009,9 @@ async function main(args) {
|
|
|
1559
2009
|
console.log("\nThese presentations contain @hint pragmas (stored in the slide titles' alt-text descriptions)");
|
|
1560
2010
|
console.log("and can be refined with AI:");
|
|
1561
2011
|
for (const [out, n] of withHints)
|
|
1562
|
-
console.log(` - ${out} (${n} hint${n > 1 ? "s" : ""})`);
|
|
2012
|
+
console.log(` - ${bold(out)} (${n} hint${n > 1 ? "s" : ""})`);
|
|
1563
2013
|
console.log("\nExample of prompt to give to an AI agent able to read and write files:\n");
|
|
1564
|
-
console.log(aiPrompt(withHints.map(([out]) => out)));
|
|
2014
|
+
console.log(cyan(aiPrompt(withHints.map(([out]) => out))));
|
|
1565
2015
|
}
|
|
1566
2016
|
if (failed)
|
|
1567
2017
|
process.exit(1);
|