use crate::graph::{Graph, GraphError};
use crate::op::GraphOp;
pub const DEFAULT_HISTORY_LIMIT: usize = 200;
#[derive(Clone, Debug)]
struct Entry {
label: &'static str,
inverse: GraphOp,
merge_key: Option<u64>,
}
#[derive(Clone, Debug)]
pub struct History {
undo: Vec<Entry>,
redo: Vec<Entry>,
limit: usize,
sealed: bool,
}
impl Default for History {
fn default() -> Self {
Self::new(DEFAULT_HISTORY_LIMIT)
}
}
impl History {
pub fn new(limit: usize) -> Self {
Self {
undo: Vec::new(),
redo: Vec::new(),
limit: limit.max(1),
sealed: true,
}
}
pub fn commit(
&mut self,
g: &mut Graph,
op: GraphOp,
label: &'static str,
) -> Result<(), GraphError> {
self.commit_inner(g, op, label, None)
}
pub fn commit_merged(
&mut self,
g: &mut Graph,
op: GraphOp,
label: &'static str,
key: u64,
) -> Result<(), GraphError> {
self.commit_inner(g, op, label, Some(key))
}
fn commit_inner(
&mut self,
g: &mut Graph,
op: GraphOp,
label: &'static str,
key: Option<u64>,
) -> Result<(), GraphError> {
if op.is_empty() {
return Ok(());
}
let inverse = g.apply(op)?;
self.record(inverse, label, key);
Ok(())
}
pub fn record(&mut self, inverse: GraphOp, label: &'static str, key: Option<u64>) {
self.redo.clear();
if let (Some(k), false, Some(top)) = (key, self.sealed, self.undo.last_mut())
&& top.merge_key == Some(k)
{
let older = std::mem::replace(&mut top.inverse, GraphOp::Batch(Vec::new()));
top.inverse = GraphOp::Batch(vec![inverse, older]);
return;
}
self.undo.push(Entry {
label,
inverse,
merge_key: key,
});
if self.undo.len() > self.limit {
self.undo.remove(0);
}
self.sealed = key.is_none();
}
pub fn seal(&mut self) {
self.sealed = true;
}
pub fn can_undo(&self) -> bool {
!self.undo.is_empty()
}
pub fn can_redo(&self) -> bool {
!self.redo.is_empty()
}
pub fn undo_label(&self) -> Option<&'static str> {
self.undo.last().map(|e| e.label)
}
pub fn redo_label(&self) -> Option<&'static str> {
self.redo.last().map(|e| e.label)
}
pub fn undo(&mut self, g: &mut Graph) -> Result<Option<&'static str>, GraphError> {
let Some(entry) = self.undo.pop() else {
return Ok(None);
};
let redo = g.apply(entry.inverse)?;
self.redo.push(Entry {
label: entry.label,
inverse: redo,
merge_key: None,
});
self.sealed = true;
Ok(Some(entry.label))
}
pub fn redo(&mut self, g: &mut Graph) -> Result<Option<&'static str>, GraphError> {
let Some(entry) = self.redo.pop() else {
return Ok(None);
};
let undo = g.apply(entry.inverse)?;
self.undo.push(Entry {
label: entry.label,
inverse: undo,
merge_key: None,
});
self.sealed = true;
Ok(Some(entry.label))
}
pub fn clear(&mut self) {
self.undo.clear();
self.redo.clear();
self.sealed = true;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::{Size2, Vec2};
#[test]
fn undo_redo_cycle() {
let mut g = Graph::new();
let (a, _, _) = g.add_node_with("a", Vec2::ZERO, Size2::new(10.0, 10.0), 0, 0);
let mut h = History::default();
let start = g.to_json();
h.commit(
&mut g,
GraphOp::MoveNodes {
moves: vec![(a, Vec2::new(5.0, 0.0))],
},
"move",
)
.unwrap();
let moved = g.to_json();
assert_eq!(h.undo(&mut g).unwrap(), Some("move"));
assert_eq!(g.to_json(), start);
assert_eq!(h.redo(&mut g).unwrap(), Some("move"));
assert_eq!(g.to_json(), moved);
}
#[test]
fn merged_nudges_undo_in_one_step() {
let mut g = Graph::new();
let (a, _, _) = g.add_node_with("a", Vec2::ZERO, Size2::new(10.0, 10.0), 0, 0);
let mut h = History::default();
for i in 1..=5 {
let op = GraphOp::MoveNodes {
moves: vec![(a, Vec2::new(i as f32, 0.0))],
};
h.commit_merged(&mut g, op, "nudge", 7).unwrap();
}
assert_eq!(g.node(a).unwrap().pos.x, 5.0);
h.undo(&mut g).unwrap();
assert_eq!(g.node(a).unwrap().pos.x, 0.0);
assert!(!h.can_undo());
h.redo(&mut g).unwrap();
assert_eq!(g.node(a).unwrap().pos.x, 5.0);
}
#[test]
fn new_commit_clears_redo_and_limit_applies() {
let mut g = Graph::new();
let (a, _, _) = g.add_node_with("a", Vec2::ZERO, Size2::new(10.0, 10.0), 0, 0);
let mut h = History::new(3);
for i in 0..5 {
let op = GraphOp::MoveNodes {
moves: vec![(a, Vec2::new(i as f32, 0.0))],
};
h.commit(&mut g, op, "move").unwrap();
}
let mut n = 0;
while h.undo(&mut g).unwrap().is_some() {
n += 1;
}
assert_eq!(n, 3);
h.commit(
&mut g,
GraphOp::ResizeNode {
id: a,
size: Size2::new(1.0, 1.0),
},
"resize",
)
.unwrap();
assert!(!h.can_redo());
}
}