1use crate::{EventStream, Signal, Sink, Var};
4use std::cell::RefCell;
5
6pub trait Command {
8 fn execute(&self);
10
11 fn undo(&self);
13
14 fn text(&self) -> String {
16 String::new()
17 }
18}
19
20pub struct UndoStack {
23 undo: RefCell<Vec<Box<dyn Command>>>,
24 redo: RefCell<Vec<Box<dyn Command>>>,
25 can_undo: Var<bool>,
26 can_redo: Var<bool>,
27 changed: Sink<()>,
28}
29
30impl UndoStack {
31 pub fn new() -> Self {
33 Self {
34 undo: RefCell::new(Vec::new()),
35 redo: RefCell::new(Vec::new()),
36 can_undo: Var::new(false),
37 can_redo: Var::new(false),
38 changed: Sink::new(),
39 }
40 }
41
42 pub fn push(&self, command: Box<dyn Command>) {
44 command.execute();
45 self.undo.borrow_mut().push(command);
46 self.redo.borrow_mut().clear();
47 self.notify();
48 }
49
50 pub fn undo(&self) -> bool {
52 let Some(command) = self.undo.borrow_mut().pop() else {
53 return false;
54 };
55 command.undo();
56 self.redo.borrow_mut().push(command);
57 self.notify();
58 true
59 }
60
61 pub fn redo(&self) -> bool {
64 let Some(command) = self.redo.borrow_mut().pop() else {
65 return false;
66 };
67 command.execute();
68 self.undo.borrow_mut().push(command);
69 self.notify();
70 true
71 }
72
73 pub fn clear(&self) {
75 if self.undo.borrow().is_empty() && self.redo.borrow().is_empty() {
76 return;
77 }
78 self.undo.borrow_mut().clear();
79 self.redo.borrow_mut().clear();
80 self.notify();
81 }
82
83 pub fn can_undo(&self) -> Signal<bool> {
85 self.can_undo.signal()
86 }
87
88 pub fn can_redo(&self) -> Signal<bool> {
90 self.can_redo.signal()
91 }
92
93 pub fn changed(&self) -> EventStream<()> {
95 self.changed.stream()
96 }
97
98 pub fn undo_text(&self) -> Option<String> {
100 self.undo.borrow().last().map(|command| command.text())
101 }
102
103 pub fn redo_text(&self) -> Option<String> {
105 self.redo.borrow().last().map(|command| command.text())
106 }
107
108 fn notify(&self) {
109 self.can_undo.set(!self.undo.borrow().is_empty());
110 self.can_redo.set(!self.redo.borrow().is_empty());
111 self.changed.send(());
112 }
113}
114
115impl Default for UndoStack {
116 fn default() -> Self {
117 Self::new()
118 }
119}