Skip to content

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

32.0 KB
Raw Blame
//! Discord's "Add a Server" dialog, opened from the server list's "+": make a
//! server from scratch or from one of Discord's templates, or join one with
//! an invite. Text, sizes, icons and the requests sent are Discord web's
//! (read from its live page, 2026-11).

use crate::app::RustCord;
use crate::backend::Command;
use crate::features::AddServerRequest;
use crate::style::{icon, icon_font, medium, Theme};
use discord::model::Id;
use eframe::egui::{
    self, load::Bytes, pos2, text::LayoutJob, vec2, Align, Align2, Color32, FontFamily, FontId, ImageSource, Key, Order, Pos2, Rect, ScrollArea,
    Sense, Stroke, TextEdit, Ui,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};

/// The dialog's width, border included.
const W: f32 = 444.0;
const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Step {
    /// "Create Your Server": Create My Own, the templates, Join a Server.
    Landing,
    /// "Tell Us More About Your Server" (friends or community).
    Intent,
    /// "Customize Your Server": icon and name.
    Customize,
    /// "Join a Server": the invite link.
    Join,
}

/// The open dialog.
pub struct AddServer {
    step: Step,
    /// Index into [`TEMPLATES`].
    template: usize,
    name: String,
    /// The default name has been put in (`name` is the person's from then on).
    named: bool,
    /// The page whose text field last took the keyboard (from the message
    /// box behind the dialog, say).
    keyboard: Option<Step>,
    icon: Option<PickedIcon>,
    invite: String,
    error: Option<String>,
    /// A request is on its way (buttons wait).
    pub busy: bool,
}

/// A server icon chosen for the new server.
struct PickedIcon {
    data_uri: String,
    uri: String,
    bytes: Arc<[u8]>,
}

/// One of the landing page's choices: label, pixel-art icon, and what
/// Discord's client sends for it besides the name and icon.
struct Template {
    label: &'static str,
    icon: (&'static str, &'static [u8]),
    body: &'static str,
}

/// "Create My Own" first, then "Start from a template" in Discord's order.
/// The bodies are exactly what Discord web posts (School Club's repeated
/// channel id included).
const TEMPLATES: [Template; 7] = [
    Template {
        label: "Create My Own",
        icon: ("create", include_bytes!("../../assets/add-server/create.svg")),
        body: r#"{"channels":[],"system_channel_id":null,"guild_template_code":"2TffvPucqHkN"}"#,
    },
    Template {
        label: "Gaming",
        icon: ("gaming", include_bytes!("../../assets/add-server/gaming.svg")),
        body: r#"{"channels":[{"id":"00","parent_id":null,"name":"Text Channels","type":4},{"id":"01","parent_id":"00","name":"general","type":0},{"id":"02","parent_id":"00","name":"clips-and-highlights","type":0},{"id":"10","parent_id":null,"name":"Voice Channels","type":4},{"id":"11","parent_id":"10","name":"Lobby","type":2},{"id":"12","parent_id":"10","name":"Gaming","type":2}],"system_channel_id":"01","guild_template_code":"hvtBQMfw6uSJ"}"#,
    },
    Template {
        label: "Friends",
        icon: ("friends", include_bytes!("../../assets/add-server/friends.svg")),
        body: r#"{"channels":[{"id":"00","parent_id":null,"name":"Text Channels","type":4},{"id":"01","parent_id":"00","name":"general","type":0},{"id":"02","parent_id":"00","name":"games","type":0},{"id":"03","parent_id":"00","name":"music","type":0},{"id":"10","parent_id":null,"name":"Voice Channels","type":4},{"id":"11","parent_id":"10","name":"Lounge","type":2},{"id":"12","parent_id":"10","name":"Stream Room","type":2}],"system_channel_id":"01","guild_template_code":"hgM48av5Q69A"}"#,
    },
    Template {
        label: "Study Group",
        icon: ("study", include_bytes!("../../assets/add-server/study.svg")),
        body: r#"{"channels":[{"id":"00","parent_id":null,"name":"Information","type":4},{"id":"01","parent_id":"00","name":"welcome-and-rules","type":0},{"id":"02","parent_id":"00","name":"notes-resources","type":0},{"id":"10","parent_id":null,"name":"Text Channels","type":4},{"id":"11","parent_id":"10","name":"general","type":0},{"id":"12","parent_id":"10","name":"homework-help","type":0},{"id":"13","parent_id":"10","name":"session-planning","type":0},{"id":"14","parent_id":"10","name":"off-topic","type":0},{"id":"20","parent_id":null,"name":"Voice Channels","type":4},{"id":"21","parent_id":"20","name":"Lounge","type":2},{"id":"22","parent_id":"20","name":"Study Room 1","type":2},{"id":"23","parent_id":"20","name":"Study Room 2","type":2}],"system_channel_id":"11","guild_template_code":"FbwUwRp4j8Es"}"#,
    },
    Template {
        label: "School Club",
        icon: ("school", include_bytes!("../../assets/add-server/school.svg")),
        body: r#"{"channels":[{"id":"00","parent_id":null,"name":"Information","type":4},{"id":"01","parent_id":"00","name":"welcome-and-rules","type":0},{"id":"02","parent_id":"00","name":"announcements","type":0},{"id":"03","parent_id":"00","name":"resources","type":0},{"id":"10","parent_id":null,"name":"Text Channels","type":4},{"id":"11","parent_id":"10","name":"general","type":0},{"id":"12","parent_id":"10","name":"meeting-plans","type":0},{"id":"13","parent_id":"10","name":"off-topic","type":0},{"id":"20","parent_id":null,"name":"Voice Channels","type":4},{"id":"21","parent_id":"20","name":"Lounge","type":2},{"id":"22","parent_id":"20","name":"Meeting Room 1","type":2},{"id":"22","parent_id":"20","name":"Meeting Room 2","type":2}],"system_channel_id":"11","roles":[{"id":"00","name":"@everyone","permissions":"1720707884502593"},{"id":"01","name":"officers (example)","mentionable":true,"hoist":true,"permissions":"1720709360909911","color":3066993}],"guild_template_code":"Ctg7PUHcQmZu"}"#,
    },
    Template {
        label: "Local Community",
        icon: ("local", include_bytes!("../../assets/add-server/local.svg")),
        body: r#"{"channels":[{"id":"00","parent_id":null,"name":"Information","type":4},{"id":"01","parent_id":"00","name":"welcome-and-rules","type":0},{"id":"02","parent_id":"00","name":"announcements","type":0},{"id":"03","parent_id":"00","name":"resources","type":0},{"id":"10","parent_id":null,"name":"Text Channels","type":4},{"id":"11","parent_id":"10","name":"general","type":0},{"id":"12","parent_id":"10","name":"meeting-plans","type":0},{"id":"13","parent_id":"10","name":"off-topic","type":0},{"id":"20","parent_id":null,"name":"Voice Channels","type":4},{"id":"21","parent_id":"20","name":"Lounge","type":2},{"id":"22","parent_id":"20","name":"Meeting Room","type":2}],"system_channel_id":"11","guild_template_code":"64UDvRNCC52Y"}"#,
    },
    Template {
        label: "Artists & Creators",
        icon: ("creators", include_bytes!("../../assets/add-server/creators.svg")),
        body: r#"{"channels":[{"id":"00","parent_id":null,"name":"Information","type":4},{"id":"01","parent_id":"00","name":"welcome-and-rules","type":0},{"id":"02","parent_id":"00","name":"announcements","type":0},{"id":"10","parent_id":null,"name":"Text Channels","type":4},{"id":"11","parent_id":"10","name":"general","type":0},{"id":"12","parent_id":"10","name":"events","type":0},{"id":"13","parent_id":"10","name":"ideas-and-feedback","type":0},{"id":"20","parent_id":null,"name":"Voice Channels","type":4},{"id":"21","parent_id":"20","name":"Lounge","type":2},{"id":"22","parent_id":"20","name":"Community Hangout","type":2},{"id":"23","parent_id":"20","name":"Stream Room","type":2}],"system_channel_id":"11","guild_template_code":"6exdzMgjZgah"}"#,
    },
];

const ARROW: &[u8] = include_bytes!("../../assets/add-server/arrow.svg");
const UPLOAD: &[u8] = include_bytes!("../../assets/add-server/upload.svg");
const DISCOVERY: &[u8] = include_bytes!("../../assets/add-server/discovery.svg");
const INTENT_FRIENDS: &[u8] = include_bytes!("../../assets/add-server/intent-friends.svg");
const INTENT_CLUB: &[u8] = include_bytes!("../../assets/add-server/intent-club.svg");
pub const RAIL_ADD: &[u8] = include_bytes!("../../assets/add-server/rail-add.svg");
pub const RAIL_DISCOVER: &[u8] = include_bytes!("../../assets/add-server/rail-discover.svg");

/// What a click in the dialog asks for.
enum Act {
    Close,
    Go(Step),
    Template(usize),
    PickIcon,
    Create,
    Join,
    OpenUrl(&'static str),
}

/// An SVG from the app's assets.
fn svg(key: &str, bytes: &'static [u8]) -> ImageSource<'static> {
    ImageSource::Bytes { uri: format!("bytes://add-server-{key}.svg").into(), bytes: Bytes::Static(bytes) }
}

/// An SVG whose `currentColor` parts are drawn in `color`.
pub fn tinted_svg(key: &str, bytes: &'static [u8], color: Color32) -> ImageSource<'static> {
    static CACHE: OnceLock<Mutex<HashMap<String, Arc<[u8]>>>> = OnceLock::new();
    let hex = format!("{:02x}{:02x}{:02x}", color.r(), color.g(), color.b());
    let key = format!("{key}-{hex}");
    let cache = CACHE.get_or_init(Default::default);
    let mut cache = cache.lock().unwrap();
    let data = cache
        .entry(key.clone())
        .or_insert_with(|| Arc::from(String::from_utf8_lossy(bytes).replacen("<svg ", &format!("<svg color=\"#{hex}\" "), 1).into_bytes()))
        .clone();
    ImageSource::Bytes { uri: format!("bytes://add-server-{key}.svg").into(), bytes: Bytes::Shared(data) }
}

fn regular(size: f32) -> FontId {
    FontId::proportional(size)
}

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

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

/// Discord's quiet surfaces: --background-mod-subtle and its border.
fn mod_subtle(alpha: f32) -> Color32 {
    crate::style::rgba(151, 151, 159, (alpha * 255.0).round() as u8)
}

/// Centred, wrapped text with its top at `top`; returns its height.
fn centered(ui: &Ui, top: f32, cx: f32, width: f32, text: &str, font: FontId, color: Color32) -> f32 {
    let mut job = LayoutJob::simple(text.to_string(), font, color, width);
    job.halign = Align::Center;
    let galley = ui.painter().layout_job(job);
    let h = galley.size().y;
    ui.painter().galley(pos2(cx, top), galley, color);
    h
}

/// A line of text runs, some of them links, laid out from `left` (or
/// centred on `cx` when `left` is `None`) at `top`. Returns the link clicked.
fn rich_line(ui: &Ui, id: &str, top: f32, left: Option<f32>, cx: f32, runs: &[(&str, FontId, Color32, bool)]) -> Option<usize> {
    let galleys: Vec<_> = runs.iter().map(|(s, f, c, _)| ui.painter().layout_no_wrap(s.to_string(), f.clone(), *c)).collect();
    let total: f32 = galleys.iter().map(|g| g.size().x).sum();
    let mut x = left.unwrap_or(cx - total / 2.0);
    let mut clicked = None;
    for (i, (g, run)) in galleys.into_iter().zip(runs).enumerate() {
        let r = Rect::from_min_size(pos2(x, top), g.size());
        if run.3 {
            let resp = ui.interact(r, egui::Id::new((id, i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            if resp.hovered() {
                ui.painter().hline(r.x_range(), r.bottom() - 1.0, Stroke::new(1.0_f32, run.2));
            }
            if resp.clicked() {
                clicked = Some(i);
            }
        }
        x += g.size().x;
        ui.painter().galley(r.min, g, run.2);
    }
    clicked
}

/// The rounded choice row Discord uses on the first two pages: icon, label,
/// arrow.
fn choice(ui: &mut Ui, t: &Theme, r: Rect, id: &str, icon: ImageSource<'static>, label: &str) -> bool {
    let resp = ui.interact(r, egui::Id::new(("add_server_choice", id)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    let fill = if resp.hovered() { mod_subtle(0.16) } else { mod_subtle(0.08) };
    ui.painter().rect(r, 8.0, fill, Stroke::new(1.0_f32, mod_subtle(0.2)));
    egui::Image::new(icon).paint_at(ui, Rect::from_min_size(pos2(r.left() + 17.0, r.top() + 17.0), vec2(20.0, 20.0)));
    ui.painter().text(pos2(r.left() + 53.0, r.center().y), Align2::LEFT_CENTER, label, regular(16.0), t.text_normal);
    egui::Image::new(svg("arrow", ARROW)).paint_at(ui, Rect::from_min_size(pos2(r.right() - 37.0, r.top() + 17.0), vec2(20.0, 20.0)));
    resp.clicked()
}

/// Discord's filled button (brand or the quiet grey one).
fn button(ui: &mut Ui, r: Rect, id: &str, label: &str, brand: bool, enabled: bool) -> bool {
    let resp = ui.interact(r, egui::Id::new(("add_server_btn", id)), if enabled { Sense::click() } else { Sense::hover() });
    let resp = if enabled { resp.on_hover_cursor(egui::CursorIcon::PointingHand) } else { resp };
    let (fill, stroke, text) = if brand {
        let fill = if !enabled { BRAND.gamma_multiply(0.5) } else if resp.hovered() { Color32::from_rgb(0x47, 0x52, 0xc4) } else { BRAND };
        (fill, crate::style::rgba(255, 255, 255, 20), Color32::WHITE)
    } else {
        (if resp.hovered() { mod_subtle(0.2) } else { mod_subtle(0.12) }, mod_subtle(0.16), Color32::from_rgb(220, 220, 223))
    };
    ui.painter().rect(r, 8.0, fill, Stroke::new(1.0_f32, stroke));
    ui.painter().text(r.center(), Align2::CENTER_CENTER, label, medium(16.0), text);
    enabled && resp.clicked()
}

/// A text-only button ("Back").
fn text_button(ui: &mut Ui, at: Pos2, id: &str, label: &str, font: FontId, color: Color32) -> bool {
    let g = ui.painter().layout_no_wrap(label.to_string(), font, color);
    let r = Rect::from_min_size(at, g.size());
    let resp = ui.interact(r, egui::Id::new(("add_server_text", id)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    if resp.hovered() {
        ui.painter().hline(r.x_range(), r.bottom() - 1.0, Stroke::new(1.0_f32, color));
    }
    ui.painter().galley(r.min, g, color);
    resp.clicked()
}

/// "Label *" above a field.
fn required_label(ui: &Ui, t: &Theme, at: Pos2, label: &str) {
    let g = ui.painter().layout_no_wrap(label.to_string(), medium(16.0), t.header_primary);
    let w = g.size().x;
    ui.painter().galley(at, g, t.header_primary);
    ui.painter().text(pos2(at.x + w + 4.0, at.y), Align2::LEFT_TOP, "*", regular(16.0), t.danger);
}

/// Discord's input box (40 px), taking the keyboard when `grab`; returns
/// whether Enter was pressed in it.
#[allow(clippy::too_many_arguments)]
fn input(ui: &mut Ui, r: Rect, id: &str, text: &mut String, hint: &str, max: usize, grab: bool, t: &Theme) -> bool {
    ui.painter().rect(r, 8.0, Color32::from_black_alpha(31), Stroke::new(1.0_f32, mod_subtle(0.24)));
    let id = egui::Id::new(("add_server_input", id));
    let edit = TextEdit::singleline(text)
        .id(id)
        .frame(false)
        .char_limit(max)
        .font(regular(16.0))
        .text_color(t.text_normal)
        .hint_text(egui::RichText::new(hint).color(t.text_muted))
        .desired_width(r.width() - 24.0);
    let resp = ui.put(Rect::from_min_max(pos2(r.left() + 12.0, r.top() + 9.0), pos2(r.right() - 12.0, r.bottom() - 9.0)), edit);
    if grab {
        resp.request_focus();
    }
    resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter))
}

/// The close "×" in the dialog's top-right corner.
fn close_button(ui: &mut Ui, t: &Theme, modal: Rect) -> bool {
    let r = Rect::from_min_size(pos2(modal.right() - 17.0 - 32.0, modal.top() + 13.0), vec2(32.0, 32.0));
    let resp = ui.interact(r, egui::Id::new("add_server_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    let c = if resp.hovered() { t.header_primary } else { t.interactive_normal };
    ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(16.0), c);
    resp.clicked()
}

impl AddServer {
    fn new() -> Self {
        Self { step: Step::Landing, template: 0, name: String::new(), named: false, keyboard: None, icon: None, invite: String::new(), error: None, busy: false }
    }

    /// The dialog opened on `page` (`RUSTCORD_DEV_VIEW=add-server:<page>`).
    pub fn dev(page: &str) -> Self {
        let step = match page {
            "intent" => Step::Intent,
            "customize" => Step::Customize,
            "join" => Step::Join,
            _ => Step::Landing,
        };
        Self { step, ..Self::new() }
    }

    /// True once per page: its text field takes the keyboard as it opens.
    fn take_keyboard(&mut self) -> bool {
        let first = self.keyboard != Some(self.step);
        self.keyboard = Some(self.step);
        first
    }

    /// How tall the dialog is on this step (Discord's sizes).
    fn height(&self, screen: f32) -> f32 {
        let err = if self.error.is_some() { 24.0 } else { 0.0 };
        match self.step {
            // The template list scrolls when the window is short.
            Step::Landing => 564.0_f32.min(screen - 40.0).max(300.0),
            Step::Intent => 376.0,
            Step::Customize => 422.0 + err,
            Step::Join => 445.0 + err,
        }
    }
}

impl RustCord {
    /// Open "Add a Server" (the server list's "+").
    pub fn open_add_server(&mut self) {
        self.add_server = Some(AddServer::new());
    }

    /// The answer to a create / join: open the server, or say why not.
    pub fn add_server_done(&mut self, request: AddServerRequest, result: Result<Id, String>, captcha: Option<crate::captcha_view::Challenge>) {
        match (result, captcha) {
            (Ok(guild), _) => {
                log::info!("add server: {} {guild}", if matches!(request, AddServerRequest::Create(_)) { "created" } else { "joined" });
                self.add_server = None;
                if self.store.guilds.contains_key(&guild) {
                    self.select_guild(Some(guild));
                } else {
                    self.open_when_joined = Some(guild);
                }
            }
            (Err(_), Some(challenge)) => {
                log::info!("captcha: Discord wants one to add a server");
                self.captcha = Some(crate::app::CaptchaPrompt {
                    msg: Default::default(),
                    friend: None,
                    friend_stranger: false,
                    server: Some(request),
                    challenge,
                    view: None,
                    rect: None,
                    error: None,
                });
            }
            (Err(e), None) => {
                log::warn!("add server: {e}");
                if let Some(a) = self.add_server.as_mut() {
                    a.busy = false;
                    a.error = Some(e);
                } else {
                    self.toast(e, true);
                }
            }
        }
    }

    pub fn add_server_ui(&mut self, ctx: &egui::Context) {
        // A server made or joined opens as soon as the gateway brings it.
        if let Some(g) = self.open_when_joined.filter(|g| self.store.guilds.contains_key(g)) {
            self.open_when_joined = None;
            self.select_guild(Some(g));
        }
        // A captcha for it is being solved: that dialog is the one showing.
        if self.captcha.as_ref().is_some_and(|c| c.server.is_some()) {
            return;
        }
        let Some(mut st) = self.add_server.take() else { return };
        let t = self.theme.clone();
        let screen = ctx.screen_rect();
        // The dimmed app behind it; a click there closes the dialog.
        egui::Area::new(egui::Id::new("add_server_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(170));
        });
        let h = st.height(screen.height());
        let modal = Rect::from_center_size(screen.center(), vec2(W, h));
        let mut act = None;
        egui::Area::new(egui::Id::new("add_server")).order(Order::Tooltip).fixed_pos(modal.min).show(ctx, |ui| {
            let (rect, _) = ui.allocate_exact_size(modal.size(), Sense::hover());
            ui.painter().rect(rect, 12.0, t.surface_high, Stroke::new(1.0_f32, super::modal_border(&t)));
            act = match st.step {
                Step::Landing => landing(ui, &t, rect),
                Step::Intent => intent(ui, &t, rect),
                Step::Customize => customize(ui, &t, rect, &mut st),
                Step::Join => join(ui, &t, rect, &mut st),
            };
            if close_button(ui, &t, rect) {
                act = Some(Act::Close);
            }
        });
        let escape = ctx.input(|i| i.key_pressed(Key::Escape));
        if escape || (super::pressed_outside(ctx, modal) && !st.busy) {
            act = Some(Act::Close);
        }
        match act {
            Some(Act::Close) => return,
            Some(Act::Go(step)) => {
                st.step = step;
                st.error = None;
            }
            Some(Act::Template(i)) => {
                st.template = i;
                st.step = Step::Intent;
            }
            Some(Act::PickIcon) => {
                if let Some(path) = rfd::FileDialog::new().set_title("Upload a Server Icon").add_filter("Images", &super::server_settings::IMAGE_EXTS).pick_file() {
                    match super::server_settings::prepare_image(&path, 1024, 8 << 20) {
                        Ok(img) => {
                            let uri = format!("bytes://add-server-icon-{}", super::server_settings::next_seq());
                            st.icon = Some(PickedIcon { data_uri: img.data_uri, uri, bytes: img.bytes });
                        }
                        Err(e) => self.toast(e, true),
                    }
                }
            }
            Some(Act::Create) => {
                if let Ok(mut body) = serde_json::from_str::<serde_json::Value>(TEMPLATES[st.template].body) {
                    body["name"] = st.name.trim().into();
                    body["icon"] = st.icon.as_ref().map(|i| i.data_uri.clone()).into();
                    st.busy = true;
                    st.error = None;
                    self.backend.send(Command::AddServer { request: AddServerRequest::Create(body), captcha: None });
                }
            }
            Some(Act::Join) => match discord::http::invite_code(&st.invite) {
                Some(code) => {
                    st.busy = true;
                    st.error = None;
                    let request = AddServerRequest::Join { code, input: st.invite.trim().to_string(), session: self.gateway_session.clone() };
                    self.backend.send(Command::AddServer { request, captcha: None });
                }
                None => st.error = Some("The invite is invalid or has expired.".into()),
            },
            Some(Act::OpenUrl(url)) => ctx.open_url(egui::OpenUrl::new_tab(url)),
            None => {}
        }
        // The name starts as Discord's "<your name>'s server" (once: clearing
        // it leaves it empty).
        if st.step == Step::Customize && !st.named {
            if let Some(me) = self.store.me.as_ref() {
                st.name = format!("{}'s server", me.display_name());
                st.named = true;
            }
        }
        self.add_server = Some(st);
    }
}

/// "Create Your Server": Create My Own, the templates (scrolling), and the
/// "Have an invite already?" footer.
fn landing(ui: &mut Ui, t: &Theme, m: Rect) -> Option<Act> {
    let mut act = None;
    let cx = m.center().x;
    centered(ui, m.top() + 25.0, cx, 410.0, "Create Your Server", heavy(24.0), t.header_primary);
    centered(ui, m.top() + 65.0, cx, 410.0, "Your server is where you and your friends hang out.\nMake yours and start talking.", regular(16.0), t.text_normal);
    let footer = Rect::from_min_max(pos2(m.left() + 1.0, m.bottom() - 105.0), pos2(m.right() - 1.0, m.bottom() - 1.0));
    let list = Rect::from_min_max(pos2(m.left() + 1.0, m.top() + 128.0), pos2(m.right() - 1.0, footer.top()));
    let mut lui = ui.new_child(egui::UiBuilder::new().max_rect(list));
    ScrollArea::vertical().id_salt("add_server_templates").max_height(list.height()).auto_shrink([false, false]).show(&mut lui, |ui| {
        ui.spacing_mut().item_spacing.y = 0.0;
        let row = |ui: &mut Ui, h: f32| ui.allocate_exact_size(vec2(list.width(), h), Sense::hover()).0;
        row(ui, 8.0);
        for (i, tpl) in TEMPLATES.iter().enumerate() {
            if i == 1 {
                let r = row(ui, 16.0 + 19.0 + 7.0);
                ui.painter().text(pos2(r.left() + 24.0, r.top() + 16.0), Align2::LEFT_TOP, "Start from a template", medium(14.0), t.text_normal);
            }
            let r = row(ui, 62.0);
            let b = Rect::from_min_size(pos2(r.left() + 24.0, r.top()), vec2(402.0, 54.0));
            if choice(ui, t, b, tpl.label, svg(tpl.icon.0, tpl.icon.1), tpl.label) {
                act = Some(Act::Template(i));
            }
        }
    });
    // The footer sits over the list's end.
    ui.painter().rect_filled(footer, egui::Rounding { nw: 0.0, ne: 0.0, sw: 11.0, se: 11.0 }, t.surface_high);
    centered(ui, footer.top() + 17.0, cx, 410.0, "Have an invite already?", semibold(20.0), t.header_primary);
    let b = Rect::from_min_size(pos2(m.left() + 25.0, footer.top() + 49.0), vec2(394.0, 40.0));
    if button(ui, b, "join", "Join a Server", false, true) {
        act = Some(Act::Go(Step::Join));
    }
    act
}

/// "Tell Us More About Your Server": for friends or a community (Discord
/// sends the same request either way).
fn intent(ui: &mut Ui, t: &Theme, m: Rect) -> Option<Act> {
    let mut act = None;
    let cx = m.center().x;
    centered(ui, m.top() + 25.0, cx, 410.0, "Tell Us More About Your Server", heavy(24.0), t.header_primary);
    centered(ui, m.top() + 65.0, cx, 410.0, "In order to help you with your setup, is your new server for just a few friends or a larger community?", regular(16.0), t.text_normal);
    for (i, (key, icon, label)) in [("intent-friends", INTENT_FRIENDS, "For me and my friends"), ("intent-club", INTENT_CLUB, "For a club or community")].into_iter().enumerate() {
        let r = Rect::from_min_size(pos2(m.left() + 17.0, m.top() + 129.0 + i as f32 * 62.0), vec2(402.0, 54.0));
        if choice(ui, t, r, key, svg(key, icon), label) {
            act = Some(Act::Go(Step::Customize));
        }
    }
    let runs = [
        ("Not sure? You can ", regular(14.0), t.text_normal, false),
        ("skip this question", regular(14.0), t.text_link, true),
        (" for now.", regular(14.0), t.text_normal, false),
    ];
    if rich_line(ui, "add_server_skip", m.top() + 263.0, None, cx, &runs) == Some(1) {
        act = Some(Act::Go(Step::Customize));
    }
    if text_button(ui, pos2(m.left() + 25.0, m.bottom() - 45.0), "back", "Back", medium(14.0), t.header_primary) {
        act = Some(Act::Go(Step::Landing));
    }
    act
}

/// "Customize Your Server": icon and name, then Create.
fn customize(ui: &mut Ui, t: &Theme, m: Rect, st: &mut AddServer) -> Option<Act> {
    let mut act = None;
    let cx = m.center().x;
    let left = m.left() + 25.0;
    centered(ui, m.top() + 25.0, cx, 394.0, "Customize Your Server", heavy(24.0), t.header_primary);
    centered(ui, m.top() + 65.0, cx, 394.0, "Give your new server a personality with a name and an icon. You can always change it later.", regular(16.0), t.text_normal);

    // The icon: Discord's dashed "Upload" circle, or the picture chosen.
    let up = Rect::from_min_size(pos2(cx - 40.0, m.top() + 133.0), vec2(80.0, 80.0));
    let resp = ui.interact(up, egui::Id::new("add_server_icon"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    match &st.icon {
        Some(i) => {
            egui::Image::from_bytes(i.uri.clone(), i.bytes.clone()).rounding(40.0).paint_at(ui, up);
        }
        None => {
            egui::Image::new(tinted_svg("upload", UPLOAD, t.header_secondary)).paint_at(ui, up);
            ui.painter().text(pos2(cx, up.top() + 44.0), Align2::CENTER_TOP, "Upload", semibold(12.0), t.header_secondary);
        }
    }
    if resp.clicked() && !st.busy {
        act = Some(Act::PickIcon);
    }

    required_label(ui, t, pos2(left, m.top() + 229.0), "Server Name");
    let field = Rect::from_min_size(pos2(left, m.top() + 257.0), vec2(394.0, 40.0));
    let grab = st.take_keyboard();
    let enter = input(ui, field, "name", &mut st.name, "", 100, grab, t);
    let mut y = field.bottom() + 16.0;
    if let Some(e) = &st.error {
        ui.painter().text(pos2(left, field.bottom() + 8.0), Align2::LEFT_TOP, e, regular(14.0), t.danger);
        y += 24.0;
    }
    let runs = [
        ("By creating a server, you agree to Discord's ", regular(12.0), t.text_muted, false),
        ("Community Guidelines", semibold(12.0), t.text_link, true),
        (".", regular(12.0), t.text_muted, false),
    ];
    if rich_line(ui, "add_server_terms", y, Some(left), cx, &runs) == Some(1) {
        act = Some(Act::OpenUrl("https://discord.com/guidelines"));
    }

    if text_button(ui, pos2(left, m.bottom() - 47.0), "back", "Back", medium(16.0), t.header_primary) && !st.busy {
        act = Some(Act::Go(Step::Intent));
    }
    let ok = !st.name.trim().is_empty() && !st.busy;
    let b = Rect::from_min_size(pos2(m.right() - 25.0 - 100.0, m.bottom() - 57.0), vec2(100.0, 40.0));
    if button(ui, b, "create", if st.busy { "…" } else { "Create" }, true, ok) || (enter && ok) {
        act = Some(Act::Create);
    }
    act
}

/// "Join a Server": the invite link, examples, Server Discovery, Join Server.
fn join(ui: &mut Ui, t: &Theme, m: Rect, st: &mut AddServer) -> Option<Act> {
    let mut act = None;
    let cx = m.center().x;
    let left = m.left() + 25.0;
    centered(ui, m.top() + 25.0, cx, 394.0, "Join a Server", heavy(24.0), t.header_primary);
    centered(ui, m.top() + 65.0, cx, 394.0, "Enter an invite below to join an existing server", regular(14.0), t.text_normal);

    required_label(ui, t, pos2(left, m.top() + 91.0), "Invite link");
    let field = Rect::from_min_size(pos2(left, m.top() + 119.0), vec2(394.0, 40.0));
    let grab = st.take_keyboard();
    let enter = input(ui, field, "invite", &mut st.invite, "https://discord.gg/hTKzmak", 200, grab, t);
    let mut y = field.bottom() + 16.0;
    if let Some(e) = &st.error {
        ui.painter().text(pos2(left, field.bottom() + 8.0), Align2::LEFT_TOP, e, regular(14.0), t.danger);
        y += 24.0;
    }

    ui.painter().text(pos2(left, y), Align2::LEFT_TOP, "Invites should look like", medium(14.0), t.header_secondary);
    // The example chips, wrapped like Discord's (two on the first row).
    let mut chip_y = y + 30.0;
    for row in [&["hTKzmak", "https://discord.gg/hTKzmak"][..], &["https://discord.gg/wumpus-friends"][..]] {
        let mut x = left + 4.0;
        for ex in row {
            let g = ui.painter().layout_no_wrap(ex.to_string(), regular(14.0), t.header_primary);
            let r = Rect::from_min_size(pos2(x, chip_y), vec2(g.size().x + 16.0, 28.0));
            ui.painter().rect(r, 4.0, mod_subtle(0.08), Stroke::new(1.0_f32, mod_subtle(0.16)));
            ui.painter().galley(pos2(r.left() + 8.0, r.center().y - g.size().y / 2.0), g, t.header_primary);
            x = r.right() + 8.0;
        }
        chip_y += 36.0;
    }

    // "Don't have an invite?": Server Discovery (on discord.com).
    let row = Rect::from_min_size(pos2(left, chip_y + 4.0), vec2(394.0, 76.0));
    let resp = ui.interact(row, egui::Id::new("add_server_discovery"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    ui.painter().rect_filled(row, 8.0, if resp.hovered() { t.bg_secondary } else { t.bg_tertiary });
    egui::Image::new(svg("discovery", DISCOVERY)).paint_at(ui, Rect::from_min_size(pos2(row.left() + 12.0, row.top() + 18.0), vec2(40.0, 40.0)));
    ui.painter().text(pos2(row.left() + 64.0, row.top() + 12.0), Align2::LEFT_TOP, "Don't have an invite?", semibold(16.0), t.header_primary);
    let desc = ui.painter().layout("Check out Discoverable communities in Server Discovery.".into(), regular(12.0), t.text_normal, 282.0);
    ui.painter().galley(pos2(row.left() + 64.0, row.top() + 32.0), desc, t.text_normal);
    egui::Image::new(svg("arrow", ARROW)).paint_at(ui, Rect::from_min_size(pos2(row.right() - 48.0, row.top() + 28.0), vec2(20.0, 20.0)));
    if resp.clicked() {
        act = Some(Act::OpenUrl("https://discord.com/discovery/servers"));
    }

    if text_button(ui, pos2(left, m.bottom() - 46.0), "back", "Back", medium(14.0), t.text_link) && !st.busy {
        act = Some(Act::Go(Step::Landing));
    }
    let ok = !st.invite.trim().is_empty() && !st.busy;
    let b = Rect::from_min_size(pos2(m.right() - 25.0 - 110.0, m.bottom() - 57.0), vec2(110.0, 40.0));
    if button(ui, b, "join", if st.busy { "…" } else { "Join Server" }, true, ok) || (enter && ok) {
        act = Some(Act::Join);
    }
    act
}