| 1 | //! Simple undo/redo stack for editor text.
|
| 2 |
|
| 3 | const DEFAULT_LIMIT: usize = 100;
|
| 4 |
|
| 5 | pub struct TextUndo {
|
| 6 | undo: Vec<String>,
|
| 7 | redo: Vec<String>,
|
| 8 | limit: usize,
|
| 9 | }
|
| 10 |
|
| 11 | impl Default for TextUndo {
|
| 12 | fn default() -> Self {
|
| 13 | Self {
|
| 14 | undo: Vec::new(),
|
| 15 | redo: Vec::new(),
|
| 16 | limit: DEFAULT_LIMIT,
|
| 17 | }
|
| 18 | }
|
| 19 | }
|
| 20 |
|
| 21 | impl TextUndo {
|
| 22 | pub fn record(&mut self, before: String) {
|
| 23 | if self.undo.last() == Some(&before) {
|
| 24 | return;
|
| 25 | }
|
| 26 | self.undo.push(before);
|
| 27 | if self.undo.len() > self.limit {
|
| 28 | self.undo.remove(0);
|
| 29 | }
|
| 30 | self.redo.clear();
|
| 31 | }
|
| 32 |
|
| 33 | pub fn undo(&mut self, current: &str) -> Option<String> {
|
| 34 | let prev = self.undo.pop()?;
|
| 35 | self.redo.push(current.to_string());
|
| 36 | Some(prev)
|
| 37 | }
|
| 38 |
|
| 39 | pub fn redo(&mut self, current: &str) -> Option<String> {
|
| 40 | let next = self.redo.pop()?;
|
| 41 | self.undo.push(current.to_string());
|
| 42 | Some(next)
|
| 43 | }
|
| 44 | }
|
| 45 |
|
| 46 | #[cfg(test)]
|
| 47 | mod tests {
|
| 48 | use super::*;
|
| 49 |
|
| 50 | #[test]
|
| 51 | fn undo_redo_roundtrip() {
|
| 52 | let mut stack = TextUndo::default();
|
| 53 | stack.record("a".into());
|
| 54 | let u = stack.undo("b").unwrap();
|
| 55 | assert_eq!(u, "a");
|
| 56 | let r = stack.redo("a").unwrap();
|
| 57 | assert_eq!(r, "b");
|
| 58 | }
|
| 59 | }
|