@tolokoban/impress 0.13.0 → 0.20.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
@@ -25,8 +25,18 @@
25
25
  * Every embedded image (graphs included) is stored as WebP (see `theme.images`).
26
26
  * @next start a new slide with the same title as the current one
27
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
28
30
  * @reveal C1,3 R1-4 the rows of the next table appear one slide after the other; the
29
31
  * columns (C) and rows (R) listed, both optional, are always visible
32
+ * @anim 1.5 (opacity=0.1:1, scale=0.5:1) 300ms 100ms ease-out { ... @}
33
+ * the blocks in between are animated in the slideshow: integral part of
34
+ * the index = number of clicks, decimals = chained in the same click
35
+ * @box info { ... @} the paragraphs, lists and boxes in between are drawn in a box, styled
36
+ * by the box "info" of the `boxes` of the style file (nestable)
37
+ * @animation (opacity=0.1:1) 300ms
38
+ * defaults of the `@anim` of the slide (properties, duration, delay,
39
+ * easing): `@anim {` takes them all, `@anim (opacity) {` the values
30
40
  * ```prompt ... ``` chat prompt bubble
31
41
  */
32
42
  import { existsSync, readFileSync, writeFileSync, statSync } from "node:fs";
@@ -60,6 +70,8 @@ let GAP = 0;
60
70
  let CENTER = false;
61
71
  function useStyle(config) {
62
72
  style = config;
73
+ // The boxes of `@box` become named styles (their values can use the theme, hence `style` first).
74
+ style = { ...config, styles: { ...config.styles, ...boxStyles(config) } };
63
75
  sizes = config.theme.sizes;
64
76
  SLIDE_W = config.theme.slide.width;
65
77
  SLIDE_H = config.theme.slide.height;
@@ -110,6 +122,225 @@ function resolveValue(value, where) {
110
122
  return String(v);
111
123
  });
112
124
  }
125
+ // ---------------------------------------------------------------- boxes (`@box`)
126
+ /** Named graphic style of the boxes `@box <name> {`. */
127
+ const boxStyleName = (name) => `Box-${name}`;
128
+ /** Named graphic style of the text frames of the boxes `name` holding other boxes. */
129
+ const boxTextStyleName = (name) => `Box-${name}-texte`;
130
+ /** A length ("0.3cm", "3mm", "8pt", "0.1in") in cm. */
131
+ function lengthCm(value, where) {
132
+ const m = value.match(/^(-?(?:\d+(?:\.\d+)?|\.\d+))(cm|mm|pt|in)$/);
133
+ if (!m)
134
+ throw new Error(`${where}: invalid length "${value}" (expected e.g. 0.3cm, 3mm or 8pt)`);
135
+ return Number(m[1]) * { cm: 1, mm: 0.1, pt: PT, in: 2.54 }[m[2]];
136
+ }
137
+ /** `#RRGGBB` or `#RGB` as [red, green, blue] from 0 to 255, or null. */
138
+ function rgb(color) {
139
+ const long = color.match(/^#([0-9a-f]{6})$/i);
140
+ if (long) {
141
+ const n = parseInt(long[1], 16);
142
+ return [n >> 16, (n >> 8) & 255, n & 255];
143
+ }
144
+ const short = color.match(/^#([0-9a-f]{3})$/i);
145
+ return short ? [...short[1]].map(c => parseInt(c + c, 16)) : null;
146
+ }
147
+ /** Black or white, whichever contrasts most with `background` (WCAG contrast ratio). */
148
+ function readableOn(background) {
149
+ const [r, g, b] = rgb(background).map(v => {
150
+ v /= 255;
151
+ return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
152
+ });
153
+ const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
154
+ return 1.05 / (lum + 0.05) >= (lum + 0.05) / 0.05 ? "#FFFFFF" : "#000000";
155
+ }
156
+ function boxGeom(name, box = style.boxes[name]) {
157
+ const where = `box "${name}" of the style file`;
158
+ const lengths = (spec) => resolveValue(spec, where).trim().split(/\s+/).filter(Boolean);
159
+ /** `<all>` or `<vertical> <horizontal>`. */
160
+ const pair = (key, spec) => {
161
+ const v = lengths(spec).map(x => lengthCm(x, `${where}, "${key}"`));
162
+ if (v.length < 1 || v.length > 2)
163
+ throw new Error(`${where}: "${key}" must be "<all>" or "<vertical> <horizontal>", got "${spec}"`);
164
+ return [v[0], v[1] ?? v[0]];
165
+ };
166
+ const [padY, padX] = pair("padding", box.padding ?? "0.4cm 0.6cm");
167
+ const [marginY, marginX] = pair("margin", box.margin ?? "0cm");
168
+ const radius = lengths(box.radius ?? "0cm");
169
+ if (radius.length !== 1)
170
+ throw new Error(`${where}: "radius" must be one length (e.g. 0.3cm), got "${box.radius}"`);
171
+ return { padY, padX, marginY, marginX, radius: lengthCm(radius[0], `${where}, "radius"`) };
172
+ }
173
+ /** Font properties of `font`: "sans", "mono" or the name of a font family. */
174
+ function boxFont(font) {
175
+ if (font === "" || font === "sans")
176
+ return { "fo:font-family": "{fonts.sans}", "style:font-family-generic": "swiss" };
177
+ if (font === "mono")
178
+ return { "fo:font-family": "{fonts.mono}", "style:font-family-generic": "modern" };
179
+ return { "fo:font-family": /^['{]/.test(font) ? font : `'${font}'` };
180
+ }
181
+ /** `none` or `<width> <solid|dashed> <color>`, in any order. */
182
+ function boxBorder(spec, where) {
183
+ if (spec === "" || spec === "none")
184
+ return { "draw:stroke": "none" };
185
+ let [width, dashed, color] = ["0.03cm", false, "#000000"];
186
+ for (const tok of spec.split(/\s+/)) {
187
+ if (tok === "solid" || tok === "dashed")
188
+ dashed = tok === "dashed";
189
+ else if (rgb(tok))
190
+ color = tok;
191
+ else
192
+ width = (lengthCm(tok, `${where}, "border"`), tok);
193
+ }
194
+ const dash = Object.keys(style.dashes)[0];
195
+ return {
196
+ "draw:stroke": dashed && dash ? "dash" : "solid",
197
+ ...(dashed && dash && { "draw:stroke-dash": dash }),
198
+ "svg:stroke-color": color,
199
+ "svg:stroke-width": width,
200
+ };
201
+ }
202
+ /** `none` or `<x> <y> [<blur>] <color> [<opacity>]`. */
203
+ function boxShadow(spec, where) {
204
+ if (spec === "" || spec === "none")
205
+ return { "draw:shadow": "hidden" };
206
+ const lengths = [];
207
+ let color = "";
208
+ let opacity = "100%";
209
+ for (const tok of spec.split(/\s+/)) {
210
+ if (rgb(tok))
211
+ color = tok;
212
+ else if (/^\d+(\.\d+)?%$/.test(tok))
213
+ opacity = tok;
214
+ else
215
+ lengths.push((lengthCm(tok, `${where}, "shadow"`), tok));
216
+ }
217
+ if (lengths.length < 2 || lengths.length > 3 || !color)
218
+ throw new Error(`${where}: "shadow" must be "none" or "<x> <y> [<blur>] <color> [<opacity>]" (e.g. "0.1cm 0.1cm 0.3cm #000000 30%"), got "${spec}"`);
219
+ return {
220
+ "draw:shadow": "visible",
221
+ "draw:shadow-offset-x": lengths[0],
222
+ "draw:shadow-offset-y": lengths[1],
223
+ "draw:shadow-color": color,
224
+ "draw:shadow-opacity": opacity,
225
+ ...(lengths[2] && { "loext:shadow-blur": lengths[2] }),
226
+ };
227
+ }
228
+ /**
229
+ * Named styles `Box-<name>` of the boxes of the style file. A style `Box-<name>` of `styles`, if
230
+ * any, is merged over the one built from the box.
231
+ */
232
+ function boxStyles(config) {
233
+ const out = {};
234
+ for (const [name, box] of Object.entries(config.boxes ?? {})) {
235
+ const where = `box "${name}" of the style file`;
236
+ const value = (v) => resolveValue(v ?? "", where).trim();
237
+ const background = value(box.background);
238
+ if (!rgb(background))
239
+ throw new Error(`${where}: "background" must be a color like #DCEBFF, got "${box.background ?? ""}"`);
240
+ const color = value(box.color) || readableOn(background);
241
+ const { padY, padX } = boxGeom(name, box);
242
+ const list = config.styles["Master-outline1"];
243
+ const def = {
244
+ family: "graphic",
245
+ parent: "standard",
246
+ graphic: {
247
+ "draw:auto-grow-height": "false",
248
+ "draw:auto-grow-width": "false",
249
+ "draw:fit-to-size": "false",
250
+ "style:shrink-to-fit": "true",
251
+ "draw:fill": "solid",
252
+ "draw:fill-color": background,
253
+ ...boxBorder(value(box.border), where),
254
+ ...boxShadow(value(box.shadow), where),
255
+ "fo:padding-top": `${f2(padY)}cm`,
256
+ "fo:padding-bottom": `${f2(padY)}cm`,
257
+ "fo:padding-left": `${f2(padX)}cm`,
258
+ "fo:padding-right": `${f2(padX)}cm`,
259
+ "draw:textarea-vertical-align": "middle",
260
+ ...box.graphic,
261
+ },
262
+ paragraph: { "fo:margin-top": "0cm", "fo:margin-bottom": "0.2cm", "fo:line-height": "110%", ...box.paragraph },
263
+ text: { ...boxFont(box.font ?? ""), "fo:font-size": box.size ?? "{sizes.text}pt", "fo:color": color, ...box.text },
264
+ // The bullets and numbers of the slides, in the color of the text of the box.
265
+ ...(list?.bullets && { bullets: { ...list.bullets, color } }),
266
+ ...(list?.numbers && { numbers: { ...list.numbers, color } }),
267
+ };
268
+ const own = config.styles[boxStyleName(name)];
269
+ out[boxStyleName(name)] = own ? deepMerge(def, own) : def;
270
+ // Text frames of a box holding other boxes: the text of the box, without its frame.
271
+ out[boxTextStyleName(name)] = {
272
+ family: "graphic",
273
+ parent: boxStyleName(name),
274
+ graphic: {
275
+ "draw:fill": "none",
276
+ "draw:stroke": "none",
277
+ "draw:shadow": "hidden",
278
+ "fo:padding-top": "0cm",
279
+ "fo:padding-bottom": "0cm",
280
+ "fo:padding-left": "0cm",
281
+ "fo:padding-right": "0cm",
282
+ "draw:textarea-vertical-align": "top",
283
+ },
284
+ };
285
+ }
286
+ return out;
287
+ }
288
+ /** Font size of the text of the boxes `name`, in points. */
289
+ function boxPt(name) {
290
+ const size = style.styles[boxStyleName(name)]?.text?.["fo:font-size"];
291
+ const m = size ? resolveValue(size, `style "${boxStyleName(name)}"`).match(/^([\d.]+)pt$/) : null;
292
+ return m ? Number(m[1]) : sizes.text;
293
+ }
294
+ /** Is the text of the boxes `name` in the monospace font of the theme? Its characters are wider. */
295
+ function boxIsMono(name) {
296
+ const family = style.styles[boxStyleName(name)]?.text?.["fo:font-family"];
297
+ return !!family && resolveValue(family, `style "${boxStyleName(name)}"`) === style.theme.fonts.mono;
298
+ }
299
+ function boxItems(b) {
300
+ const items = [];
301
+ for (const x of b.blocks) {
302
+ const last = items[items.length - 1];
303
+ // Nested boxes are shrunk with their parent (`@compact {`).
304
+ if (x.t === "box")
305
+ items.push({ kind: "box", box: b.k === undefined ? x : { ...x, k: b.k } });
306
+ else if (last?.kind === "text")
307
+ last.blocks.push(x);
308
+ else
309
+ items.push({ kind: "text", blocks: [x] });
310
+ }
311
+ return items;
312
+ }
313
+ /** Space between a nested box and what follows it in its parent. */
314
+ const BOX_GAP = 0.2;
315
+ /** Height of the paragraphs and lists of the boxes `name`, `width` wide. */
316
+ function boxTextH(name, blocks, width, k) {
317
+ const pt = boxPt(name) * k;
318
+ // Monospace characters are about 20% wider than those `textH()` assumes.
319
+ const chars = (text) => plainLen(text) * (boxIsMono(name) ? 1.2 : 1);
320
+ let h = 0;
321
+ for (const x of blocks) {
322
+ if (x.t === "para")
323
+ h += x.text.split("\n").reduce((a, p) => a + textH(chars(p), width, pt), 0) + 0.2 * k;
324
+ else if (x.t === "list")
325
+ for (const [lvl, txt] of x.items)
326
+ h += textH(chars(txt), width - 0.9 * (lvl + 1), pt) + 0.2 * k;
327
+ }
328
+ return h;
329
+ }
330
+ /** Height of the content of a box (inside its padding), `width` being the room inside its padding. */
331
+ function boxContentH(b, width) {
332
+ const k = b.k ?? 1;
333
+ return boxItems(b).reduce((h, it, i, all) => h + (it.kind === "text" ? boxTextH(b.name, it.blocks, width, k) : boxH(it.box, width) + (i < all.length - 1 ? BOX_GAP * k : 0)), 0);
334
+ }
335
+ /** Height of a box `width` wide, margins included. */
336
+ function boxH(b, width) {
337
+ const { padY, padX, marginY, marginX } = boxGeom(b.name);
338
+ return boxContentH(b, width - 2 * (padX + marginX)) + 2 * (padY + marginY);
339
+ }
340
+ function animOf(b) {
341
+ return b.anim;
342
+ }
343
+ const EASES = ["linear", "ease-in", "ease-out", "ease-in-out"];
113
344
  /** Is this cell hidden until its row is revealed? */
114
345
  function isHidden(b, row, col) {
115
346
  return !!b.reveal && !!b.shown && !b.shown.has(row) && !b.reveal.rows.has(row) && !b.reveal.cols.has(col);
@@ -165,6 +396,8 @@ class Section {
165
396
  layout = null;
166
397
  /** Created by `@next`: continues the previous section on a new slide. */
167
398
  continued = false;
399
+ /** Set by `@animation`: defaults of the animations of its slides (properties and timing). */
400
+ animation = {};
168
401
  /** Folder of the markdown file, for relative image paths. */
169
402
  source;
170
403
  constructor(level, title, parent = null, source = "") {
@@ -185,6 +418,7 @@ function stripMd(s) {
185
418
  .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
186
419
  .replaceAll("**", "")
187
420
  .replaceAll("__", "")
421
+ .replaceAll("~~", "")
188
422
  .replace(/(?<![\p{L}\p{N}_])\*(.+?)\*(?![\p{L}\p{N}_])/gu, "$1")
189
423
  .trim();
190
424
  }
@@ -192,12 +426,107 @@ function stripMd(s) {
192
426
  const LIST_RE = /^(\s*)(?:[*-]|(\d+)[.)])\s+(.*)$/;
193
427
  const IMG_RE = /^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/;
194
428
  const HEAD_RE = /^(#{1,6})\s+(.*)$/;
429
+ /** Horizontal rule: a line of at least three dashes. */
430
+ const HR_RE = /^-{3,}$/;
431
+ /** `@compact {`, `@compact 3 {` or `@compact * {`. */
432
+ const COMPACT_RE = /^@compact\s*(\d+|\*)?\s*\{$/;
433
+ /** `@box <name> {`. */
434
+ const BOX_RE = /^@box\s+([\w-]+)\s*\{$/;
435
+ /**
436
+ * `@anim 1.5 (opacity=0.1:1) 300ms 100ms ease-out {`: index, properties, timing, all optional.
437
+ * The index is not followed by a letter, so `@anim 300ms {` is a duration.
438
+ */
439
+ const ANIM_RE = /^@anim(?:\s+(\d+(?:\.\d+)?|\.\d+)(?![\w.]))?\s*(?:\((.*)\))?\s*(.*?)\s*\{$/;
440
+ /** `@animation (opacity=0.1:1 500ms) 300ms ease-out`, or the short form `@animation (300ms)`. */
441
+ const ANIMATION_RE = /^@animation(?:\s*\((.*)\))?\s*(.*)$/;
442
+ const isTimingToken = (tok) => /^(\d+(?:\.\d+)?|\.\d+)(ms|s)$/.test(tok) || EASES.includes(tok);
443
+ /** `@animation`: its properties (with their values) and its timing. */
444
+ function parseAnimation(s, where) {
445
+ const m = s.match(ANIMATION_RE);
446
+ const [inner, rest] = [(m?.[1] ?? "").trim(), (m?.[2] ?? "").trim()];
447
+ const tokens = (t) => t.split(/\s+/).filter(Boolean);
448
+ if (!m || (m[1] === undefined && rest && !tokens(rest).every(isTimingToken)))
449
+ throw new Error(`${where}: expected "@animation [(<property>=<from>:<to>, ...)] [<duration> [<delay>]] [<easing>]" (e.g. "@animation (opacity=0.1:1) 300ms"), got "${s}"`);
450
+ // `@animation (300ms ease-out)`: only a timing in the parentheses.
451
+ if (inner && tokens(inner).every(isTimingToken)) {
452
+ if (rest)
453
+ throw new Error(`${where}: "@animation" has two timings, in and after its parentheses`);
454
+ return parseTiming(tokens(inner), where, '"@animation"');
455
+ }
456
+ const props = inner ? parseAnimProps(inner, where, true) : undefined;
457
+ return { ...(props && { props }), ...parseTiming(tokens(rest), where, '"@animation"') };
458
+ }
459
+ /**
460
+ * Timing as in the CSS `transition` shorthand: the first time is the duration, the second one
461
+ * the delay, and an easing keyword can be anywhere. Times are in `ms` or `s`.
462
+ */
463
+ function parseTiming(tokens, where, what) {
464
+ const t = {};
465
+ const times = [];
466
+ for (const tok of tokens) {
467
+ const m = tok.match(/^(\d+(?:\.\d+)?|\.\d+)(ms|s)$/);
468
+ if (m)
469
+ times.push(Number(m[1]) / (m[2] === "ms" ? 1000 : 1));
470
+ else if (EASES.includes(tok))
471
+ t.ease = tok;
472
+ else
473
+ throw new Error(`${where}: unexpected "${tok}" in ${what} (expected a duration and a delay like 300ms or 0.3s, or an easing: ${EASES.join(", ")})`);
474
+ }
475
+ if (times.length > 2)
476
+ throw new Error(`${where}: too many times in ${what}: the first one is the duration, the second one the delay`);
477
+ if (times.length)
478
+ t.dur = times[0];
479
+ if (times.length > 1)
480
+ t.delay = times[1];
481
+ return t;
482
+ }
483
+ /**
484
+ * `opacity=0.1:1 300ms, scale=0.5,1:1,1`: animated properties, with their own timing. Unless
485
+ * `valuesRequired` (`@animation`), a property can come without values (`opacity 300ms`): those of
486
+ * the `@animation` of the slide are taken.
487
+ */
488
+ function parseAnimProps(spec, where, valuesRequired) {
489
+ const props = [];
490
+ // Commas also separate the x and y of a scale: only a comma followed by a name separates properties.
491
+ for (const part of spec.split(/,\s*(?=[a-z])/i).map(p => p.trim())) {
492
+ const m = part.match(/^([a-z][\w-]*)(?:\s*=\s*([^:\s]+)\s*:\s*(\S+))?(?:\s+(.*))?$/i);
493
+ if (!m || (valuesRequired && m[2] === undefined))
494
+ throw new Error(`${where}: expected "<property>=<from>:<to>" (e.g. "opacity=0.1:1"${valuesRequired ? "" : ', or "opacity" for the values of "@animation"'}), got "${part}"`);
495
+ const name = m[1];
496
+ if (name !== "opacity" && name !== "scale")
497
+ throw new Error(`${where}: unknown animated property "${name}" (only opacity and scale are supported)`);
498
+ if (props.some(p => p.name === name))
499
+ throw new Error(`${where}: "${name}" is animated twice`);
500
+ const values = (s) => {
501
+ const ns = s.split(",").map(Number);
502
+ const count = name === "opacity" ? [1] : [1, 2];
503
+ if (!count.includes(ns.length) || ns.some(n => !Number.isFinite(n) || n < 0 || (name === "opacity" && n > 1)))
504
+ throw new Error(`${where}: invalid ${name} value "${s}" (${name === "opacity" ? "a number from 0 to 1" : 'a positive number, or "x,y" for different horizontal and vertical scales'})`);
505
+ return ns.length === 1 && name === "scale" ? [ns[0], ns[0]] : ns;
506
+ };
507
+ const timing = parseTiming((m[4] ?? "").split(/\s+/).filter(Boolean), where, `the timing of "${name}"`);
508
+ props.push({ name, ...(m[2] !== undefined && { from: values(m[2]), to: values(m[3]) }), ...timing });
509
+ }
510
+ return props;
511
+ }
195
512
  function parse(md, file) {
196
513
  const root = new Section(0, "", null, dirname(file));
197
514
  let cur = root;
198
515
  const lines = md.split("\n");
199
516
  let para = [];
200
517
  let list = null;
518
+ // Open `@compact {` region: its blocks go into it until `@}`.
519
+ let region = null;
520
+ // Open `@anim {` region: its blocks are animated until `@}`, and how many there are.
521
+ let animRegion = null;
522
+ let animated = 0;
523
+ // Open `@box {` regions, innermost last, and the innermost one: its blocks go into it until `@}`.
524
+ const boxes = [];
525
+ let box = null;
526
+ // Line of the markdown being parsed (1-based), for the messages.
527
+ let lineNo = 0;
528
+ // Kinds of the open regions, innermost last: `@}` closes the last one.
529
+ const open = [];
201
530
  let layout = null;
202
531
  // `@layout` followed by content instead of a heading: the next blocks fill its cells.
203
532
  let grouped = null;
@@ -216,6 +545,21 @@ function parse(md, file) {
216
545
  reveal = null;
217
546
  };
218
547
  const push = (b) => {
548
+ // The box is animated as a whole: its blocks are not animated on their own.
549
+ if (box && b.t !== "note") {
550
+ if (b.t !== "para" && b.t !== "list" && b.t !== "box") {
551
+ const what = { image: "an image", table: "a table", quote: "a quote", prompt: "a prompt", code: "a code block", hr: "a horizontal rule" }[b.t] ?? `a ${b.t}`;
552
+ throw new Error(`${file}:${lineNo}: a "@box {" region can only hold paragraphs, lists and boxes, not ${what} (box opened at line ${box.where.split(":").pop()})`);
553
+ }
554
+ return void box.blocks.push(b);
555
+ }
556
+ if (animRegion && b.t !== "note") {
557
+ ;
558
+ b.anim = animRegion;
559
+ animated++;
560
+ }
561
+ if (region)
562
+ return void region.blocks.push(b);
219
563
  if (!grouped)
220
564
  return void cur.blocks.push(b);
221
565
  const cells = grouped.cells;
@@ -254,6 +598,13 @@ function parse(md, file) {
254
598
  const line = lines[i];
255
599
  const s = line.trim();
256
600
  let m;
601
+ lineNo = i + 1;
602
+ const inner = box ?? animRegion ?? region;
603
+ if (inner && (HEAD_RE.test(line) || s === "@next" || s.startsWith("@layout"))) {
604
+ const what = HEAD_RE.test(line) ? "a heading" : s === "@next" ? '"@next"' : '"@layout"';
605
+ const kind = inner === box ? 'a "@box' : inner === animRegion ? 'an "@anim' : 'a "@compact';
606
+ throw new Error(`${file}:${i + 1}: ${what} cannot be inside ${kind} {" region (opened at line ${inner.where.split(":").pop()}, closed by "@}")`);
607
+ }
257
608
  if ((m = line.match(HEAD_RE))) {
258
609
  flush();
259
610
  dropCompact();
@@ -297,6 +648,92 @@ function parse(md, file) {
297
648
  cur.parent.children.push(sec);
298
649
  cur = sec;
299
650
  }
651
+ else if ((m = s.match(COMPACT_RE))) {
652
+ const where = `${file}:${i + 1}`;
653
+ if (box)
654
+ throw new Error(`${where}: a "@compact {" region cannot be inside a "@box {" region (opened at line ${box.where.split(":").pop()}); put the "@box {" inside the "@compact {" instead`);
655
+ if (region)
656
+ throw new Error(`${where}: "@compact {" regions cannot be nested (one is already open since line ${region.where.split(":").pop()})`);
657
+ if (animRegion)
658
+ throw new Error(`${where}: a "@compact {" region cannot be inside an "@anim {" region (opened at line ${animRegion.where.split(":").pop()}); put the "@anim {" inside the "@compact {" instead`);
659
+ flush();
660
+ dropCompact();
661
+ dropReveal();
662
+ const columns = m[1] === "*" ? "auto" : Number(m[1] ?? 1);
663
+ if (columns === 0)
664
+ throw new Error(`${where}: a "@compact {" region needs at least one column`);
665
+ const b = { t: "compact", columns, blocks: [], where };
666
+ push(b);
667
+ region = b;
668
+ open.push("compact");
669
+ }
670
+ else if (s.startsWith("@animation")) {
671
+ const where = `${file}:${i + 1}`;
672
+ cur.animation = parseAnimation(s, where);
673
+ }
674
+ else if ((m = s.match(ANIM_RE))) {
675
+ const where = `${file}:${i + 1}`;
676
+ if (box)
677
+ throw new Error(`${where}: an "@anim {" region cannot be inside a "@box {" region (opened at line ${box.where.split(":").pop()}); put the "@box {" inside the "@anim {" instead`);
678
+ if (animRegion)
679
+ throw new Error(`${where}: "@anim {" regions cannot be nested (one is already open since line ${animRegion.where.split(":").pop()})`);
680
+ flush();
681
+ dropCompact();
682
+ dropReveal();
683
+ const timing = parseTiming(m[3].split(/\s+/).filter(Boolean), where, '"@anim"');
684
+ // `@anim {` or `@anim () {`: the properties of the `@animation` of the slide.
685
+ const props = m[2]?.trim() ? parseAnimProps(m[2], where, false) : undefined;
686
+ animRegion = { index: Number(m[1] ?? 0), ...(props && { props }), where, ...timing };
687
+ animated = 0;
688
+ open.push("anim");
689
+ }
690
+ else if (s.startsWith("@anim")) {
691
+ throw new Error(`${file}:${i + 1}: expected "@anim [<index>] (<property>=<from>:<to>, ...) [<duration> [<delay>]] [<easing>] {" (e.g. "@anim 1 (opacity=0.1:1) {"), got "${s}"`);
692
+ }
693
+ else if ((m = s.match(BOX_RE))) {
694
+ const where = `${file}:${i + 1}`;
695
+ const name = m[1];
696
+ if (!style.boxes[name]) {
697
+ const known = Object.keys(style.boxes);
698
+ throw new Error(`${where}: unknown box "${name}": add it to the "boxes" of the style file (known boxes: ${known.length ? known.join(", ") : "none"})`);
699
+ }
700
+ flush();
701
+ dropCompact();
702
+ dropReveal();
703
+ const b = { t: "box", name, blocks: [], where };
704
+ // Inside another box, it goes into that box.
705
+ push(b);
706
+ boxes.push(b);
707
+ box = b;
708
+ open.push("box");
709
+ }
710
+ else if (s.startsWith("@box")) {
711
+ throw new Error(`${file}:${i + 1}: expected "@box <name> {" (e.g. "@box info {"), got "${s}"`);
712
+ }
713
+ else if (s === "@}") {
714
+ const kind = open.pop();
715
+ if (!kind)
716
+ throw new Error(`${file}:${i + 1}: "@}" without an open "@compact {", "@anim {" or "@box {" region`);
717
+ flush();
718
+ dropCompact();
719
+ dropReveal();
720
+ if (kind === "box") {
721
+ if (!box.blocks.length)
722
+ console.warn(` ! ${bold(box.where)}: empty "@box {" region`);
723
+ boxes.pop();
724
+ box = boxes[boxes.length - 1] ?? null;
725
+ }
726
+ else if (kind === "anim") {
727
+ if (!animated)
728
+ console.warn(` ! ${bold(animRegion.where)}: empty "@anim {" region`);
729
+ animRegion = null;
730
+ }
731
+ else {
732
+ if (!region.blocks.some(b => b.t !== "note"))
733
+ console.warn(` ! ${bold(region.where)}: empty "@compact {" region`);
734
+ region = null;
735
+ }
736
+ }
300
737
  else if (s === "@compact") {
301
738
  flush();
302
739
  dropCompact();
@@ -378,6 +815,10 @@ function parse(md, file) {
378
815
  i--;
379
816
  push({ t: "quote", text: buf.join(" ") });
380
817
  }
818
+ else if (HR_RE.test(s)) {
819
+ flush();
820
+ push({ t: "hr" });
821
+ }
381
822
  else if ((m = line.match(IMG_RE))) {
382
823
  flush();
383
824
  push({ t: "image", alt: m[1], src: m[2] });
@@ -411,6 +852,12 @@ function parse(md, file) {
411
852
  flush();
412
853
  dropCompact();
413
854
  dropReveal();
855
+ if (box)
856
+ throw new Error(`${box.where}: "@box {" region not closed by "@}"`);
857
+ if (animRegion)
858
+ throw new Error(`${animRegion.where}: "@anim {" region not closed by "@}"`);
859
+ if (region)
860
+ throw new Error(`${region.where}: "@compact {" region not closed by "@}"`);
414
861
  if (layout)
415
862
  console.warn(` ! ${bold(file)}: "${layout.source}" is not followed by any section`);
416
863
  return root;
@@ -422,6 +869,7 @@ const INLINE_PATTERNS = [
422
869
  ["b", /\*\*(.+?)\*\*/s],
423
870
  ["i", /(?<![\p{L}\p{N}_*])\*(?!\s)(.+?)(?<!\s)\*(?![\p{L}\p{N}_*])/su],
424
871
  ["code", /`([^`]+)`/],
872
+ ["s", /~~(?!\s)(.+?)(?<!\s)~~/s],
425
873
  ];
426
874
  function inline(s, fmt = new Set(), href = null) {
427
875
  s = s.replace("$\\text{XX}^\\text{e}$", "XXᵉ");
@@ -489,6 +937,8 @@ function runsXml(text) {
489
937
  const st = spanStyle(fmt);
490
938
  if (st)
491
939
  x = `<text:span text:style-name="${st}">${x}</text:span>`;
940
+ if (fmt.has("s"))
941
+ x = `<text:span text:style-name="T_s">${x}</text:span>`;
492
942
  if (href)
493
943
  x = `<text:a xlink:type="simple" xlink:href="${esc(href)}">${x}</text:a>`;
494
944
  return x;
@@ -503,17 +953,17 @@ function textH(nChars, width, pt, lh = 1.25) {
503
953
  const cpl = Math.max(1, width / (pt * PT * 0.5));
504
954
  return Math.max(1, Math.ceil(nChars / cpl)) * pt * PT * lh;
505
955
  }
506
- function paraH(text, width, pt = sizes.text) {
507
- return text.split("\n").reduce((h, p) => h + textH(plainLen(p), width, pt), 0) + 0.25;
956
+ function paraH(text, width, pt = sizes.text, k = 1) {
957
+ return text.split("\n").reduce((h, p) => h + textH(plainLen(p), width, pt), 0) + 0.25 * k;
508
958
  }
509
- function listH(items, width) {
959
+ function listH(items, width, k = 1) {
510
960
  let h = 0;
511
961
  for (const [lvl, txt] of items)
512
- h += textH(plainLen(txt), width - 0.9 * (lvl + 1), sizes.list[Math.min(lvl, 8)]) + 0.3;
962
+ h += textH(plainLen(txt), width - 0.9 * (lvl + 1), sizes.list[Math.min(lvl, 8)] * k) + 0.3 * k;
513
963
  return h + 0.1;
514
964
  }
515
- function promptSize(lines, width) {
516
- const pt = sizes.prompt;
965
+ function promptSize(lines, width, k = 1) {
966
+ const pt = sizes.prompt * k;
517
967
  const longest = Math.max(10, ...lines.map(l => l.length));
518
968
  const w = Math.min(width, Math.max(8, longest * pt * PT * 0.5 + 1.4));
519
969
  const h = lines.reduce((acc, l) => acc + textH(l.length, w - 1, pt), 0) + 0.9;
@@ -616,11 +1066,11 @@ function boldWordW(word, pt) {
616
1066
  * Do the words of the header of a `@compact` or `@reveal` table fit in their columns, at the
617
1067
  * size of the table, on a slide of full width? Several words may wrap, but no word is cut.
618
1068
  */
619
- function headerFits(b) {
1069
+ function headerFits(b, width = W) {
620
1070
  if (!b.header)
621
1071
  return true;
622
1072
  const pt = b.pt ?? sizes.table;
623
- const cols = tableBlockCols(b, W);
1073
+ const cols = tableBlockCols(b, width);
624
1074
  return b.header.every((s, i) => {
625
1075
  const c = cell(s);
626
1076
  const room = cols[i] - CELL_PAD_X - cellTextIndent(c, cols[i], pt);
@@ -682,19 +1132,27 @@ function tableBlockH(b, width) {
682
1132
  const pw = tablePartW(b, width);
683
1133
  return Math.max(...tableParts(b).map(rows => tableH(b.header, rows, pw, b.pt ?? sizes.table, cols)));
684
1134
  }
1135
+ /** Height taken by a horizontal rule (the line is drawn in its middle). */
1136
+ const HR_H = 0.5;
685
1137
  function blockH(b, width) {
686
1138
  switch (b.t) {
687
1139
  case "para":
688
- return paraH(b.text, width);
1140
+ return paraH(b.text, width, sizes.text * (b.k ?? 1), b.k);
689
1141
  case "list":
690
- return listH(b.items, width);
1142
+ return listH(b.items, width, b.k);
691
1143
  case "quote":
692
- return paraH(b.text, width - 1.2, sizes.quote) + 0.8;
1144
+ return paraH(b.text, width - 1.2, sizes.quote * (b.k ?? 1), b.k) + 0.8;
693
1145
  case "prompt":
694
1146
  case "code":
695
- return promptSize(b.lines, width)[1];
1147
+ return promptSize(b.lines, width, b.k)[1];
696
1148
  case "table":
697
1149
  return tableBlockH(b, width);
1150
+ case "hr":
1151
+ return HR_H;
1152
+ case "compact":
1153
+ return arrange(b, width).h;
1154
+ case "box":
1155
+ return boxH(b, width);
698
1156
  default:
699
1157
  return 0;
700
1158
  }
@@ -740,6 +1198,168 @@ function fit(iw, ih, bw, bh) {
740
1198
  const r = Math.min(bw / iw, bh / ih);
741
1199
  return [iw * r, ih * r];
742
1200
  }
1201
+ // ---------------------------------------------------------------- compact regions
1202
+ /** Lowest font scale of a `@compact {` region: 10pt for a body text of 24pt. */
1203
+ const MIN_COMPACT_SCALE = 10 / 24;
1204
+ /** Highest number of columns tried by `@compact * {`. */
1205
+ const MAX_AUTO_COLUMNS = 8;
1206
+ /** Font scales tried for a `@compact {` region, biggest first: the body text loses half a point at each step. */
1207
+ function compactScales() {
1208
+ const out = [];
1209
+ for (let pt = sizes.text; pt >= sizes.text * MIN_COMPACT_SCALE - 1e-6; pt -= 0.5)
1210
+ out.push(pt / sizes.text);
1211
+ return out;
1212
+ }
1213
+ const piecesCache = new WeakMap();
1214
+ function compactPieces(blocks) {
1215
+ let out = piecesCache.get(blocks);
1216
+ if (out)
1217
+ return out;
1218
+ const pieces = [];
1219
+ for (const b of blocks) {
1220
+ if (b.t === "note")
1221
+ continue;
1222
+ if (b.t === "list") {
1223
+ let start = 0;
1224
+ b.items.forEach((it, i) => {
1225
+ if (i > start && it[0] === 0) {
1226
+ pieces.push({ src: b, block: { ...b, items: b.items.slice(start, i) } });
1227
+ start = i;
1228
+ }
1229
+ });
1230
+ pieces.push({ src: b, block: { ...b, items: b.items.slice(start) } });
1231
+ }
1232
+ else if (b.t === "table" && b.rows.length > 1) {
1233
+ for (const r of b.rows)
1234
+ pieces.push({ src: b, block: { ...b, rows: [r] } });
1235
+ }
1236
+ else
1237
+ pieces.push({ src: b, block: b });
1238
+ }
1239
+ piecesCache.set(blocks, (out = pieces));
1240
+ return out;
1241
+ }
1242
+ /** A block of a region at the font scale `k`. Tables keep the column widths of all their rows. */
1243
+ function scaleBlock(b, src, k) {
1244
+ if (b.t === "table")
1245
+ return { ...b, pt: sizes.table * k, ref: src.rows, compact: undefined, columns: undefined };
1246
+ if (b.t === "hr" || b.t === "note" || b.t === "layout" || b.t === "compact")
1247
+ return b;
1248
+ return { ...b, k };
1249
+ }
1250
+ /** The blocks of a column: consecutive pieces of the same list or table are merged back together. */
1251
+ function mergePieces(pieces, k) {
1252
+ const out = [];
1253
+ pieces.forEach((p, i) => {
1254
+ const last = out[out.length - 1];
1255
+ const same = i > 0 && pieces[i - 1].src === p.src;
1256
+ if (same && last.t === "list" && p.block.t === "list")
1257
+ out[out.length - 1] = { ...last, items: [...last.items, ...p.block.items] };
1258
+ else if (same && last.t === "table" && p.block.t === "table")
1259
+ out[out.length - 1] = { ...last, rows: [...last.rows, ...p.block.rows] };
1260
+ else
1261
+ out.push(scaleBlock(p.block, p.src, k));
1262
+ });
1263
+ return out;
1264
+ }
1265
+ /** 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. */
1266
+ function regionBlockH(b, width) {
1267
+ if (b.t !== "image")
1268
+ return blockH(b, width);
1269
+ return regionImageSize(b, width)[1];
1270
+ }
1271
+ function regionImageSize(b, width) {
1272
+ const [iw, ih] = imageSize(resolve(mdDir, b.src));
1273
+ return fit(iw, ih, width, H * (b.k ?? 1));
1274
+ }
1275
+ const arrangeCache = new WeakMap();
1276
+ /**
1277
+ * Lay out a region at its scale and number of columns (fewer if it has fewer pieces) in `width`.
1278
+ * The pieces flow in reading order through the columns, cut so that the tallest column is as
1279
+ * short as possible.
1280
+ */
1281
+ function arrange(b, width) {
1282
+ const k = b.k ?? 1;
1283
+ const pieces = compactPieces(b.blocks);
1284
+ const P = pieces.length;
1285
+ const n = Math.max(1, Math.min(b.n ?? (b.columns === "auto" ? 1 : b.columns), P));
1286
+ const key = `${f2(width)}|${n}|${k}`;
1287
+ let cache = arrangeCache.get(b.blocks);
1288
+ if (!cache)
1289
+ arrangeCache.set(b.blocks, (cache = new Map()));
1290
+ const hit = cache.get(key);
1291
+ if (hit)
1292
+ return hit;
1293
+ // 1em of the (scaled) body text between the columns.
1294
+ const gap = sizes.text * k * PT;
1295
+ const colW = (width - gap * (n - 1)) / n;
1296
+ const memo = new Map();
1297
+ /** Height of the column holding the pieces `i` to `j - 1`. */
1298
+ const colH = (i, j) => {
1299
+ let h = memo.get(i * (P + 1) + j);
1300
+ if (h === undefined) {
1301
+ const bs = mergePieces(pieces.slice(i, j), k);
1302
+ h = bs.reduce((a, x) => a + regionBlockH(x, colW), 0) + GAP * k * (bs.length - 1);
1303
+ memo.set(i * (P + 1) + j, h);
1304
+ }
1305
+ return h;
1306
+ };
1307
+ // best[c][j]: lowest height of the tallest of `c` columns holding the first `j` pieces;
1308
+ // cut[c][j]: first piece of the last of these columns.
1309
+ const best = [Array.from({ length: P + 1 }, (_, j) => (j ? Infinity : 0))];
1310
+ const cut = [[]];
1311
+ for (let c = 1; c <= n; c++) {
1312
+ best.push(new Array(P + 1).fill(Infinity));
1313
+ cut.push(new Array(P + 1).fill(0));
1314
+ for (let j = c; j <= P; j++)
1315
+ for (let i = c - 1; i < j; i++) {
1316
+ const h = Math.max(best[c - 1][i], colH(i, j));
1317
+ if (h < best[c][j]) {
1318
+ best[c][j] = h;
1319
+ cut[c][j] = i;
1320
+ }
1321
+ }
1322
+ }
1323
+ const cols = [];
1324
+ if (P)
1325
+ for (let c = n, j = P; c > 0; c--) {
1326
+ const i = cut[c][j];
1327
+ cols.unshift(mergePieces(pieces.slice(i, j), k));
1328
+ j = i;
1329
+ }
1330
+ const out = { n, k, colW, gap, cols, h: P ? best[n][P] : 0 };
1331
+ cache.set(key, out);
1332
+ return out;
1333
+ }
1334
+ /**
1335
+ * Do the words of a laid out region fit in its columns? The words of the table headers are always
1336
+ * checked (as for `@compact` tables); those of the paragraphs, quotes and lists only when `all`.
1337
+ */
1338
+ function regionWordsFit(arr, all) {
1339
+ const fits = (text, room, pt) => inline(text)
1340
+ .map(r => r.text)
1341
+ .join("")
1342
+ .split(/\s+/)
1343
+ .filter(Boolean)
1344
+ .every(w => boldWordW(w, pt) <= room);
1345
+ return arr.cols.every(col => col.every(b => {
1346
+ if (b.t === "table")
1347
+ return headerFits(b, arr.colW);
1348
+ if (!all)
1349
+ return true;
1350
+ if (b.t === "para")
1351
+ return fits(b.text, arr.colW - 0.5, sizes.text * arr.k);
1352
+ if (b.t === "quote")
1353
+ return fits(b.text, arr.colW - 1.7, sizes.quote * arr.k);
1354
+ if (b.t === "list")
1355
+ return b.items.every(([lvl, txt]) => fits(txt, arr.colW - 0.9 * (lvl + 1), sizes.list[Math.min(lvl, 8)] * arr.k));
1356
+ return true;
1357
+ }));
1358
+ }
1359
+ /** The tables of some blocks, including those of their `@compact {` regions. */
1360
+ function tablesOf(blocks) {
1361
+ return blocks.flatMap(b => (b.t === "table" ? [b] : b.t === "compact" ? tablesOf(b.blocks) : []));
1362
+ }
743
1363
  /** Rendered diagrams, keyed by the arguments of `dot` (which include the theme). */
744
1364
  const graphCache = new Map();
745
1365
  const IS_WINDOWS = process.platform === "win32";
@@ -998,6 +1618,8 @@ async function encodePictures(pics) {
998
1618
  .toBuffer();
999
1619
  }));
1000
1620
  }
1621
+ /** Geometry of section slides: title at the top, bar under it, then the box of the hierarchy. */
1622
+ const SEC = { x: 2, w: 24, titleY: 0.5, titleH: 2.6, barY: 3.1, boxY: 3.7, boxBottom: 15 };
1001
1623
  const f2 = (n) => n.toFixed(2);
1002
1624
  /**
1003
1625
  * The content of one slide, once per step of its `@reveal` tables: the first step shows their
@@ -1005,16 +1627,120 @@ const f2 = (n) => n.toFixed(2);
1005
1627
  * the order of the slide, rows in reading order). Rows with nothing to reveal are skipped.
1006
1628
  */
1007
1629
  function revealSteps(content) {
1008
- const order = content.flatMap(b => b.t === "table" && b.reveal ? b.rows.filter(r => !b.reveal.rows.has(r) && r.some((c, i) => c !== "" && !b.reveal.cols.has(i))) : []);
1009
- if (!content.some(b => b.t === "table" && b.reveal))
1630
+ const revealed = tablesOf(content).filter(b => b.reveal);
1631
+ if (!revealed.length)
1010
1632
  return [content];
1633
+ const order = revealed.flatMap(b => b.rows.filter(r => !b.reveal.rows.has(r) && r.some((c, i) => c !== "" && !b.reveal.cols.has(i))));
1011
1634
  return Array.from({ length: order.length + 1 }, (_, k) => {
1012
1635
  const shown = new Set(order.slice(0, k));
1013
- return content.map(b => (b.t === "table" && b.reveal ? { ...b, shown } : b));
1636
+ return content.map(b => (b.t === "table" && b.reveal) || (b.t === "compact" && tablesOf(b.blocks).some(t => t.reveal)) ? { ...b, shown } : b);
1014
1637
  });
1015
1638
  }
1639
+ /** Timing of the animations without any `@animation` on their slide. */
1640
+ const DEFAULT_TIMING = { dur: 0.5, delay: 0, ease: "linear" };
1641
+ const secs = (s) => `${Number(s.toFixed(3))}s`;
1642
+ const EASE_ATTRS = {
1643
+ linear: "",
1644
+ "ease-in": ' smil:accelerate="1"',
1645
+ "ease-out": ' smil:decelerate="1"',
1646
+ "ease-in-out": ' smil:accelerate="0.5" smil:decelerate="0.5"',
1647
+ };
1648
+ /** Presets of Impress for the effects, so that its Animation sidebar names them. */
1649
+ const ANIM_PRESETS = {
1650
+ opacity: 'presentation:preset-class="emphasis" presentation:preset-id="ooo-emphasis-transparency"',
1651
+ scale: 'presentation:preset-class="emphasis" presentation:preset-id="ooo-emphasis-grow-and-shrink"',
1652
+ };
1653
+ /**
1654
+ * The properties of an `@anim`, with their values and timing, completed by the `@animation` of its
1655
+ * slide: without properties, the `@anim` takes those of `@animation`; a property without values
1656
+ * takes the values of the same property of `@animation`. What is given explicitly in the `@anim`
1657
+ * always wins: for each of the duration, the delay and the easing, the first one given among the
1658
+ * property in `@anim`, the `@anim`, the property in `@animation`, the `@animation`, else the default.
1659
+ */
1660
+ function animProps(anim, slide) {
1661
+ const list = anim.props ?? slide.props;
1662
+ if (!list?.length)
1663
+ throw new Error(`${anim.where}: this "@anim" has no properties, and no "@animation" of its slide gives them (e.g. "@animation (opacity=0.1:1)")`);
1664
+ return list.map(p => {
1665
+ // Inherited from `@animation` as a whole, the property is the base and the `@anim` overrides it.
1666
+ const own = anim.props ? p : {};
1667
+ const base = slide.props?.find(d => d.name === p.name);
1668
+ const from = own.from ?? base?.from;
1669
+ const to = own.to ?? base?.to;
1670
+ if (!from || !to)
1671
+ throw new Error(`${anim.where}: "${p.name}" has no values, and no "@animation" of its slide gives them (e.g. "@animation (${p.name}=0.1:1)")`);
1672
+ const pick = (k) => (own[k] ?? anim[k] ?? base?.[k] ?? slide[k] ?? DEFAULT_TIMING[k]);
1673
+ return { name: p.name, from, to, dur: pick("dur"), delay: pick("delay"), ease: pick("ease") };
1674
+ });
1675
+ }
1676
+ /**
1677
+ * Timing tree of the animations of a slide (`anim:par` of `content.xml`, checked against what
1678
+ * LibreOffice reads and writes). The shapes are first set to the start values of their properties,
1679
+ * with the animations of index 0, as soon as the slide appears. Then each click plays the
1680
+ * animations of the next integral part of the index (the gaps do not matter); in a click, the
1681
+ * indexes are chained in order, and the animations of the same index play together. `slide` is
1682
+ * the `@animation` of the slide. With `setupOnly`, only the start values are set.
1683
+ */
1684
+ function timingXml(shapes, slide, setupOnly = false) {
1685
+ if (!shapes.length)
1686
+ return "";
1687
+ const effects = shapes
1688
+ .flatMap(({ id, anim }) => animProps(anim, slide).map(({ name, from, to, dur, delay, ease }) => ({ id, index: anim.index, prop: { name, from, to }, dur, delay, ease })))
1689
+ .sort((a, b) => a.index - b.index);
1690
+ const values = (p, v) => (p.name === "scale" ? `${v[0]},${v[1]}` : `${v[0]}`);
1691
+ const target = (id, p) => `smil:targetElement="${id}" smil:attributeName="${p.name === "scale" ? "transform" : p.name}"${p.name === "scale" ? ' svg:type="scale"' : ""}`;
1692
+ const animXml = (id, p, from, to, dur, ease) => `<anim:${p.name === "scale" ? "animateTransform" : "animate"} smil:dur="${secs(dur)}" smil:fill="hold"${EASE_ATTRS[ease]} ` +
1693
+ `${target(id, p)} smil:from="${values(p, from)}" smil:to="${values(p, to)}"/>`;
1694
+ // A transform cannot be `anim:set`: a scale is set by an instant transformation instead.
1695
+ const setXml = (id, p) => p.name === "opacity"
1696
+ ? `<anim:set smil:begin="0s" smil:dur="0.001s" smil:fill="hold" ${target(id, p)} smil:to="${values(p, p.from)}"/>`
1697
+ : animXml(id, p, p.from, p.from, 0.001, "linear");
1698
+ const effectPar = (node, begin, preset, inner) => `<anim:par smil:begin="${secs(begin)}" smil:fill="hold" presentation:node-type="${node}" ${preset}>${inner}</anim:par>`;
1699
+ // Start values: those of the first animation of each property of each shape, set instantly.
1700
+ const seen = new Set();
1701
+ const setup = new Map();
1702
+ for (const e of effects) {
1703
+ const key = `${e.id}/${e.prop.name}`;
1704
+ if (seen.has(key))
1705
+ continue;
1706
+ seen.add(key);
1707
+ const list = setup.get(e.prop.name) ?? [];
1708
+ list.push(setXml(e.id, e.prop));
1709
+ setup.set(e.prop.name, list);
1710
+ }
1711
+ const setupXml = [...setup].map(([name, xs]) => effectPar("with-previous", 0, ANIM_PRESETS[name], xs.join(""))).join("");
1712
+ /** The effects of a click: one block per index, each one starting when the previous one ends. */
1713
+ const clickXml = (list, click) => {
1714
+ let offset = 0;
1715
+ const out = [];
1716
+ const indexes = [...new Set(list.map(e => e.index))];
1717
+ indexes.forEach((index, n) => {
1718
+ const group = list.filter(e => e.index === index);
1719
+ const pars = group.map((e, k) => {
1720
+ const node = k > 0 ? "with-previous" : n > 0 ? "after-previous" : click ? "on-click" : "with-previous";
1721
+ return effectPar(node, e.delay, ANIM_PRESETS[e.prop.name], animXml(e.id, e.prop, e.prop.from, e.prop.to, e.dur, e.ease));
1722
+ });
1723
+ out.push(`<anim:par smil:begin="${secs(offset)}">${pars.join("")}</anim:par>`);
1724
+ offset += Math.max(...group.map(e => e.delay + e.dur));
1725
+ });
1726
+ return out.join("");
1727
+ };
1728
+ const floors = setupOnly ? [] : [...new Set(effects.map(e => Math.floor(e.index)))];
1729
+ // Played as soon as the slide appears: the start values, then the animations of index 0.
1730
+ const auto = floors[0] === 0 ? clickXml(effects.filter(e => Math.floor(e.index) === 0), false) : "";
1731
+ const clicks = floors
1732
+ .filter(f => f > 0)
1733
+ .map(f => `<anim:par smil:begin="next">${clickXml(effects.filter(e => Math.floor(e.index) === f), true)}</anim:par>`);
1734
+ return (`<anim:par presentation:node-type="timing-root"><anim:seq presentation:node-type="main-sequence">` +
1735
+ `<anim:par smil:begin="0s"><anim:par smil:begin="0s">${setupXml}</anim:par>${auto}</anim:par>` +
1736
+ `${clicks.join("")}</anim:seq></anim:par>`);
1737
+ }
1016
1738
  class Builder {
1017
1739
  base;
1740
+ /** Number of animated shapes so far, for their `draw:id`. */
1741
+ animCount = 0;
1742
+ /** Animated shapes built for the next slide. */
1743
+ animShapes = [];
1018
1744
  pictures = new Map();
1019
1745
  pages = [];
1020
1746
  colStyles = new Map();
@@ -1022,6 +1748,10 @@ class Builder {
1022
1748
  paraStyles = new Map();
1023
1749
  /** Hints waiting to be attached to the next slide title. */
1024
1750
  pendingHints = [];
1751
+ /** Heading path of the section of the last slide. */
1752
+ lastPath = [];
1753
+ /** Section of the slides being built. */
1754
+ current = null;
1025
1755
  constructor(base) {
1026
1756
  this.base = base;
1027
1757
  mdDir = base;
@@ -1052,12 +1782,22 @@ class Builder {
1052
1782
  * Automatic paragraph style setting the font size (in points) of a `@compact` table,
1053
1783
  * and the left margin (in cm) leaving room for the images of a cell.
1054
1784
  */
1055
- paraStyle(pt, indent = 0) {
1056
- const key = indent ? `${f2(pt)}/${f2(indent)}` : f2(pt);
1785
+ paraStyle(pt, indent = 0, margins) {
1786
+ const key = [f2(pt), indent ? f2(indent) : "", margins ? margins.map(f2).join(",") : ""].join("/");
1057
1787
  if (!this.paraStyles.has(key))
1058
1788
  this.paraStyles.set(key, `Pt${this.paraStyles.size + 1}`);
1059
1789
  return this.paraStyles.get(key);
1060
1790
  }
1791
+ /**
1792
+ * Style attribute of a paragraph of `pt` points shrunk by a `@compact {` region (nothing when
1793
+ * `k` is 1). The spacing above and below the paragraphs of the style `name` shrinks too.
1794
+ */
1795
+ scaledPara(pt, k = 1, name) {
1796
+ if (k === 1)
1797
+ return "";
1798
+ const margins = name ? [styleCm(name, "fo:margin-top") * k, styleCm(name, "fo:margin-bottom") * k] : undefined;
1799
+ return ` text:style-name="${this.paraStyle(pt * k, 0, margins)}"`;
1800
+ }
1061
1801
  rowStyle(h) {
1062
1802
  const key = f2(h);
1063
1803
  if (!this.rowStyles.has(key))
@@ -1065,6 +1805,28 @@ class Builder {
1065
1805
  return this.rowStyles.get(key);
1066
1806
  }
1067
1807
  // -- shapes
1808
+ /**
1809
+ * Give each top-level shape of `xml` (a table can come with the images of its cells) an id, and
1810
+ * keep them for the animations of the next slide, if they are animated. The text and the
1811
+ * attributes of the shapes are escaped, so every `<` and `>` belongs to a tag.
1812
+ */
1813
+ animated(xml, anim) {
1814
+ if (!anim)
1815
+ return xml;
1816
+ let depth = 0;
1817
+ return xml.replace(/<(\/?)([\w:-]+)([^>]*?)(\/?)>/g, (tag, close, name, rest, empty) => {
1818
+ if (close)
1819
+ depth--;
1820
+ else if (depth++ === 0) {
1821
+ const id = `anim${++this.animCount}`;
1822
+ this.animShapes.push({ id, anim });
1823
+ tag = `<${name} draw:id="${id}" xml:id="${id}"${rest}${empty}>`;
1824
+ }
1825
+ if (empty)
1826
+ depth--;
1827
+ return tag;
1828
+ });
1829
+ }
1068
1830
  static geom(x, y, w, h) {
1069
1831
  return `svg:x="${f2(x)}cm" svg:y="${f2(y)}cm" svg:width="${f2(w)}cm" svg:height="${f2(h)}cm"`;
1070
1832
  }
@@ -1087,9 +1849,9 @@ class Builder {
1087
1849
  * style. Lists with numbered items name the list styles `<frameStyle>-numbers` and
1088
1850
  * `<frameStyle>-bullets` (see `listStylesXml()`) on every nested list.
1089
1851
  */
1090
- listXml(items, frameStyle) {
1852
+ listXml(items, frameStyle, k = 1, pt, named = false) {
1091
1853
  const holder = listStyleHolder(frameStyle);
1092
- const styled = holder !== null && items.some(it => it[2] !== undefined);
1854
+ const styled = holder !== null && (named || items.some(it => it[2] !== undefined));
1093
1855
  const out = [];
1094
1856
  // For each open list: is it numbered?
1095
1857
  const open = [];
@@ -1113,7 +1875,7 @@ class Builder {
1113
1875
  out.push(`<text:list${name}><text:list-item${start}>`);
1114
1876
  open.push(ordered);
1115
1877
  }
1116
- out.push(`<text:p>${runsXml(txt)}</text:p>`);
1878
+ out.push(`<text:p${this.scaledPara(pt ?? sizes.list[Math.min(lvl, 8)], k, outlineStyle(frameStyle, lvl))}>${runsXml(txt)}</text:p>`);
1117
1879
  }
1118
1880
  while (open.length)
1119
1881
  close();
@@ -1181,36 +1943,107 @@ class Builder {
1181
1943
  (alt ? `<svg:title>${esc(alt)}</svg:title>` : "") +
1182
1944
  `</draw:frame>`);
1183
1945
  }
1184
- promptXml(lines, x, y, w, h, style = "Prompt") {
1185
- const paras = lines.map(l => `<text:p>${xmlText(l)}</text:p>`).join("");
1946
+ /** Horizontal line across the box, in its middle. */
1947
+ hrXml(x, y, w, h) {
1948
+ const ly = f2(y + h / 2);
1949
+ 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"/>`;
1950
+ }
1951
+ promptXml(lines, x, y, w, h, style = "Prompt", k = 1) {
1952
+ const ps = this.scaledPara(style === "Code" ? sizes.code : sizes.prompt, k);
1953
+ const paras = lines.map(l => `<text:p${ps}>${xmlText(l)}</text:p>`).join("");
1186
1954
  return (`<draw:custom-shape draw:style-name="${style}" ${Builder.geom(x, y, w, h)}>${paras}` +
1187
1955
  `<draw:enhanced-geometry svg:viewBox="0 0 21600 21600" draw:type="round-rectangle" draw:modifiers="1800"/>` +
1188
1956
  `</draw:custom-shape>`);
1189
1957
  }
1958
+ /** The shapes of a block, with an id if it is animated (each part of a table on its own). */
1190
1959
  blockXml(b, x, y, w, h) {
1960
+ if (b.t !== "table")
1961
+ return this.animated(this.shapeXml(b, x, y, w, h), animOf(b));
1962
+ const pw = tablePartW(b, w);
1963
+ const cols = tableBlockCols(b, w);
1964
+ return tableParts(b)
1965
+ .map((rows, i) => this.animated(this.tableXml(b.header, rows, x + i * (pw + TABLE_GAP), y, pw, b.pt ?? sizes.table, false, cols, (r, c) => isHidden(b, r, c)), b.anim))
1966
+ .join("");
1967
+ }
1968
+ shapeXml(b, x, y, w, h) {
1191
1969
  switch (b.t) {
1192
1970
  case "para":
1193
- return this.frame("Texte", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
1971
+ return this.frame("Texte", x, y, w, h, `<text:p${this.scaledPara(sizes.text, b.k, "Texte")}>${runsXml(b.text)}</text:p>`);
1194
1972
  case "list":
1195
- return this.frame("Master-outline1", x, y, w, h, this.listXml(b.items, "Master-outline1"), "outline");
1973
+ return this.frame("Master-outline1", x, y, w, h, this.listXml(b.items, "Master-outline1", b.k), "outline");
1196
1974
  case "quote":
1197
- return this.frame("Citation", x, y, w, h, `<text:p>${runsXml(b.text)}</text:p>`);
1975
+ return this.frame("Citation", x, y, w, h, `<text:p${this.scaledPara(sizes.quote, b.k, "Citation")}>${runsXml(b.text)}</text:p>`);
1198
1976
  case "prompt":
1199
1977
  case "code": {
1200
- const [pw] = promptSize(b.lines, w);
1201
- return this.promptXml(b.lines, x + w - pw, y, pw, h, b.t === "prompt" ? "Prompt" : "Code");
1202
- }
1203
- case "table": {
1204
- const pw = tablePartW(b, w);
1205
- const cols = tableBlockCols(b, w);
1206
- return tableParts(b)
1207
- .map((rows, i) => this.tableXml(b.header, rows, x + i * (pw + TABLE_GAP), y, pw, b.pt ?? sizes.table, false, cols, (r, c) => isHidden(b, r, c)))
1208
- .join("");
1978
+ const [pw] = promptSize(b.lines, w, b.k);
1979
+ return this.promptXml(b.lines, x + w - pw, y, pw, h, b.t === "prompt" ? "Prompt" : "Code", b.k);
1209
1980
  }
1981
+ case "compact":
1982
+ return this.regionXml(b, x, y, w);
1983
+ case "box":
1984
+ return this.boxXml(b, x, y, w, h);
1985
+ case "hr":
1986
+ return this.hrXml(x, y, w, h);
1210
1987
  default:
1211
1988
  throw new Error(`Unexpected block ${b.t}`);
1212
1989
  }
1213
1990
  }
1991
+ /**
1992
+ * A `@box {` region in the box `x, y, w, h`, margins included: a rectangle with rounded corners.
1993
+ * Without nested boxes, the rectangle holds the text. Otherwise the rectangle is empty, and its
1994
+ * paragraphs and lists (in text frames) and its boxes are stacked on it, centered vertically.
1995
+ */
1996
+ boxXml(b, x, y, w, h) {
1997
+ const { padY, padX, marginY, marginX, radius } = boxGeom(b.name);
1998
+ const name = boxStyleName(b.name);
1999
+ const pt = boxPt(b.name);
2000
+ const k = b.k ?? 1;
2001
+ // Lists name their list styles: shapes do not take the bullets of their style.
2002
+ const textXml = (blocks) => blocks
2003
+ .map(x => (x.t === "list" ? this.listXml(x.items, name, b.k, pt, true) : x.t === "para" ? `<text:p${this.scaledPara(pt, b.k, name)}>${runsXml(x.text)}</text:p>` : ""))
2004
+ .join("");
2005
+ const [rx, ry, rw, rh] = [x + marginX, y + marginY, w - 2 * marginX, h - 2 * marginY];
2006
+ const rect = (inner) => `<draw:rect draw:style-name="${esc(name)}" draw:corner-radius="${f2(radius)}cm" ${Builder.geom(rx, ry, rw, rh)}>${inner}</draw:rect>`;
2007
+ const items = boxItems(b);
2008
+ if (items.every(it => it.kind === "text"))
2009
+ return rect(textXml(b.blocks));
2010
+ const [cx, cw] = [rx + padX, rw - 2 * padX];
2011
+ let cy = ry + padY + Math.max(0, (rh - 2 * padY - boxContentH(b, cw)) / 2);
2012
+ const out = [rect("")];
2013
+ for (const it of items) {
2014
+ if (it.kind === "text") {
2015
+ const th = boxTextH(b.name, it.blocks, cw, k);
2016
+ out.push(this.frame(boxTextStyleName(b.name), cx, cy, cw, th, textXml(it.blocks)));
2017
+ cy += th;
2018
+ }
2019
+ else {
2020
+ const bh = boxH(it.box, cw);
2021
+ out.push(this.boxXml(it.box, cx, cy, cw, bh));
2022
+ cy += bh + BOX_GAP * k;
2023
+ }
2024
+ }
2025
+ return out.join("");
2026
+ }
2027
+ /** The columns of a `@compact {` region, top-aligned. */
2028
+ regionXml(b, x, y, w) {
2029
+ const arr = arrange(b, w);
2030
+ const out = [];
2031
+ arr.cols.forEach((col, c) => {
2032
+ const cx = x + c * (arr.colW + arr.gap);
2033
+ let cy = y;
2034
+ for (const blk of col) {
2035
+ const bh = regionBlockH(blk, arr.colW);
2036
+ if (blk.t === "image") {
2037
+ const [iw] = regionImageSize(blk, arr.colW);
2038
+ out.push(this.animated(this.imageXml(blk.src, cx + (arr.colW - iw) / 2, cy, iw, bh, blk.alt), blk.anim));
2039
+ }
2040
+ else
2041
+ out.push(this.blockXml(blk.t === "table" && b.shown ? { ...blk, shown: b.shown } : blk, cx, cy, arr.colW, bh));
2042
+ cy += bh + GAP * arr.k;
2043
+ }
2044
+ });
2045
+ return out.join("");
2046
+ }
1214
2047
  // -- slide-level layout
1215
2048
  /** Return the required height and the shapes for the content blocks of one slide. */
1216
2049
  layout(blocks) {
@@ -1231,10 +2064,11 @@ class Builder {
1231
2064
  if (!imgs.length)
1232
2065
  return [stack(texts, X0, W), shapes];
1233
2066
  const src = imgs[0].src;
2067
+ const anim = animOf(imgs[0]);
1234
2068
  const [iw, ih] = imageSize(resolve(this.base, src));
1235
2069
  if (!texts.length) {
1236
2070
  const [w, h] = fit(iw, ih, W, H);
1237
- shapes.push(this.imageXml(src, X0 + (W - w) / 2, Y0 + (H - h) / 2, w, h));
2071
+ shapes.push(this.animated(this.imageXml(src, X0 + (W - w) / 2, Y0 + (H - h) / 2, w, h), anim));
1238
2072
  return [0, shapes];
1239
2073
  }
1240
2074
  if (iw / ih >= 1.8 || (iw / ih >= 1.2 && sumH(W) < 2.5)) {
@@ -1242,7 +2076,7 @@ class Builder {
1242
2076
  const th = stack(texts, X0, W, false);
1243
2077
  const avail = Math.max(H - th - GAP, 4.5);
1244
2078
  const [w, h] = fit(iw, ih, W, avail);
1245
- shapes.push(this.imageXml(src, X0 + (W - w) / 2, Y0 + th + GAP + (avail - h) / 2, w, h));
2079
+ shapes.push(this.animated(this.imageXml(src, X0 + (W - w) / 2, Y0 + th + GAP + (avail - h) / 2, w, h), anim));
1246
2080
  return [th + GAP + 4.5, shapes];
1247
2081
  }
1248
2082
  // Give the image more room when the text is short.
@@ -1250,7 +2084,7 @@ class Builder {
1250
2084
  const th = stack(texts, X0, tw);
1251
2085
  const bw = W - tw - 0.8;
1252
2086
  const [w, h] = fit(iw, ih, bw, H);
1253
- shapes.push(this.imageXml(src, X0 + tw + 0.8 + (bw - w) / 2, Y0 + (H - h) / 2, w, h));
2087
+ shapes.push(this.animated(this.imageXml(src, X0 + tw + 0.8 + (bw - w) / 2, Y0 + (H - h) / 2, w, h), anim));
1254
2088
  return [th, shapes];
1255
2089
  }
1256
2090
  /** Split blocks into slides: list of [content blocks, notes]. */
@@ -1261,6 +2095,10 @@ class Builder {
1261
2095
  slides[slides.length - 1][1].push(b.text);
1262
2096
  continue;
1263
2097
  }
2098
+ if (b.t === "compact") {
2099
+ this.compactRegion(b, slides);
2100
+ continue;
2101
+ }
1264
2102
  if (b.t === "table" && (!this.fits([b]) || ((b.compact || b.reveal) && !headerFits(b)))) {
1265
2103
  // A revealed table must stay on one slide: on two side-by-side tables, or else shrunk.
1266
2104
  if (b.reveal)
@@ -1284,10 +2122,13 @@ class Builder {
1284
2122
  }
1285
2123
  /** Do these blocks fit on one slide? */
1286
2124
  fits(blocks) {
1287
- // `layout()` registers the automatic styles of the shapes it builds: forget those of this trial.
2125
+ // `layout()` registers the automatic styles and the animated shapes it builds: forget those of this trial.
1288
2126
  const saved = [new Map(this.colStyles), new Map(this.rowStyles), new Map(this.paraStyles)];
2127
+ const [animCount, animShapes] = [this.animCount, this.animShapes.length];
1289
2128
  const ok = this.layout(blocks)[0] <= H;
1290
2129
  [this.colStyles, this.rowStyles, this.paraStyles] = saved;
2130
+ this.animCount = animCount;
2131
+ this.animShapes.length = animShapes;
1291
2132
  return ok;
1292
2133
  }
1293
2134
  /**
@@ -1335,6 +2176,56 @@ class Builder {
1335
2176
  const carry = cur.length > 1 && intro.length && this.fits([...intro, small]) ? [cur.pop()] : [];
1336
2177
  slides.push([[...carry, small], []]);
1337
2178
  }
2179
+ /**
2180
+ * A `@compact {` region: at full size if it fits on a slide with the paragraph introducing it,
2181
+ * otherwise shrunk (by steps of half a point of body text) until its balanced columns fit.
2182
+ * `@compact * {` takes the number of columns giving the biggest text (the fewest on a tie),
2183
+ * among those where no word is too long for its column. Like a `@compact` table, it stays on
2184
+ * the current slide if it fits there, otherwise it starts a new one with its introduction.
2185
+ */
2186
+ compactRegion(b, slides) {
2187
+ const cur = slides[slides.length - 1][0];
2188
+ const last = cur[cur.length - 1];
2189
+ const intro = last?.t === "para" ? [last] : [];
2190
+ const pieces = compactPieces(b.blocks).length;
2191
+ const auto = b.columns === "auto";
2192
+ const counts = auto
2193
+ ? Array.from({ length: Math.max(1, Math.min(pieces, MAX_AUTO_COLUMNS)) }, (_, i) => i + 1)
2194
+ : [Math.max(1, Math.min(b.columns, pieces))];
2195
+ const scales = compactScales();
2196
+ const at = (n, k) => ({ ...b, n, k });
2197
+ const fitsAlone = (r) => this.fits([...intro, r]);
2198
+ // Biggest scale (fewest columns on a tie) passing `ok`.
2199
+ const search = (ok) => {
2200
+ let found = null;
2201
+ for (const n of counts) {
2202
+ const k = scales.find(k => (!found || k > found.k) && ok(at(n, k)));
2203
+ if (k !== undefined)
2204
+ found = at(n, k);
2205
+ if (found?.k === 1)
2206
+ break;
2207
+ }
2208
+ return found;
2209
+ };
2210
+ let region = search(r => fitsAlone(r) && regionWordsFit(arrange(r, W), auto)) ?? search(fitsAlone);
2211
+ const minPt = Math.round(sizes.text * MIN_COMPACT_SCALE * 2) / 2;
2212
+ if (!region) {
2213
+ // Too long even at the smallest size: the number of columns giving the shortest region.
2214
+ const k = scales[scales.length - 1];
2215
+ region = counts.map(n => at(n, k)).reduce((a, r) => (arrange(r, W).h < arrange(a, W).h ? r : a));
2216
+ console.warn(` ! ${bold(b.where)}: the "@compact {" region is still too long with a body text of ${minPt}pt: it overflows its slide`);
2217
+ }
2218
+ else if (!regionWordsFit(arrange(region, W), false)) {
2219
+ console.warn(` ! ${bold(b.where)}: a table of the "@compact {" region has header words too long for their column`);
2220
+ }
2221
+ if (!cur.length || this.fits([...cur, region]))
2222
+ cur.push(region);
2223
+ else {
2224
+ const carry = cur.length > 1 && intro.length && this.fits([...intro, region]) ? [cur.pop()] : [];
2225
+ slides.push([[...carry, region], []]);
2226
+ }
2227
+ slides[slides.length - 1][1].push(...b.blocks.flatMap(x => (x.t === "note" ? [x.text] : [])));
2228
+ }
1338
2229
  /**
1339
2230
  * Spread the rows of a table over two side-by-side tables, if they fit on one slide: on the
1340
2231
  * current slide if there is room, otherwise on a new one. Return false if they do not fit.
@@ -1388,8 +2279,15 @@ class Builder {
1388
2279
  }
1389
2280
  }
1390
2281
  // -- pages
1391
- page(master, shapes, notes = []) {
1392
- this.pages.push({ master, shapes, notes });
2282
+ /**
2283
+ * A slide, with the animations of the animated shapes built since the previous one. `animation` is
2284
+ * the `@animation` of the slide (defaults of its animations); with `setupOnly`, the animated shapes
2285
+ * only get their start values.
2286
+ */
2287
+ page(master, shapes, notes = [], animation = this.current?.animation ?? {}, setupOnly = false) {
2288
+ const page = { master, shapes, notes, sec: this.current, timing: timingXml(this.animShapes.splice(0), animation, setupOnly) };
2289
+ this.pages.push(page);
2290
+ return page;
1393
2291
  }
1394
2292
  titleShapes(title, crumbs) {
1395
2293
  const out = [];
@@ -1399,13 +2297,74 @@ class Builder {
1399
2297
  return out;
1400
2298
  }
1401
2299
  sectionPage(sec) {
1402
- // The big title is always the top-level (`#`) heading; deeper headings go in the subtitle.
1403
- const [title, ...rest] = sec.path();
1404
- const shapes = [this.frame("Section-title", 2, 5, 24, 3.5, `<text:p>${xmlText(title)}</text:p>`, "title", this.takeHints())];
1405
- if (rest.length)
1406
- shapes.push(this.frame("Section-subtitle", 2, 8.8, 24, 1.5, `<text:p>${xmlText(rest.join(" › "))}</text:p>`, "subtitle"));
2300
+ // The big title is always the top-level (`#`) heading; the hierarchy box comes in `finish()`.
2301
+ const [title] = sec.path();
2302
+ const shapes = [this.frame("Section-title", SEC.x, SEC.titleY, SEC.w, SEC.titleH, `<text:p>${xmlText(title)}</text:p>`, "title", this.takeHints())];
1407
2303
  const notes = sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : []));
1408
- this.page("Section", shapes, notes);
2304
+ this.page("Section", shapes, notes).toc = sec;
2305
+ this.lastPath = sec.path();
2306
+ }
2307
+ /** Adds the hierarchy boxes to the section slides, now that the slide after each one is known. */
2308
+ finish() {
2309
+ this.pages.forEach((page, i) => {
2310
+ if (page.toc)
2311
+ page.shapes.push(...this.tocShapes(page.toc, this.pages[i + 1]?.sec ?? null));
2312
+ });
2313
+ }
2314
+ /**
2315
+ * Box listing the sub-sections of the `#` heading of `sec`, indented by depth. A section is
2316
+ * expanded only if the next slide (in section `next`) is inside it. The highlighted section is
2317
+ * `sec`, or for a `#` slide, the sub-section holding the next slide.
2318
+ */
2319
+ tocShapes(sec, next) {
2320
+ let top = sec;
2321
+ while (top.parent && top.parent.level > 0)
2322
+ top = top.parent;
2323
+ const ancestors = new Set();
2324
+ for (let s = next?.parent ?? null; s; s = s.parent)
2325
+ ancestors.add(s);
2326
+ let current = sec.level > 1 ? sec : null;
2327
+ if (!current && next && next !== top) {
2328
+ current = next;
2329
+ while (current.parent && current.parent !== top)
2330
+ current = current.parent;
2331
+ }
2332
+ const pt = style.theme.sizes.subtitle;
2333
+ const lines = [];
2334
+ // Nested bulleted lists: the bullets come from the `bullets` of `Section-subtitle` (list style `Toc-list`).
2335
+ const listXml = (parent) => {
2336
+ const items = [];
2337
+ for (const child of parent.children) {
2338
+ if (child.continued || !child.title)
2339
+ continue;
2340
+ let text = xmlText(child.title);
2341
+ if (child === current)
2342
+ text = `<text:span text:style-name="T_section">${text}</text:span>`;
2343
+ lines.push(text);
2344
+ const sub = ancestors.has(child) ? listXml(child) : "";
2345
+ items.push(`<text:list-item><text:p text:style-name="Toc">${text}</text:p>${sub}</text:list-item>`);
2346
+ }
2347
+ const name = style.styles["Section-subtitle"]?.bullets ? ` text:style-name="Toc-list"` : "";
2348
+ return items.length ? `<text:list${name}>${items.join("")}</text:list>` : "";
2349
+ };
2350
+ const xml = listXml(top);
2351
+ if (!lines.length)
2352
+ return [];
2353
+ const lineH = pt * PT * 1.25;
2354
+ const h = Math.min(SEC.boxBottom - SEC.boxY, lines.length * lineH + 1.2);
2355
+ return [this.frame("Section-subtitle", SEC.x, SEC.boxY, SEC.w, h, xml, "subtitle")];
2356
+ }
2357
+ /**
2358
+ * When going back up more than one level (from `1 > 1 > 1` to `1 > 2`, or to `1 > 2 > 1`),
2359
+ * a section slide recalls where we are before the slides of `sec`.
2360
+ */
2361
+ recallSection(sec) {
2362
+ const path = sec.path();
2363
+ let common = 0;
2364
+ while (common < path.length && common < this.lastPath.length && path[common] === this.lastPath[common])
2365
+ common++;
2366
+ if (this.lastPath.length - common >= 2)
2367
+ this.sectionPage(sec);
1409
2368
  }
1410
2369
  contentPages(title, crumbs, blocks) {
1411
2370
  // Notes not attached to a slide yet: they go to the next one.
@@ -1418,10 +2377,12 @@ class Builder {
1418
2377
  continue;
1419
2378
  }
1420
2379
  const allNotes = [...pending.splice(0), ...notes];
1421
- for (const step of revealSteps(content)) {
2380
+ // With `@reveal`, the animations play on the last slide, once every row is revealed.
2381
+ const steps = revealSteps(content);
2382
+ steps.forEach((step, i) => {
1422
2383
  const [, shapes] = this.layout(step);
1423
- this.page("Master", [...this.titleShapes(title, crumbs), ...shapes], [...allNotes]);
1424
- }
2384
+ this.page("Master", [...this.titleShapes(title, crumbs), ...shapes], [...allNotes], undefined, i < steps.length - 1);
2385
+ });
1425
2386
  }
1426
2387
  run = [];
1427
2388
  };
@@ -1480,11 +2441,14 @@ class Builder {
1480
2441
  cellXml(sec, x, y, w, h, textStyle, textPt) {
1481
2442
  const items = [];
1482
2443
  for (const b of sec.blocks) {
2444
+ if (b.t === "compact")
2445
+ throw new Error(`${b.where}: a "@compact {" region cannot be in a cell of an "@layout"`);
1483
2446
  if (b.t === "note" || b.t === "layout")
1484
2447
  continue;
1485
2448
  const last = items[items.length - 1];
1486
2449
  if (b.t === "para" || b.t === "list" || b.t === "quote") {
1487
- if (last?.kind === "text")
2450
+ // Blocks of different `@anim` regions cannot share a text frame.
2451
+ if (last?.kind === "text" && animOf(last.blocks[0]) === b.anim)
1488
2452
  last.blocks.push(b);
1489
2453
  else
1490
2454
  items.push({ kind: "text", blocks: [b] });
@@ -1501,6 +2465,10 @@ class Builder {
1501
2465
  return tableH(b.header, b.rows, w, sizes.tableSmall);
1502
2466
  if (b.t === "prompt" || b.t === "code")
1503
2467
  return promptSize(b.lines, w)[1];
2468
+ if (b.t === "hr")
2469
+ return HR_H;
2470
+ if (b.t === "box")
2471
+ return boxH(b, w);
1504
2472
  return 0;
1505
2473
  });
1506
2474
  const flexible = items.map(it => it.kind === "text" || (it.kind === "block" && it.block.t === "image"));
@@ -1536,22 +2504,29 @@ class Builder {
1536
2504
  const inner = it.blocks
1537
2505
  .map(b => (b.t === "list" ? this.listXml(b.items, textStyle) : b.t === "para" || b.t === "quote" ? `<text:p>${runsXml(b.text)}</text:p>` : ""))
1538
2506
  .join("");
1539
- shapes.push(this.frame(textStyle, x, cy, w, ih, inner));
2507
+ shapes.push(this.animated(this.frame(textStyle, x, cy, w, ih, inner), animOf(it.blocks[0])));
1540
2508
  }
1541
2509
  else {
1542
2510
  const b = it.block;
2511
+ const push = (xml) => shapes.push(this.animated(xml, animOf(b)));
1543
2512
  if (b.t === "table") {
1544
2513
  const header = b.header?.map(stripMd) ?? null;
1545
- shapes.push(this.tableXml(header, b.rows, x, cy, w, sizes.tableSmall, true));
2514
+ push(this.tableXml(header, b.rows, x, cy, w, sizes.tableSmall, true));
1546
2515
  }
1547
2516
  else if (b.t === "image") {
1548
2517
  const [iw, ihh] = imageSize(resolve(sec.source, b.src));
1549
2518
  const [fw, fh] = fit(iw, ihh, w, ih);
1550
- shapes.push(this.imageXml(b.src, x + (w - fw) / 2, cy + (ih - fh) / 2, fw, fh));
2519
+ push(this.imageXml(b.src, x + (w - fw) / 2, cy + (ih - fh) / 2, fw, fh));
1551
2520
  }
1552
2521
  else if (b.t === "prompt" || b.t === "code") {
1553
2522
  const [pw] = promptSize(b.lines, w);
1554
- shapes.push(this.promptXml(b.lines, x + w - pw, cy, pw, ih, b.t === "prompt" ? "Prompt" : "Code"));
2523
+ push(this.promptXml(b.lines, x + w - pw, cy, pw, ih, b.t === "prompt" ? "Prompt" : "Code"));
2524
+ }
2525
+ else if (b.t === "hr") {
2526
+ push(this.hrXml(x, cy, w, ih));
2527
+ }
2528
+ else if (b.t === "box") {
2529
+ push(this.boxXml(b, x, cy, w, ih));
1555
2530
  }
1556
2531
  }
1557
2532
  cy += heights[i] + gap;
@@ -1612,9 +2587,12 @@ class Builder {
1612
2587
  shapes.push(...this.cellXml(sec, x, y + hh, w, h - hh, textStyle, textPt));
1613
2588
  notes.push(...sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : [])));
1614
2589
  });
1615
- this.page("Master", shapes, notes);
2590
+ // One slide for the whole group: the last `@animation` of its sections wins.
2591
+ const animation = group.reduce((a, s) => (Object.keys(s.animation).length ? s.animation : a), this.current?.animation ?? {});
2592
+ this.page("Master", shapes, notes, animation);
1616
2593
  }
1617
2594
  walk(sec) {
2595
+ this.current = sec;
1618
2596
  this.pendingHints.push(...sec.hints);
1619
2597
  const crumbs = sec.path().slice(0, -1);
1620
2598
  const content = sec.blocks.filter(b => b.t !== "note");
@@ -1624,9 +2602,12 @@ class Builder {
1624
2602
  this.sectionPage(sec);
1625
2603
  if (content.length)
1626
2604
  this.contentPages(sec.title, [...crumbs, sec.title], sec.blocks);
2605
+ this.lastPath = sec.path();
1627
2606
  }
1628
2607
  else if (content.length) {
2608
+ this.recallSection(sec);
1629
2609
  this.contentPages(sec.title, crumbs, sec.blocks);
2610
+ this.lastPath = sec.path();
1630
2611
  }
1631
2612
  else if (sec.children.length && !groupedOnly) {
1632
2613
  this.sectionPage(sec);
@@ -1643,13 +2624,19 @@ class Builder {
1643
2624
  continue;
1644
2625
  }
1645
2626
  const group = children.slice(i, i + cellCount(layout));
2627
+ if (sec.level > 0)
2628
+ this.recallSection(sec);
2629
+ this.current = group[0];
1646
2630
  for (const g of group)
1647
2631
  this.pendingHints.push(...g.hints);
1648
2632
  const title = sec.level > 0 ? sec.title : group[0].title;
1649
2633
  this.layoutPage(title, sec.path().slice(0, -1), group, layout, i === 0 ? notes : []);
2634
+ this.lastPath = sec.level > 0 ? sec.path() : group[0].path();
1650
2635
  // Sub-sections of grouped sections still get their own slides.
1651
- for (const g of group)
2636
+ for (const g of group) {
2637
+ this.current = g;
1652
2638
  this.walkChildren(g);
2639
+ }
1653
2640
  i += group.length - 1;
1654
2641
  }
1655
2642
  }
@@ -1668,6 +2655,8 @@ const NS = [
1668
2655
  'xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"',
1669
2656
  'xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"',
1670
2657
  'xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0"',
2658
+ 'xmlns:anim="urn:oasis:names:tc:opendocument:xmlns:animation:1.0"',
2659
+ 'xmlns:smil="urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0"',
1671
2660
  'office:version="1.3"',
1672
2661
  ].join(" ");
1673
2662
  function attrs(props = {}, where = "") {
@@ -1684,6 +2673,23 @@ function bulletsXml(def, name) {
1684
2673
  `</text:list-level-style-bullet>`);
1685
2674
  return `<text:list-style style:name="${esc(name)}-list">${levels.join("")}</text:list-style>`;
1686
2675
  }
2676
+ /** Length in cm of a paragraph property (`"0.2cm"`) of a style or of its parents, 0 if none. */
2677
+ function styleCm(name, prop) {
2678
+ for (let n = name, depth = 0; n && depth < 20; depth++) {
2679
+ const s = style.styles[n];
2680
+ const v = s?.paragraph?.[prop];
2681
+ if (v !== undefined) {
2682
+ const m = resolveValue(String(v), `style "${n}"`).match(/^(-?[\d.]+)(cm|mm|pt)$/);
2683
+ return m ? Number(m[1]) * (m[2] === "mm" ? 0.1 : m[2] === "pt" ? PT : 1) : 0;
2684
+ }
2685
+ n = s?.parent;
2686
+ }
2687
+ return 0;
2688
+ }
2689
+ /** Style of the paragraphs of level `lvl` (0-based) in a frame of style `Master-outline1`. */
2690
+ function outlineStyle(frameStyle, lvl) {
2691
+ return frameStyle.replace(/(-outline)1$/, `$1${Math.min(lvl, 8) + 1}`);
2692
+ }
1687
2693
  /** `name` or its nearest parent style defining both `bullets` and `numbers`, if any. */
1688
2694
  function listStyleHolder(name) {
1689
2695
  for (let n = name, depth = 0; n && depth < 20; depth++) {
@@ -1783,9 +2789,9 @@ function stylesXml(b) {
1783
2789
  `<style:master-page style:name="Section" style:page-layout-name="PM1" draw:style-name="Mdp1">` +
1784
2790
  `<draw:rect draw:style-name="Section-fond" ${Builder.geom(0, 0, SLIDE_W, SLIDE_H)}/>` +
1785
2791
  backgroundXml(b, "Section") +
1786
- `<draw:rect draw:style-name="Decor" ${Builder.geom(0, 8.55, SLIDE_W, 0.12)}/>` +
1787
- placeholder("Section-title", "title", 2, 5, 24, 3.5) +
1788
- placeholder("Section-subtitle", "subtitle", 2, 8.8, 24, 1.5) +
2792
+ `<draw:rect draw:style-name="Decor" ${Builder.geom(0, SEC.barY, SLIDE_W, 0.12)}/>` +
2793
+ placeholder("Section-title", "title", SEC.x, SEC.titleY, SEC.w, SEC.titleH) +
2794
+ placeholder("Section-subtitle", "subtitle", SEC.x, SEC.boxY, SEC.w, SEC.boxBottom - SEC.boxY) +
1789
2795
  `${notes("Section")}</style:master-page>`,
1790
2796
  ];
1791
2797
  return (`<?xml version="1.0" encoding="UTF-8"?><office:document-styles ${NS}>` +
@@ -1801,16 +2807,24 @@ function contentXml(b) {
1801
2807
  for (const [key, name] of b.colStyles)
1802
2808
  auto.push(`<style:style style:name="${name}" style:family="table-column"><style:table-column-properties style:column-width="${key}cm"/></style:style>`);
1803
2809
  for (const [key, name] of b.paraStyles) {
1804
- const [pt, indent] = key.split("/");
1805
- const para = indent ? `<style:paragraph-properties fo:margin-left="${indent}cm"/>` : "";
2810
+ const [pt, indent, margins] = key.split("/");
2811
+ const [top, bottom] = margins ? margins.split(",") : [];
2812
+ const props = [indent ? `fo:margin-left="${indent}cm"` : "", margins ? `fo:margin-top="${top}cm" fo:margin-bottom="${bottom}cm"` : ""].filter(Boolean);
2813
+ const para = props.length ? `<style:paragraph-properties ${props.join(" ")}/>` : "";
1806
2814
  auto.push(`<style:style style:name="${name}" style:family="paragraph">${para}<style:text-properties fo:font-size="${pt}pt"/></style:style>`);
1807
2815
  }
2816
+ // Lines of the hierarchy boxes of section slides: left aligned (the bullets indent them).
2817
+ 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>`);
2818
+ const tocBullets = style.styles["Section-subtitle"]?.bullets;
2819
+ if (tocBullets)
2820
+ auto.push(bulletsXml(tocBullets, "Toc"));
1808
2821
  for (const [key, name] of b.rowStyles)
1809
2822
  auto.push(`<style:style style:name="${name}" style:family="table-row"><style:table-row-properties style:row-height="${key}cm"/></style:style>`);
1810
- const pages = b.pages.map(({ master, shapes, notes }, i) => {
2823
+ const pages = b.pages.map(({ master, shapes, notes, timing }, i) => {
1811
2824
  const n = i + 1;
1812
2825
  const noteXml = notes.map(t => `<text:p>${xmlText(t)}</text:p>`).join("");
1813
- return (`<draw:page draw:name="page${n}" draw:master-page-name="${master}">${shapes.join("")}` +
2826
+ // The ODF schema puts the animations between the shapes and the notes.
2827
+ return (`<draw:page draw:name="page${n}" draw:master-page-name="${master}">${shapes.join("")}${timing ?? ""}` +
1814
2828
  `<presentation:notes><draw:page-thumbnail presentation:style-name="${master}-title" presentation:class="page" draw:page-number="${n}" svg:x="1.5cm" svg:y="1.5cm" svg:width="18cm" svg:height="10.13cm"/>` +
1815
2829
  `<draw:frame presentation:style-name="${master}-notes" presentation:class="notes" svg:x="1.5cm" svg:y="12.5cm" svg:width="18cm" svg:height="15cm"><draw:text-box>${noteXml}</draw:text-box></draw:frame>` +
1816
2830
  `</presentation:notes></draw:page>`);
@@ -1912,6 +2926,7 @@ async function convert(src, config) {
1912
2926
  const root = parse(readFileSync(src, "utf8"), src);
1913
2927
  const b = new Builder(dirname(src));
1914
2928
  b.walkChildren(root);
2929
+ b.finish();
1915
2930
  const out = src.replace(/\.md$/i, ".odp");
1916
2931
  await writeOdp(b, out, basename(src, extname(src)));
1917
2932
  return { out, hints: countHints(root) };
@@ -1954,6 +2969,7 @@ const PRAGMAS = [
1954
2969
  ["@graph <file.dot>", "Insert a Graphviz diagram (path relative to the .md), rendered as a PNG image by dot."],
1955
2970
  ["@next", "Start a new slide with the same title as the current one (unless a heading follows)."],
1956
2971
  ["@compact", "Shrink the next table so that it fits on one slide, instead of splitting it."],
2972
+ ["@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.'],
1957
2973
  ["@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.'],
1958
2974
  ["```prompt ... ```", "Not a pragma: a code block shown as a chat prompt bubble."],
1959
2975
  ];