Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

Search filters and Discord's filter list under the search box (#38)

VRonGitHub9b1df5329251
diff --git a/apps/rustcord/src/app.rs b/apps/rustcord/src/app.rs
index d3eecbb..5146e29 100644
--- a/apps/rustcord/src/app.rs
+++ b/apps/rustcord/src/app.rs
@@ -320,6 +320,8 @@ pub struct RustCord {
/// The open select menu of a message: (message, its custom id).
pub open_select: Option<(Id, String)>,
pub search_input: String,
+ /// The list of filters under the search box.
+ pub search_suggest: crate::ui::search::SearchSuggest,
/// Profile panel on the right of 1:1 DMs.
pub show_dm_profile: bool,
/// Back / forward navigation history (title bar arrows).
@@ -675,6 +677,7 @@ impl RustCord {
bot_modal: None,
open_select: None,
search_input: String::new(),
+ search_suggest: Default::default(),
show_dm_profile: true,
nav_back: Vec::new(),
nav_forward: Vec::new(),
diff --git a/apps/rustcord/src/backend.rs b/apps/rustcord/src/backend.rs
index 96f84b6..59a9555 100644
--- a/apps/rustcord/src/backend.rs
+++ b/apps/rustcord/src/backend.rs
@@ -96,7 +96,9 @@ pub enum Command {
Ignore { user: Id, on: bool },
/// Op 8: member info (roles, nickname) for these users in a server.
RequestMembers { guild: Id, users: Vec<Id> },
- Search { guild: Option<Id>, channel: Id, query: String },
+ /// `query` is the search box's text (it names the results); `filters`
+ /// what it asks Discord for.
+ Search { guild: Option<Id>, channel: Id, query: String, filters: discord::http::SearchQuery },
/// Recent mentions for the inbox.
FetchMentions,
/// Trending GIFs (None) or a GIF search.
@@ -1567,10 +1569,10 @@ async fn run(mut rx: UnboundedReceiver<Command>, base: Emitter) {
em.emit(Event::Pins { channel, result });
});
}
- Command::Search { guild, channel, query } => {
+ Command::Search { guild, channel, query, filters } => {
let (http, em) = (http.clone(), em.clone());
tokio::spawn(async move {
- let result = http.search(guild, channel, &query).await.map_err(|e| format!("{e:#}"));
+ let result = http.search(guild, channel, &filters).await.map_err(|e| format!("{e:#}"));
em.emit(Event::Search { query, result });
});
}
diff --git a/apps/rustcord/src/demo.rs b/apps/rustcord/src/demo.rs
index 6406a0b..1c8015b 100644
--- a/apps/rustcord/src/demo.rs
+++ b/apps/rustcord/src/demo.rs
@@ -961,8 +961,9 @@ pub async fn run(mut rx: UnboundedReceiver<Command>, em: Emitter) {
let pinned: Vec<Message> = state.pins(channel, None).iter().filter_map(|v| Message::deserialize(v).ok()).collect();
em.emit(Event::Pins { channel, result: Ok(pinned) });
}
- Command::Search { query, .. } => {
- let q = query.to_lowercase();
+ Command::Search { query, filters, .. } => {
+ // The words and who wrote it; the other filters aren't modelled.
+ let q = filters.content.to_lowercase();
let mut hits: Vec<Message> = state
.messages
.lock()
@@ -970,6 +971,7 @@ pub async fn run(mut rx: UnboundedReceiver<Command>, em: Emitter) {
.unwrap_or_default()
.iter()
.filter_map(|v| Message::deserialize(v).ok())
+ .filter(|m| filters.author_id.is_empty() || filters.author_id.contains(&m.author.id))
.collect();
hits.sort_by_key(|m| std::cmp::Reverse(m.id));
hits.truncate(25);
diff --git a/apps/rustcord/src/ui/chat.rs b/apps/rustcord/src/ui/chat.rs
index 5703e19..0e4dcd2 100644
--- a/apps/rustcord/src/ui/chat.rs
+++ b/apps/rustcord/src/ui/chat.rs
@@ -728,6 +728,10 @@ impl RustCord {
self.message_select_input(ch);
let (mut open_pins, mut toggle_members, mut do_search, mut toggle_profile) = (false, false, false, false);
+ // The search box (for its list of filters) and a row picked with the keyboard.
+ // (Ctrl+F focuses it by this id: see shortcuts.rs.)
+ let search_id = egui::Id::new("chat_search_input");
+ let mut search_bar: Option<(Rect, Option<usize>)> = None;
let mut open_notify: Option<Rect> = None;
let (mut start_call, mut start_video, mut toggle_group_members, mut open_invite) = (false, false, false, false);
let mut open_threads: Option<Pos2> = None;
@@ -829,10 +833,11 @@ impl RustCord {
}
hint = format!("{}…", hint.trim_end());
}
+ let key_pick = self.search_keys(ui.ctx(), search_id);
let search = ui.put(
text_r,
TextEdit::singleline(&mut self.search_input)
- .id(egui::Id::new("chat_search_input"))
+ .id(search_id)
.frame(false)
.font(crate::style::medium(14.0))
.hint_text(RichText::new(hint).font(crate::style::medium(14.0)).color(hint_color))
@@ -842,6 +847,7 @@ impl RustCord {
);
ui.add_space(4.0);
do_search = search.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) && !self.search_input.trim().is_empty();
+ search_bar = Some((sr, key_pick));
if channel.guild_id.is_some() {
let r = header_icon(ui, &t, icon::PEOPLE, self.show_members, if self.show_members { "Hide Member List" } else { "Show Member List" });
toggle_members = r.clicked();
@@ -946,10 +952,19 @@ impl RustCord {
self.open_pins(ch);
}
}
+ if let Some((bar, key_pick)) = search_bar {
+ self.search_suggest_ui(ui.ctx(), bar, ch, search_id, key_pick);
+ }
if do_search {
let query = self.search_input.trim().to_string();
- self.search = Some((query.clone(), None));
- self.backend.send(crate::backend::Command::Search { guild: channel.guild_id, channel: ch, query });
+ match self.search_query(ch, &query) {
+ Ok(filters) => {
+ self.search = Some((query.clone(), None));
+ self.backend.send(crate::backend::Command::Search { guild: channel.guild_id, channel: ch, query, filters });
+ }
+ // A name or date it couldn't make out: said in the results panel.
+ Err(e) => self.search = Some((query, Some(Err(e)))),
+ }
}
// Member list / DM profile: under the header, right of the chat and composer.
self.chat_side_panel(ui);
diff --git a/apps/rustcord/src/ui/mentions.rs b/apps/rustcord/src/ui/mentions.rs
index b5193af..3180a31 100644
--- a/apps/rustcord/src/ui/mentions.rs
+++ b/apps/rustcord/src/ui/mentions.rs
@@ -135,7 +135,7 @@ fn replace_names(text: &str, sigil: char, names: &[(String, String)]) -> String
impl RustCord {
/// Everyone we know who can be mentioned in a channel, most recent
/// speakers first: (user, server nickname).
- fn mention_pool(&self, ch: Id) -> Vec<(User, Option<String>)> {
+ pub(super) fn mention_pool(&self, ch: Id) -> Vec<(User, Option<String>)> {
let Some(channel) = self.store.channels.get(&ch) else { return Vec::new() };
let mut seen: HashSet<Id> = HashSet::new();
let mut out: Vec<(User, Option<String>)> = Vec::new();
@@ -179,7 +179,7 @@ impl RustCord {
/// The server's channels "#" can name: the text-like ones we can see (in
/// sidebar order), then its threads. Discord's list has no voice channels.
- fn channel_pool(&self, ch: Id) -> Vec<&discord::model::Channel> {
+ pub(super) fn channel_pool(&self, ch: Id) -> Vec<&discord::model::Channel> {
let Some(guild) = self.store.channels.get(&ch).and_then(|c| c.guild_id) else { return Vec::new() };
let mut out: Vec<&discord::model::Channel> = self
.store
diff --git a/apps/rustcord/src/ui/mod.rs b/apps/rustcord/src/ui/mod.rs
index 5ea69aa..5ff6891 100644
--- a/apps/rustcord/src/ui/mod.rs
+++ b/apps/rustcord/src/ui/mod.rs
@@ -18,6 +18,7 @@ pub mod interactions;
mod login;
mod members;
mod mentions;
+pub mod search;
pub mod motion;
mod popups;
pub mod process_viewer;
diff --git a/apps/rustcord/src/ui/search.rs b/apps/rustcord/src/ui/search.rs
new file mode 100644
index 0000000..aff4b42
--- /dev/null
+++ b/apps/rustcord/src/ui/search.rs
@@ -0,0 +1,551 @@
+//! The search box's filters and the list of suggestions under it, as Discord
+//! web has them (measured 2026-12-04). Filters are typed among the words:
+//! `from:name`, `in:channel`, `has:image`, `mentions:name`, `before:`,
+//! `during:` and `after:` with a date, `pinned:true`, `authorType:bot`.
+
+use crate::app::RustCord;
+use discord::http::SearchQuery;
+use discord::model::{Id, User, DISCORD_EPOCH};
+use eframe::egui::{self, pos2, vec2, Align2, Color32, FontId, Key, Modifiers, Order, Rect, Sense, Stroke};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Filter {
+ From,
+ In,
+ Has,
+ Mentions,
+ Before,
+ During,
+ After,
+ Pinned,
+ AuthorType,
+}
+
+impl Filter {
+ const ALL: [Filter; 9] =
+ [Filter::From, Filter::In, Filter::Has, Filter::Mentions, Filter::Before, Filter::During, Filter::After, Filter::Pinned, Filter::AuthorType];
+
+ fn key(self) -> &'static str {
+ match self {
+ Filter::From => "from:",
+ Filter::In => "in:",
+ Filter::Has => "has:",
+ Filter::Mentions => "mentions:",
+ Filter::Before => "before:",
+ Filter::During => "during:",
+ Filter::After => "after:",
+ Filter::Pinned => "pinned:",
+ Filter::AuthorType => "authorType:",
+ }
+ }
+
+ /// The filter a word starts with (case aside), and the rest of it.
+ fn split(word: &str) -> Option<(Filter, &str)> {
+ Filter::ALL.into_iter().find_map(|f| {
+ let k = f.key();
+ let head = word.get(..k.len())?;
+ head.eq_ignore_ascii_case(k).then(|| (f, &word[k.len()..]))
+ })
+ }
+}
+
+/// `has:` as typed, in Discord's order, and as the API names it.
+const HAS: [(&str, &str); 9] = [
+ ("image", "image"),
+ ("video", "video"),
+ ("link", "link"),
+ ("file", "file"),
+ ("embed", "embed"),
+ ("sound", "sound"),
+ ("poll", "poll"),
+ ("sticker", "sticker"),
+ ("forward", "snapshot"),
+];
+const AUTHOR_TYPES: [&str; 3] = ["user", "bot", "webhook"];
+
+/// The text as words, a filter's value joined to its key when typed after a
+/// space ("from: vr"): `(Some(filter), value)` or `(None, word)`.
+fn words(text: &str) -> Vec<(Option<Filter>, String)> {
+ let mut out = Vec::new();
+ let mut it = text.split_whitespace().peekable();
+ while let Some(w) = it.next() {
+ match Filter::split(w) {
+ Some((f, "")) => {
+ let value = it.next_if(|next| Filter::split(next).is_none()).unwrap_or("");
+ out.push((Some(f), value.to_string()));
+ }
+ Some((f, value)) => out.push((Some(f), value.to_string())),
+ None => out.push((None, w.to_string())),
+ }
+ }
+ out
+}
+
+fn same(a: &str, b: &str) -> bool {
+ a.to_lowercase() == b.to_lowercase()
+}
+
+fn parse_date(v: &str) -> Option<chrono::NaiveDate> {
+ ["%Y-%m-%d", "%Y/%m/%d"].iter().find_map(|f| chrono::NaiveDate::parse_from_str(v, f).ok())
+}
+
+/// The first message ID of `day`, from your local midnight, as Discord web
+/// works it out for `before:` / `during:` / `after:`.
+fn day_start(day: chrono::NaiveDate) -> Option<Id> {
+ let t = day.and_hms_opt(0, 0, 0)?.and_local_timezone(chrono::Local).earliest()?;
+ let ms = u64::try_from(t.timestamp_millis()).ok()?.checked_sub(DISCORD_EPOCH)?;
+ Some(Id(ms << 22))
+}
+
+/// The part of the text being typed (a word, or a filter and its value so
+/// far) and what's before it: `(before, filter, value)`.
+fn current(text: &str) -> (&str, Option<Filter>, &str) {
+ let trimmed = text.trim_end();
+ let typing = trimmed.len() == text.len();
+ let last_start = trimmed.rfind(char::is_whitespace).map_or(0, |i| i + 1);
+ let last = &trimmed[last_start..];
+ if !typing {
+ // "from: " — the key alone, its value still to come.
+ return match Filter::split(last) {
+ Some((f, "")) => (&text[..last_start], Some(f), ""),
+ _ => (text, None, ""),
+ };
+ }
+ if let Some((f, value)) = Filter::split(last) {
+ return (&text[..last_start], Some(f), value);
+ }
+ // "from: vr": the value of the key before it.
+ let before_last = trimmed[..last_start].trim_end();
+ let prev_start = before_last.rfind(char::is_whitespace).map_or(0, |i| i + 1);
+ match Filter::split(&before_last[prev_start..]) {
+ Some((f, "")) if !before_last.is_empty() => (&text[..prev_start], Some(f), last),
+ _ => (&text[..last_start], None, last),
+ }
+}
+
+/// One row of the list.
+enum Row {
+ /// A filter to start: icon, what it does, its key, what follows the key.
+ Filter { filter: Option<Filter>, icon: Option<&'static str>, title: &'static str, key: &'static str, hint: &'static str },
+ User(User, Option<String>),
+ Channel(String),
+ Value(String),
+}
+
+/// The list's state between frames.
+#[derive(Default)]
+pub struct SearchSuggest {
+ pub open: bool,
+ /// The row chosen with the arrow keys.
+ highlight: Option<usize>,
+ /// "More filters" was clicked.
+ more: bool,
+ /// Rows shown last frame (for the arrow keys).
+ len: usize,
+ /// Where the list was last frame: a press there keeps it open.
+ rect: Option<Rect>,
+ /// The member search last asked of the gateway for `from:` / `mentions:`.
+ asked: Option<(Id, String)>,
+}
+
+/// The list: 356 px wide, its right edge 4 px inside the box's and its top
+/// 8 px under it; 44 px filter rows 4 px apart, 12 px / 8 px padding.
+const LIST_W: f32 = 356.0;
+const FILTER_ROW_H: f32 = 44.0;
+const VALUE_ROW_H: f32 = 36.0;
+const MAX_VALUES: usize = 10;
+
+impl RustCord {
+ /// What the search box's text asks Discord for, or what in it can't be
+ /// asked ("Couldn't find …").
+ pub(super) fn search_query(&self, ch: Id, text: &str) -> Result<SearchQuery, String> {
+ let mut q = SearchQuery::default();
+ let mut content = Vec::new();
+ for (filter, v) in words(text) {
+ let Some(filter) = filter else {
+ content.push(v);
+ continue;
+ };
+ if v.is_empty() {
+ continue;
+ }
+ match filter {
+ Filter::From | Filter::Mentions => {
+ let id = self.search_user(ch, &v).ok_or_else(|| format!("Couldn't find anyone called \"{v}\"."))?;
+ if filter == Filter::From {
+ q.author_id.push(id);
+ } else {
+ q.mentions.push(id);
+ }
+ }
+ Filter::In => {
+ let name = v.trim_start_matches('#');
+ let id = self.channel_pool(ch).into_iter().find(|c| c.name.as_deref().is_some_and(|n| same(n, name))).map(|c| c.id);
+ q.channel_id.push(id.ok_or_else(|| format!("Couldn't find a channel called \"{name}\"."))?);
+ }
+ Filter::Has => {
+ let api = HAS.iter().find(|(typed, _)| same(typed, &v)).map(|(_, api)| api.to_string());
+ q.has.push(api.ok_or_else(|| format!("has: can be {}.", HAS.map(|(t, _)| t).join(", ")))?);
+ }
+ Filter::Before | Filter::During | Filter::After => {
+ let today = chrono::Local::now().date_naive().format("%Y-%m-%d");
+ let day = parse_date(&v).ok_or_else(|| format!("\"{v}\" isn't a date. Dates look like {today}."))?;
+ let (start, next) = (day_start(day), day.succ_opt().and_then(day_start));
+ // Several dates narrow it down, as on Discord.
+ let earlier = |a: Option<Id>, b: Option<Id>| a.into_iter().chain(b).min();
+ let later = |a: Option<Id>, b: Option<Id>| a.into_iter().chain(b).max();
+ match filter {
+ Filter::Before => q.max_id = earlier(q.max_id, start),
+ Filter::After => q.min_id = later(q.min_id, next),
+ _ => {
+ q.min_id = later(q.min_id, start);
+ q.max_id = earlier(q.max_id, next);
+ }
+ }
+ }
+ Filter::Pinned => {
+ let pinned = match v.to_lowercase().as_str() {
+ "true" => true,
+ "false" => false,
+ _ => return Err("pinned: is true or false.".into()),
+ };
+ // Discord keeps "true" if both are given.
+ q.pinned = Some(q.pinned.unwrap_or(false) || pinned);
+ }
+ Filter::AuthorType => {
+ let kind = AUTHOR_TYPES.iter().find(|t| same(t, &v)).ok_or_else(|| "authorType: is user, bot or webhook.".to_string())?;
+ q.author_type.push(kind.to_string());
+ }
+ }
+ }
+ q.content = content.join(" ");
+ Ok(q)
+ }
+
+ /// Someone named in `from:` / `mentions:`: by username, then by display
+ /// name or server nickname.
+ fn search_user(&self, ch: Id, name: &str) -> Option<Id> {
+ let name = name.trim_start_matches('@');
+ let pool = self.mention_pool(ch);
+ let by_username = pool.iter().find(|(u, _)| same(&u.username, name)).map(|(u, _)| u.id);
+ let by_name = || {
+ pool.iter()
+ .find(|(u, nick)| u.global_name.as_deref().is_some_and(|g| same(g, name)) || nick.as_deref().is_some_and(|n| same(n, name)))
+ .map(|(u, _)| u.id)
+ };
+ let anyone = || self.store.users.values().find(|u| same(&u.username, name)).map(|u| u.id);
+ by_username.or_else(by_name).or_else(anyone)
+ }
+
+ /// The list's rows for the search box's text.
+ fn search_rows(&self, ch: Id, text: &str) -> Vec<Row> {
+ let in_guild = self.store.channels.get(&ch).is_some_and(|c| c.guild_id.is_some());
+ let (_, filter, value) = current(text);
+ let q = value.to_lowercase();
+ let Some(filter) = filter else {
+ // Discord's "Filters", narrowed to the keys a word starts.
+ let row = |filter: Filter, icon: Option<&'static str>, title: &'static str, hint: &'static str| Row::Filter {
+ filter: Some(filter),
+ icon,
+ title,
+ key: filter.key(),
+ hint,
+ };
+ let mut rows = vec![row(Filter::From, Some("account"), "From a specific user", "user")];
+ if in_guild {
+ rows.push(row(Filter::In, Some("#"), "Sent in a specific channel", "channel"));
+ }
+ rows.push(row(Filter::Has, Some("search-has"), "Includes a specific type of data", "link, embed or file"));
+ rows.push(row(Filter::Mentions, Some("search-at"), "Mentions a specific user", "user"));
+ let more = [
+ row(Filter::Before, None, "When the message was sent", "specific date"),
+ row(Filter::During, None, "When the message was sent", "specific date"),
+ row(Filter::After, None, "When the message was sent", "specific date"),
+ row(Filter::Pinned, None, "If the message is pinned or not", "true or false"),
+ row(Filter::AuthorType, None, "Sent by any of the selected types of author", "user, bot or webhook"),
+ ];
+ if !q.is_empty() {
+ // "be" → before:. Words that start no filter get no list.
+ rows.extend(more);
+ rows.retain(|r| matches!(r, Row::Filter { key, .. } if key.to_lowercase().starts_with(&q)));
+ } else if self.search_suggest.more {
+ rows.extend(more);
+ } else {
+ rows.push(Row::Filter { filter: None, icon: Some("search-more"), title: "More filters", key: "", hint: "dates, author type, and more" });
+ }
+ return rows;
+ };
+ match filter {
+ Filter::From | Filter::Mentions => {
+ let q = q.trim_start_matches('@');
+ let rank = |u: &User, nick: &Option<String>| -> Option<u8> {
+ let names = [Some(u.username.as_str()), u.global_name.as_deref(), nick.as_deref()];
+ let names = names.iter().flatten().map(|n| n.to_lowercase());
+ let names: Vec<String> = names.collect();
+ if names.iter().any(|n| n.starts_with(q)) {
+ Some(0)
+ } else if names.iter().any(|n| n.contains(q)) {
+ Some(1)
+ } else {
+ None
+ }
+ };
+ let mut users: Vec<(u8, User, Option<String>)> =
+ self.mention_pool(ch).into_iter().filter_map(|(u, nick)| Some((rank(&u, &nick)?, u, nick))).collect();
+ users.sort_by_key(|(r, _, _)| *r);
+ users.into_iter().take(MAX_VALUES).map(|(_, u, nick)| Row::User(u, nick)).collect()
+ }
+ Filter::In => {
+ let q = q.trim_start_matches('#');
+ let pool = self.channel_pool(ch);
+ let names = pool.iter().filter_map(|c| c.name.clone()).filter(|n| n.to_lowercase().contains(q));
+ names.take(MAX_VALUES).map(Row::Channel).collect()
+ }
+ Filter::Has => HAS.iter().filter(|(t, _)| t.starts_with(&q)).map(|(t, _)| Row::Value(t.to_string())).collect(),
+ Filter::Pinned => ["true", "false"].iter().filter(|v| v.starts_with(&q)).map(|v| Row::Value(v.to_string())).collect(),
+ Filter::AuthorType => AUTHOR_TYPES.iter().filter(|v| v.starts_with(&q)).map(|v| Row::Value(v.to_string())).collect(),
+ Filter::Before | Filter::During | Filter::After => {
+ // Today and yesterday, written the way a date is typed.
+ let today = chrono::Local::now().date_naive();
+ let days = [Some(today), today.pred_opt()];
+ let dates = days.into_iter().flatten().map(|d| d.format("%Y-%m-%d").to_string());
+ dates.filter(|d| d.starts_with(&q)).map(Row::Value).collect()
+ }
+ }
+ }
+
+ /// Arrow keys, Enter and Tab for the list, taken before the search box
+ /// sees them. The row picked with Enter or Tab, if any.
+ pub(super) fn search_keys(&mut self, ctx: &egui::Context, box_id: egui::Id) -> Option<usize> {
+ let s = &mut self.search_suggest;
+ if !s.open || s.len == 0 || !ctx.memory(|m| m.has_focus(box_id)) {
+ return None;
+ }
+ let (down, up, enter, tab) = ctx.input_mut(|i| {
+ (
+ i.consume_key(Modifiers::NONE, Key::ArrowDown),
+ i.consume_key(Modifiers::NONE, Key::ArrowUp),
+ s.highlight.is_some() && i.consume_key(Modifiers::NONE, Key::Enter),
+ i.consume_key(Modifiers::NONE, Key::Tab),
+ )
+ });
+ if down {
+ s.highlight = Some(s.highlight.map_or(0, |h| (h + 1) % s.len));
+ }
+ if up {
+ s.highlight = Some(s.highlight.map_or(s.len - 1, |h| (h + s.len - 1) % s.len));
+ }
+ if enter {
+ return s.highlight;
+ }
+ tab.then(|| s.highlight.unwrap_or(0))
+ }
+
+ /// The list under the search box (`bar`), while the box is in use.
+ /// `picked`: a row chosen with the keyboard this frame.
+ pub(super) fn search_suggest_ui(&mut self, ctx: &egui::Context, bar: Rect, ch: Id, box_id: egui::Id, picked: Option<usize>) {
+ let focused = ctx.memory(|m| m.has_focus(box_id));
+ let s = &mut self.search_suggest;
+ if focused {
+ s.open = true;
+ } else if s.open {
+ // A press on the list takes the focus from the box: stay open for it.
+ let pressed_off = ctx.input(|i| i.pointer.any_pressed() && i.pointer.press_origin().is_some_and(|p| !s.rect.is_some_and(|r| r.contains(p))));
+ let escape = ctx.input(|i| i.key_pressed(Key::Escape));
+ if pressed_off || escape || !ctx.input(|i| i.pointer.any_down() || i.pointer.any_released()) {
+ s.open = false;
+ }
+ }
+ if !s.open {
+ *s = SearchSuggest { asked: s.asked.take(), ..Default::default() };
+ return;
+ }
+ let text = self.search_input.clone();
+ // Members not met yet: ask Discord for those matching the name.
+ if let (_, Some(Filter::From | Filter::Mentions), value) = current(&text) {
+ let value = value.trim_start_matches('@').to_string();
+ if let Some(g) = self.store.channels.get(&ch).and_then(|c| c.guild_id).filter(|_| !value.is_empty()) {
+ if self.search_suggest.asked.as_ref() != Some(&(g, value.clone())) {
+ self.backend.send(crate::backend::Command::SearchMembers { guild: g, query: value.clone() });
+ self.search_suggest.asked = Some((g, value));
+ }
+ }
+ }
+ let rows = self.search_rows(ch, &text);
+ self.search_suggest.len = rows.len();
+ if self.search_suggest.highlight.is_some_and(|h| h >= rows.len()) {
+ self.search_suggest.highlight = None;
+ }
+ // Naming someone, a channel or a value: the first match is chosen,
+ // so Enter takes it (as on Discord). The filter list waits for the arrows.
+ if self.search_suggest.highlight.is_none() && current(&text).1.is_some() && !rows.is_empty() {
+ self.search_suggest.highlight = Some(0);
+ }
+ if rows.is_empty() {
+ self.search_suggest.rect = None;
+ return;
+ }
+ let t = self.theme.clone();
+ let highlight = self.search_suggest.highlight;
+ let mut clicked = None;
+ let mut hovered = None;
+ let pos = pos2(bar.right() - 4.0 - LIST_W, bar.bottom() + 8.0);
+ let area = egui::Area::new(egui::Id::new("search_suggest")).order(Order::Foreground).fixed_pos(pos).constrain(true).show(ctx, |ui| {
+ egui::Frame::none()
+ .fill(t.bg_floating)
+ .stroke(Stroke::new(1.0_f32, t.border_subtle))
+ .rounding(8.0)
+ .shadow(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) })
+ .inner_margin(egui::Margin::symmetric(8.0, 12.0))
+ .show(ui, |ui| {
+ ui.set_width(LIST_W - 18.0);
+ ui.spacing_mut().item_spacing.y = 4.0;
+ if rows.iter().any(|r| matches!(r, Row::Filter { .. })) {
+ // "Filters": 12 px semibold, 8 px in, 10 px above the rows.
+ let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 23.0), Sense::hover());
+ let font = FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into()));
+ ui.painter().text(pos2(r.left() + 8.0, r.top() + 15.0), Align2::LEFT_CENTER, "Filters", font, t.text_muted);
+ ui.add_space(2.0);
+ }
+ for (i, row) in rows.iter().enumerate() {
+ let h = if matches!(row, Row::Filter { .. }) { FILTER_ROW_H } else { VALUE_ROW_H };
+ let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());
+ let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
+ if resp.hovered() {
+ hovered = Some(i);
+ }
+ if resp.hovered() || highlight == Some(i) {
+ ui.painter().rect_filled(r, 8.0, t.bg_hover);
+ }
+ if resp.clicked() {
+ clicked = Some(i);
+ }
+ paint_row(ui, &t, r, row);
+ }
+ });
+ });
+ self.search_suggest.rect = Some(area.response.rect);
+ if hovered.is_some() && ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO) {
+ self.search_suggest.highlight = hovered;
+ }
+ let Some(row) = clicked.or(picked).and_then(|i| rows.get(i)) else { return };
+ let (before, filter, _) = current(&text);
+ let key = filter.map_or("", |f| f.key());
+ let new_text = match row {
+ Row::Filter { filter: None, .. } => {
+ self.search_suggest.more = true;
+ text.clone()
+ }
+ Row::Filter { key, .. } => format!("{before}{key}"),
+ Row::User(u, _) => format!("{before}{key}{} ", u.username),
+ Row::Channel(name) => format!("{before}{key}{name} "),
+ Row::Value(v) => format!("{before}{key}{v} "),
+ };
+ self.search_suggest.highlight = None;
+ self.search_input = new_text;
+ // Back to the box, typing at the end.
+ ctx.memory_mut(|m| m.request_focus(box_id));
+ if let Some(mut state) = egui::text_edit::TextEditState::load(ctx, box_id) {
+ let end = egui::text::CCursor::new(self.search_input.chars().count());
+ state.cursor.set_char_range(Some(egui::text::CCursorRange::one(end)));
+ state.store(ctx, box_id);
+ }
+ }
+}
+
+/// A row's contents: a filter (icon, title, `key` hint), a person (avatar,
+/// name, username), a channel or a value.
+fn paint_row(ui: &egui::Ui, t: &crate::style::Theme, r: Rect, row: &Row) {
+ let p = ui.painter_at(r);
+ let semibold = FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
+ let medium = crate::style::medium(14.0);
+ match row {
+ Row::Filter { icon, title, key, hint, .. } => {
+ let icon_r = Rect::from_center_size(pos2(r.left() + 18.0, r.center().y), vec2(20.0, 20.0));
+ match *icon {
+ Some("#") => {
+ p.text(icon_r.center(), Align2::CENTER_CENTER, crate::style::icon::HASH, crate::style::icon_font(20.0), t.text_muted);
+ }
+ Some(name) => {
+ if let Some(src) = super::settings_icons::icon(name, t.text_muted) {
+ egui::Image::new(src).paint_at(ui, icon_r);
+ }
+ }
+ None => {}
+ }
+ p.text(pos2(r.left() + 36.0, r.top() + 13.0), Align2::LEFT_CENTER, *title, medium.clone(), t.text_normal);
+ let mut x = r.left() + 36.0;
+ if !key.is_empty() {
+ let g = p.layout_no_wrap(key.to_string(), semibold, t.text_muted);
+ let w = g.size().x;
+ p.galley(pos2(x, r.top() + 31.0 - g.size().y / 2.0), g, t.text_muted);
+ x += w + 4.0;
+ }
+ p.text(pos2(x, r.top() + 31.0), Align2::LEFT_CENTER, *hint, medium, t.channel_default);
+ }
+ Row::User(u, nick) => {
+ let av = Rect::from_center_size(pos2(r.left() + 20.0, r.center().y), vec2(24.0, 24.0));
+ let name = nick.clone().unwrap_or_else(|| u.display_name().to_string());
+ super::paint_avatar(ui, av, Some(super::avatar_uri(u, 32, false)), &name);
+ let g = p.layout_no_wrap(name, medium.clone(), t.text_normal);
+ let w = g.size().x;
+ p.galley(pos2(r.left() + 40.0, r.center().y - g.size().y / 2.0), g, t.text_normal);
+ p.text(pos2(r.left() + 40.0 + w + 6.0, r.center().y), Align2::LEFT_CENTER, &u.username, medium, t.text_muted);
+ }
+ Row::Channel(name) => {
+ let icon_r = Rect::from_center_size(pos2(r.left() + 18.0, r.center().y), vec2(20.0, 20.0));
+ p.text(icon_r.center(), Align2::CENTER_CENTER, crate::style::icon::HASH, crate::style::icon_font(18.0), t.text_muted);
+ p.text(pos2(r.left() + 36.0, r.center().y), Align2::LEFT_CENTER, name, medium, t.text_normal);
+ }
+ Row::Value(v) => {
+ p.text(pos2(r.left() + 12.0, r.center().y), Align2::LEFT_CENTER, v, medium, t.text_normal);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn filters_are_read_among_the_words() {
+ let w = words("hello from: vr has:IMAGE world in:#general pinned:");
+ assert_eq!(
+ w,
+ vec![
+ (None, "hello".into()),
+ (Some(Filter::From), "vr".into()),
+ (Some(Filter::Has), "IMAGE".into()),
+ (None, "world".into()),
+ (Some(Filter::In), "#general".into()),
+ (Some(Filter::Pinned), "".into()),
+ ]
+ );
+ // A key straight after a key is a key, not the first one's value.
+ assert_eq!(words("from: has:link"), vec![(Some(Filter::From), "".into()), (Some(Filter::Has), "link".into())]);
+ assert_eq!(Filter::split("AUTHORTYPE:bot"), Some((Filter::AuthorType, "bot")));
+ }
+
+ #[test]
+ fn the_part_being_typed_is_found() {
+ assert_eq!(current(""), ("", None, ""));
+ assert_eq!(current("hello "), ("hello ", None, ""));
+ assert_eq!(current("hello fr"), ("hello ", None, "fr"));
+ assert_eq!(current("hello from:"), ("hello ", Some(Filter::From), ""));
+ assert_eq!(current("hello from: "), ("hello ", Some(Filter::From), ""));
+ assert_eq!(current("hello from:v"), ("hello ", Some(Filter::From), "v"));
+ assert_eq!(current("hello from: vr"), ("hello ", Some(Filter::From), "vr"));
+ assert_eq!(current("from:vr "), ("from:vr ", None, ""));
+ }
+
+ #[test]
+ fn a_day_starts_at_local_midnight() {
+ let day = chrono::NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
+ let id = day_start(day).unwrap();
+ let ms = (id.0 >> 22) + DISCORD_EPOCH;
+ let back = chrono::DateTime::from_timestamp_millis(ms as i64).unwrap().with_timezone(&chrono::Local);
+ assert_eq!(back.date_naive(), day);
+ assert_eq!(back.format("%H:%M:%S").to_string(), "00:00:00");
+ assert_eq!(id.0 & ((1 << 22) - 1), 0);
+ }
+}
diff --git a/apps/rustcord/src/ui/settings_icons.rs b/apps/rustcord/src/ui/settings_icons.rs
index 600f059..09bba9c 100644
--- a/apps/rustcord/src/ui/settings_icons.rs
+++ b/apps/rustcord/src/ui/settings_icons.rs
@@ -83,6 +83,11 @@ const ICONS: &[(&str, &[(bool, &str)])] = &[
(false, "M15.3 16.7a1 1 0 0 1 1.4-1.4l4.3 4.29V16a1 1 0 1 1 2 0v6a1 1 0 0 1-1 1h-6a1 1 0 1 1 0-2h3.59l-4.3-4.3Z"),
],
),
+ // The search box's filter list (Discord's AtIcon, PaperclipIcon and
+ // SlidersIcon; "account" is its user icon).
+ ("search-at", &[(false, "M16.44 6.96c.29 0 .51.25.47.54l-.82 6.34c-.02.08-.03.2-.03.34 0 .71.28 1.07.85 1.07.49 0 .94-.21 1.36-.63.43-.42.77-1 1.02-1.72.26-.75.38-1.57.38-2.48 0-1.35-.29-2.54-.87-3.56a5.92 5.92 0 0 0-2.45-2.35 7.68 7.68 0 0 0-3.61-.83c-1.55 0-2.96.37-4.22 1.1a7.66 7.66 0 0 0-2.96 3.07 9.53 9.53 0 0 0-1.09 4.66c0 1.45.26 2.77.78 3.95a6.3 6.3 0 0 0 2.47 2.81 8.3 8.3 0 0 0 4.36 1.05 12.43 12.43 0 0 0 5.35-1.18.5.5 0 0 1 .7.24l.46 1.07c.1.22.02.47-.19.59-.77.43-1.69.77-2.75 1.02-1.23.3-2.48.44-3.76.44-2.18 0-4-.44-5.48-1.33a8.1 8.1 0 0 1-3.27-3.57 11.93 11.93 0 0 1-1.07-5.12c0-2.24.47-4.19 1.4-5.84a9.7 9.7 0 0 1 3.86-3.8c1.62-.9 3.4-1.34 5.36-1.34 1.8 0 3.4.37 4.8 1.12 1.4.72 2.5 1.76 3.28 3.1a8.86 8.86 0 0 1 1.16 4.56c0 1.36-.23 2.57-.7 3.64a5.81 5.81 0 0 1-1.92 2.47c-.82.58-1.76.87-2.81.87a2.4 2.4 0 0 1-1.6-.5c-.4-.35-.65-.78-.73-1.32-.3.55-.74 1-1.36 1.34a4.3 4.3 0 0 1-2.03.48A3.4 3.4 0 0 1 8 16C7.33 15.16 7 14 7 12.5c0-1.14.2-2.16.6-3.05.43-.89 1-1.57 1.73-2.06a4.3 4.3 0 0 1 4.27-.31c.47.29.82.68 1.07 1.16l.3-.95c.06-.2.25-.33.46-.33h1.02Zm-5.06 8.24c.8 0 1.45-.35 1.97-1.04.51-.7.77-1.6.77-2.7 0-.88-.18-1.56-.53-2.03a1.76 1.76 0 0 0-1.5-.73c-.8 0-1.45.35-1.97 1.04a4.28 4.28 0 0 0-.78 2.67c0 .9.17 1.58.51 2.06.36.49.87.73 1.53.73Z")]),
+ ("search-has", &[(false, "M10.57 4.01a6.97 6.97 0 0 1 9.86 0l.54.55a6.99 6.99 0 0 1 0 9.88l-7.26 7.27a1 1 0 0 1-1.42-1.42l7.27-7.26a4.99 4.99 0 0 0 0-7.06L19 5.43a4.97 4.97 0 0 0-7.02 0l-8.02 8.02a3.24 3.24 0 1 0 4.58 4.58l6.24-6.24a1.12 1.12 0 0 0-1.58-1.58l-3.5 3.5a1 1 0 0 1-1.42-1.42l3.5-3.5a3.12 3.12 0 1 1 4.42 4.42l-6.24 6.24a5.24 5.24 0 0 1-7.42-7.42l8.02-8.02Z")]),
+ ("search-more", &[(false, "M22 5a1 1 0 0 1-1 1h-8.2a2.5 2.5 0 1 1 0-2H21a1 1 0 0 1 1 1ZM6 5c0 .34.04.67.11 1H3a1 1 0 0 1 0-2h3.11A4.5 4.5 0 0 0 6 5ZM22 19a1 1 0 0 1-1 1h-8.2a2.5 2.5 0 1 1 0-2H21a1 1 0 0 1 1 1ZM6 19c0 .34.04.67.11 1H3a1 1 0 1 1 0-2h3.11A4.5 4.5 0 0 0 6 19ZM21 13a1 1 0 1 0 0-2h-3.2a2.5 2.5 0 1 0 0 2H21ZM11.11 13a4.5 4.5 0 0 1 0-2H3a1 1 0 1 0 0 2h8.11Z")]),
];
/// The icon `name` in `color`, for an `egui::Image`.
diff --git a/crates/discord/src/http.rs b/crates/discord/src/http.rs
index b729b32..ec2d819 100644
--- a/crates/discord/src/http.rs
+++ b/crates/discord/src/http.rs
@@ -54,6 +54,49 @@ pub struct Http {
}
/// Percent-encode a query-string value.
+/// A message search, as Discord web's search box sends it: the words, then
+/// what its filters (`from:`, `has:`, `before:`, ...) turned into.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct SearchQuery {
+ pub content: String,
+ /// `from:`
+ pub author_id: Vec<Id>,
+ /// `mentions:`
+ pub mentions: Vec<Id>,
+ /// `has:`, by the API's names (`forward` is `snapshot`).
+ pub has: Vec<String>,
+ /// `in:`
+ pub channel_id: Vec<Id>,
+ /// `before:` / `during:` / `after:`, as message IDs at local midnights.
+ pub max_id: Option<Id>,
+ pub min_id: Option<Id>,
+ /// `pinned:`
+ pub pinned: Option<bool>,
+ /// `authorType:` (user, bot, webhook)
+ pub author_type: Vec<String>,
+}
+
+impl SearchQuery {
+ /// The URL query, in the order Discord web writes it (read from its
+ /// requests, 2026-12-04), newest results first.
+ pub fn to_query_string(&self) -> String {
+ let mut out: Vec<String> = Vec::new();
+ if !self.content.is_empty() {
+ out.push(format!("content={}", url_encode(&self.content)));
+ }
+ out.extend(self.author_id.iter().map(|id| format!("author_id={id}")));
+ out.extend(self.mentions.iter().map(|id| format!("mentions={id}")));
+ out.extend(self.has.iter().map(|h| format!("has={}", url_encode(h))));
+ out.extend(self.channel_id.iter().map(|id| format!("channel_id={id}")));
+ out.extend(self.max_id.map(|id| format!("max_id={id}")));
+ out.extend(self.min_id.map(|id| format!("min_id={id}")));
+ out.extend(self.pinned.map(|p| format!("pinned={p}")));
+ out.extend(self.author_type.iter().map(|t| format!("author_type={}", url_encode(t))));
+ out.push("sort_by=timestamp&sort_order=desc&offset=0".into());
+ out.join("&")
+ }
+}
+
pub(crate) fn url_encode(s: &str) -> String {
s.bytes()
.map(|b| match b {
@@ -881,11 +924,11 @@ impl Http {
}
/// Message search in a server (or a DM channel). Returns (total, hits).
- pub async fn search(&self, guild: Option<Id>, channel: Id, query: &str) -> Result<(u64, Vec<Message>)> {
- let q = url_encode(query);
+ pub async fn search(&self, guild: Option<Id>, channel: Id, query: &SearchQuery) -> Result<(u64, Vec<Message>)> {
+ let q = query.to_query_string();
let path = match guild {
- Some(g) => format!("/guilds/{g}/messages/search?content={q}"),
- None => format!("/channels/{channel}/messages/search?content={q}"),
+ Some(g) => format!("/guilds/{g}/messages/search?{q}"),
+ None => format!("/channels/{channel}/messages/search?{q}"),
};
let v = self.request(Method::GET, &path, None).await?;
if v.get("messages").is_none() {
@@ -1054,6 +1097,26 @@ impl Http {
mod tests {
use super::*;
+ /// The request Discord web made for `hello has:forward has:sound
+ /// before:2026-12-01 after:2026-11-01 during:2026-11-15 pinned:false
+ /// authorType:bot` (2026-12-04).
+ #[test]
+ fn a_search_asks_like_discord_web() {
+ let q = SearchQuery {
+ content: "hello".into(),
+ has: vec!["snapshot".into(), "sound".into()],
+ max_id: Some(Id(1571676173107200000)),
+ min_id: Some(Id(1571313785241600000)),
+ pinned: Some(false),
+ author_type: vec!["bot".into()],
+ ..Default::default()
+ };
+ assert_eq!(
+ q.to_query_string(),
+ "content=hello&has=snapshot&has=sound&max_id=1571676173107200000&min_id=1571313785241600000&pinned=false&author_type=bot&sort_by=timestamp&sort_order=desc&offset=0"
+ );
+ }
+
/// A file from disk goes out whole, with the length given up front
/// (storage upload links want Content-Length, not chunks).
#[test]