Branchwell

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

Raw 2.4 KB on 50233c80eae1be554eda84594e30c13efcafb9d4
1//! Bookmarks, kept on this device only. No account, no sync.
2
3use alloc::string::{String, ToString};
4use alloc::vec::Vec;
5
6#[derive(Clone, Debug, PartialEq, Eq)]
7pub struct Bookmark {
8 pub title: String,
9 pub url: String,
10}
11
12#[derive(Clone, Debug, Default, PartialEq, Eq)]
13pub struct Bookmarks {
14 pub items: Vec<Bookmark>,
15}
16
17impl Bookmarks {
18 pub fn contains(&self, url: &str) -> bool {
19 self.items.iter().any(|b| b.url == url)
20 }
21
22 /// Add the page, or remove it when it is already saved. Returns true
23 /// when the page is saved afterwards.
24 pub fn toggle(&mut self, url: &str, title: &str) -> bool {
25 if let Some(i) = self.items.iter().position(|b| b.url == url) {
26 self.items.remove(i);
27 false
28 } else {
29 let title = if title.trim().is_empty() { url } else { title.trim() };
30 self.items.push(Bookmark { title: title.to_string(), url: url.to_string() });
31 true
32 }
33 }
34
35 pub fn remove(&mut self, url: &str) {
36 self.items.retain(|b| b.url != url);
37 }
38
39 /// One bookmark per line: address, a tab, then the title.
40 pub fn to_text(&self) -> String {
41 let mut s = String::new();
42 for b in &self.items {
43 s.push_str(&b.url);
44 s.push('\t');
45 s.push_str(&b.title.replace(['\t', '\n'], " "));
46 s.push('\n');
47 }
48 s
49 }
50
51 pub fn from_text(text: &str) -> Bookmarks {
52 let items = text
53 .lines()
54 .filter_map(|l| {
55 let mut p = l.splitn(2, '\t');
56 let url = p.next()?.trim();
57 if url.is_empty() {
58 return None;
59 }
60 let title = p.next().unwrap_or(url).trim();
61 Some(Bookmark { title: title.to_string(), url: url.to_string() })
62 })
63 .collect();
64 Bookmarks { items }
65 }
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71 #[test]
72 fn round_trip() {
73 let mut b = Bookmarks::default();
74 assert!(b.toggle("https://a.example/", "A\tpage"));
75 assert!(b.toggle("https://b.example/", ""));
76 let back = Bookmarks::from_text(&b.to_text());
77 assert_eq!(back.items[0].title, "A page");
78 assert_eq!(back.items[1].title, "https://b.example/");
79 assert!(!b.toggle("https://a.example/", "A"));
80 assert!(!b.contains("https://a.example/"));
81 }
82}