use std::collections::HashMap;
use super::command::EditCommand;
#[derive(Debug)]
pub struct EditHistory {
pub commands: Vec<EditCommand>,
pub current_index: usize,
pub rollback_points: HashMap<String, usize>,
}
impl EditHistory {
pub fn new() -> Self {
Self {
commands: Vec::new(),
current_index: 0,
rollback_points: HashMap::new(),
}
}
pub fn record_command(&mut self, command: EditCommand) {
self.commands.truncate(self.current_index);
self.commands.push(command);
self.current_index += 1;
}
pub fn undo(&mut self) -> Option<&EditCommand> {
if self.current_index == 0 {
return None;
}
self.current_index -= 1;
self.commands.get(self.current_index)
}
pub fn redo(&mut self) -> Option<&EditCommand> {
if self.current_index >= self.commands.len() {
return None;
}
let command = self.commands.get(self.current_index)?;
self.current_index += 1;
Some(command)
}
pub fn create_rollback_point(&mut self, name: String) {
self.rollback_points.insert(name, self.current_index);
}
pub fn rollback(&mut self, name: &str) -> Option<&EditCommand> {
let index = self.rollback_points.get(name)?;
self.current_index = *index;
self.commands.get(self.current_index)
}
pub fn current_index(&self) -> usize {
self.current_index
}
pub fn len(&self) -> usize {
self.commands.len()
}
pub fn is_empty(&self) -> bool {
self.commands.is_empty()
}
pub fn commands(&self) -> &[EditCommand] {
&self.commands
}
}
impl Default for EditHistory {
fn default() -> Self {
Self::new()
}
}