crisol_plot_core/
history.rs1use crisol_core::data::Bounds;
4
5#[derive(Clone, Debug, Default, PartialEq)]
7pub struct ViewHistory {
8 entries: Vec<Option<Bounds>>,
9 index: usize,
10}
11
12impl ViewHistory {
13 pub fn new() -> Self {
15 Self {
16 entries: vec![None],
17 index: 0,
18 }
19 }
20
21 pub fn with_view(view: Bounds) -> Self {
23 Self {
24 entries: vec![Some(view)],
25 index: 0,
26 }
27 }
28
29 pub fn push(&mut self, view: Option<Bounds>) {
31 if self.current() == view.as_ref() {
32 return;
33 }
34 self.entries.truncate(self.index + 1);
35 self.entries.push(view);
36 self.index = self.entries.len() - 1;
37 if self.entries.len() > 64 {
38 self.entries.remove(0);
39 self.index = self.index.saturating_sub(1);
40 }
41 }
42
43 pub fn current(&self) -> Option<&Bounds> {
45 self.entries.get(self.index).and_then(Option::as_ref)
46 }
47
48 pub fn back(&mut self) -> bool {
50 if self.index == 0 {
51 return false;
52 }
53 self.index -= 1;
54 true
55 }
56
57 pub fn forward(&mut self) -> bool {
59 if self.index + 1 >= self.entries.len() {
60 return false;
61 }
62 self.index += 1;
63 true
64 }
65
66 pub fn can_back(&self) -> bool {
68 self.index > 0
69 }
70
71 pub fn can_forward(&self) -> bool {
73 self.index + 1 < self.entries.len()
74 }
75
76 pub fn len(&self) -> usize {
78 self.entries.len()
79 }
80
81 pub fn is_empty(&self) -> bool {
83 self.entries.len() <= 1
84 }
85}
86
87#[cfg(test)]
88mod tests {
89 use super::*;
90
91 #[test]
92 fn back_and_forward_walk_the_zoom_history() {
93 let mut history = ViewHistory::new();
94 let first = Bounds::from_corners([0.0, 0.0], [1.0, 1.0]);
95 let second = Bounds::from_corners([0.2, 0.2], [0.8, 0.8]);
96 history.push(Some(first));
97 history.push(Some(second));
98 assert_eq!(history.current(), Some(&second));
99 assert!(history.back());
100 assert_eq!(history.current(), Some(&first));
101 assert!(history.forward());
102 assert_eq!(history.current(), Some(&second));
103 history.push(None);
104 assert!(!history.can_forward());
105 }
106
107 #[test]
108 fn duplicate_views_do_not_grow_the_history() {
109 let mut history = ViewHistory::with_view(Bounds::from_corners([0.0, 0.0], [1.0, 1.0]));
110 history.push(Some(Bounds::from_corners([0.0, 0.0], [1.0, 1.0])));
111 assert_eq!(history.len(), 1);
112 }
113}