Skip to content

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

40.8 KB
Raw Blame
//! Forum and media channels (Discord's "thread-only" channels): the list of
//! posts under the "Search or create a post…" card, the sort and tag
//! filters, and the form that starts a post. A post is a thread; opening one
//! shows it in the chat view.
//!
//! Sizes are Discord web's: 12 px corners and a hairline border on the cards,
//! 16 px between posts, 24 px tag pills, a 20 px semibold title, the 14 px
//! "Author: message" line and a 72 px thumbnail on the right.

use std::collections::HashMap;

use crate::app::RustCord;
use crate::store::Store;
use crate::style::{icon, icon_font, medium, overlay, Theme};
use discord::model::{Channel, ForumTag, Id, Message};
use eframe::egui::{
    self, pos2, vec2, Align, Align2, CentralPanel, Color32, FontFamily, FontId, Frame, Key, Margin, Rect, Response, RichText, ScrollArea, Sense,
    Stroke, TextEdit, Ui,
};
use serde::Deserialize;
use serde_json::json;

/// Posts per request (Discord's page size).
const PAGE: usize = 25;
/// Manage Threads: may use moderated tags.
const MANAGE_THREADS: u64 = 1 << 34;

fn strong(size: f32) -> FontId {
    FontId::new(size, FontFamily::Name(crate::style::BOLD.into()))
}

/// The forum that's open: its posts as Discord last listed them.
#[derive(Default)]
pub struct ForumState {
    pub channel: Option<Id>,
    /// Active posts (Discord lists these first, latest activity on top).
    active: Vec<Id>,
    /// Archived posts, in Discord's order, a page at a time.
    posts: Vec<Id>,
    /// Each post's first message, for the preview line and thumbnail.
    first: HashMap<Id, Message>,
    /// Posts Discord listed for RustCord (so a missing first message means it was
    /// deleted, not that RustCord hasn't asked).
    listed: std::collections::HashSet<Id>,
    has_more: bool,
    loaded: bool,
    error: Option<String>,
    /// Sorted by creation date rather than latest activity.
    by_creation: bool,
    /// Only posts with one of these tags.
    tags: Vec<Id>,
    /// The search box, which is also a new post's title.
    query: String,
    draft: Option<PostDraft>,
    /// What the box searches for, and the posts Discord found (None until
    /// it has answered).
    search: Option<(String, Option<Vec<Id>>)>,
    /// When to send the search (a pause in typing), and its request.
    search_due: Option<std::time::Instant>,
    search_tag: Option<String>,
    sort_menu: Option<(egui::Pos2, u64)>,
    /// The request for archived posts in flight, and whether its posts add
    /// to the list.
    tag: Option<String>,
    append: bool,
    /// The request for active posts in flight (there are rarely more than
    /// a page of them; further pages follow by themselves).
    active_tag: Option<String>,
    active_loaded: bool,
    generation: u32,
    /// Requests whose answers no longer matter (dropped when they arrive).
    stale: Vec<String>,
}

#[derive(Default)]
struct PostDraft {
    message: String,
    tags: Vec<Id>,
}

/// ">30d ago" as Discord's post cards put it.
fn ago(ms: u64) -> String {
    let now = chrono::Utc::now().timestamp_millis().max(0) as u64;
    let mins = now.saturating_sub(ms) / 60_000;
    match mins {
        0 => "just now".into(),
        1..=59 => format!("{mins}m ago"),
        60..=1439 => format!("{}h ago", mins / 60),
        1440..=43_199 => format!("{}d ago", mins / 1440),
        _ => ">30d ago".into(),
    }
}

fn tag_emoji(tag: &ForumTag) -> Option<String> {
    match (tag.emoji_id, tag.emoji_name.as_deref()) {
        (Some(id), _) => Some(super::emoji_img(id, false, 48)),
        (None, Some(n)) if !n.is_empty() => Some(crate::emoji::twemoji_url(n)),
        _ => None,
    }
}

/// A picture from the post's first message, cut to the 72 px thumbnail.
fn thumbnail(m: &Message) -> Option<String> {
    let url = m.attachments.iter().find(|a| a.is_image()).map(|a| a.proxy_url.clone()).filter(|u| !u.is_empty()).or_else(|| {
        m.embeds.iter().find_map(|e| e.thumbnail.as_ref().or(e.image.as_ref())).and_then(|i| i.proxy_url.clone())
    })?;
    Some(format!("{url}{}width=144&height=144", if url.contains('?') { '&' } else { '?' }))
}

/// The reaction a post card shows: the forum's default one (with no count
/// while nobody has used it), else the first message's most used.
fn leading_reaction(forum: &Channel, m: &Message) -> Option<(Option<String>, u32, bool)> {
    let image = |id: Option<Id>, name: Option<&str>, animated: bool| match (id, name) {
        (Some(id), _) => Some(super::emoji_img(id, animated, 48)),
        (None, Some(n)) if !n.is_empty() => Some(crate::emoji::twemoji_url(n)),
        _ => None,
    };
    if let Some(d) = forum.default_reaction_emoji.as_ref().filter(|d| d.emoji_id.is_some() || d.emoji_name.as_deref().is_some_and(|n| !n.is_empty())) {
        let used = m.reactions.iter().find(|r| match d.emoji_id {
            Some(id) => r.emoji.id == Some(id),
            None => r.emoji.id.is_none() && r.emoji.name == d.emoji_name,
        });
        return Some((image(d.emoji_id, d.emoji_name.as_deref(), false), used.map_or(0, |r| r.count), used.is_some_and(|r| r.me)));
    }
    // (`max_by_key` keeps the last of equals; the first is the older reaction.)
    let top = m.reactions.iter().rev().max_by_key(|r| r.count)?;
    Some((image(top.emoji.id, top.emoji.name.as_deref(), top.emoji.animated), top.count, top.me))
}

/// Discord's pill: a tag (24 px on a post, 32 px in the filter row) or the
/// sort button. Returns its response.
fn pill(ui: &mut Ui, t: &Theme, label: &str, emoji: Option<&str>, glyph: Option<&str>, selected: bool, small: bool, sense: Sense) -> Response {
    let (h, pad, font) = if small { (24.0, 8.0, strong(12.0)) } else { (32.0, 12.0, medium(14.0)) };
    let fg = t.header_primary;
    let text = ui.painter().layout_no_wrap(label.to_string(), font, fg);
    let lead = if emoji.is_some() || glyph.is_some() { if small { 18.0 } else { 22.0 } } else { 0.0 };
    let (rect, resp) = ui.allocate_exact_size(vec2(pad * 2.0 + lead + text.size().x, h), sense);
    let hovered = resp.hovered() && sense != Sense::hover();
    let (fill, border) = if selected {
        let a = t.accent;
        (crate::style::rgba(a.r(), a.g(), a.b(), if hovered { 82 } else { 38 }), a)
    } else {
        (overlay(if hovered { 0.20 } else { 0.12 }), t.border_subtle)
    };
    ui.painter().rect(rect, h / 2.0, fill, Stroke::new(1.0_f32, border));
    let size = if small { 14.0 } else { 16.0 };
    let at = Rect::from_center_size(pos2(rect.left() + pad + size / 2.0, rect.center().y), vec2(size, size));
    if let Some(url) = emoji {
        egui::Image::new(url.to_string()).paint_at(ui, at);
    } else if let Some(g) = glyph {
        ui.painter().text(at.center(), Align2::CENTER_CENTER, g, icon_font(size - 2.0), fg);
    }
    ui.painter().galley(pos2(rect.left() + pad + lead, rect.center().y - text.size().y / 2.0), text, fg);
    if sense == Sense::hover() {
        resp
    } else {
        resp.on_hover_cursor(egui::CursorIcon::PointingHand)
    }
}

/// What a post card shows.
struct Card<'a> {
    title: &'a str,
    tags: Vec<&'a ForumTag>,
    /// "Author" and the first message on one line (inner None: it was
    /// deleted; outer None: not known yet).
    preview: Option<Option<(String, String)>>,
    thumb: Option<String>,
    /// The first message's leading reaction: picture and count.
    reaction: Option<(Option<String>, u32, bool)>,
    messages: u32,
    when: String,
    unread: bool,
    pinned: bool,
    locked: bool,
}

fn post_card(ui: &mut Ui, t: &Theme, c: &Card) -> Response {
    let has_tags = !c.tags.is_empty();
    let h = 2.0 + 24.0 + if has_tags { 32.0 } else { 0.0 } + 24.0 + 6.0 + 18.0 + 8.0 + 20.0;
    let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());
    let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
    if !ui.is_rect_visible(rect) {
        return resp;
    }
    let hovered = resp.hovered();
    // (A translucent lift, so a client theme's gradient still shows through.)
    let (fill, border) = if hovered { (overlay(0.08), t.interactive_muted) } else { (Color32::TRANSPARENT, t.border_subtle) };
    ui.painter().rect(rect, 12.0, fill, Stroke::new(1.0_f32, border));

    let left = rect.left() + 11.0;
    let right = rect.right() - 11.0 - if c.thumb.is_some() { 84.0 } else { 0.0 };
    let clip = ui.painter_at(Rect::from_min_max(pos2(left, rect.top()), pos2(right, rect.bottom())));
    let dim = if c.unread { t.header_primary } else { t.text_muted };
    let mut y = rect.top() + 13.0;

    // Tags: at most three, then "+N".
    if has_tags {
        let mut x = left;
        let shown = c.tags.len().min(3);
        let mut labels: Vec<(String, Option<String>)> = c.tags[..shown].iter().map(|tag| (tag.name.clone(), tag_emoji(tag))).collect();
        if c.tags.len() > shown {
            labels.push((format!("+{}", c.tags.len() - shown), None));
        }
        for (label, emoji) in labels {
            let text = clip.layout_no_wrap(label, strong(12.0), t.header_primary);
            let lead = if emoji.is_some() { 18.0 } else { 0.0 };
            let r = Rect::from_min_size(pos2(x, y), vec2(16.0 + lead + text.size().x, 24.0));
            clip.rect(r, 12.0, overlay(0.12), Stroke::new(1.0_f32, t.border_subtle));
            if let Some(url) = emoji {
                egui::Image::new(url).paint_at(ui, Rect::from_center_size(pos2(r.left() + 15.0, r.center().y), vec2(14.0, 14.0)));
            }
            clip.galley(pos2(r.left() + 8.0 + lead, r.center().y - text.size().y / 2.0), text, t.header_primary);
            x = r.right() + 8.0;
        }
        y += 32.0;
    }

    // Title: 20 px semibold on one line, a pin or padlock before it.
    let mut x = left;
    for (on, glyph) in [(c.pinned, icon::PIN), (c.locked, icon::TEXT_LOCK)] {
        if on {
            super::paint_icon(&clip, Rect::from_center_size(pos2(x + 9.0, y + 12.0), vec2(18.0, 18.0)), glyph, t.interactive_normal);
            x += 24.0;
        }
    }
    let title_font = strong(20.0);
    let title = super::elide_text_emoji(ui, c.title, &title_font, right - x - 8.0);
    super::paint_text_emoji(ui, &clip, pos2(x, y + 12.0), &title, title_font, dim);
    y += 30.0;

    // "Author: the first message", on one line.
    match &c.preview {
        None => {}
        Some(Some((author, text))) => {
            let label = if text.is_empty() { author.clone() } else { format!("{author}:") };
            let r = super::paint_text_emoji(ui, &clip, pos2(left, y + 9.0), &label, strong(14.0), dim);
            if !text.is_empty() {
                let font = medium(14.0);
                let text = super::elide_text_emoji(ui, text, &font, right - r.right() - 4.0);
                super::paint_text_emoji(ui, &clip, pos2(r.right() + 4.0, y + 9.0), &text, font, dim);
            }
        }
        Some(None) => {
            clip.text(pos2(left, y + 9.0), Align2::LEFT_CENTER, "Original message was deleted", FontId::proportional(14.0), t.text_muted);
        }
    }
    y += 26.0;

    // Footer: the leading reaction, replies, "•", how long ago.
    let mid = y + 10.0;
    let mut x = left;
    if let Some((image, count, mine)) = &c.reaction {
        // (Nobody has used the forum's reaction yet: just the emoji.)
        let text = clip.layout_no_wrap(if *count > 0 { count.to_string() } else { String::new() }, strong(14.0), t.interactive_normal);
        let w = if *count > 0 { 6.0 + 20.0 + 6.0 + text.size().x + 8.0 } else { 32.0 };
        let r = Rect::from_min_size(pos2(x, mid - 14.0), vec2(w, 28.0));
        let a = t.accent;
        let (fill, border) = if *mine { (crate::style::rgba(a.r(), a.g(), a.b(), 38), a) } else { (overlay(0.12), Color32::TRANSPARENT) };
        clip.rect(r, 8.0, fill, Stroke::new(1.0_f32, border));
        if let Some(url) = image {
            egui::Image::new(url.clone()).paint_at(ui, Rect::from_center_size(pos2(r.left() + 16.0, mid), vec2(20.0, 20.0)));
        }
        clip.galley(pos2(r.left() + 33.0, mid - text.size().y / 2.0), text, t.interactive_normal);
        x = r.right() + 12.0;
    }
    clip.text(pos2(x + 7.0, mid + 1.0), Align2::CENTER_CENTER, icon::MESSAGE, icon_font(14.0), t.text_normal);
    let r = clip.text(pos2(x + 18.0, mid), Align2::LEFT_CENTER, c.messages.to_string(), medium(14.0), t.text_normal);
    let r = clip.text(pos2(r.right() + 8.0, mid), Align2::LEFT_CENTER, "•", FontId::proportional(16.0), t.interactive_muted);
    clip.text(pos2(r.right() + 8.0, mid), Align2::LEFT_CENTER, &c.when, FontId::proportional(14.0), t.text_normal);

    if let Some(url) = &c.thumb {
        let r = Rect::from_min_size(pos2(rect.right() - 11.0 - 72.0, rect.top() + 13.0), vec2(72.0, 72.0));
        ui.painter().rect_filled(r, 8.0, overlay(0.12));
        super::paint_cover(ui, r, url, egui::Rounding::same(8.0));
    }
    resp
}

impl RustCord {
    /// Ask for a page of the forum's posts. Discord's search lists archived
    /// and active posts separately (asked for both at once, it misplaces
    /// active posts nobody has replied to), so each is its own request, as
    /// in Discord's client.
    fn forum_request(&mut self, ch: Id, archived: bool, offset: usize) -> String {
        let f = &mut self.forum;
        f.generation += 1;
        let mut path = format!(
            "/channels/{ch}/threads/search?archived={archived}&sort_by={}&sort_order=desc&limit={PAGE}&tag_setting=match_some&offset={offset}",
            if f.by_creation { "creation_time" } else { "last_message_time" }
        );
        if !f.tags.is_empty() {
            path += "&tag=";
            path += &f.tags.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",");
        }
        let tag = format!("forum:{ch}:{}", f.generation);
        self.api(&tag, reqwest::Method::GET, path, None);
        tag
    }

    /// Load the archived posts from `offset` on; from 0, the active ones too.
    fn forum_load(&mut self, ch: Id, offset: usize) {
        if let Some(old) = self.forum.tag.take() {
            self.forum.stale.push(old);
        }
        self.forum.append = offset > 0;
        self.forum.tag = Some(self.forum_request(ch, true, offset));
        if offset == 0 {
            if let Some(old) = self.forum.active_tag.take() {
                self.forum.stale.push(old);
            }
            self.forum.active_loaded = false;
            self.forum.active_tag = Some(self.forum_request(ch, false, 0));
        }
    }

    /// Keep a page of posts: the threads go to the store, their first
    /// messages here. Returns the post ids and whether more follow.
    fn forum_keep(&mut self, v: &serde_json::Value) -> (Vec<Id>, bool) {
        let mut ids = Vec::new();
        for t in v["threads"].as_array().into_iter().flatten() {
            self.store.upsert_channel(t);
            ids.extend(Id::from_value(&t["id"]));
        }
        for m in v["first_messages"].as_array().into_iter().flatten() {
            if let Ok(m) = Message::deserialize(m) {
                self.forum.first.insert(m.channel_id, m);
            }
        }
        self.forum.listed.extend(ids.iter().copied());
        (ids, v["has_more"].as_bool().unwrap_or(false))
    }

    /// Posts by title, as Discord's box finds them: asked of Discord once
    /// the typing pauses. `needle` empty: no search.
    fn forum_search(&mut self, ch: Id, needle: &str) {
        if needle.is_empty() {
            if self.forum.search.take().is_some() {
                self.forum.stale.extend(self.forum.search_tag.take());
                self.forum.search_due = None;
            }
            return;
        }
        if self.forum.search.as_ref().is_none_or(|s| s.0 != needle) {
            self.forum.search = Some((needle.to_string(), None));
            self.forum.stale.extend(self.forum.search_tag.take());
            self.forum.search_due = Some(std::time::Instant::now() + std::time::Duration::from_millis(300));
        }
        let Some(due) = self.forum.search_due else { return };
        let now = std::time::Instant::now();
        if now < due {
            self.ctx.request_repaint_after(due - now);
            return;
        }
        self.forum.search_due = None;
        self.forum.generation += 1;
        let name: String = url::form_urlencoded::byte_serialize(needle.as_bytes()).collect();
        let mut path = format!("/channels/{ch}/threads/search?name={name}&tag_setting=match_some");
        if !self.forum.tags.is_empty() {
            path += "&tag=";
            path += &self.forum.tags.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",");
        }
        let tag = format!("forum:{ch}:{}", self.forum.generation);
        self.api(&tag, reqwest::Method::GET, path, None);
        self.forum.search_tag = Some(tag);
    }

    /// Take the list request's answer (and drop answers nobody waits for).
    fn forum_poll(&mut self) {
        let stale = std::mem::take(&mut self.forum.stale);
        self.forum.stale = stale.into_iter().filter(|t| self.api_take(t).is_none() && self.api_busy(t)).collect();
        if let Some(result) = self.forum.search_tag.clone().and_then(|tag| self.api_take(&tag)) {
            self.forum.search_tag = None;
            let ids = match result {
                Ok(v) => self.forum_keep(&v).0,
                Err(e) => {
                    log::warn!("forum: search: {e}");
                    Vec::new()
                }
            };
            if let Some(s) = self.forum.search.as_mut() {
                s.1 = Some(ids);
            }
        }
        // Active posts: all of them, a page after another (up to 200).
        if let Some(result) = self.forum.active_tag.clone().and_then(|tag| self.api_take(&tag)) {
            self.forum.active_tag = None;
            self.forum.active_loaded = true;
            match result {
                Ok(v) => {
                    let (ids, more) = self.forum_keep(&v);
                    let known = self.forum.active.len();
                    for id in ids {
                        if !self.forum.active.contains(&id) {
                            self.forum.active.push(id);
                        }
                    }
                    let n = self.forum.active.len();
                    if let (true, Some(ch)) = (more && n > known && n < 200, self.forum.channel) {
                        self.forum.active_tag = Some(self.forum_request(ch, false, n));
                    }
                }
                // (The archived list's failure is the one that's shown.)
                Err(e) => log::warn!("forum: active posts: {e}"),
            }
        }
        let Some(tag) = self.forum.tag.clone() else { return };
        let Some(result) = self.api_take(&tag) else { return };
        self.forum.tag = None;
        self.forum.loaded = true;
        match result {
            Ok(v) => {
                if !self.forum.append {
                    self.forum.posts.clear();
                }
                let (ids, more) = self.forum_keep(&v);
                for id in ids {
                    if !self.forum.posts.contains(&id) {
                        self.forum.posts.push(id);
                    }
                }
                self.forum.has_more = more;
                self.forum.error = None;
            }
            Err(e) => {
                self.forum.has_more = false;
                self.forum.error = Some(e);
            }
        }
    }

    /// A forum or media channel: its posts, newest activity first.
    pub(super) fn forum_ui(&mut self, ui: &mut Ui, channel: &Channel) {
        let t = self.theme.clone();
        let ch = channel.id;
        if self.forum.channel != Some(ch) {
            let mut stale = std::mem::take(&mut self.forum.stale);
            stale.extend(self.forum.tag.take());
            stale.extend(self.forum.active_tag.take());
            stale.extend(self.forum.search_tag.take());
            self.forum = ForumState {
                channel: Some(ch),
                by_creation: channel.default_sort_order == Some(1),
                generation: self.forum.generation,
                stale,
                ..Default::default()
            };
            self.forum_load(ch, 0);
        }
        self.forum_poll();
        // (With no form open, the box searches the posts by title.)
        let needle = if self.forum.draft.is_none() { self.forum.query.trim().to_string() } else { String::new() };
        self.forum_search(ch, &needle);
        match self.api_take("forum:create") {
            Some(Ok(v)) => {
                self.store.upsert_channel(&v);
                self.forum.draft = None;
                self.forum.query.clear();
                if let Some(id) = Id::from_value(&v["id"]) {
                    self.store.joined_threads.insert(id);
                    self.select_channel(Some(id));
                }
                // (The list is fetched afresh when you come back to it.)
                self.forum.channel = None;
                return;
            }
            Some(Err(e)) => self.toast(format!("Couldn't create the post: {e}"), true),
            None => {}
        }

        let can_post = self.store.can_send(channel);
        let can_moderate = self.store.channel_perms(channel).map_or(true, |p| p & MANAGE_THREADS != 0);
        let posting = self.api_busy("forum:create");
        let title_id = egui::Id::new("forum_title");
        let (mut open, mut reload, mut more, mut submit, mut cancel) = (None, false, false, false, false);
        let mut toggle_tag = None;
        let mut sort_at = None;

        CentralPanel::default().frame(Frame::none().fill(t.page(t.bg_primary))).show_inside(ui, |ui| {
            ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
                Frame::none().inner_margin(Margin { left: 16.0, right: 24.0, top: 20.0, bottom: 24.0 }).show(ui, |ui| {
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    ui.set_width(ui.available_width());

                    // ---- "Search or create a post…" and the New Post form ----
                    Frame::none()
                        .fill(t.page(t.bg_secondary))
                        .rounding(12.0)
                        .stroke(Stroke::new(1.0_f32, t.border_subtle))
                        .inner_margin(Margin::symmetric(0.0, 8.0))
                        .show(ui, |ui| {
                            ui.set_width(ui.available_width());
                            let drafting = self.forum.draft.is_some();
                            ui.horizontal(|ui| {
                                ui.set_height(32.0);
                                ui.add_space(12.0);
                                let (r, _) = ui.allocate_exact_size(vec2(26.0, 32.0), Sense::hover());
                                let glyph = if drafting { icon::FORUM } else { icon::SEARCH };
                                super::paint_icon(ui.painter(), Rect::from_center_size(r.center(), vec2(22.0, 22.0)), glyph, t.interactive_normal);
                                ui.add_space(8.0);
                                let buttons = if can_post && !drafting { 117.0 } else { 12.0 };
                                let hint = if drafting {
                                    "Title"
                                } else if can_post {
                                    "Search or create a post…"
                                } else {
                                    "Search posts…"
                                };
                                let edit = ui.add_sized(
                                    vec2((ui.available_width() - buttons).max(60.0), 32.0),
                                    TextEdit::singleline(&mut self.forum.query)
                                        .id(title_id)
                                        .frame(false)
                                        .font(strong(20.0))
                                        .hint_text(RichText::new(hint).font(strong(20.0)).color(t.text_muted))
                                        .text_color(t.header_primary)
                                        .char_limit(100)
                                        .vertical_align(Align::Center)
                                        .margin(vec2(0.0, 0.0)),
                                );
                                let enter = edit.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
                                let mut start = enter && can_post && !drafting && !self.forum.query.trim().is_empty();
                                if can_post && !drafting {
                                    ui.add_space(8.0);
                                    let (r, resp) = ui.allocate_exact_size(vec2(101.0, 32.0), Sense::click());
                                    let fill = if resp.hovered() { t.accent.gamma_multiply(0.85) } else { t.accent };
                                    ui.painter().rect(r, 8.0, fill, Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
                                    super::paint_icon(ui.painter(), Rect::from_center_size(pos2(r.left() + 20.0, r.center().y), vec2(16.0, 16.0)), icon::FORUM, Color32::WHITE);
                                    ui.painter().text(pos2(r.left() + 34.0, r.center().y), Align2::LEFT_CENTER, "New Post", medium(14.0), Color32::WHITE);
                                    start |= resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                                }
                                if start {
                                    self.forum.draft = Some(PostDraft::default());
                                    ui.memory_mut(|m| m.request_focus(if self.forum.query.trim().is_empty() { title_id } else { egui::Id::new("forum_message") }));
                                }
                            });
                            let Some(draft) = self.forum.draft.as_mut() else { return };
                            ui.add_space(8.0);
                            ui.painter().hline(ui.max_rect().x_range(), ui.cursor().top(), Stroke::new(1.0_f32, t.border_subtle));
                            Frame::none().inner_margin(Margin { left: 12.0, right: 12.0, top: 12.0, bottom: 4.0 }).show(ui, |ui| {
                                ui.add(
                                    TextEdit::multiline(&mut draft.message)
                                        .id(egui::Id::new("forum_message"))
                                        .frame(false)
                                        .desired_rows(4)
                                        .desired_width(ui.available_width())
                                        .hint_text(RichText::new("Enter a message…").color(t.text_muted))
                                        .font(FontId::proportional(16.0))
                                        .text_color(t.text_normal)
                                        .char_limit(2000),
                                );
                                let usable: Vec<&ForumTag> = channel.available_tags.iter().filter(|g| can_moderate || !g.moderated).collect();
                                if !usable.is_empty() {
                                    ui.add_space(12.0);
                                    ui.horizontal_wrapped(|ui| {
                                        ui.spacing_mut().item_spacing = vec2(8.0, 8.0);
                                        for tag in usable {
                                            let on = draft.tags.contains(&tag.id);
                                            // Discord allows five tags on a post.
                                            let full = !on && draft.tags.len() >= 5;
                                            let emoji = tag_emoji(tag);
                                            let r = pill(ui, &t, &tag.name, emoji.as_deref(), None, on, false, if full { Sense::hover() } else { Sense::click() });
                                            if r.clicked() {
                                                if on {
                                                    draft.tags.retain(|i| *i != tag.id);
                                                } else {
                                                    draft.tags.push(tag.id);
                                                }
                                            }
                                        }
                                    });
                                }
                                ui.add_space(12.0);
                                let need_tag = channel.flags & Channel::FLAG_REQUIRE_TAG != 0 && draft.tags.is_empty();
                                let ready = !self.forum.query.trim().is_empty() && !draft.message.trim().is_empty() && !need_tag && !posting;
                                ui.horizontal(|ui| {
                                    ui.set_height(32.0);
                                    if need_tag {
                                        ui.label(RichText::new("Posts here need at least one tag.").size(14.0).color(t.text_muted));
                                    }
                                    ui.with_layout(egui::Layout::right_to_left(Align::Center), |ui| {
                                        let (r, resp) = ui.allocate_exact_size(vec2(64.0, 32.0), if ready { Sense::click() } else { Sense::hover() });
                                        let fill = if !ready { t.accent.gamma_multiply(0.5) } else if resp.hovered() { t.accent.gamma_multiply(0.85) } else { t.accent };
                                        ui.painter().rect_filled(r, 8.0, fill);
                                        let label = if posting { "Posting…" } else { "Post" };
                                        ui.painter().text(r.center(), Align2::CENTER_CENTER, label, medium(14.0), if ready { Color32::WHITE } else { crate::style::rgba(255, 255, 255, 140) });
                                        submit = ready && resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                                        ui.add_space(8.0);
                                        let (r, resp) = ui.allocate_exact_size(vec2(72.0, 32.0), Sense::click());
                                        ui.painter().text(r.center(), Align2::CENTER_CENTER, "Cancel", medium(14.0), if resp.hovered() { t.header_primary } else { t.interactive_normal });
                                        cancel = resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                                    });
                                });
                            });
                        });
                    if self.forum.draft.is_some() && ui.input(|i| i.key_pressed(Key::Escape)) {
                        cancel = true;
                    }

                    // ---- sort, then the tags to filter by ----
                    ui.add_space(16.0);
                    ui.horizontal_wrapped(|ui| {
                        ui.spacing_mut().item_spacing = vec2(8.0, 8.0);
                        let label = if self.forum.by_creation { "Date Posted" } else { "Recently Active" };
                        let r = pill(ui, &t, label, None, Some(icon::CHEVRON_DOWN), self.forum.sort_menu.is_some(), false, Sense::click());
                        if r.clicked() {
                            sort_at = Some(r.rect.left_bottom() + vec2(0.0, 6.0));
                        }
                        for tag in &channel.available_tags {
                            let emoji = tag_emoji(tag);
                            if pill(ui, &t, &tag.name, emoji.as_deref(), None, self.forum.tags.contains(&tag.id), false, Sense::click()).clicked() {
                                toggle_tag = Some(tag.id);
                            }
                        }
                    });
                    ui.add_space(20.0);

                    // ---- the posts ----
                    // Active posts first: the ones Discord listed, and any the
                    // gateway has told RustCord of since (a post made just now).
                    let by_creation = self.forum.by_creation;
                    let tags = &self.forum.tags;
                    let mut posts: Vec<&Channel> = self
                        .store
                        .channels
                        .values()
                        .filter(|c| c.parent_id == Some(ch) && !c.archived() && discord::model::channel_kind::is_thread(c.kind))
                        .filter(|c| self.forum.active.contains(&c.id) || (self.forum.active_loaded && (tags.is_empty() || c.applied_tags.iter().any(|g| tags.contains(g)))))
                        .collect();
                    posts.sort_by_key(|c| std::cmp::Reverse(if by_creation { c.id } else { c.last_message_id.unwrap_or(c.id).max(c.id) }));
                    posts.extend(self.forum.posts.iter().filter_map(|id| self.store.channels.get(id)).filter(|c| c.archived()));
                    // Searching: what Discord found instead, in its order.
                    let searching = self.forum.search.is_some();
                    let found = self.forum.search.as_ref().and_then(|s| s.1.as_ref());
                    if searching {
                        posts = found.into_iter().flatten().filter_map(|id| self.store.channels.get(id)).collect();
                    }
                    // Pinned posts lead, as in Discord.
                    posts.sort_by_key(|p| p.flags & Channel::FLAG_PINNED == 0);
                    let shown = posts.len();
                    for post in posts {
                        let first = self.forum.first.get(&post.id);
                        let title = Store::channel_label(post);
                        let last = if self.forum.by_creation { post.id } else { post.last_message_id.unwrap_or(post.id).max(post.id) };
                        let last_read = self.store.read_states.get(&post.id).and_then(|r| r.last_read);
                        let card = Card {
                            title: &title,
                            tags: post.applied_tags.iter().filter_map(|id| channel.available_tags.iter().find(|g| g.id == *id)).collect(),
                            preview: match first {
                                Some(m) => Some(Some((m.display_name().to_string(), self.plain_mentions(m, &m.content).split_whitespace().collect::<Vec<_>>().join(" ")))),
                                None if self.forum.listed.contains(&post.id) => Some(None),
                                None => None,
                            },
                            thumb: first.and_then(thumbnail),
                            reaction: first.and_then(|m| leading_reaction(channel, m)),
                            messages: post.message_count.unwrap_or(0),
                            when: ago(last.timestamp_ms()),
                            unread: last_read.is_some_and(|r| post.last_message_id.is_some_and(|l| l > r)),
                            pinned: post.flags & Channel::FLAG_PINNED != 0,
                            locked: post.locked(),
                        };
                        if post_card(ui, &t, &card).clicked() {
                            open = Some(post.id);
                        }
                        ui.add_space(16.0);
                    }

                    // ---- what's below the last post ----
                    let note = |ui: &mut Ui, text: &str| {
                        ui.add_space(24.0);
                        ui.vertical_centered(|ui| ui.label(RichText::new(text).size(16.0).color(t.text_muted)));
                        ui.add_space(24.0);
                    };
                    if searching {
                        if found.is_none() {
                            note(ui, "Searching…");
                        } else if shown == 0 {
                            note(ui, "No posts match.");
                        }
                    } else if let Some(e) = &self.forum.error {
                        note(ui, &format!("Couldn't load the posts: {e}"));
                        ui.vertical_centered(|ui| {
                            if ui.link("Try again").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                reload = true;
                            }
                        });
                    } else if !self.forum.loaded || (shown == 0 && !self.forum.active_loaded) {
                        note(ui, "Loading posts…");
                    } else if shown == 0 && !self.forum.has_more {
                        note(ui, if self.forum.tags.is_empty() { "There are no posts here yet." } else { "No posts match." });
                    } else if self.forum.has_more {
                        // Reaching the end of the list brings the next page.
                        let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::hover());
                        ui.painter().text(r.center(), Align2::CENTER_CENTER, "Loading more posts…", FontId::proportional(14.0), t.text_muted);
                        more = ui.is_rect_visible(r) && self.forum.tag.is_none();
                    }
                });
            });
        });

        // (A click on the pill while its menu is open closes it.)
        let was_open = self.forum.sort_menu.is_some();
        self.forum_sort_menu(ui.ctx(), &t, &mut reload);
        if let Some(at) = sort_at {
            self.forum.sort_menu = if was_open { None } else { Some((at, ui.ctx().cumulative_pass_nr())) };
        }
        if let Some(id) = toggle_tag {
            let tags = &mut self.forum.tags;
            match tags.iter().position(|i| *i == id) {
                Some(i) => {
                    tags.remove(i);
                }
                None => tags.push(id),
            }
            self.forum.search = None;
            reload = true;
        }
        if cancel {
            self.forum.draft = None;
            self.forum.query.clear();
        }
        if submit {
            if let Some(d) = &self.forum.draft {
                let body = json!({
                    "name": self.forum.query.trim(),
                    "auto_archive_duration": 4320,
                    "applied_tags": d.tags.iter().map(|i| i.to_string()).collect::<Vec<_>>(),
                    "message": { "content": d.message.trim() },
                });
                self.api("forum:create", reqwest::Method::POST, format!("/channels/{ch}/threads"), Some(body));
            }
        }
        if reload {
            self.forum.loaded = false;
            self.forum.error = None;
            self.forum.active.clear();
            self.forum.posts.clear();
            self.forum_load(ch, 0);
        } else if more {
            self.forum_load(ch, self.forum.posts.len());
        }
        if let Some(id) = open {
            self.select_channel(Some(id));
        }
    }

    /// The sort pill's menu: Discord's "Sort by" choices.
    fn forum_sort_menu(&mut self, ctx: &egui::Context, t: &Theme, reload: &mut bool) {
        let Some((at, opened)) = self.forum.sort_menu else { return };
        let mut pick = None;
        let area = egui::Area::new(egui::Id::new("forum_sort")).order(egui::Order::Foreground).fixed_pos(at).constrain(true).show(ctx, |ui| {
            Frame::none()
                .fill(t.bg_floating)
                .rounding(8.0)
                .stroke(Stroke::new(1.0_f32, t.border_subtle))
                .shadow(egui::epaint::Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) })
                .inner_margin(8.0)
                .show(ui, |ui| {
                    ui.spacing_mut().item_spacing = vec2(0.0, 2.0);
                    ui.set_width(204.0);
                    let (r, _) = ui.allocate_exact_size(vec2(204.0, 24.0), Sense::hover());
                    ui.painter().text(pos2(r.left() + 8.0, r.center().y), Align2::LEFT_CENTER, "Sort by", strong(12.0), t.text_muted);
                    for (label, by_creation) in [("Recently Active", false), ("Date Posted", true)] {
                        let (r, resp) = ui.allocate_exact_size(vec2(204.0, 32.0), Sense::click());
                        if resp.hovered() {
                            ui.painter().rect_filled(r, 4.0, t.bg_hover);
                        }
                        ui.painter().text(pos2(r.left() + 8.0, r.center().y), Align2::LEFT_CENTER, label, medium(14.0), if resp.hovered() { t.header_primary } else { t.interactive_normal });
                        // Discord's radio mark on the right.
                        let c = pos2(r.right() - 16.0, r.center().y);
                        let on = self.forum.by_creation == by_creation;
                        ui.painter().circle_stroke(c, 8.0, Stroke::new(2.0_f32, if on { t.accent } else { t.interactive_normal }));
                        if on {
                            ui.painter().circle_filled(c, 4.0, t.accent);
                        }
                        if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            pick = Some(by_creation);
                        }
                    }
                });
        });
        let outside = area.response.clicked_elsewhere() && ctx.cumulative_pass_nr() > opened + 1;
        if let Some(by_creation) = pick {
            if self.forum.by_creation != by_creation {
                self.forum.by_creation = by_creation;
                *reload = true;
            }
            self.forum.sort_menu = None;
        } else if outside || ctx.input(|i| i.key_pressed(Key::Escape)) {
            self.forum.sort_menu = None;
        }
    }
}