Skip to main content

nex_core/
model.rs

1#[derive(Debug, Clone, PartialEq, Eq)]
2pub struct SearchItem {
3    pub id: String,
4    pub kind: String,
5    pub title: String,
6    pub path: String,
7    pub subtitle: String,
8    pub use_count: u32,
9    pub last_accessed_epoch_secs: i64,
10    normalized_title: String,
11    normalized_search_text: String,
12}
13
14impl SearchItem {
15    pub fn new(id: &str, kind: &str, title: &str, path: &str) -> Self {
16        Self::from_owned(
17            id.to_string(),
18            kind.to_string(),
19            title.to_string(),
20            path.to_string(),
21            0,
22            0,
23        )
24    }
25
26    pub fn from_owned(
27        id: String,
28        kind: String,
29        title: String,
30        path: String,
31        use_count: u32,
32        last_accessed_epoch_secs: i64,
33    ) -> Self {
34        Self::from_owned_with_subtitle(
35            id,
36            kind,
37            title,
38            path,
39            String::new(),
40            use_count,
41            last_accessed_epoch_secs,
42        )
43    }
44
45    pub fn from_owned_with_subtitle(
46        id: String,
47        kind: String,
48        title: String,
49        path: String,
50        subtitle: String,
51        use_count: u32,
52        last_accessed_epoch_secs: i64,
53    ) -> Self {
54        let normalized_title = normalize_for_search(&title);
55        let normalized_search_text = normalize_for_search(&format!("{title} {path} {subtitle}"));
56        Self {
57            id,
58            kind,
59            title,
60            path,
61            subtitle,
62            use_count,
63            last_accessed_epoch_secs,
64            normalized_title,
65            normalized_search_text,
66        }
67    }
68
69    pub fn with_usage(mut self, use_count: u32, last_accessed_epoch_secs: i64) -> Self {
70        self.use_count = use_count;
71        self.last_accessed_epoch_secs = last_accessed_epoch_secs;
72        self
73    }
74
75    pub fn with_subtitle(mut self, subtitle: &str) -> Self {
76        self.subtitle = subtitle.to_string();
77        self.normalized_search_text =
78            normalize_for_search(&format!("{} {} {}", self.title, self.path, self.subtitle));
79        self
80    }
81
82    pub fn normalized_title(&self) -> &str {
83        &self.normalized_title
84    }
85
86    pub fn normalized_search_text(&self) -> &str {
87        &self.normalized_search_text
88    }
89}
90
91pub fn normalize_for_search(input: &str) -> String {
92    input
93        .chars()
94        .filter(|c| c.is_alphanumeric())
95        .flat_map(|c| c.to_lowercase())
96        .collect()
97}