//! GET /search?q=...: full-text search across note titles and bodies, inside the app shell. use std::sync::Arc; use topcoat::{ Result, context::{Cx, app_context}, router::{page, query_params}, view::{Child, View, view}, }; use crate::app::pane::{self, Entry}; use crate::app::shell::{now_millis, notebook_name, title_of}; use crate::i18n::{self, Msg, relative_time, results_for, t}; use crate::matcher::{Matcher, Options}; use crate::store::Store; use note_model::links::percent_encode; /// Most results shown on one page. const RESULT_LIMIT: usize = 50; /// How long a search reads long notes before it shows what it found, with a link to /// search them all. const SEARCH_BUDGET: std::time::Duration = std::time::Duration::from_millis(500); /// The `q` parameter of the search page and of the sidebar search box, and the search /// filters, each on when its parameter is "1". #[query_params(error = bad_request)] pub struct SearchQuery { pub q: Option, pub case: Option, pub word: Option, pub exact: Option, pub re: Option, /// "1": read every note, however long it takes. pub all: Option, } /// GET /search: notes whose title or text contain every word of `q`. #[page] async fn search(cx: &Cx) -> Result { let store = app_context::>(cx); let query = query_params::(cx)?; let q = query.q.as_deref().unwrap_or("").trim().to_owned(); let flag = |v: &Option| v.as_deref() == Some("1"); let opts = Options { case: flag(&query.case), word: flag(&query.word), exact: flag(&query.exact), regex: flag(&query.re), }; let (matcher, invalid) = match Matcher::new(&q, opts) { Ok(m) => (m, false), Err(_) => (None, true), }; if matcher.is_none() && !invalid { return Ok(Child::new(crate::app::all_notes(cx).await?)); } let budget = (!flag(&query.all)).then_some(SEARCH_BUDGET); let (hits, partial) = match &matcher { Some(m) => { let found = store.search(m, RESULT_LIMIT, budget).await.map_err(topcoat::Error::from_anyhow)?; (found.hits, found.partial) } None => (Vec::new(), false), }; // The same search without the budget. let search_all = partial.then(|| { let mut href = format!("/search?q={}&all=1", percent_encode(&q)); for (on, key) in [(opts.case, "case"), (opts.word, "word"), (opts.exact, "exact"), (opts.regex, "re")] { if on { href.push_str(&format!("&{key}=1")); } } href }); let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?; let lang = i18n::lang(cx); let now = now_millis(); let count = hits.len(); let entries: Vec = hits .into_iter() .map(|hit| { let title = title_of(lang, &hit.note.title); let excerpt = excerpt(&hit.snippet, &title); Entry { href: format!("/notes/{}", hit.note.id), when: relative_time(lang, hit.note.updated_at, now), parts: matcher.as_ref().map_or_else(Vec::new, |m| highlight(&excerpt, m)), notebook: notebook_name(¬ebooks, hit.note.notebook_id.as_deref()), title, selected: false, } }) .collect(); let title = t(lang, Msg::Search); // The filters in use, after the count: "2 results for “x” · Match case, Whole word". let active: Vec<&str> = [ (opts.case, Msg::MatchCase), (opts.word, Msg::WholeWord), (opts.exact, Msg::ExactPhrase), (opts.regex, Msg::RegexSearch), ] .into_iter() .filter(|(on, _)| *on) .map(|(_, msg)| t(lang, msg)) .collect(); let summary = if active.is_empty() { results_for(lang, count, &q) } else { format!("{} · {}", results_for(lang, count, &q), active.join(", ")) }; let (no_matches, check) = if invalid { (t(lang, Msg::InvalidRegex), t(lang, Msg::InvalidRegexHint)) } else { (t(lang, Msg::NoMatches), t(lang, Msg::CheckSpelling)) }; // Results take the list pane's place, like any other list of notes. let list = view! {
if entries.is_empty() {

(no_matches)

(check)

} else {
    for entry in entries { (Child::new(pane::entry_item(cx, entry, true))) }
}
}; Ok(Child::new(pane::split( cx, pane::Mobile::List, Child::new(list), Child::new(pane::empty_detail(cx, lang)), ))) } /// The excerpt without the note's title line, which the row already shows. When the /// excerpt is only the title, the result is empty. fn excerpt(snippet: &str, title: &str) -> String { match snippet.strip_prefix(title.trim()) { Some(rest) => rest.trim_start().to_owned(), None => snippet.to_owned(), } } /// Splits `text` into runs, marking where `matcher` matches. fn highlight(text: &str, matcher: &Matcher) -> Vec<(String, bool)> { let chars: Vec = text.chars().collect(); let mut parts = Vec::new(); let mut at = 0; for (start, end) in matcher.ranges(text) { if start > at { parts.push((chars[at..start].iter().collect(), false)); } parts.push((chars[start..end].iter().collect(), true)); at = end; } if at < chars.len() { parts.push((chars[at..].iter().collect(), false)); } parts }