| 1 | |
| 2 | |
| 3 | use std::sync::Arc; |
| 4 | |
| 5 | use topcoat::{ |
| 6 | Result, |
| 7 | context::{Cx, app_context}, |
| 8 | router::{page, query_params}, |
| 9 | view::{Child, View, view}, |
| 10 | }; |
| 11 | |
| 12 | use crate::app::pane::{self, Entry}; |
| 13 | use crate::app::shell::{now_millis, notebook_name, title_of}; |
| 14 | use crate::i18n::{self, Msg, relative_time, results_for, t}; |
| 15 | use crate::matcher::{Matcher, Options}; |
| 16 | use crate::store::Store; |
| 17 | use note_model::links::percent_encode; |
| 18 | |
| 19 | |
| 20 | const RESULT_LIMIT: usize = 50; |
| 21 | |
| 22 | |
| 23 | const SEARCH_BUDGET: std::time::Duration = std::time::Duration::from_millis(500); |
| 24 | |
| 25 | |
| 26 | |
| 27 | #[query_params(error = bad_request)] |
| 28 | pub struct SearchQuery { |
| 29 | pub q: Option<String>, |
| 30 | pub case: Option<String>, |
| 31 | pub word: Option<String>, |
| 32 | pub exact: Option<String>, |
| 33 | pub re: Option<String>, |
| 34 | |
| 35 | pub all: Option<String>, |
| 36 | } |
| 37 | |
| 38 | |
| 39 | #[page] |
| 40 | async fn search(cx: &Cx) -> Result<impl View> { |
| 41 | let store = app_context::<Arc<Store>>(cx); |
| 42 | let query = query_params::<SearchQuery>(cx)?; |
| 43 | let q = query.q.as_deref().unwrap_or("").trim().to_owned(); |
| 44 | let flag = |v: &Option<String>| v.as_deref() == Some("1"); |
| 45 | let opts = Options { |
| 46 | case: flag(&query.case), |
| 47 | word: flag(&query.word), |
| 48 | exact: flag(&query.exact), |
| 49 | regex: flag(&query.re), |
| 50 | }; |
| 51 | let (matcher, invalid) = match Matcher::new(&q, opts) { |
| 52 | Ok(m) => (m, false), |
| 53 | Err(_) => (None, true), |
| 54 | }; |
| 55 | if matcher.is_none() && !invalid { |
| 56 | return Ok(Child::new(crate::app::all_notes(cx).await?)); |
| 57 | } |
| 58 | |
| 59 | let budget = (!flag(&query.all)).then_some(SEARCH_BUDGET); |
| 60 | let (hits, partial) = match &matcher { |
| 61 | Some(m) => { |
| 62 | let found = store.search(m, RESULT_LIMIT, budget).await.map_err(topcoat::Error::from_anyhow)?; |
| 63 | (found.hits, found.partial) |
| 64 | } |
| 65 | None => (Vec::new(), false), |
| 66 | }; |
| 67 | |
| 68 | let search_all = partial.then(|| { |
| 69 | let mut href = format!("/search?q={}&all=1", percent_encode(&q)); |
| 70 | for (on, key) in [(opts.case, "case"), (opts.word, "word"), (opts.exact, "exact"), (opts.regex, "re")] { |
| 71 | if on { |
| 72 | href.push_str(&format!("&{key}=1")); |
| 73 | } |
| 74 | } |
| 75 | href |
| 76 | }); |
| 77 | let notebooks = store.list_notebooks().await.map_err(topcoat::Error::from_anyhow)?; |
| 78 | let lang = i18n::lang(cx); |
| 79 | let now = now_millis(); |
| 80 | let count = hits.len(); |
| 81 | let entries: Vec<Entry> = hits |
| 82 | .into_iter() |
| 83 | .map(|hit| { |
| 84 | let title = title_of(lang, &hit.note.title); |
| 85 | let excerpt = excerpt(&hit.snippet, &title); |
| 86 | Entry { |
| 87 | href: format!("/notes/{}", hit.note.id), |
| 88 | when: relative_time(lang, hit.note.updated_at, now), |
| 89 | parts: matcher.as_ref().map_or_else(Vec::new, |m| highlight(&excerpt, m)), |
| 90 | notebook: notebook_name(¬ebooks, hit.note.notebook_id.as_deref()), |
| 91 | title, |
| 92 | selected: false, |
| 93 | } |
| 94 | }) |
| 95 | .collect(); |
| 96 | |
| 97 | let title = t(lang, Msg::Search); |
| 98 | |
| 99 | let active: Vec<&str> = [ |
| 100 | (opts.case, Msg::MatchCase), |
| 101 | (opts.word, Msg::WholeWord), |
| 102 | (opts.exact, Msg::ExactPhrase), |
| 103 | (opts.regex, Msg::RegexSearch), |
| 104 | ] |
| 105 | .into_iter() |
| 106 | .filter(|(on, _)| *on) |
| 107 | .map(|(_, msg)| t(lang, msg)) |
| 108 | .collect(); |
| 109 | let summary = if active.is_empty() { |
| 110 | results_for(lang, count, &q) |
| 111 | } else { |
| 112 | format!("{} · {}", results_for(lang, count, &q), active.join(", ")) |
| 113 | }; |
| 114 | let (no_matches, check) = if invalid { |
| 115 | (t(lang, Msg::InvalidRegex), t(lang, Msg::InvalidRegexHint)) |
| 116 | } else { |
| 117 | (t(lang, Msg::NoMatches), t(lang, Msg::CheckSpelling)) |
| 118 | }; |
| 119 | |
| 120 | |
| 121 | |
| 122 | let list = view! { |
| 123 | <section class="flex min-h-0 min-w-0 flex-1 flex-col"> |
| 124 | <header class="sidebar-lead flex shrink-0 items-center gap-2 border-b border-border px-4 py-3"> |
| 125 | <div class="min-w-0 flex-1"> |
| 126 | <h1 class="truncate text-base font-semibold">(title)</h1> |
| 127 | <p class="truncate text-xs text-muted-foreground">(summary)</p> |
| 128 | if let Some(href) = search_all { |
| 129 | <p class="text-xs text-muted-foreground"> |
| 130 | (t(lang, Msg::SearchPartial))" " |
| 131 | <a href=(href) class="font-medium underline underline-offset-4">(t(lang, Msg::SearchAll))</a> |
| 132 | </p> |
| 133 | } |
| 134 | </div> |
| 135 | </header> |
| 136 | <div class="min-h-0 flex-1 overflow-y-auto"> |
| 137 | if entries.is_empty() { |
| 138 | <div class="flex flex-col items-center gap-2 px-6 py-12 text-center"> |
| 139 | <p class="text-sm font-medium">(no_matches)</p> |
| 140 | <p class="text-sm text-muted-foreground">(check)</p> |
| 141 | </div> |
| 142 | } else { |
| 143 | <ul class="divide-y divide-border"> |
| 144 | for entry in entries { |
| 145 | (Child::new(pane::entry_item(cx, entry, true))) |
| 146 | } |
| 147 | </ul> |
| 148 | } |
| 149 | </div> |
| 150 | </section> |
| 151 | }; |
| 152 | Ok(Child::new(pane::split( |
| 153 | cx, |
| 154 | pane::Mobile::List, |
| 155 | Child::new(list), |
| 156 | Child::new(pane::empty_detail(cx, lang)), |
| 157 | ))) |
| 158 | } |
| 159 | |
| 160 | |
| 161 | |
| 162 | fn excerpt(snippet: &str, title: &str) -> String { |
| 163 | match snippet.strip_prefix(title.trim()) { |
| 164 | Some(rest) => rest.trim_start().to_owned(), |
| 165 | None => snippet.to_owned(), |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | |
| 170 | fn highlight(text: &str, matcher: &Matcher) -> Vec<(String, bool)> { |
| 171 | let chars: Vec<char> = text.chars().collect(); |
| 172 | let mut parts = Vec::new(); |
| 173 | let mut at = 0; |
| 174 | for (start, end) in matcher.ranges(text) { |
| 175 | if start > at { |
| 176 | parts.push((chars[at..start].iter().collect(), false)); |
| 177 | } |
| 178 | parts.push((chars[start..end].iter().collect(), true)); |
| 179 | at = end; |
| 180 | } |
| 181 | if at < chars.len() { |
| 182 | parts.push((chars[at..].iter().collect(), false)); |
| 183 | } |
| 184 | parts |
| 185 | } |