Skip to main content

katana_markdown_model/document/
impls.rs

1use super::types::{KmmDocument, KmmNode, KmmNodeId, KmmNodeKind};
2use crate::TextFingerprint;
3
4impl KmmDocument {
5    pub fn nodes_by_kind(&self, predicate: impl Fn(&KmmNodeKind) -> bool) -> Vec<&KmmNode> {
6        self.nodes
7            .iter()
8            .filter(|node| predicate(&node.kind))
9            .collect()
10    }
11
12    pub fn node_by_id(&self, id: &KmmNodeId) -> Option<&KmmNode> {
13        self.nodes.iter().find(|node| &node.id == id)
14    }
15}
16
17impl KmmNode {
18    pub(crate) fn new(
19        kind: KmmNodeKind,
20        raw: &str,
21        ordinal: usize,
22        source: crate::SourceSpan,
23    ) -> Self {
24        Self {
25            id: KmmNodeId::from_parts(&kind, raw, ordinal),
26            kind,
27            source,
28            children: Vec::new(),
29        }
30    }
31}
32
33impl KmmNodeId {
34    pub(crate) fn from_parts(kind: &KmmNodeKind, raw: &str, ordinal: usize) -> Self {
35        let seed = format!("{}\0{}\0{}", kind.label(), raw, ordinal);
36        Self(format!("kmm-{}", TextFingerprint::for_text(&seed).value))
37    }
38}
39
40impl KmmNodeKind {
41    pub fn label(&self) -> &'static str {
42        match self {
43            Self::Heading(_) => "heading",
44            Self::Paragraph => "paragraph",
45            Self::Text(_) => "text",
46            Self::Strong(_) => "strong",
47            Self::Emphasis(_) => "emphasis",
48            Self::Strikethrough(_) => "strikethrough",
49            Self::InlineCode(_) => "inline-code",
50            Self::InlineHtml(_) => "inline-html",
51            Self::Link(_) => "link",
52            Self::Image(_) => "image",
53            Self::FootnoteReference(_) => "footnote-reference",
54            Self::FootnoteDefinition(_) => "footnote-definition",
55            Self::InlineMath(_) => "inline-math",
56            Self::DollarMathBlock(_) => "dollar-math-block",
57            Self::Emoji(_) => "emoji",
58            Self::HtmlBlock(_) => "html-block",
59            Self::List(_) => "list",
60            Self::CodeBlock(_) => "code-block",
61            Self::Table(_) => "table",
62            Self::BlockQuote => "blockquote",
63            Self::Alert { .. } => "alert",
64            Self::DescriptionList { .. } => "description-list",
65            Self::ThematicBreak => "thematic-break",
66            Self::RawBlock { .. } => "raw-block",
67        }
68    }
69}