diff --git a/crates/Cargo.lock b/crates/Cargo.lock index fcf1a0965..7ee50b4dc 100644 --- a/crates/Cargo.lock +++ b/crates/Cargo.lock @@ -8212,6 +8212,7 @@ dependencies = [ "js-sys", "libc", "libcrux-ml-kem", + "memchr", "ml-kem", "negentropy", "noq-proto", diff --git a/crates/vector-core/Cargo.toml b/crates/vector-core/Cargo.toml index 15a268362..1e80ce6d0 100644 --- a/crates/vector-core/Cargo.toml +++ b/crates/vector-core/Cargo.toml @@ -82,6 +82,7 @@ ghash = "0.6" argon2 = "0.5.3" sha2 = "0.10.9" unicode-normalization = "0.1" +memchr = "2" # HKDF-SHA256 for the Community protocol's frozen key-derivation convention # (GROUP_PROTOCOL.md §14). Audited RustCrypto crate rather than a hand-rolled # construction, since the derivation is wire-immutable. diff --git a/crates/vector-core/benches/core/main.rs b/crates/vector-core/benches/core/main.rs index 3be81095b..2b87c4027 100644 --- a/crates/vector-core/benches/core/main.rs +++ b/crates/vector-core/benches/core/main.rs @@ -12,6 +12,7 @@ mod compact; mod db_reads; mod parse; mod pool; +mod search; use nostr_sdk::prelude::{Keys, ToBech32}; use vector_core::crypto::guarded_key::bench as vault; @@ -38,6 +39,7 @@ const ALL: &[(&str, fn())] = &[ ("crypto::chacha20_raw", parse::chacha20_raw), ("crypto::nip44_decrypt", parse::nip44_decrypt), ("crypto::chacha20_backends", parse::chacha20_backends), + ("search::scan", search::scan), ("profile::processor", vector_core::profile::sync::bench::processor), ("vault::designs", vault::designs), ("vault::set_sources", vault::set_sources), diff --git a/crates/vector-core/benches/core/search.rs b/crates/vector-core/benches/core/search.rs new file mode 100644 index 000000000..d5aad58eb --- /dev/null +++ b/crates/vector-core/benches/core/search.rs @@ -0,0 +1,64 @@ +//! Message search: building the corpus, then the scans a keystroke runs. + +use std::time::Instant; +use vector_core::search::{Corpus, Filter, Has, Query, Record}; + +const WORDS: &[&str] = &[ + "the", "build", "relay", "lunch", "tomorrow", "café", "release", "voice", "channel", "bug", + "fixed", "photo", "meeting", "deploy", "東京", "会議", "night", "cats", "music", "invoice", +]; + +/// 200,000 messages of 12 to 30 words across 300 chats. +pub fn scan() { + const N: usize = 200_000; + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let records: Vec = (0..N) + .map(|i| { + let n = 12 + (next() % 19) as usize; + let text = (0..n).map(|_| WORDS[(next() % WORDS.len() as u64) as usize]).collect::>().join(" "); + let files = if i % 25 == 0 { vec![("jpg".to_string(), format!("IMG_{i}.jpg"))] } else { Vec::new() }; + Record { + chat: format!("chat{}", next() % 300), + id: format!("{i:064x}"), + author: Some(format!("npub1{:0>58}", next() % 500)), + mine: i % 7 == 0, + at: 1_800_000_000_000 - i as u64 * 1000, + text, + files, + } + }) + .collect(); + let t = Instant::now(); + let mut corpus = Corpus::new(); + for r in &records { + corpus.push(r, &r.text); + } + println!("build {:>9.1} ms ({} messages)", t.elapsed().as_secs_f64() * 1e3, corpus.len()); + + let cases: &[(&str, &str, Filter)] = &[ + ("rare word", "invoice deploy", Filter::default()), + ("common word", "the", Filter::default()), + ("no match", "zzzzzz", Filter::default()), + ("cjk", "会議", Filter::default()), + ("phrase", "\"lunch tomorrow\"", Filter::default()), + ("has:image", "", Filter { has: Has::IMAGE, ..Default::default() }), + ("in: + word", "relay", Filter { chats: vec!["chat7".into()], ..Default::default() }), + ("oldest", "cats", Filter { oldest: true, ..Default::default() }), + ]; + for (name, q, f) in cases { + let query = Query::parse(q); + let runs = 20; + let t = Instant::now(); + let mut total = 0; + for _ in 0..runs { + total = corpus.search(&query, f, 200).total; + } + println!("{name:<12} {:>7.2} ms ({total} matches)", t.elapsed().as_secs_f64() * 1e3 / runs as f64); + } +} diff --git a/crates/vector-core/src/lib.rs b/crates/vector-core/src/lib.rs index f4f5e5e71..b985799df 100644 --- a/crates/vector-core/src/lib.rs +++ b/crates/vector-core/src/lib.rs @@ -449,6 +449,7 @@ pub mod requests; // === Message Deletion (NIP-09 against retained gift-wraps) === pub mod deletion; +pub mod search; pub mod early; pub mod self_destruct; pub mod transfer; diff --git a/crates/vector-core/src/search.rs b/crates/vector-core/src/search.rs new file mode 100644 index 000000000..d47f5b2f8 --- /dev/null +++ b/crates/vector-core/src/search.rs @@ -0,0 +1,799 @@ +//! On-device message search: every chat's text folded into one buffer and scanned with +//! `memchr::memmem`, so a query is a single SIMD pass with nothing sent anywhere. +//! +//! A [`Corpus`] holds plaintext, so it lives only as long as the search surface that built it. + +use std::ops::Range; + +use memchr::memmem; + +/// One searchable message. +struct Doc { + id: Box, + chat: u32, + author: Option>, + mine: bool, + at: u64, + has: Has, + mentions: Box<[Box]>, + /// Span in `Corpus::text`. + text: Range, + /// Span in `Corpus::folded`. + folded: Range, +} + +/// Messages to search, newest first. +#[derive(Default)] +pub struct Corpus { + chats: Vec>, + docs: Vec, + text: String, + /// Each doc folded by [`fold`], NUL-separated so a match never spans two. + folded: String, +} + +/// What [`Corpus::search`] found. +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Found { + /// The newest `limit` matches. + pub hits: Vec, + /// Every match, including those past `limit`. + pub total: usize, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Hit { + pub id: String, + pub chat: String, + pub author: Option, + pub mine: bool, + pub at: u64, + pub has: Has, + /// A window of the message around its first match, on one line. + pub snippet: String, + /// Each term's occurrences within `snippet`, in order. + pub marks: Vec>, +} + +/// What a message carries, for `has:` filters. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Has(u8); + +impl Has { + pub const LINK: Has = Has(1); + pub const IMAGE: Has = Has(2); + pub const VIDEO: Has = Has(4); + pub const AUDIO: Has = Has(8); + /// Any attachment, media included. + pub const FILE: Has = Has(16); + + pub fn contains(self, other: Has) -> bool { + self.0 & other.0 == other.0 + } + + pub fn is_empty(self) -> bool { + self.0 == 0 + } + + /// From a message's text and its attachments' extensions. + pub fn of<'a>(text: &str, extensions: impl IntoIterator) -> Has { + let mut has = Has::default(); + if memmem::find(text.as_bytes(), b"https://").is_some() || memmem::find(text.as_bytes(), b"http://").is_some() { + has |= Has::LINK; + } + for ext in extensions { + has |= Has::FILE; + let mime = crate::crypto::mime_from_extension(ext); + if mime.starts_with("image/") { + has |= Has::IMAGE; + } else if mime.starts_with("video/") { + has |= Has::VIDEO; + } else if mime.starts_with("audio/") { + has |= Has::AUDIO; + } + } + has + } +} + +impl std::ops::BitOr for Has { + type Output = Has; + fn bitor(self, rhs: Has) -> Has { + Has(self.0 | rhs.0) + } +} + +impl std::ops::BitOrAssign for Has { + fn bitor_assign(&mut self, rhs: Has) { + self.0 |= rhs.0; + } +} + +/// Narrows a search. Each list matches any of its entries; the lists all have to match. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Filter { + /// Authors by npub. `from_me` counts this account's own messages too. + pub from: Vec, + pub from_me: bool, + /// Mentioned npubs. + pub mentions: Vec, + pub has: Has, + /// Chat ids: DM npubs or channel ids. + pub chats: Vec, + /// Inclusive bounds in ms. + pub after: Option, + pub before: Option, + /// Oldest first instead of newest. + pub oldest: bool, +} + +impl Filter { + pub fn is_empty(&self) -> bool { + self.from.is_empty() + && !self.from_me + && self.mentions.is_empty() + && self.has.is_empty() + && self.chats.is_empty() + && self.after.is_none() + && self.before.is_none() + } +} + +/// One message as [`load`] reads it, before it joins a [`Corpus`]. +#[derive(Debug, Clone, Default)] +pub struct Record { + pub chat: String, + pub id: String, + pub author: Option, + pub mine: bool, + pub at: u64, + pub text: String, + /// Attachments' `(extension, file name)`. + pub files: Vec<(String, String)>, +} + +/// A parsed query: whitespace-separated terms that must all appear, `"quoted phrases"` kept whole. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Query { + terms: Vec, +} + +impl Query { + pub fn parse(input: &str) -> Self { + let mut terms = Vec::new(); + let mut rest = input; + while let Some(start) = rest.find(|c: char| !c.is_whitespace()) { + rest = &rest[start..]; + let (raw, next) = if let Some(body) = rest.strip_prefix('"') { + match body.find('"') { + Some(end) => (&body[..end], &body[end + 1..]), + None => (body, ""), + } + } else { + let end = rest.find(char::is_whitespace).unwrap_or(rest.len()); + (&rest[..end], &rest[end..]) + }; + let mut folded = String::new(); + fold_into(raw, &mut folded, None); + if !folded.trim().is_empty() && !terms.contains(&folded) { + terms.push(folded); + } + rest = next; + } + // The longest term scans the buffer; the rest only confirm its candidates. + terms.sort_by_key(|t| std::cmp::Reverse(t.len())); + Self { terms } + } + + pub fn is_empty(&self) -> bool { + self.terms.is_empty() + } +} + +/// Case and accent folding: `É` and `e` match, as do `ß`/`ss`-free lowercase forms. Scripts +/// without case (CJK, Arabic) pass through, so substring matching needs no word breaks. +pub fn fold(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + fold_into(text, &mut out, None); + out +} + +/// [`fold`], appending to `out`; `map` gets, per folded byte, the source byte it came from. +fn fold_into(text: &str, out: &mut String, mut map: Option<&mut Vec>) { + for (at, ch) in text.char_indices() { + let before = out.len(); + if ch.is_ascii() { + // NUL separates documents. + out.push(if ch == '\0' { ' ' } else { ch.to_ascii_lowercase() }); + } else { + unicode_normalization::char::decompose_canonical(ch, |d| { + if !unicode_normalization::char::is_combining_mark(d) { + out.extend(d.to_lowercase()); + } + }); + } + if let Some(m) = map.as_deref_mut() { + m.extend(std::iter::repeat_n(at as u32, out.len() - before)); + } + } + if let Some(m) = map { + m.push(text.len() as u32); + } +} + +impl Corpus { + pub fn new() -> Self { + Self::default() + } + + pub fn len(&self) -> usize { + self.docs.len() + } + + pub fn is_empty(&self) -> bool { + self.docs.is_empty() + } + + /// Adds a message as `shown`: its text with mentions already named. Push newest first. + pub fn push(&mut self, record: &Record, shown: &str) { + let names = record.files.iter().map(|(_, n)| n.as_str()).filter(|n| !n.is_empty()); + let has = Has::of(&record.text, record.files.iter().map(|(e, _)| e.as_str())); + if shown.trim().is_empty() && has.is_empty() { + return; + } + let chat = match self.chats.iter().rposition(|c| **c == *record.chat) { + Some(ix) => ix as u32, + None => { + self.chats.push(record.chat.as_str().into()); + (self.chats.len() - 1) as u32 + } + }; + let t0 = self.text.len() as u32; + self.text.push_str(shown.trim()); + for name in names { + if self.text.len() as u32 > t0 { + self.text.push('\n'); + } + self.text.push_str(name); + } + let t1 = self.text.len() as u32; + let f0 = self.folded.len() as u32; + fold_into(&self.text[t0 as usize..], &mut self.folded, None); + let f1 = self.folded.len() as u32; + self.folded.push('\0'); + let mentions: Vec> = crate::types::extract_mentions(&record.text).into_iter().map(Into::into).collect(); + self.docs.push(Doc { + id: record.id.as_str().into(), + chat, + author: record.author.as_deref().map(Into::into), + mine: record.mine, + at: record.at, + has, + mentions: mentions.into_boxed_slice(), + text: t0..t1, + folded: f0..f1, + }); + } + + /// Messages holding every term and passing `filter`. A query with no terms lists every + /// message the filter passes. + pub fn search(&self, query: &Query, filter: &Filter, limit: usize) -> Found { + let mut found = Found::default(); + if query.is_empty() && filter.is_empty() { + return found; + } + let chats: Vec = filter + .chats + .iter() + .filter_map(|c| self.chats.iter().position(|x| **x == **c).map(|i| i as u32)) + .collect(); + if !filter.chats.is_empty() && chats.is_empty() { + return found; + } + let passes = |d: &Doc| { + (chats.is_empty() || chats.contains(&d.chat)) + && (filter.from.is_empty() && !filter.from_me + || filter.from_me && d.mine + || d.author.as_deref().is_some_and(|a| filter.from.iter().any(|f| f == a))) + && (filter.mentions.is_empty() || d.mentions.iter().any(|m| filter.mentions.iter().any(|f| **f == **m))) + && d.has.contains(filter.has) + && filter.after.is_none_or(|a| d.at >= a) + && filter.before.is_none_or(|b| d.at <= b) + }; + // Matches as doc indices, newest first; hits are built only for those listed. + let mut matched: Vec = Vec::new(); + let mut note = |ix: usize| { + found.total += 1; + if filter.oldest || matched.len() < limit { + matched.push(ix as u32); + } + }; + match query.terms.split_first() { + None => { + for (ix, _) in self.docs.iter().enumerate().filter(|(_, d)| passes(d)) { + note(ix); + } + } + // A chat filter walks only its chats' messages. + Some(_) if !chats.is_empty() => { + let finders: Vec = query.terms.iter().map(|t| memmem::Finder::new(t.as_bytes())).collect(); + let hay = self.folded.as_bytes(); + for (ix, d) in self.docs.iter().enumerate() { + if chats.contains(&d.chat) && passes(d) { + let body = &hay[d.folded.start as usize..d.folded.end as usize]; + if finders.iter().all(|f| f.find(body).is_some()) { + note(ix); + } + } + } + } + Some((lead, rest)) => { + let finders: Vec = rest.iter().map(|t| memmem::Finder::new(t.as_bytes())).collect(); + let hay = self.folded.as_bytes(); + let lead = memmem::Finder::new(lead.as_bytes()); + let mut cursor = 0usize; + let mut doc_ix = 0usize; + while cursor < hay.len() { + let Some(pos) = lead.find(&hay[cursor..]).map(|p| p + cursor) else { break }; + // Docs are laid out in order, so the owner is at or after the last one found. + doc_ix += self.docs[doc_ix..].partition_point(|d| (d.folded.end as usize) < pos); + let Some(doc) = self.docs.get(doc_ix) else { break }; + cursor = doc.folded.end as usize + 1; + let body = &hay[doc.folded.start as usize..doc.folded.end as usize]; + if passes(doc) && finders.iter().all(|f| f.find(body).is_some()) { + note(doc_ix); + } + doc_ix += 1; + } + } + } + if filter.oldest { + let skip = matched.len().saturating_sub(limit); + matched.drain(..skip); + matched.reverse(); + } + found.hits = matched.into_iter().map(|ix| self.hit(&self.docs[ix as usize], query)).collect(); + found + } + + fn hit(&self, doc: &Doc, query: &Query) -> Hit { + let text = &self.text[doc.text.start as usize..doc.text.end as usize]; + let (snippet, marks) = snippet(text, &query.terms, 60); + Hit { + id: doc.id.to_string(), + chat: self.chats[doc.chat as usize].to_string(), + author: doc.author.as_deref().map(str::to_string), + mine: doc.mine, + at: doc.at, + has: doc.has, + snippet, + marks, + } + } +} + +/// `text` cut to about `context` characters either side of its first match, whitespace runs +/// collapsed, with every term's occurrences marked in the result. +fn snippet(text: &str, terms: &[String], context: usize) -> (String, Vec>) { + let mut folded = String::with_capacity(text.len()); + let mut map = Vec::with_capacity(text.len() + 1); + fold_into(text, &mut folded, Some(&mut map)); + let mut spans: Vec> = Vec::new(); + for term in terms { + let mut from = 0; + while let Some(at) = memmem::find(&folded.as_bytes()[from..], term.as_bytes()).map(|p| p + from) { + let end = at + term.len(); + spans.push(map[at] as usize..source_end(&map, end, text)); + from = end; + } + } + spans.sort_by_key(|r| (r.start, std::cmp::Reverse(r.end))); + let mut merged: Vec> = Vec::with_capacity(spans.len()); + for s in spans { + match merged.last_mut() { + Some(last) if s.start <= last.end => last.end = last.end.max(s.end), + _ => merged.push(s), + } + } + let first = merged.first().map_or(0, |r| r.start); + let start = back_chars(text, first, context); + let end = merged.first().map_or(0, |r| r.end); + let stop = fwd_chars(text, end, context * 2); + + let mut out = String::with_capacity(stop - start + 8); + let mut marks = Vec::new(); + if start > 0 { + out.push('…'); + } + let mut open: Option = None; + let mut spans = merged.iter().peekable(); + let mut space = false; + for (i, ch) in text[start..stop].char_indices() { + let at = start + i; + while spans.peek().is_some_and(|s| s.end <= at) { + let s = spans.next().unwrap(); + if let Some(o) = open.take() { + marks.push(o..out.len()); + } + let _ = s; + } + if open.is_none() && spans.peek().is_some_and(|s| s.start <= at) { + if space { + out.push(' '); + space = false; + } + open = Some(out.len()); + } + if ch.is_whitespace() { + space = !out.is_empty() && !out.ends_with('…'); + continue; + } + if space { + out.push(' '); + space = false; + } + out.push(ch); + } + if let Some(o) = open.take() { + marks.push(o..out.len()); + } + if stop < text.len() { + out.push('…'); + } + (out, marks) +} + +/// The source byte after folded byte `end - 1`: the end of the character it came from. +fn source_end(map: &[u32], end: usize, text: &str) -> usize { + let src = map[end - 1] as usize; + src + text[src..].chars().next().map_or(0, char::len_utf8) +} + +fn back_chars(text: &str, from: usize, n: usize) -> usize { + let head = &text[..from]; + let cut = head.char_indices().rev().nth(n.saturating_sub(1)).map_or(0, |(i, _)| i); + if cut == 0 { + return 0; + } + // Start on a word where one is near. + head[cut..].find(char::is_whitespace).filter(|&w| w < 16).map_or(cut, |w| cut + w + 1).min(from) +} + +fn fwd_chars(text: &str, from: usize, n: usize) -> usize { + text[from..].char_indices().nth(n).map_or(text.len(), |(i, _)| from + i) +} + +/// `text` with each mentioned npub (`@npub1…`, `nostr:npub1…` or bare) shown as `@name`, +/// so a search for the name finds the mention. +pub fn name_mentions(text: &str, name: impl Fn(&str) -> Option) -> String { + let mentions = crate::types::extract_mentions(text); + if mentions.is_empty() { + return text.to_string(); + } + let base = text.as_ptr() as usize; + let mut out = String::with_capacity(text.len()); + let mut last = 0; + for m in mentions { + let mut start = m.as_ptr() as usize - base; + let end = start + m.len(); + if text[..start].ends_with("nostr:") { + start -= 6; + } + if text[..start].ends_with('@') { + start -= 1; + } + if start < last { + continue; + } + out.push_str(&text[last..start]); + match name(m) { + Some(n) => { + out.push('@'); + out.push_str(&n); + } + None => out.push_str(&text[start..end]), + } + last = end; + } + out.push_str(&text[last..]); + out +} + +/// Every stored message's current text (edits applied), newest first, for the account the +/// caller is bound to. Banned authors' posts are left out, as the timeline leaves them out. +#[cfg(not(target_arch = "wasm32"))] +pub fn load() -> Result, String> { + use std::collections::HashMap; + use crate::stored_event::event_kind; + + struct Row { + id: String, + kind: u16, + chat: String, + content: String, + reference: Option, + at: u64, + mine: bool, + npub: Option, + } + + let (rows, communities, files) = { + let conn = crate::db::get_db_connection_guard_static()?; + let mut stmt = conn + .prepare( + "SELECT e.id, e.kind, c.chat_identifier, e.content, e.reference_id, e.created_at, e.tags, e.mine, e.npub \ + FROM events e JOIN chats c ON c.id = e.chat_id \ + WHERE e.kind IN (?1, ?2, ?3, ?4) \ + ORDER BY e.created_at DESC, e.received_at DESC", + ) + .map_err(|e| format!("Failed to prepare search query: {e}"))?; + let rows: Vec = stmt + .query_map( + rusqlite::params![ + event_kind::CHAT_MESSAGE as i32, + event_kind::PRIVATE_DIRECT_MESSAGE as i32, + event_kind::FILE_ATTACHMENT as i32, + event_kind::MESSAGE_EDIT as i32, + ], + |r| { + let tags: String = r.get(6)?; + let secs = r.get::<_, i64>(5)? as u64; + Ok(Row { + id: r.get(0)?, + kind: r.get::<_, i32>(1)? as u16, + chat: r.get(2)?, + content: r.get(3)?, + reference: r.get(4)?, + at: secs * 1000 + ms_of(&tags), + mine: r.get::<_, i32>(7)? != 0, + npub: r.get(8)?, + }) + }, + ) + .map_err(|e| format!("Failed to run search query: {e}"))? + .filter_map(Result::ok) + .collect(); + let communities: HashMap = conn + .prepare("SELECT channel_id, community_id FROM community_channels") + .and_then(|mut s| { + s.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))) + .map(|it| it.filter_map(Result::ok).collect()) + }) + .unwrap_or_default(); + let files: Vec<(String, String, String)> = conn + .prepare("SELECT event_id, extension, name FROM attachments ORDER BY event_id, att_index") + .and_then(|mut s| { + s.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?))) + .map(|it| it.filter_map(Result::ok).collect()) + }) + .unwrap_or_default(); + (rows, communities, files) + }; + + let mut banned: HashMap<&str, std::collections::HashSet> = HashMap::new(); + for community in communities.values() { + banned.entry(community.as_str()).or_insert_with(|| { + use nostr_sdk::prelude::ToBech32; + crate::db::community::banned_set(community) + .iter() + .filter_map(|b| nostr_sdk::prelude::PublicKey::from_slice(b).ok()?.to_bech32().ok()) + .collect() + }); + } + + crate::crypto::open_batch(|at_rest| { + let mut by_event: HashMap> = HashMap::new(); + for (event, ext, name) in files { + by_event.entry(event).or_default().push((ext, at_rest.open_or_keep(name))); + } + // Newest edit per message: rows arrive newest first, so the first seen wins. + let mut edits: HashMap = HashMap::new(); + for row in rows.iter().filter(|r| r.kind == event_kind::MESSAGE_EDIT) { + let Some(target) = &row.reference else { continue }; + if !edits.contains_key(target) { + if let Ok(text) = at_rest.open(row.content.clone()) { + edits.insert(target.clone(), text); + } + } + } + let mut out = Vec::with_capacity(rows.len()); + for row in rows.into_iter().filter(|r| r.kind != event_kind::MESSAGE_EDIT) { + let is_banned = match (&row.npub, communities.get(&row.chat)) { + (Some(author), Some(community)) => banned.get(community.as_str()).is_some_and(|b| b.contains(author)), + _ => false, + }; + if is_banned { + continue; + } + let files = by_event.remove(&row.id).unwrap_or_default(); + let text = match edits.remove(&row.id) { + Some(edited) => edited, + // A file event's content is its URL, not words. + None if row.kind == event_kind::FILE_ATTACHMENT => String::new(), + None => match at_rest.open(row.content) { + Ok(t) => t, + Err(_) => continue, + }, + }; + out.push(Record { chat: row.chat, id: row.id, author: row.npub, mine: row.mine, at: row.at, text, files }); + } + Ok(out) + }) +} + +#[cfg(not(target_arch = "wasm32"))] +fn ms_of(tags: &str) -> u64 { + // `["ms","123"]` without parsing every row's whole tag list. + let Some(at) = tags.find("[\"ms\",\"") else { return 0 }; + let digits = &tags[at + 7..]; + digits[..digits.find('"').unwrap_or(0)].parse().unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rec(chat: &str, id: &str, author: Option<&str>, mine: bool, at: u64, text: &str) -> Record { + Record { chat: chat.into(), id: id.into(), author: author.map(Into::into), mine, at, text: text.into(), files: Vec::new() } + } + + fn add(c: &mut Corpus, r: Record) { + let shown = r.text.clone(); + c.push(&r, &shown); + } + + fn corpus() -> Corpus { + let mut c = Corpus::new(); + add(&mut c, rec("npub1a", "m4", Some("npub1a"), false, 4000, "Café at nine? Bring the BLUEPRINTS https://x.io")); + add(&mut c, rec("chan", "m3", Some("npub1b"), false, 3000, "the blueprints are in the shared folder")); + add(&mut c, rec("npub1a", "m2", None, true, 2000, "see you at the café")); + add(&mut c, rec("chan", "m1", Some("npub1c"), false, 1000, "東京で会いましょう")); + let mut pic = rec("chan", "m0", Some("npub1b"), false, 500, ""); + pic.files.push(("png".into(), "harbour.png".into())); + add(&mut c, pic); + c + } + + fn find(c: &Corpus, q: &str) -> Found { + c.search(&Query::parse(q), &Filter::default(), 10) + } + + fn ids(f: &Found) -> Vec<&str> { + f.hits.iter().map(|h| h.id.as_str()).collect() + } + + #[test] + fn folds_case_and_accents() { + let c = corpus(); + assert_eq!(ids(&find(&c, "CAFE")), ["m4", "m2"]); + assert_eq!(ids(&find(&c, "blueprints")), ["m4", "m3"]); + } + + #[test] + fn every_term_must_match_in_any_order() { + let c = corpus(); + assert_eq!(ids(&find(&c, "folder blueprints")), ["m3"]); + assert!(find(&c, "folder café").hits.is_empty()); + } + + #[test] + fn phrases_stay_whole() { + let c = corpus(); + assert_eq!(ids(&find(&c, "\"at the\"")), ["m2"]); + assert_eq!(ids(&find(&c, "at the")), ["m4", "m2"]); + } + + #[test] + fn cjk_matches_without_word_breaks() { + let c = corpus(); + assert_eq!(ids(&find(&c, "会い")), ["m1"]); + } + + fn chat(id: &str) -> Filter { + Filter { chats: vec![id.into()], ..Default::default() } + } + + #[test] + fn scope_and_limit() { + let c = corpus(); + assert_eq!(ids(&c.search(&Query::parse("the"), &chat("chan"), 10)), ["m3"]); + let f = c.search(&Query::parse("e"), &Filter::default(), 2); + assert_eq!(ids(&f), ["m4", "m3"]); + assert_eq!(f.total, 3); + assert!(c.search(&Query::parse("the"), &chat("nowhere"), 10).hits.is_empty()); + } + + #[test] + fn oldest_first_keeps_the_oldest() { + let c = corpus(); + let f = c.search(&Query::parse("e"), &Filter { oldest: true, ..Default::default() }, 2); + assert_eq!(ids(&f), ["m2", "m3"]); + assert_eq!(f.total, 3); + } + + #[test] + fn filters_alone_list_messages() { + let c = corpus(); + let from = Filter { from: vec!["npub1b".into()], ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse(""), &from, 10)), ["m3", "m0"]); + let me = Filter { from_me: true, ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse("cafe"), &me, 10)), ["m2"]); + let image = Filter { has: Has::IMAGE, ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse(""), &image, 10)), ["m0"]); + let link = Filter { has: Has::LINK, ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse(""), &link, 10)), ["m4"]); + let span = Filter { after: Some(1000), before: Some(3000), ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse(""), &span, 10)), ["m3", "m2", "m1"]); + } + + #[test] + fn file_names_are_searchable() { + let c = corpus(); + assert_eq!(ids(&find(&c, "harbour")), ["m0"]); + } + + #[test] + fn mentions_filter_and_names() { + let npub = "npub1sg6plzptd64u62a878hep2kev88swjh3tw00gjsfl8f237lmu63q0uf63m"; + let mut c = Corpus::new(); + let r = rec("chan", "a", Some("npub1x"), false, 2, &format!("ping @{npub} about lunch")); + let shown = name_mentions(&r.text, |n| (n == npub).then(|| "Alice".to_string())); + assert_eq!(shown, "ping @Alice about lunch"); + c.push(&r, &shown); + add(&mut c, rec("chan", "b", Some("npub1x"), false, 1, "lunch?")); + let f = Filter { mentions: vec![npub.into()], ..Default::default() }; + assert_eq!(ids(&c.search(&Query::parse("lunch"), &f, 10)), ["a"]); + assert_eq!(ids(&find(&c, "alice")), ["a"]); + } + + #[test] + fn no_match_across_messages() { + let mut c = Corpus::new(); + add(&mut c, rec("x", "a", None, true, 2, "end")); + add(&mut c, rec("x", "b", None, true, 1, "start")); + assert!(find(&c, "endstart").hits.is_empty()); + assert!(find(&c, "dst").hits.is_empty()); + } + + #[test] + fn marks_point_at_the_original_text() { + let c = corpus(); + let hit = &find(&c, "cafe blueprints").hits[0]; + let marked: Vec<&str> = hit.marks.iter().map(|r| &hit.snippet[r.clone()]).collect(); + assert_eq!(marked, ["Café", "BLUEPRINTS"]); + } + + #[test] + fn long_text_is_cut_around_the_match() { + let mut c = Corpus::new(); + let long = format!("{} needle {}", "lorem ipsum ".repeat(40), "dolor sit ".repeat(40)); + add(&mut c, rec("x", "a", None, true, 1, &long)); + let hit = &find(&c, "needle").hits[0]; + assert!(hit.snippet.starts_with('…') && hit.snippet.ends_with('…'), "{}", hit.snippet); + assert!(hit.snippet.chars().count() < 200); + assert_eq!(&hit.snippet[hit.marks[0].clone()], "needle"); + } + + #[test] + fn whitespace_collapses_in_snippets() { + let mut c = Corpus::new(); + add(&mut c, rec("x", "a", None, true, 1, "line one\n\n line two")); + let hit = &find(&c, "two").hits[0]; + assert_eq!(hit.snippet, "line one line two"); + assert_eq!(&hit.snippet[hit.marks[0].clone()], "two"); + } + + #[test] + fn blank_queries_find_nothing() { + let c = corpus(); + assert!(Query::parse(" ").is_empty()); + assert!(Query::parse("\"\"").is_empty()); + assert_eq!(find(&c, ""), Found::default()); + } + + #[test] + fn ms_tag_is_read() { + assert_eq!(ms_of(r#"[["p","x"],["ms","417"]]"#), 417); + assert_eq!(ms_of("[]"), 0); + } +} diff --git a/crates/vector-gpui/Cargo.lock b/crates/vector-gpui/Cargo.lock index c876fb108..715161cf0 100644 --- a/crates/vector-gpui/Cargo.lock +++ b/crates/vector-gpui/Cargo.lock @@ -13389,6 +13389,7 @@ dependencies = [ "js-sys", "libc", "libcrux-ml-kem", + "memchr", "negentropy", "noq-proto", "nostr", diff --git a/crates/vector-gpui/src/community.rs b/crates/vector-gpui/src/community.rs index 5e0fa7e44..4da643e65 100644 --- a/crates/vector-gpui/src/community.rs +++ b/crates/vector-gpui/src/community.rs @@ -52,6 +52,10 @@ pub enum Act { ChannelsMenu(gpui::Point), /// The open channel's ⋯. ChatMenu, + /// Search this channel. + Search, + /// The member pane's search. + Find(crate::search::Act), EditChannel(String), /// A member tapped: their mini profile, beside what was painted under the key. Member(String, SharedString), @@ -132,6 +136,8 @@ pub struct View { pub loading: bool, pub panel: bool, pub search: Entity, + /// What the member pane's field finds beyond members: the Community's messages. + pub find: crate::search::Search, pub folded: HashSet, pub scroll: gpui::ScrollHandle, } @@ -732,6 +738,7 @@ pub fn header( .child(crate::kit::one_line(&topic).into_owned()) })), ) + .child(crate::search::button(click(on, || Act::Search))) .children(pins.map(crate::pins::button)) .child( div() @@ -990,6 +997,9 @@ fn member_row(store: &Store, cid: &str, npub: &str, owner: bool, colour: Option< ) } +/// Members listed above the messages while the pane searches. +const MINI_MEMBERS: usize = 5; + /// The roster's sections, filtered by the search, by rank, or why there are none. pub fn roster( d: E, @@ -1002,7 +1012,8 @@ pub fn roster( visible: Option<(f32, f32)>, cx: &App, ) -> E { - let query = view.search.read(cx).text().trim().to_lowercase(); + let finding = !view.search.read(cx).text().trim().is_empty(); + let query = view.find.parsed.words.trim().to_lowercase(); let owner = com.owner_npub.as_deref(); let matches = |n: &&String| { query.is_empty() @@ -1036,6 +1047,20 @@ pub fn roster( }; let mut everyone: Vec<&String> = everyone().filter(matches).collect(); everyone.sort_by_cached_key(key); + if finding { + let colour = |n: &str| graph.filter(|g| g.activated).and_then(|g| g.highest(n, |r| r.color != 0)).map(|r| r.color); + let people = if query.is_empty() || !view.find.parsed.tokens.is_empty() { Vec::new() } else { everyone }; + let rows = people + .iter() + .take(MINI_MEMBERS) + .map(|n| member_row(store, &com.community_id, n, owner == Some(n.as_str()), colour(n), view.unlisted.get(n.as_str()).map(String::as_str), on, anchors).into_any_element()) + .collect(); + let find: crate::search::OnAct = { + let on = on.clone(); + Rc::new(move |a, w, cx| on(Act::Find(a), w, cx)) + }; + return d.children(crate::search::mini(&view.find, store, open, rows, people.len(), &find)); + } let mut order: Vec<(String, String)> = Vec::new(); if let Some(g) = graph { let mut heads: Vec<&GraphRole> = g.roles.iter().filter(|r| g.heads(r)).collect(); diff --git a/crates/vector-gpui/src/coretext_table.rs b/crates/vector-gpui/src/coretext_table.rs index 60e5a3aa4..4a98a00fc 100644 --- a/crates/vector-gpui/src/coretext_table.rs +++ b/crates/vector-gpui/src/coretext_table.rs @@ -642,4 +642,6 @@ ("Gyroscope", |_| Some(t::core_permission_gyroscope().to_string())), ("Magnetometer", |_| Some(t::core_permission_magnetometer().to_string())), ("Bluetooth", |_| Some(t::core_permission_bluetooth().to_string())), + ("Failed to prepare search query: {e}", |a| Some(t::core_search_prepare_failed(&a[0]).to_string())), + ("Failed to run search query: {e}", |a| Some(t::core_search_query_failed(&a[0]).to_string())), ] diff --git a/crates/vector-gpui/src/main.rs b/crates/vector-gpui/src/main.rs index 4fbfdcbc9..cac98706d 100644 --- a/crates/vector-gpui/src/main.rs +++ b/crates/vector-gpui/src/main.rs @@ -25,6 +25,7 @@ mod voice; mod miniprofile; mod pings; mod pins; +mod search; mod pickers; mod edithistory; mod textdiff; diff --git a/crates/vector-gpui/src/search.rs b/crates/vector-gpui/src/search.rs new file mode 100644 index 000000000..73a563430 --- /dev/null +++ b/crates/vector-gpui/src/search.rs @@ -0,0 +1,1186 @@ +//! Message search: one field where free words and `key:value` filters mix (`from:`, `mentions:`, +//! `has:`, `in:`, `before:`, `after:`, `during:`), suggestions for the filter being typed, and +//! results that open the message in its chat. The scan is `vector_core::search`'s. + +use std::ops::Range; +use std::rc::Rc; +use std::sync::Arc; + +use chrono::{Datelike, Local, NaiveDate, TimeZone}; +use gpui::prelude::*; +use crate::kit::Tipped as _; +use gpui::{AnyElement, App, Entity, FontWeight, HighlightStyle, SharedString, StyledText, Window, div, px, svg}; +use vector_core::search::{Corpus, Filter, Found, Has, Query, Record}; + +use crate::composer::TextInput; +use crate::data::Store; +use crate::t; +use crate::theme::*; + +/// Results listed at once; the count still covers every match. +pub const LIMIT: usize = 200; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Key { + From, + Mentions, + Has, + In, + Before, + After, + During, +} + +pub const KEYS: [Key; 7] = [Key::From, Key::Mentions, Key::Has, Key::In, Key::Before, Key::After, Key::During]; + +impl Key { + /// The syntax word, the same in every language. + pub fn word(self) -> &'static str { + // i18n-exempt: search syntax + match self { + Key::From => "from", + Key::Mentions => "mentions", + Key::Has => "has", + Key::In => "in", + Key::Before => "before", + Key::After => "after", + Key::During => "during", + } + } + + fn parse(word: &str) -> Option { + KEYS.into_iter().find(|k| k.word().eq_ignore_ascii_case(word)) + } + + fn label(self) -> SharedString { + match self { + Key::From => t::search_opt_from(), + Key::Mentions => t::search_opt_mentions(), + Key::Has => t::search_opt_has(), + Key::In => t::search_opt_in(), + Key::Before => t::search_opt_before(), + Key::After => t::search_opt_after(), + Key::During => t::search_opt_during(), + } + } + + fn icon(self) -> &'static str { + match self { + Key::From | Key::Mentions => "icons/user-circle.svg", + Key::Has => "icons/attachment.svg", + Key::In => "icons/channel-hash.svg", + Key::Before | Key::After | Key::During => "icons/clock.svg", + } + } +} + +/// `has:` values: the syntax word and what it asks for. +const HAS: [(&str, Has); 12] = [ + ("link", Has::LINK), // i18n-exempt: search syntax + ("image", Has::IMAGE), // i18n-exempt: search syntax + ("video", Has::VIDEO), // i18n-exempt: search syntax + ("audio", Has::AUDIO), // i18n-exempt: search syntax + ("file", Has::FILE), // i18n-exempt: search syntax + ("sound", Has::AUDIO), // i18n-exempt: search syntax + ("img", Has::IMAGE), // i18n-exempt: search syntax + ("photo", Has::IMAGE), // i18n-exempt: search syntax + ("picture", Has::IMAGE), // i18n-exempt: search syntax + ("vid", Has::VIDEO), // i18n-exempt: search syntax + ("url", Has::LINK), // i18n-exempt: search syntax + ("attachment", Has::FILE), // i18n-exempt: search syntax +]; + +fn has_icon(h: Has) -> &'static str { + if h == Has::LINK { + "icons/globe.svg" + } else if h == Has::IMAGE { + "icons/image.svg" + } else if h == Has::VIDEO { + "icons/video.svg" + } else if h == Has::AUDIO { + "icons/volume-max.svg" + } else { + "icons/file.svg" + } +} + +fn has_label(h: Has) -> SharedString { + if h == Has::LINK { + t::search_has_link() + } else if h == Has::IMAGE { + t::search_has_image() + } else if h == Has::VIDEO { + t::search_has_video() + } else if h == Has::AUDIO { + t::search_has_audio() + } else { + t::search_has_file() + } +} + +/// A filter as typed: where it sits in the field, and what it reads as. +#[derive(Clone, Debug, PartialEq)] +pub struct Token { + pub key: Key, + pub value: String, + pub range: Range, +} + +/// The field split into filters and the words left over. +#[derive(Debug, Default, PartialEq)] +pub struct Parsed { + pub tokens: Vec, + pub words: String, +} + +/// Splits `text` on whitespace (a `"quoted value"` stays whole) into filters and free words. +pub fn parse(text: &str) -> Parsed { + let mut out = Parsed::default(); + let b = text.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i].is_ascii_whitespace() { + i += 1; + continue; + } + let start = i; + let mut quoted = false; + while i < b.len() && (quoted || !b[i].is_ascii_whitespace()) { + if b[i] == b'"' { + quoted = !quoted; + } + i += 1; + } + let word = &text[start..i]; + let filter = word.split_once(':').and_then(|(k, v)| Some((Key::parse(k)?, v))); + match filter { + Some((key, v)) => out.tokens.push(Token { key, value: v.trim_matches('"').to_string(), range: start..i }), + None => { + if !out.words.is_empty() { + out.words.push(' '); + } + out.words.push_str(word); + } + } + } + out +} + +/// A person or chat a filter value may name. +#[derive(Clone, Debug)] +pub struct Named { + pub id: String, + pub name: String, + folded: String, +} + +/// The people and chats filters resolve against, read from the store as search opens. +#[derive(Clone, Default)] +pub struct Directory { + pub me: String, + pub people: Vec, + pub chats: Vec, +} + +impl Directory { + pub fn read(store: &Store) -> Self { + let named = |id: String, name: String| Named { folded: vector_core::search::fold(&name), id, name }; + let mut people: Vec = store + .profiles + .keys() + .filter(|n| **n != store.my_npub) + .map(|n| named(n.clone(), store.name(n))) + .collect(); + people.sort_by(|a, b| a.folded.cmp(&b.folded)); + let mut chats = Vec::new(); + for chat in &store.chats { + if chat.chat_type == vector_core::ChatType::DirectMessage && (store.listed(chat) || chat.id == store.my_npub) { + chats.push(named(chat.id.clone(), store.name(&chat.id))); + } + } + for com in &store.communities { + for ch in com.channels.iter().filter(|c| c.view != "voice") { + // i18n-exempt: channel sigil + chats.push(named(ch.channel_id.clone(), format!("#{} · {}", ch.name, com.name))); + } + } + Self { me: store.my_npub.clone(), people, chats } + } + + /// A Community's members and channels, named as the Community names them. + pub fn community(store: &Store, com: &crate::data::Community, members: impl Iterator) -> Self { + let named = |id: String, name: String| Named { folded: vector_core::search::fold(&name), id, name }; + let mut people: Vec = members + .filter(|n| *n != store.my_npub) + .map(|n| { + let name = store.name_in(&n, Some(&com.community_id)); + named(n, name) + }) + .collect(); + people.sort_by(|a, b| a.folded.cmp(&b.folded)); + people.dedup_by(|a, b| a.id == b.id); + let chats = com + .channels + .iter() + .filter(|c| c.view != "voice") + // i18n-exempt: channel sigil + .map(|ch| named(ch.channel_id.clone(), format!("#{}", ch.name))) + .collect(); + Self { me: store.my_npub.clone(), people, chats } + } + + /// The best matches for `value`: exact names first, else names starting with it, else + /// names holding it. + fn matches<'a>(list: &'a [Named], value: &str) -> Vec<&'a Named> { + let v = vector_core::search::fold(value.trim_start_matches(['@', '#'])); + if v.is_empty() { + return Vec::new(); + } + let exact: Vec<&Named> = list.iter().filter(|n| n.folded == v || n.id == value).collect(); + if !exact.is_empty() { + return exact; + } + let bare = |n: &&Named| n.folded.trim_start_matches('#').to_string(); + let start: Vec<&Named> = list.iter().filter(|n| bare(n).starts_with(&v)).collect(); + if !start.is_empty() { + return start; + } + list.iter().filter(|n| n.folded.contains(&v)).collect() + } + + fn is_me(value: &str) -> bool { + let v = vector_core::search::fold(value); + // i18n-exempt: search syntax + v == "me" || v == vector_core::search::fold(&t::search_me()) + } +} + +/// Day bounds in local ms for `2026-11-18`, `2026-11`, `2026`, `today` or `yesterday`. +pub fn day_span(value: &str, now_ms: u64) -> Option<(u64, u64)> { + let v = value.trim().to_ascii_lowercase(); + let today = Local.timestamp_millis_opt(now_ms as i64).single()?.date_naive(); + let (from, to) = match v.as_str() { + // i18n-exempt: search syntax + "today" => (today, today), + // i18n-exempt: search syntax + "yesterday" => (today.pred_opt()?, today.pred_opt()?), + _ => { + let parts: Vec<&str> = v.split(['-', '/', '.']).collect(); + let num = |i: usize| parts.get(i).and_then(|p| p.parse::().ok()); + let year = num(0).filter(|y| (1970..=9999).contains(y))? as i32; + match parts.len() { + 1 => (NaiveDate::from_ymd_opt(year, 1, 1)?, NaiveDate::from_ymd_opt(year, 12, 31)?), + 2 => { + let m = num(1)?; + let first = NaiveDate::from_ymd_opt(year, m, 1)?; + let next = if m == 12 { NaiveDate::from_ymd_opt(year + 1, 1, 1)? } else { NaiveDate::from_ymd_opt(year, m + 1, 1)? }; + (first, next.pred_opt()?) + } + 3 => { + let d = NaiveDate::from_ymd_opt(year, num(1)?, num(2)?)?; + (d, d) + } + _ => return None, + } + } + }; + let start = Local.from_local_datetime(&from.and_hms_opt(0, 0, 0)?).earliest()?.timestamp_millis(); + let end = Local.from_local_datetime(&to.and_hms_milli_opt(23, 59, 59, 999)?).latest()?.timestamp_millis(); + Some((start.max(0) as u64, end.max(0) as u64)) +} + +/// Matches nothing: a filter whose value names no one. +const NOBODY: &str = "\u{0}"; + +/// The filter the tokens ask for. An empty value (still being typed) asks for nothing. +pub fn filter_of(tokens: &[Token], dir: &Directory, now_ms: u64, oldest: bool) -> Filter { + let mut f = Filter { oldest, ..Default::default() }; + for tok in tokens.iter().filter(|t| !t.value.is_empty()) { + match tok.key { + Key::From | Key::Mentions => { + let mut ids: Vec = Directory::matches(&dir.people, &tok.value).into_iter().map(|n| n.id.clone()).collect(); + let me = Directory::is_me(&tok.value); + if tok.key == Key::From && me { + f.from_me = true; + } else if me { + ids.push(dir.me.clone()); + } + if ids.is_empty() && !me { + ids.push(NOBODY.into()); + } + if tok.key == Key::From { + f.from.extend(ids); + } else { + f.mentions.extend(ids); + } + } + Key::Has => { + let v = tok.value.to_ascii_lowercase(); + match HAS.iter().find(|(w, _)| *w == v || (v.len() >= 2 && w.starts_with(&v))) { + Some((_, h)) => f.has |= *h, + None => f.chats.push(NOBODY.into()), + } + } + Key::In => { + let found = Directory::matches(&dir.chats, &tok.value); + if found.is_empty() { + f.chats.push(NOBODY.into()); + } + f.chats.extend(found.into_iter().map(|n| n.id.clone())); + } + Key::Before | Key::After | Key::During => match day_span(&tok.value, now_ms) { + Some((start, end)) => match tok.key { + Key::Before => f.before = Some(f.before.map_or(start - 1, |b| b.min(start - 1))), + Key::After => f.after = Some(f.after.map_or(end + 1, |a| a.max(end + 1))), + _ => { + f.after = Some(f.after.map_or(start, |a| a.max(start))); + f.before = Some(f.before.map_or(end, |b| b.min(end))); + } + }, + None => f.chats.push(NOBODY.into()), + }, + } + } + f +} + +/// What the suggestion list offers for the word at the caret. +#[derive(Clone, Debug, PartialEq)] +pub enum Suggest { + Key(Key), + Value { key: Key, value: String, label: SharedString, npub: Option }, +} + +/// The word under the caret, when the caret ends it. +fn word_at(text: &str, caret: usize) -> (Range, &str) { + let caret = caret.min(text.len()); + let head = &text[..caret]; + let mut quotes = 0; + let mut start = 0; + for (i, ch) in head.char_indices() { + if ch == '"' { + quotes += 1; + } else if ch.is_whitespace() && quotes % 2 == 0 { + start = i + ch.len_utf8(); + } + } + (start..caret, &text[start..caret]) +} + +pub fn suggestions(text: &str, caret: usize, dir: &Directory, now_ms: u64) -> (Range, Vec) { + let (range, word) = word_at(text, caret); + if text.trim().is_empty() { + return (range, KEYS.into_iter().map(Suggest::Key).collect()); + } + let Some((k, partial)) = word.split_once(':') else { + // A filter word half typed, such as `fr`. + let keys: Vec = if word.len() >= 2 { + KEYS.into_iter().filter(|k| k.word().starts_with(&word.to_ascii_lowercase())).map(Suggest::Key).collect() + } else { + Vec::new() + }; + return (range, keys); + }; + let Some(key) = Key::parse(k) else { return (range, Vec::new()) }; + let partial = partial.trim_start_matches('"'); + let value = |value: String, label: SharedString, npub: Option| Suggest::Value { key, value, label, npub }; + let list = match key { + Key::From | Key::Mentions => { + let mut out = Vec::new(); + let me = t::search_me(); + if partial.is_empty() || vector_core::search::fold(&me).starts_with(&vector_core::search::fold(partial)) { + // i18n-exempt: search syntax + out.push(value("me".into(), me, Some(dir.me.clone()))); + } + let people: Vec<&Named> = if partial.is_empty() { dir.people.iter().collect() } else { Directory::matches(&dir.people, partial) }; + out.extend(people.into_iter().take(8).map(|n| value(n.name.clone(), n.name.clone().into(), Some(n.id.clone())))); + out + } + Key::In => { + let chats: Vec<&Named> = if partial.is_empty() { dir.chats.iter().collect() } else { Directory::matches(&dir.chats, partial) }; + chats + .into_iter() + .take(8) + .map(|n| { + let npub = n.id.starts_with("npub1").then(|| n.id.clone()); + let short = n.name.split(" · ").next().unwrap_or(&n.name).to_string(); + value(short, n.name.clone().into(), npub) + }) + .collect() + } + Key::Has => HAS[..5] + .iter() + .filter(|(w, _)| w.starts_with(&partial.to_ascii_lowercase())) + .map(|(w, h)| value(w.to_string(), has_label(*h), None)) + .collect(), + Key::Before | Key::After | Key::During => { + let mut out = vec![ + // i18n-exempt: search syntax + value("today".into(), t::search_today(), None), + // i18n-exempt: search syntax + value("yesterday".into(), t::search_yesterday(), None), + ]; + out.retain(|s| matches!(s, Suggest::Value { value, .. } if value.starts_with(&partial.to_ascii_lowercase()))); + if let Some(d) = Local.timestamp_millis_opt(now_ms as i64).single() { + let iso = format!("{:04}-{:02}-{:02}", d.year(), d.month(), d.day()); + if iso.starts_with(partial) && !partial.is_empty() { + out.push(value(iso.clone(), iso.into(), None)); + } + } + if day_span(partial, now_ms).is_some() && !out.iter().any(|s| matches!(s, Suggest::Value { value, .. } if value == partial)) { + out.insert(0, value(partial.to_string(), partial.to_string().into(), None)); + } + out + } + }; + (range, list) +} + +/// What picking a suggestion writes in place of the word at the caret. +pub fn completion(s: &Suggest) -> String { + match s { + Suggest::Key(k) => format!("{}:", k.word()), + Suggest::Value { key, value, .. } if value.contains(' ') => format!("{}:\"{}\" ", key.word(), value), + Suggest::Value { key, value, .. } => format!("{}:{} ", key.word(), value), + } +} + +/// The corpus for the fixtures: the messages the store holds. +pub fn fixture_corpus(store: &Store) -> Corpus { + let mut records: Vec = Vec::new(); + for chat in &store.chats { + for m in &chat.messages { + records.push(Record { + chat: chat.id.clone(), + id: m.id.clone(), + author: if m.mine { Some(store.my_npub.clone()) } else { m.npub.clone().or_else(|| Some(chat.id.clone())) }, + mine: m.mine, + at: m.at, + text: m.content.clone(), + files: m.attachments.iter().map(|a| (a.extension.clone(), a.name.clone())).collect(), + }); + } + } + records.sort_by_key(|r| std::cmp::Reverse(r.at)); + build(&records, &names(store), &blocked(store)) +} + +/// Display names by npub, for naming mentions in what is searched. +pub fn names(store: &Store) -> std::collections::HashMap { + store.profiles.keys().map(|n| (n.clone(), store.name(n))).collect() +} + +pub fn blocked(store: &Store) -> std::collections::HashSet { + store.profiles.iter().filter(|(_, p)| p.is_blocked).map(|(n, _)| n.clone()).collect() +} + +/// A corpus from records: mentions named, blocked people left out. DMs carry no author on +/// their side's messages, so a DM's own id stands in. +pub fn build(records: &[Record], names: &std::collections::HashMap, blocked: &std::collections::HashSet) -> Corpus { + let mut corpus = Corpus::new(); + for r in records { + let mut r = std::borrow::Cow::Borrowed(r); + if r.author.is_none() && r.chat.starts_with("npub1") && !r.mine { + r.to_mut().author = Some(r.chat.clone()); + } + if r.author.as_ref().is_some_and(|a| blocked.contains(a)) { + continue; + } + let shown = vector_core::search::name_mentions(&r.text, |n| names.get(n).cloned()); + corpus.push(&r, &shown); + } + corpus +} + +pub struct Search { + pub input: Entity, + pub dir: Directory, + /// `None` while the messages are read. + pub corpus: Option>, + pub found: Found, + pub parsed: Parsed, + pub suggest: Vec, + /// Where the word being completed sits in the field. + pub suggest_at: Range, + /// The highlighted row: of the suggestions while they show, else of the results. + pub sel: usize, + pub oldest: bool, + pub scroll: gpui::ScrollHandle, + /// How long the last scan took, in µs. + pub took: u128, + /// The chats searched when no `in:` names one; empty is every chat. + pub scope: Vec, + pub loading: bool, +} + +impl Search { + pub fn new(input: Entity, dir: Directory) -> Self { + Self { + input, + dir, + corpus: None, + found: Found::default(), + parsed: Parsed::default(), + suggest: Vec::new(), + suggest_at: 0..0, + sel: 0, + oldest: false, + scroll: gpui::ScrollHandle::new(), + took: 0, + scope: Vec::new(), + loading: false, + } + } + + /// Re-reads the field: filters, suggestions and results. + pub fn refresh(&mut self, text: &str, caret: usize, now_ms: u64) { + self.parsed = parse(text); + let (at, list) = suggestions(text, caret, &self.dir, now_ms); + self.suggest_at = at; + self.suggest = list; + let mut filter = filter_of(&self.parsed.tokens, &self.dir, now_ms, self.oldest); + if filter.chats.is_empty() { + filter.chats = self.scope.clone(); + } + let query = Query::parse(&self.parsed.words); + let t0 = std::time::Instant::now(); + self.found = match &self.corpus { + Some(c) => c.search(&query, &filter, LIMIT), + None => Found::default(), + }; + self.took = t0.elapsed().as_micros(); + self.sel = 0; + self.scroll.scroll_to_item(0); + } + + pub fn showing_suggestions(&self) -> bool { + !self.suggest.is_empty() + } + + fn rows(&self) -> usize { + if self.showing_suggestions() { self.suggest.len() } else { self.found.hits.len() } + } + + pub fn step(&mut self, down: bool) { + let n = self.rows(); + if n == 0 { + return; + } + self.sel = if down { (self.sel + 1) % n } else { (self.sel + n - 1) % n }; + let ix = if self.showing_suggestions() { self.sel } else { self.result_row(self.sel) }; + self.scroll.scroll_to_item(ix); + } + + /// The list child index of result `i`, counting the chat headers above it. + fn result_row(&self, i: usize) -> usize { + let hits = &self.found.hits; + let headers = (0..=i.min(hits.len().saturating_sub(1))).filter(|&j| j == 0 || hits[j].chat != hits[j - 1].chat).count(); + i + headers + } +} + +pub enum Act { + Close, + Pick(usize), + Hover(usize), + Suggest(usize), + Sort, + Unfilter(Range), +} + +pub type OnAct = Rc; + +fn click(on: &OnAct, act: impl Fn() -> Act + 'static) -> impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static { + let on = on.clone(); + move |_, w, cx| { + cx.stop_propagation(); + on(act(), w, cx) + } +} + +/// The header's magnifier: search the open chat. +pub fn button(on: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static) -> impl IntoElement { + // i18n-exempt: key names + let keys = if cfg!(target_os = "macos") { "\u{2318}F" } else { "Ctrl+F" }; + div() + .id("search-btn") + .tip(t::search_button_tip(keys.to_string())) + .size(px(40.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .on_click(on) + .child(svg().path("icons/search.svg").size(px(19.)).text_color(c(ICON_MUTED))) +} + +/// Where a chat is: its name, and the picture that stands for it. +fn place(store: &Store, chat: &str) -> (String, Option, bool) { + if let Some(com) = store.community_of(chat) { + let ch = com.channel(chat).map(|c| c.name.clone()).unwrap_or_default(); + // i18n-exempt: channel sigil + return (format!("#{ch} · {}", com.name), store.icon(&com.community_id), false); + } + (store.name(chat), store.avatar_path(chat), true) +} + +fn when(ms: u64, now_ms: u64) -> String { + use crate::dates::{Clock, DateStyle}; + let Some(d) = crate::dates::at_ms(ms as i64) else { return String::new() }; + let now = crate::dates::at_ms(now_ms as i64); + if now.is_some_and(|n| n.date_naive() == d.date_naive()) { + return crate::dates::time(&d, Clock::default()); + } + crate::dates::date_time(&d, DateStyle::Medium, Clock::default()) +} + +fn snippet(text: &str, marks: &[Range]) -> StyledText { + let mark = HighlightStyle { + color: Some(c(ACCENT)), + font_weight: Some(FontWeight::SEMIBOLD), + ..Default::default() + }; + StyledText::new(text.to_string()).with_highlights(marks.iter().map(|r| (r.clone(), mark))) +} + +fn chip(tok: &Token, store: &Store, dir: &Directory, on: &OnAct) -> AnyElement { + let shown: String = match tok.key { + Key::From | Key::Mentions if Directory::is_me(&tok.value) => t::search_you().to_string(), + Key::From | Key::Mentions => { + let m = Directory::matches(&dir.people, &tok.value); + match m.as_slice() { + [one] => store.name(&one.id), + _ => tok.value.clone(), + } + } + Key::Has => HAS.iter().find(|(w, _)| *w == tok.value.to_ascii_lowercase()).map_or(tok.value.clone(), |(_, h)| has_label(*h).to_string()), + _ => tok.value.clone(), + }; + let range = tok.range.clone(); + div() + .id(SharedString::from(format!("search-chip-{}", tok.range.start))) + .flex() + .items_center() + .gap(px(6.)) + .h(px(26.)) + .pl(px(10.)) + .pr(px(4.)) + .rounded(px(13.)) + .bg(white_a(0.06)) + .border_1() + .border_color(white_a(0.12)) + .text_size(px(13.)) + .child(div().text_color(c(ICON_MUTED)).font_weight(FontWeight::SEMIBOLD).child(format!("{}:", tok.key.word()))) + .child(div().text_color(c(TEXT)).max_w(px(180.)).overflow_hidden().text_ellipsis().whitespace_nowrap().child(shown)) + .child( + div() + .id(SharedString::from(format!("search-chip-x-{}", tok.range.start))) + .tip(t::search_remove_filter()) + .size(px(18.)) + .rounded_full() + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|s| s.bg(white_a(0.12))) + .on_click(click(on, move || Act::Unfilter(range.clone()))) + .child(svg().path("icons/x.svg").size(px(10.)).text_color(white_a(0.7))), + ) + .into_any_element() +} + +fn suggestion_row(i: usize, s: &Suggest, sel: bool, store: &Store, compact: bool, on: &OnAct) -> AnyElement { + let (lead_px, glyph) = if compact { (22., 12.) } else { (28., 15.) }; + let (lead, title, hint): (AnyElement, SharedString, Option) = match s { + Suggest::Key(k) => ( + div() + .size(px(lead_px)) + .rounded(px(lead_px / 4.)) + .bg(white_a(0.06)) + .flex() + .items_center() + .justify_center() + .child(svg().path(k.icon()).size(px(glyph)).text_color(c(ICON_MUTED))) + .into_any_element(), + format!("{}:", k.word()).into(), + Some(k.label()), + ), + Suggest::Value { key, label, npub, .. } => { + let lead = match (npub, key) { + (Some(n), _) => crate::ui::avatar(store, n, lead_px), + (None, k) => { + let path = match (k, s) { + (Key::Has, Suggest::Value { value, .. }) => HAS.iter().find(|(w, _)| w == value).map_or(k.icon(), |(_, h)| has_icon(*h)), + _ => k.icon(), + }; + div() + .size(px(lead_px)) + .rounded(px(lead_px / 4.)) + .bg(white_a(0.06)) + .flex() + .items_center() + .justify_center() + .child(svg().path(path).size(px(glyph)).text_color(c(ICON_MUTED))) + .into_any_element() + } + }; + (lead, label.clone(), None) + } + }; + div() + .id(SharedString::from(format!("search-suggest-{i}"))) + .flex() + .items_center() + .gap(px(if compact { 8. } else { 12. })) + .h(px(if compact { 34. } else { 44. })) + .px(px(if compact { 8. } else { 12. })) + .when(!compact, |d| d.mx(px(8.))) + .rounded(px(if compact { 6. } else { 8. })) + .cursor_pointer() + .when(sel, |d| d.bg(white_a(0.07))) + .hover(|d| d.bg(white_a(0.05))) + .on_mouse_move({ + let on = on.clone(); + move |_, w, cx| on(Act::Hover(i), w, cx) + }) + .on_click(click(on, move || Act::Suggest(i))) + .child(lead) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .items_baseline() + .gap(px(10.)) + .child(div().font_weight(FontWeight::SEMIBOLD).text_size(px(if compact { 13. } else { 15. })).whitespace_nowrap().child(title)) + .children(hint.filter(|_| !compact).map(|h| div().text_size(px(13.)).text_color(c(LIST_TIME)).overflow_hidden().text_ellipsis().whitespace_nowrap().child(h))), + ) + .into_any_element() +} + +fn header(store: &Store, chat: &str) -> AnyElement { + let (name, pic, dm) = place(store, chat); + div() + .flex() + .items_center() + .gap(px(8.)) + .px(px(20.)) + .pt(px(14.)) + .pb(px(6.)) + .child(match pic { + Some(p) => crate::pic::img_face(p, 18.).object_fit(gpui::ObjectFit::Cover).size(px(18.)).when(dm, |i| i.rounded_full()).when(!dm, |i| i.rounded(px(5.))).into_any_element(), + None => svg().path(if dm { "icons/user-circle.svg" } else { "icons/chats.svg" }).size(px(14.)).text_color(c(LIST_TIME)).into_any_element(), + }) + .child( + div() + .text_size(px(12.)) + .font_weight(FontWeight::BOLD) + .text_color(c(LIST_TIME)) + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .child(name.to_uppercase()), + ) + .into_any_element() +} + +fn result_row(i: usize, hit: &vector_core::search::Hit, sel: bool, store: &Store, now_ms: u64, on: &OnAct) -> AnyElement { + let who = if hit.mine { store.my_npub.clone() } else { hit.author.clone().unwrap_or_else(|| hit.chat.clone()) }; + let name = if hit.mine { t::search_you().to_string() } else { store.chat_name(&who, &hit.chat) }; + let badges: Vec<&str> = [(Has::IMAGE, "icons/image.svg"), (Has::VIDEO, "icons/video.svg"), (Has::AUDIO, "icons/volume-max.svg")] + .into_iter() + .filter(|(h, _)| hit.has.contains(*h)) + .map(|(_, p)| p) + .collect(); + let file_only = hit.has.contains(Has::FILE) && badges.is_empty(); + div() + .id(SharedString::from(format!("search-hit-{i}"))) + .flex() + .gap(px(12.)) + .px(px(12.)) + .py(px(10.)) + .mx(px(8.)) + .rounded(px(8.)) + .cursor_pointer() + .border_1() + .border_color(if sel { white_a(0.14) } else { gpui::transparent_black() }) + .bg(if sel { white_a(0.06) } else { white_a(0.025) }) + .hover(|d| d.bg(white_a(0.05))) + .on_mouse_move({ + let on = on.clone(); + move |_, w, cx| on(Act::Hover(i), w, cx) + }) + .on_click(click(on, move || Act::Pick(i))) + .child(crate::ui::avatar(store, &who, 36.)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .flex() + .items_baseline() + .gap(px(8.)) + .child(div().font_weight(FontWeight::SEMIBOLD).text_size(px(15.)).overflow_hidden().text_ellipsis().whitespace_nowrap().child(name)) + .child(div().text_size(px(12.)).text_color(c(LIST_TIME)).whitespace_nowrap().child(when(hit.at, now_ms))) + .children(badges.into_iter().map(|p| svg().path(p).size(px(13.)).text_color(c(LIST_TIME)))) + .when(file_only, |d| d.child(svg().path("icons/attachment.svg").size(px(13.)).text_color(c(LIST_TIME)))), + ) + .map(|d| { + if hit.snippet.is_empty() { + let kind = [Has::IMAGE, Has::VIDEO, Has::AUDIO, Has::FILE].into_iter().find(|h| hit.has.contains(*h)).unwrap_or(Has::FILE); + d.child(div().text_size(px(14.)).line_height(px(20.)).italic().text_color(c(LIST_TIME)).child(has_label(kind))) + } else { + d.child(div().text_size(px(14.)).line_height(px(20.)).text_color(white_a(0.82)).child(snippet(&hit.snippet, &hit.marks))) + } + }), + ) + .into_any_element() +} + +fn mini_label(text: SharedString, count: Option) -> AnyElement { + div() + .flex() + .items_center() + .gap(px(6.)) + .h(px(28.)) + .px(px(8.)) + .text_size(px(11.)) + .font_weight(FontWeight::BOLD) + .text_color(c(0x8a8a8a)) + .child(text.to_uppercase()) + .children(count.map(|n| div().text_color(white_a(0.32)).child(crate::lang::num(n)))) + .into_any_element() +} + +fn mini_row(i: usize, hit: &vector_core::search::Hit, sel: bool, open: &str, store: &Store, now_ms: u64, on: &OnAct) -> AnyElement { + let who = if hit.mine { store.my_npub.clone() } else { hit.author.clone().unwrap_or_else(|| hit.chat.clone()) }; + let name = if hit.mine { t::search_you().to_string() } else { store.chat_name(&who, &hit.chat) }; + let channel = (hit.chat != open) + .then(|| store.community_of(&hit.chat).and_then(|com| com.channel(&hit.chat)).map(|ch| format!("#{}", ch.name))) // i18n-exempt: channel sigil + .flatten(); + div() + .id(SharedString::from(format!("mini-hit-{i}"))) + .flex() + .flex_col() + .gap(px(2.)) + .px(px(8.)) + .py(px(6.)) + .rounded(px(6.)) + .cursor_pointer() + .when(sel, |d| d.bg(white_a(0.06))) + .hover(|d| d.bg(white_a(0.04))) + .on_mouse_move({ + let on = on.clone(); + move |_, w, cx| on(Act::Hover(i), w, cx) + }) + .on_click(click(on, move || Act::Pick(i))) + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child(crate::ui::avatar(store, &who, 18.)) + .child(div().flex_shrink(1.).min_w_0().font_weight(FontWeight::SEMIBOLD).text_size(px(13.)).overflow_hidden().text_ellipsis().whitespace_nowrap().child(name)) + .children(channel.map(|ch| div().flex_shrink(1.).min_w_0().text_size(px(11.)).text_color(c(LIST_TIME)).overflow_hidden().text_ellipsis().whitespace_nowrap().child(ch))) + .child(div().flex_1()) + .child(div().flex_shrink_0().text_size(px(11.)).text_color(c(LIST_TIME)).whitespace_nowrap().child(when(hit.at, now_ms))), + ) + .map(|d| { + if hit.snippet.is_empty() { + let kind = [Has::IMAGE, Has::VIDEO, Has::AUDIO, Has::FILE].into_iter().find(|h| hit.has.contains(*h)).unwrap_or(Has::FILE); + d.child(div().pl(px(24.)).text_size(px(12.5)).line_height(px(17.)).italic().text_color(c(LIST_TIME)).child(has_label(kind))) + } else { + d.child(div().pl(px(24.)).text_size(px(12.5)).line_height(px(17.)).line_clamp(3).text_color(white_a(0.82)).child(snippet(&hit.snippet, &hit.marks))) + } + }) + .into_any_element() +} + +/// The compact search in a Community's member pane: suggestions for the filter being typed, +/// else the members whose names match and the messages that do. +pub fn mini(s: &Search, store: &Store, open: &str, members: Vec, matched: usize, on: &OnAct) -> Vec { + if s.showing_suggestions() { + return s.suggest.iter().enumerate().map(|(i, sg)| suggestion_row(i, sg, i == s.sel, store, true, on)).collect(); + } + let now = store.now_ms(); + let mut out = Vec::new(); + if !members.is_empty() { + out.push(mini_label(t::community_section_members(), Some(matched))); + out.extend(members); + } + let messages = (s.corpus.is_some() && !s.loading).then_some(s.found.total); + out.push(div().when(!out.is_empty(), |d| d.mt(px(10.))).child(mini_label(t::search_mini_messages(), messages)).into_any_element()); + if s.corpus.is_none() || s.loading { + out.push(div().px(px(8.)).py(px(6.)).child(crate::kit::processing(t::search_indexing())).into_any_element()); + } else if s.found.hits.is_empty() { + out.push(div().px(px(8.)).py(px(6.)).text_size(px(12.5)).italic().text_color(c(LIST_TIME)).child(t::search_none()).into_any_element()); + } else { + out.extend(s.found.hits.iter().enumerate().map(|(i, hit)| mini_row(i, hit, i == s.sel, open, store, now, on))); + } + out +} + +/// The panel: a centred card on a wide window, the whole window on a slim one. +pub fn view(s: &Search, store: &Store, vp: (f32, f32), slim: bool, cx: &App, on: &OnAct) -> AnyElement { + let now = store.now_ms(); + let text_empty = s.input.read(cx).text().trim().is_empty(); + let field = div() + .flex() + .items_center() + .gap(px(10.)) + .h(px(52.)) + .px(px(16.)) + .child(svg().path("icons/search.svg").size(px(18.)).text_color(c(ICON_MUTED))) + .child(div().flex_1().min_w_0().child(s.input.clone())) + .child( + div() + .id("search-sort") + .tip(t::search_sort()) + .flex() + .items_center() + .gap(px(6.)) + .h(px(28.)) + .px(px(10.)) + .rounded(px(14.)) + .border_1() + .border_color(white_a(0.12)) + .text_size(px(12.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(white_a(0.75)) + .cursor_pointer() + .hover(|d| d.bg(white_a(0.06))) + .on_click(click(on, || Act::Sort)) + .child(if s.oldest { t::search_oldest() } else { t::search_newest() }), + ) + .child( + div() + .id("search-close") + .tip(t::search_close()) + .size(px(28.)) + .rounded_full() + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|d| d.bg(white_a(0.08))) + .on_click(click(on, || Act::Close)) + .child(svg().path("icons/x.svg").size(px(13.)).text_color(white_a(0.7))), + ); + let set: Vec<&Token> = s.parsed.tokens.iter().filter(|t| !t.value.is_empty()).collect(); + let chips = (!set.is_empty()).then(|| { + div() + .flex() + .flex_wrap() + .gap(px(6.)) + .px(px(16.)) + .pb(px(12.)) + .children(set.iter().map(|tok| chip(tok, store, &s.dir, on))) + }); + + let mut list = div().id("search-list").flex_1().min_h_0().overflow_y_scroll().track_scroll(&s.scroll).flex().flex_col().pb(px(8.)); + let mut status: Option = None; + if s.showing_suggestions() { + let dated = matches!(s.suggest.first(), Some(Suggest::Value { key: Key::Before | Key::After | Key::During, .. })); + let title = if text_empty { + Some(t::search_options()) + } else if dated { + Some(t::search_date_hint()) + } else { + None + }; + list = list + .children(title.map(|t| { + div().px(px(20.)).pt(px(12.)).pb(px(6.)).text_size(px(12.)).font_weight(FontWeight::BOLD).text_color(c(LIST_TIME)).child(if text_empty { t.to_uppercase() } else { t.to_string() }) + })) + .children(s.suggest.iter().enumerate().map(|(i, sg)| suggestion_row(i, sg, i == s.sel, store, false, on))); + } else if s.corpus.is_none() { + status = Some(crate::kit::processing(t::search_indexing()).into_any_element()); + } else if s.found.hits.is_empty() { + status = Some( + div() + .flex() + .flex_col() + .items_center() + .gap(px(6.)) + .py(px(40.)) + .child(svg().path("icons/file-search.svg").size(px(40.)).text_color(white_a(0.25))) + .child(div().font_weight(FontWeight::SEMIBOLD).child(t::search_none())) + .child(div().text_size(px(13.)).text_color(c(LIST_TIME)).child(t::search_none_hint())) + .into_any_element(), + ); + } else { + let hits = &s.found.hits; + let mut rows: Vec = Vec::with_capacity(hits.len() * 2); + for (i, hit) in hits.iter().enumerate() { + if i == 0 || hits[i - 1].chat != hit.chat { + rows.push(header(store, &hit.chat)); + } + rows.push(result_row(i, hit, i == s.sel, store, now, on)); + } + list = list.children(rows); + } + let count = (!s.showing_suggestions() && s.corpus.is_some() && !s.found.hits.is_empty()).then(|| { + let shown = s.found.hits.len(); + let label = if shown < s.found.total { + if s.oldest { t::search_results_capped_oldest(shown, s.found.total) } else { t::search_results_capped(shown, s.found.total) } + } else { + t::search_results(s.found.total) + }; + div() + .flex() + .items_center() + .justify_between() + .px(px(20.)) + .py(px(8.)) + .border_t_1() + .border_color(c(DIVIDER)) + .text_size(px(12.)) + .text_color(c(LIST_TIME)) + .child(label) + .child(div().text_color(white_a(0.3)).child(format!("{:.1} ms", s.took as f32 / 1000.))) // i18n-exempt: unit + }); + let body = div() + .flex() + .flex_col() + .size_full() + .child(field) + .child(div().h(px(1.)).bg(c(DIVIDER)).mb(px(if chips.is_some() { 12. } else { 0. }))) + .children(chips) + .child(div().flex_1().min_h_0().flex().flex_col().children(status).child(list)) + .children(count); + + let (w, h) = vp; + let card = if slim { + div().absolute().inset_0().bg(c(APP_BG)).pt(px(28.)).child(body) + } else { + let width = (w - 48.).min(680.); + let height = (h * 0.72).clamp(320., 640.); + div() + .absolute() + .top(px((h * 0.1).max(36.))) + .left(px((w - width) / 2.)) + .w(px(width)) + .h(px(height)) + .rounded(px(12.)) + .border_1() + .border_color(c(0x262626)) + .bg(c(APP_BG)) + .overflow_hidden() + .shadow(vec![gpui::BoxShadow { + color: ca(0, 0, 0, 0.6), + offset: gpui::point(px(0.), px(8.)), + blur_radius: px(32.), + spread_radius: px(0.), + inset: false, + }]) + .child(body) + }; + gpui::deferred( + div() + .id("search-backdrop") + .absolute() + .inset_0() + .bg(ca(0, 0, 0, if slim { 1. } else { 0.6 })) + .occlude() + .on_click(click(on, || Act::Close)) + .child( + card.id("search-card") + .on_click(|_, _, cx| cx.stop_propagation()) + .font_family(INTER) + .text_color(c(TEXT)), + ), + ) + .with_priority(11) + .into_any_element() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dir() -> Directory { + let n = |id: &str, name: &str| Named { id: id.into(), name: name.into(), folded: vector_core::search::fold(name) }; + Directory { + me: "npub1me".into(), + people: vec![n("npub1al", "Alice"), n("npub1ali", "Alicia Keys"), n("npub1bo", "Bob")], + chats: vec![n("npub1bo", "Bob"), n("chan1", "#general · Vector"), n("chan2", "#dev · Vector")], + } + } + + #[test] + fn splits_filters_from_words() { + let p = parse("hello from:alice has:image world in:\"Alicia Keys\""); + assert_eq!(p.words, "hello world"); + let keys: Vec<(Key, &str)> = p.tokens.iter().map(|t| (t.key, t.value.as_str())).collect(); + assert_eq!(keys, [(Key::From, "alice"), (Key::Has, "image"), (Key::In, "Alicia Keys")]); + assert_eq!(&"hello from:alice has:image world in:\"Alicia Keys\""[p.tokens[2].range.clone()], "in:\"Alicia Keys\""); + // An unknown key is just a word. + assert_eq!(parse("ratio:2").words, "ratio:2"); + } + + #[test] + fn names_resolve_exact_first() { + let d = dir(); + let f = filter_of(&parse("from:alice").tokens, &d, 0, false); + assert_eq!(f.from, ["npub1al"]); + let f = filter_of(&parse("from:ali").tokens, &d, 0, false); + assert_eq!(f.from, ["npub1al", "npub1ali"]); + let f = filter_of(&parse("from:me").tokens, &d, 0, false); + assert!(f.from_me && f.from.is_empty()); + let f = filter_of(&parse("mentions:me").tokens, &d, 0, false); + assert_eq!(f.mentions, ["npub1me"]); + let f = filter_of(&parse("from:zed").tokens, &d, 0, false); + assert_eq!(f.from, [NOBODY]); + } + + #[test] + fn chats_and_kinds() { + let d = dir(); + let f = filter_of(&parse("in:#general has:img").tokens, &d, 0, false); + assert_eq!(f.chats, ["chan1"]); + assert_eq!(f.has, Has::IMAGE); + let f = filter_of(&parse("in:vector").tokens, &d, 0, false); + assert_eq!(f.chats, ["chan1", "chan2"]); + } + + #[test] + fn dates_bound_whole_days() { + let now = Local.with_ymd_and_hms(2026, 11, 19, 12, 0, 0).unwrap().timestamp_millis() as u64; + let (s, e) = day_span("2026-11-18", now).unwrap(); + assert_eq!(e - s, 86_400_000 - 1); + let (ts, _) = day_span("today", now).unwrap(); + assert_eq!(ts, e + 1); + let (ms, me) = day_span("2026-02", now).unwrap(); + assert_eq!((me + 1 - ms) / 86_400_000, 28); + assert!(day_span("2026-13-01", now).is_none()); + assert!(day_span("soon", now).is_none()); + let f = filter_of(&parse("during:2026-11-18").tokens, &dir(), now, false); + assert_eq!((f.after, f.before), (Some(s), Some(e))); + let f = filter_of(&parse("before:2026-11-18").tokens, &dir(), now, false); + assert_eq!(f.before, Some(s - 1)); + } + + #[test] + fn suggests_for_the_word_at_the_caret() { + let d = dir(); + let (_, s) = suggestions("", 0, &d, 0); + assert_eq!(s.len(), KEYS.len()); + let (r, s) = suggestions("hi fr", 5, &d, 0); + assert_eq!(r, 3..5); + assert_eq!(s, [Suggest::Key(Key::From)]); + let (r, s) = suggestions("hi from:al", 10, &d, 0); + assert_eq!(r, 3..10); + let names: Vec = s.iter().map(|s| match s { Suggest::Value { value, .. } => value.clone(), _ => String::new() }).collect(); + assert_eq!(names, ["Alice", "Alicia Keys"]); + assert_eq!(completion(&s[1]), "from:\"Alicia Keys\" "); + let (_, s) = suggestions("has:v", 5, &d, 0); + assert_eq!(s.len(), 1); + // Ordinary words offer nothing. + assert!(suggestions("hello", 5, &d, 0).1.is_empty()); + } +} diff --git a/crates/vector-gpui/src/ui.rs b/crates/vector-gpui/src/ui.rs index 637c10edd..fbd91b612 100644 --- a/crates/vector-gpui/src/ui.rs +++ b/crates/vector-gpui/src/ui.rs @@ -298,6 +298,7 @@ pub struct VectorApp { switcher_up: bool, badge_card: Option, new_chat: Option, + search: Option, create_community: Option, invite: Option, comm_settings: Option, @@ -434,6 +435,7 @@ enum Mode { /// What a context menu row does. enum MenuAct { FoldRail, + SearchHere, /// The Messages door's catch-up: every unread DM. ReadAllDms, AddFriend, @@ -693,6 +695,8 @@ mod ui_scrollbar; mod ui_routing; #[path = "ui_pins.rs"] mod pins_ops; +#[path = "ui_search.rs"] +mod search_ops; #[path = "ui_msgmenu.rs"] mod msgmenu_ops; #[path = "ui_timeouts.rs"] @@ -1091,6 +1095,7 @@ impl VectorApp { switcher_up: false, badge_card: None, new_chat: None, + search: None, create_community: None, invite: None, comm_settings: None, @@ -2015,6 +2020,7 @@ impl VectorApp { self.show_toast(&t::copied_link(), cx); } MenuAct::NewMessage => self.open_new_chat(window, cx), + MenuAct::SearchHere => self.open_search(true, window, cx), MenuAct::AddFriend => { let me = self.store.borrow().my_npub.clone(); self.show_profile_qr(&me, window, cx); @@ -6691,6 +6697,20 @@ impl VectorApp { cx.stop_propagation(); return; } + if e.keystroke.key == "escape" && app.search.is_some() { + app.on_search(crate::search::Act::Close, window, cx); + cx.stop_propagation(); + return; + } + // Cmd/Ctrl+K searches every chat, Cmd/Ctrl+F the open one. + let m = &e.keystroke.modifiers; + let primary = if cfg!(target_os = "macos") { m.platform && !m.control } else { m.control && !m.platform }; + if primary && !m.alt && !m.shift && matches!(e.keystroke.key.as_str(), "k" | "f") && matches!(app.screen, Screen::Main) { + let here = e.keystroke.key == "f" && app.open.is_some(); + app.open_search(here, window, cx); + cx.stop_propagation(); + return; + } if e.keystroke.key == "escape" && (app.escape_overlay() || app.escape_panel(window, cx) || app.nexus_escape(window, cx)) { @@ -7056,6 +7076,7 @@ impl VectorApp { .children(self.status_view(&store, window, cx)) .children(self.qr_view(window, cx)) .children(self.qr_scanner_view(window, cx)) + .children(self.search_view(window, cx)) .children(self.badge_card.as_ref().map(|card| { if card.opened.elapsed().as_secs_f32() < 0.45 { window.request_animation_frame(); @@ -8994,6 +9015,7 @@ impl VectorApp { ), ) }) + .when(!self.is_slim, |d| d.child(crate::search::button(cx.listener(|app, _, window, cx| app.open_search(true, window, cx))))) .when(menu, |d| d.child({ let probe = self.chat_menu_btn.clone(); let chat = id.to_string(); @@ -9249,8 +9271,8 @@ impl VectorApp { /// `buildChatMenuItems`: what the open chat's ⋯ offers. fn open_chat_menu(&mut self, chat: String, cx: &mut Context) { - let mut items = vec![kit::MenuItem::new(t::chat_menu_self_destruct(), "clock")]; - let mut acts = vec![MenuAct::SelfDestruct(chat.clone())]; + let mut items = vec![kit::MenuItem::new(t::search_in_chat(), "search"), kit::MenuItem::new(t::chat_menu_self_destruct(), "clock")]; + let mut acts = vec![MenuAct::SearchHere, MenuAct::SelfDestruct(chat.clone())]; let community = self.store.borrow().community_of(&chat).map(|c| c.community_id.clone()); if let Some(community) = community && self.community_caps(&community).contains("manage_channels") @@ -11281,12 +11303,12 @@ impl VectorApp { let cached = self.store.borrow().rosters.get(&id).cloned(); if self.community.as_ref().is_none_or(|v| v.id != id) { let search = cx.new(|cx| { - TextInput::new(t::member_search(), cx).with_look(crate::community::member_search_look(self.is_slim)) + let mut i = TextInput::new(t::search_mini(), cx).with_look(crate::community::member_search_look(self.is_slim)); + i.set_nav(true); + i }); - cx.subscribe(&search, |_, _, _: &crate::composer::InputChanged, cx| { - cx.notify() - }) - .detach(); + cx.subscribe(&search, |app, _, _: &crate::composer::InputChanged, cx| app.pane_find_changed(cx)).detach(); + cx.subscribe_in(&search, window, |app, _, nav: &crate::composer::Nav, window, cx| app.pane_find_nav(nav, window, cx)).detach(); let (members, admins, unlisted) = match cached { Some(r) => r, None => (members, Vec::new(), self.store.borrow().fixture_unlisted.get(&id).cloned().unwrap_or_default()), @@ -11298,6 +11320,7 @@ impl VectorApp { members, admins, panel: !self.live || backend::prefs::sql("ws_members_open").as_deref() != Some("false"), + find: crate::search::Search::new(search.clone(), Default::default()), search, folded: folded_sections(&id), scroll: gpui::ScrollHandle::new(), @@ -11575,6 +11598,8 @@ impl VectorApp { } Act::DropChannel(moved, at) => self.drop_channel(moved, at, cx), Act::DropCategory(moved, target, before) => self.drop_category(moved, target, before, cx), + Act::Search => self.open_search(true, window, cx), + Act::Find(act) => self.on_pane_find(act, window, cx), Act::ChatMenu => { if let Some(chat) = self.open.clone() { self.open_chat_menu(chat.to_string(), cx); diff --git a/crates/vector-gpui/src/ui_search.rs b/crates/vector-gpui/src/ui_search.rs new file mode 100644 index 000000000..3d7481ee4 --- /dev/null +++ b/crates/vector-gpui/src/ui_search.rs @@ -0,0 +1,305 @@ +//! Message search's lifecycle: opened from the keyboard or a chat header, the corpus read in +//! the background, each keystroke a fresh scan, and a result opened where it was said. + +use std::rc::Rc; +use std::sync::Arc; + +use gpui::{AnyElement, AppContext as _, Context, Focusable as _, SharedString, Window}; + +use super::VectorApp; +use crate::backend; +use crate::composer::{CancelInput, InputChanged, Nav, TextInput}; +use crate::search::{Act, Directory, Search, Suggest}; +use crate::t; + +impl VectorApp { + /// Opens search over every chat, or over the open one when `here`. + pub(super) fn open_search(&mut self, here: bool, window: &mut Window, cx: &mut Context) { + let dir = Directory::read(&self.store.borrow()); + let scope = here + .then(|| self.open.clone()) + .flatten() + .and_then(|id| dir.chats.iter().find(|c| c.id == id.as_ref()).cloned()); + if let Some(s) = self.search.as_ref() { + let focus = s.input.focus_handle(cx); + window.focus(&focus, cx); + if scope.is_none() { + return; + } + } + let placeholder: SharedString = match &scope { + Some(c) => t::search_placeholder_in(c.name.split(" · ").next().unwrap_or(&c.name).to_string()), + None => t::search_placeholder(), + }; + let input = cx.new(|cx| { + let mut i = TextInput::new(placeholder, cx).with_look(crate::composer::Look { + size: gpui::px(17.), + ..crate::kit::field_look() + }); + i.set_nav(true); + if let Some(c) = &scope { + let value = c.name.clone(); + let text = crate::search::completion(&Suggest::Value { + key: crate::search::Key::In, + value, + label: SharedString::default(), + npub: None, + }); + i.set_text(&text, cx); + } + i + }); + cx.subscribe_in(&input, window, |app, _, _: &InputChanged, _, cx| app.search_changed(cx)).detach(); + cx.subscribe_in(&input, window, |app, _, nav: &Nav, window, cx| { + let Some(s) = app.search.as_mut() else { return }; + match nav { + Nav::Up => s.step(false), + Nav::Down => s.step(true), + Nav::Pick => { + let sel = s.sel; + let act = if s.showing_suggestions() { Act::Suggest(sel) } else { Act::Pick(sel) }; + return app.on_search(act, window, cx); + } + Nav::Close => return app.on_search(Act::Close, window, cx), + } + cx.notify(); + }) + .detach(); + cx.subscribe_in(&input, window, |app, _, _: &CancelInput, window, cx| app.on_search(Act::Close, window, cx)).detach(); + window.focus(&input.focus_handle(cx), cx); + let reuse = self.search.as_mut().and_then(|s| s.corpus.take()); + self.search = Some(Search::new(input, dir)); + self.close_popups(cx); + match reuse { + Some(corpus) => self.search_loaded(corpus, cx), + None => self.search_load(cx), + } + self.search_changed(cx); + } + + fn search_load(&mut self, cx: &mut Context) { + let (names, blocked) = { + let store = self.store.borrow(); + (crate::search::names(&store), crate::search::blocked(&store)) + }; + if !self.live { + let corpus = Arc::new(crate::search::fixture_corpus(&self.store.borrow())); + return self.search_loaded(corpus, cx); + } + let rx = backend::run(async move { + let records = vector_core::search::load()?; + Ok::<_, String>(Arc::new(crate::search::build(&records, &names, &blocked))) + }); + cx.spawn(async move |this, cx| { + let res = rx.await; + this.update(cx, |this, cx| match res { + Ok(Ok(corpus)) => this.search_loaded(corpus, cx), + Ok(Err(e)) => this.show_toast(&e, cx), + Err(_) => {} + }) + .ok(); + }) + .detach(); + } + + fn search_loaded(&mut self, corpus: Arc, cx: &mut Context) { + if let Some(s) = self.search.as_mut() { + s.corpus = Some(corpus); + } + self.search_changed(cx); + } + + fn search_changed(&mut self, cx: &mut Context) { + let now = self.store.borrow().now_ms(); + let Some(s) = self.search.as_mut() else { return }; + let (text, caret) = { + let i = s.input.read(cx); + (i.text().to_string(), i.caret()) + }; + s.refresh(&text, caret, now); + cx.notify(); + } + + pub(super) fn on_search(&mut self, act: Act, window: &mut Window, cx: &mut Context) { + let Some(s) = self.search.as_mut() else { return }; + match act { + Act::Close => { + // The plaintext corpus goes with the panel. + self.search = None; + window.focus(&self.input.read(cx).focus_handle(cx), cx); + } + Act::Hover(i) => { + if s.sel == i { + return; + } + s.sel = i; + } + Act::Sort => { + s.oldest = !s.oldest; + return self.search_changed(cx); + } + Act::Suggest(i) => { + let Some(sg) = s.suggest.get(i).cloned() else { return }; + let range = s.suggest_at.clone(); + let input = s.input.clone(); + input.update(cx, |inp, cx| inp.replace(range, &crate::search::completion(&sg), window, cx)); + return self.search_changed(cx); + } + Act::Unfilter(range) => { + let input = s.input.clone(); + input.update(cx, |inp, cx| { + let text = inp.text().to_string(); + let end = text[range.end..].find(|c: char| !c.is_whitespace()).map_or(text.len(), |n| range.end + n); + inp.replace(range.start..end, "", window, cx); + }); + let focus = input.focus_handle(cx); + window.focus(&focus, cx); + return self.search_changed(cx); + } + Act::Pick(i) => { + let Some(hit) = s.found.hits.get(i).cloned() else { return }; + self.search = None; + self.settings = None; + self.profile = None; + self.close_nexus(cx); + self.new_chat = None; + self.create_community = None; + if self.is_slim { + self.slim.drawer = false; + } + self.open_chat(SharedString::from(hit.chat), window, cx); + self.jump_or_say(hit.id, t::msg_jump_not_local(), cx); + } + } + cx.notify(); + } + + pub(super) fn search_view(&mut self, window: &mut Window, cx: &mut Context) -> Option { + let s = self.search.as_ref()?; + let app = cx.entity().downgrade(); + let on: crate::search::OnAct = Rc::new(move |act, window, cx| { + app.update(cx, |app, cx| app.on_search(act, window, cx)).ok(); + }); + let vp = window.viewport_size(); + let store = self.store.borrow(); + Some(crate::search::view(s, &store, (f32::from(vp.width), f32::from(vp.height)), self.is_slim, cx, &on)) + } + + /// The member pane's field changed: members filter as before, messages scan the Community. + pub(super) fn pane_find_changed(&mut self, cx: &mut Context) { + let now = self.store.borrow().now_ms(); + let Some(v) = self.community.as_mut() else { return }; + let (text, caret) = { + let i = v.search.read(cx); + (i.text().to_string(), i.caret()) + }; + if text.trim().is_empty() { + // Read afresh on the next search, so it sees what arrived meanwhile. + v.find.corpus = None; + v.find.loading = false; + v.find.refresh(&text, caret, now); + return cx.notify(); + } + if v.find.corpus.is_none() && !v.find.loading { + let store = self.store.borrow(); + if let Some(com) = store.community(&v.id) { + let people = v.members.iter().chain(v.unlisted.keys()).cloned(); + v.find.dir = Directory::community(&store, com, people); + v.find.scope = com.channels.iter().filter(|c| c.view != "voice").map(|c| c.channel_id.clone()).collect(); + } + drop(store); + v.find.loading = true; + let id = v.id.clone(); + self.pane_find_load(id, cx); + } + let Some(v) = self.community.as_mut() else { return }; + v.find.refresh(&text, caret, now); + cx.notify(); + } + + fn pane_find_load(&mut self, id: String, cx: &mut Context) { + let done = move |this: &mut Self, corpus: Arc, cx: &mut Context| { + if let Some(v) = this.community.as_mut().filter(|v| v.id == id && v.find.loading) { + v.find.corpus = Some(corpus); + v.find.loading = false; + this.pane_find_changed(cx); + } + }; + if !self.live { + let corpus = Arc::new(crate::search::fixture_corpus(&self.store.borrow())); + return done(self, corpus, cx); + } + let (names, blocked) = { + let store = self.store.borrow(); + (crate::search::names(&store), crate::search::blocked(&store)) + }; + let rx = backend::run(async move { + let records = vector_core::search::load()?; + Ok::<_, String>(Arc::new(crate::search::build(&records, &names, &blocked))) + }); + cx.spawn(async move |this, cx| { + let res = rx.await; + this.update(cx, |this, cx| match res { + Ok(Ok(corpus)) => done(this, corpus, cx), + Ok(Err(e)) => { + if let Some(v) = this.community.as_mut() { + v.find.loading = false; + } + this.show_toast(&e, cx) + } + Err(_) => {} + }) + .ok(); + }) + .detach(); + } + + pub(super) fn pane_find_nav(&mut self, nav: &Nav, window: &mut Window, cx: &mut Context) { + let Some(v) = self.community.as_mut() else { return }; + if v.search.read(cx).text().trim().is_empty() { + return; + } + match nav { + Nav::Up => v.find.step(false), + Nav::Down => v.find.step(true), + Nav::Pick => { + let act = if v.find.showing_suggestions() { Act::Suggest(v.find.sel) } else { Act::Pick(v.find.sel) }; + return self.on_pane_find(act, window, cx); + } + Nav::Close => return self.on_pane_find(Act::Close, window, cx), + } + cx.notify(); + } + + pub(super) fn on_pane_find(&mut self, act: Act, window: &mut Window, cx: &mut Context) { + let Some(v) = self.community.as_mut() else { return }; + let input = v.search.clone(); + match act { + Act::Close => input.update(cx, |i, cx| i.set_text("", cx)), + Act::Hover(i) => { + if v.find.sel == i { + return; + } + v.find.sel = i; + return cx.notify(); + } + Act::Suggest(i) => { + let Some(sg) = v.find.suggest.get(i).cloned() else { return }; + let range = v.find.suggest_at.clone(); + input.update(cx, |inp, cx| inp.replace(range, &crate::search::completion(&sg), window, cx)); + window.focus(&input.focus_handle(cx), cx); + } + Act::Pick(i) => { + let Some(hit) = v.find.found.hits.get(i).cloned() else { return }; + if self.is_slim { + self.slim.details = None; + } + self.open_channel(hit.chat, window, cx); + self.jump_or_say(hit.id, t::msg_jump_not_local(), cx); + return cx.notify(); + } + Act::Sort | Act::Unfilter(_) => {} + } + self.pane_find_changed(cx); + } +} diff --git a/crates/vector-i18n/locales/en-GB/core.ftl b/crates/vector-i18n/locales/en-GB/core.ftl index c48548e10..861acf490 100644 --- a/crates/vector-i18n/locales/en-GB/core.ftl +++ b/crates/vector-i18n/locales/en-GB/core.ftl @@ -1016,3 +1016,7 @@ core-miniapp-invalid-mini-app = Invalid mini app: { $error } core-miniapp-invalid-manifest-too-large = Invalid manifest: too large # $error: a technical reason, often in English core-miniapp-invalid-manifest = Invalid manifest: { $error } +# $error: a technical reason, often in English +core-search-prepare-failed = Failed to prepare search query: { $error } +# $error: a technical reason, often in English +core-search-query-failed = Failed to run search query: { $error } diff --git a/crates/vector-i18n/locales/en-GB/members.ftl b/crates/vector-i18n/locales/en-GB/members.ftl index 6022ed142..d7b44ae9c 100644 --- a/crates/vector-i18n/locales/en-GB/members.ftl +++ b/crates/vector-i18n/locales/en-GB/members.ftl @@ -31,7 +31,6 @@ member-ban-failed = Couldn't ban # Hovering the clock by a timed-out member's name. $left is a countdown, like "2h 5m". member-timeout-ends = Timeout ends in { $left } member-timeout-ending = Timeout ending -member-search = Search Members... ## A member's small profile card diff --git a/crates/vector-i18n/locales/en-GB/search.ftl b/crates/vector-i18n/locales/en-GB/search.ftl new file mode 100644 index 000000000..08f62daed --- /dev/null +++ b/crates/vector-i18n/locales/en-GB/search.ftl @@ -0,0 +1,52 @@ +### Message search: the search panel, its filters and its results. + +search-placeholder = Search messages +# Shown in the field while a search is limited to the open chat. $chat is its name. +search-placeholder-in = Search { $chat } +search-indexing = Reading your messages… +search-none = No results +search-none-hint = Try fewer words, or take a filter away. +# $count is how many messages matched. +search-results = { $count -> + [one] { $count } result + *[other] { $count } results +} +# $shown of $count matches are listed. +search-results-capped = Showing the newest { $shown } of { $count } results +# $shown of $count matches are listed, the oldest first. +search-results-capped-oldest = Showing the oldest { $shown } of { $count } results +search-newest = Newest +search-oldest = Oldest +search-sort = Sort order +search-close = Close search + +## Filters. The words before the colon in the search field (from:, in:, ...) stay English, as +## they do in every language; these are the labels shown beside them. + +search-options = Search options +search-opt-from = From a person +search-opt-mentions = Mentions a person +search-opt-has = Has a link, image, video, audio or file +search-opt-in = In a chat or channel +search-opt-before = Before a date +search-opt-after = After a date +search-opt-during = On a date +search-has-link = Link +search-has-image = Image +search-has-video = Video +search-has-audio = Audio +search-has-file = File +search-me = Me +search-today = Today +search-yesterday = Yesterday +# How a date is typed into a before:, after: or during: filter. +search-date-hint = A date, like 2026-11-18, 2026-11 or 2026 +search-remove-filter = Remove filter +search-you = You +search-in-chat = Search in Chat +# The heading over message results in a Community's member pane. +search-mini-messages = Messages +# The member pane's field, which searches members and messages. +search-mini = Search +# The header's search button. $keys is its shortcut, such as Ctrl+F. +search-button-tip = Search ({ $keys }) diff --git a/crates/vector-i18n/src/tests.rs b/crates/vector-i18n/src/tests.rs index 03aa05f22..d13cdaad5 100644 --- a/crates/vector-i18n/src/tests.rs +++ b/crates/vector-i18n/src/tests.rs @@ -139,6 +139,7 @@ fn the_checker_reports_missing_obsolete_and_broken() { #[test] fn lookups_work_from_any_thread() { + let _g = SWITCH.lock().unwrap_or_else(|e| e.into_inner()); let h = std::thread::spawn(|| t::day_today().to_string()); let s = h.join().unwrap(); assert!(s == "Today" || s.contains('Ŧ') || s == "day-today" || s == "Hoy" || s == "Region"); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 61c8db15c..252916021 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -11803,6 +11803,7 @@ dependencies = [ "js-sys", "libc", "libcrux-ml-kem", + "memchr", "negentropy", "noq-proto", "nostr",