Skip to main content

odox_ui/
edit.rs

1//! What the shell keeps about a document being edited: whether editing is on,
2//! what has changed since the file was read, and how to take it back.
3//!
4//! Undo is a stack of snapshots of the content tree rather than a log of
5//! commands. The tree derives `Clone`, a document of the size these
6//! applications open clones in well under a millisecond, and commands would buy
7//! redo granularity nobody has asked for. DESIGN.md ยง11.
8//!
9//! Each snapshot also holds where the caret stood in that state, where the
10//! view has one, so that taking an edit back or putting it back shows the
11//! place it happened.
12//
13// Author: David M. Anderson
14// Built with AI assistance (Claude, Anthropic)
15
16use egui_richedit::Position;
17use odox_core::Element;
18
19/// How many edits can be taken back. Past this the oldest is forgotten.
20const DEPTH: usize = 100;
21
22/// Where a caret stood: a paragraph's path under the root the view draws, and
23/// a character offset into its text.
24pub type Caret = Position<Vec<usize>>;
25
26/// A state of the content tree and where the caret was in it.
27struct Snapshot {
28    content: Element,
29    caret: Option<Caret>,
30}
31
32/// The shell's editing state, handed to the view on every frame.
33#[derive(Default)]
34pub struct Editing {
35    /// Whether the window is in edit mode. Outside it a view draws and
36    /// selects and never opens an editor.
37    pub on: bool,
38    /// A question is up over the window, and the keys belong to it: a view
39    /// does not open an editor on the Enter that answers it.
40    pub asking: bool,
41    undo: Vec<Snapshot>,
42    redo: Vec<Snapshot>,
43    /// The depth of the undo stack when the document was last read or saved,
44    /// which is the state the file on disk holds. `None` once that state can no
45    /// longer be reached by undoing, because a new edit was made below it.
46    saved_at: Option<usize>,
47    /// Counts every change to the content, including the ones an undo step
48    /// absorbs, so that whatever is derived from the text can tell it is stale.
49    revision: u64,
50}
51
52impl Editing {
53    /// A document was just read or closed: nothing to undo, nothing changed.
54    pub fn reset(&mut self) {
55        self.undo.clear();
56        self.redo.clear();
57        self.saved_at = Some(0);
58        self.touch();
59    }
60
61    /// The content changed, in a way that need not have begun an undo step.
62    pub fn touch(&mut self) {
63        self.revision += 1;
64    }
65
66    /// A number that is different whenever the text may be.
67    pub fn revision(&self) -> u64 {
68        self.revision
69    }
70
71    /// Take a snapshot of the content tree before an edit changes it.
72    ///
73    /// Every edit calls this first, with the tree as it stands, and then
74    /// mutates. A redo history is discarded, because the edit that follows is
75    /// a new branch.
76    pub fn record(&mut self, content: &Element) {
77        self.record_snapshot(content.clone(), None);
78    }
79
80    /// The same, for a snapshot already taken, with where the caret stood in
81    /// it: an editor that learns only after an edit whether it succeeded
82    /// takes the tree before trying, and records it once it has.
83    pub fn record_snapshot(&mut self, content: Element, caret: Option<Caret>) {
84        if self.saved_at.is_some_and(|depth| depth > self.undo.len()) {
85            // The saved state was above this point and is now off the line.
86            self.saved_at = None;
87        }
88        self.redo.clear();
89        self.touch();
90        self.undo.push(Snapshot { content, caret });
91        if self.undo.len() > DEPTH {
92            self.undo.remove(0);
93            self.saved_at = self.saved_at.and_then(|depth| depth.checked_sub(1));
94        }
95    }
96
97    /// Take the last edit back. Given the tree as it stands and where the
98    /// caret is, so that the edit can be redone; answers the tree to put in
99    /// its place and where the caret was in it.
100    pub fn undo(
101        &mut self,
102        current: &Element,
103        caret: Option<Caret>,
104    ) -> Option<(Element, Option<Caret>)> {
105        let previous = self.undo.pop()?;
106        self.touch();
107        self.redo.push(Snapshot {
108            content: current.clone(),
109            caret,
110        });
111        Some((previous.content, previous.caret))
112    }
113
114    /// Put back the edit last taken back, the same way.
115    pub fn redo(
116        &mut self,
117        current: &Element,
118        caret: Option<Caret>,
119    ) -> Option<(Element, Option<Caret>)> {
120        let next = self.redo.pop()?;
121        self.touch();
122        self.undo.push(Snapshot {
123            content: current.clone(),
124            caret,
125        });
126        Some((next.content, next.caret))
127    }
128
129    /// Whether there is anything to undo.
130    pub fn can_undo(&self) -> bool {
131        !self.undo.is_empty()
132    }
133
134    /// Whether there is anything to redo.
135    pub fn can_redo(&self) -> bool {
136        !self.redo.is_empty()
137    }
138
139    /// Whether the document differs from the file it was read from or last
140    /// saved to. Undoing back to that state answers false again.
141    pub fn modified(&self) -> bool {
142        self.saved_at != Some(self.undo.len())
143    }
144
145    /// The document was written: what it holds now is what the file holds.
146    pub fn mark_saved(&mut self) {
147        self.saved_at = Some(self.undo.len());
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::Editing;
154    use odox_core::{Element, Ns};
155
156    fn tree(text: &str) -> Element {
157        let mut e = Element::new("text", "p", Ns::Text);
158        e.children.push(odox_core::Node::Text(text.to_owned()));
159        e
160    }
161
162    #[test]
163    fn undo_returns_to_the_saved_state_and_redo_leaves_it() {
164        let mut editing = Editing::default();
165        editing.reset();
166        assert!(!editing.modified());
167
168        let mut current = tree("one");
169        editing.record(&current);
170        current = tree("two");
171        assert!(editing.modified());
172
173        current = editing
174            .undo(&current, None)
175            .map(|(tree, _)| tree)
176            .expect("something to undo");
177        assert_eq!(current, tree("one"));
178        assert!(!editing.modified(), "undone to what the file holds");
179
180        current = editing
181            .redo(&current, None)
182            .map(|(tree, _)| tree)
183            .expect("something to redo");
184        assert_eq!(current, tree("two"));
185        assert!(editing.modified());
186    }
187
188    #[test]
189    fn a_new_edit_below_the_saved_state_makes_it_unreachable() {
190        let mut editing = Editing::default();
191        editing.reset();
192        let mut current = tree("one");
193        editing.record(&current);
194        current = tree("two");
195        editing.mark_saved();
196        assert!(!editing.modified());
197
198        // Back to "one", then a different second edit: the saved "two" is on
199        // a branch that no longer exists.
200        current = editing
201            .undo(&current, None)
202            .map(|(tree, _)| tree)
203            .expect("something to undo");
204        assert!(editing.modified());
205        editing.record(&current);
206        assert!(
207            editing.modified(),
208            "the same depth is not the same document"
209        );
210        assert!(!editing.can_redo(), "the branch the save was on is gone");
211    }
212
213    #[test]
214    fn undo_and_redo_answer_where_the_caret_was() {
215        let mut editing = Editing::default();
216        editing.reset();
217        let before = super::Caret::new(vec![0], 1);
218        let after = super::Caret::new(vec![0], 4);
219        editing.record_snapshot(tree("one"), Some(before.clone()));
220        let (_, caret) = editing
221            .undo(&tree("one more"), Some(after.clone()))
222            .expect("something to undo");
223        assert_eq!(caret, Some(before), "where the edit began");
224        let (_, caret) = editing.redo(&tree("one"), None).expect("something to redo");
225        assert_eq!(caret, Some(after), "where the caret was when it was undone");
226    }
227
228    #[test]
229    fn the_stack_is_bounded() {
230        let mut editing = Editing::default();
231        editing.reset();
232        for i in 0..(super::DEPTH + 10) {
233            editing.record(&tree(&i.to_string()));
234        }
235        assert!(editing.modified());
236        let mut undone = 0;
237        let mut current = tree("last");
238        while let Some(previous) = editing.undo(&current, None).map(|(tree, _)| tree) {
239            current = previous;
240            undone += 1;
241        }
242        assert_eq!(undone, super::DEPTH);
243        assert!(
244            editing.modified(),
245            "the saved state was forgotten with the oldest snapshots"
246        );
247    }
248}