1use std::collections::BTreeMap;
58use std::ops::Range;
59
60use serde::{Deserialize, Serialize};
61
62mod anchor;
63
64pub use anchor::{Anchors, LinkTarget};
65
66#[derive(
71 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
72)]
73pub struct NodeId(u32);
74
75impl NodeId {
76 pub const UNASSIGNED: NodeId = NodeId(0);
78
79 pub fn get(self) -> u32 {
81 self.0
82 }
83
84 pub fn new(id: u32) -> NodeId {
89 NodeId(id)
90 }
91
92 pub(crate) fn shifted(self, step: i64) -> NodeId {
97 if self == NodeId::UNASSIGNED {
98 return self;
99 }
100 if let Some((element, which)) = self.pseudo_element() {
101 return element.shifted(step).pseudo(which);
102 }
103 NodeId((self.0 as i64 + step).max(0) as u32)
104 }
105
106 pub(crate) fn pseudo(self, which: PseudoElement) -> NodeId {
109 let kind = match which {
110 PseudoElement::Before => 0,
111 PseudoElement::After => 1,
112 PseudoElement::FirstLetter => 2,
113 PseudoElement::FirstLine => 3,
114 };
115 NodeId(PSEUDO | (self.0 << 2) | kind)
116 }
117
118 pub fn pseudo_element(self) -> Option<(NodeId, PseudoElement)> {
121 if self.0 & PSEUDO == 0 {
122 return None;
123 }
124 let which = match self.0 & 3 {
125 0 => PseudoElement::Before,
126 1 => PseudoElement::After,
127 2 => PseudoElement::FirstLetter,
128 _ => PseudoElement::FirstLine,
129 };
130 Some((NodeId((self.0 & !PSEUDO) >> 2), which))
131 }
132
133 pub fn element(self) -> NodeId {
136 self.pseudo_element().map_or(self, |(element, _)| element)
137 }
138}
139
140const PSEUDO: u32 = 1 << 31;
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
147pub enum PseudoElement {
148 Before,
151 After,
154 FirstLetter,
156 FirstLine,
158}
159
160#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
167pub struct SourceRange {
168 pub node: NodeId,
170 pub range: Range<u32>,
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
182pub struct SourceSpan {
183 pub start: u32,
185 pub end: u32,
187}
188
189impl SourceSpan {
190 pub fn covers(self, byte: u32) -> bool {
194 (self.start..self.end).contains(&byte)
195 }
196
197 pub(crate) fn width(self) -> u32 {
199 self.end.saturating_sub(self.start)
200 }
201}
202
203#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
210pub struct Attributes {
211 #[serde(default, skip_serializing_if = "Option::is_none")]
213 pub id: Option<String>,
214 #[serde(default, skip_serializing_if = "Vec::is_empty")]
217 pub classes: Vec<String>,
218}
219
220impl Attributes {
221 pub fn is_empty(&self) -> bool {
224 self.id.is_none() && self.classes.is_empty()
225 }
226}
227
228#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
231pub struct Names {
232 pub classes: Vec<String>,
234 pub ids: Vec<String>,
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
243pub struct SourcePos {
244 pub line: u32,
246 pub column: u32,
248}
249
250pub fn origin(source: Option<&str>, position: Option<SourcePos>) -> String {
254 match (source, position) {
255 (Some(file), Some(pos)) => format!("{file}:{}:{}", pos.line, pos.column),
256 (Some(file), None) => file.to_string(),
257 (None, Some(pos)) => format!("{}:{}", pos.line, pos.column),
258 (None, None) => String::new(),
259 }
260}
261
262#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
264pub struct Metadata {
265 #[serde(skip_serializing_if = "Option::is_none")]
267 pub title: Option<String>,
268 #[serde(skip_serializing_if = "Option::is_none")]
270 pub author: Option<String>,
271 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
279 pub extra: BTreeMap<String, String>,
280}
281
282impl Metadata {
283 pub fn language(&self) -> Option<&str> {
287 self.extra
288 .get("language")
289 .map(|tag| tag.trim())
290 .filter(|tag| !tag.is_empty())
291 }
292}
293
294#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
296pub struct Book {
297 pub metadata: Metadata,
299 pub sections: Vec<Section>,
301}
302
303#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
306pub struct Section {
307 #[serde(skip)]
309 pub id: NodeId,
310 #[serde(skip_serializing_if = "Option::is_none")]
312 pub source: Option<String>,
313 #[serde(skip_serializing_if = "Option::is_none")]
316 pub title: Option<String>,
317 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
321 pub attributes: Attributes,
322 pub blocks: Vec<Block>,
324 #[serde(skip_serializing_if = "Option::is_none")]
326 pub position: Option<SourcePos>,
327 #[serde(skip_serializing_if = "Option::is_none")]
329 pub span: Option<SourceSpan>,
330}
331
332#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
334#[serde(tag = "type", rename_all = "snake_case")]
335pub enum Block {
336 Heading {
338 #[serde(skip)]
340 id: NodeId,
341 level: HeadingLevel,
343 inlines: Vec<Inline>,
345 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
347 attributes: Attributes,
348 #[serde(skip_serializing_if = "Option::is_none")]
350 position: Option<SourcePos>,
351 #[serde(skip_serializing_if = "Option::is_none")]
353 span: Option<SourceSpan>,
354 },
355 Paragraph {
357 #[serde(skip)]
359 id: NodeId,
360 inlines: Vec<Inline>,
362 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
364 attributes: Attributes,
365 #[serde(skip_serializing_if = "Option::is_none")]
367 position: Option<SourcePos>,
368 #[serde(skip_serializing_if = "Option::is_none")]
370 span: Option<SourceSpan>,
371 },
372 Blockquote {
375 #[serde(skip)]
377 id: NodeId,
378 blocks: Vec<Block>,
380 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
382 attributes: Attributes,
383 #[serde(skip_serializing_if = "Option::is_none")]
385 position: Option<SourcePos>,
386 #[serde(skip_serializing_if = "Option::is_none")]
388 span: Option<SourceSpan>,
389 },
390 CodeBlock {
396 #[serde(skip)]
398 id: NodeId,
399 #[serde(default, skip_serializing_if = "Option::is_none")]
403 info: Option<String>,
404 text: String,
406 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
408 attributes: Attributes,
409 #[serde(skip_serializing_if = "Option::is_none")]
411 position: Option<SourcePos>,
412 #[serde(skip_serializing_if = "Option::is_none")]
414 span: Option<SourceSpan>,
415 },
416 ThematicBreak {
418 #[serde(skip)]
420 id: NodeId,
421 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
423 attributes: Attributes,
424 #[serde(skip_serializing_if = "Option::is_none")]
426 position: Option<SourcePos>,
427 #[serde(skip_serializing_if = "Option::is_none")]
429 span: Option<SourceSpan>,
430 },
431 PageBreak {
434 #[serde(skip)]
436 id: NodeId,
437 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
439 attributes: Attributes,
440 #[serde(skip_serializing_if = "Option::is_none")]
442 position: Option<SourcePos>,
443 #[serde(skip_serializing_if = "Option::is_none")]
445 span: Option<SourceSpan>,
446 },
447 ColumnBreak {
450 #[serde(skip)]
452 id: NodeId,
453 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
455 attributes: Attributes,
456 #[serde(skip_serializing_if = "Option::is_none")]
458 position: Option<SourcePos>,
459 #[serde(skip_serializing_if = "Option::is_none")]
461 span: Option<SourceSpan>,
462 },
463 Image {
465 #[serde(skip)]
467 id: NodeId,
468 url: String,
470 alt: String,
473 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
475 attributes: Attributes,
476 #[serde(skip_serializing_if = "Option::is_none")]
478 position: Option<SourcePos>,
479 #[serde(skip_serializing_if = "Option::is_none")]
481 span: Option<SourceSpan>,
482 },
483 List {
486 #[serde(skip)]
488 id: NodeId,
489 #[serde(default)]
491 ordered: bool,
492 #[serde(default = "first_number", skip_serializing_if = "is_first_number")]
494 start: u32,
495 #[serde(default)]
499 tight: bool,
500 #[serde(default)]
502 items: Vec<ListItem>,
503 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
505 attributes: Attributes,
506 #[serde(skip_serializing_if = "Option::is_none")]
508 position: Option<SourcePos>,
509 #[serde(skip_serializing_if = "Option::is_none")]
511 span: Option<SourceSpan>,
512 },
513 Table {
515 #[serde(skip)]
517 id: NodeId,
518 #[serde(default)]
520 head: Vec<Row>,
521 #[serde(default)]
523 body: Vec<Row>,
524 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
526 attributes: Attributes,
527 #[serde(skip_serializing_if = "Option::is_none")]
529 position: Option<SourcePos>,
530 #[serde(skip_serializing_if = "Option::is_none")]
532 span: Option<SourceSpan>,
533 },
534}
535
536#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
538#[serde(into = "u8", try_from = "u8")]
539pub enum HeadingLevel {
540 H1,
542 H2,
544 H3,
546 H4,
548 H5,
550 H6,
552}
553
554impl From<HeadingLevel> for u8 {
555 fn from(level: HeadingLevel) -> u8 {
556 match level {
557 HeadingLevel::H1 => 1,
558 HeadingLevel::H2 => 2,
559 HeadingLevel::H3 => 3,
560 HeadingLevel::H4 => 4,
561 HeadingLevel::H5 => 5,
562 HeadingLevel::H6 => 6,
563 }
564 }
565}
566
567impl TryFrom<u8> for HeadingLevel {
568 type Error = InvalidHeadingLevel;
569
570 fn try_from(value: u8) -> Result<Self, Self::Error> {
571 match value {
572 1 => Ok(HeadingLevel::H1),
573 2 => Ok(HeadingLevel::H2),
574 3 => Ok(HeadingLevel::H3),
575 4 => Ok(HeadingLevel::H4),
576 5 => Ok(HeadingLevel::H5),
577 6 => Ok(HeadingLevel::H6),
578 _ => Err(InvalidHeadingLevel(value)),
579 }
580 }
581}
582
583#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
585#[error("heading level must be 1-6, got {0}")]
586pub struct InvalidHeadingLevel(pub u8);
587
588fn first_number() -> u32 {
590 1
591}
592
593fn is_first_number(start: &u32) -> bool {
594 *start == 1
595}
596
597#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
599pub struct ListItem {
600 #[serde(skip)]
602 pub id: NodeId,
603 #[serde(default)]
605 pub blocks: Vec<Block>,
606 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
608 pub attributes: Attributes,
609 #[serde(skip_serializing_if = "Option::is_none")]
611 pub position: Option<SourcePos>,
612 #[serde(skip_serializing_if = "Option::is_none")]
614 pub span: Option<SourceSpan>,
615}
616
617pub fn item_blocks(items: &[ListItem]) -> impl Iterator<Item = &[Block]> {
619 items.iter().map(|item| item.blocks.as_slice())
620}
621
622#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
624pub struct Row {
625 #[serde(skip)]
627 pub id: NodeId,
628 #[serde(default)]
631 pub cells: Vec<Cell>,
632 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
634 pub attributes: Attributes,
635 #[serde(skip_serializing_if = "Option::is_none")]
637 pub position: Option<SourcePos>,
638 #[serde(skip_serializing_if = "Option::is_none")]
640 pub span: Option<SourceSpan>,
641}
642
643#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
645pub struct Cell {
646 #[serde(skip)]
648 pub id: NodeId,
649 #[serde(default)]
651 pub blocks: Vec<Block>,
652 #[serde(default, skip_serializing_if = "Option::is_none")]
655 pub align: Option<Alignment>,
656 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
658 pub attributes: Attributes,
659 #[serde(skip_serializing_if = "Option::is_none")]
661 pub position: Option<SourcePos>,
662 #[serde(skip_serializing_if = "Option::is_none")]
664 pub span: Option<SourceSpan>,
665}
666
667#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
669#[serde(rename_all = "snake_case")]
670pub enum Alignment {
671 Left,
673 Center,
675 Right,
677}
678
679pub fn rows<'a>(head: &'a [Row], body: &'a [Row]) -> impl Iterator<Item = &'a Row> {
681 head.iter().chain(body)
682}
683
684pub fn cell_blocks<'a>(head: &'a [Row], body: &'a [Row]) -> impl Iterator<Item = &'a [Block]> {
687 rows(head, body).flat_map(|row| row.cells.iter().map(|cell| cell.blocks.as_slice()))
688}
689
690#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
692#[serde(tag = "type", rename_all = "snake_case")]
693pub enum Inline {
694 Text {
697 #[serde(skip)]
699 id: NodeId,
700 value: String,
702 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
704 attributes: Attributes,
705 #[serde(skip_serializing_if = "Option::is_none")]
707 position: Option<SourcePos>,
708 #[serde(skip_serializing_if = "Option::is_none")]
710 span: Option<SourceSpan>,
711 },
712 Break {
715 #[serde(skip)]
717 id: NodeId,
718 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
720 attributes: Attributes,
721 #[serde(skip_serializing_if = "Option::is_none")]
723 position: Option<SourcePos>,
724 #[serde(skip_serializing_if = "Option::is_none")]
726 span: Option<SourceSpan>,
727 },
728 Emphasis {
730 #[serde(skip)]
732 id: NodeId,
733 children: Vec<Inline>,
735 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
737 attributes: Attributes,
738 #[serde(skip_serializing_if = "Option::is_none")]
740 position: Option<SourcePos>,
741 #[serde(skip_serializing_if = "Option::is_none")]
743 span: Option<SourceSpan>,
744 },
745 Strong {
747 #[serde(skip)]
749 id: NodeId,
750 children: Vec<Inline>,
752 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
754 attributes: Attributes,
755 #[serde(skip_serializing_if = "Option::is_none")]
757 position: Option<SourcePos>,
758 #[serde(skip_serializing_if = "Option::is_none")]
760 span: Option<SourceSpan>,
761 },
762 Code {
764 #[serde(skip)]
766 id: NodeId,
767 value: String,
769 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
771 attributes: Attributes,
772 #[serde(skip_serializing_if = "Option::is_none")]
774 position: Option<SourcePos>,
775 #[serde(skip_serializing_if = "Option::is_none")]
777 span: Option<SourceSpan>,
778 },
779 Link {
782 #[serde(skip)]
784 id: NodeId,
785 url: String,
787 children: Vec<Inline>,
789 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
791 attributes: Attributes,
792 #[serde(skip_serializing_if = "Option::is_none")]
794 position: Option<SourcePos>,
795 #[serde(skip_serializing_if = "Option::is_none")]
797 span: Option<SourceSpan>,
798 },
799 Note {
808 #[serde(skip)]
810 id: NodeId,
811 blocks: Vec<Block>,
813 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
815 attributes: Attributes,
816 #[serde(skip_serializing_if = "Option::is_none")]
818 position: Option<SourcePos>,
819 #[serde(skip_serializing_if = "Option::is_none")]
821 span: Option<SourceSpan>,
822 },
823 Strikethrough {
825 #[serde(skip)]
827 id: NodeId,
828 children: Vec<Inline>,
830 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
832 attributes: Attributes,
833 #[serde(skip_serializing_if = "Option::is_none")]
835 position: Option<SourcePos>,
836 #[serde(skip_serializing_if = "Option::is_none")]
838 span: Option<SourceSpan>,
839 },
840 Highlight {
842 #[serde(skip)]
844 id: NodeId,
845 children: Vec<Inline>,
847 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
849 attributes: Attributes,
850 #[serde(skip_serializing_if = "Option::is_none")]
852 position: Option<SourcePos>,
853 #[serde(skip_serializing_if = "Option::is_none")]
855 span: Option<SourceSpan>,
856 },
857 Span {
861 #[serde(skip)]
863 id: NodeId,
864 children: Vec<Inline>,
866 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
868 attributes: Attributes,
869 #[serde(skip_serializing_if = "Option::is_none")]
871 position: Option<SourcePos>,
872 #[serde(skip_serializing_if = "Option::is_none")]
874 span: Option<SourceSpan>,
875 },
876}
877
878pub fn text(inlines: &[Inline]) -> String {
882 let mut out = String::new();
883 push_text(inlines, &mut out);
884 out
885}
886
887fn push_text(inlines: &[Inline], out: &mut String) {
888 for inline in inlines {
889 match inline {
890 Inline::Text { value, .. } | Inline::Code { value, .. } => out.push_str(value),
891 Inline::Break { .. } => out.push('\n'),
892 Inline::Note { .. } => {}
895 Inline::Emphasis { children, .. }
896 | Inline::Strong { children, .. }
897 | Inline::Link { children, .. }
898 | Inline::Strikethrough { children, .. }
899 | Inline::Highlight { children, .. }
900 | Inline::Span { children, .. } => push_text(children, out),
901 }
902 }
903}
904
905impl Book {
906 pub fn assign_node_ids(&mut self) {
910 let mut next = 1u32;
911 for section in &mut self.sections {
912 section.id = next_id(&mut next);
913 for block in &mut section.blocks {
914 assign_block(block, &mut next);
915 }
916 }
917 }
918
919 pub fn node_at(&self, source: &str, byte: u32) -> Option<NodeId> {
929 self.sections
930 .iter()
931 .filter(|section| section.source.as_deref() == Some(source))
932 .find_map(|section| {
933 let span = section.span.filter(|span| span.covers(byte))?;
934 let inner = node_in_blocks(§ion.blocks, byte);
935 let inner = match node_in_notes(§ion.blocks, byte) {
936 Some(note) => Some(narrowest(note, inner)),
937 None => inner,
938 };
939 Some(narrowest((section.id, span), inner))
940 })
941 .map(|(node, _)| node)
942 }
943
944 pub fn source_of(&self, node: NodeId) -> Option<(&str, SourceSpan)> {
950 if node == NodeId::UNASSIGNED {
951 return None;
952 }
953 let at = self
957 .sections
958 .partition_point(|section| section.id.get() <= node.get())
959 .checked_sub(1)?;
960 let section = &self.sections[at];
961 let source = section.source.as_deref()?;
962 let span = if section.id == node {
963 section.span?
964 } else {
965 span_in_blocks(§ion.blocks, node)?
966 };
967 Some((source, span))
968 }
969
970 pub fn names(&self, source: Option<&str>) -> Names {
978 let mut classes = std::collections::BTreeSet::new();
979 let mut ids = std::collections::BTreeSet::new();
980 let mut add = |attributes: &Attributes| {
981 classes.extend(attributes.classes.iter().cloned());
982 ids.extend(attributes.id.iter().cloned());
983 };
984 for section in &self.sections {
985 if source.is_none_or(|source| section.source.as_deref() == Some(source)) {
986 names_in_blocks(§ion.blocks, &mut add);
987 }
988 }
989 Names {
990 classes: classes.into_iter().collect(),
991 ids: ids.into_iter().collect(),
992 }
993 }
994
995 pub fn subtree(&self, node: NodeId) -> Option<Range<u32>> {
1004 if node == NodeId::UNASSIGNED {
1005 return None;
1006 }
1007 let at = self
1008 .sections
1009 .partition_point(|section| section.id.get() <= node.get())
1010 .checked_sub(1)?;
1011 let section = &self.sections[at];
1012 let first = section.id.get();
1013 let count = 1 + section.blocks.iter().map(block_nodes).sum::<u32>();
1014 if section.id == node {
1015 return Some(first..first + count);
1016 }
1017 if !(first..first + count).contains(&node.get()) {
1018 return None;
1019 }
1020 subtree_in_blocks(§ion.blocks, node)
1021 }
1022}
1023
1024fn names_in_blocks(blocks: &[Block], add: &mut impl FnMut(&Attributes)) {
1027 for block in blocks {
1028 add(block_attributes(block));
1029 match block {
1030 Block::Heading { inlines, .. } | Block::Paragraph { inlines, .. } => {
1031 names_in_inlines(inlines, add)
1032 }
1033 Block::Blockquote { blocks, .. } => names_in_blocks(blocks, add),
1034 Block::List { items, .. } => {
1035 for item in items {
1036 add(&item.attributes);
1037 names_in_blocks(&item.blocks, add);
1038 }
1039 }
1040 Block::Table { head, body, .. } => {
1041 for row in rows(head, body) {
1042 add(&row.attributes);
1043 for cell in &row.cells {
1044 add(&cell.attributes);
1045 names_in_blocks(&cell.blocks, add);
1046 }
1047 }
1048 }
1049 Block::CodeBlock { .. }
1050 | Block::ThematicBreak { .. }
1051 | Block::PageBreak { .. }
1052 | Block::ColumnBreak { .. }
1053 | Block::Image { .. } => {}
1054 }
1055 }
1056}
1057
1058fn names_in_inlines(inlines: &[Inline], add: &mut impl FnMut(&Attributes)) {
1060 for inline in inlines {
1061 add(inline_attributes(inline));
1062 match inline {
1063 Inline::Text { .. } | Inline::Code { .. } | Inline::Break { .. } => {}
1064 Inline::Note { blocks, .. } => names_in_blocks(blocks, add),
1065 Inline::Emphasis { children, .. }
1066 | Inline::Strong { children, .. }
1067 | Inline::Link { children, .. }
1068 | Inline::Strikethrough { children, .. }
1069 | Inline::Highlight { children, .. }
1070 | Inline::Span { children, .. } => names_in_inlines(children, add),
1071 }
1072 }
1073}
1074
1075fn subtree_in_blocks(blocks: &[Block], node: NodeId) -> Option<Range<u32>> {
1079 for block in blocks {
1080 let first = block_id(block).get();
1081 let held = first..first + block_nodes(block);
1082 if !held.contains(&node.get()) {
1083 continue;
1084 }
1085 if block_id(block) == node {
1086 return Some(held);
1087 }
1088 return match block {
1089 Block::Heading { inlines, .. } | Block::Paragraph { inlines, .. } => {
1090 subtree_in_inlines(inlines, node)
1091 }
1092 Block::Blockquote { blocks, .. } => subtree_in_blocks(blocks, node),
1093 Block::List { items, .. } => subtree_in_items(items, node),
1094 Block::Table { head, body, .. } => subtree_in_rows(rows(head, body), node),
1095 Block::CodeBlock { .. }
1096 | Block::ThematicBreak { .. }
1097 | Block::PageBreak { .. }
1098 | Block::ColumnBreak { .. }
1099 | Block::Image { .. } => None,
1100 };
1101 }
1102 None
1103}
1104
1105fn subtree_in_items(items: &[ListItem], node: NodeId) -> Option<Range<u32>> {
1107 let item = items
1108 .iter()
1109 .find(|item| (item.id.get()..item.id.get() + item_nodes(item)).contains(&node.get()))?;
1110 if item.id == node {
1111 return Some(item.id.get()..item.id.get() + item_nodes(item));
1112 }
1113 subtree_in_blocks(&item.blocks, node)
1114}
1115
1116fn item_nodes(item: &ListItem) -> u32 {
1118 1 + item.blocks.iter().map(block_nodes).sum::<u32>()
1119}
1120
1121fn subtree_in_inlines(inlines: &[Inline], node: NodeId) -> Option<Range<u32>> {
1123 for inline in inlines {
1124 let first = inline_id(inline).get();
1125 let held = first..first + inline_nodes(inline);
1126 if !held.contains(&node.get()) {
1127 continue;
1128 }
1129 if inline_id(inline) == node {
1130 return Some(held);
1131 }
1132 return match inline {
1133 Inline::Text { .. } | Inline::Code { .. } | Inline::Break { .. } => None,
1134 Inline::Note { blocks, .. } => subtree_in_blocks(blocks, node),
1135 Inline::Emphasis { children, .. }
1136 | Inline::Strong { children, .. }
1137 | Inline::Link { children, .. }
1138 | Inline::Strikethrough { children, .. }
1139 | Inline::Highlight { children, .. }
1140 | Inline::Span { children, .. } => subtree_in_inlines(children, node),
1141 };
1142 }
1143 None
1144}
1145
1146fn block_nodes(block: &Block) -> u32 {
1148 1 + match block {
1149 Block::Heading { inlines, .. } | Block::Paragraph { inlines, .. } => {
1150 inlines.iter().map(inline_nodes).sum()
1151 }
1152 Block::Blockquote { blocks, .. } => blocks.iter().map(block_nodes).sum(),
1153 Block::List { items, .. } => items.iter().map(item_nodes).sum(),
1154 Block::Table { head, body, .. } => rows(head, body).map(row_nodes).sum(),
1155 Block::CodeBlock { .. }
1156 | Block::ThematicBreak { .. }
1157 | Block::PageBreak { .. }
1158 | Block::ColumnBreak { .. }
1159 | Block::Image { .. } => 0,
1160 }
1161}
1162
1163fn row_nodes(row: &Row) -> u32 {
1165 1 + row.cells.iter().map(cell_nodes).sum::<u32>()
1166}
1167
1168fn cell_nodes(cell: &Cell) -> u32 {
1170 1 + cell.blocks.iter().map(block_nodes).sum::<u32>()
1171}
1172
1173fn subtree_in_rows<'a>(rows: impl Iterator<Item = &'a Row>, node: NodeId) -> Option<Range<u32>> {
1175 for row in rows {
1176 let held = row.id.get()..row.id.get() + row_nodes(row);
1177 if !held.contains(&node.get()) {
1178 continue;
1179 }
1180 if row.id == node {
1181 return Some(held);
1182 }
1183 for cell in &row.cells {
1184 let held = cell.id.get()..cell.id.get() + cell_nodes(cell);
1185 if !held.contains(&node.get()) {
1186 continue;
1187 }
1188 if cell.id == node {
1189 return Some(held);
1190 }
1191 return subtree_in_blocks(&cell.blocks, node);
1192 }
1193 return None;
1194 }
1195 None
1196}
1197
1198pub(crate) fn inline_nodes(inline: &Inline) -> u32 {
1200 1 + match inline {
1201 Inline::Text { .. } | Inline::Code { .. } | Inline::Break { .. } => 0,
1202 Inline::Note { blocks, .. } => blocks.iter().map(block_nodes).sum(),
1203 Inline::Emphasis { children, .. }
1204 | Inline::Strong { children, .. }
1205 | Inline::Link { children, .. }
1206 | Inline::Strikethrough { children, .. }
1207 | Inline::Highlight { children, .. }
1208 | Inline::Span { children, .. } => children.iter().map(inline_nodes).sum(),
1209 }
1210}
1211
1212fn narrowest(
1215 node: (NodeId, SourceSpan),
1216 inner: Option<(NodeId, SourceSpan)>,
1217) -> (NodeId, SourceSpan) {
1218 match inner {
1219 Some(inner) if inner.1.width() <= node.1.width() => inner,
1220 _ => node,
1221 }
1222}
1223
1224fn node_in_blocks(blocks: &[Block], byte: u32) -> Option<(NodeId, SourceSpan)> {
1230 let mut found: Option<(NodeId, SourceSpan)> = None;
1231 for block in blocks {
1232 let Some(span) = block_span(block) else {
1233 continue;
1234 };
1235 if span.start > byte {
1236 break;
1237 }
1238 if !span.covers(byte) {
1239 continue;
1240 }
1241 let inner = match block {
1242 Block::Heading { inlines, .. } | Block::Paragraph { inlines, .. } => {
1243 node_in_inlines(inlines, byte)
1244 }
1245 Block::Blockquote { blocks, .. } => node_in_blocks(blocks, byte),
1246 Block::List { items, .. } => node_in_items(items, byte),
1247 Block::Table { head, body, .. } => node_in_rows(rows(head, body), byte),
1248 Block::CodeBlock { .. }
1249 | Block::ThematicBreak { .. }
1250 | Block::PageBreak { .. }
1251 | Block::ColumnBreak { .. }
1252 | Block::Image { .. } => None,
1253 };
1254 let hit = narrowest((block_id(block), span), inner);
1255 if found.is_none_or(|found| hit.1.width() < found.1.width()) {
1256 found = Some(hit);
1257 }
1258 }
1259 found
1260}
1261
1262fn node_in_inlines(inlines: &[Inline], byte: u32) -> Option<(NodeId, SourceSpan)> {
1264 for inline in inlines {
1265 let Some(span) = inline_span(inline) else {
1266 continue;
1267 };
1268 if span.start > byte {
1269 break;
1270 }
1271 if !span.covers(byte) {
1272 continue;
1273 }
1274 let inner = match inline {
1275 Inline::Text { .. }
1279 | Inline::Code { .. }
1280 | Inline::Break { .. }
1281 | Inline::Note { .. } => None,
1282 Inline::Emphasis { children, .. }
1283 | Inline::Strong { children, .. }
1284 | Inline::Link { children, .. }
1285 | Inline::Strikethrough { children, .. }
1286 | Inline::Highlight { children, .. }
1287 | Inline::Span { children, .. } => node_in_inlines(children, byte),
1288 };
1289 return Some(narrowest((inline_id(inline), span), inner));
1290 }
1291 None
1292}
1293
1294pub fn notes_in_blocks(blocks: &[Block]) -> Vec<&Inline> {
1297 let mut out = Vec::new();
1298 gather_notes_in_blocks(blocks, &mut out);
1299 out
1300}
1301
1302pub fn notes_in_inlines(inlines: &[Inline]) -> Vec<&Inline> {
1305 let mut out = Vec::new();
1306 shallow_notes_in_inlines(inlines, &mut out);
1307 out
1308}
1309
1310fn shallow_notes_in_inlines<'b>(inlines: &'b [Inline], out: &mut Vec<&'b Inline>) {
1311 for inline in inlines {
1312 match inline {
1313 Inline::Note { .. } => out.push(inline),
1314 Inline::Emphasis { children, .. }
1315 | Inline::Strong { children, .. }
1316 | Inline::Link { children, .. }
1317 | Inline::Strikethrough { children, .. }
1318 | Inline::Highlight { children, .. }
1319 | Inline::Span { children, .. } => shallow_notes_in_inlines(children, out),
1320 Inline::Text { .. } | Inline::Code { .. } | Inline::Break { .. } => {}
1321 }
1322 }
1323}
1324
1325fn gather_notes_in_blocks<'b>(blocks: &'b [Block], out: &mut Vec<&'b Inline>) {
1326 for block in blocks {
1327 match block {
1328 Block::Heading { inlines, .. } | Block::Paragraph { inlines, .. } => {
1329 gather_notes_in_inlines(inlines, out)
1330 }
1331 Block::Blockquote { blocks, .. } => gather_notes_in_blocks(blocks, out),
1332 Block::List { items, .. } => {
1333 for item in items {
1334 gather_notes_in_blocks(&item.blocks, out);
1335 }
1336 }
1337 Block::Table { head, body, .. } => {
1338 for blocks in cell_blocks(head, body) {
1339 gather_notes_in_blocks(blocks, out);
1340 }
1341 }
1342 Block::CodeBlock { .. }
1343 | Block::ThematicBreak { .. }
1344 | Block::PageBreak { .. }
1345 | Block::ColumnBreak { .. }
1346 | Block::Image { .. } => {}
1347 }
1348 }
1349}
1350
1351fn gather_notes_in_inlines<'b>(inlines: &'b [Inline], out: &mut Vec<&'b Inline>) {
1352 for inline in inlines {
1353 match inline {
1354 Inline::Note { blocks, .. } => {
1355 out.push(inline);
1356 gather_notes_in_blocks(blocks, out);
1357 }
1358 Inline::Emphasis { children, .. }
1359 | Inline::Strong { children, .. }
1360 | Inline::Link { children, .. }
1361 | Inline::Strikethrough { children, .. }
1362 | Inline::Highlight { children, .. }
1363 | Inline::Span { children, .. } => gather_notes_in_inlines(children, out),
1364 Inline::Text { .. } | Inline::Code { .. } | Inline::Break { .. } => {}
1365 }
1366 }
1367}
1368
1369fn node_in_notes(blocks: &[Block], byte: u32) -> Option<(NodeId, SourceSpan)> {
1377 let mut found: Option<(NodeId, SourceSpan)> = None;
1378 for note in notes_in_blocks(blocks) {
1379 let Inline::Note { id, blocks, .. } = note else {
1380 continue;
1381 };
1382 let Some(hit) = node_in_blocks(blocks, byte) else {
1383 continue;
1384 };
1385 let hit = match inline_span(note) {
1386 Some(span) if span.covers(byte) => narrowest((*id, span), Some(hit)),
1387 _ => hit,
1388 };
1389 if found.is_none_or(|found| hit.1.width() < found.1.width()) {
1390 found = Some(hit);
1391 }
1392 }
1393 found
1394}
1395
1396fn span_in_blocks(blocks: &[Block], node: NodeId) -> Option<SourceSpan> {
1398 for block in blocks {
1399 if block_id(block) == node {
1400 return block_span(block);
1401 }
1402 let found = match block {
1403 Block::Heading { inlines, .. } | Block::Paragraph { inlines, .. } => {
1404 span_in_inlines(inlines, node)
1405 }
1406 Block::Blockquote { blocks, .. } => span_in_blocks(blocks, node),
1407 Block::List { items, .. } => span_in_items(items, node),
1408 Block::Table { head, body, .. } => span_in_rows(rows(head, body), node),
1409 Block::CodeBlock { .. }
1410 | Block::ThematicBreak { .. }
1411 | Block::PageBreak { .. }
1412 | Block::ColumnBreak { .. }
1413 | Block::Image { .. } => None,
1414 };
1415 if found.is_some() {
1416 return found;
1417 }
1418 }
1419 None
1420}
1421
1422fn node_in_items(items: &[ListItem], byte: u32) -> Option<(NodeId, SourceSpan)> {
1425 items.iter().find_map(|item| {
1426 let span = item.span.filter(|span| span.covers(byte))?;
1427 Some(narrowest(
1428 (item.id, span),
1429 node_in_blocks(&item.blocks, byte),
1430 ))
1431 })
1432}
1433
1434fn span_in_items(items: &[ListItem], node: NodeId) -> Option<SourceSpan> {
1436 items.iter().find_map(|item| {
1437 if item.id == node {
1438 item.span
1439 } else {
1440 span_in_blocks(&item.blocks, node)
1441 }
1442 })
1443}
1444
1445fn span_in_inlines(inlines: &[Inline], node: NodeId) -> Option<SourceSpan> {
1447 for inline in inlines {
1448 if inline_id(inline) == node {
1449 return inline_span(inline);
1450 }
1451 let found = match inline {
1452 Inline::Text { .. } | Inline::Code { .. } | Inline::Break { .. } => None,
1453 Inline::Note { blocks, .. } => span_in_blocks(blocks, node),
1454 Inline::Emphasis { children, .. }
1455 | Inline::Strong { children, .. }
1456 | Inline::Link { children, .. }
1457 | Inline::Strikethrough { children, .. }
1458 | Inline::Highlight { children, .. }
1459 | Inline::Span { children, .. } => span_in_inlines(children, node),
1460 };
1461 if found.is_some() {
1462 return found;
1463 }
1464 }
1465 None
1466}
1467
1468fn node_in_rows<'a>(
1471 rows: impl Iterator<Item = &'a Row>,
1472 byte: u32,
1473) -> Option<(NodeId, SourceSpan)> {
1474 for row in rows {
1475 let Some(span) = row.span.filter(|span| span.covers(byte)) else {
1476 continue;
1477 };
1478 let inner = row.cells.iter().find_map(|cell| {
1479 let span = cell.span.filter(|span| span.covers(byte))?;
1480 Some(narrowest(
1481 (cell.id, span),
1482 node_in_blocks(&cell.blocks, byte),
1483 ))
1484 });
1485 return Some(narrowest((row.id, span), inner));
1486 }
1487 None
1488}
1489
1490fn span_in_rows<'a>(rows: impl Iterator<Item = &'a Row>, node: NodeId) -> Option<SourceSpan> {
1492 for row in rows {
1493 if row.id == node {
1494 return row.span;
1495 }
1496 for cell in &row.cells {
1497 if cell.id == node {
1498 return cell.span;
1499 }
1500 let found = span_in_blocks(&cell.blocks, node);
1501 if found.is_some() {
1502 return found;
1503 }
1504 }
1505 }
1506 None
1507}
1508
1509pub fn block_attributes(block: &Block) -> &Attributes {
1511 match block {
1512 Block::Heading { attributes, .. }
1513 | Block::Paragraph { attributes, .. }
1514 | Block::Blockquote { attributes, .. }
1515 | Block::ThematicBreak { attributes, .. }
1516 | Block::PageBreak { attributes, .. }
1517 | Block::ColumnBreak { attributes, .. }
1518 | Block::Image { attributes, .. }
1519 | Block::List { attributes, .. }
1520 | Block::CodeBlock { attributes, .. }
1521 | Block::Table { attributes, .. } => attributes,
1522 }
1523}
1524
1525pub fn inline_attributes(inline: &Inline) -> &Attributes {
1527 match inline {
1528 Inline::Text { attributes, .. }
1529 | Inline::Code { attributes, .. }
1530 | Inline::Break { attributes, .. }
1531 | Inline::Emphasis { attributes, .. }
1532 | Inline::Strong { attributes, .. }
1533 | Inline::Link { attributes, .. }
1534 | Inline::Note { attributes, .. }
1535 | Inline::Strikethrough { attributes, .. }
1536 | Inline::Highlight { attributes, .. }
1537 | Inline::Span { attributes, .. } => attributes,
1538 }
1539}
1540
1541pub fn block_position(block: &Block) -> Option<SourcePos> {
1543 match block {
1544 Block::Heading { position, .. }
1545 | Block::Paragraph { position, .. }
1546 | Block::Blockquote { position, .. }
1547 | Block::ThematicBreak { position, .. }
1548 | Block::PageBreak { position, .. }
1549 | Block::ColumnBreak { position, .. }
1550 | Block::Image { position, .. }
1551 | Block::List { position, .. }
1552 | Block::CodeBlock { position, .. }
1553 | Block::Table { position, .. } => *position,
1554 }
1555}
1556
1557pub fn inline_position(inline: &Inline) -> Option<SourcePos> {
1559 match inline {
1560 Inline::Text { position, .. }
1561 | Inline::Code { position, .. }
1562 | Inline::Break { position, .. }
1563 | Inline::Emphasis { position, .. }
1564 | Inline::Strong { position, .. }
1565 | Inline::Link { position, .. }
1566 | Inline::Note { position, .. }
1567 | Inline::Strikethrough { position, .. }
1568 | Inline::Highlight { position, .. }
1569 | Inline::Span { position, .. } => *position,
1570 }
1571}
1572
1573pub fn block_id(block: &Block) -> NodeId {
1575 match block {
1576 Block::Heading { id, .. }
1577 | Block::Paragraph { id, .. }
1578 | Block::Blockquote { id, .. }
1579 | Block::ThematicBreak { id, .. }
1580 | Block::PageBreak { id, .. }
1581 | Block::ColumnBreak { id, .. }
1582 | Block::Image { id, .. }
1583 | Block::List { id, .. }
1584 | Block::CodeBlock { id, .. }
1585 | Block::Table { id, .. } => *id,
1586 }
1587}
1588
1589pub fn block_span(block: &Block) -> Option<SourceSpan> {
1591 match block {
1592 Block::Heading { span, .. }
1593 | Block::Paragraph { span, .. }
1594 | Block::Blockquote { span, .. }
1595 | Block::ThematicBreak { span, .. }
1596 | Block::PageBreak { span, .. }
1597 | Block::ColumnBreak { span, .. }
1598 | Block::Image { span, .. }
1599 | Block::List { span, .. }
1600 | Block::CodeBlock { span, .. }
1601 | Block::Table { span, .. } => *span,
1602 }
1603}
1604
1605pub fn inline_id(inline: &Inline) -> NodeId {
1607 match inline {
1608 Inline::Text { id, .. }
1609 | Inline::Code { id, .. }
1610 | Inline::Break { id, .. }
1611 | Inline::Emphasis { id, .. }
1612 | Inline::Strong { id, .. }
1613 | Inline::Link { id, .. }
1614 | Inline::Note { id, .. }
1615 | Inline::Strikethrough { id, .. }
1616 | Inline::Highlight { id, .. }
1617 | Inline::Span { id, .. } => *id,
1618 }
1619}
1620
1621pub fn inline_span(inline: &Inline) -> Option<SourceSpan> {
1623 match inline {
1624 Inline::Text { span, .. }
1625 | Inline::Code { span, .. }
1626 | Inline::Break { span, .. }
1627 | Inline::Emphasis { span, .. }
1628 | Inline::Strong { span, .. }
1629 | Inline::Link { span, .. }
1630 | Inline::Note { span, .. }
1631 | Inline::Strikethrough { span, .. }
1632 | Inline::Highlight { span, .. }
1633 | Inline::Span { span, .. } => *span,
1634 }
1635}
1636
1637fn next_id(next: &mut u32) -> NodeId {
1638 let id = NodeId(*next);
1639 *next += 1;
1640 id
1641}
1642
1643fn assign_block(block: &mut Block, next: &mut u32) {
1644 match block {
1645 Block::Heading { id, inlines, .. } | Block::Paragraph { id, inlines, .. } => {
1646 *id = next_id(next);
1647 for inline in inlines {
1648 assign_inline(inline, next);
1649 }
1650 }
1651 Block::Blockquote { id, blocks, .. } => {
1652 *id = next_id(next);
1653 for nested in blocks {
1654 assign_block(nested, next);
1655 }
1656 }
1657 Block::CodeBlock { id, .. }
1658 | Block::ThematicBreak { id, .. }
1659 | Block::PageBreak { id, .. }
1660 | Block::ColumnBreak { id, .. }
1661 | Block::Image { id, .. } => {
1662 *id = next_id(next);
1663 }
1664 Block::List { id, items, .. } => {
1665 *id = next_id(next);
1666 for item in items {
1667 item.id = next_id(next);
1668 for nested in &mut item.blocks {
1669 assign_block(nested, next);
1670 }
1671 }
1672 }
1673 Block::Table { id, head, body, .. } => {
1674 *id = next_id(next);
1675 for row in head.iter_mut().chain(body.iter_mut()) {
1676 row.id = next_id(next);
1677 for cell in &mut row.cells {
1678 cell.id = next_id(next);
1679 for nested in &mut cell.blocks {
1680 assign_block(nested, next);
1681 }
1682 }
1683 }
1684 }
1685 }
1686}
1687
1688fn assign_inline(inline: &mut Inline, next: &mut u32) {
1689 match inline {
1690 Inline::Text { id, .. } | Inline::Code { id, .. } | Inline::Break { id, .. } => {
1691 *id = next_id(next);
1692 }
1693 Inline::Note { id, blocks, .. } => {
1694 *id = next_id(next);
1695 for block in blocks {
1696 assign_block(block, next);
1697 }
1698 }
1699 Inline::Emphasis { id, children, .. }
1700 | Inline::Strong { id, children, .. }
1701 | Inline::Link { id, children, .. }
1702 | Inline::Strikethrough { id, children, .. }
1703 | Inline::Highlight { id, children, .. }
1704 | Inline::Span { id, children, .. } => {
1705 *id = next_id(next);
1706 for child in children {
1707 assign_inline(child, next);
1708 }
1709 }
1710 }
1711}
1712
1713#[cfg(test)]
1714mod tests {
1715 use super::*;
1716
1717 #[test]
1721 fn a_pseudo_element_maps_to_its_element_and_moves_with_it() {
1722 let element = NodeId::new(40);
1723 let kinds = [
1724 PseudoElement::Before,
1725 PseudoElement::After,
1726 PseudoElement::FirstLetter,
1727 PseudoElement::FirstLine,
1728 ];
1729 let ids: Vec<NodeId> = kinds.iter().map(|which| element.pseudo(*which)).collect();
1730 for (id, which) in ids.iter().zip(kinds) {
1731 assert_eq!(id.pseudo_element(), Some((element, which)));
1732 assert_eq!(id.element(), element);
1733 assert!(id.get() >= 1 << 31, "{id:?} is in the range of content ids");
1734 assert_eq!(
1735 id.shifted(-3).pseudo_element(),
1736 Some((NodeId::new(37), which))
1737 );
1738 assert_eq!(ids.iter().filter(|other| *other == id).count(), 1);
1739 }
1740 assert_eq!(element.pseudo_element(), None);
1741 assert_eq!(element.element(), element);
1742 assert_eq!(element.shifted(-3).pseudo_element(), None);
1743 }
1744
1745 const SOURCE: &str = "\
1748# Chapter One
1749
1750It was the kind of morning that made you suspicious — too *clean*, too quiet.
1751
1752> \"Nobody's early here.\"
1753
1754---
1755
1756
1757
17581. A watch
17592. A purse
1760
1761| Pocket | Found |
1762|:---|---:|
1763| Right | A handkerchief |
1764";
1765
1766 fn span(of: &str) -> Option<SourceSpan> {
1768 let start = SOURCE.find(of).expect("the sample source has it");
1769 Some(SourceSpan {
1770 start: start as u32,
1771 end: (start + of.len()) as u32,
1772 })
1773 }
1774
1775 fn text(value: &str) -> Inline {
1778 Inline::Text {
1779 id: NodeId::UNASSIGNED,
1780 value: value.into(),
1781 attributes: Attributes::default(),
1782 position: None,
1783 span: span(value),
1784 }
1785 }
1786
1787 fn item(line: &str, value: &str) -> ListItem {
1790 ListItem {
1791 blocks: vec![Block::Paragraph {
1792 id: NodeId::UNASSIGNED,
1793 inlines: vec![text(value)],
1794 attributes: Attributes::default(),
1795 position: None,
1796 span: span(value),
1797 }],
1798 span: span(line),
1799 ..ListItem::default()
1800 }
1801 }
1802
1803 #[test]
1806 fn a_list_serializes_as_items_of_blocks() {
1807 let list = sample_book().sections[0].blocks[5].clone();
1808 let json = serde_json::to_value(&list).unwrap();
1809 assert_eq!(json["type"], "list");
1810 assert_eq!(json["ordered"], true);
1811 assert_eq!(json["tight"], true);
1812 assert!(json.get("start").is_none(), "{json}");
1813 assert_eq!(
1814 json["items"][1]["blocks"][0]["inlines"][0]["value"],
1815 "A purse"
1816 );
1817
1818 let Block::List {
1819 ordered,
1820 tight,
1821 items,
1822 attributes,
1823 position,
1824 span,
1825 ..
1826 } = list
1827 else {
1828 panic!("the sixth block is a list");
1829 };
1830 let seventh = Block::List {
1831 id: NodeId::UNASSIGNED,
1832 ordered,
1833 start: 7,
1834 tight,
1835 items,
1836 attributes,
1837 position,
1838 span,
1839 };
1840 let json = serde_json::to_value(&seventh).unwrap();
1841 assert_eq!(json["start"], 7);
1842 let read: Block = serde_json::from_value(json).unwrap();
1843 assert_eq!(read, seventh);
1844 }
1845
1846 #[test]
1851 fn a_list_numbers_its_items_and_a_byte_of_one_answers_with_its_run() {
1852 let mut book = sample_book();
1853 book.assign_node_ids();
1854 let Block::List { id, items, .. } = &book.sections[0].blocks[5] else {
1855 panic!("the sixth block is a list");
1856 };
1857 assert!(*id < items[0].id);
1858 assert!(items[0].id < block_id(&items[0].blocks[0]));
1859 assert!(block_id(&items[0].blocks[0]) < items[1].id);
1860 let held = book.subtree(*id).expect("the book holds the list");
1861 assert!(held.contains(&block_id(&items[1].blocks[0]).get()));
1862
1863 let Block::Paragraph { inlines, .. } = &items[1].blocks[0] else {
1864 panic!("the item holds a paragraph");
1865 };
1866 let byte = SOURCE.find("purse").unwrap() as u32;
1867 assert_eq!(
1868 book.node_at("chapter-01.md", byte),
1869 Some(inline_id(&inlines[0]))
1870 );
1871 let marker = SOURCE.find("2. A purse").unwrap() as u32;
1872 assert_eq!(book.node_at("chapter-01.md", marker), Some(items[1].id));
1873 }
1874
1875 fn row(line: &str, cells: Vec<Cell>) -> Row {
1877 Row {
1878 cells,
1879 span: span(line),
1880 ..Row::default()
1881 }
1882 }
1883
1884 fn cell(value: &str, align: Alignment) -> Cell {
1887 Cell {
1888 blocks: vec![Block::Paragraph {
1889 id: NodeId::UNASSIGNED,
1890 inlines: vec![text(value)],
1891 attributes: Attributes::default(),
1892 position: None,
1893 span: span(value),
1894 }],
1895 align: Some(align),
1896 span: span(value),
1897 ..Cell::default()
1898 }
1899 }
1900
1901 fn table(book: &Book) -> (&[Row], &[Row]) {
1903 let Some(Block::Table { head, body, .. }) = book.sections[0].blocks.last() else {
1904 panic!("the sample book ends with a table");
1905 };
1906 (head, body)
1907 }
1908
1909 #[test]
1913 fn a_table_serializes_as_rows_of_cells() {
1914 let json = serde_json::to_value(sample_book().sections[0].blocks.last()).unwrap();
1915 assert_eq!(json["type"], "table");
1916 assert_eq!(json["head"][0]["cells"][1]["align"], "right");
1917 assert_eq!(
1918 json["body"][0]["cells"][1]["blocks"][0],
1919 serde_json::json!({
1920 "type": "paragraph",
1921 "inlines": [{"type": "text", "value": "A handkerchief", "span": {
1922 "start": SOURCE.find("A handkerchief").unwrap(),
1923 "end": SOURCE.find("A handkerchief").unwrap() + "A handkerchief".len(),
1924 }}],
1925 "span": {
1926 "start": SOURCE.find("A handkerchief").unwrap(),
1927 "end": SOURCE.find("A handkerchief").unwrap() + "A handkerchief".len(),
1928 },
1929 }),
1930 );
1931 }
1932
1933 #[test]
1937 fn a_table_numbers_its_rows_and_cells_in_reading_order() {
1938 let mut book = sample_book();
1939 book.assign_node_ids();
1940 let table_id = block_id(book.sections[0].blocks.last().unwrap());
1941 let (head, body) = table(&book);
1942 let header = &head[0];
1943 let first = &body[0];
1944 assert!(table_id < header.id);
1945 assert!(header.id < header.cells[0].id);
1946 assert!(header.cells[0].id < block_id(&header.cells[0].blocks[0]));
1947 assert!(block_id(&header.cells[1].blocks[0]) < first.id);
1948 assert!(first.id < first.cells[1].id);
1949
1950 let held = book.subtree(first.id).expect("the book holds the row");
1952 assert_eq!(held.start, first.id.get());
1953 assert!(held.contains(&block_id(&first.cells[1].blocks[0]).get()));
1954 assert_eq!(
1955 book.subtree(table_id).map(|held| held.end),
1956 book.subtree(book.sections[0].id).map(|held| held.end),
1957 "the table is the last node of the book",
1958 );
1959 }
1960
1961 #[test]
1964 fn a_byte_of_a_cell_answers_with_the_run_written_there() {
1965 let mut book = sample_book();
1966 book.assign_node_ids();
1967 let (_, body) = table(&book);
1968 let Block::Paragraph { inlines, .. } = &body[0].cells[1].blocks[0] else {
1969 panic!("the cell holds a paragraph");
1970 };
1971 let byte = SOURCE.find("handkerchief").unwrap() as u32;
1972 assert_eq!(
1973 book.node_at("chapter-01.md", byte),
1974 Some(inline_id(&inlines[0]))
1975 );
1976 let pipe = SOURCE.find("| Right").unwrap() as u32;
1977 assert_eq!(book.node_at("chapter-01.md", pipe), Some(body[0].id));
1978 }
1979
1980 #[test]
1985 fn a_tree_the_engine_wrote_reads_back() {
1986 for book in [sample_book(), Book::default()] {
1987 let json = serde_json::to_string(&book).unwrap();
1988 let read: Book = serde_json::from_str(&json).unwrap();
1989 assert_eq!(read, book, "{json}");
1990 }
1991 }
1992
1993 fn sample_book() -> Book {
1994 Book {
1995 metadata: Metadata {
1996 title: Some("The Fixture Book".into()),
1997 author: Some("A. Author".into()),
1998 extra: [("language".to_string(), "en".to_string())]
1999 .into_iter()
2000 .collect(),
2001 },
2002 sections: vec![Section {
2003 attributes: Default::default(),
2004 id: NodeId::UNASSIGNED,
2005 source: Some("chapter-01.md".into()),
2006 title: Some("Chapter One".into()),
2007 blocks: vec![
2008 Block::Heading {
2009 id: NodeId::UNASSIGNED,
2010 level: HeadingLevel::H1,
2011 inlines: vec![text("Chapter One")],
2012 attributes: Attributes::default(),
2013 position: Some(SourcePos { line: 1, column: 1 }),
2014 span: span("# Chapter One\n"),
2015 },
2016 Block::Paragraph {
2017 id: NodeId::UNASSIGNED,
2018 inlines: vec![
2019 text("It was the kind of morning that made you suspicious — too "),
2020 Inline::Emphasis {
2021 id: NodeId::UNASSIGNED,
2022 children: vec![text("clean")],
2023 attributes: Attributes::default(),
2024 position: None,
2025 span: span("*clean*"),
2026 },
2027 text(", too quiet."),
2028 ],
2029 attributes: Attributes::default(),
2030 position: Some(SourcePos { line: 3, column: 1 }),
2031 span: span(
2032 "It was the kind of morning that made you suspicious — too *clean*, too quiet.\n",
2033 ),
2034 },
2035 Block::Blockquote {
2036 id: NodeId::UNASSIGNED,
2037 blocks: vec![Block::Paragraph {
2038 id: NodeId::UNASSIGNED,
2039 inlines: vec![text("\"Nobody's early here.\"")],
2040 attributes: Attributes::default(),
2041 position: None,
2042 span: span("\"Nobody's early here.\"\n"),
2043 }],
2044 attributes: Attributes::default(),
2045 position: Some(SourcePos { line: 5, column: 1 }),
2046 span: span("> \"Nobody's early here.\"\n"),
2047 },
2048 Block::ThematicBreak {
2049 id: NodeId::UNASSIGNED,
2050 attributes: Attributes::default(),
2051 position: Some(SourcePos { line: 7, column: 1 }),
2052 span: span("---\n"),
2053 },
2054 Block::Image {
2055 id: NodeId::UNASSIGNED,
2056 url: "images/drawer.png".into(),
2057 alt: "The drawer of knives".into(),
2058 attributes: Attributes::default(),
2059 position: Some(SourcePos { line: 9, column: 1 }),
2060 span: span(""),
2061 },
2062 Block::List {
2063 id: NodeId::UNASSIGNED,
2064 ordered: true,
2065 start: 1,
2066 tight: true,
2067 items: vec![
2068 item("1. A watch\n", "A watch"),
2069 item("2. A purse\n", "A purse"),
2070 ],
2071 attributes: Attributes::default(),
2072 position: Some(SourcePos {
2073 line: 11,
2074 column: 1,
2075 }),
2076 span: span("1. A watch\n2. A purse\n"),
2077 },
2078 Block::Table {
2079 id: NodeId::UNASSIGNED,
2080 head: vec![row(
2081 "| Pocket | Found |\n",
2082 vec![
2083 cell("Pocket", Alignment::Left),
2084 cell("Found", Alignment::Right),
2085 ],
2086 )],
2087 body: vec![row(
2088 "| Right | A handkerchief |\n",
2089 vec![
2090 cell("Right", Alignment::Left),
2091 cell("A handkerchief", Alignment::Right),
2092 ],
2093 )],
2094 attributes: Attributes::default(),
2095 position: Some(SourcePos {
2096 line: 14,
2097 column: 1,
2098 }),
2099 span: span("| Pocket | Found |\n|:---|---:|\n| Right | A handkerchief |\n"),
2100 },
2101 ],
2102 position: Some(SourcePos { line: 1, column: 1 }),
2103 span: Some(SourceSpan {
2104 start: 0,
2105 end: SOURCE.len() as u32,
2106 }),
2107 }],
2108 }
2109 }
2110
2111 fn collect_ids(book: &Book) -> Vec<NodeId> {
2113 fn walk_block(ids: &mut Vec<NodeId>, block: &Block) {
2114 match block {
2115 Block::Heading { id, inlines, .. } | Block::Paragraph { id, inlines, .. } => {
2116 ids.push(*id);
2117 ids.extend(inlines.iter().flat_map(walk_inline_ids));
2118 }
2119 Block::Blockquote { id, blocks, .. } => {
2120 ids.push(*id);
2121 for nested in blocks {
2122 walk_block(ids, nested);
2123 }
2124 }
2125 Block::CodeBlock { id, .. }
2126 | Block::ThematicBreak { id, .. }
2127 | Block::PageBreak { id, .. }
2128 | Block::ColumnBreak { id, .. }
2129 | Block::Image { id, .. } => ids.push(*id),
2130 Block::List { id, items, .. } => {
2131 ids.push(*id);
2132 for item in items {
2133 ids.push(item.id);
2134 for nested in &item.blocks {
2135 walk_block(ids, nested);
2136 }
2137 }
2138 }
2139 Block::Table { id, head, body, .. } => {
2140 ids.push(*id);
2141 for row in rows(head, body) {
2142 ids.push(row.id);
2143 for cell in &row.cells {
2144 ids.push(cell.id);
2145 for nested in &cell.blocks {
2146 walk_block(ids, nested);
2147 }
2148 }
2149 }
2150 }
2151 }
2152 }
2153
2154 fn walk_inline_ids(inline: &Inline) -> Vec<NodeId> {
2155 match inline {
2156 Inline::Text { id, .. } | Inline::Code { id, .. } | Inline::Break { id, .. } => {
2157 vec![*id]
2158 }
2159 Inline::Note { id, blocks, .. } => {
2160 let mut ids = vec![*id];
2161 for block in blocks {
2162 walk_block(&mut ids, block);
2163 }
2164 ids
2165 }
2166 Inline::Emphasis { id, children, .. }
2167 | Inline::Strong { id, children, .. }
2168 | Inline::Link { id, children, .. }
2169 | Inline::Strikethrough { id, children, .. }
2170 | Inline::Highlight { id, children, .. }
2171 | Inline::Span { id, children, .. } => {
2172 let mut ids = vec![*id];
2173 ids.extend(children.iter().flat_map(walk_inline_ids));
2174 ids
2175 }
2176 }
2177 }
2178
2179 let mut ids = Vec::new();
2180 for section in &book.sections {
2181 ids.push(section.id);
2182 for block in §ion.blocks {
2183 walk_block(&mut ids, block);
2184 }
2185 }
2186 ids
2187 }
2188
2189 #[test]
2192 fn serialization_is_stable() {
2193 let mut book = sample_book();
2194 book.assign_node_ids();
2195 let once = serde_json::to_string_pretty(&book).unwrap();
2196 assert_eq!(once, serde_json::to_string_pretty(&book).unwrap());
2197 }
2198
2199 #[test]
2202 fn ids_are_never_serialized() {
2203 let mut book = sample_book();
2204 book.assign_node_ids();
2205 let json = serde_json::to_string(&book).unwrap();
2206 assert!(!json.contains("\"id\""));
2207 }
2208
2209 #[test]
2212 fn a_serialized_tree_is_internally_tagged() {
2213 let block = Block::Paragraph {
2214 id: NodeId::UNASSIGNED,
2215 inlines: vec![
2216 Inline::Text {
2217 id: NodeId::UNASSIGNED,
2218 value: "plain ".into(),
2219 attributes: Attributes::default(),
2220 position: None,
2221 span: None,
2222 },
2223 Inline::Strong {
2224 id: NodeId::UNASSIGNED,
2225 children: vec![Inline::Text {
2226 id: NodeId::UNASSIGNED,
2227 value: "bold".into(),
2228 attributes: Attributes::default(),
2229 position: None,
2230 span: None,
2231 }],
2232 attributes: Attributes::default(),
2233 position: None,
2234 span: None,
2235 },
2236 ],
2237 attributes: Attributes::default(),
2238 position: Some(SourcePos { line: 4, column: 1 }),
2239 span: Some(SourceSpan { start: 40, end: 58 }),
2240 };
2241 assert_eq!(
2242 serde_json::to_value(&block).unwrap(),
2243 serde_json::json!({
2244 "type": "paragraph",
2245 "inlines": [
2246 {"type": "text", "value": "plain "},
2247 {"type": "strong", "children": [{"type": "text", "value": "bold"}]},
2248 ],
2249 "position": {"line": 4, "column": 1},
2250 "span": {"start": 40, "end": 58},
2251 }),
2252 );
2253 }
2254
2255 #[test]
2259 fn a_hard_break_is_an_inline_of_its_own() {
2260 let words = |value: &str| Inline::Text {
2261 id: NodeId::UNASSIGNED,
2262 value: value.into(),
2263 attributes: Attributes::default(),
2264 position: None,
2265 span: None,
2266 };
2267 let inlines = vec![
2268 words("Chapter One"),
2269 Inline::Break {
2270 id: NodeId::UNASSIGNED,
2271 attributes: Attributes::default(),
2272 position: None,
2273 span: None,
2274 },
2275 words("The Voyage to Lilliput"),
2276 ];
2277 let json = serde_json::to_value(&inlines).unwrap();
2278 assert_eq!(json[1], serde_json::json!({"type": "break"}));
2279 let read: Vec<Inline> = serde_json::from_value(json).unwrap();
2280 assert_eq!(read, inlines);
2281 assert_eq!(super::text(&inlines), "Chapter One\nThe Voyage to Lilliput");
2282 }
2283
2284 #[test]
2287 fn heading_levels_run_one_to_six() {
2288 for level in 1..=6u8 {
2289 let heading = HeadingLevel::try_from(level).expect("1-6 is a heading level");
2290 assert_eq!(u8::from(heading), level);
2291 }
2292 for outside in [0u8, 7, 255] {
2293 assert_eq!(
2294 HeadingLevel::try_from(outside),
2295 Err(InvalidHeadingLevel(outside)),
2296 );
2297 }
2298 }
2299
2300 #[test]
2303 fn node_ids_are_dense_pre_order_and_deterministic() {
2304 let mut book = sample_book();
2305 book.assign_node_ids();
2306 let ids = collect_ids(&book);
2307
2308 let mut sorted = ids.clone();
2310 sorted.sort_by_key(|id| id.get());
2311 sorted.dedup();
2312 assert_eq!(sorted.len(), ids.len());
2313 assert_eq!(sorted.first().unwrap().get(), 1);
2314 assert_eq!(sorted.last().unwrap().get(), ids.len() as u32);
2315
2316 let section = book.sections[0].id;
2319 let Block::Heading { id: heading, .. } = &book.sections[0].blocks[0] else {
2320 panic!("fixture starts with a heading");
2321 };
2322 let Block::Paragraph {
2323 id: paragraph,
2324 inlines,
2325 ..
2326 } = &book.sections[0].blocks[1]
2327 else {
2328 panic!("second block is a paragraph");
2329 };
2330 assert!(section.get() < heading.get());
2331 assert!(heading.get() < paragraph.get());
2332 let Inline::Emphasis {
2333 id: emphasis,
2334 children,
2335 ..
2336 } = &inlines[1]
2337 else {
2338 panic!("second inline is emphasis");
2339 };
2340 let Inline::Text { id: child, .. } = &children[0] else {
2341 panic!("emphasis child is text");
2342 };
2343 assert!(paragraph.get() < emphasis.get());
2344 assert!(emphasis.get() < child.get());
2345
2346 let first = collect_ids(&book);
2349 book.assign_node_ids();
2350 assert_eq!(first, collect_ids(&book));
2351 }
2352
2353 #[test]
2357 fn a_byte_answers_with_the_innermost_node_written_there() {
2358 let mut book = sample_book();
2359 book.assign_node_ids();
2360
2361 let letter = SOURCE.find("clean").unwrap() as u32;
2362 let Some(Inline::Emphasis {
2363 id: emphasis,
2364 children,
2365 ..
2366 }) = paragraph(&book).get(1)
2367 else {
2368 panic!("the sample paragraph holds an emphasis");
2369 };
2370 assert_eq!(
2371 book.node_at("chapter-01.md", letter),
2372 Some(inline_id(&children[0]))
2373 );
2374 assert_eq!(book.node_at("chapter-01.md", letter - 1), Some(*emphasis));
2377 let blank = SOURCE.find("\n\n").unwrap() as u32 + 1;
2380 assert_eq!(
2381 book.node_at("chapter-01.md", blank),
2382 Some(book.sections[0].id)
2383 );
2384 assert_eq!(book.node_at("chapter-01.md", SOURCE.len() as u32), None);
2385 }
2386
2387 #[test]
2391 fn a_question_is_answered_from_one_source() {
2392 let mut book = sample_book();
2393 let mut second = book.sections[0].clone();
2394 second.source = Some("chapter-02.md".into());
2395 book.sections.push(second);
2396 book.assign_node_ids();
2397
2398 let letter = SOURCE.find("clean").unwrap() as u32;
2399 let first = book
2400 .node_at("chapter-01.md", letter)
2401 .expect("the first chapter");
2402 let second = book.node_at("chapter-02.md", letter).expect("the second");
2403 assert_ne!(first, second);
2404 assert_eq!(
2405 book.source_of(first).map(|(name, _)| name),
2406 Some("chapter-01.md")
2407 );
2408 assert_eq!(
2409 book.source_of(second).map(|(name, _)| name),
2410 Some("chapter-02.md")
2411 );
2412 assert_eq!(book.node_at("chapter-03.md", letter), None);
2413 }
2414
2415 #[test]
2418 fn a_node_taken_to_its_source_and_back_is_the_same_node() {
2419 let mut book = sample_book();
2420 book.assign_node_ids();
2421
2422 for id in collect_ids(&book) {
2423 let (source, span) = book
2424 .source_of(id)
2425 .expect("a parsed node was read from a file");
2426 assert_eq!(source, "chapter-01.md");
2427 assert!(
2428 span.end as usize <= SOURCE.len(),
2429 "node {} covers {span:?}, which is past the source",
2430 id.get(),
2431 );
2432 let there = book
2433 .node_at(source, span.start)
2434 .expect("a node was read there");
2435 let (_, back) = book.source_of(there).expect("and it says so");
2436 assert_eq!(back.start, span.start, "node {} starts elsewhere", id.get());
2437 }
2438 }
2439
2440 #[test]
2443 fn a_tree_built_rather_than_parsed_answers_with_nothing() {
2444 let mut book = Book {
2445 metadata: Metadata::default(),
2446 sections: vec![Section {
2447 attributes: Default::default(),
2448 source: Some("chapter-01.md".into()),
2449 blocks: vec![Block::Paragraph {
2450 id: NodeId::UNASSIGNED,
2451 inlines: vec![Inline::Text {
2452 id: NodeId::UNASSIGNED,
2453 value: "Built by hand.".into(),
2454 attributes: Attributes::default(),
2455 position: None,
2456 span: None,
2457 }],
2458 attributes: Attributes::default(),
2459 position: None,
2460 span: None,
2461 }],
2462 ..Section::default()
2463 }],
2464 };
2465 book.assign_node_ids();
2466
2467 assert_eq!(book.node_at("chapter-01.md", 0), None);
2468 for id in collect_ids(&book) {
2469 assert_eq!(
2470 book.source_of(id),
2471 None,
2472 "node {} was read from nothing",
2473 id.get()
2474 );
2475 }
2476 assert_eq!(book.source_of(NodeId::UNASSIGNED), None);
2477 }
2478
2479 #[test]
2484 fn a_subtree_is_a_run_of_ids() {
2485 let mut book = sample_book();
2486 book.assign_node_ids();
2487 let ids = collect_ids(&book);
2488 let last = ids.last().expect("the sample book has nodes").get();
2489
2490 let section = book.sections[0].id;
2491 assert_eq!(book.subtree(section), Some(section.get()..last + 1));
2492
2493 let quote = book.sections[0].blocks[2].clone();
2494 let Block::Blockquote { id, blocks, .. } = "e else {
2495 panic!("the third block is a blockquote");
2496 };
2497 let quoted = block_id(&blocks[0]);
2498 assert_eq!(book.subtree(*id), Some(id.get()..quoted.get() + 2));
2499
2500 for id in ids {
2501 let held = book.subtree(id).expect("the book holds it");
2502 assert_eq!(held.start, id.get(), "a node opens its own run");
2503 assert!(held.end <= last + 1, "a run stops inside the book");
2504 }
2505 }
2506
2507 #[test]
2510 fn an_id_the_book_does_not_hold_covers_nothing() {
2511 let mut book = sample_book();
2512 book.assign_node_ids();
2513 let past = collect_ids(&book).last().expect("nodes").get() + 1;
2514
2515 assert_eq!(book.subtree(NodeId::UNASSIGNED), None);
2516 assert_eq!(book.subtree(NodeId::new(past)), None);
2517 assert_eq!(Book::default().subtree(NodeId::new(1)), None);
2518 }
2519
2520 fn paragraph(book: &Book) -> &[Inline] {
2522 let Block::Paragraph { inlines, .. } = &book.sections[0].blocks[1] else {
2523 panic!("the second block is a paragraph");
2524 };
2525 inlines
2526 }
2527
2528 #[test]
2531 fn a_break_serializes_under_its_own_tag() {
2532 let page = Block::PageBreak {
2533 id: NodeId::UNASSIGNED,
2534 attributes: Attributes::default(),
2535 position: None,
2536 span: None,
2537 };
2538 let column = Block::ColumnBreak {
2539 id: NodeId::UNASSIGNED,
2540 attributes: Attributes::default(),
2541 position: None,
2542 span: None,
2543 };
2544 assert_eq!(
2545 serde_json::to_value(&page).expect("a break serializes"),
2546 serde_json::json!({ "type": "page_break" })
2547 );
2548 assert_eq!(
2549 serde_json::to_value(&column).expect("a break serializes"),
2550 serde_json::json!({ "type": "column_break" })
2551 );
2552 }
2553
2554 #[test]
2556 fn origin_formats_file_line_column() {
2557 let pos = SourcePos {
2558 line: 12,
2559 column: 3,
2560 };
2561 assert_eq!(
2562 origin(Some("chapter-01.md"), Some(pos)),
2563 "chapter-01.md:12:3"
2564 );
2565 assert_eq!(origin(Some("chapter-01.md"), None), "chapter-01.md");
2566 assert_eq!(origin(None, Some(pos)), "12:3");
2567 assert_eq!(origin(None, None), "");
2568 }
2569
2570 #[test]
2575 fn a_source_reports_the_names_its_blocks_and_inlines_carry() {
2576 let text = |value: &str| serde_json::json!({"type": "text", "value": value});
2577 let book: Book = serde_json::from_value(serde_json::json!({
2578 "metadata": {},
2579 "sections": [
2580 {
2581 "source": "one.md",
2582 "attributes": {"id": "front", "classes": ["chapter"]},
2583 "blocks": [
2584 {"type": "heading", "level": 1, "inlines": [text("One")],
2585 "attributes": {"id": "ch1", "classes": ["opening"]}},
2586 {"type": "paragraph", "inlines": [
2587 {"type": "span", "children": [text("aside")],
2588 "attributes": {"classes": ["smallcaps"]}},
2589 {"type": "note", "blocks": [
2590 {"type": "paragraph", "inlines": [text("n")],
2591 "attributes": {"classes": ["gloss"]}}
2592 ]}
2593 ]},
2594 {"type": "list", "items": [
2595 {"blocks": [], "attributes": {"id": "first-item", "classes": ["opening"]}}
2596 ]},
2597 {"type": "table", "body": [
2598 {"cells": [{"blocks": [], "attributes": {"classes": ["total"]}}],
2599 "attributes": {"classes": ["sum"]}}
2600 ]}
2601 ]
2602 },
2603 {
2604 "source": "two.md",
2605 "blocks": [
2606 {"type": "blockquote", "blocks": [], "attributes": {"classes": ["epigraph"]}}
2607 ]
2608 }
2609 ]
2610 }))
2611 .unwrap();
2612
2613 let one = book.names(Some("one.md"));
2614 assert_eq!(
2615 one.classes,
2616 ["gloss", "opening", "smallcaps", "sum", "total"]
2617 );
2618 assert_eq!(one.ids, ["ch1", "first-item"]);
2619 assert_eq!(book.names(Some("two.md")).classes, ["epigraph"]);
2620 assert_eq!(book.names(Some("three.md")), Names::default());
2621 let all = book.names(None);
2622 assert_eq!(
2623 all.classes,
2624 ["epigraph", "gloss", "opening", "smallcaps", "sum", "total"]
2625 );
2626 assert_eq!(all.ids, ["ch1", "first-item"]);
2627 }
2628}