@tolokoban/impress 0.3.0 → 0.16.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/dist/impress.js CHANGED
@@ -18,15 +18,37 @@
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
- * @graph diagram.dot Graphviz diagram converted into native, editable shapes
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
+ * @compact N { ... @} the blocks in between are compacted on one slide, in N columns (1 by
29
+ * default, "*" for the number giving the biggest text), shrunk if needed
30
+ * @reveal C1,3 R1-4 the rows of the next table appear one slide after the other; the
31
+ * columns (C) and rows (R) listed, both optional, are always visible
23
32
  * ```prompt ... ``` chat prompt bubble
24
33
  */
25
34
  import { existsSync, readFileSync, writeFileSync, statSync } from "node:fs";
26
- import { basename, dirname, extname, resolve } from "node:path";
35
+ import { basename, dirname, extname, join, resolve } from "node:path";
27
36
  import { crc32, deflateRawSync } from "node:zlib";
37
+ import { spawnSync } from "node:child_process";
38
+ import { createInterface } from "node:readline/promises";
39
+ import sharp from "sharp";
28
40
  import { defaultStyle } from "./styles.js";
29
41
  const PT = 0.03528; // cm per point
42
+ // ---------------------------------------------------------------- terminal colors
43
+ /** ANSI styles, only when writing to a terminal and NO_COLOR is not set. */
44
+ const COLOR = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
45
+ const ansi = (on, off) => (text) => (COLOR ? `\x1b[${on}m${text}\x1b[${off}m` : text);
46
+ /** File names. Ends with "normal intensity" only, so it can be nested in a colored text. */
47
+ const bold = ansi("1", "22");
48
+ /** Example of prompt for an AI agent. */
49
+ const cyan = ansi("36", "39");
50
+ /** Questions waiting for an answer. */
51
+ const yellow = ansi("93", "39");
30
52
  // Style of the file being converted (see `useStyle()`).
31
53
  let style = defaultStyle;
32
54
  let sizes = style.theme.sizes;
@@ -37,12 +59,14 @@ let Y0 = 0;
37
59
  let W = 0;
38
60
  let H = 0;
39
61
  let GAP = 0;
62
+ let CENTER = false;
40
63
  function useStyle(config) {
41
64
  style = config;
42
65
  sizes = config.theme.sizes;
43
66
  SLIDE_W = config.theme.slide.width;
44
67
  SLIDE_H = config.theme.slide.height;
45
68
  ({ x: X0, y: Y0, width: W, height: H, gap: GAP } = config.theme.content);
69
+ CENTER = config.theme.content.align === "center";
46
70
  }
47
71
  function isObject(v) {
48
72
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -88,6 +112,23 @@ function resolveValue(value, where) {
88
112
  return String(v);
89
113
  });
90
114
  }
115
+ /** Is this cell hidden until its row is revealed? */
116
+ function isHidden(b, row, col) {
117
+ return !!b.reveal && !!b.shown && !b.shown.has(row) && !b.reveal.rows.has(row) && !b.reveal.cols.has(col);
118
+ }
119
+ /** `1,3`, `1-4`, `2,5-7`: 1-based numbers, returned 0-based. */
120
+ function parseNumbers(spec, where) {
121
+ const out = [];
122
+ for (const part of spec.split(",")) {
123
+ const m = part.match(/^(\d+)(?:-(\d+))?$/);
124
+ const [a, b] = m ? [Number(m[1]), Number(m[2] ?? m[1])] : [0, 0];
125
+ if (!m || a < 1 || b < a)
126
+ throw new Error(`${where}: invalid list "${spec}" (expected numbers or ranges, e.g. 1,3 or 1-4)`);
127
+ for (let n = a; n <= b; n++)
128
+ out.push(n - 1);
129
+ }
130
+ return out;
131
+ }
91
132
  function cellCount(layout) {
92
133
  return layout.kind === "grid" ? layout.columns * layout.rows : layout.widths.length;
93
134
  }
@@ -149,16 +190,55 @@ function stripMd(s) {
149
190
  .replace(/(?<![\p{L}\p{N}_])\*(.+?)\*(?![\p{L}\p{N}_])/gu, "$1")
150
191
  .trim();
151
192
  }
152
- const LIST_RE = /^(\s*)[*-]\s+(.*)$/;
193
+ /** `- item`, `* item`, `1. item` or `1) item`: [indent, number (ordered only), text]. */
194
+ const LIST_RE = /^(\s*)(?:[*-]|(\d+)[.)])\s+(.*)$/;
153
195
  const IMG_RE = /^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/;
154
196
  const HEAD_RE = /^(#{1,6})\s+(.*)$/;
197
+ /** Horizontal rule: a line of at least three dashes. */
198
+ const HR_RE = /^-{3,}$/;
199
+ /** `@compact {`, `@compact 3 {` or `@compact * {`. */
200
+ const COMPACT_RE = /^@compact\s*(\d+|\*)?\s*\{$/;
155
201
  function parse(md, file) {
156
202
  const root = new Section(0, "", null, dirname(file));
157
203
  let cur = root;
158
204
  const lines = md.split("\n");
159
205
  let para = [];
160
206
  let list = null;
207
+ // Open `@compact {` region: its blocks go into it until `@}`.
208
+ let region = null;
161
209
  let layout = null;
210
+ // `@layout` followed by content instead of a heading: the next blocks fill its cells.
211
+ let grouped = null;
212
+ // Line number of an `@compact` waiting for its table (0 if none).
213
+ let compact = 0;
214
+ const dropCompact = () => {
215
+ if (compact)
216
+ console.warn(` ! ${bold(file)}:${compact}: "@compact" is not followed by a table`);
217
+ compact = 0;
218
+ };
219
+ // `@reveal` waiting for its table: line number, always visible columns and rows (0-based).
220
+ let reveal = null;
221
+ const dropReveal = () => {
222
+ if (reveal)
223
+ console.warn(` ! ${bold(file)}:${reveal.line}: "@reveal" is not followed by a table`);
224
+ reveal = null;
225
+ };
226
+ const push = (b) => {
227
+ if (region)
228
+ return void region.blocks.push(b);
229
+ if (!grouped)
230
+ return void cur.blocks.push(b);
231
+ const cells = grouped.cells;
232
+ if (b.t === "note")
233
+ return void (cells.length ? cells[cells.length - 1].blocks : cur.blocks).push(b);
234
+ if (cells.length === cellCount(grouped.layout)) {
235
+ grouped = null;
236
+ return void cur.blocks.push(b);
237
+ }
238
+ const cell = new Section(cur.level + 1, "", cur, root.source);
239
+ cell.blocks.push(b);
240
+ cells.push(cell);
241
+ };
162
242
  const flushPara = () => {
163
243
  if (!para.length)
164
244
  return;
@@ -168,12 +248,12 @@ function parse(md, file) {
168
248
  if (j < para.length - 1)
169
249
  text += l.endsWith(" ") ? "\n" : " ";
170
250
  });
171
- cur.blocks.push({ t: "para", text });
251
+ push({ t: "para", text });
172
252
  para = [];
173
253
  };
174
254
  const flushList = () => {
175
255
  if (list)
176
- cur.blocks.push(list);
256
+ push(list);
177
257
  list = null;
178
258
  };
179
259
  const flush = () => {
@@ -184,8 +264,14 @@ function parse(md, file) {
184
264
  const line = lines[i];
185
265
  const s = line.trim();
186
266
  let m;
267
+ if (region && (HEAD_RE.test(line) || s === "@next" || s.startsWith("@layout"))) {
268
+ const what = HEAD_RE.test(line) ? "a heading" : s === "@next" ? '"@next"' : '"@layout"';
269
+ throw new Error(`${file}:${i + 1}: ${what} cannot be inside a "@compact {" region (opened at line ${region.where.split(":").pop()}, closed by "@}")`);
270
+ }
187
271
  if ((m = line.match(HEAD_RE))) {
188
272
  flush();
273
+ dropCompact();
274
+ grouped = null;
189
275
  const level = m[1].length;
190
276
  while (cur.level >= level)
191
277
  cur = cur.parent;
@@ -197,10 +283,21 @@ function parse(md, file) {
197
283
  }
198
284
  else if (s.startsWith("@layout")) {
199
285
  flush();
200
- layout = parseLayout(s.slice(7).trim(), `${file}:${i + 1}`);
286
+ grouped = null;
287
+ const spec = parseLayout(s.slice(7).trim(), `${file}:${i + 1}`);
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
+ layout = spec;
293
+ else {
294
+ grouped = { t: "layout", layout: spec, cells: [] };
295
+ cur.blocks.push(grouped);
296
+ }
201
297
  }
202
298
  else if (s === "@next") {
203
299
  flush();
300
+ grouped = null;
204
301
  // A heading right after `@next` starts the new slide by itself.
205
302
  let j = i + 1;
206
303
  while (j < lines.length && lines[j].trim() === "")
@@ -214,6 +311,47 @@ function parse(md, file) {
214
311
  cur.parent.children.push(sec);
215
312
  cur = sec;
216
313
  }
314
+ else if ((m = s.match(COMPACT_RE))) {
315
+ const where = `${file}:${i + 1}`;
316
+ if (region)
317
+ throw new Error(`${where}: "@compact {" regions cannot be nested (one is already open since line ${region.where.split(":").pop()})`);
318
+ flush();
319
+ dropCompact();
320
+ dropReveal();
321
+ const columns = m[1] === "*" ? "auto" : Number(m[1] ?? 1);
322
+ if (columns === 0)
323
+ throw new Error(`${where}: a "@compact {" region needs at least one column`);
324
+ const b = { t: "compact", columns, blocks: [], where };
325
+ push(b);
326
+ region = b;
327
+ }
328
+ else if (s === "@}") {
329
+ if (!region)
330
+ throw new Error(`${file}:${i + 1}: "@}" without an open "@compact {" region`);
331
+ flush();
332
+ dropCompact();
333
+ dropReveal();
334
+ if (!region.blocks.some(b => b.t !== "note"))
335
+ console.warn(` ! ${bold(region.where)}: empty "@compact {" region`);
336
+ region = null;
337
+ }
338
+ else if (s === "@compact") {
339
+ flush();
340
+ dropCompact();
341
+ compact = i + 1;
342
+ }
343
+ else if (s === "@reveal" || s.startsWith("@reveal ")) {
344
+ flush();
345
+ dropReveal();
346
+ const where = `${file}:${i + 1}`;
347
+ reveal = { line: i + 1, cols: [], rows: [] };
348
+ for (const arg of s.slice(7).trim().split(/\s+/).filter(Boolean)) {
349
+ const m = arg.match(/^([CR])(.+)$/i);
350
+ if (!m)
351
+ throw new Error(`${where}: expected "@reveal [C<columns>] [R<rows>]" (e.g. "@reveal C1,3 R1-4"), got "${s}"`);
352
+ reveal[m[1].toUpperCase() === "C" ? "cols" : "rows"].push(...parseNumbers(m[2], where));
353
+ }
354
+ }
217
355
  else if (s.startsWith("@graph")) {
218
356
  flush();
219
357
  const src = s.slice(6).trim();
@@ -222,7 +360,7 @@ function parse(md, file) {
222
360
  throw new Error(`${where}: expected "@graph <relative path of a .dot file>", got "${s}"`);
223
361
  if (!existsSync(resolve(dirname(file), src)))
224
362
  throw new Error(`${where}: file not found: ${src}`);
225
- cur.blocks.push({ t: "image", alt: "", src });
363
+ push({ t: "image", alt: "", src });
226
364
  }
227
365
  else if (s.startsWith("@hint")) {
228
366
  flush();
@@ -233,11 +371,11 @@ function parse(md, file) {
233
371
  const buf = [];
234
372
  for (i++; i < lines.length && lines[i].trim() !== "@note end"; i++)
235
373
  buf.push(lines[i]);
236
- cur.blocks.push({ t: "note", text: buf.join("\n").trim() });
374
+ push({ t: "note", text: buf.join("\n").trim() });
237
375
  }
238
376
  else if (s.startsWith("@note")) {
239
377
  flush();
240
- cur.blocks.push({ t: "note", text: s.slice(5).trim() });
378
+ push({ t: "note", text: s.slice(5).trim() });
241
379
  }
242
380
  else if (s.startsWith("```")) {
243
381
  flush();
@@ -245,7 +383,7 @@ function parse(md, file) {
245
383
  const buf = [];
246
384
  for (i++; i < lines.length && !lines[i].trim().startsWith("```"); i++)
247
385
  buf.push(lines[i]);
248
- cur.blocks.push({ t: lang === "prompt" ? "prompt" : "code", lines: buf });
386
+ push({ t: lang === "prompt" ? "prompt" : "code", lines: buf });
249
387
  }
250
388
  else if (s.startsWith("|")) {
251
389
  flush();
@@ -259,7 +397,16 @@ function parse(md, file) {
259
397
  const body = rows.slice(1).filter(r => !/^[\s:\-|]*$/.test(r.join("")));
260
398
  if (header.every(c => c === "" || c === "."))
261
399
  header = null;
262
- cur.blocks.push({ t: "table", header, rows: body });
400
+ const table = { t: "table", header, rows: body };
401
+ if (compact)
402
+ table.compact = true;
403
+ compact = 0;
404
+ if (reveal) {
405
+ const { cols, rows: fixed } = reveal;
406
+ table.reveal = { cols: new Set(cols), rows: new Set(fixed.flatMap(n => (body[n] ? [body[n]] : []))) };
407
+ reveal = null;
408
+ }
409
+ push(table);
263
410
  }
264
411
  else if (s.startsWith(">")) {
265
412
  flush();
@@ -267,16 +414,23 @@ function parse(md, file) {
267
414
  for (; i < lines.length && lines[i].trim().startsWith(">"); i++)
268
415
  buf.push(lines[i].trim().slice(1).trim());
269
416
  i--;
270
- cur.blocks.push({ t: "quote", text: buf.join(" ") });
417
+ push({ t: "quote", text: buf.join(" ") });
418
+ }
419
+ else if (HR_RE.test(s)) {
420
+ flush();
421
+ push({ t: "hr" });
271
422
  }
272
423
  else if ((m = line.match(IMG_RE))) {
273
424
  flush();
274
- cur.blocks.push({ t: "image", alt: m[1], src: m[2] });
425
+ push({ t: "image", alt: m[1], src: m[2] });
275
426
  }
276
427
  else if ((m = line.match(LIST_RE))) {
277
428
  flushPara();
278
429
  list ??= { t: "list", items: [] };
279
- list.items.push([Math.floor(m[1].length / 2), m[2].trim()]);
430
+ const item = [Math.floor(m[1].length / 2), m[3].trim()];
431
+ if (m[2] !== undefined)
432
+ item.push(Number(m[2]));
433
+ list.items.push(item);
280
434
  }
281
435
  else if (s === "") {
282
436
  flushPara();
@@ -297,8 +451,12 @@ function parse(md, file) {
297
451
  }
298
452
  }
299
453
  flush();
454
+ dropCompact();
455
+ dropReveal();
456
+ if (region)
457
+ throw new Error(`${region.where}: "@compact {" region not closed by "@}"`);
300
458
  if (layout)
301
- console.warn(` ! ${file}: "${layout.source}" is not followed by any section`);
459
+ console.warn(` ! ${bold(file)}: "${layout.source}" is not followed by any section`);
302
460
  return root;
303
461
  }
304
462
  const INLINE_PATTERNS = [
@@ -389,51 +547,204 @@ function textH(nChars, width, pt, lh = 1.25) {
389
547
  const cpl = Math.max(1, width / (pt * PT * 0.5));
390
548
  return Math.max(1, Math.ceil(nChars / cpl)) * pt * PT * lh;
391
549
  }
392
- function paraH(text, width, pt = sizes.text) {
393
- return text.split("\n").reduce((h, p) => h + textH(plainLen(p), width, pt), 0) + 0.25;
550
+ function paraH(text, width, pt = sizes.text, k = 1) {
551
+ return text.split("\n").reduce((h, p) => h + textH(plainLen(p), width, pt), 0) + 0.25 * k;
394
552
  }
395
- function listH(items, width) {
553
+ function listH(items, width, k = 1) {
396
554
  let h = 0;
397
555
  for (const [lvl, txt] of items)
398
- h += textH(plainLen(txt), width - 0.9 * (lvl + 1), sizes.list[Math.min(lvl, 8)]) + 0.3;
556
+ h += textH(plainLen(txt), width - 0.9 * (lvl + 1), sizes.list[Math.min(lvl, 8)] * k) + 0.3 * k;
399
557
  return h + 0.1;
400
558
  }
401
- function promptSize(lines, width) {
402
- const pt = sizes.prompt;
559
+ function promptSize(lines, width, k = 1) {
560
+ const pt = sizes.prompt * k;
403
561
  const longest = Math.max(10, ...lines.map(l => l.length));
404
562
  const w = Math.min(width, Math.max(8, longest * pt * PT * 0.5 + 1.4));
405
563
  const h = lines.reduce((acc, l) => acc + textH(l.length, w - 1, pt), 0) + 0.9;
406
564
  return [w, h];
407
565
  }
566
+ // ---------------------------------------------------------------- images in table cells
567
+ /** Folder of the markdown file being converted, for the relative paths of cell images. */
568
+ let mdDir = ".";
569
+ /** `<img src="..." width="48" height="48">` or `![alt](src)`. */
570
+ const CELL_IMG_RE = /<img\s[^>]*>|!\[([^\]]*)\]\(([^)\s]+)\)/gi;
571
+ /** Pixels per em: the HTML sizes of the markdown assume a 16px font. */
572
+ const PX_PER_EM = 16;
573
+ /** Height (in em) of a cell image without any size. */
574
+ const DEFAULT_IMG_EM = 2;
575
+ /** Horizontal gap (in em) between the images of a cell, and between them and the text. */
576
+ const IMG_GAP_EM = 0.3;
577
+ /** Horizontal padding of the table cells (both sides), in cm. */
578
+ const CELL_PAD_X = 0.4;
579
+ const cellCache = new Map();
580
+ function htmlAttr(tag, name) {
581
+ const m = tag.match(new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
582
+ return m ? (m[1] ?? m[2] ?? m[3]) : undefined;
583
+ }
584
+ /** Split a table cell into its text and its images (HTML `<img>` or markdown `![]()`). */
585
+ function cell(s) {
586
+ let c = cellCache.get(s);
587
+ if (c)
588
+ return c;
589
+ const imgs = [];
590
+ const text = s
591
+ .replace(CELL_IMG_RE, (tag, mdAlt, mdSrc) => {
592
+ const src = mdSrc ?? htmlAttr(tag, "src");
593
+ if (!src)
594
+ return tag;
595
+ const px = (name) => {
596
+ const v = mdSrc ? undefined : htmlAttr(tag, name);
597
+ const n = v === undefined ? NaN : parseFloat(v);
598
+ return n > 0 ? n / PX_PER_EM : undefined;
599
+ };
600
+ let w = px("width");
601
+ let h = px("height");
602
+ if (w === undefined || h === undefined) {
603
+ const [iw, ih] = imageSize(resolve(mdDir, src));
604
+ if (w !== undefined)
605
+ h = (w * ih) / iw;
606
+ else if (h !== undefined)
607
+ w = (h * iw) / ih;
608
+ else
609
+ [w, h] = [(DEFAULT_IMG_EM * iw) / ih, DEFAULT_IMG_EM];
610
+ }
611
+ imgs.push({ src, alt: mdAlt ?? htmlAttr(tag, "alt") ?? "", w: w, h: h });
612
+ return " ";
613
+ })
614
+ .replace(/\s+/g, " ")
615
+ .trim();
616
+ c = { text, imgs };
617
+ cellCache.set(s, c);
618
+ return c;
619
+ }
620
+ /**
621
+ * Size (in cm) of the images of a cell at `pt` points, side by side: [scale, width, height].
622
+ * They are shrunk to fit in the column if needed (`scale` < 1).
623
+ */
624
+ function cellImgBox(c, colW, pt) {
625
+ if (!c.imgs.length)
626
+ return [1, 0, 0];
627
+ const em = pt * PT;
628
+ const w = (c.imgs.reduce((a, i) => a + i.w, 0) + IMG_GAP_EM * (c.imgs.length - 1)) * em;
629
+ const h = Math.max(...c.imgs.map(i => i.h)) * em;
630
+ const room = Math.max(colW - CELL_PAD_X - (c.text ? 2 * em : 0), 0.1);
631
+ const scale = Math.min(1, room / w);
632
+ return [scale, w * scale, h * scale];
633
+ }
634
+ /** Width (in cm) taken by the images of a cell before its text, gap included. */
635
+ function cellTextIndent(c, colW, pt) {
636
+ const [, w] = cellImgBox(c, colW, pt);
637
+ return w && c.text ? w + IMG_GAP_EM * pt * PT : 0;
638
+ }
639
+ /**
640
+ * Advance widths (in 1/1000 em) of the printable ASCII characters, from space to "~", in
641
+ * Liberation Sans Bold (the metrics of Arial Bold): the font of the table headers.
642
+ */
643
+ const BOLD_WIDTHS = [
644
+ 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556,
645
+ 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778,
646
+ 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611,
647
+ 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584,
648
+ ];
649
+ /** Width (in cm) of a word in bold at `pt` points, a bit overestimated to be safe. */
650
+ function boldWordW(word, pt) {
651
+ let units = 0;
652
+ for (const ch of word) {
653
+ // Accented letters are as wide as their base letter.
654
+ const code = ch.normalize("NFD").charCodeAt(0);
655
+ units += code >= 32 && code <= 126 ? BOLD_WIDTHS[code - 32] : 650;
656
+ }
657
+ return (units / 1000) * pt * PT * 1.05;
658
+ }
659
+ /**
660
+ * Do the words of the header of a `@compact` or `@reveal` table fit in their columns, at the
661
+ * size of the table, on a slide of full width? Several words may wrap, but no word is cut.
662
+ */
663
+ function headerFits(b, width = W) {
664
+ if (!b.header)
665
+ return true;
666
+ const pt = b.pt ?? sizes.table;
667
+ const cols = tableBlockCols(b, width);
668
+ return b.header.every((s, i) => {
669
+ const c = cell(s);
670
+ const room = cols[i] - CELL_PAD_X - cellTextIndent(c, cols[i], pt);
671
+ const words = inline(c.text)
672
+ .map(r => r.text)
673
+ .join("")
674
+ .split(/\s+/)
675
+ .filter(Boolean);
676
+ return words.every(w => boldWordW(w, pt) <= room);
677
+ });
678
+ }
408
679
  function tableCols(header, rows, width) {
409
680
  const all = header ? [header, ...rows] : rows;
410
681
  const ncol = Math.max(...all.map(r => r.length));
411
682
  const lens = new Array(ncol).fill(0);
412
683
  for (const r of all)
413
- r.forEach((cell, c) => (lens[c] = Math.max(lens[c], Math.min(plainLen(cell), 45) + 4)));
684
+ r.forEach((s, c) => {
685
+ const { text, imgs } = cell(s);
686
+ // An em is about two characters (see `textH()`).
687
+ const imgLen = imgs.length ? 2 * (imgs.reduce((a, i) => a + i.w, 0) + IMG_GAP_EM * imgs.length) : 0;
688
+ lens[c] = Math.max(lens[c], Math.min(plainLen(text), 45) + imgLen + 4);
689
+ });
414
690
  const tot = lens.reduce((a, b) => a + b, 0);
415
691
  return lens.map(l => (width * l) / tot);
416
692
  }
417
693
  function rowH(r, cols, pt) {
418
- return Math.max(...r.map((c, i) => textH(plainLen(c), cols[i] - 0.4, pt))) + 0.35;
694
+ // Below the size of small tables (`@compact`), the room around the text shrinks too, down to the cell padding.
695
+ const pad = pt >= sizes.tableSmall ? 0.35 : 0.2 + (0.15 * pt) / sizes.tableSmall;
696
+ return (Math.max(...r.map((s, i) => {
697
+ const c = cell(s);
698
+ const th = c.text ? textH(plainLen(c.text), cols[i] - CELL_PAD_X - cellTextIndent(c, cols[i], pt), pt) : 0;
699
+ return Math.max(th, cellImgBox(c, cols[i], pt)[2]);
700
+ })) + pad);
419
701
  }
420
702
  function tableH(header, rows, width, pt, cols) {
421
703
  cols ??= tableCols(header, rows, width);
422
704
  return (header ? [header, ...rows] : rows).reduce((h, r) => h + rowH(r, cols, pt), 0);
423
705
  }
706
+ /** Horizontal gap between the side-by-side parts of a table. */
707
+ const TABLE_GAP = 0.6;
708
+ /** Rows of each side-by-side part of a table block. */
709
+ function tableParts(b) {
710
+ const n = b.columns ?? 1;
711
+ if (n <= 1)
712
+ return [b.rows];
713
+ const per = Math.ceil(b.rows.length / n);
714
+ return Array.from({ length: n }, (_, i) => b.rows.slice(i * per, (i + 1) * per)).filter(p => p.length);
715
+ }
716
+ function tablePartW(b, width) {
717
+ const n = b.columns ?? 1;
718
+ return (width - TABLE_GAP * (n - 1)) / n;
719
+ }
720
+ /** Column widths of each part, the same for all the parts of a table. */
721
+ function tableBlockCols(b, width) {
722
+ return tableCols(b.header, b.ref ?? b.rows, tablePartW(b, width));
723
+ }
724
+ function tableBlockH(b, width) {
725
+ const cols = tableBlockCols(b, width);
726
+ const pw = tablePartW(b, width);
727
+ return Math.max(...tableParts(b).map(rows => tableH(b.header, rows, pw, b.pt ?? sizes.table, cols)));
728
+ }
729
+ /** Height taken by a horizontal rule (the line is drawn in its middle). */
730
+ const HR_H = 0.5;
424
731
  function blockH(b, width) {
425
732
  switch (b.t) {
426
733
  case "para":
427
- return paraH(b.text, width);
734
+ return paraH(b.text, width, sizes.text * (b.k ?? 1), b.k);
428
735
  case "list":
429
- return listH(b.items, width);
736
+ return listH(b.items, width, b.k);
430
737
  case "quote":
431
- return paraH(b.text, width - 1.2, sizes.quote) + 0.8;
738
+ return paraH(b.text, width - 1.2, sizes.quote * (b.k ?? 1), b.k) + 0.8;
432
739
  case "prompt":
433
740
  case "code":
434
- return promptSize(b.lines, width)[1];
741
+ return promptSize(b.lines, width, b.k)[1];
435
742
  case "table":
436
- return tableH(b.header, b.rows, width, sizes.table);
743
+ return tableBlockH(b, width);
744
+ case "hr":
745
+ return HR_H;
746
+ case "compact":
747
+ return arrange(b, width).h;
437
748
  default:
438
749
  return 0;
439
750
  }
@@ -441,7 +752,7 @@ function blockH(b, width) {
441
752
  function imageSize(path) {
442
753
  const ext = extname(path).toLowerCase();
443
754
  if (ext === ".dot")
444
- return graphLayout(path).size;
755
+ return graphPng(path).size;
445
756
  const data = readFileSync(path);
446
757
  if (ext === ".svg") {
447
758
  const head = data.subarray(0, 4000).toString("utf8");
@@ -479,151 +790,389 @@ function fit(iw, ih, bw, bh) {
479
790
  const r = Math.min(bw / iw, bh / ih);
480
791
  return [iw * r, ih * r];
481
792
  }
482
- // ---------------------------------------------------------------- graphviz
483
- const CM_PER_POINT = 2.54 / 72;
793
+ // ---------------------------------------------------------------- compact regions
794
+ /** Lowest font scale of a `@compact {` region: 10pt for a body text of 24pt. */
795
+ const MIN_COMPACT_SCALE = 10 / 24;
796
+ /** Highest number of columns tried by `@compact * {`. */
797
+ const MAX_AUTO_COLUMNS = 8;
798
+ /** Font scales tried for a `@compact {` region, biggest first: the body text loses half a point at each step. */
799
+ function compactScales() {
800
+ const out = [];
801
+ for (let pt = sizes.text; pt >= sizes.text * MIN_COMPACT_SCALE - 1e-6; pt -= 0.5)
802
+ out.push(pt / sizes.text);
803
+ return out;
804
+ }
805
+ const piecesCache = new WeakMap();
806
+ function compactPieces(blocks) {
807
+ let out = piecesCache.get(blocks);
808
+ if (out)
809
+ return out;
810
+ const pieces = [];
811
+ for (const b of blocks) {
812
+ if (b.t === "note")
813
+ continue;
814
+ if (b.t === "list") {
815
+ let start = 0;
816
+ b.items.forEach((it, i) => {
817
+ if (i > start && it[0] === 0) {
818
+ pieces.push({ src: b, block: { ...b, items: b.items.slice(start, i) } });
819
+ start = i;
820
+ }
821
+ });
822
+ pieces.push({ src: b, block: { ...b, items: b.items.slice(start) } });
823
+ }
824
+ else if (b.t === "table" && b.rows.length > 1) {
825
+ for (const r of b.rows)
826
+ pieces.push({ src: b, block: { ...b, rows: [r] } });
827
+ }
828
+ else
829
+ pieces.push({ src: b, block: b });
830
+ }
831
+ piecesCache.set(blocks, (out = pieces));
832
+ return out;
833
+ }
834
+ /** A block of a region at the font scale `k`. Tables keep the column widths of all their rows. */
835
+ function scaleBlock(b, src, k) {
836
+ if (b.t === "table")
837
+ return { ...b, pt: sizes.table * k, ref: src.rows, compact: undefined, columns: undefined };
838
+ if (b.t === "hr" || b.t === "note" || b.t === "layout" || b.t === "compact")
839
+ return b;
840
+ return { ...b, k };
841
+ }
842
+ /** The blocks of a column: consecutive pieces of the same list or table are merged back together. */
843
+ function mergePieces(pieces, k) {
844
+ const out = [];
845
+ pieces.forEach((p, i) => {
846
+ const last = out[out.length - 1];
847
+ const same = i > 0 && pieces[i - 1].src === p.src;
848
+ if (same && last.t === "list" && p.block.t === "list")
849
+ out[out.length - 1] = { ...last, items: [...last.items, ...p.block.items] };
850
+ else if (same && last.t === "table" && p.block.t === "table")
851
+ out[out.length - 1] = { ...last, rows: [...last.rows, ...p.block.rows] };
852
+ else
853
+ out.push(scaleBlock(p.block, p.src, k));
854
+ });
855
+ return out;
856
+ }
857
+ /** Height of a block in a column of a region. An image takes the width of the column, up to the (scaled) height of the slide. */
858
+ function regionBlockH(b, width) {
859
+ if (b.t !== "image")
860
+ return blockH(b, width);
861
+ return regionImageSize(b, width)[1];
862
+ }
863
+ function regionImageSize(b, width) {
864
+ const [iw, ih] = imageSize(resolve(mdDir, b.src));
865
+ return fit(iw, ih, width, H * (b.k ?? 1));
866
+ }
867
+ const arrangeCache = new WeakMap();
868
+ /**
869
+ * Lay out a region at its scale and number of columns (fewer if it has fewer pieces) in `width`.
870
+ * The pieces flow in reading order through the columns, cut so that the tallest column is as
871
+ * short as possible.
872
+ */
873
+ function arrange(b, width) {
874
+ const k = b.k ?? 1;
875
+ const pieces = compactPieces(b.blocks);
876
+ const P = pieces.length;
877
+ const n = Math.max(1, Math.min(b.n ?? (b.columns === "auto" ? 1 : b.columns), P));
878
+ const key = `${f2(width)}|${n}|${k}`;
879
+ let cache = arrangeCache.get(b.blocks);
880
+ if (!cache)
881
+ arrangeCache.set(b.blocks, (cache = new Map()));
882
+ const hit = cache.get(key);
883
+ if (hit)
884
+ return hit;
885
+ // 1em of the (scaled) body text between the columns.
886
+ const gap = sizes.text * k * PT;
887
+ const colW = (width - gap * (n - 1)) / n;
888
+ const memo = new Map();
889
+ /** Height of the column holding the pieces `i` to `j - 1`. */
890
+ const colH = (i, j) => {
891
+ let h = memo.get(i * (P + 1) + j);
892
+ if (h === undefined) {
893
+ const bs = mergePieces(pieces.slice(i, j), k);
894
+ h = bs.reduce((a, x) => a + regionBlockH(x, colW), 0) + GAP * k * (bs.length - 1);
895
+ memo.set(i * (P + 1) + j, h);
896
+ }
897
+ return h;
898
+ };
899
+ // best[c][j]: lowest height of the tallest of `c` columns holding the first `j` pieces;
900
+ // cut[c][j]: first piece of the last of these columns.
901
+ const best = [Array.from({ length: P + 1 }, (_, j) => (j ? Infinity : 0))];
902
+ const cut = [[]];
903
+ for (let c = 1; c <= n; c++) {
904
+ best.push(new Array(P + 1).fill(Infinity));
905
+ cut.push(new Array(P + 1).fill(0));
906
+ for (let j = c; j <= P; j++)
907
+ for (let i = c - 1; i < j; i++) {
908
+ const h = Math.max(best[c - 1][i], colH(i, j));
909
+ if (h < best[c][j]) {
910
+ best[c][j] = h;
911
+ cut[c][j] = i;
912
+ }
913
+ }
914
+ }
915
+ const cols = [];
916
+ if (P)
917
+ for (let c = n, j = P; c > 0; c--) {
918
+ const i = cut[c][j];
919
+ cols.unshift(mergePieces(pieces.slice(i, j), k));
920
+ j = i;
921
+ }
922
+ const out = { n, k, colW, gap, cols, h: P ? best[n][P] : 0 };
923
+ cache.set(key, out);
924
+ return out;
925
+ }
926
+ /**
927
+ * Do the words of a laid out region fit in its columns? The words of the table headers are always
928
+ * checked (as for `@compact` tables); those of the paragraphs, quotes and lists only when `all`.
929
+ */
930
+ function regionWordsFit(arr, all) {
931
+ const fits = (text, room, pt) => inline(text)
932
+ .map(r => r.text)
933
+ .join("")
934
+ .split(/\s+/)
935
+ .filter(Boolean)
936
+ .every(w => boldWordW(w, pt) <= room);
937
+ return arr.cols.every(col => col.every(b => {
938
+ if (b.t === "table")
939
+ return headerFits(b, arr.colW);
940
+ if (!all)
941
+ return true;
942
+ if (b.t === "para")
943
+ return fits(b.text, arr.colW - 0.5, sizes.text * arr.k);
944
+ if (b.t === "quote")
945
+ return fits(b.text, arr.colW - 1.7, sizes.quote * arr.k);
946
+ if (b.t === "list")
947
+ return b.items.every(([lvl, txt]) => fits(txt, arr.colW - 0.9 * (lvl + 1), sizes.list[Math.min(lvl, 8)] * arr.k));
948
+ return true;
949
+ }));
950
+ }
951
+ /** The tables of some blocks, including those of their `@compact {` regions. */
952
+ function tablesOf(blocks) {
953
+ return blocks.flatMap(b => (b.t === "table" ? [b] : b.t === "compact" ? tablesOf(b.blocks) : []));
954
+ }
955
+ /** Rendered diagrams, keyed by the arguments of `dot` (which include the theme). */
484
956
  const graphCache = new Map();
485
- /** Graphviz compiled to WebAssembly (`@hpcc-js/wasm-graphviz`), loaded by `loadGraphviz()`. */
486
- let graphviz = null;
487
- let graphvizError = "";
488
- async function loadGraphviz() {
489
- try {
490
- const lib = await import("@hpcc-js/wasm-graphviz");
491
- graphviz = await lib.Graphviz.load();
957
+ const IS_WINDOWS = process.platform === "win32";
958
+ /** Path of the Graphviz `dot` executable: `undefined` until searched, `null` if not found. */
959
+ let dotPath;
960
+ function hasCommand(cmd) {
961
+ const r = IS_WINDOWS
962
+ ? spawnSync("where", [cmd], { stdio: "ignore" })
963
+ : spawnSync("sh", ["-c", `command -v ${cmd}`], { stdio: "ignore" });
964
+ return r.status === 0;
965
+ }
966
+ /** `dot` from the PATH, or from the usual install folders (a fresh install may not be in the PATH yet). */
967
+ function findDot() {
968
+ if (hasCommand("dot"))
969
+ return "dot";
970
+ const candidates = IS_WINDOWS
971
+ ? [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "Programs")]
972
+ .filter((d) => !!d)
973
+ .map(d => join(d, "Graphviz", "bin", "dot.exe"))
974
+ : ["/opt/homebrew/bin/dot", "/usr/local/bin/dot", "/opt/local/bin/dot", "/usr/bin/dot"];
975
+ return candidates.find(p => existsSync(p)) ?? null;
976
+ }
977
+ /** The command installing Graphviz on this system, if a known package manager is available. */
978
+ function installCommand() {
979
+ const sudo = !IS_WINDOWS && process.getuid?.() !== 0 && hasCommand("sudo") ? ["sudo"] : [];
980
+ const managers = process.platform === "darwin"
981
+ ? [
982
+ ["brew", ["brew", "install", "graphviz"]],
983
+ ["port", [...sudo, "port", "install", "graphviz"]],
984
+ ]
985
+ : IS_WINDOWS
986
+ ? [
987
+ ["winget", ["winget", "install", "--id", "Graphviz.Graphviz", "-e", "--accept-package-agreements", "--accept-source-agreements"]],
988
+ ["choco", ["choco", "install", "graphviz", "-y"]],
989
+ ["scoop", ["scoop", "install", "graphviz"]],
990
+ ]
991
+ : [
992
+ ["apt-get", [...sudo, "apt-get", "install", "-y", "graphviz"]],
993
+ ["dnf", [...sudo, "dnf", "install", "-y", "graphviz"]],
994
+ ["yum", [...sudo, "yum", "install", "-y", "graphviz"]],
995
+ ["pacman", [...sudo, "pacman", "-S", "--noconfirm", "graphviz"]],
996
+ ["zypper", [...sudo, "zypper", "install", "-y", "graphviz"]],
997
+ ["apk", [...sudo, "apk", "add", "graphviz"]],
998
+ ["brew", ["brew", "install", "graphviz"]],
999
+ ];
1000
+ return managers.find(([cmd]) => hasCommand(cmd))?.[1] ?? null;
1001
+ }
1002
+ /**
1003
+ * Make sure the Graphviz `dot` tool is available, offering to install it if it is not.
1004
+ * Searched once per run; `graphPng()` fails with an explanation if it is still missing.
1005
+ */
1006
+ async function ensureDot() {
1007
+ if (dotPath !== undefined)
1008
+ return;
1009
+ dotPath = findDot();
1010
+ if (dotPath)
1011
+ return;
1012
+ console.log(" ! @graph needs the Graphviz \"dot\" tool, which is not installed on this machine.");
1013
+ const cmd = installCommand();
1014
+ if (!cmd) {
1015
+ console.log(" Install Graphviz (https://graphviz.org/download/), then run again.");
1016
+ return;
492
1017
  }
493
- catch (err) {
494
- graphvizError = err instanceof Error ? err.message : String(err);
1018
+ const shown = cmd.join(" ");
1019
+ if (!process.stdin.isTTY) {
1020
+ console.log(` Install it with: ${shown}`);
1021
+ return;
1022
+ }
1023
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1024
+ const answer = (await rl.question(yellow(` Install it now with "${shown}"? [Y/n] `))).trim().toLowerCase();
1025
+ rl.close();
1026
+ if (answer && !["y", "yes", "o", "oui"].includes(answer))
1027
+ return;
1028
+ const r = spawnSync(cmd[0], cmd.slice(1), { stdio: "inherit", shell: IS_WINDOWS });
1029
+ if (r.status !== 0)
1030
+ console.log(` Installation failed${r.error ? `: ${r.error.message}` : ""}.`);
1031
+ dotPath = findDot();
1032
+ if (dotPath)
1033
+ console.log(` Graphviz installed (${dotPath}).`);
1034
+ else if (r.status === 0)
1035
+ console.log(" Graphviz is installed, but \"dot\" is not found yet: open a new terminal and run again.");
1036
+ }
1037
+ /** Does this markdown use `@graph` (outside code blocks)? */
1038
+ function usesGraph(src) {
1039
+ let fenced = false;
1040
+ for (const line of readFileSync(src, "utf8").split(/\r?\n/)) {
1041
+ const s = line.trim();
1042
+ if (s.startsWith("```"))
1043
+ fenced = !fenced;
1044
+ else if (!fenced && s.startsWith("@graph"))
1045
+ return true;
1046
+ }
1047
+ return false;
1048
+ }
1049
+ /** An argument as typed in a shell, quoted when needed. */
1050
+ function shellArg(arg) {
1051
+ return /^[\w@%+=:,./#-]+$/.test(arg) ? arg : `"${arg.replace(/(["\\$`])/g, "\\$1")}"`;
1052
+ }
1053
+ /**
1054
+ * Index just after the `{` opening the body of the root graph of a DOT source
1055
+ * (skipping comments and quoted strings), or -1 if there is none.
1056
+ */
1057
+ function dotBodyStart(dot) {
1058
+ let i = 0;
1059
+ let lineStart = true;
1060
+ while (i < dot.length) {
1061
+ const c = dot[i];
1062
+ if (lineStart && c === "#") {
1063
+ // Preprocessor-like line, ignored by Graphviz.
1064
+ const end = dot.indexOf("\n", i);
1065
+ i = end < 0 ? dot.length : end;
1066
+ continue;
1067
+ }
1068
+ if (c === "\n")
1069
+ lineStart = true;
1070
+ else if (!/\s/.test(c))
1071
+ lineStart = false;
1072
+ if (c === "/" && dot[i + 1] === "/") {
1073
+ const end = dot.indexOf("\n", i);
1074
+ i = end < 0 ? dot.length : end;
1075
+ continue;
1076
+ }
1077
+ if (c === "/" && dot[i + 1] === "*") {
1078
+ const end = dot.indexOf("*/", i + 2);
1079
+ i = end < 0 ? dot.length : end + 2;
1080
+ continue;
1081
+ }
1082
+ if (c === '"') {
1083
+ i++;
1084
+ while (i < dot.length && dot[i] !== '"')
1085
+ i += dot[i] === "\\" ? 2 : 1;
1086
+ i++;
1087
+ continue;
1088
+ }
1089
+ if (c === "<") {
1090
+ // HTML-like ID: balanced angle brackets.
1091
+ let depth = 0;
1092
+ do {
1093
+ if (dot[i] === "<")
1094
+ depth++;
1095
+ else if (dot[i] === ">")
1096
+ depth--;
1097
+ i++;
1098
+ } while (i < dot.length && depth > 0);
1099
+ continue;
1100
+ }
1101
+ if (c === "{")
1102
+ return i + 1;
1103
+ i++;
495
1104
  }
1105
+ return -1;
1106
+ }
1107
+ /** A DOT attribute list: `[a="x", b="y"]`. */
1108
+ function dotAttrs(attrs) {
1109
+ return `[${Object.entries(attrs)
1110
+ .map(([k, v]) => `${k}="${String(v).replace(/(["\\])/g, "\\$1")}"`)
1111
+ .join(", ")}]`;
496
1112
  }
497
1113
  /**
498
- * Lay out a .dot file with Graphviz, using the fonts of the current style.
499
- * The fonts are inserted as default attributes after the opening brace, so
500
- * attributes set in the .dot file still take precedence.
1114
+ * Render a .dot file as PNG with Graphviz (its own Cairo renderer, as in DOT viewers:
1115
+ * LibreOffice's SVG import changes the look of Graphviz SVGs), using the fonts and colors of the
1116
+ * current style. They are inserted as `graph`/`node`/`edge` default statements at the very
1117
+ * beginning of the root graph body, so every attribute set in the .dot file (including its own
1118
+ * `node [...]` / `edge [...]` defaults) still takes precedence. They are NOT given on the command
1119
+ * line: Graphviz's `-N`/`-E` options override the defaults declared in the file.
1120
+ * The resolution is `theme.graph.dpi`.
501
1121
  */
502
- function graphLayout(path) {
503
- if (!graphviz)
504
- throw new Error(`Graphviz is not available (run "pnpm install" in scripts/impress): ${graphvizError}`);
1122
+ function graphPng(path) {
1123
+ if (!dotPath)
1124
+ throw new Error(`${path}: the Graphviz "dot" tool is required by @graph (https://graphviz.org/download/)`);
505
1125
  const font = style.theme.fonts.sans.replace(/'/g, "");
506
- const defaults = `graph [fontname="${font}", fontsize=${sizes.graphEdgeText}]; ` +
507
- `node [fontname="${font}", fontsize=${sizes.graphText}]; ` +
508
- `edge [fontname="${font}", fontsize=${sizes.graphEdgeText}]; `;
1126
+ const { colors } = style.theme;
1127
+ const dpi = style.theme.graph.dpi;
509
1128
  const source = readFileSync(path, "utf8");
510
- const head = source.match(/\b(?:strict\s+)?(?:di)?graph\b[^{]*\{/i);
511
- if (!head || head.index === undefined)
512
- throw new Error(`${path}: no "graph { ... }" or "digraph { ... }" found`);
513
- const at = head.index + head[0].length;
514
- const dot = source.slice(0, at) + defaults + source.slice(at);
515
- let layout = graphCache.get(dot);
516
- if (layout)
517
- return layout;
518
- let json;
519
- try {
520
- json = graphviz.layout(dot, "json", "dot");
1129
+ const at = dotBodyStart(source);
1130
+ if (at < 0)
1131
+ throw new Error(`${path}: no graph body found (expected "graph { ... }" or "digraph { ... }")`);
1132
+ const defaults = [
1133
+ `graph ${dotAttrs({
1134
+ bgcolor: "transparent",
1135
+ fontname: font,
1136
+ fontsize: sizes.graphEdgeText,
1137
+ fontcolor: colors.primary,
1138
+ style: "filled",
1139
+ fillcolor: colors.graphCluster,
1140
+ pencolor: colors.muted,
1141
+ })};`,
1142
+ `node ${dotAttrs({
1143
+ fontname: font,
1144
+ fontsize: sizes.graphText,
1145
+ fontcolor: colors.ink,
1146
+ style: "filled",
1147
+ fillcolor: colors.graphNode,
1148
+ color: colors.primary,
1149
+ })};`,
1150
+ `edge ${dotAttrs({
1151
+ fontname: font,
1152
+ fontsize: sizes.graphEdgeText,
1153
+ fontcolor: colors.ink,
1154
+ color: colors.ink,
1155
+ })};`,
1156
+ ].join(" ");
1157
+ const input = `${source.slice(0, at)} ${defaults}\n${source.slice(at)}`;
1158
+ // The dpi stays on the command line: it is not a matter of style, the file must not change it.
1159
+ const args = ["-Tpng", `-Gdpi=${dpi}`];
1160
+ const key = [...args, input].join("\0");
1161
+ let graph = graphCache.get(key);
1162
+ if (graph)
1163
+ return graph;
1164
+ console.log(` ${bold(cyan("> "))}${bold([dotPath, ...args].map(shellArg).join(" "))} < ${shellArg(path)} ${cyan("(with the theme defaults)")}`);
1165
+ const r = spawnSync(dotPath, args, { input, maxBuffer: 256 * 1024 * 1024 });
1166
+ if (r.error || r.status !== 0) {
1167
+ throw new Error(`Graphviz failed on ${path}: ${r.error?.message ?? r.stderr.toString("utf8").trim()}`);
521
1168
  }
522
- catch (err) {
523
- throw new Error(`Graphviz failed on ${path}: ${err instanceof Error ? err.message : err}`);
524
- }
525
- const g = JSON.parse(json);
526
- const bb = String(g.bb ?? "0,0,0,0").split(",").map(Number);
527
- layout = {
528
- name: g.name ?? "",
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];
1169
+ const png = r.stdout;
1170
+ if (png.length < 24 || png.readUInt32BE(0) !== 0x89504e47)
1171
+ throw new Error(`Graphviz did not produce a PNG for ${path}`);
1172
+ const cmPerPixel = 2.54 / dpi;
1173
+ graph = { png, size: [png.readUInt32BE(16) * cmPerPixel, png.readUInt32BE(20) * cmPerPixel] };
1174
+ graphCache.set(key, graph);
1175
+ return graph;
627
1176
  }
628
1177
  // ---------------------------------------------------------------- layout
629
1178
  const MIME = {
@@ -633,32 +1182,81 @@ const MIME = {
633
1182
  ".jpg": "image/jpeg",
634
1183
  ".jpeg": "image/jpeg",
635
1184
  };
1185
+ /**
1186
+ * Encode the pictures as WebP (`theme.images.quality`), shrunk so that their longest side
1187
+ * is at most `theme.images.maxSize` pixels. SVG images are rasterized at that size too.
1188
+ * A WebP already small enough is kept as is, to avoid losing quality twice.
1189
+ */
1190
+ async function encodePictures(pics) {
1191
+ const { quality, maxSize } = style.theme.images;
1192
+ await Promise.all(pics.map(async (pic) => {
1193
+ const input = pic.data;
1194
+ const isSvg = /^\s*(<\?xml|<svg|<!--|<!DOCTYPE)/i.test(input.subarray(0, 256).toString("utf8"));
1195
+ let density;
1196
+ if (isSvg) {
1197
+ // Rasterize at maxSize pixels for the longest side (72 dpi = 1 SVG unit per pixel).
1198
+ const longest = Math.max(pic.size[0], pic.size[1], 1);
1199
+ density = Math.min(Math.max((72 * maxSize) / longest, 1), 100000);
1200
+ }
1201
+ const img = sharp(input, { density, limitInputPixels: false });
1202
+ const meta = await img.metadata();
1203
+ const big = Math.max(meta.width ?? 0, meta.height ?? 0) > maxSize;
1204
+ if (meta.format === "webp" && !big)
1205
+ return;
1206
+ pic.data = await img
1207
+ .rotate() // apply the EXIF orientation of photos
1208
+ .resize({ width: maxSize, height: maxSize, fit: "inside", withoutEnlargement: true })
1209
+ .webp({ quality })
1210
+ .toBuffer();
1211
+ }));
1212
+ }
1213
+ /** Geometry of section slides: title at the top, bar under it, then the box of the hierarchy. */
1214
+ const SEC = { x: 2, w: 24, titleY: 0.5, titleH: 2.6, barY: 3.1, boxY: 3.7, boxBottom: 15 };
636
1215
  const f2 = (n) => n.toFixed(2);
1216
+ /**
1217
+ * The content of one slide, once per step of its `@reveal` tables: the first step shows their
1218
+ * header and their always visible cells, each following step reveals one more row (tables in
1219
+ * the order of the slide, rows in reading order). Rows with nothing to reveal are skipped.
1220
+ */
1221
+ function revealSteps(content) {
1222
+ const revealed = tablesOf(content).filter(b => b.reveal);
1223
+ if (!revealed.length)
1224
+ return [content];
1225
+ const order = revealed.flatMap(b => b.rows.filter(r => !b.reveal.rows.has(r) && r.some((c, i) => c !== "" && !b.reveal.cols.has(i))));
1226
+ return Array.from({ length: order.length + 1 }, (_, k) => {
1227
+ const shown = new Set(order.slice(0, k));
1228
+ return content.map(b => (b.t === "table" && b.reveal) || (b.t === "compact" && tablesOf(b.blocks).some(t => t.reveal)) ? { ...b, shown } : b);
1229
+ });
1230
+ }
637
1231
  class Builder {
638
1232
  base;
639
1233
  pictures = new Map();
640
1234
  pages = [];
641
1235
  colStyles = new Map();
642
1236
  rowStyles = new Map();
1237
+ paraStyles = new Map();
643
1238
  /** Hints waiting to be attached to the next slide title. */
644
1239
  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;
1240
+ /** Heading path of the section of the last slide. */
1241
+ lastPath = [];
1242
+ /** Section of the slides being built. */
1243
+ current = null;
650
1244
  constructor(base) {
651
1245
  this.base = base;
1246
+ mdDir = base;
1247
+ cellCache.clear();
652
1248
  }
653
1249
  // -- resources
654
1250
  picture(src) {
655
1251
  let pic = this.pictures.get(src);
656
1252
  if (!pic) {
657
1253
  const path = resolve(this.base, src);
658
- let name = basename(src);
1254
+ const isGraph = extname(src).toLowerCase() === ".dot";
1255
+ let name = `${basename(src, extname(src))}.webp`;
659
1256
  while ([...this.pictures.values()].some(p => p.href === `Pictures/${name}`))
660
1257
  name = `_${name}`;
661
- pic = { href: `Pictures/${name}`, data: readFileSync(path), size: imageSize(path) };
1258
+ const graph = isGraph ? graphPng(path) : null;
1259
+ pic = { href: `Pictures/${name}`, data: graph ? graph.png : readFileSync(path), size: graph ? graph.size : imageSize(path) };
662
1260
  this.pictures.set(src, pic);
663
1261
  }
664
1262
  return pic;
@@ -669,6 +1267,26 @@ class Builder {
669
1267
  this.colStyles.set(key, `co${this.colStyles.size + 1}`);
670
1268
  return this.colStyles.get(key);
671
1269
  }
1270
+ /**
1271
+ * Automatic paragraph style setting the font size (in points) of a `@compact` table,
1272
+ * and the left margin (in cm) leaving room for the images of a cell.
1273
+ */
1274
+ paraStyle(pt, indent = 0, margins) {
1275
+ const key = [f2(pt), indent ? f2(indent) : "", margins ? margins.map(f2).join(",") : ""].join("/");
1276
+ if (!this.paraStyles.has(key))
1277
+ this.paraStyles.set(key, `Pt${this.paraStyles.size + 1}`);
1278
+ return this.paraStyles.get(key);
1279
+ }
1280
+ /**
1281
+ * Style attribute of a paragraph of `pt` points shrunk by a `@compact {` region (nothing when
1282
+ * `k` is 1). The spacing above and below the paragraphs of the style `name` shrinks too.
1283
+ */
1284
+ scaledPara(pt, k = 1, name) {
1285
+ if (k === 1)
1286
+ return "";
1287
+ const margins = name ? [styleCm(name, "fo:margin-top") * k, styleCm(name, "fo:margin-bottom") * k] : undefined;
1288
+ return ` text:style-name="${this.paraStyle(pt * k, 0, margins)}"`;
1289
+ }
672
1290
  rowStyle(h) {
673
1291
  const key = f2(h);
674
1292
  if (!this.rowStyles.has(key))
@@ -693,29 +1311,51 @@ class Builder {
693
1311
  this.pendingHints = [];
694
1312
  return desc;
695
1313
  }
696
- listXml(items) {
1314
+ /**
1315
+ * Lists of a frame using the style `frameStyle`. Bullet-only lists take their bullets from that
1316
+ * style. Lists with numbered items name the list styles `<frameStyle>-numbers` and
1317
+ * `<frameStyle>-bullets` (see `listStylesXml()`) on every nested list.
1318
+ */
1319
+ listXml(items, frameStyle, k = 1) {
1320
+ const holder = listStyleHolder(frameStyle);
1321
+ const styled = holder !== null && items.some(it => it[2] !== undefined);
697
1322
  const out = [];
698
- let depth = 0;
699
- for (const [lvl, txt] of items) {
700
- while (depth > lvl + 1) {
701
- out.push("</text:list-item></text:list>");
702
- depth--;
1323
+ // For each open list: is it numbered?
1324
+ const open = [];
1325
+ const close = () => {
1326
+ out.push("</text:list-item></text:list>");
1327
+ open.pop();
1328
+ };
1329
+ for (const [lvl, txt, num] of items) {
1330
+ const ordered = num !== undefined;
1331
+ while (open.length > lvl + 1)
1332
+ close();
1333
+ if (open.length === lvl + 1) {
1334
+ if (open[lvl] === ordered)
1335
+ out.push("</text:list-item><text:list-item>");
1336
+ else
1337
+ close();
703
1338
  }
704
- if (depth === lvl + 1)
705
- out.push("</text:list-item><text:list-item>");
706
- while (depth < lvl + 1) {
707
- out.push("<text:list><text:list-item>");
708
- depth++;
1339
+ while (open.length < lvl + 1) {
1340
+ const name = styled ? ` text:style-name="${esc(holder)}-${ordered ? "numbers" : "bullets"}"` : "";
1341
+ const start = ordered && open.length === lvl && num !== 1 ? ` text:start-value="${num}"` : "";
1342
+ out.push(`<text:list${name}><text:list-item${start}>`);
1343
+ open.push(ordered);
709
1344
  }
710
- out.push(`<text:p>${runsXml(txt)}</text:p>`);
1345
+ out.push(`<text:p${this.scaledPara(sizes.list[Math.min(lvl, 8)], k, outlineStyle(frameStyle, lvl))}>${runsXml(txt)}</text:p>`);
711
1346
  }
712
- while (depth-- > 0)
713
- out.push("</text:list-item></text:list>");
1347
+ while (open.length)
1348
+ close();
714
1349
  return out.join("");
715
1350
  }
716
- tableXml(header, rows, x, y, width, pt, small = false, cols) {
1351
+ tableXml(header, rows, x, y, width, pt, small = false, cols, hidden = () => false) {
717
1352
  cols ??= tableCols(header, rows, width);
718
1353
  const prefix = small ? "Tableau-petit" : "Tableau";
1354
+ // A size other than the one of the cell styles (`@compact`) needs a paragraph style.
1355
+ const defaultPt = pt === (small ? sizes.tableSmall : sizes.table);
1356
+ const para = (indent) => (defaultPt && !indent ? "" : ` text:style-name="${this.paraStyle(pt, indent)}"`);
1357
+ // Images of the cells, drawn over the table: a table cell of Impress only holds text.
1358
+ const overlays = [];
719
1359
  const parts = [
720
1360
  `<draw:frame draw:style-name="Tableau-cadre" ${Builder.geom(x, y, width, tableH(header, rows, width, pt, cols))}>`,
721
1361
  `<table:table table:template-name="${prefix}" table:use-first-row-styles="${header ? "true" : "false"}" table:use-banding-rows-styles="true">`,
@@ -725,150 +1365,59 @@ class Builder {
725
1365
  ...(header ? [["entete", header]] : []),
726
1366
  ...rows.map((r, i) => [i % 2 === 0 ? "cellule" : "cellule-alt", r]),
727
1367
  ];
1368
+ let cy = y;
728
1369
  for (const [kind, r] of all) {
729
- parts.push(`<table:table-row table:style-name="${this.rowStyle(rowH(r, cols, pt))}">`);
730
- cols.forEach((_, i) => {
731
- parts.push(`<table:table-cell table:style-name="${prefix}-${kind}"><text:p>${runsXml(r[i] ?? "")}</text:p></table:table-cell>`);
1370
+ const rh = rowH(r, cols, pt);
1371
+ parts.push(`<table:table-row table:style-name="${this.rowStyle(rh)}">`);
1372
+ let cx = x;
1373
+ cols.forEach((cw, i) => {
1374
+ // A hidden cell keeps the size of its content, so the table does not move when it shows up.
1375
+ const c = kind !== "entete" && hidden(r, i) ? { text: "", imgs: [] } : cell(r[i] ?? "");
1376
+ const indent = cellTextIndent(c, cw, pt);
1377
+ parts.push(`<table:table-cell table:style-name="${prefix}-${kind}"><text:p${para(indent)}>${runsXml(c.text)}</text:p></table:table-cell>`);
1378
+ if (c.imgs.length) {
1379
+ const [scale, iw] = cellImgBox(c, cw, pt);
1380
+ const em = pt * PT * scale;
1381
+ // Alone in its cell, an image is centered; otherwise it comes before the text.
1382
+ let ix = c.text ? cx + CELL_PAD_X / 2 : cx + (cw - iw) / 2;
1383
+ for (const img of c.imgs) {
1384
+ const [w, h] = [img.w * em, img.h * em];
1385
+ overlays.push(this.imageXml(img.src, ix, cy + (rh - h) / 2, w, h, img.alt));
1386
+ ix += w + IMG_GAP_EM * em;
1387
+ }
1388
+ }
1389
+ cx += cw;
732
1390
  });
733
1391
  parts.push("</table:table-row>");
1392
+ cy += rh;
734
1393
  }
735
1394
  parts.push("</table:table></draw:frame>");
736
- return parts.join("");
737
- }
738
- imageXml(src, x, y, w, h) {
739
- if (extname(src).toLowerCase() === ".dot")
740
- return this.graphXml(resolve(this.base, src), x, y, w, h);
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>`);
1395
+ return parts.join("") + overlays.join("");
746
1396
  }
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.
1397
+ imageXml(src, x, y, w, h, alt = "") {
1398
+ const { href, size } = this.picture(src);
1399
+ // Do not blow small diagrams up: their text would become huge.
778
1400
  const maxScale = style.theme.graph.maxScale;
779
- if (w > g.size[0] * maxScale) {
780
- const [fw, fh] = fit(g.size[0], g.size[1], g.size[0] * maxScale, g.size[1] * maxScale);
1401
+ if (extname(src).toLowerCase() === ".dot" && w > size[0] * maxScale) {
1402
+ const [fw, fh] = fit(size[0], size[1], size[0] * maxScale, size[1] * maxScale);
781
1403
  x += (w - fw) / 2;
782
1404
  y += (h - fh) / 2;
783
1405
  w = fw;
784
1406
  h = fh;
785
1407
  }
786
- const scale = (w / g.size[0]) * CM_PER_POINT;
787
- // Text follows the diagram scale, starting from the font sizes of the .dot file.
788
- const textProps = (fontsize, fallback, color) => {
789
- const pt = Math.max(4, Math.round(Number(fontsize ?? fallback) * (scale / CM_PER_POINT) * 2) / 2);
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("");
1408
+ return (`<draw:frame draw:style-name="Image" ${Builder.geom(x, y, w, h)}>` +
1409
+ `<draw:image xlink:href="${esc(href)}" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>` +
1410
+ (alt ? `<svg:title>${esc(alt)}</svg:title>` : "") +
1411
+ `</draw:frame>`);
1412
+ }
1413
+ /** Horizontal line across the box, in its middle. */
1414
+ hrXml(x, y, w, h) {
1415
+ const ly = f2(y + h / 2);
1416
+ return `<draw:line draw:style-name="Separateur" svg:x1="${f2(x)}cm" svg:y1="${ly}cm" svg:x2="${f2(x + w)}cm" svg:y2="${ly}cm"/>`;
869
1417
  }
870
- promptXml(lines, x, y, w, h, style = "Prompt") {
871
- const paras = lines.map(l => `<text:p>${xmlText(l)}</text:p>`).join("");
1418
+ promptXml(lines, x, y, w, h, style = "Prompt", k = 1) {
1419
+ const ps = this.scaledPara(style === "Code" ? sizes.code : sizes.prompt, k);
1420
+ const paras = lines.map(l => `<text:p${ps}>${xmlText(l)}</text:p>`).join("");
872
1421
  return (`<draw:custom-shape draw:style-name="${style}" ${Builder.geom(x, y, w, h)}>${paras}` +
873
1422
  `<draw:enhanced-geometry svg:viewBox="0 0 21600 21600" draw:type="round-rectangle" draw:modifiers="1800"/>` +
874
1423
  `</draw:custom-shape>`);
@@ -876,40 +1425,68 @@ class Builder {
876
1425
  blockXml(b, x, y, w, h) {
877
1426
  switch (b.t) {
878
1427
  case "para":
879
- return this.frame("Texte", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
1428
+ return this.frame("Texte", x, y, w, h, `<text:p${this.scaledPara(sizes.text, b.k, "Texte")}>${runsXml(b.text)}</text:p>`);
880
1429
  case "list":
881
- return this.frame("Master-outline1", x, y, w, h, this.listXml(b.items), "outline");
1430
+ return this.frame("Master-outline1", x, y, w, h, this.listXml(b.items, "Master-outline1", b.k), "outline");
882
1431
  case "quote":
883
- return this.frame("Citation", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
1432
+ return this.frame("Citation", x, y, w, h, `<text:p${this.scaledPara(sizes.quote, b.k, "Citation")}>${runsXml(b.text)}</text:p>`);
884
1433
  case "prompt":
885
1434
  case "code": {
886
- const [pw] = promptSize(b.lines, w);
887
- return this.promptXml(b.lines, x + w - pw, y, pw, h, b.t === "prompt" ? "Prompt" : "Code");
1435
+ const [pw] = promptSize(b.lines, w, b.k);
1436
+ return this.promptXml(b.lines, x + w - pw, y, pw, h, b.t === "prompt" ? "Prompt" : "Code", b.k);
888
1437
  }
1438
+ case "compact":
1439
+ return this.regionXml(b, x, y, w);
889
1440
  case "table": {
890
- const tw = Math.min(w, tableCols(b.header, b.rows, w).reduce((a, c) => a + c, 0));
891
- return this.tableXml(b.header, b.rows, x, y, tw, sizes.table);
1441
+ const pw = tablePartW(b, w);
1442
+ const cols = tableBlockCols(b, w);
1443
+ return tableParts(b)
1444
+ .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)))
1445
+ .join("");
892
1446
  }
1447
+ case "hr":
1448
+ return this.hrXml(x, y, w, h);
893
1449
  default:
894
1450
  throw new Error(`Unexpected block ${b.t}`);
895
1451
  }
896
1452
  }
1453
+ /** The columns of a `@compact {` region, top-aligned. */
1454
+ regionXml(b, x, y, w) {
1455
+ const arr = arrange(b, w);
1456
+ const out = [];
1457
+ arr.cols.forEach((col, c) => {
1458
+ const cx = x + c * (arr.colW + arr.gap);
1459
+ let cy = y;
1460
+ for (const blk of col) {
1461
+ const bh = regionBlockH(blk, arr.colW);
1462
+ if (blk.t === "image") {
1463
+ const [iw] = regionImageSize(blk, arr.colW);
1464
+ out.push(this.imageXml(blk.src, cx + (arr.colW - iw) / 2, cy, iw, bh, blk.alt));
1465
+ }
1466
+ else
1467
+ out.push(this.blockXml(blk.t === "table" && b.shown ? { ...blk, shown: b.shown } : blk, cx, cy, arr.colW, bh));
1468
+ cy += bh + GAP * arr.k;
1469
+ }
1470
+ });
1471
+ return out.join("");
1472
+ }
897
1473
  // -- slide-level layout
898
1474
  /** Return the required height and the shapes for the content blocks of one slide. */
899
1475
  layout(blocks) {
900
1476
  const imgs = blocks.filter(b => b.t === "image");
901
1477
  const texts = blocks.filter(b => b.t !== "image");
902
1478
  const shapes = [];
903
- const stack = (bs, x, width) => {
904
- let y = Y0;
1479
+ const sumH = (width) => texts.reduce((h, b) => h + blockH(b, width), 0) + GAP * (texts.length - 1);
1480
+ const stack = (bs, x, width, center = CENTER) => {
1481
+ const top = center ? Y0 + Math.max(0, (H - sumH(width)) / 2) : Y0;
1482
+ let y = top;
905
1483
  for (const b of bs) {
906
1484
  const bh = blockH(b, width);
907
1485
  shapes.push(this.blockXml(b, x, y, width, Math.min(bh, Math.max(Y0 + H - y, 1.5))));
908
1486
  y += bh + GAP;
909
1487
  }
910
- return y - Y0 - (bs.length ? GAP : 0);
1488
+ return y - top - (bs.length ? GAP : 0);
911
1489
  };
912
- const sumH = (width) => texts.reduce((h, b) => h + blockH(b, width), 0) + GAP * (texts.length - 1);
913
1490
  if (!imgs.length)
914
1491
  return [stack(texts, X0, W), shapes];
915
1492
  const src = imgs[0].src;
@@ -920,7 +1497,8 @@ class Builder {
920
1497
  return [0, shapes];
921
1498
  }
922
1499
  if (iw / ih >= 1.8 || (iw / ih >= 1.2 && sumH(W) < 2.5)) {
923
- const th = stack(texts, X0, W);
1500
+ // The image below the text takes the free height.
1501
+ const th = stack(texts, X0, W, false);
924
1502
  const avail = Math.max(H - th - GAP, 4.5);
925
1503
  const [w, h] = fit(iw, ih, W, avail);
926
1504
  shapes.push(this.imageXml(src, X0 + (W - w) / 2, Y0 + th + GAP + (avail - h) / 2, w, h));
@@ -942,12 +1520,24 @@ class Builder {
942
1520
  slides[slides.length - 1][1].push(b.text);
943
1521
  continue;
944
1522
  }
1523
+ if (b.t === "compact") {
1524
+ this.compactRegion(b, slides);
1525
+ continue;
1526
+ }
1527
+ if (b.t === "table" && (!this.fits([b]) || ((b.compact || b.reveal) && !headerFits(b)))) {
1528
+ // A revealed table must stay on one slide: on two side-by-side tables, or else shrunk.
1529
+ if (b.reveal)
1530
+ this.twoColumns(b, slides) || this.compactTable(b, slides);
1531
+ else if (b.compact)
1532
+ this.compactTable(b, slides);
1533
+ else
1534
+ this.splitTable(b, slides);
1535
+ continue;
1536
+ }
945
1537
  const cur = slides[slides.length - 1][0];
946
1538
  const hasImg = cur.some(x => x.t === "image");
947
- if (cur.length && ((b.t === "image" && hasImg) || this.layout([...cur, b])[0] > H)) {
948
- // Keep an introductory paragraph with what follows it.
949
- const carry = cur.length > 1 && cur[cur.length - 1].t === "para" ? [cur.pop()] : [];
950
- slides.push([[...carry, b], []]);
1539
+ if (cur.length && ((b.t === "image" && hasImg) || !this.fits([...cur, b]))) {
1540
+ slides.push([[...this.carry(cur, b), b], []]);
951
1541
  }
952
1542
  else {
953
1543
  cur.push(b);
@@ -955,9 +1545,166 @@ class Builder {
955
1545
  }
956
1546
  return slides.filter(([c, n]) => c.length || n.length);
957
1547
  }
1548
+ /** Do these blocks fit on one slide? */
1549
+ fits(blocks) {
1550
+ // `layout()` registers the automatic styles of the shapes it builds: forget those of this trial.
1551
+ const saved = [new Map(this.colStyles), new Map(this.rowStyles), new Map(this.paraStyles)];
1552
+ const ok = this.layout(blocks)[0] <= H;
1553
+ [this.colStyles, this.rowStyles, this.paraStyles] = saved;
1554
+ return ok;
1555
+ }
1556
+ /**
1557
+ * Keep an introductory paragraph with the block `next` that starts a new slide:
1558
+ * the last paragraph of `cur`, removed from it, if it fits with `next`.
1559
+ */
1560
+ carry(cur, next) {
1561
+ const last = cur[cur.length - 1];
1562
+ return cur.length > 1 && last.t === "para" && this.fits([last, next]) ? [cur.pop()] : [];
1563
+ }
1564
+ /**
1565
+ * A `@compact` table too long for one slide: its text is shrunk (by steps of half a point)
1566
+ * until it fits on a slide with the paragraph introducing it, if any. It stays on the current
1567
+ * slide if it fits there at that size, otherwise it starts a new one with its introduction.
1568
+ */
1569
+ compactTable(b, slides) {
1570
+ const MIN_PT = 4;
1571
+ const cur = slides[slides.length - 1][0];
1572
+ const last = cur[cur.length - 1];
1573
+ const intro = last?.t === "para" ? [last] : [];
1574
+ const shrink = (t) => {
1575
+ let small = t;
1576
+ for (let pt = sizes.table - 0.5; pt >= MIN_PT; pt -= 0.5) {
1577
+ small = { ...t, pt };
1578
+ if (this.fits([...intro, small]) && headerFits(small))
1579
+ break;
1580
+ }
1581
+ return small;
1582
+ };
1583
+ let small = shrink(b);
1584
+ // A revealed table can also be spread over two side-by-side tables, if its text stays bigger.
1585
+ if (b.reveal && b.rows.length > 1) {
1586
+ const two = shrink({ ...b, columns: 2 });
1587
+ const ok = (t) => this.fits([t]) && headerFits(t);
1588
+ if ((two.pt ?? sizes.table) > (small.pt ?? sizes.table) || !ok(small))
1589
+ small = two;
1590
+ }
1591
+ const pragma = b.reveal ? "@reveal" : "@compact";
1592
+ if (!this.fits([small]))
1593
+ console.warn(` ! a ${pragma} table is still too long at ${MIN_PT}pt: it overflows its slide`);
1594
+ else if (!headerFits(small))
1595
+ console.warn(` ! a ${pragma} table still has header words too long for their column at ${MIN_PT}pt`);
1596
+ if (!cur.length || this.fits([...cur, small]))
1597
+ return void cur.push(small);
1598
+ const carry = cur.length > 1 && intro.length && this.fits([...intro, small]) ? [cur.pop()] : [];
1599
+ slides.push([[...carry, small], []]);
1600
+ }
1601
+ /**
1602
+ * A `@compact {` region: at full size if it fits on a slide with the paragraph introducing it,
1603
+ * otherwise shrunk (by steps of half a point of body text) until its balanced columns fit.
1604
+ * `@compact * {` takes the number of columns giving the biggest text (the fewest on a tie),
1605
+ * among those where no word is too long for its column. Like a `@compact` table, it stays on
1606
+ * the current slide if it fits there, otherwise it starts a new one with its introduction.
1607
+ */
1608
+ compactRegion(b, slides) {
1609
+ const cur = slides[slides.length - 1][0];
1610
+ const last = cur[cur.length - 1];
1611
+ const intro = last?.t === "para" ? [last] : [];
1612
+ const pieces = compactPieces(b.blocks).length;
1613
+ const auto = b.columns === "auto";
1614
+ const counts = auto
1615
+ ? Array.from({ length: Math.max(1, Math.min(pieces, MAX_AUTO_COLUMNS)) }, (_, i) => i + 1)
1616
+ : [Math.max(1, Math.min(b.columns, pieces))];
1617
+ const scales = compactScales();
1618
+ const at = (n, k) => ({ ...b, n, k });
1619
+ const fitsAlone = (r) => this.fits([...intro, r]);
1620
+ // Biggest scale (fewest columns on a tie) passing `ok`.
1621
+ const search = (ok) => {
1622
+ let found = null;
1623
+ for (const n of counts) {
1624
+ const k = scales.find(k => (!found || k > found.k) && ok(at(n, k)));
1625
+ if (k !== undefined)
1626
+ found = at(n, k);
1627
+ if (found?.k === 1)
1628
+ break;
1629
+ }
1630
+ return found;
1631
+ };
1632
+ let region = search(r => fitsAlone(r) && regionWordsFit(arrange(r, W), auto)) ?? search(fitsAlone);
1633
+ const minPt = Math.round(sizes.text * MIN_COMPACT_SCALE * 2) / 2;
1634
+ if (!region) {
1635
+ // Too long even at the smallest size: the number of columns giving the shortest region.
1636
+ const k = scales[scales.length - 1];
1637
+ region = counts.map(n => at(n, k)).reduce((a, r) => (arrange(r, W).h < arrange(a, W).h ? r : a));
1638
+ console.warn(` ! ${bold(b.where)}: the "@compact {" region is still too long with a body text of ${minPt}pt: it overflows its slide`);
1639
+ }
1640
+ else if (!regionWordsFit(arrange(region, W), false)) {
1641
+ console.warn(` ! ${bold(b.where)}: a table of the "@compact {" region has header words too long for their column`);
1642
+ }
1643
+ if (!cur.length || this.fits([...cur, region]))
1644
+ cur.push(region);
1645
+ else {
1646
+ const carry = cur.length > 1 && intro.length && this.fits([...intro, region]) ? [cur.pop()] : [];
1647
+ slides.push([[...carry, region], []]);
1648
+ }
1649
+ slides[slides.length - 1][1].push(...b.blocks.flatMap(x => (x.t === "note" ? [x.text] : [])));
1650
+ }
1651
+ /**
1652
+ * Spread the rows of a table over two side-by-side tables, if they fit on one slide: on the
1653
+ * current slide if there is room, otherwise on a new one. Return false if they do not fit.
1654
+ */
1655
+ twoColumns(b, slides) {
1656
+ if (b.rows.length < 2)
1657
+ return false;
1658
+ const cur = slides[slides.length - 1][0];
1659
+ const two = { ...b, columns: 2 };
1660
+ // Narrower columns must not cut the words of the header of a `@compact` or `@reveal` table.
1661
+ if ((b.compact || b.reveal) && !headerFits(two))
1662
+ return false;
1663
+ if (cur.length && this.fits([...cur, two]))
1664
+ cur.push(two);
1665
+ else if (!this.fits([two]))
1666
+ return false;
1667
+ else if (!cur.length)
1668
+ cur.push(two);
1669
+ else
1670
+ slides.push([[...this.carry(cur, two), two], []]);
1671
+ return true;
1672
+ }
1673
+ /**
1674
+ * A table too long for one slide: its rows are spread over two side-by-side tables if they fit
1675
+ * on one slide, otherwise over several slides. The header is repeated on each part.
1676
+ */
1677
+ splitTable(b, slides) {
1678
+ if (this.twoColumns(b, slides))
1679
+ return;
1680
+ const cur = () => slides[slides.length - 1][0];
1681
+ const ref = b.rows;
1682
+ let rest = b.rows;
1683
+ while (rest.length) {
1684
+ const part = (k) => ({ ...b, rows: rest.slice(0, k), ref });
1685
+ const c = cur();
1686
+ let k = 0;
1687
+ while (k < rest.length && this.fits([...c, part(k + 1)]))
1688
+ k++;
1689
+ if (!k && c.length) {
1690
+ // Not even one row fits under the current content: start on a new slide.
1691
+ const last = c[c.length - 1];
1692
+ slides.push([c.length > 1 && last.t === "para" ? [c.pop()] : [], []]);
1693
+ continue;
1694
+ }
1695
+ // A single row taller than the slide still has to go somewhere.
1696
+ k = Math.max(k, 1);
1697
+ c.push(part(k));
1698
+ rest = rest.slice(k);
1699
+ if (rest.length)
1700
+ slides.push([[], []]);
1701
+ }
1702
+ }
958
1703
  // -- pages
959
1704
  page(master, shapes, notes = []) {
960
- this.pages.push({ master, shapes, notes });
1705
+ const page = { master, shapes, notes, sec: this.current };
1706
+ this.pages.push(page);
1707
+ return page;
961
1708
  }
962
1709
  titleShapes(title, crumbs) {
963
1710
  const out = [];
@@ -967,63 +1714,105 @@ class Builder {
967
1714
  return out;
968
1715
  }
969
1716
  sectionPage(sec) {
970
- const crumbs = sec.path().slice(0, -1);
971
- const shapes = [this.frame("Section-title", 2, 5, 24, 3.5, `<text:p>${xmlText(sec.title)}</text:p>`, "title", this.takeHints())];
972
- if (crumbs.length)
973
- shapes.push(this.frame("Section-subtitle", 2, 8.8, 24, 1.5, `<text:p>${xmlText(crumbs.join(" › "))}</text:p>`, "subtitle"));
1717
+ // The big title is always the top-level (`#`) heading; the hierarchy box comes in `finish()`.
1718
+ const [title] = sec.path();
1719
+ const shapes = [this.frame("Section-title", SEC.x, SEC.titleY, SEC.w, SEC.titleH, `<text:p>${xmlText(title)}</text:p>`, "title", this.takeHints())];
974
1720
  const notes = sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : []));
975
- this.page("Section", shapes, notes);
1721
+ this.page("Section", shapes, notes).toc = sec;
1722
+ this.lastPath = sec.path();
1723
+ }
1724
+ /** Adds the hierarchy boxes to the section slides, now that the slide after each one is known. */
1725
+ finish() {
1726
+ this.pages.forEach((page, i) => {
1727
+ if (page.toc)
1728
+ page.shapes.push(...this.tocShapes(page.toc, this.pages[i + 1]?.sec ?? null));
1729
+ });
1730
+ }
1731
+ /**
1732
+ * Box listing the sub-sections of the `#` heading of `sec`, indented by depth. A section is
1733
+ * expanded only if the next slide (in section `next`) is inside it. The highlighted section is
1734
+ * `sec`, or for a `#` slide, the sub-section holding the next slide.
1735
+ */
1736
+ tocShapes(sec, next) {
1737
+ let top = sec;
1738
+ while (top.parent && top.parent.level > 0)
1739
+ top = top.parent;
1740
+ const ancestors = new Set();
1741
+ for (let s = next?.parent ?? null; s; s = s.parent)
1742
+ ancestors.add(s);
1743
+ let current = sec.level > 1 ? sec : null;
1744
+ if (!current && next && next !== top) {
1745
+ current = next;
1746
+ while (current.parent && current.parent !== top)
1747
+ current = current.parent;
1748
+ }
1749
+ const pt = style.theme.sizes.subtitle;
1750
+ const lines = [];
1751
+ // Nested bulleted lists: the bullets come from the `bullets` of `Section-subtitle` (list style `Toc-list`).
1752
+ const listXml = (parent) => {
1753
+ const items = [];
1754
+ for (const child of parent.children) {
1755
+ if (child.continued || !child.title)
1756
+ continue;
1757
+ let text = xmlText(child.title);
1758
+ if (child === current)
1759
+ text = `<text:span text:style-name="T_section">${text}</text:span>`;
1760
+ lines.push(text);
1761
+ const sub = ancestors.has(child) ? listXml(child) : "";
1762
+ items.push(`<text:list-item><text:p text:style-name="Toc">${text}</text:p>${sub}</text:list-item>`);
1763
+ }
1764
+ const name = style.styles["Section-subtitle"]?.bullets ? ` text:style-name="Toc-list"` : "";
1765
+ return items.length ? `<text:list${name}>${items.join("")}</text:list>` : "";
1766
+ };
1767
+ const xml = listXml(top);
1768
+ if (!lines.length)
1769
+ return [];
1770
+ const lineH = pt * PT * 1.25;
1771
+ const h = Math.min(SEC.boxBottom - SEC.boxY, lines.length * lineH + 1.2);
1772
+ return [this.frame("Section-subtitle", SEC.x, SEC.boxY, SEC.w, h, xml, "subtitle")];
1773
+ }
1774
+ /**
1775
+ * When going back up more than one level (from `1 > 1 > 1` to `1 > 2`, or to `1 > 2 > 1`),
1776
+ * a section slide recalls where we are before the slides of `sec`.
1777
+ */
1778
+ recallSection(sec) {
1779
+ const path = sec.path();
1780
+ let common = 0;
1781
+ while (common < path.length && common < this.lastPath.length && path[common] === this.lastPath[common])
1782
+ common++;
1783
+ if (this.lastPath.length - common >= 2)
1784
+ this.sectionPage(sec);
976
1785
  }
977
1786
  contentPages(title, crumbs, blocks) {
978
- for (const [content, notes] of this.paginate(blocks)) {
979
- const [, shapes] = this.layout(content);
980
- this.page("Master", [...this.titleShapes(title, crumbs), ...shapes], notes);
981
- }
982
- }
983
- /** A table whose rows appear one slide after the other. */
984
- revealTable(sec, crumbs) {
985
- const table = sec.blocks.find(b => b.t === "table");
986
- if (!table || table.t !== "table")
987
- return this.contentPages(sec.title, crumbs, sec.blocks);
988
- const header = (table.header ?? []).map(stripMd);
989
- const rows = table.rows;
990
- const ncol = Math.max(header.length, ...rows.map(r => r.length));
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));
1787
+ // Notes not attached to a slide yet: they go to the next one.
1788
+ const pending = [];
1789
+ let run = [];
1790
+ const flush = () => {
1791
+ for (const [content, notes] of this.paginate(run)) {
1792
+ if (!content.length) {
1793
+ pending.push(...notes);
1794
+ continue;
1795
+ }
1796
+ const allNotes = [...pending.splice(0), ...notes];
1797
+ for (const step of revealSteps(content)) {
1798
+ const [, shapes] = this.layout(step);
1799
+ this.page("Master", [...this.titleShapes(title, crumbs), ...shapes], [...allNotes]);
1022
1800
  }
1023
1801
  }
1024
- const notes = k === 0 ? sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : [])) : [];
1025
- this.page("Master", [...this.titleShapes(sec.title, crumbs), ...shapes], notes);
1802
+ run = [];
1803
+ };
1804
+ // An `@layout` of blocks gets its own slide, between the slides of the blocks around it.
1805
+ for (const b of blocks) {
1806
+ if (b.t !== "layout")
1807
+ run.push(b);
1808
+ else if (b.cells.length) {
1809
+ flush();
1810
+ this.layoutPage(title, crumbs, b.cells, b.layout, pending.splice(0));
1811
+ }
1026
1812
  }
1813
+ flush();
1814
+ if (pending.length)
1815
+ this.pages[this.pages.length - 1].notes.push(...pending);
1027
1816
  }
1028
1817
  /** Height of a group of paragraphs/lists rendered at `pt` points. */
1029
1818
  static textGroupH(blocks, width, pt) {
@@ -1051,7 +1840,7 @@ class Builder {
1051
1840
  const ncol = Math.max(...all.map(r => r.length));
1052
1841
  let tw = 0;
1053
1842
  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;
1843
+ tw += Math.max(...all.map(r => Math.min(plainLen(cell(r[c] ?? "").text), 30))) * cw(sizes.tableSmall) + 0.6;
1055
1844
  w = Math.max(w, tw);
1056
1845
  }
1057
1846
  else if (b.t === "image") {
@@ -1067,7 +1856,9 @@ class Builder {
1067
1856
  cellXml(sec, x, y, w, h, textStyle, textPt) {
1068
1857
  const items = [];
1069
1858
  for (const b of sec.blocks) {
1070
- if (b.t === "note")
1859
+ if (b.t === "compact")
1860
+ throw new Error(`${b.where}: a "@compact {" region cannot be in a cell of an "@layout"`);
1861
+ if (b.t === "note" || b.t === "layout")
1071
1862
  continue;
1072
1863
  const last = items[items.length - 1];
1073
1864
  if (b.t === "para" || b.t === "list" || b.t === "quote") {
@@ -1088,6 +1879,8 @@ class Builder {
1088
1879
  return tableH(b.header, b.rows, w, sizes.tableSmall);
1089
1880
  if (b.t === "prompt" || b.t === "code")
1090
1881
  return promptSize(b.lines, w)[1];
1882
+ if (b.t === "hr")
1883
+ return HR_H;
1091
1884
  return 0;
1092
1885
  });
1093
1886
  const flexible = items.map(it => it.kind === "text" || (it.kind === "block" && it.block.t === "image"));
@@ -1121,7 +1914,7 @@ class Builder {
1121
1914
  const ih = Math.max(0.5, Math.min(heights[i], y + h - cy));
1122
1915
  if (it.kind === "text") {
1123
1916
  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>` : ""))
1917
+ .map(b => (b.t === "list" ? this.listXml(b.items, textStyle) : b.t === "para" || b.t === "quote" ? `<text:p>${runsXml(b.text)}</text:p>` : ""))
1125
1918
  .join("");
1126
1919
  shapes.push(this.frame(textStyle, x, cy, w, ih, inner));
1127
1920
  }
@@ -1140,15 +1933,17 @@ class Builder {
1140
1933
  const [pw] = promptSize(b.lines, w);
1141
1934
  shapes.push(this.promptXml(b.lines, x + w - pw, cy, pw, ih, b.t === "prompt" ? "Prompt" : "Code"));
1142
1935
  }
1936
+ else if (b.t === "hr") {
1937
+ shapes.push(this.hrXml(x, cy, w, ih));
1938
+ }
1143
1939
  }
1144
1940
  cy += heights[i] + gap;
1145
1941
  });
1146
1942
  return shapes;
1147
1943
  }
1148
1944
  /** Sections laid out on a single slide, following an `@layout` pragma. */
1149
- layoutPage(parent, group, layout, notes) {
1150
- const title = parent.level > 0 ? parent.title : group[0].title;
1151
- const shapes = this.titleShapes(title, parent.path().slice(0, -1));
1945
+ layoutPage(title, crumbs, group, layout, notes) {
1946
+ const shapes = this.titleShapes(title, crumbs);
1152
1947
  const headH = 0.9;
1153
1948
  let cells;
1154
1949
  if (layout.kind === "grid") {
@@ -1193,13 +1988,17 @@ class Builder {
1193
1988
  const [headStyle, textStyle, textPt] = layout.kind === "grid"
1194
1989
  ? [`Grille-titre-${(n % colors) + 1}`, `Grille-texte-${(n % colors) + 1}`, sizes.gridText]
1195
1990
  : ["Colonne-titre", "Colonne-texte", sizes.columnText];
1196
- shapes.push(this.frame(headStyle, x, y, w, headH, `<text:p>${xmlText(sec.title)}</text:p>`));
1197
- shapes.push(...this.cellXml(sec, x, y + headH, w, h - headH, textStyle, textPt));
1991
+ // Cells of an `@layout` of blocks have no heading.
1992
+ const hh = sec.title ? headH : 0;
1993
+ if (sec.title)
1994
+ shapes.push(this.frame(headStyle, x, y, w, hh, `<text:p>${xmlText(sec.title)}</text:p>`));
1995
+ shapes.push(...this.cellXml(sec, x, y + hh, w, h - hh, textStyle, textPt));
1198
1996
  notes.push(...sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : [])));
1199
1997
  });
1200
1998
  this.page("Master", shapes, notes);
1201
1999
  }
1202
2000
  walk(sec) {
2001
+ this.current = sec;
1203
2002
  this.pendingHints.push(...sec.hints);
1204
2003
  const crumbs = sec.path().slice(0, -1);
1205
2004
  const content = sec.blocks.filter(b => b.t !== "note");
@@ -1209,12 +2008,12 @@ class Builder {
1209
2008
  this.sectionPage(sec);
1210
2009
  if (content.length)
1211
2010
  this.contentPages(sec.title, [...crumbs, sec.title], sec.blocks);
1212
- }
1213
- else if (sec.hints.some(h => h.includes("revealed line by line"))) {
1214
- this.revealTable(sec, crumbs);
2011
+ this.lastPath = sec.path();
1215
2012
  }
1216
2013
  else if (content.length) {
2014
+ this.recallSection(sec);
1217
2015
  this.contentPages(sec.title, crumbs, sec.blocks);
2016
+ this.lastPath = sec.path();
1218
2017
  }
1219
2018
  else if (sec.children.length && !groupedOnly) {
1220
2019
  this.sectionPage(sec);
@@ -1231,12 +2030,19 @@ class Builder {
1231
2030
  continue;
1232
2031
  }
1233
2032
  const group = children.slice(i, i + cellCount(layout));
2033
+ if (sec.level > 0)
2034
+ this.recallSection(sec);
2035
+ this.current = group[0];
1234
2036
  for (const g of group)
1235
2037
  this.pendingHints.push(...g.hints);
1236
- this.layoutPage(sec, group, layout, i === 0 ? notes : []);
2038
+ const title = sec.level > 0 ? sec.title : group[0].title;
2039
+ this.layoutPage(title, sec.path().slice(0, -1), group, layout, i === 0 ? notes : []);
2040
+ this.lastPath = sec.level > 0 ? sec.path() : group[0].path();
1237
2041
  // Sub-sections of grouped sections still get their own slides.
1238
- for (const g of group)
2042
+ for (const g of group) {
2043
+ this.current = g;
1239
2044
  this.walkChildren(g);
2045
+ }
1240
2046
  i += group.length - 1;
1241
2047
  }
1242
2048
  }
@@ -1271,6 +2077,52 @@ function bulletsXml(def, name) {
1271
2077
  `</text:list-level-style-bullet>`);
1272
2078
  return `<text:list-style style:name="${esc(name)}-list">${levels.join("")}</text:list-style>`;
1273
2079
  }
2080
+ /** Length in cm of a paragraph property (`"0.2cm"`) of a style or of its parents, 0 if none. */
2081
+ function styleCm(name, prop) {
2082
+ for (let n = name, depth = 0; n && depth < 20; depth++) {
2083
+ const s = style.styles[n];
2084
+ const v = s?.paragraph?.[prop];
2085
+ if (v !== undefined) {
2086
+ const m = resolveValue(String(v), `style "${n}"`).match(/^(-?[\d.]+)(cm|mm|pt)$/);
2087
+ return m ? Number(m[1]) * (m[2] === "mm" ? 0.1 : m[2] === "pt" ? PT : 1) : 0;
2088
+ }
2089
+ n = s?.parent;
2090
+ }
2091
+ return 0;
2092
+ }
2093
+ /** Style of the paragraphs of level `lvl` (0-based) in a frame of style `Master-outline1`. */
2094
+ function outlineStyle(frameStyle, lvl) {
2095
+ return frameStyle.replace(/1$/, String(Math.min(lvl, 8) + 1));
2096
+ }
2097
+ /** `name` or its nearest parent style defining both `bullets` and `numbers`, if any. */
2098
+ function listStyleHolder(name) {
2099
+ for (let n = name, depth = 0; n && depth < 20; depth++) {
2100
+ const s = style.styles[n];
2101
+ if (s?.bullets && s.numbers)
2102
+ return n;
2103
+ n = s?.parent;
2104
+ }
2105
+ return null;
2106
+ }
2107
+ /** Level of a numbered list style: `1.`, `a.`, `i.`... */
2108
+ function numbersXml(def, name) {
2109
+ const where = `numbers of style "${name}"`;
2110
+ 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)}">` +
2111
+ `<style:list-level-properties text:space-before="${f2(def.indent * i)}cm" text:min-label-width="${f2(def.width)}cm"/>` +
2112
+ `<style:text-properties style:use-window-font-color="false" fo:color="${esc(resolveValue(def.color, where))}" ` +
2113
+ `fo:font-size="${esc(resolveValue(def.size, where))}" fo:font-weight="${esc(resolveValue(def.weight, where))}"/>` +
2114
+ `</text:list-level-style-number>`);
2115
+ return `<text:list-style style:name="${esc(name)}-numbers">${levels.join("")}</text:list-style>`;
2116
+ }
2117
+ /**
2118
+ * Named list styles `<name>-bullets` and `<name>-numbers` of a style holding numbered lists:
2119
+ * lists mixing bullets and numbers name them explicitly (see `Builder.listXml()`).
2120
+ */
2121
+ function listStylesXml(name, s) {
2122
+ if (!s.bullets || !s.numbers)
2123
+ return "";
2124
+ return bulletsXml(s.bullets, name).replace(`style:name="${esc(name)}-list"`, `style:name="${esc(name)}-bullets"`) + numbersXml(s.numbers, name);
2125
+ }
1274
2126
  function styleXml(name, s) {
1275
2127
  const parent = s.parent ? ` style:parent-style-name="${esc(s.parent)}"` : "";
1276
2128
  const list = s.bullets ? bulletsXml(s.bullets, name) : "";
@@ -1304,9 +2156,8 @@ function backgroundXml(b, master) {
1304
2156
  w = size[0] * scale;
1305
2157
  h = size[1] * scale;
1306
2158
  }
1307
- const mime = href.endsWith(".svg") ? ' draw:mime-type="image/svg+xml"' : "";
1308
2159
  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"${mime}/>` +
2160
+ `<draw:image xlink:href="${esc(href)}" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>` +
1310
2161
  `</draw:frame>`);
1311
2162
  }
1312
2163
  function stylesXml(b) {
@@ -1342,9 +2193,9 @@ function stylesXml(b) {
1342
2193
  `<style:master-page style:name="Section" style:page-layout-name="PM1" draw:style-name="Mdp1">` +
1343
2194
  `<draw:rect draw:style-name="Section-fond" ${Builder.geom(0, 0, SLIDE_W, SLIDE_H)}/>` +
1344
2195
  backgroundXml(b, "Section") +
1345
- `<draw:rect draw:style-name="Decor" ${Builder.geom(0, 8.55, SLIDE_W, 0.12)}/>` +
1346
- placeholder("Section-title", "title", 2, 5, 24, 3.5) +
1347
- placeholder("Section-subtitle", "subtitle", 2, 8.8, 24, 1.5) +
2196
+ `<draw:rect draw:style-name="Decor" ${Builder.geom(0, SEC.barY, SLIDE_W, 0.12)}/>` +
2197
+ placeholder("Section-title", "title", SEC.x, SEC.titleY, SEC.w, SEC.titleH) +
2198
+ placeholder("Section-subtitle", "subtitle", SEC.x, SEC.boxY, SEC.w, SEC.boxBottom - SEC.boxY) +
1348
2199
  `${notes("Section")}</style:master-page>`,
1349
2200
  ];
1350
2201
  return (`<?xml version="1.0" encoding="UTF-8"?><office:document-styles ${NS}>` +
@@ -1354,13 +2205,23 @@ function stylesXml(b) {
1354
2205
  }
1355
2206
  function contentXml(b) {
1356
2207
  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>`);
2208
+ // Impress only finds the list styles named by `<text:list>` among the automatic styles.
2209
+ for (const [name, s] of Object.entries(style.styles))
2210
+ auto.push(listStylesXml(name, s));
1357
2211
  for (const [key, name] of b.colStyles)
1358
2212
  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 { name, parent, graphic } of b.autoStyles.values())
1360
- auto.push(`<style:style style:name="${name}" style:family="graphic" style:parent-style-name="${esc(parent)}">` +
1361
- `<style:graphic-properties ${attrs(graphic)}/></style:style>`);
1362
- for (const { name, text } of b.paraStyles.values())
1363
- auto.push(`<style:style style:name="${name}" style:family="paragraph"><style:text-properties ${attrs(text)}/></style:style>`);
2213
+ for (const [key, name] of b.paraStyles) {
2214
+ const [pt, indent, margins] = key.split("/");
2215
+ const [top, bottom] = margins ? margins.split(",") : [];
2216
+ const props = [indent ? `fo:margin-left="${indent}cm"` : "", margins ? `fo:margin-top="${top}cm" fo:margin-bottom="${bottom}cm"` : ""].filter(Boolean);
2217
+ const para = props.length ? `<style:paragraph-properties ${props.join(" ")}/>` : "";
2218
+ auto.push(`<style:style style:name="${name}" style:family="paragraph">${para}<style:text-properties fo:font-size="${pt}pt"/></style:style>`);
2219
+ }
2220
+ // Lines of the hierarchy boxes of section slides: left aligned (the bullets indent them).
2221
+ auto.push(`<style:style style:name="Toc" style:family="paragraph"><style:paragraph-properties fo:text-align="start" fo:margin-top="0.1cm" fo:margin-bottom="0.1cm"/></style:style>`);
2222
+ const tocBullets = style.styles["Section-subtitle"]?.bullets;
2223
+ if (tocBullets)
2224
+ auto.push(bulletsXml(tocBullets, "Toc"));
1364
2225
  for (const [key, name] of b.rowStyles)
1365
2226
  auto.push(`<style:style style:name="${name}" style:family="table-row"><style:table-row-properties style:row-height="${key}cm"/></style:style>`);
1366
2227
  const pages = b.pages.map(({ master, shapes, notes }, i) => {
@@ -1424,10 +2285,12 @@ function zip(entries) {
1424
2285
  end.writeUInt32LE(offset, 16);
1425
2286
  return Buffer.concat([...locals, cd, end]);
1426
2287
  }
1427
- function writeOdp(b, out, title) {
2288
+ async function writeOdp(b, out, title) {
1428
2289
  // Before listing the pictures: the master pages can add some.
1429
2290
  const styles = stylesXml(b);
2291
+ const content = contentXml(b);
1430
2292
  const pics = [...b.pictures.values()];
2293
+ await encodePictures(pics);
1431
2294
  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
2295
  '<manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.presentation"/>' +
1433
2296
  '<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>' +
@@ -1443,7 +2306,7 @@ function writeOdp(b, out, title) {
1443
2306
  { name: "META-INF/manifest.xml", data: text(manifest) },
1444
2307
  { name: "meta.xml", data: text(meta) },
1445
2308
  { name: "styles.xml", data: text(styles) },
1446
- { name: "content.xml", data: text(contentXml(b)) },
2309
+ { name: "content.xml", data: text(content) },
1447
2310
  ...pics.map(p => ({ name: p.href, data: p.data, store: true })),
1448
2311
  ]));
1449
2312
  }
@@ -1461,13 +2324,14 @@ function humanSize(bytes) {
1461
2324
  function countHints(sec) {
1462
2325
  return sec.hints.length + sec.children.reduce((n, c) => n + countHints(c), 0);
1463
2326
  }
1464
- function convert(src, config) {
2327
+ async function convert(src, config) {
1465
2328
  useStyle(config);
1466
2329
  const root = parse(readFileSync(src, "utf8"), src);
1467
2330
  const b = new Builder(dirname(src));
1468
2331
  b.walkChildren(root);
2332
+ b.finish();
1469
2333
  const out = src.replace(/\.md$/i, ".odp");
1470
- writeOdp(b, out, basename(src, extname(src)));
2334
+ await writeOdp(b, out, basename(src, extname(src)));
1471
2335
  return { out, hints: countHints(root) };
1472
2336
  }
1473
2337
  /** A ready-to-paste prompt asking an AI agent to apply the `@hint` pragmas of the given presentations. */
@@ -1476,7 +2340,7 @@ function aiPrompt(files) {
1476
2340
  return [
1477
2341
  rule,
1478
2342
  `Refine ${files.length > 1 ? "these LibreOffice Impress presentations" : "this LibreOffice Impress presentation"}:`,
1479
- ...files.map(f => ` - ${f}`),
2343
+ ...files.map(f => ` - ${bold(f)}`),
1480
2344
  "",
1481
2345
  "An .odp file is a ZIP archive. In its content.xml, some slide titles carry",
1482
2346
  "layout instructions in their alt-text description: <svg:desc> elements whose",
@@ -1504,8 +2368,12 @@ const PRAGMAS = [
1504
2368
  ["@hint <text>", "Instruction for an AI: stored verbatim in the .odp (alt-text of the slide title), never displayed."],
1505
2369
  ["@layout grid <C>x<R>", "Put the next C×R sections (starting at the next heading) on one slide, in a grid."],
1506
2370
  ["@layout columns <sizes>", 'Put the next sections on one slide, in columns sized "1fr", "2fr"... or "auto" (one size per section).'],
1507
- ["@graph <file.dot>", "Insert a Graphviz diagram (path relative to the .md) as native shapes editable in Impress."],
2371
+ ["@layout ... (no heading after)", "Put the next blocks (paragraph, list, image...) of the section on one slide, one per cell, without headings."],
2372
+ ["@graph <file.dot>", "Insert a Graphviz diagram (path relative to the .md), rendered as a PNG image by dot."],
1508
2373
  ["@next", "Start a new slide with the same title as the current one (unless a heading follows)."],
2374
+ ["@compact", "Shrink the next table so that it fits on one slide, instead of splitting it."],
2375
+ ["@compact [N|*] { ... @}", 'Compact the blocks in between on one slide, flowing through N columns (1 by default, "*": the number giving the biggest text), shrunk if needed.'],
2376
+ ["@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
2377
  ["```prompt ... ```", "Not a pragma: a code block shown as a chat prompt bubble."],
1510
2378
  ];
1511
2379
  function printHelp() {
@@ -1531,22 +2399,23 @@ async function main(args) {
1531
2399
  const files = args.filter(f => f.toLowerCase().endsWith(".md"));
1532
2400
  for (const f of args)
1533
2401
  if (!files.includes(f))
1534
- console.warn(`Ignoring ${f}: not a .md file`);
2402
+ console.warn(`Ignoring ${bold(f)}: not a .md file`);
1535
2403
  if (!files.length) {
1536
2404
  console.error("No .md file given. Run without arguments for help.");
1537
2405
  process.exit(1);
1538
2406
  }
1539
- await loadGraphviz();
1540
2407
  const withHints = [];
1541
2408
  let failed = false;
1542
2409
  for (const file of files) {
1543
2410
  const src = resolve(file);
1544
- console.log(`Processing ${src}`);
2411
+ console.log(`Processing ${bold(src)}`);
1545
2412
  try {
2413
+ if (existsSync(src) && usesGraph(src))
2414
+ await ensureDot();
1546
2415
  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)})`);
2416
+ console.log(created ? ` + ${bold(path)} (created with the default style)` : ` ⚙ ${bold(path)}`);
2417
+ const { out, hints } = await convert(src, config);
2418
+ console.log(` → ${bold(out)} (${humanSize(statSync(out).size)})`);
1550
2419
  if (hints)
1551
2420
  withHints.push([out, hints]);
1552
2421
  }
@@ -1559,9 +2428,9 @@ async function main(args) {
1559
2428
  console.log("\nThese presentations contain @hint pragmas (stored in the slide titles' alt-text descriptions)");
1560
2429
  console.log("and can be refined with AI:");
1561
2430
  for (const [out, n] of withHints)
1562
- console.log(` - ${out} (${n} hint${n > 1 ? "s" : ""})`);
2431
+ console.log(` - ${bold(out)} (${n} hint${n > 1 ? "s" : ""})`);
1563
2432
  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)));
2433
+ console.log(cyan(aiPrompt(withHints.map(([out]) => out))));
1565
2434
  }
1566
2435
  if (failed)
1567
2436
  process.exit(1);