Branchwell

Clearwake / app · clearwake.ai / crates / clearwake-core / src / history.rs

1//! Back and forward.
2
3use alloc::string::String;
4use alloc::vec::Vec;
5
6#[derive(Default, Clone, Debug)]
7pub struct History {
8 back: Vec<String>,
9 current: Option<String>,
10 forward: Vec<String>,
11}
12
13impl History {
14 /// A new page was opened by the person (not back or forward).
15 pub fn visit(&mut self, url: String) {
16 if self.current.as_deref() == Some(url.as_str()) {
17 return;
18 }
19 if let Some(c) = self.current.take() {
20 self.back.push(c);
21 if self.back.len() > 500 {
22 self.back.remove(0);
23 }
24 }
25 self.current = Some(url);
26 self.forward.clear();
27 }
28
29 /// After a redirect, the page that opened has a different address.
30 pub fn replace(&mut self, url: String) {
31 self.current = Some(url);
32 }
33
34 pub fn current(&self) -> Option<&str> {
35 self.current.as_deref()
36 }
37 pub fn can_back(&self) -> bool {
38 !self.back.is_empty()
39 }
40 pub fn can_forward(&self) -> bool {
41 !self.forward.is_empty()
42 }
43
44 pub fn back(&mut self) -> Option<String> {
45 let prev = self.back.pop()?;
46 if let Some(c) = self.current.replace(prev.clone()) {
47 self.forward.push(c);
48 }
49 Some(prev)
50 }
51
52 pub fn forward(&mut self) -> Option<String> {
53 let next = self.forward.pop()?;
54 if let Some(c) = self.current.replace(next.clone()) {
55 self.back.push(c);
56 }
57 Some(next)
58 }
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64 #[test]
65 fn back_and_forward() {
66 let mut h = History::default();
67 h.visit("a".into());
68 h.visit("b".into());
69 h.visit("c".into());
70 assert_eq!(h.back().as_deref(), Some("b"));
71 assert_eq!(h.back().as_deref(), Some("a"));
72 assert!(h.back().is_none());
73 assert_eq!(h.forward().as_deref(), Some("b"));
74 h.visit("d".into());
75 assert!(!h.can_forward());
76 assert_eq!(h.current(), Some("d"));
77 }
78}