use crate::{EventStream, Signal, Sink, Var};
use std::cell::RefCell;
pub trait Command {
fn execute(&self);
fn undo(&self);
fn text(&self) -> String {
String::new()
}
}
pub struct UndoStack {
undo: RefCell<Vec<Box<dyn Command>>>,
redo: RefCell<Vec<Box<dyn Command>>>,
can_undo: Var<bool>,
can_redo: Var<bool>,
changed: Sink<()>,
}
impl UndoStack {
pub fn new() -> Self {
Self {
undo: RefCell::new(Vec::new()),
redo: RefCell::new(Vec::new()),
can_undo: Var::new(false),
can_redo: Var::new(false),
changed: Sink::new(),
}
}
pub fn push(&self, command: Box<dyn Command>) {
command.execute();
self.undo.borrow_mut().push(command);
self.redo.borrow_mut().clear();
self.notify();
}
pub fn undo(&self) -> bool {
let Some(command) = self.undo.borrow_mut().pop() else {
return false;
};
command.undo();
self.redo.borrow_mut().push(command);
self.notify();
true
}
pub fn redo(&self) -> bool {
let Some(command) = self.redo.borrow_mut().pop() else {
return false;
};
command.execute();
self.undo.borrow_mut().push(command);
self.notify();
true
}
pub fn clear(&self) {
if self.undo.borrow().is_empty() && self.redo.borrow().is_empty() {
return;
}
self.undo.borrow_mut().clear();
self.redo.borrow_mut().clear();
self.notify();
}
pub fn can_undo(&self) -> Signal<bool> {
self.can_undo.signal()
}
pub fn can_redo(&self) -> Signal<bool> {
self.can_redo.signal()
}
pub fn changed(&self) -> EventStream<()> {
self.changed.stream()
}
pub fn undo_text(&self) -> Option<String> {
self.undo.borrow().last().map(|command| command.text())
}
pub fn redo_text(&self) -> Option<String> {
self.redo.borrow().last().map(|command| command.text())
}
fn notify(&self) {
self.can_undo.set(!self.undo.borrow().is_empty());
self.can_redo.set(!self.redo.borrow().is_empty());
self.changed.send(());
}
}
impl Default for UndoStack {
fn default() -> Self {
Self::new()
}
}