Skip to main content

leptos_node_graph/
history.rs

1use leptos::prelude::*;
2
3#[derive(Clone, Debug)]
4pub struct HistoryCommand<T: Clone + 'static> {
5    pub data: T,
6}
7
8#[derive(Clone)]
9pub struct UndoHistory<T: Clone + Send + Sync + 'static> {
10    undo_stack: RwSignal<Vec<HistoryCommand<T>>>,
11    redo_stack: RwSignal<Vec<HistoryCommand<T>>>,
12    max_size: usize,
13}
14
15impl<T: Clone + Send + Sync + 'static> UndoHistory<T> {
16    pub fn new(max_size: usize) -> Self {
17        Self {
18            undo_stack: RwSignal::new(Vec::new()),
19            redo_stack: RwSignal::new(Vec::new()),
20            max_size,
21        }
22    }
23
24    pub fn push(&self, data: T) {
25        self.redo_stack.set(Vec::new());
26        self.undo_stack.update(|stack| {
27            if stack.len() >= self.max_size {
28                stack.remove(0);
29            }
30            stack.push(HistoryCommand { data });
31        });
32    }
33
34    pub fn undo(&self) -> Option<T> {
35        let cmd = self.undo_stack.try_update(|stack| stack.pop()).flatten();
36        if let Some(ref cmd) = cmd {
37            self.redo_stack.update(|stack| {
38                stack.push(HistoryCommand {
39                    data: cmd.data.clone(),
40                });
41            });
42        }
43        cmd.map(|c| c.data)
44    }
45
46    pub fn redo(&self) -> Option<T> {
47        let cmd = self.redo_stack.try_update(|stack| stack.pop()).flatten();
48        if let Some(ref cmd) = cmd {
49            self.undo_stack.update(|stack| {
50                stack.push(HistoryCommand {
51                    data: cmd.data.clone(),
52                });
53            });
54        }
55        cmd.map(|c| c.data)
56    }
57
58    pub fn can_undo(&self) -> bool {
59        self.undo_stack.with_untracked(|s| !s.is_empty())
60    }
61
62    pub fn can_redo(&self) -> bool {
63        self.redo_stack.with_untracked(|s| !s.is_empty())
64    }
65
66    pub fn clear(&self) {
67        self.undo_stack.set(Vec::new());
68        self.redo_stack.set(Vec::new());
69    }
70}