1use std::collections::BTreeMap;
33
34use serde::{Deserialize, Serialize};
35
36pub type Value = serde_json::Value;
38
39pub type Metadata = BTreeMap<String, Value>;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
47#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
48pub struct Span {
49 pub start: u32,
51 pub end: u32,
53}
54
55impl Span {
56 pub const fn new(start: u32, end: u32) -> Self {
58 Self { start, end }
59 }
60}
61
62#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
64#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
65pub struct Document {
66 pub source: String,
69 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
71 pub metadata: Metadata,
72 #[serde(default)]
74 pub children: Vec<Node>,
75}
76
77impl Document {
78 pub fn new(source: impl Into<String>) -> Self {
80 Self {
81 source: source.into(),
82 ..Self::default()
83 }
84 }
85
86 pub fn descendants(&self) -> Descendants<'_> {
89 Descendants {
90 stack: self.children.iter().rev().collect(),
91 }
92 }
93
94 pub fn title(&self) -> Option<String> {
97 self.metadata
98 .get("title")
99 .and_then(Value::as_str)
100 .map(str::to_owned)
101 .or_else(|| {
102 self.descendants().find_map(|n| match n {
103 Node::Heading(h) => Some(plain_text(&h.children)),
104 _ => None,
105 })
106 })
107 }
108}
109
110pub fn plain_text(nodes: &[Node]) -> String {
113 let mut out = String::new();
114 for node in nodes {
115 match node {
116 Node::Text(t) => out.push_str(&t.value),
117 Node::InlineCode(c) => out.push_str(&c.value),
118 Node::Image(i) => out.push_str(&i.alt),
119 other => out.push_str(&plain_text(other.children())),
120 }
121 }
122 out
123}
124
125#[derive(Debug, Clone)]
128pub struct Descendants<'a> {
129 stack: Vec<&'a Node>,
130}
131
132impl<'a> Iterator for Descendants<'a> {
133 type Item = &'a Node;
134
135 fn next(&mut self) -> Option<Self::Item> {
136 let node = self.stack.pop()?;
137 self.stack.extend(node.children().iter().rev());
138 Some(node)
139 }
140}
141
142#[derive(Debug, Clone, PartialEq, Serialize)]
150#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
151#[serde(tag = "type", rename_all = "snake_case")]
152pub enum Node {
153 Section(Section),
155 Heading(Heading),
157 Paragraph(Paragraph),
159 List(List),
161 ListItem(ListItem),
163 BlockQuote(BlockQuote),
165 CodeBlock(CodeBlock),
167 Table(Table),
169 TableRow(TableRow),
171 TableCell(TableCell),
173 ThematicBreak(ThematicBreak),
175 Raw(Raw),
178 Text(Text),
180 Emphasis(Emphasis),
182 Strong(Strong),
184 InlineCode(InlineCode),
186 Link(Link),
188 Image(Image),
190 LineBreak(LineBreak),
192 Admonition(Admonition),
194 DefinitionList(DefinitionList),
198 DefinitionTerm(DefinitionTerm),
200 DefinitionDescription(DefinitionDescription),
202 FootnoteReference(FootnoteReference),
204 FootnoteDefinition(FootnoteDefinition),
206 Math(Math),
208 Figure(Figure),
211 Caption(Caption),
213 Anchor(Anchor),
216 Custom(Custom),
218}
219
220impl Node {
221 pub fn kind(&self) -> std::borrow::Cow<'static, str> {
225 use std::borrow::Cow::{Borrowed, Owned};
226 Borrowed(match self {
227 Node::Section(_) => "section",
228 Node::Heading(_) => "heading",
229 Node::Paragraph(_) => "paragraph",
230 Node::List(_) => "list",
231 Node::ListItem(_) => "list_item",
232 Node::BlockQuote(_) => "block_quote",
233 Node::CodeBlock(_) => "code_block",
234 Node::Table(_) => "table",
235 Node::TableRow(_) => "table_row",
236 Node::TableCell(_) => "table_cell",
237 Node::ThematicBreak(_) => "thematic_break",
238 Node::Raw(_) => "raw",
239 Node::Text(_) => "text",
240 Node::Emphasis(_) => "emphasis",
241 Node::Strong(_) => "strong",
242 Node::InlineCode(_) => "inline_code",
243 Node::Link(_) => "link",
244 Node::Image(_) => "image",
245 Node::LineBreak(_) => "line_break",
246 Node::Admonition(_) => "admonition",
247 Node::DefinitionList(_) => "definition_list",
248 Node::DefinitionTerm(_) => "definition_term",
249 Node::DefinitionDescription(_) => "definition_description",
250 Node::FootnoteReference(_) => "footnote_reference",
251 Node::FootnoteDefinition(_) => "footnote_definition",
252 Node::Math(_) => "math",
253 Node::Figure(_) => "figure",
254 Node::Caption(_) => "caption",
255 Node::Anchor(_) => "anchor",
256 Node::Custom(c) => return Owned(format!("custom:{}", c.kind)),
257 })
258 }
259
260 pub fn span(&self) -> Option<Span> {
262 match self {
263 Node::Section(n) => n.span,
264 Node::Heading(n) => n.span,
265 Node::Paragraph(n) => n.span,
266 Node::List(n) => n.span,
267 Node::ListItem(n) => n.span,
268 Node::BlockQuote(n) => n.span,
269 Node::CodeBlock(n) => n.span,
270 Node::Table(n) => n.span,
271 Node::TableRow(n) => n.span,
272 Node::TableCell(n) => n.span,
273 Node::ThematicBreak(n) => n.span,
274 Node::Raw(n) => n.span,
275 Node::Text(n) => n.span,
276 Node::Emphasis(n) => n.span,
277 Node::Strong(n) => n.span,
278 Node::InlineCode(n) => n.span,
279 Node::Link(n) => n.span,
280 Node::Image(n) => n.span,
281 Node::LineBreak(n) => n.span,
282 Node::Admonition(n) => n.span,
283 Node::DefinitionList(n) => n.span,
284 Node::DefinitionTerm(n) => n.span,
285 Node::DefinitionDescription(n) => n.span,
286 Node::FootnoteReference(n) => n.span,
287 Node::FootnoteDefinition(n) => n.span,
288 Node::Math(n) => n.span,
289 Node::Figure(n) => n.span,
290 Node::Caption(n) => n.span,
291 Node::Anchor(n) => n.span,
292 Node::Custom(n) => n.span,
293 }
294 }
295
296 pub fn span_mut(&mut self) -> &mut Option<Span> {
299 match self {
300 Node::Section(n) => &mut n.span,
301 Node::Heading(n) => &mut n.span,
302 Node::Paragraph(n) => &mut n.span,
303 Node::List(n) => &mut n.span,
304 Node::ListItem(n) => &mut n.span,
305 Node::BlockQuote(n) => &mut n.span,
306 Node::CodeBlock(n) => &mut n.span,
307 Node::Table(n) => &mut n.span,
308 Node::TableRow(n) => &mut n.span,
309 Node::TableCell(n) => &mut n.span,
310 Node::ThematicBreak(n) => &mut n.span,
311 Node::Raw(n) => &mut n.span,
312 Node::Text(n) => &mut n.span,
313 Node::Emphasis(n) => &mut n.span,
314 Node::Strong(n) => &mut n.span,
315 Node::InlineCode(n) => &mut n.span,
316 Node::Link(n) => &mut n.span,
317 Node::Image(n) => &mut n.span,
318 Node::LineBreak(n) => &mut n.span,
319 Node::Admonition(n) => &mut n.span,
320 Node::DefinitionList(n) => &mut n.span,
321 Node::DefinitionTerm(n) => &mut n.span,
322 Node::DefinitionDescription(n) => &mut n.span,
323 Node::FootnoteReference(n) => &mut n.span,
324 Node::FootnoteDefinition(n) => &mut n.span,
325 Node::Math(n) => &mut n.span,
326 Node::Figure(n) => &mut n.span,
327 Node::Caption(n) => &mut n.span,
328 Node::Anchor(n) => &mut n.span,
329 Node::Custom(n) => &mut n.span,
330 }
331 }
332
333 pub fn children(&self) -> &[Node] {
335 match self {
336 Node::Section(n) => &n.children,
337 Node::Heading(n) => &n.children,
338 Node::Paragraph(n) => &n.children,
339 Node::List(n) => &n.children,
340 Node::ListItem(n) => &n.children,
341 Node::BlockQuote(n) => &n.children,
342 Node::Table(n) => &n.children,
343 Node::TableRow(n) => &n.children,
344 Node::TableCell(n) => &n.children,
345 Node::Emphasis(n) => &n.children,
346 Node::Strong(n) => &n.children,
347 Node::Link(n) => &n.children,
348 Node::Admonition(n) => &n.children,
349 Node::DefinitionList(n) => &n.children,
350 Node::DefinitionTerm(n) => &n.children,
351 Node::DefinitionDescription(n) => &n.children,
352 Node::FootnoteDefinition(n) => &n.children,
353 Node::Figure(n) => &n.children,
354 Node::Caption(n) => &n.children,
355 Node::Custom(n) => &n.children,
356 Node::CodeBlock(_)
357 | Node::ThematicBreak(_)
358 | Node::Raw(_)
359 | Node::Text(_)
360 | Node::InlineCode(_)
361 | Node::Image(_)
362 | Node::LineBreak(_)
363 | Node::FootnoteReference(_)
364 | Node::Math(_)
365 | Node::Anchor(_) => &[],
366 }
367 }
368
369 pub fn children_mut(&mut self) -> Option<&mut Vec<Node>> {
371 match self {
372 Node::Section(n) => Some(&mut n.children),
373 Node::Heading(n) => Some(&mut n.children),
374 Node::Paragraph(n) => Some(&mut n.children),
375 Node::List(n) => Some(&mut n.children),
376 Node::ListItem(n) => Some(&mut n.children),
377 Node::BlockQuote(n) => Some(&mut n.children),
378 Node::Table(n) => Some(&mut n.children),
379 Node::TableRow(n) => Some(&mut n.children),
380 Node::TableCell(n) => Some(&mut n.children),
381 Node::Emphasis(n) => Some(&mut n.children),
382 Node::Strong(n) => Some(&mut n.children),
383 Node::Link(n) => Some(&mut n.children),
384 Node::Admonition(n) => Some(&mut n.children),
385 Node::DefinitionList(n) => Some(&mut n.children),
386 Node::DefinitionTerm(n) => Some(&mut n.children),
387 Node::DefinitionDescription(n) => Some(&mut n.children),
388 Node::FootnoteDefinition(n) => Some(&mut n.children),
389 Node::Figure(n) => Some(&mut n.children),
390 Node::Caption(n) => Some(&mut n.children),
391 Node::Custom(n) => Some(&mut n.children),
392 Node::CodeBlock(_)
393 | Node::ThematicBreak(_)
394 | Node::Raw(_)
395 | Node::Text(_)
396 | Node::InlineCode(_)
397 | Node::Image(_)
398 | Node::LineBreak(_)
399 | Node::FootnoteReference(_)
400 | Node::Math(_)
401 | Node::Anchor(_) => None,
402 }
403 }
404
405 pub fn descendants(&self) -> Descendants<'_> {
407 Descendants { stack: vec![self] }
408 }
409}
410
411mod de {
412 use std::fmt;
421
422 use serde::de::value::MapAccessDeserializer;
423 use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
424
425 use super::*;
426
427 macro_rules! variants {
429 ($tag:expr, $d:expr, $( $name:literal => $variant:ident ),* $(,)?) => {
430 match $tag {
431 $( $name => $variant::deserialize($d).map(Node::$variant), )*
432 other => Err(de::Error::unknown_variant(other, &[$($name),*])),
433 }
434 };
435 }
436
437 fn variant<'de, D: Deserializer<'de>>(tag: &str, d: D) -> Result<Node, D::Error> {
438 variants!(tag, d,
439 "section" => Section,
440 "heading" => Heading,
441 "paragraph" => Paragraph,
442 "list" => List,
443 "list_item" => ListItem,
444 "block_quote" => BlockQuote,
445 "code_block" => CodeBlock,
446 "table" => Table,
447 "table_row" => TableRow,
448 "table_cell" => TableCell,
449 "thematic_break" => ThematicBreak,
450 "raw" => Raw,
451 "text" => Text,
452 "emphasis" => Emphasis,
453 "strong" => Strong,
454 "inline_code" => InlineCode,
455 "link" => Link,
456 "image" => Image,
457 "line_break" => LineBreak,
458 "admonition" => Admonition,
459 "definition_list" => DefinitionList,
460 "definition_term" => DefinitionTerm,
461 "definition_description" => DefinitionDescription,
462 "footnote_reference" => FootnoteReference,
463 "footnote_definition" => FootnoteDefinition,
464 "math" => Math,
465 "figure" => Figure,
466 "caption" => Caption,
467 "anchor" => Anchor,
468 "custom" => Custom,
469 )
470 }
471
472 enum Key {
474 Type,
475 Other(String),
476 }
477
478 impl<'de> Deserialize<'de> for Key {
479 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
480 struct KeyVisitor;
481 impl Visitor<'_> for KeyVisitor {
482 type Value = Key;
483 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484 f.write_str("a field name")
485 }
486 fn visit_str<E: de::Error>(self, v: &str) -> Result<Key, E> {
487 Ok(if v == "type" {
488 Key::Type
489 } else {
490 Key::Other(v.to_owned())
491 })
492 }
493 }
494 d.deserialize_str(KeyVisitor)
495 }
496 }
497
498 struct Tag<'de>(std::borrow::Cow<'de, str>);
500
501 impl<'de> Deserialize<'de> for Tag<'de> {
502 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
503 struct TagVisitor;
504 impl<'de> Visitor<'de> for TagVisitor {
505 type Value = Tag<'de>;
506 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507 f.write_str("a node type")
508 }
509 fn visit_borrowed_str<E: de::Error>(self, v: &'de str) -> Result<Tag<'de>, E> {
510 Ok(Tag(v.into()))
511 }
512 fn visit_str<E: de::Error>(self, v: &str) -> Result<Tag<'de>, E> {
513 Ok(Tag(v.to_owned().into()))
514 }
515 }
516 d.deserialize_str(TagVisitor)
517 }
518 }
519
520 struct NodeVisitor;
521
522 impl<'de> Visitor<'de> for NodeVisitor {
523 type Value = Node;
524
525 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526 f.write_str("a document node: a map with a `type` field")
527 }
528
529 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Node, A::Error> {
530 let first = match map.next_key::<Key>()? {
531 None => return Err(de::Error::missing_field("type")),
532 Some(Key::Type) => {
533 let Tag(tag) = map.next_value()?;
534 return variant(&tag, MapAccessDeserializer::new(map));
535 }
536 Some(Key::Other(key)) => key,
537 };
538 let mut fields = serde_json::Map::new();
540 fields.insert(first, map.next_value()?);
541 while let Some((key, value)) = map.next_entry::<String, Value>()? {
542 fields.insert(key, value);
543 }
544 let tag = match fields.remove("type") {
545 Some(Value::String(tag)) => tag,
546 Some(_) => return Err(de::Error::custom("`type` must be a string")),
547 None => return Err(de::Error::missing_field("type")),
548 };
549 variant(&tag, Value::Object(fields)).map_err(de::Error::custom)
550 }
551 }
552
553 impl<'de> Deserialize<'de> for Node {
554 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
555 d.deserialize_map(NodeVisitor)
556 }
557 }
558}
559
560macro_rules! node_struct {
563 (
564 $(#[$meta:meta])*
565 $name:ident {
566 $( $(#[$fmeta:meta])* $field:ident : $ty:ty ),* $(,)?
567 }
568 ) => {
569 $(#[$meta])*
570 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
571 #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
572 pub struct $name {
573 #[serde(default, skip_serializing_if = "Option::is_none")]
575 pub span: Option<Span>,
576 $( $(#[$fmeta])* pub $field: $ty, )*
577 }
578
579 impl From<$name> for Node {
580 fn from(n: $name) -> Self {
581 Node::$name(n)
582 }
583 }
584 };
585}
586
587node_struct! {
588 Section {
590 #[serde(default, skip_serializing_if = "Option::is_none")]
594 id: Option<String>,
595 #[serde(default)]
597 children: Vec<Node>,
598 }
599}
600
601node_struct! {
602 Heading {
604 level: u8,
608 #[serde(default, skip_serializing_if = "Option::is_none")]
611 id: Option<String>,
612 #[serde(default)]
614 children: Vec<Node>,
615 }
616}
617
618node_struct! {
619 Paragraph {
621 #[serde(default)]
623 children: Vec<Node>,
624 }
625}
626
627node_struct! {
628 List {
630 #[serde(default)]
632 ordered: bool,
633 #[serde(default, skip_serializing_if = "Option::is_none")]
635 start: Option<u64>,
636 #[serde(default)]
638 children: Vec<Node>,
639 }
640}
641
642node_struct! {
643 ListItem {
645 #[serde(default, skip_serializing_if = "Option::is_none")]
647 checked: Option<bool>,
648 #[serde(default)]
650 children: Vec<Node>,
651 }
652}
653
654node_struct! {
655 BlockQuote {
657 #[serde(default)]
659 children: Vec<Node>,
660 }
661}
662
663node_struct! {
664 CodeBlock {
666 #[serde(default, skip_serializing_if = "Option::is_none")]
668 language: Option<String>,
669 #[serde(default, skip_serializing_if = "Option::is_none")]
671 info: Option<String>,
672 value: String,
674 }
675}
676
677node_struct! {
678 Table {
680 #[serde(default, skip_serializing_if = "Vec::is_empty")]
682 align: Vec<Align>,
683 #[serde(default)]
685 children: Vec<Node>,
686 }
687}
688
689node_struct! {
690 TableRow {
692 #[serde(default)]
694 header: bool,
695 #[serde(default)]
697 children: Vec<Node>,
698 }
699}
700
701node_struct! {
702 TableCell {
704 #[serde(default)]
706 children: Vec<Node>,
707 }
708}
709
710node_struct! {
711 ThematicBreak {}
713}
714
715node_struct! {
716 Raw {
718 format: String,
720 value: String,
722 }
723}
724
725node_struct! {
726 Text {
728 value: String,
730 }
731}
732
733node_struct! {
734 Emphasis {
736 #[serde(default)]
738 children: Vec<Node>,
739 }
740}
741
742node_struct! {
743 Strong {
745 #[serde(default)]
747 children: Vec<Node>,
748 }
749}
750
751node_struct! {
752 InlineCode {
754 value: String,
756 }
757}
758
759node_struct! {
760 Link {
762 url: String,
764 #[serde(default, skip_serializing_if = "Option::is_none")]
766 title: Option<String>,
767 #[serde(default, skip_serializing_if = "Option::is_none")]
770 target: Option<LinkTarget>,
771 #[serde(default)]
773 children: Vec<Node>,
774 }
775}
776
777#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
783#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
784pub struct LinkTarget {
785 #[serde(default, skip_serializing_if = "Option::is_none")]
788 pub document: Option<String>,
789 #[serde(default, skip_serializing_if = "Option::is_none")]
791 pub anchor: Option<String>,
792 #[serde(default, skip_serializing_if = "Option::is_none")]
795 pub label: Option<String>,
796}
797
798node_struct! {
799 Image {
801 url: String,
803 #[serde(default)]
805 alt: String,
806 #[serde(default, skip_serializing_if = "Option::is_none")]
808 title: Option<String>,
809 }
810}
811
812node_struct! {
813 LineBreak {}
815}
816
817node_struct! {
818 Admonition {
820 kind: String,
822 #[serde(default, skip_serializing_if = "Option::is_none")]
824 title: Option<String>,
825 #[serde(default)]
827 children: Vec<Node>,
828 }
829}
830
831node_struct! {
832 DefinitionList {
834 #[serde(default)]
836 children: Vec<Node>,
837 }
838}
839
840node_struct! {
841 DefinitionTerm {
843 #[serde(default)]
845 children: Vec<Node>,
846 }
847}
848
849node_struct! {
850 DefinitionDescription {
852 #[serde(default)]
854 children: Vec<Node>,
855 }
856}
857
858node_struct! {
859 FootnoteReference {
861 label: String,
863 }
864}
865
866node_struct! {
867 FootnoteDefinition {
869 label: String,
871 #[serde(default)]
873 children: Vec<Node>,
874 }
875}
876
877node_struct! {
878 Math {
880 value: String,
882 #[serde(default)]
884 display: bool,
885 }
886}
887
888node_struct! {
889 Figure {
891 #[serde(default, skip_serializing_if = "Option::is_none")]
893 id: Option<String>,
894 #[serde(default)]
896 children: Vec<Node>,
897 }
898}
899
900node_struct! {
901 Caption {
903 #[serde(default)]
905 children: Vec<Node>,
906 }
907}
908
909node_struct! {
910 Anchor {
912 id: String,
914 }
915}
916
917node_struct! {
918 Custom {
920 kind: String,
923 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
925 attrs: BTreeMap<String, Value>,
926 #[serde(default)]
928 children: Vec<Node>,
929 }
930}
931
932#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
934#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
935#[serde(rename_all = "snake_case")]
936pub enum Align {
937 #[default]
939 None,
940 Left,
942 Center,
944 Right,
946}
947
948pub fn text(value: impl Into<String>) -> Node {
950 Text {
951 span: None,
952 value: value.into(),
953 }
954 .into()
955}
956
957#[cfg(test)]
958mod tests {
959 #![allow(clippy::unwrap_used)]
960 use super::*;
961 use serde_json::json;
962
963 fn sample() -> Document {
964 let mut doc = Document::new("guide/intro.md");
965 doc.metadata.insert("title".into(), json!("Intro"));
966 doc.children = vec![
967 Heading {
968 span: Some(Span::new(0, 8)),
969 level: 1,
970 id: Some("intro".into()),
971 children: vec![text("Intro")],
972 }
973 .into(),
974 Paragraph {
975 span: None,
976 children: vec![
977 text("See "),
978 Link {
979 url: "https://example.com".into(),
980 children: vec![text("here")],
981 ..Link::default()
982 }
983 .into(),
984 ],
985 }
986 .into(),
987 Custom {
988 kind: "mermaid".into(),
989 attrs: BTreeMap::from([("source".into(), json!("graph TD; A-->B"))]),
990 ..Custom::default()
991 }
992 .into(),
993 ];
994 doc
995 }
996
997 #[test]
998 fn nodes_are_tagged_by_type_and_omit_empty_fields() {
999 let heading = &sample().children[0];
1000 assert_eq!(
1001 serde_json::to_value(heading).unwrap(),
1002 json!({
1003 "type": "heading",
1004 "span": {"start": 0, "end": 8},
1005 "level": 1,
1006 "id": "intro",
1007 "children": [{"type": "text", "value": "Intro"}],
1008 })
1009 );
1010 }
1011
1012 #[test]
1013 fn json_round_trip() {
1014 let doc = sample();
1015 let json = serde_json::to_string(&doc).unwrap();
1016 assert_eq!(serde_json::from_str::<Document>(&json).unwrap(), doc);
1017 }
1018
1019 #[test]
1020 fn missing_optional_fields_and_unknown_fields_are_accepted() {
1021 let node: Node = serde_json::from_value(json!({
1022 "type": "paragraph",
1023 "added_in_a_later_version": true,
1024 }))
1025 .unwrap();
1026 assert_eq!(node, Paragraph::default().into());
1027 }
1028
1029 #[test]
1030 fn kind_matches_the_type_tag() {
1031 for node in sample().descendants() {
1032 let kind = node.kind();
1033 match node {
1034 Node::Custom(c) => assert_eq!(kind, format!("custom:{}", c.kind)),
1035 _ => {
1036 let tag = serde_json::to_value(node).unwrap()["type"].clone();
1037 assert_eq!(json!(kind), tag);
1038 }
1039 }
1040 }
1041 }
1042
1043 #[test]
1044 fn titles_and_plain_text() {
1045 let mut doc = sample();
1046 assert_eq!(doc.title().as_deref(), Some("Intro"));
1047 doc.metadata.clear();
1048 doc.children[0] = Heading {
1049 level: 1,
1050 children: vec![
1051 text("A "),
1052 InlineCode {
1053 value: "b".into(),
1054 ..InlineCode::default()
1055 }
1056 .into(),
1057 Image {
1058 alt: " c".into(),
1059 ..Image::default()
1060 }
1061 .into(),
1062 ],
1063 ..Heading::default()
1064 }
1065 .into();
1066 assert_eq!(doc.title().as_deref(), Some("A b c"));
1067 assert_eq!(Document::new("x.md").title(), None);
1068 }
1069
1070 #[test]
1071 fn nodes_decode_whatever_the_key_order() {
1072 let tag_first =
1073 json!({"type": "heading", "level": 2, "children": [{"type": "text", "value": "A"}]});
1074 let tag_last =
1075 json!({"level": 2, "children": [{"value": "A", "type": "text"}], "type": "heading"});
1076 let a: Node = serde_json::from_value(tag_first).unwrap();
1077 let b: Node = serde_json::from_value(tag_last).unwrap();
1078 assert_eq!(a, b);
1079 assert_eq!(a.kind(), "heading");
1080 let bad = serde_json::from_value::<Node>(json!({"type": "nope"})).unwrap_err();
1081 assert!(bad.to_string().contains("unknown variant `nope`"), "{bad}");
1082 let missing = serde_json::from_value::<Node>(json!({"level": 1})).unwrap_err();
1083 assert!(missing.to_string().contains("type"), "{missing}");
1084 }
1085
1086 #[test]
1087 fn descendants_are_depth_first() {
1088 let kinds: Vec<_> = sample().descendants().map(|n| n.kind()).collect();
1089 assert_eq!(
1090 kinds,
1091 [
1092 "heading",
1093 "text",
1094 "paragraph",
1095 "text",
1096 "link",
1097 "text",
1098 "custom:mermaid"
1099 ]
1100 );
1101 }
1102}