Skip to main content

rofd_editor/
editor.rs

1use rofd_dom::{AnnotationId, OfdDocument};
2
3use crate::cursor::TextCursor;
4use crate::selection::AnnotationSelection;
5use crate::steps::history::History;
6use crate::steps::transaction::Transaction;
7
8/// Annotation editor. Owns the document; mutates only `.annotations` via commands.
9/// No callbacks - the host/component layer queries state after commands.
10pub struct Editor {
11    pub(crate) document: OfdDocument,
12    pub(crate) selection: AnnotationSelection,
13    pub(crate) text_cursor: Option<TextCursor>,
14    pub(crate) history: History,
15    pub(crate) author: String,
16    pub(crate) current_ts: i64,
17}
18
19impl Editor {
20    pub fn new() -> Self {
21        Self {
22            document: OfdDocument::default(),
23            selection: AnnotationSelection::None,
24            text_cursor: None,
25            history: History::new(100),
26            author: String::new(),
27            current_ts: 0,
28        }
29    }
30
31    pub fn load_document(&mut self, doc: OfdDocument) {
32        self.document = doc;
33        self.selection = AnnotationSelection::None;
34        self.text_cursor = None;
35        self.history = History::new(100);
36    }
37
38    /// Caller-supplied author + timestamp. The library never reads a system clock.
39    pub fn set_clock(&mut self, author: String, ts: i64) {
40        self.author = author;
41        self.current_ts = ts;
42    }
43
44    pub fn document(&self) -> &OfdDocument {
45        &self.document
46    }
47    pub fn selection(&self) -> &AnnotationSelection {
48        &self.selection
49    }
50    pub fn text_cursor(&self) -> Option<&TextCursor> {
51        self.text_cursor.as_ref()
52    }
53    pub fn can_undo(&self) -> bool {
54        self.history.can_undo()
55    }
56    pub fn can_redo(&self) -> bool {
57        self.history.can_redo()
58    }
59    /// Number of undoable transactions on the history stack. Mainly for
60    /// testing (e.g. asserting a drag pushes exactly one Transaction).
61    pub fn history_len(&self) -> usize {
62        self.history.done_len()
63    }
64
65    /// Select a single annotation by id.
66    pub fn select(&mut self, id: AnnotationId) {
67        self.selection = AnnotationSelection::Single(id);
68    }
69    /// Replace the current selection wholesale.
70    pub fn set_selection(&mut self, sel: AnnotationSelection) {
71        self.selection = sel;
72    }
73    /// Clear the selection.
74    pub fn clear_selection(&mut self) {
75        self.selection = AnnotationSelection::None;
76    }
77    /// Position the text cursor at `offset` within `annotation`.
78    pub fn set_cursor(&mut self, annotation: AnnotationId, offset: usize) {
79        self.text_cursor = Some(TextCursor {
80            annotation,
81            offset,
82            preferred_x: None,
83        });
84    }
85    /// Clear the text cursor.
86    pub fn clear_cursor(&mut self) {
87        self.text_cursor = None;
88    }
89
90    /// Apply a Transaction: run its steps forward, set selection/cursor to the
91    /// "after" state, and push it onto the history. Used by the command methods
92    /// (create/delete/move/...) starting in Task 5; the unit tests here exercise
93    /// it directly.
94    pub(crate) fn execute_transaction(&mut self, txn: Transaction) {
95        for step in &txn.steps {
96            step.apply(&mut self.document.annotations);
97        }
98        self.selection = txn.selection_after.clone();
99        self.text_cursor = txn.text_cursor_after.clone();
100        self.history.push(txn);
101    }
102
103    pub fn undo(&mut self) -> bool {
104        let txn = self.history.undo();
105        if let Some(txn) = txn {
106            for step in txn.steps.iter().rev() {
107                step.revert(&mut self.document.annotations);
108            }
109            self.selection = txn.selection_before.clone();
110            self.text_cursor = txn.text_cursor_before.clone();
111            true
112        } else {
113            false
114        }
115    }
116
117    pub fn redo(&mut self) -> bool {
118        let txn = self.history.redo();
119        if let Some(txn) = txn {
120            for step in &txn.steps {
121                step.apply(&mut self.document.annotations);
122            }
123            self.selection = txn.selection_after.clone();
124            self.text_cursor = txn.text_cursor_after.clone();
125            true
126        } else {
127            false
128        }
129    }
130}
131
132impl Default for Editor {
133    fn default() -> Self {
134        Self::new()
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use crate::steps::annotation_steps::InsertAnnotationStep;
142    use rofd_dom::{
143        Annotation, AnnotationId, AnnotationKind, AnnotationPayload, Color, NoteIcon, PageId, Rect,
144    };
145
146    fn note_ann(id: &str) -> Annotation {
147        Annotation {
148            id: AnnotationId::new(id),
149            kind: AnnotationKind::Note,
150            page: PageId::new("P0"),
151            creator: "t".into(),
152            created: 0,
153            modified: 0,
154            reply_to: None,
155            payload: AnnotationPayload::Note {
156                rect: Rect {
157                    x: 0.0,
158                    y: 0.0,
159                    w: 1.0,
160                    h: 1.0,
161                },
162                color: Color::Rgb(0, 0, 0),
163                content: "x".into(),
164                icon: NoteIcon::Note,
165            },
166        }
167    }
168
169    #[test]
170    fn execute_undo_redo_via_transaction() {
171        let mut e = Editor::new();
172        let ann = note_ann("21");
173        let txn = Transaction {
174            steps: vec![Box::new(InsertAnnotationStep {
175                annotation: ann.clone(),
176            })],
177            selection_before: AnnotationSelection::None,
178            selection_after: AnnotationSelection::Single(ann.id.clone()),
179            text_cursor_before: None,
180            text_cursor_after: None,
181        };
182        e.execute_transaction(txn);
183        assert!(e.document().annotations.find(&ann.id).is_some());
184        assert!(e.undo());
185        assert!(e.document().annotations.find(&ann.id).is_none());
186        assert!(e.redo());
187        assert!(e.document().annotations.find(&ann.id).is_some());
188    }
189
190    #[test]
191    fn history_capacity_evicts_oldest() {
192        let mut e = Editor::new();
193        for i in 0..105u32 {
194            let ann = note_ann(&format!("{}", i));
195            let txn = Transaction {
196                steps: vec![Box::new(InsertAnnotationStep { annotation: ann })],
197                selection_before: AnnotationSelection::None,
198                selection_after: AnnotationSelection::None,
199                text_cursor_before: None,
200                text_cursor_after: None,
201            };
202            e.execute_transaction(txn);
203        }
204        assert!(e.can_undo());
205        for _ in 0..100 {
206            assert!(e.undo());
207        }
208        assert!(!e.can_undo());
209    }
210}