Skip to content

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

30.6 KB
Raw Blame
//! "@" and "#" in the message box: Discord's member / role list and its
//! channel list above the composer (arrows move, Enter / Tab / a click
//! pick), which put "@username " or "#channel " in the box. On send those
//! names become real mentions (`<@id>`, `<@&id>`, `<#id>`), as do ones typed
//! out by hand.
//!
//! ":" works the same way for emoji: from two letters on, Discord's "Emoji
//! matching :sm" list, which puts the emoji itself in the box.

use super::paint_avatar;
use crate::app::RustCord;
use crate::features::MentionQuery;
use crate::store::ListItem;
use discord::model::{channel_kind, Id, User};
use eframe::egui::{self, pos2, vec2, Align2, Color32, FontId, Key, Order, Rect, Sense, Stroke};
use std::collections::HashSet;

const MENTION_EVERYONE: u64 = 1 << 17;
/// Discord lists at most this many members, then the roles.
const MAX_MEMBERS: usize = 10;
const MAX_ROLES: usize = 5;
/// Likewise the "#" list (text channels and threads).
const MAX_TEXT: usize = 10;
const MAX_EMOJI: usize = 10;
// Discord web's autocomplete, measured 2026-11-17: the box is 8 px in from
// the composer's left edge and 16 px from its right, 8 px above it, with 5 px
// corners and 8 px of padding at the bottom. A title block is 42.7 px (14 px
// medium text, sentence case); a member row 40 px (24 px avatar), any other
// row 36 px, an emoji row 31 px (20 px picture); groups are split by a 17 px
// gap with a line through it. Names are 16 px regular, the text on the right
// 12 px.
const ROW_MEMBER: f32 = 40.0;
const ROW: f32 = 36.0;
const ROW_EMOJI: f32 = 31.0;
const TITLE: f32 = 42.7;
const DIVIDER: f32 = 17.0;
const PAD_BOTTOM: f32 = 8.0;

/// The "@word" or "#word" ending at the caret (a character index), if the
/// caret is in one: the sigil, its index and the word. The sigil has to
/// start a word, so an e-mail address isn't one.
pub fn query_at(text: &str, caret: usize) -> Option<(char, usize, String)> {
    let chars: Vec<char> = text.chars().take(caret).collect();
    if chars.len() < caret {
        return None;
    }
    let at = chars.iter().rposition(|c| c.is_whitespace()).map_or(0, |i| i + 1);
    let sigil = *chars.get(at).filter(|c| matches!(c, '@' | '#' | ':'))?;
    if caret - at > 33 {
        return None;
    }
    let query: String = chars[at + 1..].iter().collect();
    // An emoji name: two letters at least, and nothing a smiley has (":-)").
    if sigil == ':' && (query.chars().count() < 2 || !query.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '+')) {
        return None;
    }
    Some((sigil, at, query))
}

/// Are `needle`'s characters all in `hay`, in that order?
fn in_order(hay: &str, needle: &str) -> bool {
    let mut rest = hay.chars();
    needle.chars().all(|n| rest.any(|h| h == n))
}

/// What a user is typed as in the box: the username (with the old #tag where
/// an account still has one, as bots do).
fn user_tag(u: &User) -> String {
    match u.discriminator.as_deref().filter(|d| !d.is_empty() && d.chars().any(|c| c != '0')) {
        Some(d) => format!("{}#{d}", u.username),
        None => u.username.clone(),
    }
}

enum Entry {
    User { user: User, nick: Option<String> },
    Role { name: String, color: u32 },
    Everyone,
    Here,
    Channel { name: String, kind: u8, category: Option<String> },
    /// `text` is what goes in the box: the emoji, or `<:name:id>`.
    Emoji { name: String, url: String, text: String, unicode: bool, from: Option<String> },
}

impl Entry {
    /// The text that goes into the message box.
    fn insert(&self) -> String {
        match self {
            Entry::User { user, .. } => format!("@{} ", user_tag(user)),
            Entry::Role { name, .. } => format!("@{name} "),
            Entry::Everyone => "@everyone ".into(),
            Entry::Here => "@here ".into(),
            Entry::Channel { name, .. } => format!("#{name} "),
            Entry::Emoji { text, .. } => format!("{text} "),
        }
    }
}

/// `text` with each "@name" (or "#name": `sigil`) from `names` (name →
/// mention) made a real mention. The longest name wins ("@Mod Team" over "@Mod"), it has to be a
/// whole word, and code spans are left alone.
fn replace_names(text: &str, sigil: char, names: &[(String, String)]) -> String {
    let mut out = String::with_capacity(text.len());
    let mut code = false;
    let mut prev: Option<char> = None;
    let mut rest = text;
    while let Some(c) = rest.chars().next() {
        if c == '`' {
            code = !code;
        }
        if c == sigil && !code && prev.map_or(true, char::is_whitespace) {
            let after = &rest[1..];
            let hit = names
                .iter()
                .filter(|(name, _)| {
                    !name.is_empty()
                        && after.get(..name.len()).is_some_and(|s| s.eq_ignore_ascii_case(name))
                        && !after[name.len()..].chars().next().is_some_and(|n| n.is_alphanumeric() || n == '_' || (sigil == '#' && n == '-'))
                })
                .max_by_key(|(name, _)| name.len());
            if let Some((name, mention)) = hit {
                out.push_str(mention);
                prev = name.chars().last();
                rest = &after[name.len()..];
                continue;
            }
        }
        out.push(c);
        prev = Some(c);
        rest = &rest[c.len_utf8()..];
    }
    out
}

impl RustCord {
    /// Everyone RustCord knows who can be mentioned in a channel, most recent
    /// speakers first: (user, server nickname).
    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();
        let Some(guild) = channel.guild_id else {
            for u in channel.recipients.iter().chain(self.store.me.as_ref()) {
                if seen.insert(u.id) {
                    out.push((u.clone(), None));
                }
            }
            return out;
        };
        let nick = |id: Id| self.store.members.get(&(guild, id)).and_then(|m| m.nick.clone());
        if let Some(cm) = self.store.messages.get(&ch) {
            // (Webhooks post under made-up users: nobody to mention.)
            for m in cm.list.iter().rev().filter(|m| m.webhook_id.is_none()) {
                if seen.insert(m.author.id) {
                    let n = nick(m.author.id).or_else(|| m.member.as_ref().and_then(|p| p.nick.clone()));
                    out.push((m.author.clone(), n));
                }
            }
        }
        if let Some(list) = self.store.list_id_for(ch).and_then(|key| self.store.member_lists.get(&key)) {
            for item in list.items.iter().flatten() {
                if let ListItem::Member { user, nick, .. } = item {
                    if seen.insert(user.id) {
                        out.push((user.clone(), nick.clone()));
                    }
                }
            }
        }
        for ((g, uid), info) in &self.store.members {
            if *g == guild && !seen.contains(uid) {
                if let Some(u) = self.store.users.get(uid) {
                    seen.insert(*uid);
                    out.push((u.clone(), info.nick.clone()));
                }
            }
        }
        out
    }

    /// The server's channels "#" can name: the text-like ones you can see (in
    /// sidebar order), then its threads. Discord's list has no voice channels.
    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
            .channels
            .values()
            .filter(|c| c.guild_id == Some(guild) && c.kind != channel_kind::GUILD_CATEGORY && !channel_kind::is_voice(c.kind))
            .filter(|c| c.name.as_deref().is_some_and(|n| !n.is_empty()))
            .filter(|c| match (channel_kind::is_thread(c.kind), c.parent_id.and_then(|p| self.store.channels.get(&p))) {
                // A thread is seen by whoever sees its channel.
                (true, Some(parent)) => self.store.can_view(parent),
                (true, None) => false,
                (false, _) => self.store.can_view(c),
            })
            .collect();
        let cat_pos = |c: &discord::model::Channel| c.parent_id.and_then(|p| self.store.channels.get(&p)).map_or(-1, |p| p.position);
        out.sort_by_key(|c| (channel_kind::is_thread(c.kind), cat_pos(c), c.position, c.id));
        out
    }

    /// The list for "#query": names starting with it, then containing it,
    /// then merely having its letters in order ("#te" finds "thesis"), as
    /// Discord's does.
    fn channel_entries(&self, ch: Id, query: &str) -> Vec<Entry> {
        let q = query.to_lowercase();
        let mut hits: Vec<(u8, &discord::model::Channel)> = self
            .channel_pool(ch)
            .into_iter()
            .filter_map(|c| {
                let name = c.name.as_deref()?.to_lowercase();
                let rank = if name.starts_with(&q) {
                    0
                } else if name.contains(&q) {
                    1
                } else if in_order(&name, &q) {
                    2
                } else {
                    return None;
                };
                Some((rank, c))
            })
            .collect();
        // (A stable sort: sidebar order survives within a rank.)
        hits.sort_by_key(|(rank, _)| *rank);
        hits.into_iter()
            .take(MAX_TEXT)
            .map(|(_, c)| Entry::Channel {
                name: c.name.clone().unwrap_or_default(),
                kind: c.kind,
                // (A thread's channel, or a channel's category.)
                category: c.parent_id.and_then(|p| self.store.channels.get(&p)).and_then(|p| p.name.clone()),
            })
            .collect()
    }

    /// The list for ":query": emoji whose name matches, the exact name first,
    /// then names starting with it; this server's own before the standard
    /// ones, other servers' last. Emoji you can't use here (Nitro-locked,
    /// or other servers' where the channel forbids them) aren't offered.
    fn emoji_entries(&self, ch: Id, query: &str) -> Vec<Entry> {
        let rules = self.emoji_rules(Some(ch));
        let q = query.to_lowercase();
        let rank = |name: &str| -> Option<u8> {
            if name == q {
                Some(0)
            } else if name.starts_with(&q) {
                Some(1)
            } else if name.contains(&q) {
                Some(2)
            } else {
                None
            }
        };
        let here = rules.here;
        let mut hits: Vec<((u8, u8), Entry)> = Vec::new();
        for gid in here.iter().chain(self.store.guild_order.iter().filter(|g| Some(**g) != here)) {
            let Some(g) = self.store.guilds.get(gid) else { continue };
            let usable = |e: &&discord::model::GuildEmoji| rules.access(*gid, e.animated, e.managed) == crate::features::EmojiAccess::Usable;
            for e in g.guild.emojis.iter().filter(|e| e.available != Some(false)).filter(usable) {
                let (Some(id), Some(name)) = (e.id, e.name.as_ref()) else { continue };
                let Some(r) = rank(&name.to_lowercase()) else { continue };
                let text = format!("<{}:{name}:{id}>", if e.animated { "a" } else { "" });
                let entry = Entry::Emoji { name: name.clone(), url: discord::model::emoji_url(id, false, 48), text, unicode: false, from: Some(g.guild.name.clone()) };
                hits.push(((r, if Some(*gid) == here { 0 } else { 2 }), entry));
            }
        }
        for (emoji, name) in crate::emoji_data::CATEGORIES.iter().flat_map(|(_, items)| items.iter()) {
            if let Some(r) = crate::emoji::search_rank(emoji, name, &q) {
                let emoji = crate::emoji::in_chosen_tone(emoji);
                let entry = Entry::Emoji { name: name.to_string(), url: crate::emoji::twemoji_url(&emoji), text: emoji.to_string(), unicode: true, from: None };
                hits.push(((r, 1), entry));
            }
        }
        // (A stable sort: the picker's order survives within a rank.)
        hits.sort_by_key(|(k, _)| *k);
        hits.into_iter().take(MAX_EMOJI).map(|(_, e)| e).collect()
    }

    /// The list for "@query": matching members (names starting with it
    /// first), then @everyone / @here and the roles you may mention.
    fn mention_entries(&self, ch: Id, sigil: char, query: &str) -> Vec<Entry> {
        if sigil == '#' {
            return self.channel_entries(ch, query);
        }
        if sigil == ':' {
            return self.emoji_entries(ch, query);
        }
        let Some(channel) = self.store.channels.get(&ch) else { return Vec::new() };
        let q = query.to_lowercase();
        let rank = |names: &[&str]| -> Option<u8> {
            let lower: Vec<String> = names.iter().map(|n| n.to_lowercase()).collect();
            if lower.iter().any(|n| n.starts_with(&q)) {
                Some(0)
            } else if lower.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)| {
                let r = rank(&[u.username.as_str(), u.global_name.as_deref().unwrap_or(""), nick.as_deref().unwrap_or("")])?;
                Some((r, u, nick))
            })
            .collect();
        users.sort_by_key(|(r, _, _)| *r);
        let mut out: Vec<Entry> = users.into_iter().take(MAX_MEMBERS).map(|(_, user, nick)| Entry::User { user, nick }).collect();

        let everyone = match channel.guild_id {
            Some(_) => self.store.channel_perms(channel).map_or(true, |p| p & MENTION_EVERYONE != 0),
            None => channel.kind == channel_kind::GROUP_DM,
        };
        if everyone {
            if "everyone".starts_with(&q) {
                out.push(Entry::Everyone);
            }
            if "here".starts_with(&q) {
                out.push(Entry::Here);
            }
        }
        if let Some(g) = channel.guild_id.and_then(|g| self.store.guilds.get(&g)) {
            let mut roles: Vec<(u8, &discord::model::Role)> = g
                .guild
                .roles
                .iter()
                .filter(|r| r.id != g.guild.id && (r.mentionable || everyone))
                .filter_map(|r| Some((rank(&[r.name.as_str()])?, r)))
                .collect();
            roles.sort_by_key(|(rank, r)| (*rank, -r.position));
            out.extend(roles.into_iter().take(MAX_ROLES).map(|(_, r)| Entry::Role { name: r.name.clone(), color: r.color }));
        }
        out
    }

    /// The text about to be sent, with its "@username", "@Role" and
    /// "#channel" turned into mentions Discord delivers (`<@id>`, `<@&id>`,
    /// `<#id>`).
    pub fn resolve_mentions(&self, text: &str, ch: Id) -> String {
        let text = if text.contains('#') {
            let names: Vec<(String, String)> =
                self.channel_pool(ch).iter().map(|c| (c.name.clone().unwrap_or_default(), format!("<#{}>", c.id))).collect();
            replace_names(text, '#', &names)
        } else {
            text.to_string()
        };
        let text = text.as_str();
        if !text.contains('@') {
            return text.to_string();
        }
        let mut names: Vec<(String, String)> = self.mention_pool(ch).iter().map(|(u, _)| (user_tag(u), format!("<@{}>", u.id))).collect();
        let guild = self.store.channels.get(&ch).and_then(|c| c.guild_id).and_then(|g| self.store.guilds.get(&g));
        if let Some(g) = guild {
            names.extend(g.guild.roles.iter().filter(|r| r.id != g.guild.id).map(|r| (r.name.clone(), format!("<@&{}>", r.id))));
        }
        // (These two already are what Discord wants; listed so "@everyone"
        // never matches a role or user called "every".)
        names.push(("everyone".into(), "@everyone".into()));
        names.push(("here".into(), "@here".into()));
        replace_names(text, '@', &names)
    }

    /// Arrows / Enter / Tab / Escape for the list, taken before the message
    /// box sees them. True while the list has them.
    pub(super) fn mention_keys(&mut self, ui: &egui::Ui, ch: Id) -> bool {
        let Some(m) = self.compose.mention.as_ref().filter(|m| m.channel == ch) else { return false };
        if self.compose.mention_rows == 0 {
            return false;
        }
        let start = m.start;
        ui.input_mut(|i| {
            if i.consume_key(egui::Modifiers::NONE, Key::ArrowDown) {
                self.compose.mention_nav += 1;
            }
            if i.consume_key(egui::Modifiers::NONE, Key::ArrowUp) {
                self.compose.mention_nav -= 1;
            }
            if i.consume_key(egui::Modifiers::NONE, Key::Tab) || i.consume_key(egui::Modifiers::NONE, Key::Enter) {
                self.compose.mention_pick = true;
            }
            if i.consume_key(egui::Modifiers::NONE, Key::Escape) {
                self.compose.mention_dismissed = Some((ch, start));
            }
        });
        true
    }

    /// Note the "@word" / "#word" at the message box's caret (once it has drawn).
    pub(super) fn track_mention(&mut self, ctx: &egui::Context, ch: Id, id: egui::Id, draft: &str) {
        let caret = egui::TextEdit::load_state(ctx, id)
            .and_then(|s| s.cursor.char_range())
            .filter(|r| r.primary.index == r.secondary.index)
            .map(|r| r.primary.index);
        let now = caret.and_then(|c| query_at(draft, c).map(|(sigil, start, query)| MentionQuery { channel: ch, sigil, start, end: c, query }));
        // A different word: the highlight goes back to the first match.
        if now != self.compose.mention {
            self.compose.mention_sel = 0;
        }
        self.compose.mention = now;
    }

    pub(super) fn mention_list_ui(&mut self, ctx: &egui::Context) {
        let query = match (self.compose.composer_rect, self.compose.mention.clone()) {
            (Some((ch, rect)), Some(m)) if m.channel == ch && Some(ch) == self.current_channel && self.compose.command.is_none() => Some((rect, m)),
            _ => None,
        };
        let Some((composer, m)) = query else {
            self.compose.mention_dismissed = None;
            self.compose.mention_rows = 0;
            self.compose.mention_pick = false;
            return;
        };
        let ch = m.channel;
        if self.compose.mention_dismissed == Some((ch, m.start)) {
            self.compose.mention_rows = 0;
            self.compose.mention_pick = false;
            return;
        }
        self.compose.mention_dismissed = None;
        let guild = self.store.channels.get(&ch).and_then(|c| c.guild_id);
        // Members RustCord hasn't met yet: ask Discord for ones matching the text
        // (they arrive as a member chunk and show up on a later frame).
        if let Some(g) = guild.filter(|_| m.sigil == '@' && !m.query.is_empty()) {
            let key = (g, m.query.clone());
            if self.compose.mention_searched.as_ref() != Some(&key) {
                self.backend.send(crate::backend::Command::SearchMembers { guild: g, query: m.query.clone() });
                self.compose.mention_searched = Some(key);
            }
        }
        let entries = self.mention_entries(ch, m.sigil, &m.query);
        self.compose.mention_rows = entries.len();
        if entries.is_empty() {
            self.compose.mention_pick = false;
            return;
        }
        let t = self.theme.clone();
        let n = entries.len() as i64;
        let sel = (self.compose.mention_sel as i64 + self.compose.mention_nav as i64).rem_euclid(n) as usize;
        self.compose.mention_sel = sel;
        self.compose.mention_nav = 0;
        let mut chosen = std::mem::take(&mut self.compose.mention_pick).then_some(sel);

        // What the box holds, top to bottom: a title, the rows, and a line
        // between the groups of "@" (members / @everyone and @here / roles).
        enum Item {
            Title(String),
            Divider,
            Row(usize, f32),
        }
        let group = |e: &Entry| match e {
            Entry::User { .. } => 0,
            Entry::Everyone | Entry::Here => 1,
            Entry::Role { .. } => 2,
            Entry::Channel { .. } | Entry::Emoji { .. } => 3,
        };
        let title = match (m.sigil, m.query.is_empty()) {
            ('#', true) => Some("Text Channels".to_string()),
            ('#', false) => Some(format!("Text channels matching #{}", m.query)),
            (':', _) => Some(format!("Emoji matching :{}", m.query)),
            (_, true) => entries.iter().any(|e| group(e) == 0).then(|| "Members".to_string()),
            (_, false) => entries.iter().any(|e| group(e) == 0).then(|| format!("Members matching @{}", m.query)),
        };
        let mut items: Vec<Item> = title.into_iter().map(Item::Title).collect();
        for (i, e) in entries.iter().enumerate() {
            if i > 0 && group(e) != group(&entries[i - 1]) {
                items.push(Item::Divider);
            }
            let h = match e {
                Entry::User { .. } => ROW_MEMBER,
                Entry::Emoji { .. } => ROW_EMOJI,
                _ => ROW,
            };
            items.push(Item::Row(i, h));
        }
        let height: f32 = items
            .iter()
            .map(|it| match it {
                Item::Title(_) => TITLE,
                Item::Divider => DIVIDER,
                Item::Row(_, h) => *h,
            })
            .sum::<f32>()
            + PAD_BOTTOM
            + if matches!(items.first(), Some(Item::Title(_))) { 0.0 } else { 8.0 };
        let rect = Rect::from_min_max(pos2(composer.left() + 8.0, composer.top() - 8.0 - height), pos2(composer.right() - 16.0, composer.top() - 8.0));
        let small = FontId::proportional(12.0);
        egui::Area::new(egui::Id::new("mention_list")).order(Order::Foreground).fixed_pos(rect.min).show(ctx, |ui| {
            ui.expand_to_include_rect(rect);
            let p = ui.painter().clone();
            // Discord: a 1 px ring of white at 8 % and a soft shadow below.
            p.add(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) }.as_shape(rect, 5.0));
            p.rect_filled(rect, 5.0, t.bg_secondary);
            p.rect_stroke(rect.expand(0.5), 5.5, Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
            // (A click on the list itself isn't a click "elsewhere" for the chat.)
            ui.interact(rect, egui::Id::new("mention_list_bg"), Sense::click());
            let mut y = rect.top() + if matches!(items.first(), Some(Item::Title(_))) { 0.0 } else { 8.0 };
            for item in &items {
                let (i, h) = match item {
                    Item::Title(text) => {
                        p.with_clip_rect(rect).text(pos2(rect.left() + 8.0, y + 21.3), Align2::LEFT_CENTER, text, crate::style::medium(14.0), t.header_secondary);
                        y += TITLE;
                        continue;
                    }
                    Item::Divider => {
                        p.hline(rect.left()..=rect.right(), (y + 8.0).round() + 0.5, Stroke::new(1.0_f32, t.border_subtle));
                        y += DIVIDER;
                        continue;
                    }
                    Item::Row(i, h) => (*i, *h),
                };
                let e = &entries[i];
                let row = Rect::from_min_size(pos2(rect.left() + 8.0, y), vec2(rect.width() - 16.0, h));
                y += h;
                let resp = ui.interact(row, egui::Id::new(("mention_row", i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                if resp.hovered() && ui.input(|inp| inp.pointer.delta() != egui::Vec2::ZERO) {
                    self.compose.mention_sel = i;
                }
                if i == self.compose.mention_sel {
                    p.rect_filled(row, 3.0, t.bg_hover);
                }
                let rp = p.with_clip_rect(row);
                let mid = row.center().y;
                let dot = |s: &str| s.replace(['\u{30FB}', '\u{FF65}'], " · ");
                // The muted text on the right gives way to the name.
                let (name_x, name, name_color, detail) = match e {
                    Entry::User { user, nick } => {
                        let av = Rect::from_min_size(pos2(row.left() + 8.0, mid - 12.0), vec2(24.0, 24.0));
                        let shown = nick.as_deref().filter(|n| !n.is_empty()).unwrap_or_else(|| user.display_name());
                        paint_avatar(ui, av, user.avatar_url(64), shown);
                        (av.right() + 8.0, shown.to_string(), t.header_primary, user_tag(user))
                    }
                    Entry::Role { name, color } => {
                        let c = if *color == 0 { t.header_primary } else { Color32::from_rgb((*color >> 16) as u8, (*color >> 8) as u8, *color as u8) };
                        (row.left() + 8.0, format!("@{name}"), c, "Notify users with this role who have permission to view this channel.".to_string())
                    }
                    Entry::Everyone => (row.left() + 8.0, "@everyone".to_string(), t.header_primary, "Notify everyone who has permission to view this channel.".to_string()),
                    Entry::Here => (row.left() + 8.0, "@here".to_string(), t.header_primary, "Notify everyone online who has permission to view this channel.".to_string()),
                    Entry::Channel { name, kind, category } => {
                        let ic = Rect::from_min_size(pos2(row.left() + 8.0, mid - 8.0), vec2(16.0, 16.0));
                        super::paint_icon(&rp, ic, super::channel_icon(*kind), t.header_secondary);
                        // (A channel outside any category says "Text channels".)
                        let place = category.as_deref().map(dot).unwrap_or_else(|| "Text channels".to_string());
                        (ic.right() + 8.0, dot(name), t.header_primary, place)
                    }
                    Entry::Emoji { name, url, from, .. } => {
                        let ic = Rect::from_min_size(pos2(row.left() + 8.0, mid - 10.0), vec2(20.0, 20.0));
                        egui::Image::new(url.as_str()).show_loading_spinner(false).paint_at(ui, ic);
                        (ic.right() + 8.0, format!(":{name}:"), t.header_primary, from.clone().unwrap_or_default())
                    }
                };
                let name_r = rp.text(pos2(name_x, mid), Align2::LEFT_CENTER, name, FontId::proportional(16.0), name_color);
                let detail_clip = Rect::from_min_max(pos2(name_r.right() + 16.0, row.top()), row.max);
                p.with_clip_rect(detail_clip).text(pos2(row.right() - 8.0, mid), Align2::RIGHT_CENTER, detail, small.clone(), t.header_secondary);
                if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                    chosen = Some(i);
                }
            }
        });

        let Some(entry) = chosen.and_then(|i| entries.get(i)) else { return };
        // (A standard emoji picked here counts towards Frequently Used.)
        let used = match entry {
            Entry::Emoji { text, unicode: true, .. } => Some(text.clone()),
            _ => None,
        };
        let draft = self.drafts.entry(ch).or_default();
        let chars: Vec<char> = draft.chars().collect();
        if m.end > chars.len() || chars.get(m.start) != Some(&m.sigil) {
            return;
        }
        let mut text: String = chars[..m.start].iter().collect();
        text.push_str(&entry.insert());
        let caret = text.chars().count();
        // (No second space when one already follows the word.)
        let tail = &chars[m.end..];
        text.extend(tail.iter().skip(usize::from(tail.first() == Some(&' '))));
        *draft = text;
        let id = egui::Id::new(("composer", ch.0));
        let mut st = egui::TextEdit::load_state(ctx, id).unwrap_or_default();
        st.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(caret))));
        st.store(ctx, id);
        self.compose.mention = None;
        self.compose.mention_rows = 0;
        self.compose.mention_sel = 0;
        self.compose.focus_composer = true;
        if let Some(e) = used {
            self.use_emoji(&e);
        }
        ctx.request_repaint();
    }
}

#[cfg(test)]
mod tests {
    use super::{query_at, replace_names};

    #[test]
    fn the_word_after_an_at_is_the_query() {
        assert_eq!(query_at("@", 1), Some(('@', 0, String::new())));
        assert_eq!(query_at("hi @fer", 7), Some(('@', 3, "fer".into())));
        assert_eq!(query_at("hi @fer", 5), Some(('@', 3, "f".into())));
        assert_eq!(query_at("see #gen", 8), Some(('#', 4, "gen".into())));
        assert_eq!(query_at("#", 1), Some(('#', 0, String::new())));
        // A heading ("# Title") isn't a channel query; an old-style tag stays an "@" one.
        assert_eq!(query_at("# Title", 7), None);
        // Emoji names from two letters on; smileys and times aren't ones.
        assert_eq!(query_at("nice :sm", 8), Some((':', 5, "sm".into())));
        assert_eq!(query_at(":s", 2), None);
        assert_eq!(query_at(":-)", 3), None);
        assert_eq!(query_at("at 12:30", 8), None);
        assert_eq!(query_at("@bot#1234", 9), Some(('@', 0, "bot#1234".into())));
        // Past the word, in an e-mail address, or with no "@" at all.
        assert_eq!(query_at("hi @fer there", 13), None);
        assert_eq!(query_at("mail [email protected]", 19), None);
        assert_eq!(query_at("hello", 5), None);
        assert_eq!(query_at("a\n@é", 4), Some(('@', 2, "é".into())));
    }

    #[test]
    fn typed_names_become_mentions() {
        let names = vec![
            ("ferris".to_string(), "<@1>".to_string()),
            ("fer".to_string(), "<@2>".to_string()),
            ("Mod Team".to_string(), "<@&3>".to_string()),
            ("Mod".to_string(), "<@&4>".to_string()),
            ("everyone".to_string(), "@everyone".to_string()),
        ];
        assert_eq!(replace_names("hey @ferris, look", '@', &names), "hey <@1>, look");
        assert_eq!(replace_names("@fer @Ferris", '@', &names), "<@2> <@1>");
        assert_eq!(replace_names("ping @Mod Team now and @Mod", '@', &names), "ping <@&3> now and <@&4>");
        // Not whole words, not at a word's start, or inside code: left alone.
        assert_eq!(replace_names("@ferrissa me@fer `@fer`", '@', &names), "@ferrissa me@fer `@fer`");
        assert_eq!(replace_names("<@1> @everyone @nobody", '@', &names), "<@1> @everyone @nobody");
        let channels = vec![("general".to_string(), "<#7>".to_string()), ("general-chat".to_string(), "<#8>".to_string())];
        assert_eq!(replace_names("go to #general or #general-chat, not a#general", '#', &channels), "go to <#7> or <#8>, not a#general");
    }
}