use odox_core::Element;
const DEPTH: usize = 100;
#[derive(Default)]
pub struct Editing {
pub on: bool,
pub asking: bool,
undo: Vec<Element>,
redo: Vec<Element>,
saved_at: Option<usize>,
}
impl Editing {
pub fn reset(&mut self) {
self.undo.clear();
self.redo.clear();
self.saved_at = Some(0);
}
pub fn record(&mut self, content: &Element) {
if self.saved_at.is_some_and(|depth| depth > self.undo.len()) {
self.saved_at = None;
}
self.redo.clear();
self.undo.push(content.clone());
if self.undo.len() > DEPTH {
self.undo.remove(0);
self.saved_at = self.saved_at.and_then(|depth| depth.checked_sub(1));
}
}
pub fn undo(&mut self, current: &Element) -> Option<Element> {
let previous = self.undo.pop()?;
self.redo.push(current.clone());
Some(previous)
}
pub fn redo(&mut self, current: &Element) -> Option<Element> {
let next = self.redo.pop()?;
self.undo.push(current.clone());
Some(next)
}
pub fn can_undo(&self) -> bool {
!self.undo.is_empty()
}
pub fn can_redo(&self) -> bool {
!self.redo.is_empty()
}
pub fn modified(&self) -> bool {
self.saved_at != Some(self.undo.len())
}
pub fn mark_saved(&mut self) {
self.saved_at = Some(self.undo.len());
}
}
#[cfg(test)]
mod tests {
use super::Editing;
use odox_core::{Element, Ns};
fn tree(text: &str) -> Element {
let mut e = Element::new("text", "p", Ns::Text);
e.children.push(odox_core::Node::Text(text.to_owned()));
e
}
#[test]
fn undo_returns_to_the_saved_state_and_redo_leaves_it() {
let mut editing = Editing::default();
editing.reset();
assert!(!editing.modified());
let mut current = tree("one");
editing.record(¤t);
current = tree("two");
assert!(editing.modified());
current = editing.undo(¤t).expect("something to undo");
assert_eq!(current, tree("one"));
assert!(!editing.modified(), "undone to what the file holds");
current = editing.redo(¤t).expect("something to redo");
assert_eq!(current, tree("two"));
assert!(editing.modified());
}
#[test]
fn a_new_edit_below_the_saved_state_makes_it_unreachable() {
let mut editing = Editing::default();
editing.reset();
let mut current = tree("one");
editing.record(¤t);
current = tree("two");
editing.mark_saved();
assert!(!editing.modified());
current = editing.undo(¤t).expect("something to undo");
assert!(editing.modified());
editing.record(¤t);
assert!(
editing.modified(),
"the same depth is not the same document"
);
assert!(!editing.can_redo(), "the branch the save was on is gone");
}
#[test]
fn the_stack_is_bounded() {
let mut editing = Editing::default();
editing.reset();
for i in 0..(super::DEPTH + 10) {
editing.record(&tree(&i.to_string()));
}
assert!(editing.modified());
let mut undone = 0;
let mut current = tree("last");
while let Some(previous) = editing.undo(¤t) {
current = previous;
undone += 1;
}
assert_eq!(undone, super::DEPTH);
assert!(
editing.modified(),
"the saved state was forgotten with the oldest snapshots"
);
}
}