1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! The expanded tree (spec §12.3), what stage 4b makes of a document: content only, with every `compmd` definition,
//! `if`, `each`, `value` and interpolation replaced by what it produces. Components stay as nodes only where the
//! processor renders them itself: `box`, the input components, and host-language components, with their params
//! evaluated.
//!
//! It shares the mdast node types of the [parse tree](crate::tree), with expanded children, and serializes to the
//! JSON `conformance/compmd-tree.schema.json` defines as `#/$defs/expandedRoot`.
mod heading;
use crate::cel;
use crate::tree::{
Blockquote, FootnoteDefinition, Image, ImageReference, Link, LinkDefinition, LinkReference,
List, ListItem, Literal, Math, Parent, Point, Reference, Table, Void, WikiLink,
};
pub use heading::Heading;
use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};
use serde_json::Value;
use std::rc::Rc;
/// The root of an expanded tree.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(tag = "type", rename = "root")]
pub struct Root {
/// The document's content.
pub children: Vec<Node>,
/// The document's inputs, in declared order, with the values the render used; absent when it has none.
#[serde(skip_serializing_if = "Inputs::is_empty")]
pub inputs: Inputs,
/// For an example (spec §7.8), its number among the processed document's examples, from 1, which its
/// host-language components are listed under; absent for the processed document.
#[serde(skip_serializing_if = "Option::is_none")]
pub example: Option<usize>,
/// The document's language, `md.lang`, when it writes one (spec §2.1).
#[serde(skip_serializing_if = "Option::is_none")]
pub lang: Option<String>,
/// The document's direction, `md.dir`, or its language's when it writes only `md.lang`: `ltr`, `rtl` or `auto`.
#[serde(skip_serializing_if = "Option::is_none")]
pub dir: Option<String>,
/// The fonts its `font-family` params name, in the order they first do (spec §9.4); absent when they name none.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub fonts: Vec<Font>,
}
/// A font of a document's own that the expanded tree uses (spec §12.3): a `font-family` param names it by `family`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Font {
/// Its one name in the tree.
pub family: String,
/// The type token that shows while it loads, or where it can't: `body`, `heading` or `mono`.
pub fallback: String,
/// Its files.
pub files: Vec<FontFile>,
}
/// A file of a font, resolved as a destination is (spec §8.6).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct FontFile {
/// Its URL: a path relative to the processed document, or, for a pack's file, its place.
pub url: String,
/// Whether `url` is the place of a pack's file, which the host maps to where it serves it.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub pack: bool,
/// `normal` or `bold`.
pub weight: String,
/// `normal` or `italic`.
pub style: String,
}
/// A document's inputs, serialized as a map from each name to its state.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Inputs(pub(crate) Vec<Input>);
impl Inputs {
/// Whether the document declares no input.
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// The inputs, in declared order.
pub fn iter(&self) -> std::slice::Iter<'_, Input> {
self.0.iter()
}
/// `md.input`: each input's value by its name.
pub(crate) fn value(&self) -> cel::Value {
let values = self.iter().map(|input| {
(
cel::Key::String(Rc::from(input.name.as_str())),
cel::Value::from_json(&input.value),
)
});
cel::Value::Map(Rc::new(values.collect()))
}
}
impl<'a> IntoIterator for &'a Inputs {
type Item = &'a Input;
type IntoIter = std::slice::Iter<'a, Input>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl Serialize for Inputs {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(Some(self.0.len()))?;
for input in self {
map.serialize_entry(&input.name, input)?;
}
map.end()
}
}
/// An input of the document (spec §8.7), as input components read it.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Input {
/// Its name.
#[serde(skip)]
pub name: String,
/// Its type: a type name, or `enum`.
#[serde(rename = "type")]
pub kind: String,
/// An enum's members, its choices.
#[serde(skip_serializing_if = "Option::is_none")]
pub members: Option<Vec<String>>,
/// The value the render used: the one given, or the default.
pub value: Value,
}
/// A node of the expanded tree.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Node {
/// What the node is.
#[serde(flatten)]
pub content: Content,
/// The range of the processed document that made it (the `origins` feature, spec §12.3).
#[serde(skip_serializing_if = "Option::is_none")]
pub origin: Option<Origin>,
}
impl Node {
/// A node without an origin.
pub(crate) fn new(content: Content) -> Self {
Self {
content,
origin: None,
}
}
}
/// What an expanded node is, serialized with its `type`.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Content {
/// A block quote.
Blockquote(Blockquote<Node>),
/// A hard line break.
Break(Void),
/// A code block.
Code(Code),
/// A `box`, or a host-language component that takes a body.
ComponentContainer(Container),
/// An inline component the processor renders: an input component, or a host-language one.
ComponentInline(Leaf),
/// A leaf the processor renders: an input component, or a host-language one.
ComponentLeaf(Leaf),
/// A use of a component whose pack is pending, with the fallback it renders meanwhile (spec §4.5).
ComponentPending(Pending),
/// A link reference definition.
Definition(LinkDefinition),
/// GFM strikethrough.
Delete(Parent<Node>),
/// Emphasis.
Emphasis(Parent<Node>),
/// A GFM footnote definition.
FootnoteDefinition(FootnoteDefinition<Node>),
/// A GFM footnote reference.
FootnoteReference(Reference),
/// A heading, at its computed depth, with its anchor.
Heading(Heading),
/// Raw HTML.
Html(Literal),
/// An image.
Image(Image),
/// An image by reference.
ImageReference(ImageReference),
/// A code span.
InlineCode(Literal),
/// Inline math.
InlineMath(Literal),
/// A link.
Link(Link<Node>),
/// A link by reference.
LinkReference(LinkReference<Node>),
/// A list.
List(List<Node>),
/// An item of a list.
ListItem(ListItem<Node>),
/// Display math.
Math(Math),
/// A paragraph.
Paragraph(Parent<Node>),
/// Strong emphasis.
Strong(Parent<Node>),
/// A GFM table.
Table(Table<Node>),
/// A cell of a table row.
TableCell(Parent<Node>),
/// A row of a table.
TableRow(Parent<Node>),
/// Text.
Text(Literal),
/// A thematic break.
ThematicBreak(Void),
/// A wiki link.
WikiLink(WikiLink),
}
impl Content {
/// Its children: a parent's content, a container's default slot, a leaf's fallback.
#[must_use]
pub fn children(&self) -> &[Node] {
match self {
Self::Blockquote(Blockquote { children, .. })
| Self::Delete(Parent { children, .. })
| Self::Emphasis(Parent { children, .. })
| Self::Paragraph(Parent { children, .. })
| Self::Strong(Parent { children, .. })
| Self::TableCell(Parent { children, .. })
| Self::TableRow(Parent { children, .. })
| Self::FootnoteDefinition(FootnoteDefinition { children, .. })
| Self::Heading(Heading { children, .. })
| Self::Link(Link { children, .. })
| Self::LinkReference(LinkReference { children, .. })
| Self::List(List { children, .. })
| Self::ListItem(ListItem { children, .. })
| Self::Table(Table { children, .. })
| Self::ComponentContainer(Container { children, .. })
| Self::ComponentPending(Pending { children, .. }) => children,
Self::ComponentLeaf(leaf) | Self::ComponentInline(leaf) => &leaf.fallback,
_ => &[],
}
}
/// Every list of nodes it holds: its children, then a container's template instances and each named slot's
/// content and instances.
pub(crate) fn lists(&self) -> Vec<&[Node]> {
let mut lists = vec![self.children()];
if let Self::ComponentContainer(container) = self {
lists.extend(instances(container.instances.as_deref()));
for slot in &container.slots {
lists.push(&slot.children);
lists.extend(instances(slot.instances.as_deref()));
}
}
lists
}
/// Every list of nodes it holds, to change them: as [`Content::lists`].
pub(crate) fn lists_mut(&mut self) -> Vec<&mut Vec<Node>> {
let Self::ComponentContainer(container) = self else {
return self.children_mut().into_iter().collect();
};
let mut lists = vec![&mut container.children];
lists.extend(instances_mut(container.instances.as_deref_mut()));
for slot in &mut container.slots {
lists.push(&mut slot.children);
lists.extend(instances_mut(slot.instances.as_deref_mut()));
}
lists
}
/// Its children, to change them.
pub(crate) fn children_mut(&mut self) -> Option<&mut Vec<Node>> {
match self {
Self::Blockquote(Blockquote { children, .. })
| Self::Delete(Parent { children, .. })
| Self::Emphasis(Parent { children, .. })
| Self::Paragraph(Parent { children, .. })
| Self::Strong(Parent { children, .. })
| Self::TableCell(Parent { children, .. })
| Self::TableRow(Parent { children, .. })
| Self::FootnoteDefinition(FootnoteDefinition { children, .. })
| Self::Heading(Heading { children, .. })
| Self::Link(Link { children, .. })
| Self::LinkReference(LinkReference { children, .. })
| Self::List(List { children, .. })
| Self::ListItem(ListItem { children, .. })
| Self::Table(Table { children, .. })
| Self::ComponentContainer(Container { children, .. })
| Self::ComponentPending(Pending { children, .. }) => Some(children),
Self::ComponentLeaf(leaf) | Self::ComponentInline(leaf) => Some(&mut leaf.fallback),
_ => None,
}
}
}
/// The content of a template slot's instances.
fn instances(instances: Option<&[Instance]>) -> impl Iterator<Item = &[Node]> {
instances
.into_iter()
.flatten()
.map(|instance| instance.children.as_slice())
}
fn instances_mut(instances: Option<&mut [Instance]>) -> impl Iterator<Item = &mut Vec<Node>> {
instances
.into_iter()
.flatten()
.map(|instance| &mut instance.children)
}
/// A component container the processor renders.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Container {
/// The component's name: `box`, or the host-language component's.
pub name: String,
/// Its params, evaluated.
pub params: Vec<Param>,
/// The default slot, expanded; empty for a template slot, whose content is in `instances`.
pub children: Vec<Node>,
/// A template default slot's content, once per element (spec §7.5).
#[serde(skip_serializing_if = "Option::is_none")]
pub instances: Option<Vec<Instance>>,
/// The named slots, expanded.
pub slots: Vec<Slot>,
}
/// A named slot of a component container.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(tag = "type", rename = "componentSlot")]
pub struct Slot {
/// The slot's name.
pub name: String,
/// Its content, expanded; empty for a template slot.
pub children: Vec<Node>,
/// A template slot's content, once per element.
#[serde(skip_serializing_if = "Option::is_none")]
pub instances: Option<Vec<Instance>>,
/// The range of the processed document that made it.
#[serde(skip_serializing_if = "Option::is_none")]
pub origin: Option<Origin>,
}
/// A template slot's content for one element (spec §7.5).
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Instance {
/// The element.
pub value: Value,
/// The slot's content, expanded with the element bound.
pub children: Vec<Node>,
}
/// A code block; one a code renderer renders names it, with its params, and its text alternative (spec §7.7, §12.3).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Code {
/// The first word of the info string.
pub lang: Option<String>,
/// The rest of the info string.
pub meta: Option<String>,
/// The code.
pub value: String,
/// The code renderer that renders it, when one does.
#[serde(skip_serializing_if = "Option::is_none")]
pub component: Option<Rendered>,
/// Its text alternative, `alt`, when a code renderer renders it.
#[serde(skip_serializing_if = "Option::is_none")]
pub alt: Option<String>,
/// What it shows, when a code renderer renders it or it is an example; a `source` block has no `component`.
#[serde(skip_serializing_if = "Option::is_none")]
pub render: Option<crate::render::Render>,
/// An example's box params, evaluated: the common params, `class` and `id` (spec §7.8).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub params: Vec<Param>,
/// An example's expanded root (spec §7.8, §12.3).
#[serde(skip_serializing_if = "Option::is_none")]
pub document: Option<Box<Root>>,
}
/// The code renderer of a code block, with its params, the block's text as `code` (spec §7.7).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Rendered {
/// The component's name, as the document gives it.
pub name: String,
/// Its params, evaluated.
pub params: Vec<Param>,
}
/// A leaf or an inline component the processor renders.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Leaf {
/// The component's name.
pub name: String,
/// Its params, evaluated.
pub params: Vec<Param>,
/// The fallback, expanded.
pub fallback: Vec<Node>,
}
/// A use of a component whose pack is pending (spec §4.5, §12.3).
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Pending {
/// The component's name, as the document gives it.
pub name: String,
/// The pending pack, as the import names it.
pub pack: compmd_pack::PackName,
/// The fallback the use renders until the pack arrives, expanded.
pub children: Vec<Node>,
}
/// An evaluated param (spec §12.3).
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Param {
/// The key; `class` for all the classes, `id` for `#name`.
pub key: String,
/// The breakpoint it applies from.
pub breakpoint: Option<String>,
/// The value, as JSON; whole numbers are written without a fraction.
pub value: Value,
/// For a param bound to an input, the input's name.
#[serde(skip_serializing_if = "Option::is_none")]
pub input: Option<String>,
}
/// The range of the processed document that made an expanded node, and how many nodes before it in the same list
/// have the same range (spec §12.3).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
pub struct Origin {
/// Where the range starts.
pub start: Point,
/// Where it ends.
pub end: Point,
/// How many nodes before this one, in the same list of children, have the same range.
pub occurrence: usize,
}