Skip to main content

strata_editor/
model.rs

1//! Headless Block Document Tree and Inline Mark AST.
2
3use serde::{Deserialize, Serialize};
4
5/// Text formatting marks.
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
7pub enum InlineMark {
8    Bold,
9    Italic,
10    Code,
11    Underline,
12    Strike,
13    Link(String),
14}
15
16/// A formatted span of text within a block node.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct InlineSpan {
19    pub text: String,
20    pub marks: Vec<InlineMark>,
21}
22
23impl InlineSpan {
24    pub fn plain(text: impl Into<String>) -> Self {
25        Self {
26            text: text.into(),
27            marks: Vec::new(),
28        }
29    }
30
31    pub fn with_mark(mut self, mark: InlineMark) -> Self {
32        self.marks.push(mark);
33        self
34    }
35}
36
37/// Structural block kinds supported by the document editor.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub enum BlockKind {
40    Paragraph,
41    Heading(u8),
42    Blockquote,
43    CodeBlock(Option<String>),
44    BulletListItem,
45    NumberedListItem(usize),
46    HorizontalRule,
47}
48
49/// A single block node containing child inline spans.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51pub struct BlockNode {
52    pub id: String,
53    pub kind: BlockKind,
54    pub spans: Vec<InlineSpan>,
55}
56
57impl BlockNode {
58    pub fn new(id: impl Into<String>, kind: BlockKind) -> Self {
59        Self {
60            id: id.into(),
61            kind,
62            spans: Vec::new(),
63        }
64    }
65
66    pub fn paragraph(id: impl Into<String>, text: impl Into<String>) -> Self {
67        Self {
68            id: id.into(),
69            kind: BlockKind::Paragraph,
70            spans: vec![InlineSpan::plain(text)],
71        }
72    }
73
74    pub fn heading(id: impl Into<String>, level: u8, text: impl Into<String>) -> Self {
75        Self {
76            id: id.into(),
77            kind: BlockKind::Heading(level),
78            spans: vec![InlineSpan::plain(text)],
79        }
80    }
81
82    pub fn plain_text(&self) -> String {
83        self.spans.iter().map(|s| s.text.as_str()).collect()
84    }
85}
86
87/// The root headless document containing top-level blocks.
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
89pub struct Document {
90    pub blocks: Vec<BlockNode>,
91}
92
93impl Document {
94    pub fn new() -> Self {
95        Self { blocks: Vec::new() }
96    }
97
98    pub fn add_block(&mut self, block: BlockNode) {
99        self.blocks.push(block);
100    }
101
102    pub fn push(&mut self, block: BlockNode) {
103        self.blocks.push(block);
104    }
105}