Skip to main content

rofd_editor/commands/
text_commands.rs

1use rofd_dom::{AnnotationId, AnnotationKind, AnnotationPayload, Color, NoteIcon, Rect};
2
3use crate::editor::Editor;
4use crate::payload_util::{set_color, set_width};
5
6impl Editor {
7    /// Set the primary color.
8    pub fn set_annotation_color(&mut self, id: &AnnotationId, color: Color) {
9        let before = match self.document.annotations.find(id).cloned() {
10            Some(a) => a,
11            None => return,
12        };
13        let mut after = before.clone();
14        set_color(&mut after.payload, color);
15        after.modified = self.current_ts;
16        self.execute_transaction(self.replace_txn(id.clone(), before, after));
17    }
18
19    /// Set the stroke width (Freehand/Shape).
20    pub fn set_annotation_width(&mut self, id: &AnnotationId, width: f64) {
21        let before = match self.document.annotations.find(id).cloned() {
22            Some(a) => a,
23            None => return,
24        };
25        let mut after = before.clone();
26        set_width(&mut after.payload, width);
27        after.modified = self.current_ts;
28        self.execute_transaction(self.replace_txn(id.clone(), before, after));
29    }
30
31    /// Insert text into a text annotation (TextBox/Note/Watermark) at char offset.
32    pub fn insert_text(&mut self, id: &AnnotationId, offset: usize, chars: &str) {
33        let before = match self.document.annotations.find(id).cloned() {
34            Some(a) => a,
35            None => return,
36        };
37        let mut after = before.clone();
38        if let Some(content) = text_content_mut(&mut after.payload) {
39            let off = offset.min(content.chars().count());
40            let mut new = content.chars().take(off).collect::<String>();
41            new.push_str(chars);
42            new.extend(content.chars().skip(off));
43            *content = new;
44        }
45        after.modified = self.current_ts;
46        self.execute_transaction(self.replace_txn(id.clone(), before, after));
47    }
48
49    /// Delete `len` chars from a text annotation at char offset.
50    pub fn delete_text(&mut self, id: &AnnotationId, offset: usize, len: usize) {
51        let before = match self.document.annotations.find(id).cloned() {
52            Some(a) => a,
53            None => return,
54        };
55        let mut after = before.clone();
56        if let Some(content) = text_content_mut(&mut after.payload) {
57            let total = content.chars().count();
58            let start = offset.min(total);
59            let end = (offset + len).min(total);
60            let kept: String = content
61                .chars()
62                .enumerate()
63                .filter(|(i, _)| *i < start || *i >= end)
64                .map(|(_, c)| c)
65                .collect();
66            *content = kept;
67        }
68        after.modified = self.current_ts;
69        self.execute_transaction(self.replace_txn(id.clone(), before, after));
70    }
71
72    /// Replace the whole text content.
73    pub fn set_annotation_text(&mut self, id: &AnnotationId, text: &str) {
74        let before = match self.document.annotations.find(id).cloned() {
75            Some(a) => a,
76            None => return,
77        };
78        let mut after = before.clone();
79        if let Some(content) = text_content_mut(&mut after.payload) {
80            *content = text.into();
81        }
82        after.modified = self.current_ts;
83        self.execute_transaction(self.replace_txn(id.clone(), before, after));
84    }
85
86    /// Reply to an annotation (creates a Note with reply_to set).
87    pub fn reply_to(&mut self, parent: &AnnotationId, content: &str) -> AnnotationId {
88        // Find the parent's page so the reply lives on the same page.
89        let page = self
90            .document
91            .annotations
92            .find(parent)
93            .map(|a| a.page.clone())
94            .unwrap_or_default();
95        self.create_annotation(
96            AnnotationKind::Note,
97            page,
98            AnnotationPayload::Note {
99                rect: Rect {
100                    x: 0.0,
101                    y: 0.0,
102                    w: 40.0,
103                    h: 20.0,
104                },
105                color: Color::Rgb(255, 200, 0),
106                content: content.into(),
107                icon: NoteIcon::Comment,
108            },
109        );
110        // create_annotation doesn't set reply_to; patch it with a Replace step.
111        // (Slight inefficiency: create + replace = 2 transactions. Acceptable for v1.)
112        let new_id = self.last_created_id();
113        if let Some(new_id) = new_id {
114            // Re-fetch the created annotation to snapshot before/after.
115            if let Some(before) = self.document.annotations.find(&new_id).cloned() {
116                let mut after = before.clone();
117                after.reply_to = Some(parent.clone());
118                after.modified = self.current_ts;
119                self.execute_transaction(self.replace_txn(new_id.clone(), before, after));
120            }
121            return new_id;
122        }
123        // create_annotation always sets selection to Single(id), so last_created_id
124        // is always Some here. This is unreachable in practice.
125        unreachable!("create_annotation should have set selection to the new id")
126    }
127
128    /// The id of the most recently created annotation (create_annotation sets
129    /// selection to Single(id), so this reads from selection).
130    fn last_created_id(&self) -> Option<AnnotationId> {
131        match &self.selection {
132            crate::selection::AnnotationSelection::Single(id) => Some(id.clone()),
133            _ => None,
134        }
135    }
136}
137
138/// Mutable text content for text-bearing payloads (TextBox/Note/Watermark). None for others.
139fn text_content_mut(p: &mut AnnotationPayload) -> Option<&mut String> {
140    match p {
141        AnnotationPayload::Note { content, .. } => Some(content),
142        AnnotationPayload::TextBox { content, .. } => Some(content),
143        AnnotationPayload::Watermark { content, .. } => Some(content),
144        _ => None,
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use crate::editor::Editor;
151    use rofd_dom::{
152        AnnotationId, AnnotationKind, AnnotationPayload, Color, NoteIcon, PageId, Rect,
153    };
154
155    fn note_editor(content: &str) -> (Editor, AnnotationId) {
156        let mut e = Editor::new();
157        e.set_clock("t".into(), 1);
158        let id = e.create_annotation(
159            AnnotationKind::Note,
160            PageId::new("P0"),
161            AnnotationPayload::Note {
162                rect: Rect {
163                    x: 0.0,
164                    y: 0.0,
165                    w: 10.0,
166                    h: 10.0,
167                },
168                color: Color::Rgb(0, 0, 0),
169                content: content.into(),
170                icon: NoteIcon::Note,
171            },
172        );
173        (e, id)
174    }
175
176    fn content_of(e: &Editor, id: &AnnotationId) -> String {
177        let a = e.document().annotations.find(id).unwrap();
178        match &a.payload {
179            AnnotationPayload::Note { content, .. } => content.clone(),
180            _ => panic!("not a text annotation"),
181        }
182    }
183
184    #[test]
185    fn insert_text_at_offset() {
186        let (mut e, id) = note_editor("Hello");
187        e.insert_text(&id, 2, "XX");
188        assert_eq!(content_of(&e, &id), "HeXXllo");
189    }
190
191    #[test]
192    fn delete_text_range() {
193        let (mut e, id) = note_editor("Hello");
194        e.delete_text(&id, 1, 2);
195        assert_eq!(content_of(&e, &id), "Hlo");
196    }
197
198    #[test]
199    fn set_text_replaces() {
200        let (mut e, id) = note_editor("Hello");
201        e.set_annotation_text(&id, "World");
202        assert_eq!(content_of(&e, &id), "World");
203    }
204
205    #[test]
206    fn text_edit_undo_restores() {
207        let (mut e, id) = note_editor("Hello");
208        e.insert_text(&id, 5, "!");
209        assert_eq!(content_of(&e, &id), "Hello!");
210        e.undo();
211        assert_eq!(content_of(&e, &id), "Hello");
212    }
213
214    #[test]
215    fn reply_to_creates_note_with_parent() {
216        let (mut e, parent) = note_editor("parent");
217        let child = e.reply_to(&parent, "reply");
218        let c = e.document().annotations.find(&child).unwrap();
219        assert_eq!(c.reply_to, Some(parent.clone()));
220    }
221}