Skip to content

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

27.3 KB
Raw Blame
//! Group DMs: the member list beside the chat and Discord's "Invite to Group
//! DM" dialog (also "Add Friends to DM" in a one-to-one DM, which starts a
//! new group). Measured on Discord web, 2026-12-03.

use super::{paint_avatar, paint_status_dot};
use crate::app::RustCord;
use crate::style::{icon, icon_font, medium, overlay, rgba};
use discord::model::{channel_kind, Id, User};
use eframe::egui::{self, pos2, vec2, Align2, Color32, CursorIcon, FontId, Key, Margin, Modifiers, Rect, ScrollArea, Sense, Stroke, TextEdit, Ui};
use serde_json::json;

/// Discord's limit: ten people in a group DM, you included.
pub(super) const MAX_MEMBERS: usize = 10;
/// The owner's crown (`--icon-feedback-warning`, read from the page).
pub(super) const CROWN: Color32 = Color32::from_rgb(206, 129, 0);
const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);
const BRAND_HOVER: Color32 = Color32::from_rgb(0x47, 0x52, 0xc4);
const CRITICAL: Color32 = Color32::from_rgb(0xd2, 0x2d, 0x39);
const CRITICAL_HOVER: Color32 = Color32::from_rgb(0xa9, 0x23, 0x2e);
/// The dialog's width and the API tag of a new group.
const DIALOG_W: f32 = 478.0;
const LEAVE_W: f32 = 440.0;
const CREATE_TAG: &str = "group-dm-create";

/// The "Leave '<group>'" confirmation dialog while it is up.
pub struct LeaveGroup {
    pub channel: Id,
    pub silent: bool,
}

/// Discord's title for it (the same shape as Leave Server's).
fn leave_group_title(name: &str) -> String {
    format!("Leave '{name}'")
}

/// The invite dialog while it is up.
pub struct GroupInvite {
    /// The DM or group DM it was opened from.
    channel: Id,
    search: String,
    picked: Vec<Id>,
    /// Frame it opened on (the search field takes the focus then).
    opened: u64,
}

fn add_tag(user: Id) -> String {
    format!("group-dm-add:{user}")
}

impl RustCord {
    /// Who is in the group: its recipients and you, by username (as Discord
    /// lists them).
    fn group_members(&self, ch: Id) -> Vec<User> {
        let Some(channel) = self.store.channels.get(&ch) else { return Vec::new() };
        let mut people: Vec<User> = channel.recipients.clone();
        if let Some(me) = self.store.me.clone().filter(|me| !people.iter().any(|u| u.id == me.id)) {
            people.push(me);
        }
        people.sort_by_cached_key(|u| u.username.to_lowercase());
        people
    }

    /// Discord's group DM member list: "Members—N" (14/18 medium, 20 px down,
    /// 16 px in), one 42 px row per person (44 with a status line), offline
    /// people at 30 % until hovered, a crown after the owner's name, and an
    /// "Invite to Group DM" button under the list while there is room.
    pub fn group_member_list_ui(&mut self, ui: &mut Ui, ch: Id) {
        let t = self.theme.clone();
        let people = self.group_members(ch);
        let owner = self.store.channels.get(&ch).and_then(|c| c.owner_id);
        let me = self.store.me_id();
        let mut open: Option<(User, egui::Pos2)> = None;
        let mut invite = false;
        ScrollArea::vertical().id_salt(("group_members", ch.0)).auto_shrink([false, false]).show(ui, |ui| {
            ui.spacing_mut().item_spacing.y = 0.0;
            ui.add_space(20.0);
            let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover());
            ui.painter().text(pos2(r.left() + 16.0, r.center().y), Align2::LEFT_CENTER, format!("Members—{}", people.len()), medium(14.0), t.channel_default);
            ui.add_space(4.0);
            for user in &people {
                let status = self.store.dot_status(user.id).to_string();
                let sub = if Some(user.id) == me {
                    self.custom_status_of(user.id).map(|custom| super::SubLine::Status { activity: None, more: 0, custom: Some(custom) })
                } else {
                    self.store.presences.get(&user.id).and_then(super::SubLine::of)
                };
                let height = super::dense(if sub.is_some() { 44.0 } else { 42.0 });
                let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::click());
                if !ui.is_rect_visible(rect) {
                    continue;
                }
                let resp = resp.on_hover_cursor(CursorIcon::PointingHand);
                let inner = rect.shrink2(vec2(8.0, 1.0));
                if resp.hovered() {
                    ui.painter().rect_filled(inner, 8.0, t.bg_hover);
                    self.profiles_wanted.borrow_mut().push((user.id, None));
                }
                let dim = status == "offline" && !resp.hovered();
                let opacity = ui.opacity();
                if dim {
                    ui.multiply_opacity(0.3);
                }
                let av = Rect::from_center_size(pos2(inner.left() + 24.0, inner.center().y), vec2(32.0, 32.0));
                let name = self.store.nick_in(None, Some(ch), user.id).unwrap_or_else(|| user.display_name().to_string());
                paint_avatar(ui, av, Some(super::avatar_uri(user, 64, resp.hovered())), &name);
                if let Some(deco) = super::decoration_uri(user, resp.hovered()) {
                    egui::Image::new(deco).paint_at(ui, av.expand(av.width() * 0.1));
                }
                if !dim {
                    paint_status_dot(ui, av.right_bottom() - vec2(3.0, 3.0), 5.0, &status, if resp.hovered() { t.bg_hover } else { t.bg_primary });
                }
                let painter = ui.painter_at(inner.with_max_x(inner.right() - 4.0));
                let font = super::name_font(user, medium(16.0));
                let color = super::name_style_colors(user).and_then(|c| c.first().copied()).map_or(t.interactive_normal, |c| Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8));
                let y = if sub.is_some() { inner.center().y - 8.0 } else { inner.center().y };
                let galley = painter.layout_no_wrap(name, font, color);
                let name_w = galley.size().x;
                painter.galley(pos2(av.right() + 12.0, y - galley.size().y / 2.0), galley, color);
                // After the name, as Discord orders them: the server tag,
                // then the APP tag and the owner's crown.
                let mut x = av.right() + 12.0 + name_w;
                if let Some((tag, badge)) = user.server_tag() {
                    x += 4.0 + super::paint_tag_chip(ui, &painter, x + 4.0, y, &tag, badge.as_deref(), &t);
                }
                if let Some(right) = super::paint_bot_badge(&painter, x + 4.0, y, user, &t) {
                    x = right;
                }
                if owner == Some(user.id) {
                    let crown = Rect::from_min_size(pos2(x + 4.0, y - 7.0), vec2(14.0, 14.0));
                    painter.text(crown.center(), Align2::CENTER_CENTER, icon::CROWN, icon_font(14.0), CROWN);
                    if ui.rect_contains_pointer(crown) {
                        resp.clone().on_hover_text("Group Owner");
                    }
                }
                if let Some(sub) = &sub {
                    sub.paint(ui, &painter, pos2(av.right() + 12.0, inner.center().y + 9.0), t.text_muted);
                }
                ui.set_opacity(opacity);
                if resp.clicked() {
                    open = Some((user.clone(), rect.left_top()));
                }
            }
            // Discord: 16 px under the list, 16 px in from the left, 8 from
            // the right: a 40 px button with the icon before its label.
            if people.len() < MAX_MEMBERS {
                ui.add_space(16.0);
                let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::hover());
                let r = Rect::from_min_max(pos2(row.left() + 16.0, row.top()), pos2(row.right() - 8.0, row.bottom()));
                let resp = ui.interact(r, egui::Id::new(("group_invite_button", ch.0)), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                let fill = if resp.hovered() { rgba(151, 151, 159, 51) } else { rgba(151, 151, 159, 31) };
                ui.painter().rect(r, 8.0, fill, Stroke::new(1.0_f32, rgba(151, 151, 159, 41)));
                let label = ui.painter().layout_no_wrap("Invite to Group DM".into(), medium(16.0), t.text_normal);
                let left = r.center().x - (20.0 + 8.0 + label.size().x) / 2.0;
                super::paint_icon(ui.painter(), Rect::from_min_size(pos2(left, r.center().y - 10.0), vec2(20.0, 20.0)), icon::GROUP_PLUS, t.text_normal);
                ui.painter().galley(pos2(left + 28.0, r.center().y - label.size().y / 2.0), label, t.text_normal);
                invite = resp.clicked();
            }
            ui.add_space(super::USER_PANEL_SPACE / 2.0);
        });
        if let Some((user, at)) = open {
            self.open_profile(user, None, at - vec2(352.0, 0.0));
        }
        if invite {
            self.open_group_invite(ch);
        }
    }

    /// The header's "Invite to Group DM" / "Add Friends to DM" button.
    pub fn open_group_invite(&mut self, channel: Id) {
        self.group_invite = Some(GroupInvite { channel, search: String::new(), picked: Vec::new(), opened: self.ctx.cumulative_pass_nr() });
    }

    pub fn group_invite_open(&self, channel: Id) -> bool {
        self.group_invite.as_ref().is_some_and(|d| d.channel == channel)
    }

    /// Friends who could be added: not in the conversation yet, matching the
    /// search, the ones you talk to most recently first (by your DM with them).
    fn invite_candidates(&self, channel: Id, search: &str) -> Vec<User> {
        let present: Vec<Id> = self.store.channels.get(&channel).map(|c| c.recipients.iter().map(|u| u.id).collect()).unwrap_or_default();
        let recent: std::collections::HashMap<Id, Id> = self
            .store
            .channels
            .values()
            .filter(|c| c.kind == channel_kind::DM)
            .filter_map(|c| Some((c.recipients.first()?.id, c.last_message_id?)))
            .collect();
        let query = search.trim().to_lowercase();
        let mut friends: Vec<User> = self
            .store
            .relationships
            .values()
            .filter(|r| r.kind == 1 && !present.contains(&r.id))
            .filter_map(|r| self.store.users.get(&r.id).cloned().or_else(|| r.user.clone()))
            .filter(|u| {
                query.is_empty()
                    || u.username.to_lowercase().contains(&query)
                    || u.display_name().to_lowercase().contains(&query)
                    || self.store.friend_nickname(u.id).is_some_and(|n| n.to_lowercase().contains(&query))
            })
            .collect();
        friends.sort_by_cached_key(|u| (std::cmp::Reverse(recent.get(&u.id).copied()), u.display_name().to_lowercase()));
        friends
    }

    /// Discord's dialog (2026-12-03): 478 px, 20/24 semibold title and the
    /// 16/20 "You can add N more people." under it; a search field beside a
    /// 100 × 40 Add button, a 12/16 hint, then the friends in 48 px rows
    /// (32 px avatar, name over username, a 20 px check box on the right).
    /// Discord's invite-link footer is left out: opening it creates a link.
    pub fn group_invite_ui(&mut self, ctx: &egui::Context) {
        self.group_invite_results();
        let Some(dialog) = self.group_invite.as_ref() else { return };
        let ch = dialog.channel;
        let Some(channel) = self.store.channels.get(&ch).cloned() else {
            self.group_invite = None;
            return;
        };
        let t = self.theme.clone();
        let is_group = channel.kind == channel_kind::GROUP_DM;
        // A new group from a DM holds you, them and whoever is picked.
        let room = MAX_MEMBERS.saturating_sub(channel.recipients.len() + 1);
        let candidates = self.invite_candidates(ch, &dialog.search);
        let creating = self.api_pending.contains(CREATE_TAG);
        let search_id = egui::Id::new(("group_invite_search", ch.0));
        if ctx.cumulative_pass_nr() <= dialog.opened + 1 {
            ctx.memory_mut(|m| m.request_focus(search_id));
        }
        let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
        let mut add = false;
        let dialog = self.group_invite.as_mut().expect("checked above");
        let picked_now = dialog.picked.len();
        let left_to_add = room.saturating_sub(picked_now);
        close |= super::guild_pages::modal_frame(ctx, &t, "group_invite", DIALOG_W, |ui| {
            let (head, _) = ui.allocate_exact_size(vec2(DIALOG_W, 24.0 + 24.0 + 8.0 + 20.0), Sense::hover());
            let left = head.left() + 24.0;
            let title = if is_group { "Invite to Group DM" } else { "Add Friends to DM" };
            ui.painter().text(pos2(left, head.top() + 36.0), Align2::LEFT_CENTER, title, super::guild_pages::strong(20.0), t.header_primary);
            let x = Rect::from_min_size(pos2(head.right() - 8.0 - 40.0, head.top() + 8.0), vec2(40.0, 40.0));
            let xr = ui.interact(x, egui::Id::new("group_invite_close"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            if xr.hovered() {
                ui.painter().rect_filled(x, 8.0, t.bg_hover);
            }
            ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(14.0), if xr.hovered() { t.header_primary } else { t.interactive_normal });
            close |= xr.clicked();
            let room_line = match left_to_add {
                0 => "This group has reached its limit of 10 members.".to_string(),
                1 => "You can add 1 more person.".to_string(),
                n => format!("You can add {n} more people."),
            };
            ui.painter().text(pos2(left, head.bottom() - 10.0), Align2::LEFT_CENTER, room_line, FontId::proportional(16.0), t.header_secondary);

            // Search field and Add.
            ui.add_space(24.0);
            let (row, _) = ui.allocate_exact_size(vec2(DIALOG_W, 40.0), Sense::hover());
            let button = Rect::from_min_size(pos2(row.right() - 24.0 - 100.0, row.top()), vec2(100.0, 40.0));
            let field = Rect::from_min_max(pos2(left, row.top()), pos2(button.left() - 8.0, row.bottom()));
            let focused = ui.memory(|m| m.has_focus(search_id));
            ui.painter().rect(field, 8.0, Color32::from_black_alpha(31), Stroke::new(1.0_f32, if focused { t.text_link } else { rgba(151, 151, 159, 61) }));
            let edit = TextEdit::singleline(&mut dialog.search)
                .id(search_id)
                .frame(false)
                .margin(Margin::symmetric(0.0, 0.0))
                .hint_text(egui::RichText::new("Search").color(t.text_muted))
                .font(FontId::proportional(16.0))
                .text_color(t.text_normal)
                .vertical_align(egui::Align::Center);
            let resp = ui.put(field.shrink2(vec2(10.0, 1.0)), edit);
            let enabled = !dialog.picked.is_empty() && !creating;
            let br = ui.interact(button, egui::Id::new("group_invite_add"), if enabled { Sense::click() } else { Sense::hover() });
            let fill = if enabled && br.hovered() { BRAND_HOVER } else { BRAND };
            ui.painter().rect(button, 8.0, if enabled { fill } else { fill.gamma_multiply(0.5) }, Stroke::new(1.0_f32, rgba(255, 255, 255, 20)));
            let label = if is_group { "Add" } else { "Create" };
            ui.painter().text(button.center(), Align2::CENTER_CENTER, label, medium(16.0), if enabled { Color32::WHITE } else { Color32::from_white_alpha(128) });
            add |= enabled && (br.on_hover_cursor(CursorIcon::PointingHand).clicked() || (resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter))));
            ui.add_space(6.0);
            let (hint, _) = ui.allocate_exact_size(vec2(DIALOG_W, 16.0), Sense::hover());
            ui.painter().text(pos2(left, hint.center().y), Align2::LEFT_CENTER, "Add friends to group DMs.", FontId::proportional(12.0), t.header_secondary);
            ui.add_space(12.0);

            // The friends.
            ScrollArea::vertical().id_salt("group_invite_list").max_height(340.0).min_scrolled_height(340.0_f32.min(48.0 * candidates.len().max(1) as f32)).show(ui, |ui| {
                ui.spacing_mut().item_spacing.y = 0.0;
                if candidates.is_empty() {
                    let (r, _) = ui.allocate_exact_size(vec2(DIALOG_W, 48.0), Sense::hover());
                    let text = if dialog.search.trim().is_empty() { "All your friends are here already." } else { "No friends found." };
                    ui.painter().text(r.center(), Align2::CENTER_CENTER, text, FontId::proportional(14.0), t.text_muted);
                }
                for user in &candidates {
                    let (row, _) = ui.allocate_exact_size(vec2(DIALOG_W, 48.0), Sense::hover());
                    let r = Rect::from_min_max(pos2(row.left() + 16.0, row.top()), pos2(row.right() - 16.0, row.bottom()));
                    if !ui.is_rect_visible(r) {
                        continue;
                    }
                    let on = dialog.picked.contains(&user.id);
                    let can = on || dialog.picked.len() < room;
                    let resp = ui.interact(r, egui::Id::new(("group_invite_row", user.id.0)), if can { Sense::click() } else { Sense::hover() });
                    if resp.hovered() && can {
                        ui.painter().rect_filled(r, 8.0, rgba(79, 80, 90, 77));
                    }
                    let av = Rect::from_min_size(pos2(r.left() + 8.0, r.center().y - 16.0), vec2(32.0, 32.0));
                    let name = self.store.friend_nickname(user.id).map(String::from).unwrap_or_else(|| user.display_name().to_string());
                    paint_avatar(ui, av, Some(super::avatar_uri(user, 64, false)), &name);
                    paint_status_dot(ui, av.right_bottom() - vec2(3.0, 3.0), 5.0, self.store.dot_status(user.id), if resp.hovered() && can { t.bg_hover } else { t.surface_high });
                    let painter = ui.painter_at(r.with_max_x(r.right() - 40.0));
                    painter.text(pos2(av.right() + 8.0, r.top() + 16.0), Align2::LEFT_CENTER, &name, medium(16.0), t.header_primary);
                    painter.text(pos2(av.right() + 8.0, r.top() + 34.0), Align2::LEFT_CENTER, &user.username, FontId::proportional(12.0), rgba(129, 130, 138, 255));
                    let b = Rect::from_center_size(pos2(r.right() - 18.0, r.center().y), vec2(20.0, 20.0));
                    if on {
                        ui.painter().rect_filled(b, 6.0, BRAND);
                        ui.painter().text(b.center(), Align2::CENTER_CENTER, icon::CHECK, icon_font(12.0), Color32::WHITE);
                    } else {
                        let edge = if can { if resp.hovered() { t.interactive_hover } else { t.interactive_normal } } else { t.interactive_muted };
                        ui.painter().rect_stroke(b, 6.0, Stroke::new(1.0_f32, edge));
                    }
                    if resp.on_hover_cursor(if can { CursorIcon::PointingHand } else { CursorIcon::NotAllowed }).clicked() {
                        if on {
                            dialog.picked.retain(|id| *id != user.id);
                        } else {
                            dialog.picked.push(user.id);
                        }
                    }
                }
            });
            ui.add_space(16.0);
        });

        if add {
            let picked = dialog.picked.clone();
            if is_group {
                // One request per person, as Discord's client does.
                for user in &picked {
                    log::info!("group dm: adding {user} to {ch}");
                    self.api(&add_tag(*user), reqwest::Method::PUT, format!("/channels/{ch}/recipients/{user}"), None);
                }
                self.group_adds.extend(picked);
                self.group_invite = None;
            } else {
                let mut recipients: Vec<Id> = channel.recipients.iter().map(|u| u.id).collect();
                recipients.extend(picked);
                log::info!("group dm: starting a group of {} from {ch}", recipients.len() + 1);
                self.api(CREATE_TAG, reqwest::Method::POST, "/users/@me/channels", Some(json!({ "recipients": recipients })));
            }
        } else if close {
            ctx.memory_mut(|m| m.surrender_focus(search_id));
            self.group_invite = None;
        }
    }

    /// Answers to Add (a toast for anyone who couldn't be added; Discord's
    /// CHANNEL_RECIPIENT_ADD updates the list) and to a new group (opened
    /// as soon as it exists).
    fn group_invite_results(&mut self) {
        let mut failed = Vec::new();
        let mut i = 0;
        while i < self.group_adds.len() {
            let user = self.group_adds[i];
            match self.api_take(&add_tag(user)) {
                Some(result) => {
                    if let Err(e) = result {
                        failed.push(e);
                    }
                    self.group_adds.swap_remove(i);
                }
                None => i += 1,
            }
        }
        if let Some(e) = failed.first() {
            self.toast(format!("Couldn't add {} to the group: {e}", if failed.len() == 1 { "them".to_string() } else { format!("{} people", failed.len()) }), true);
        }
        match self.api_take(CREATE_TAG) {
            Some(Ok(v)) => {
                self.group_invite = None;
                self.store.upsert_channel(&v);
                if let Some(id) = Id::from_value(&v["id"]) {
                    self.current_guild = None;
                    self.select_channel(Some(id));
                }
            }
            Some(Err(e)) => self.toast(format!("Couldn't create the group: {e}"), true),
            None => {}
        }
    }

    /// Open the "Leave '<group>'" confirmation dialog for a group DM.
    pub fn open_leave_group(&mut self, channel: Id) {
        if self.store.channels.get(&channel).is_some_and(|c| c.kind == channel_kind::GROUP_DM) {
            self.group_leave = Some(LeaveGroup { channel, silent: false });
        }
    }

    /// Discord's confirmation before leaving a group DM, with its "Leave
    /// without notifying other members" box.
    pub fn leave_group_ui(&mut self, ctx: &egui::Context) {
        let Some(mut dialog) = self.group_leave.take() else { return };
        let Some(channel) = self.store.channels.get(&dialog.channel).filter(|c| c.kind == channel_kind::GROUP_DM) else {
            return;
        };
        let name = self.store.label(channel);
        let t = self.theme.clone();
        let mut cancel = ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));
        let mut confirm = false;
        cancel |= super::guild_pages::modal_frame(ctx, &t, "leave_group", LEAVE_W, |ui| {
            let plain = egui::TextFormat {
                font_id: FontId::proportional(16.0),
                color: t.header_secondary,
                line_height: Some(20.0),
                ..Default::default()
            };
            let bold_fmt = egui::TextFormat {
                font_id: FontId::new(16.0, egui::FontFamily::Name(crate::style::BOLD.into())),
                ..plain.clone()
            };
            let mut job = egui::text::LayoutJob::default();
            job.append("Are you sure you want to leave ", 0.0, plain.clone());
            job.append(&name, 0.0, bold_fmt);
            job.append("? You won't be able to rejoin this group unless you are re-invited.", 0.0, plain);
            job.wrap.max_width = LEAVE_W - 48.0;
            let body = ui.fonts(|f| f.layout_job(job));
            let check_label = ui.painter().layout_no_wrap(
                "Leave without notifying other members".into(),
                FontId::proportional(14.0),
                t.text_normal,
            );
            let body_h = body.size().y;
            let h = 56.0 + body_h + 12.0 + 24.0 + 16.0 + 40.0 + 24.0;
            let (r, _) = ui.allocate_exact_size(vec2(LEAVE_W, h), Sense::hover());
            let left = r.left() + 24.0;

            let title_font = super::guild_pages::strong(20.0);
            let title_text = leave_group_title(&name);
            let title_elided = super::elide_text_emoji(ui, &title_text, &title_font, LEAVE_W - 24.0 - 56.0);
            super::paint_text_emoji(ui, ui.painter(), pos2(left, r.top() + 36.0), &title_elided, title_font, t.header_primary);

            let x = Rect::from_min_size(pos2(r.right() - 8.0 - 40.0, r.top() + 8.0), vec2(40.0, 40.0));
            let xr = ui.interact(x, egui::Id::new("leave_group_close"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            if xr.hovered() {
                ui.painter().rect_filled(x, 8.0, t.bg_hover);
            }
            ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(14.0), if xr.hovered() { t.header_primary } else { t.interactive_normal });
            cancel |= xr.clicked();

            ui.painter().galley(pos2(left, r.top() + 56.0), body, t.header_secondary);

            let check_w = (24.0 + 8.0 + check_label.size().x).min(LEAVE_W - 48.0);
            let check_row = Rect::from_min_size(pos2(left, r.top() + 56.0 + body_h + 12.0), vec2(check_w, 24.0));
            let cr = ui.interact(check_row, egui::Id::new("leave_group_silent"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            let b = Rect::from_min_size(check_row.min + vec2(2.0, 2.0), vec2(20.0, 20.0));
            if dialog.silent {
                ui.painter().rect_filled(b, 4.0, BRAND);
                let p = |px: f32, py: f32| b.min + vec2(px, py);
                ui.painter().line_segment([p(5.0, 10.5), p(8.5, 14.0)], Stroke::new(2.0_f32, Color32::WHITE));
                ui.painter().line_segment([p(8.5, 14.0), p(15.0, 6.5)], Stroke::new(2.0_f32, Color32::WHITE));
            } else {
                ui.painter().rect_stroke(b, 4.0, Stroke::new(1.5_f32, t.interactive_normal));
            }
            ui.painter().galley(pos2(b.right() + 10.0, check_row.center().y - check_label.size().y / 2.0), check_label, t.text_normal);
            if cr.clicked() {
                dialog.silent = !dialog.silent;
            }

            let bw = (LEAVE_W - 48.0 - 8.0) / 2.0;
            let no = Rect::from_min_size(pos2(left, r.bottom() - 24.0 - 40.0), vec2(bw, 40.0));
            let yes = no.translate(vec2(bw + 8.0, 0.0));
            let nr = ui.interact(no, egui::Id::new("leave_group_cancel"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            ui.painter().rect(no, 8.0, overlay(if nr.hovered() { 0.2 } else { 0.12 }), Stroke::new(1.0_f32, rgba(151, 151, 159, 10)));
            ui.painter().text(no.center(), Align2::CENTER_CENTER, "Cancel", medium(16.0), t.header_primary);
            cancel |= nr.clicked();

            let yr = ui.interact(yes, egui::Id::new("leave_group_ok"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            let fill = if yr.hovered() { CRITICAL_HOVER } else { CRITICAL };
            ui.painter().rect(yes, 8.0, fill, Stroke::new(1.0_f32, rgba(255, 255, 255, 20)));
            ui.painter().text(yes.center(), Align2::CENTER_CENTER, "Leave Group", medium(16.0), Color32::WHITE);
            confirm |= yr.clicked();
        });
        if confirm {
            log::info!("group dm: leaving {} (silent={})", dialog.channel, dialog.silent);
            self.backend.send(crate::backend::Command::LeaveGroup { channel: dialog.channel, silent: dialog.silent });
        } else if !cancel {
            self.group_leave = Some(dialog);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn leave_title_quotes_group_name() {
        assert_eq!(leave_group_title("crab rave planning"), "Leave 'crab rave planning'");
        assert_eq!(leave_group_title("Ferris, Corro"), "Leave 'Ferris, Corro'");
    }
}