@tolokoban/impress 0.16.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/README.md CHANGED
@@ -58,9 +58,51 @@ At the start of a line in the `.md` file:
58
58
  | `@compact` | The next table of the section, if it is too long for one slide, has its text shrunk (down to 4pt) until it fits on one slide with the paragraph introducing it, instead of being split into two columns or over several slides. The words of the header are never cut: if one of them is too long for its column, the text is shrunk further, even when the table would fit at full size (a header cell of several words may still wrap between words). |
59
59
  | `@compact [N\|*] {` … `@}` | Compact everything in between on one slide, flowing through `N` columns (`@compact {`: one column). The content flows in reading order and the columns are balanced, so the tallest one is as short as possible. A list can be cut between its top-level items (a sub-item stays with its parent, numbering continues), and a table between its rows (its header is repeated at the top of each column). Paragraphs, quotes, code blocks and images are never cut. If there are fewer of these pieces than columns, fewer columns are used. The columns are separated by 1em, and an image takes the width of its column. If the region does not fit on the slide with the paragraph introducing it, everything in it (text, spacing, tables, images) is shrunk by the same factor, half a point of body text at a time, down to 10pt for a 24pt body text. Like a `@compact` table, the region stays on the current slide if it fits there, otherwise it starts a new one with its introduction. `@compact * {` tries 1, 2, 3… columns and keeps the number giving the biggest text, the fewest columns on a tie, avoiding those where a word would be too long for its column. `@note` and `@reveal` work inside a region. A heading, `@next` or `@layout` inside a region, a region inside another one, a region in a cell of an `@layout`, a region not closed by `@}` and an `@}` without a region are errors. |
60
60
  | `@reveal [C<columns>] [R<rows>]` | The rows of the next table appear one slide after the other: the first slide shows only the header, each following slide reveals one more row. The table keeps its final size and place from the first slide. `C` and `R` list the columns and the body rows (counted from 1, header excluded) that are always visible, as numbers and ranges: `@reveal C1,3 R1-4` always shows columns 1 and 3 and rows 1 to 4. Both are optional. The speaker notes are repeated on every slide of the sequence. A revealed table always stays on one slide, and its header words are never cut, as with `@compact`: if it is too long, its rows are first spread over two side-by-side tables, and if that is still too long, its text is shrunk, on one table or two side by side, whichever keeps the text bigger. A table inside an `@layout` is shown entirely. |
61
+ | `@anim [<index>] (<property>=<from>:<to>, …) [<duration> [<delay>]] [<easing>] {` … `@}` | Animate everything in between in the slideshow, on the same slide as the rest (see [Animations](#animations)). |
62
+ | `@animation [(<property>=<from>:<to>, …)] [<duration> [<delay>]] [<easing>]` | Defaults of the animations of the current slide: properties and timing (see [Animations](#animations)). |
63
+ | `@box <name> {` … `@}` | Draw the paragraphs, lists and boxes in between in a box, styled by the box `<name>` of the style file: background, text color, font, border, rounded corners, shadow, padding and margin (see [Boxes](#boxes)). Boxes can be nested: each `@}` closes the innermost open box. The box takes the width of the content (or of its column, in a `@compact {` region or an `@layout` cell) and the height of its content. It can be inside a `@compact {` or an `@anim {` region (it is animated as a whole, with its nested boxes), but cannot hold a `@compact {` or `@anim {` region, a heading, an image, a table, a quote or a code block. An unknown box name, a box not closed by `@}` and these blocks inside a box are errors. |
61
64
 
62
65
  When some files contain `@hint`, the end of the output gives a ready-to-paste prompt asking an AI agent to apply them to the `.odp`.
63
66
 
67
+ ### Animations
68
+
69
+ `@anim … {` … `@}` animates the blocks in between with real Impress animations, played by the slideshow, all on one slide:
70
+
71
+ ```md
72
+ @animation (300ms)
73
+
74
+ @anim 2 (opacity=0.1:1) {
75
+
76
+ - Foo
77
+ - Bar
78
+
79
+ @}
80
+
81
+ Hello world!
82
+
83
+ @anim 1 (opacity=0.1:1) {
84
+
85
+ ![Alt text](img/toto.png)
86
+
87
+ @}
88
+ ```
89
+
90
+ When the slide appears, the list and the image have an opacity of 0.1. The first click fades the image in (index 1) in 300ms, the second one fades the list in (index 2), and the next click goes to the next slide.
91
+
92
+ - **Properties**: `opacity=<from>:<to>` (from 0 to 1) and `scale=<from>:<to>` (`scale=0.5:1`, or `scale=0.5,1:1,1` for different horizontal and vertical scales, around the center of the shape). Several properties are separated by commas: `(opacity=0.1:1, scale=0.5:1)`. The shapes start with the `from` values as soon as the slide appears.
93
+ - **Index**: the integral part of the index is the number of clicks that plays the animation. The gaps do not matter, only the order: indexes 1 and 5 take two clicks. Index 0 (or no index) plays as soon as the slide appears, without a click. In a click, the decimals chain the animations: with indexes 1, 1.2 and 1.5, the click plays 1, then 1.2 once 1 has ended, then 1.5. Animations with the same index play together.
94
+ - **Timing**: as in the CSS `transition` shorthand, the first time (`300ms`, `0.3s`) is the duration and the second one is the delay before the start, and an easing (`linear`, `ease-in`, `ease-out`, `ease-in-out`) can come anywhere: `@anim 1 (opacity=0.1:1) 500ms 200ms ease-out {`. A property can have its own timing: `(opacity=0.1:1 300ms, scale=0.5:1 600ms 100ms)`. The next index of a click starts when the longest animation of the previous one ends, delay included.
95
+ - **`@animation`** gives the defaults of the `@anim` regions of the slide it is on (its section, including the slides it overflows onto), with the same syntax as `@anim` without the index: `@animation (opacity=0.2:0.8 500ms) 300ms ease-out`. The last one of the slide wins, wherever it is. `@animation (300ms)` is a short form for a timing alone. The `@anim` regions inherit what they do not give themselves:
96
+ - `@anim {` or `@anim 2 300ms {` (no parentheses) takes all the properties of `@animation`, with their values and timing.
97
+ - `@anim (opacity 900ms) {` (a property without values) takes the values of the same property of `@animation`.
98
+ - `@anim (scale=0.5:1) {` has its own list of properties: the other properties of `@animation` are not animated.
99
+ - For each of the duration, the delay and the easing, the first one given wins: on the property in `@anim`, on the `@anim`, on the property in `@animation`, on the `@animation`. Without any, animations last 500ms, with no delay and a linear easing. An `@anim` without properties, or a property without values, that `@animation` does not complete is an error.
100
+ - Each block in a region (paragraph, list, table, image, code…) is a shape of its own, and all of them animate together. A table carries the images of its cells along.
101
+ - A region can be inside a `@compact {` region (a list cut over several columns animates as one), but a `@compact {` region cannot be inside an `@anim {` region. Regions cannot be nested. A heading, `@next` or `@layout` inside a region, a region not closed by `@}`, an unknown property and a value out of range are errors.
102
+ - In an `@layout`, the paragraphs and lists of a cell share a text frame, except across the border of a region.
103
+ - With `@reveal`, the animations play on the last slide of the sequence, once every row is revealed; the slides before it show the `from` values.
104
+ - The animations only exist in the slideshow: the edit view, the printouts and a PDF export show every shape in its static state, fully visible. They can be tweaked afterwards in the Animation sidebar of Impress (they show up as "Transparency" and "Grow and Shrink" effects).
105
+
64
106
  ## Styles
65
107
 
66
108
  Every element of the slides uses a named style, so it can also be changed afterwards in LibreOffice (Styles sidebar: _Drawing Styles_ and _Presentation Styles_).
@@ -79,16 +121,17 @@ The first conversion of `foo.md` writes `foo.style.json` with the complete defau
79
121
  { "theme": { "colors": { "primary": "#800020" } } }
80
122
  ```
81
123
 
82
- The file has six top-level sections:
124
+ The file has seven top-level sections:
83
125
 
84
126
  | Key | Content |
85
127
  | --- | --- |
86
128
  | `theme` | Colors, fonts, font sizes, slide geometry and diagram options. |
87
129
  | `styles` | Every named style, with ODF properties. |
88
130
  | `tableTemplates` | Which cell styles a table uses for its header, body and banded rows. |
89
- | `spanStyles` | Inline formatting: bold, italic, code. |
131
+ | `spanStyles` | Inline formatting: bold, italic, code, strikethrough (`T_s`, for `~~text~~`). |
90
132
  | `markers` | Line ends (arrows) used by diagram edges. |
91
133
  | `dashes` | Dash patterns used by diagram edges and shapes. |
134
+ | `boxes` | The boxes of `@box <name> {`. |
92
135
 
93
136
  ### Theme
94
137
 
@@ -427,6 +470,52 @@ Like everything else, span styles are merged with the defaults: here `T_code` ke
427
470
 
428
471
  The **first** entry of `dashes` (`Tirets` by default) is used for `@graph` nodes and edges with `style=dashed` or `style=dotted`.
429
472
 
473
+ ### Boxes
474
+
475
+ `boxes` defines the boxes of `@box <name> { … @}`. Boxes can be nested, each `@}` closing the innermost open box:
476
+
477
+ ```md
478
+ @box prompt-assistant {
479
+ Voici la question posée à l'assistant :
480
+
481
+ @box terminal {
482
+ $ claude "Y a-t-il une jurisprudence ?"
483
+ @}
484
+
485
+ Et sa réponse : il y a bien une jurisprudence du … qui dit …
486
+ @}
487
+ ```
488
+
489
+ ```json
490
+ "boxes": {
491
+ "prompt-assistant": {
492
+ "background": "#1F3A5F",
493
+ "border": "0.05cm dashed {colors.accent}",
494
+ "radius": "0.5cm",
495
+ "shadow": "0.15cm 0.15cm 0.2cm #000000 40%",
496
+ "padding": "0.4cm 0.6cm",
497
+ "margin": "0cm",
498
+ "font": "sans",
499
+ "size": "{sizes.text}pt"
500
+ }
501
+ }
502
+ ```
503
+
504
+ | Key | Value |
505
+ | --- | --- |
506
+ | `background` | Fill color, `#RRGGBB` or `#RGB` (required). |
507
+ | `color` | Text color, also used for the bullets and numbers of the lists. Missing or `""`: black or white, whichever is more readable on the background. |
508
+ | `border` | `none`, or as in CSS `<width> <solid\|dashed> <color>`, in any order. A dashed border uses the first entry of `dashes`. |
509
+ | `radius` | Radius of the corners, e.g. `0.3cm` (`0cm` for square corners). |
510
+ | `shadow` | `none`, or `<x> <y> [<blur>] <color> [<opacity>]`, e.g. `0.1cm 0.1cm 0.3cm #000000 30%`. |
511
+ | `padding` | Room between the border and the content: `<all>` or `<vertical> <horizontal>` (default `0.4cm 0.6cm`). |
512
+ | `margin` | Room around the box, outside its border: `<all>` or `<vertical> <horizontal>` (default `0cm`). A horizontal margin makes the box narrower than its column; a nested box is also separated by 0.2cm from what follows it. |
513
+ | `font` | Font of the text: `sans` (default, `theme.fonts.sans`), `mono` (`theme.fonts.mono`, e.g. for a terminal or some code) or the name of any installed font family, e.g. `Liberation Serif`. |
514
+ | `size` | Font size of the text (default `{sizes.text}pt`), e.g. `{sizes.code}pt` or `18pt`. |
515
+ | `graphic`, `paragraph`, `text` | Optional ODF properties, merged over those built from the values above, e.g. `"text": { "fo:font-style": "italic", "fo:font-weight": "bold" }`. |
516
+
517
+ Lengths are in `cm`, `mm`, `pt` or `in`, and every value can use [placeholders](#placeholders). Each box `<name>` becomes the named drawing style `Box-<name>` (content vertically centered, text shrunk if it does not fit), so it can also be changed in LibreOffice afterwards; a style `Box-<name>` in `styles` is merged over it. A box without nested boxes is one shape holding its text. A box holding other boxes is an empty shape, with its nested boxes and its text frames (style `Box-<name>-texte`: the text of `Box-<name>` without fill, border, shadow or padding) drawn over it. Three boxes come by default: `info` (light, with an automatic text color), `warning` (orange with white text) and `terminal` (dark, monospace text of `{sizes.code}pt`, to put in another box).
518
+
430
519
  ### Recipes
431
520
 
432
521
  Bigger text everywhere:
package/dist/impress.js CHANGED
@@ -29,6 +29,14 @@
29
29
  * default, "*" for the number giving the biggest text), shrunk if needed
30
30
  * @reveal C1,3 R1-4 the rows of the next table appear one slide after the other; the
31
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
32
40
  * ```prompt ... ``` chat prompt bubble
33
41
  */
34
42
  import { existsSync, readFileSync, writeFileSync, statSync } from "node:fs";
@@ -62,6 +70,8 @@ let GAP = 0;
62
70
  let CENTER = false;
63
71
  function useStyle(config) {
64
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) } };
65
75
  sizes = config.theme.sizes;
66
76
  SLIDE_W = config.theme.slide.width;
67
77
  SLIDE_H = config.theme.slide.height;
@@ -112,6 +122,225 @@ function resolveValue(value, where) {
112
122
  return String(v);
113
123
  });
114
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"];
115
344
  /** Is this cell hidden until its row is revealed? */
116
345
  function isHidden(b, row, col) {
117
346
  return !!b.reveal && !!b.shown && !b.shown.has(row) && !b.reveal.rows.has(row) && !b.reveal.cols.has(col);
@@ -167,6 +396,8 @@ class Section {
167
396
  layout = null;
168
397
  /** Created by `@next`: continues the previous section on a new slide. */
169
398
  continued = false;
399
+ /** Set by `@animation`: defaults of the animations of its slides (properties and timing). */
400
+ animation = {};
170
401
  /** Folder of the markdown file, for relative image paths. */
171
402
  source;
172
403
  constructor(level, title, parent = null, source = "") {
@@ -187,6 +418,7 @@ function stripMd(s) {
187
418
  .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
188
419
  .replaceAll("**", "")
189
420
  .replaceAll("__", "")
421
+ .replaceAll("~~", "")
190
422
  .replace(/(?<![\p{L}\p{N}_])\*(.+?)\*(?![\p{L}\p{N}_])/gu, "$1")
191
423
  .trim();
192
424
  }
@@ -198,6 +430,85 @@ const HEAD_RE = /^(#{1,6})\s+(.*)$/;
198
430
  const HR_RE = /^-{3,}$/;
199
431
  /** `@compact {`, `@compact 3 {` or `@compact * {`. */
200
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
+ }
201
512
  function parse(md, file) {
202
513
  const root = new Section(0, "", null, dirname(file));
203
514
  let cur = root;
@@ -206,6 +517,16 @@ function parse(md, file) {
206
517
  let list = null;
207
518
  // Open `@compact {` region: its blocks go into it until `@}`.
208
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 = [];
209
530
  let layout = null;
210
531
  // `@layout` followed by content instead of a heading: the next blocks fill its cells.
211
532
  let grouped = null;
@@ -224,6 +545,19 @@ function parse(md, file) {
224
545
  reveal = null;
225
546
  };
226
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
+ }
227
561
  if (region)
228
562
  return void region.blocks.push(b);
229
563
  if (!grouped)
@@ -264,9 +598,12 @@ function parse(md, file) {
264
598
  const line = lines[i];
265
599
  const s = line.trim();
266
600
  let m;
267
- if (region && (HEAD_RE.test(line) || s === "@next" || s.startsWith("@layout"))) {
601
+ lineNo = i + 1;
602
+ const inner = box ?? animRegion ?? region;
603
+ if (inner && (HEAD_RE.test(line) || s === "@next" || s.startsWith("@layout"))) {
268
604
  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 "@}")`);
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 "@}")`);
270
607
  }
271
608
  if ((m = line.match(HEAD_RE))) {
272
609
  flush();
@@ -313,8 +650,12 @@ function parse(md, file) {
313
650
  }
314
651
  else if ((m = s.match(COMPACT_RE))) {
315
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`);
316
655
  if (region)
317
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`);
318
659
  flush();
319
660
  dropCompact();
320
661
  dropReveal();
@@ -324,16 +665,74 @@ function parse(md, file) {
324
665
  const b = { t: "compact", columns, blocks: [], where };
325
666
  push(b);
326
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}"`);
327
712
  }
328
713
  else if (s === "@}") {
329
- if (!region)
330
- throw new Error(`${file}:${i + 1}: "@}" without an open "@compact {" region`);
714
+ const kind = open.pop();
715
+ if (!kind)
716
+ throw new Error(`${file}:${i + 1}: "@}" without an open "@compact {", "@anim {" or "@box {" region`);
331
717
  flush();
332
718
  dropCompact();
333
719
  dropReveal();
334
- if (!region.blocks.some(b => b.t !== "note"))
335
- console.warn(` ! ${bold(region.where)}: empty "@compact {" region`);
336
- region = null;
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
+ }
337
736
  }
338
737
  else if (s === "@compact") {
339
738
  flush();
@@ -453,6 +852,10 @@ function parse(md, file) {
453
852
  flush();
454
853
  dropCompact();
455
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 "@}"`);
456
859
  if (region)
457
860
  throw new Error(`${region.where}: "@compact {" region not closed by "@}"`);
458
861
  if (layout)
@@ -466,6 +869,7 @@ const INLINE_PATTERNS = [
466
869
  ["b", /\*\*(.+?)\*\*/s],
467
870
  ["i", /(?<![\p{L}\p{N}_*])\*(?!\s)(.+?)(?<!\s)\*(?![\p{L}\p{N}_*])/su],
468
871
  ["code", /`([^`]+)`/],
872
+ ["s", /~~(?!\s)(.+?)(?<!\s)~~/s],
469
873
  ];
470
874
  function inline(s, fmt = new Set(), href = null) {
471
875
  s = s.replace("$\\text{XX}^\\text{e}$", "XXᵉ");
@@ -533,6 +937,8 @@ function runsXml(text) {
533
937
  const st = spanStyle(fmt);
534
938
  if (st)
535
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>`;
536
942
  if (href)
537
943
  x = `<text:a xlink:type="simple" xlink:href="${esc(href)}">${x}</text:a>`;
538
944
  return x;
@@ -745,6 +1151,8 @@ function blockH(b, width) {
745
1151
  return HR_H;
746
1152
  case "compact":
747
1153
  return arrange(b, width).h;
1154
+ case "box":
1155
+ return boxH(b, width);
748
1156
  default:
749
1157
  return 0;
750
1158
  }
@@ -1228,8 +1636,111 @@ function revealSteps(content) {
1228
1636
  return content.map(b => (b.t === "table" && b.reveal) || (b.t === "compact" && tablesOf(b.blocks).some(t => t.reveal)) ? { ...b, shown } : b);
1229
1637
  });
1230
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
+ }
1231
1738
  class Builder {
1232
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 = [];
1233
1744
  pictures = new Map();
1234
1745
  pages = [];
1235
1746
  colStyles = new Map();
@@ -1294,6 +1805,28 @@ class Builder {
1294
1805
  return this.rowStyles.get(key);
1295
1806
  }
1296
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
+ }
1297
1830
  static geom(x, y, w, h) {
1298
1831
  return `svg:x="${f2(x)}cm" svg:y="${f2(y)}cm" svg:width="${f2(w)}cm" svg:height="${f2(h)}cm"`;
1299
1832
  }
@@ -1316,9 +1849,9 @@ class Builder {
1316
1849
  * style. Lists with numbered items name the list styles `<frameStyle>-numbers` and
1317
1850
  * `<frameStyle>-bullets` (see `listStylesXml()`) on every nested list.
1318
1851
  */
1319
- listXml(items, frameStyle, k = 1) {
1852
+ listXml(items, frameStyle, k = 1, pt, named = false) {
1320
1853
  const holder = listStyleHolder(frameStyle);
1321
- const styled = holder !== null && items.some(it => it[2] !== undefined);
1854
+ const styled = holder !== null && (named || items.some(it => it[2] !== undefined));
1322
1855
  const out = [];
1323
1856
  // For each open list: is it numbered?
1324
1857
  const open = [];
@@ -1342,7 +1875,7 @@ class Builder {
1342
1875
  out.push(`<text:list${name}><text:list-item${start}>`);
1343
1876
  open.push(ordered);
1344
1877
  }
1345
- out.push(`<text:p${this.scaledPara(sizes.list[Math.min(lvl, 8)], k, outlineStyle(frameStyle, lvl))}>${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>`);
1346
1879
  }
1347
1880
  while (open.length)
1348
1881
  close();
@@ -1422,7 +1955,17 @@ class Builder {
1422
1955
  `<draw:enhanced-geometry svg:viewBox="0 0 21600 21600" draw:type="round-rectangle" draw:modifiers="1800"/>` +
1423
1956
  `</draw:custom-shape>`);
1424
1957
  }
1958
+ /** The shapes of a block, with an id if it is animated (each part of a table on its own). */
1425
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) {
1426
1969
  switch (b.t) {
1427
1970
  case "para":
1428
1971
  return this.frame("Texte", x, y, w, h, `<text:p${this.scaledPara(sizes.text, b.k, "Texte")}>${runsXml(b.text)}</text:p>`);
@@ -1437,19 +1980,50 @@ class Builder {
1437
1980
  }
1438
1981
  case "compact":
1439
1982
  return this.regionXml(b, x, y, w);
1440
- case "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("");
1446
- }
1983
+ case "box":
1984
+ return this.boxXml(b, x, y, w, h);
1447
1985
  case "hr":
1448
1986
  return this.hrXml(x, y, w, h);
1449
1987
  default:
1450
1988
  throw new Error(`Unexpected block ${b.t}`);
1451
1989
  }
1452
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
+ }
1453
2027
  /** The columns of a `@compact {` region, top-aligned. */
1454
2028
  regionXml(b, x, y, w) {
1455
2029
  const arr = arrange(b, w);
@@ -1461,7 +2035,7 @@ class Builder {
1461
2035
  const bh = regionBlockH(blk, arr.colW);
1462
2036
  if (blk.t === "image") {
1463
2037
  const [iw] = regionImageSize(blk, arr.colW);
1464
- out.push(this.imageXml(blk.src, cx + (arr.colW - iw) / 2, cy, iw, bh, blk.alt));
2038
+ out.push(this.animated(this.imageXml(blk.src, cx + (arr.colW - iw) / 2, cy, iw, bh, blk.alt), blk.anim));
1465
2039
  }
1466
2040
  else
1467
2041
  out.push(this.blockXml(blk.t === "table" && b.shown ? { ...blk, shown: b.shown } : blk, cx, cy, arr.colW, bh));
@@ -1490,10 +2064,11 @@ class Builder {
1490
2064
  if (!imgs.length)
1491
2065
  return [stack(texts, X0, W), shapes];
1492
2066
  const src = imgs[0].src;
2067
+ const anim = animOf(imgs[0]);
1493
2068
  const [iw, ih] = imageSize(resolve(this.base, src));
1494
2069
  if (!texts.length) {
1495
2070
  const [w, h] = fit(iw, ih, W, H);
1496
- 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));
1497
2072
  return [0, shapes];
1498
2073
  }
1499
2074
  if (iw / ih >= 1.8 || (iw / ih >= 1.2 && sumH(W) < 2.5)) {
@@ -1501,7 +2076,7 @@ class Builder {
1501
2076
  const th = stack(texts, X0, W, false);
1502
2077
  const avail = Math.max(H - th - GAP, 4.5);
1503
2078
  const [w, h] = fit(iw, ih, W, avail);
1504
- 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));
1505
2080
  return [th + GAP + 4.5, shapes];
1506
2081
  }
1507
2082
  // Give the image more room when the text is short.
@@ -1509,7 +2084,7 @@ class Builder {
1509
2084
  const th = stack(texts, X0, tw);
1510
2085
  const bw = W - tw - 0.8;
1511
2086
  const [w, h] = fit(iw, ih, bw, H);
1512
- 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));
1513
2088
  return [th, shapes];
1514
2089
  }
1515
2090
  /** Split blocks into slides: list of [content blocks, notes]. */
@@ -1547,10 +2122,13 @@ class Builder {
1547
2122
  }
1548
2123
  /** Do these blocks fit on one slide? */
1549
2124
  fits(blocks) {
1550
- // `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.
1551
2126
  const saved = [new Map(this.colStyles), new Map(this.rowStyles), new Map(this.paraStyles)];
2127
+ const [animCount, animShapes] = [this.animCount, this.animShapes.length];
1552
2128
  const ok = this.layout(blocks)[0] <= H;
1553
2129
  [this.colStyles, this.rowStyles, this.paraStyles] = saved;
2130
+ this.animCount = animCount;
2131
+ this.animShapes.length = animShapes;
1554
2132
  return ok;
1555
2133
  }
1556
2134
  /**
@@ -1701,8 +2279,13 @@ class Builder {
1701
2279
  }
1702
2280
  }
1703
2281
  // -- pages
1704
- page(master, shapes, notes = []) {
1705
- const page = { master, shapes, notes, sec: this.current };
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) };
1706
2289
  this.pages.push(page);
1707
2290
  return page;
1708
2291
  }
@@ -1794,10 +2377,12 @@ class Builder {
1794
2377
  continue;
1795
2378
  }
1796
2379
  const allNotes = [...pending.splice(0), ...notes];
1797
- 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) => {
1798
2383
  const [, shapes] = this.layout(step);
1799
- this.page("Master", [...this.titleShapes(title, crumbs), ...shapes], [...allNotes]);
1800
- }
2384
+ this.page("Master", [...this.titleShapes(title, crumbs), ...shapes], [...allNotes], undefined, i < steps.length - 1);
2385
+ });
1801
2386
  }
1802
2387
  run = [];
1803
2388
  };
@@ -1862,7 +2447,8 @@ class Builder {
1862
2447
  continue;
1863
2448
  const last = items[items.length - 1];
1864
2449
  if (b.t === "para" || b.t === "list" || b.t === "quote") {
1865
- 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)
1866
2452
  last.blocks.push(b);
1867
2453
  else
1868
2454
  items.push({ kind: "text", blocks: [b] });
@@ -1881,6 +2467,8 @@ class Builder {
1881
2467
  return promptSize(b.lines, w)[1];
1882
2468
  if (b.t === "hr")
1883
2469
  return HR_H;
2470
+ if (b.t === "box")
2471
+ return boxH(b, w);
1884
2472
  return 0;
1885
2473
  });
1886
2474
  const flexible = items.map(it => it.kind === "text" || (it.kind === "block" && it.block.t === "image"));
@@ -1916,25 +2504,29 @@ class Builder {
1916
2504
  const inner = it.blocks
1917
2505
  .map(b => (b.t === "list" ? this.listXml(b.items, textStyle) : b.t === "para" || b.t === "quote" ? `<text:p>${runsXml(b.text)}</text:p>` : ""))
1918
2506
  .join("");
1919
- 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])));
1920
2508
  }
1921
2509
  else {
1922
2510
  const b = it.block;
2511
+ const push = (xml) => shapes.push(this.animated(xml, animOf(b)));
1923
2512
  if (b.t === "table") {
1924
2513
  const header = b.header?.map(stripMd) ?? null;
1925
- 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));
1926
2515
  }
1927
2516
  else if (b.t === "image") {
1928
2517
  const [iw, ihh] = imageSize(resolve(sec.source, b.src));
1929
2518
  const [fw, fh] = fit(iw, ihh, w, ih);
1930
- 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));
1931
2520
  }
1932
2521
  else if (b.t === "prompt" || b.t === "code") {
1933
2522
  const [pw] = promptSize(b.lines, w);
1934
- 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"));
1935
2524
  }
1936
2525
  else if (b.t === "hr") {
1937
- shapes.push(this.hrXml(x, cy, w, ih));
2526
+ push(this.hrXml(x, cy, w, ih));
2527
+ }
2528
+ else if (b.t === "box") {
2529
+ push(this.boxXml(b, x, cy, w, ih));
1938
2530
  }
1939
2531
  }
1940
2532
  cy += heights[i] + gap;
@@ -1995,7 +2587,9 @@ class Builder {
1995
2587
  shapes.push(...this.cellXml(sec, x, y + hh, w, h - hh, textStyle, textPt));
1996
2588
  notes.push(...sec.blocks.flatMap(b => (b.t === "note" ? [b.text] : [])));
1997
2589
  });
1998
- 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);
1999
2593
  }
2000
2594
  walk(sec) {
2001
2595
  this.current = sec;
@@ -2061,6 +2655,8 @@ const NS = [
2061
2655
  'xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"',
2062
2656
  'xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"',
2063
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"',
2064
2660
  'office:version="1.3"',
2065
2661
  ].join(" ");
2066
2662
  function attrs(props = {}, where = "") {
@@ -2092,7 +2688,7 @@ function styleCm(name, prop) {
2092
2688
  }
2093
2689
  /** Style of the paragraphs of level `lvl` (0-based) in a frame of style `Master-outline1`. */
2094
2690
  function outlineStyle(frameStyle, lvl) {
2095
- return frameStyle.replace(/1$/, String(Math.min(lvl, 8) + 1));
2691
+ return frameStyle.replace(/(-outline)1$/, `$1${Math.min(lvl, 8) + 1}`);
2096
2692
  }
2097
2693
  /** `name` or its nearest parent style defining both `bullets` and `numbers`, if any. */
2098
2694
  function listStyleHolder(name) {
@@ -2224,10 +2820,11 @@ function contentXml(b) {
2224
2820
  auto.push(bulletsXml(tocBullets, "Toc"));
2225
2821
  for (const [key, name] of b.rowStyles)
2226
2822
  auto.push(`<style:style style:name="${name}" style:family="table-row"><style:table-row-properties style:row-height="${key}cm"/></style:style>`);
2227
- const pages = b.pages.map(({ master, shapes, notes }, i) => {
2823
+ const pages = b.pages.map(({ master, shapes, notes, timing }, i) => {
2228
2824
  const n = i + 1;
2229
2825
  const noteXml = notes.map(t => `<text:p>${xmlText(t)}</text:p>`).join("");
2230
- 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 ?? ""}` +
2231
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"/>` +
2232
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>` +
2233
2830
  `</presentation:notes></draw:page>`);
package/dist/styles.js CHANGED
@@ -395,11 +395,42 @@ export const defaultStyle = {
395
395
  dashes: {
396
396
  Tirets: { "draw:style": "rect", "draw:dots1": "1", "draw:dots1-length": "0.2cm", "draw:distance": "0.15cm" },
397
397
  },
398
+ boxes: {
399
+ /** No `color`: black or white, whichever is more readable on the background. */
400
+ info: {
401
+ background: "{colors.quoteBackground}",
402
+ border: "0.03cm solid {colors.primary}",
403
+ radius: "0.3cm",
404
+ shadow: "0.1cm 0.1cm 0.3cm {colors.muted} 30%",
405
+ padding: "0.4cm 0.6cm",
406
+ },
407
+ warning: {
408
+ background: "{colors.accent}",
409
+ color: "{colors.white}",
410
+ border: "none",
411
+ radius: "0.3cm",
412
+ shadow: "0.1cm 0.1cm 0.3cm {colors.muted} 30%",
413
+ padding: "0.4cm 0.6cm",
414
+ },
415
+ /** Monospace text, e.g. a terminal output inside another box. */
416
+ terminal: {
417
+ background: "#1E1E1E",
418
+ border: "none",
419
+ radius: "0.15cm",
420
+ shadow: "none",
421
+ padding: "0.25cm 0.4cm",
422
+ margin: "0.1cm 0cm",
423
+ font: "mono",
424
+ size: "{sizes.code}pt",
425
+ },
426
+ },
398
427
  spanStyles: {
399
428
  T_b: { "fo:font-weight": "bold" },
400
429
  T_i: { "fo:font-style": "italic" },
401
430
  T_bi: { "fo:font-weight": "bold", "fo:font-style": "italic" },
402
431
  T_code: mono,
432
+ /** Strikethrough: `~~text~~`. Nested around the other span styles, so it combines with them. */
433
+ T_s: { "style:text-line-through-style": "solid", "style:text-line-through-type": "single" },
403
434
  /** Highlighted section in the hierarchy box of a section slide. */
404
435
  T_section: { "fo:font-weight": "bold", "fo:color": "{colors.sectionHighlight}" },
405
436
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tolokoban/impress",
3
- "version": "0.16.0",
3
+ "version": "0.20.0",
4
4
  "description": "Convert teaching markdown files into LibreOffice Impress presentations (.odp)",
5
5
  "type": "module",
6
6
  "bin": {