Skip to content

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

35.2 KB
Raw Blame
//! The server-name dropdown (Discord's guild menu), channel editing and the
//! small dialogs they open.

use crate::app::RustCord;
use super::guild_menu::GuildAct;
use crate::backend::Command;
use crate::features::ServerDialog;
use crate::style::{bold, icon, icon_font, overlay};
use discord::model::{channel_kind, permissions, Id};
use eframe::egui::{
    self, epaint::Shadow, pos2, vec2, Align2, Button, Color32, FontId, Frame, Key, Margin, Order, Rect, RichText, Sense,
    Stroke, TextEdit, Ui,
};
use serde_json::json;

fn shadow() -> Shadow {
    Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) }
}

/// Slowmode choices, like Discord's slider stops.
const SLOWMODE: &[(u32, &str)] = &[
    (0, "Off"),
    (5, "5s"),
    (10, "10s"),
    (15, "15s"),
    (30, "30s"),
    (60, "1m"),
    (120, "2m"),
    (300, "5m"),
    (600, "10m"),
    (900, "15m"),
    (1800, "30m"),
    (3600, "1h"),
    (7200, "2h"),
    (21600, "6h"),
];

impl RustCord {
    /// Server header click: open / close the dropdown.
    pub fn toggle_server_menu(&mut self, guild: Id) {
        self.server_menu = match self.server_menu {
            Some((g, _)) if g == guild => None,
            _ => Some((guild, self.ctx.cumulative_pass_nr())),
        };
    }

    /// Discord's server dropdown, under the sidebar header. Items and their
    /// conditions follow Discord's GuildHeaderPopout (2026-11-23); what they do
    /// is shared with the server icon's right-click menu (`guild_menu.rs`).
    pub fn server_menu_ui(&mut self, ctx: &egui::Context, anchor: Rect) {
        let Some((guild, opened)) = self.server_menu else { return };
        let Some(gs) = self.store.guilds.get(&guild) else {
            self.server_menu = None;
            return;
        };
        let t = self.theme.clone();
        let perms = self.store.guild_perms(guild);
        let has = |p: u64| perms & p != 0;
        let feature = |f: &str| super::guild_pages::has_feature(&gs.guild, f);
        let community = feature("COMMUNITY");
        let owner = gs.guild.owner_id.is_some() && gs.guild.owner_id == self.store.me_id();
        let hide_muted = self.store.hide_muted.contains(&guild);
        let show_all = self.store.guild_notify.get(&guild).is_none_or(|n| n.flags & crate::store::GuildNotify::OPT_IN_CHANNELS_ON == 0);
        // Discord lists "Server Tag" whenever the server has one to adopt.
        let tag = gs.guild.tag().map(|(t, b)| (t.to_string(), b));
        let can_settings = self.server_settings_pages_any(guild);
        // Discord lists Active Threads only while the server has some.
        let threads = self.store.channels.values().any(|c| c.guild_id == Some(guild) && channel_kind::is_thread(c.kind) && !c.archived());
        // Security Actions / Report Raid: Community servers, moderators.
        let moderator = community && has(super::guild_menu::INCIDENT_PERMS);
        let mut picked: Option<GuildAct> = None;
        let mut tag_page = false;
        let medium14 = crate::style::medium(14.0);

        let area = egui::Area::new(egui::Id::new("server_menu"))
            .order(Order::Foreground)
            .fixed_pos(pos2(anchor.left() + 8.0, anchor.bottom() + 4.0))
            .constrain(true)
            .show(ctx, |ui| {
                Frame::none()
                    .fill(t.bg_floating)
                    .rounding(8.0)
                    .stroke(Stroke::new(1.0_f32, t.border_subtle))
                    .shadow(shadow())
                    .inner_margin(Margin::symmetric(6.0, 6.0))
                    .show(ui, |ui| {
                        ui.set_width(anchor.width() - 28.0);
                        ui.spacing_mut().item_spacing.y = 0.0;
                        // glyph, label, danger?, checkbox state; true when clicked
                        let row = |ui: &mut Ui, glyph: &str, label: &str, danger: bool, check: Option<bool>| -> bool {
                            let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());
                            let color = if danger { t.danger } else if resp.hovered() { t.header_primary } else { t.interactive_normal };
                            if resp.hovered() {
                                ui.painter().rect_filled(r, 4.0, if danger { t.danger.gamma_multiply(0.15) } else { overlay(0.16) });
                            }
                            super::paint_icon(ui.painter(), Rect::from_center_size(r.left_center() + vec2(14.0, 0.0), vec2(18.0, 18.0)), glyph, color);
                            // Long labels end in "…" before the checkbox, as Discord's do.
                            let room = if check.is_some() { 44.0 } else { 12.0 };
                            let mut job = egui::text::LayoutJob::simple_singleline(label.to_owned(), medium14.clone(), color);
                            job.wrap = egui::text::TextWrapping { max_width: (r.width() - 32.0 - room).max(0.0), max_rows: 1, break_anywhere: true, overflow_character: Some('…') };
                            let g = ui.painter().layout_job(job);
                            ui.painter().galley(pos2(r.left() + 32.0, r.center().y - g.size().y / 2.0), g, color);
                            if let Some(on) = check {
                                let b = Rect::from_center_size(r.right_center() - vec2(16.0, 0.0), vec2(18.0, 18.0));
                                if on {
                                    ui.painter().rect_filled(b, 4.0, t.accent);
                                    ui.painter().text(b.center(), Align2::CENTER_CENTER, icon::CHECK, icon_font(11.0), Color32::WHITE);
                                } else {
                                    ui.painter().rect_stroke(b, 4.0, Stroke::new(1.5_f32, t.interactive_normal));
                                }
                            }
                            resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
                        };
                        let sep = |ui: &mut Ui| {
                            ui.add_space(4.0);
                            let y = ui.cursor().top();
                            ui.painter().hline(ui.max_rect().x_range().shrink(6.0), y, Stroke::new(1.0_f32, t.border_subtle));
                            ui.add_space(4.0);
                        };
                        let mut pick = |on: bool, act: GuildAct| {
                            if on {
                                picked = Some(act);
                            }
                        };

                        pick(row(ui, icon::BOOST, "Server Boost", false, None), GuildAct::Boost);
                        // The tag's chip in front of "Server Tag".
                        if let Some((tag, badge)) = &tag {
                            let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());
                            let color = if resp.hovered() { t.header_primary } else { t.interactive_normal };
                            if resp.hovered() {
                                ui.painter().rect_filled(r, 4.0, overlay(0.16));
                            }
                            let p = ui.painter();
                            let chip_w = super::tag_adopt::tag_chip(ui, p, &t, pos2(r.left() + 8.0, r.center().y - 9.0), tag, badge.as_deref(), 16.0, 12.0);
                            p.text(pos2(r.left() + 8.0 + chip_w + 8.0, r.center().y), Align2::LEFT_CENTER, "Server Tag", medium14.clone(), color);
                            tag_page |= resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                        }
                        sep(ui);
                        if has(permissions::CREATE_INSTANT_INVITE) {
                            pick(row(ui, icon::INVITE, "Invite to Server", false, None), GuildAct::Invite);
                        }
                        if can_settings {
                            pick(row(ui, icon::SETTINGS, "Server Settings", false, None), GuildAct::Settings(None));
                        }
                        // View Server Insights (1 << 19), Community servers only.
                        if has(1 << 19) && community {
                            pick(row(ui, icon::BADGE, "Server Insights", false, None), GuildAct::Insights);
                        }
                        if has(permissions::MANAGE_CHANNELS) {
                            pick(row(ui, icon::ADD, "Create Channel", false, None), GuildAct::CreateChannel);
                            pick(row(ui, icon::FOLDER, "Create Category", false, None), GuildAct::CreateCategory);
                        }
                        if has(super::guild_pages::MANAGE_EVENTS | super::guild_pages::CREATE_EVENTS) {
                            pick(row(ui, icon::CALENDAR, "Create Event", false, None), GuildAct::CreateEvent);
                        }
                        if threads {
                            pick(row(ui, icon::THREADS, "Active Threads", false, None), GuildAct::ActiveThreads);
                        }
                        pick(row(ui, icon::APPS, "App Directory", false, None), GuildAct::AppDirectory);
                        sep(ui);
                        if community {
                            pick(row(ui, icon::PEOPLE, "Show All Channels", false, Some(show_all)), GuildAct::ShowAllChannels);
                        }
                        pick(row(ui, icon::BELL, "Notification Settings", false, None), GuildAct::Notifications);
                        pick(row(ui, icon::SHIELD, "Privacy Settings", false, None), GuildAct::Privacy);
                        sep(ui);
                        pick(row(ui, icon::EDIT, "Edit Per-server Profile", false, None), GuildAct::PerServerProfile);
                        pick(row(ui, icon::EYE_SLASH, "Hide Muted Channels", false, Some(hide_muted)), GuildAct::HideMuted);
                        if moderator || !owner {
                            sep(ui);
                        }
                        if moderator {
                            pick(row(ui, icon::SHIELD, "Security Actions", true, None), GuildAct::SecurityActions);
                            pick(row(ui, icon::SHIELD, "Report Raid", true, None), GuildAct::ReportRaid);
                        }
                        if !owner {
                            pick(row(ui, icon::LEAVE, "Leave Server", true, None), GuildAct::Leave);
                        }
                        sep(ui);
                        pick(row(ui, icon::ID, "Copy Server ID", false, None), GuildAct::CopyId);
                    });
            });

        let close_click = area.response.clicked_elsewhere() && ctx.cumulative_pass_nr() > opened + 1;
        if tag_page {
            self.server_menu = None;
            self.open_tag_adopt(guild);
            return;
        }
        match picked {
            None => {
                if close_click || ctx.input(|i| i.key_pressed(Key::Escape)) {
                    self.server_menu = None;
                }
            }
            Some(act) => {
                self.server_menu = None;
                self.guild_act(guild, act);
            }
        }
    }

    /// Whether any Server Settings page is open to you here.
    fn server_settings_pages_any(&self, guild: Id) -> bool {
        super::guild_menu::SETTINGS_PAGES.iter().any(|(k, _)| self.server_settings_has(guild, k))
    }

    /// Channel gear: edit the channel.
    pub fn open_channel_editor(&mut self, channel: Id) {
        let Some(c) = self.store.channels.get(&channel) else { return };
        self.server_dialog = Some(ServerDialog::EditChannel {
            channel,
            name: c.name.clone().unwrap_or_default(),
            topic: c.topic.clone().unwrap_or_default(),
            slowmode: c.rate_limit_per_user,
            nsfw: c.nsfw,
            confirm_delete: false,
        });
    }

    /// The dialog opened from the menu / gear, and the invite link box.
    pub fn server_dialog_ui(&mut self, ctx: &egui::Context) {
        let t = self.theme.clone();
        if self.invite.is_some() {
            self.invite_modal_ui(ctx);
            return;
        }

        let Some(mut d) = self.server_dialog.take() else { return };
        let mut done = ctx.input(|i| i.key_pressed(Key::Escape));
        match &mut d {
            ServerDialog::EditChannel { channel, name, topic, slowmode, nsfw, confirm_delete } => {
                let channel = *channel;
                let is_text = self.store.channels.get(&channel).is_some_and(|c| channel_kind::is_text(c.kind));
                // Clicking off closes it only while nothing here is changed.
                let unchanged = !*confirm_delete
                    && self.store.channels.get(&channel).is_some_and(|c| {
                        c.name.as_deref().unwrap_or_default() == name.as_str()
                            && c.topic.as_deref().unwrap_or_default() == topic.as_str()
                            && c.rate_limit_per_user == *slowmode
                            && c.nsfw == *nsfw
                    });
                let off = modal(ctx, &t, "Channel Settings", |ui| {
                    field(ui, &t, "CHANNEL NAME");
                    ui.add(TextEdit::singleline(name).desired_width(f32::INFINITY).margin(vec2(8.0, 6.0)));
                    if is_text {
                        ui.add_space(10.0);
                        field(ui, &t, "CHANNEL TOPIC");
                        ui.add(TextEdit::multiline(topic).desired_width(f32::INFINITY).desired_rows(3).char_limit(1024).hint_text("Let everyone know how to use this channel!"));
                        ui.add_space(10.0);
                        field(ui, &t, "SLOWMODE");
                        ui.horizontal_wrapped(|ui| {
                            for (secs, label) in SLOWMODE {
                                if ui.selectable_label(*slowmode == *secs, *label).clicked() {
                                    *slowmode = *secs;
                                }
                            }
                        });
                        ui.add_space(10.0);
                        ui.checkbox(nsfw, "Age-Restricted Channel");
                    }
                    ui.add_space(16.0);
                    ui.horizontal(|ui| {
                        if *confirm_delete {
                            ui.label(RichText::new("Delete this channel for good?").color(t.danger));
                            if ui.add(Button::new(bold("Delete").color(Color32::WHITE)).fill(t.danger)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                self.backend.send(Command::DeleteChannel(channel));
                                done = true;
                            }
                            if ui.button("Keep it").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                *confirm_delete = false;
                            }
                        } else if ui.add(Button::new(RichText::new("Delete Channel").color(t.danger)).frame(false)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            *confirm_delete = true;
                        }
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            if ui.add(Button::new(bold("Save Changes").color(Color32::WHITE)).fill(t.accent).rounding(6.0)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                let mut patch = json!({ "name": name.trim() });
                                if is_text {
                                    patch["topic"] = json!(topic.trim());
                                    patch["rate_limit_per_user"] = json!(slowmode);
                                    patch["nsfw"] = json!(nsfw);
                                }
                                self.backend.send(Command::EditChannel { channel, patch });
                                done = true;
                            }
                            if ui.button("Cancel").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                done = true;
                            }
                        });
                    });
                });
                done |= off && unchanged;
            }
            ServerDialog::CreateChannel { guild, parent, name, kind, private, category } => {
                let (guild, parent, category) = (*guild, *parent, *category);
                let parent_name = parent.and_then(|p| self.store.channels.get(&p)).and_then(|c| c.name.clone());
                let me = self.store.me_id();
                let admin = self.store.has_perm(guild, permissions::ADMINISTRATOR);
                let mut create = false;
                done |= create_channel_dialog(ctx, &t, category, parent_name.as_deref(), name, kind, private, &mut create);
                if create {
                    let k = if category { 4 } else { *kind };
                    let mut body = json!({ "name": name.trim(), "type": k });
                    if let Some(p) = parent.filter(|_| !category) {
                        body["parent_id"] = json!(p.to_string());
                    }
                    if *private {
                        // Hidden from @everyone; you keep access if you aren't an admin.
                        let mut ows = vec![json!({ "id": guild.to_string(), "type": 0, "allow": "0", "deny": permissions::VIEW_CHANNEL.to_string() })];
                        if let (false, Some(me)) = (admin, me) {
                            ows.push(json!({ "id": me.to_string(), "type": 1, "allow": permissions::VIEW_CHANNEL.to_string(), "deny": "0" }));
                        }
                        body["permission_overwrites"] = json!(ows);
                    }
                    self.backend.send(Command::CreateChannel { guild, body });
                    done = true;
                }
            }
            ServerDialog::Nickname { guild, nick, pronouns, bio } => {
                let guild = *guild;
                let me = self.store.me_id();
                // The server's own pronouns and bio are Nitro perks.
                let nitro = self.store.me.as_ref().and_then(|u| u.premium_type).unwrap_or(0) > 0;
                // Without Change Nickname the box stays, greyed out, as in Discord.
                let can_nick = self.store.guild_perms(guild) & permissions::CHANGE_NICKNAME != 0;
                let profile = me.and_then(|me| self.profiles.get(&(me, Some(guild)))).and_then(|p| p.as_ref().ok()).and_then(|p| p.guild_member_profile.clone());
                let loaded = me.is_some_and(|me| self.profiles.contains_key(&(me, Some(guild))));
                if pronouns.is_none() && loaded {
                    *pronouns = Some(profile.as_ref().and_then(|p| p.pronouns.clone()).unwrap_or_default());
                    *bio = Some(profile.as_ref().and_then(|p| p.bio.clone()).unwrap_or_default());
                }
                let (was_pronouns, was_bio) = (profile.as_ref().and_then(|p| p.pronouns.clone()).unwrap_or_default(), profile.as_ref().and_then(|p| p.bio.clone()).unwrap_or_default());
                // Clicking off closes it only while nothing is changed.
                let now = me.and_then(|me| self.store.members.get(&(guild, me))).and_then(|m| m.nick.as_deref()).unwrap_or_default();
                let unchanged = now == nick.as_str() && pronouns.as_ref().is_none_or(|p| *p == was_pronouns) && bio.as_ref().is_none_or(|b| *b == was_bio);
                let off = modal(ctx, &t, "Edit Per-server Profile", |ui| {
                    field(ui, &t, "SERVER NICKNAME");
                    ui.add_enabled(can_nick, TextEdit::singleline(nick).desired_width(f32::INFINITY).char_limit(32).margin(vec2(8.0, 6.0)).hint_text("Your name in this server"));
                    if !can_nick {
                        ui.add_space(4.0);
                        ui.label(RichText::new("You don't have permission to change your nickname in this server.").size(12.0).color(t.text_muted));
                    }
                    if nitro {
                        if let (Some(p), Some(b)) = (pronouns.as_mut(), bio.as_mut()) {
                            ui.add_space(12.0);
                            field(ui, &t, "PRONOUNS");
                            ui.add(TextEdit::singleline(p).desired_width(f32::INFINITY).char_limit(40).margin(vec2(8.0, 6.0)).hint_text("Add your pronouns"));
                            ui.add_space(12.0);
                            field(ui, &t, "ABOUT ME");
                            ui.add(TextEdit::multiline(b).desired_width(f32::INFINITY).desired_rows(4).char_limit(190).hint_text("You can use markdown and links if you'd like."));
                        } else {
                            ui.add_space(8.0);
                            ui.spinner();
                        }
                    }
                    ui.add_space(16.0);
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if ui.add(Button::new(bold("Save").color(Color32::WHITE)).fill(t.accent).rounding(6.0)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            let mut body = json!({});
                            if can_nick {
                                // An empty nickname clears it.
                                let n = nick.trim();
                                body["nick"] = json!((!n.is_empty()).then_some(n));
                            }
                            if let (true, Some(p), Some(b)) = (nitro, pronouns.as_ref(), bio.as_ref()) {
                                if *p != was_pronouns {
                                    body["pronouns"] = json!(p.trim());
                                }
                                if *b != was_bio {
                                    body["bio"] = json!(b.trim());
                                }
                            }
                            if let Some(me) = me {
                                // Fresh copy next time the profile is shown.
                                self.profiles.remove(&(me, Some(guild)));
                                self.profile_requested.remove(&(me, Some(guild)));
                            }
                            // (Nothing to save when only the greyed-out nickname is there.)
                            if body.as_object().is_some_and(|b| !b.is_empty()) {
                                self.api("pp:save", reqwest::Method::PATCH, format!("/guilds/{guild}/members/@me"), Some(body));
                            }
                            done = true;
                        }
                        if ui.button("Cancel").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            done = true;
                        }
                    });
                });
                done |= off && unchanged;
            }
            ServerDialog::LeaveServer { guild } => {
                let guild = *guild;
                let name = self.store.guilds.get(&guild).map(|g| g.guild.name.clone()).unwrap_or_default();
                let off = modal(ctx, &t, &format!("Leave '{name}'"), |ui| {
                    ui.label(RichText::new("You won't be able to rejoin this server unless you are re-invited.").color(t.text_normal));
                    ui.add_space(16.0);
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if ui.add(Button::new(bold("Leave Server").color(Color32::WHITE)).fill(t.danger).rounding(6.0)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            self.backend.send(Command::LeaveGuild(guild));
                            done = true;
                        }
                        if ui.button("Cancel").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            done = true;
                        }
                    });
                });
                done |= off;
            }
            ServerDialog::DeleteChannel { channel, category } => {
                let (channel, category) = (*channel, *category);
                let Some(name) = self.store.channels.get(&channel).map(crate::store::Store::channel_label) else { return };
                let (title, what) = if category { ("Delete Category", name) } else { ("Delete Channel", format!("#{name}")) };
                let off = modal(ctx, &t, title, |ui| {
                    ui.label(RichText::new(format!("Are you sure you want to delete {what}? This cannot be undone.")).color(t.text_normal));
                    ui.add_space(16.0);
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if ui.add(Button::new(bold(title).color(Color32::WHITE)).fill(t.danger).rounding(6.0)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            self.backend.send(Command::DeleteChannel(channel));
                            done = true;
                        }
                        if ui.button("Cancel").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            done = true;
                        }
                    });
                });
                done |= off;
            }
        }
        if !done {
            self.server_dialog = Some(d);
        }
    }
}

/// Discord's Create Channel / Create Category dialog. Returns true to close;
/// sets `create` when "Create Channel" is pressed.
#[allow(clippy::too_many_arguments)]
fn create_channel_dialog(
    ctx: &egui::Context,
    t: &crate::style::Theme,
    category: bool,
    parent: Option<&str>,
    name: &mut String,
    kind: &mut u8,
    private: &mut bool,
    create: &mut bool,
) -> bool {
    const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);
    let strong = |s: f32| FontId::new(s, egui::FontFamily::Name(crate::style::BOLD.into()));
    let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
    dim(ctx, 170);
    // Clicking off closes it only while no name is typed.
    let unnamed = name.is_empty();
    let area = egui::Area::new(egui::Id::new("create_channel_dialog")).order(Order::Tooltip).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
        Frame::none()
            .fill(t.bg_secondary)
            .rounding(12.0)
            .stroke(Stroke::new(1.0_f32, t.border_subtle))
            .shadow(shadow())
            .inner_margin(Margin::same(24.0))
            .show(ui, |ui| {
                ui.set_width(412.0);
                ui.spacing_mut().item_spacing.y = 0.0;
                // Title, "in <category>", close.
                let top = ui.cursor().min;
                ui.label(RichText::new(if category { "Create Category" } else { "Create Channel" }).font(strong(20.0)).color(t.header_primary));
                if let Some(p) = parent.filter(|_| !category) {
                    ui.add_space(6.0);
                    ui.label(RichText::new(format!("in {p}")).size(14.0).color(t.text_muted));
                }
                let x = Rect::from_center_size(pos2(top.x + 412.0 - 10.0, top.y + 12.0), vec2(24.0, 24.0));
                let xr = ui.interact(x, egui::Id::new("create_channel_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(15.0), if xr.hovered() { t.header_primary } else { t.interactive_normal });
                close |= xr.clicked();
                ui.add_space(24.0);

                if !category {
                    ui.label(RichText::new("Channel Type").font(strong(16.0)).color(t.header_primary));
                    ui.add_space(12.0);
                    for (k, title, desc) in [
                        (0u8, "Text", "Send messages, images, GIFs, emoji, opinions and puns"),
                        (2, "Voice", "Hang out together with voice, video and screen share"),
                        (15, "Forum", "Create a space for organised discussions"),
                    ] {
                        let (row, resp) = ui.allocate_exact_size(vec2(412.0, 58.0), Sense::click());
                        let sel = *kind == k;
                        let c = pos2(row.left() + 10.0, row.top() + 14.0);
                        ui.painter().circle_stroke(c, 9.0, Stroke::new(2.0_f32, if sel { BRAND } else { t.interactive_normal }));
                        if sel {
                            ui.painter().circle_filled(c, 9.0, BRAND);
                            ui.painter().circle_filled(c, 3.5, Color32::WHITE);
                        }
                        let ix = row.left() + 42.0;
                        let fg = if resp.hovered() || sel { t.header_primary } else { t.text_normal };
                        let glyph_rect = Rect::from_center_size(pos2(ix, c.y), vec2(18.0, 18.0));
                        match k {
                            0 => super::paint_hashtag(ui.painter(), glyph_rect, fg),
                            k => super::paint_icon(ui.painter(), glyph_rect, super::channel_icon(k), fg),
                        }
                        ui.painter().text(pos2(ix + 14.0, c.y), Align2::LEFT_CENTER, title, strong(16.0), fg);
                        ui.painter().text(pos2(row.left() + 32.0, c.y + 23.0), Align2::LEFT_CENTER, desc, FontId::proportional(14.0), t.text_muted);
                        if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                            *kind = k;
                        }
                    }
                    ui.add_space(10.0);
                }

                ui.label(RichText::new(if category { "Category Name" } else { "Channel Name" }).font(strong(16.0)).color(t.header_primary));
                ui.add_space(10.0);
                let id = egui::Id::new("create_channel_name");
                let focused = ui.memory(|m| m.has_focus(id));
                Frame::none()
                    .fill(Color32::from_black_alpha(46))
                    .stroke(Stroke::new(if focused { 2.0_f32 } else { 1.0_f32 }, if focused { BRAND } else { overlay(0.2) }))
                    .rounding(8.0)
                    .inner_margin(Margin { left: 12.0, right: 12.0, top: 9.0, bottom: 9.0 })
                    .show(ui, |ui| {
                        ui.horizontal(|ui| {
                            if !category {
                                let (g, _) = ui.allocate_exact_size(vec2(18.0, 20.0), Sense::hover());
                                match *kind {
                                    k @ (2 | 15) => super::paint_icon(ui.painter(), Rect::from_center_size(g.center(), vec2(16.0, 16.0)), super::channel_icon(k), t.text_muted),
                                    _ => super::paint_hashtag(ui.painter(), Rect::from_center_size(g.center(), vec2(16.0, 16.0)), t.text_muted),
                                }
                                ui.add_space(6.0);
                            }
                            let r = ui.add(
                                TextEdit::singleline(name)
                                    .id(id)
                                    .frame(false)
                                    .desired_width(ui.available_width())
                                    .font(FontId::proportional(16.0))
                                    .hint_text(if category { "New Category" } else if *kind == 2 { "New Voice Channel" } else { "new-channel" }),
                            );
                            if !focused && name.is_empty() {
                                r.request_focus();
                            }
                            // Text and forum names are lowercase-with-dashes, like Discord does as you type.
                            if r.changed() && !category && *kind != 2 {
                                *name = name.to_lowercase().replace(' ', "-");
                            }
                            *create |= r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) && !name.trim().is_empty();
                        });
                    });
                ui.add_space(20.0);

                // Private toggle.
                ui.horizontal(|ui| {
                    ui.label(RichText::new("\u{E72E}").font(icon_font(14.0)).color(t.header_primary));
                    ui.add_space(4.0);
                    ui.label(RichText::new(if category { "Private Category" } else { "Private Channel" }).font(strong(15.0)).color(t.header_primary));
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        super::toggle_switch(ui, private, t);
                    });
                });
                ui.add_space(6.0);
                let desc = if category {
                    "By making a category private, only selected members and roles will be able to view this category. Synced channels in this category will automatically match to this setting."
                } else {
                    "Only selected members and roles will be able to view this channel."
                };
                ui.add(egui::Label::new(RichText::new(desc).size(13.0).color(t.text_muted)).wrap());
                ui.add_space(24.0);

                // Cancel / Create.
                ui.horizontal(|ui| {
                    ui.spacing_mut().item_spacing.x = 8.0;
                    let w = (412.0 - 8.0) / 2.0;
                    let cancel = Button::new(RichText::new("Cancel").font(strong(15.0)).color(t.header_primary)).fill(overlay(0.12)).rounding(8.0).min_size(vec2(w, 40.0));
                    close |= ui.add(cancel).clicked();
                    let ok = !name.trim().is_empty();
                    let fill = if ok { BRAND } else { BRAND.gamma_multiply(0.5) };
                    let label = if category { "Create Category" } else { "Create Channel" };
                    let b = Button::new(RichText::new(label).font(strong(15.0)).color(Color32::WHITE)).fill(fill).rounding(8.0).min_size(vec2(w, 40.0));
                    *create |= ui.add_enabled(ok, b).clicked();
                });
            });
    });
    close || (unnamed && super::pressed_outside(ctx, area.response.rect))
}

/// Small section label above a field.
fn field(ui: &mut Ui, t: &crate::style::Theme, label: &str) {
    ui.label(bold(label).size(12.0).color(t.header_secondary));
    ui.add_space(4.0);
}

/// The dimmed app behind a dialog. It takes the pointer: a click off the
/// dialog stops here.
fn dim(ctx: &egui::Context, alpha: u8) {
    let screen = ctx.screen_rect();
    egui::Area::new(egui::Id::new("server_dialog_dim")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
        ui.allocate_exact_size(screen.size(), Sense::click());
        ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha(alpha));
    });
}

/// Centred dialog over a dimmed window. Returns whether the mouse was pressed
/// off it (on the dimmed app).
fn modal(ctx: &egui::Context, t: &crate::style::Theme, title: &str, body: impl FnOnce(&mut Ui)) -> bool {
    dim(ctx, 150);
    let area = egui::Area::new(egui::Id::new("server_dialog")).order(Order::Tooltip).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
        // Discord's modal card: surface-high, 1 px border-normal, 12 px corners.
        Frame::none()
            .fill(t.surface_high)
            .rounding(12.0)
            .stroke(Stroke::new(1.0_f32, super::modal_border(t)))
            .shadow(shadow())
            .inner_margin(Margin::symmetric(20.0, 18.0))
            .show(ui, |ui| {
                ui.set_width(440.0);
                ui.label(bold(title).size(20.0).color(t.header_primary));
                ui.add_space(14.0);
                body(ui);
            });
    });
    super::pressed_outside(ctx, area.response.rect)
}