1use crate::markdown::{from_markdown, to_markdown};
4use crate::model::{BlockKind, BlockNode, Document, InlineSpan};
5use strata_dom::Signal;
6
7#[derive(Clone)]
9pub struct EditorState {
10 pub document: Signal<Document>,
11 pub cursor: Signal<Option<(usize, usize)>>,
12}
13
14impl Default for EditorState {
15 fn default() -> Self {
16 Self::new()
17 }
18}
19
20impl EditorState {
21 pub fn new() -> Self {
23 let mut doc = Document::new();
24 doc.add_block(BlockNode::paragraph("block-1", ""));
25 Self {
26 document: Signal::new(doc),
27 cursor: Signal::new(Some((0, 0))),
28 }
29 }
30
31 pub fn to_markdown(&self) -> String {
33 to_markdown(&self.document.get())
34 }
35
36 pub fn load_markdown(&self, md: &str) {
38 let doc = from_markdown(md);
39 self.document.set(doc);
40 self.cursor.set(Some((0, 0)));
41 }
42
43 pub fn insert_text(&self, text: &str) {
45 let mut doc = self.document.get();
46 if let Some((b_idx, _)) = self.cursor.get() {
47 if let Some(block) = doc.blocks.get_mut(b_idx) {
48 if let Some(span) = block.spans.last_mut() {
49 span.text.push_str(text);
50 } else {
51 block.spans.push(InlineSpan::plain(text));
52 }
53 }
54 }
55 self.document.set(doc);
56 }
57
58 pub fn insert_block(&self, kind: BlockKind) {
60 let mut doc = self.document.get();
61 let next_id = format!("block-{}", doc.blocks.len() + 1);
62 let new_block = BlockNode::new(next_id, kind);
63
64 let insert_idx = if let Some((b_idx, _)) = self.cursor.get() {
65 (b_idx + 1).min(doc.blocks.len())
66 } else {
67 doc.blocks.len()
68 };
69
70 doc.blocks.insert(insert_idx, new_block);
71 self.document.set(doc);
72 self.cursor.set(Some((insert_idx, 0)));
73 }
74}
75
76pub fn use_editor(initial_markdown: Option<&str>) -> EditorState {
78 let editor = EditorState::new();
79 if let Some(md) = initial_markdown {
80 editor.load_markdown(md);
81 }
82 editor
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88
89 #[test]
90 fn test_editor_operations() {
91 let editor = use_editor(Some("# Initial Header\n\nInitial paragraph"));
92 assert_eq!(editor.document.get().blocks.len(), 2);
93
94 editor.insert_block(BlockKind::Paragraph);
95 editor.insert_text("Added line via editor");
96
97 let md = editor.to_markdown();
98 assert!(md.contains("Added line via editor"));
99 }
100}