kimun_notes/components/search_list/seams.rs
1//! The seams a `SearchList` varies across (see CONTEXT.md: SearchList, Row
2//! source, Search row, Suggestion source). Everything else is folded into the
3//! engine.
4
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use ratatui::widgets::ListItem;
9
10use crate::settings::icons::Icons;
11use crate::settings::themes::Theme;
12
13/// What a single row must tell its `SearchList` to be listed, filtered,
14/// navigated and drawn. The only thing that varies with the row's type.
15pub trait SearchRow: Clone + Send + Sync + 'static {
16 /// Collapsed one-or-few-line rendering. `selected` lets a row self-style.
17 fn to_list_item(&self, theme: &Theme, icons: &Icons, selected: bool) -> ListItem<'static>;
18
19 /// Terminal rows this collapsed item occupies (mouse hit-testing / scroll).
20 fn visual_height(&self) -> u16 {
21 1
22 }
23
24 /// Haystack a LOCAL filter (`Filter::Fuzzy`/`Rank`) matches against.
25 /// `None` => never removed by a local filter (e.g. an "Up .." / "Create"
26 /// / pinned virtual row); ignored entirely by `Filter::SourceOrder`.
27 fn match_text(&self) -> Option<&str> {
28 None
29 }
30
31 /// What this row offers to the OS clipboard, or `None` when it has nothing
32 /// worth copying (a command entry, a virtual "Up .." row).
33 ///
34 /// Declared by the row rather than by the surface displaying it, so every
35 /// list built on [`SearchList`](super::SearchList) inherits the yank instead
36 /// of each panel wiring its own key — which is how the note browser ended up
37 /// without one while the Query panel had it.
38 fn yank_target(&self) -> Option<YankTarget> {
39 None
40 }
41}
42
43/// A row's contribution to the OS clipboard: the text, plus the noun naming it
44/// so the confirmation says *what* was copied ("path copied", "tag copied")
45/// rather than a bare "copied" that would be a lie where nothing was.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct YankTarget {
48 pub text: String,
49 pub noun: &'static str,
50}
51
52impl YankTarget {
53 pub fn new(text: impl Into<String>, noun: &'static str) -> Self {
54 Self {
55 text: text.into(),
56 noun,
57 }
58 }
59
60 /// The overwhelmingly common case: a row that stands for a note.
61 pub fn path(text: impl Into<String>) -> Self {
62 Self::new(text, "path")
63 }
64}
65
66/// How rows arrive from a source. One-shot sources send one `Replace`;
67/// streamed sources send many `Push` then `Done`.
68pub enum Loaded<R> {
69 Replace(Vec<R>),
70 Push(R),
71 Done,
72}
73
74/// Ranking function for `Filter::Rank`: takes the full row slice, the candidate
75/// indices into it (`base` — already in `SearchListBuilder::order_by` order, so
76/// ranking may fall back on it for ties), and the current query string; returns
77/// display indices in preferred order (absent = hidden).
78pub type RankFn<R> = std::sync::Arc<dyn Fn(&[R], &[usize], &str) -> Vec<usize> + Send + Sync>;
79
80/// Total order over rows for `SearchListBuilder::order_by`: applied to the
81/// row set before any local filter, so streamed rows land in place as they
82/// arrive and a sort change is a recompute, not a reload.
83pub type OrderFn<R> = std::sync::Arc<dyn Fn(&R, &R) -> std::cmp::Ordering + Send + Sync>;
84
85/// How a loaded row set is narrowed/ordered for display. Three known
86/// strategies; none need test substitution, so folded in here.
87pub enum Filter<R: SearchRow> {
88 /// Trust the source's order (server-side filter already applied).
89 SourceOrder,
90 /// Local nucleo fuzzy over `match_text`.
91 Fuzzy,
92 /// Local rank: `(rows, base, query) -> display indices` (lower = better;
93 /// absent = hidden). `base` carries the `order_by` order, so honoring it
94 /// for equally-ranked rows is what makes the two compose.
95 Rank(RankFn<R>),
96}
97
98/// The sink a `RowSource` writes rows into. Cheap to clone; carries the load
99/// generation so the engine can drop results from a superseded load.
100#[derive(Clone)]
101pub struct Emit<R> {
102 tx: std::sync::mpsc::Sender<(u64, Loaded<R>)>,
103 generation: u64,
104 redraw: Arc<dyn Fn() + Send + Sync>,
105}
106
107impl<R> Emit<R> {
108 pub(super) fn new(
109 tx: std::sync::mpsc::Sender<(u64, Loaded<R>)>,
110 generation: u64,
111 redraw: Arc<dyn Fn() + Send + Sync>,
112 ) -> Self {
113 Self {
114 tx,
115 generation,
116 redraw,
117 }
118 }
119
120 /// One-shot: deliver the whole set.
121 pub fn replace(&self, rows: Vec<R>) {
122 let _ = self.tx.send((self.generation, Loaded::Replace(rows)));
123 (self.redraw)();
124 }
125
126 /// Streamed: one row at a time.
127 pub fn push(&self, row: R) {
128 let _ = self.tx.send((self.generation, Loaded::Push(row)));
129 (self.redraw)();
130 }
131
132 /// Streamed: no more rows for this generation.
133 pub fn done(&self) {
134 let _ = self.tx.send((self.generation, Loaded::Done));
135 (self.redraw)();
136 }
137
138 /// Test sink: an `Emit` whose every event lands on the returned receiver,
139 /// so a source's delivery sequence can be asserted without an engine.
140 #[cfg(test)]
141 pub(crate) fn capture() -> (Self, std::sync::mpsc::Receiver<(u64, Loaded<R>)>) {
142 let (tx, rx) = std::sync::mpsc::channel();
143 (Self::new(tx, 0, Arc::new(|| {})), rx)
144 }
145}
146
147/// One autocomplete candidate: the inserted/display text plus an optional
148/// secondary line shown muted in the popup (a note path, a tag usage count).
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct SuggestionItem {
151 pub display: String,
152 pub secondary: Option<String>,
153}
154
155impl SuggestionItem {
156 pub fn plain(display: impl Into<String>) -> Self {
157 Self {
158 display: display.into(),
159 secondary: None,
160 }
161 }
162}
163
164/// Autocomplete candidates for the query input, kept separate from the vault
165/// so the autocomplete host is testable in isolation.
166#[async_trait]
167pub trait SuggestionSource: Send + Sync + 'static {
168 async fn notes_by_prefix(&self, prefix: &str, limit: usize) -> Vec<SuggestionItem>;
169 async fn tags_by_prefix(&self, prefix: &str, limit: usize) -> Vec<SuggestionItem>;
170
171 /// Saved searches whose name matches `prefix` (case-insensitive). Each
172 /// item's `display` is the name and `secondary` the stored query — the
173 /// popup preview AND the text inserted on accept.
174 /// Defaults to empty so non-search-box suggestion sources opt out.
175 async fn saved_searches_by_prefix(&self, _prefix: &str, _limit: usize) -> Vec<SuggestionItem> {
176 Vec::new()
177 }
178}
179
180/// Production adapter over the vault. Formats the secondary line (note path,
181/// tag usage count) so the popup looks exactly as before.
182pub struct VaultSuggestions {
183 pub vault: std::sync::Arc<kimun_core::NoteVault>,
184}
185
186#[async_trait]
187impl SuggestionSource for VaultSuggestions {
188 async fn notes_by_prefix(&self, prefix: &str, limit: usize) -> Vec<SuggestionItem> {
189 self.vault
190 .suggest_notes_by_prefix(prefix, limit)
191 .await
192 .map(|v| {
193 v.into_iter()
194 .map(|n| SuggestionItem {
195 display: n.name,
196 secondary: Some(n.path.to_string()),
197 })
198 .collect()
199 })
200 .unwrap_or_default()
201 }
202 async fn tags_by_prefix(&self, prefix: &str, limit: usize) -> Vec<SuggestionItem> {
203 self.vault
204 .suggest_tags_by_prefix(prefix, limit)
205 .await
206 .map(|v| {
207 v.into_iter()
208 .map(|t| SuggestionItem {
209 display: t.label,
210 secondary: Some(format!("{}×", t.usage_count)),
211 })
212 .collect()
213 })
214 .unwrap_or_default()
215 }
216 async fn saved_searches_by_prefix(&self, prefix: &str, limit: usize) -> Vec<SuggestionItem> {
217 // Prefix matching + casing live in core (`NoteVault`), like the
218 // notes/tags suggestion sources. Here we only adapt to `SuggestionItem`:
219 // the name is the popup row, the stored query is the muted preview AND
220 // the text inserted on accept.
221 self.vault
222 .suggest_saved_searches_by_prefix(prefix, limit)
223 .await
224 .map(|v| {
225 v.into_iter()
226 .map(|s| SuggestionItem {
227 display: s.name,
228 secondary: Some(s.query),
229 })
230 .collect()
231 })
232 .unwrap_or_default()
233 }
234}
235
236/// Where a `SearchList`'s rows come from. Vault-backed in the app, in-memory
237/// in tests. Streaming vs one-shot is a delivery detail of the SAME seam.
238#[async_trait]
239pub trait RowSource<R: SearchRow>: Send + Sync + 'static {
240 /// Called on construction and on every committed query change. Empty query
241 /// = initial state. Write rows into `emit`. Cancel-safe: the engine drops
242 /// the prior load on requery, so a slow source may be left unfinished.
243 async fn load(&self, query: &str, emit: Emit<R>);
244
245 /// An optional synthetic leading row (the `Create: <q>` affordance),
246 /// prepended and exempt from local filtering. Keeps create-policy here.
247 fn leading_row(&self, _query: &str) -> Option<R> {
248 None
249 }
250
251 /// `true` (default): `load` is re-run on every query keystroke (server-side
252 /// filter). `false`: `load` runs once with `""`, then a local `Filter`
253 /// narrows the set per keystroke.
254 fn reload_on_query(&self) -> bool {
255 true
256 }
257}
258
259/// A [`RowSource`] for the synchronous build path: its rows are supplied at
260/// build time via [`SearchListBuilder::build_with_rows`], so its async `load`
261/// is never called. Pairs with any static, in-memory row set
262/// (`reload_on_query() == false` — the query is a local filter over the built
263/// rows), replacing a hand-rolled one-shot `emit.replace(rows.clone())` source.
264///
265/// [`SearchListBuilder::build_with_rows`]: super::SearchListBuilder::build_with_rows
266pub struct StaticRowSource;
267
268#[async_trait]
269impl<R: SearchRow> RowSource<R> for StaticRowSource {
270 async fn load(&self, _query: &str, _emit: Emit<R>) {}
271 fn reload_on_query(&self) -> bool {
272 false
273 }
274}
275
276#[cfg(test)]
277mod suggestion_tests {
278 use super::*;
279 struct Mem {
280 notes: Vec<SuggestionItem>,
281 tags: Vec<SuggestionItem>,
282 }
283 #[async_trait]
284 impl SuggestionSource for Mem {
285 async fn notes_by_prefix(&self, p: &str, _n: usize) -> Vec<SuggestionItem> {
286 self.notes
287 .iter()
288 .filter(|x| x.display.starts_with(p))
289 .cloned()
290 .collect()
291 }
292 async fn tags_by_prefix(&self, p: &str, _n: usize) -> Vec<SuggestionItem> {
293 self.tags
294 .iter()
295 .filter(|x| x.display.starts_with(p))
296 .cloned()
297 .collect()
298 }
299 }
300 #[tokio::test]
301 async fn mem_suggestions_filter_by_prefix() {
302 let m = Mem {
303 notes: vec![SuggestionItem {
304 display: "projects".into(),
305 secondary: Some("work/projects".into()),
306 }],
307 tags: vec![SuggestionItem::plain("todo")],
308 };
309 assert_eq!(m.notes_by_prefix("pro", 9).await.len(), 1);
310 assert_eq!(m.notes_by_prefix("pro", 9).await[0].display, "projects");
311 assert_eq!(m.tags_by_prefix("to", 9).await[0].display, "todo");
312 }
313}