Skip to main content

lb_rs/search/
path.rs

1use super::{SearchFilter, SearchResult, build_descendants};
2use crate::Lb;
3use crate::io::docs::LocalDocuments;
4use crate::io::server::Server;
5use crate::model::file::File;
6use nucleo::{
7    Matcher, Nucleo,
8    pattern::{CaseMatching, Normalization},
9};
10use std::cmp::Reverse;
11use std::collections::{HashMap, HashSet};
12use std::sync::Arc;
13use uuid::Uuid;
14
15/// Split a path into (parent_path, filename).
16pub(crate) fn split_path(path: &str) -> (&str, &str) {
17    // Strip trailing slash for folders
18    let path = path.trim_end_matches('/');
19    match path.rfind('/') {
20        Some(idx) if idx > 0 => (&path[..idx], &path[idx + 1..]),
21        Some(_) => ("/", &path[1..]), // root case: "/filename"
22        None => ("", path),
23    }
24}
25
26#[derive(Clone)]
27struct PathEntry {
28    file: File,
29    path: String,
30    filename: String,
31    parent_path: String,
32}
33
34fn path_result(entry: &PathEntry, path_indices: Vec<u32>) -> SearchResult {
35    SearchResult {
36        id: entry.file.id,
37        filename: entry.filename.clone(),
38        parent_path: entry.parent_path.clone(),
39        is_folder: entry.file.is_folder(),
40        path_indices,
41        path_matches: Vec::new(),
42        content_matches: Vec::new(),
43    }
44}
45
46pub struct PathSearcher {
47    nucleo: Nucleo<PathEntry>,
48    results: Vec<SearchResult>,
49    submitted_query: String,
50    descendants: HashMap<Uuid, Vec<Uuid>>,
51    path_to_id: HashMap<String, Uuid>,
52    filter_ids: Option<HashSet<Uuid>>,
53    searched: Vec<Uuid>,
54}
55
56impl PathSearcher {
57    pub async fn new<S: Server, D: LocalDocuments>(lb: &Lb<S, D>) -> Self {
58        let files = lb.list_metadatas().await.unwrap_or_default();
59        let paths = lb.list_paths_with_ids(None).await.unwrap_or_default();
60        let by_id: HashMap<Uuid, File> = files.into_iter().map(|f| (f.id, f)).collect();
61        let mut searcher = Self::from_files(
62            paths
63                .into_iter()
64                .filter_map(|(id, path)| by_id.get(&id).cloned().map(|file| (file, path))),
65        );
66        searcher.searched = lb.ro_tx().await.db().searched_files.as_slice().to_vec();
67        searcher.rebuild();
68        searcher
69    }
70
71    /// Build a path index from an in-memory file list (`File` + path string).
72    /// Same matcher as [`Self::new`]; used by editor link completions so they
73    /// share ranking (including empty-query recents) with filename search.
74    pub fn from_files(entries: impl IntoIterator<Item = (File, String)>) -> Self {
75        let notify = Arc::new(|| {});
76        let nucleo: Nucleo<PathEntry> = Nucleo::new(nucleo::Config::DEFAULT, notify, None, 1);
77        let injector = nucleo.injector();
78
79        let mut files = Vec::new();
80        let mut path_to_id = HashMap::new();
81
82        for (file, path) in entries {
83            if path == "/" {
84                files.push(file);
85                continue;
86            }
87            let (parent_path, filename) = split_path(&path);
88            injector.push(
89                PathEntry {
90                    file: file.clone(),
91                    path: path.clone(),
92                    filename: filename.to_string(),
93                    parent_path: parent_path.to_string(),
94                },
95                |entry, cols| {
96                    cols[0] = entry.path.as_str().into();
97                },
98            );
99            path_to_id.insert(path, file.id);
100            files.push(file);
101        }
102
103        let descendants = build_descendants(&files);
104
105        let mut searcher = Self {
106            nucleo,
107            results: Vec::new(),
108            submitted_query: String::new(),
109            descendants,
110            path_to_id,
111            filter_ids: None,
112            searched: Vec::new(),
113        };
114        searcher.query("");
115        searcher
116    }
117
118    /// Update the active filter and refresh results for the current query.
119    pub fn update_filter(&mut self, filter: Option<SearchFilter>) {
120        self.filter_ids = super::resolve_filter(filter, &self.path_to_id, &self.descendants);
121        self.rebuild();
122    }
123
124    /// Update the search query. Results available via `results()`.
125    pub fn query(&mut self, input: &str) {
126        self.nucleo.pattern.reparse(
127            0,
128            input,
129            CaseMatching::Smart,
130            Normalization::Smart,
131            input.starts_with(&self.submitted_query),
132        );
133        self.submitted_query = input.to_string();
134
135        while self.nucleo.tick(10).running {}
136
137        self.rebuild();
138    }
139
140    /// Rebuild `results` from the current query and filter without re-running the
141    /// matcher. Shared by `query` (after a reparse) and `update_filter`.
142    fn rebuild(&mut self) {
143        self.results.clear();
144        let snapshot = self.nucleo.snapshot();
145
146        if self.submitted_query.is_empty() {
147            let mut entries: Vec<&PathEntry> = (0..snapshot.matched_item_count())
148                .filter_map(|i| snapshot.get_matched_item(i).map(|item| item.data))
149                .filter(|e| {
150                    self.filter_ids
151                        .as_ref()
152                        .is_none_or(|ids| ids.contains(&e.file.id))
153                })
154                .collect();
155            entries.sort_by_cached_key(|e| {
156                let searched = self.searched.iter().rposition(|id| *id == e.file.id);
157                (Reverse(searched), Reverse(e.file.last_modified))
158            });
159            self.results.extend(
160                entries
161                    .into_iter()
162                    .take(100)
163                    .map(|e| path_result(e, Vec::new())),
164            );
165            return;
166        }
167
168        let mut matcher = Matcher::new(nucleo::Config::DEFAULT);
169
170        for i in 0..snapshot.matched_item_count() {
171            if self.results.len() >= 100 {
172                break;
173            }
174            if let Some(item) = snapshot.get_matched_item(i) {
175                if let Some(ids) = &self.filter_ids {
176                    if !ids.contains(&item.data.file.id) {
177                        continue;
178                    }
179                }
180
181                let mut indices = Vec::new();
182                self.nucleo.pattern.column_pattern(0).indices(
183                    item.matcher_columns[0].slice(..),
184                    &mut matcher,
185                    &mut indices,
186                );
187
188                self.results.push(path_result(item.data, indices));
189            }
190        }
191    }
192
193    /// Get search results.
194    pub fn results(&self) -> &[SearchResult] {
195        &self.results
196    }
197}