Skip to content

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

26.7 KB
Raw Blame
//! Discord's "Invite friends to …" modal (server, channel and voice invites):
//! your recent DMs and friends with an **Invite** button each, which sends
//! them the link in a DM like Discord does; the link itself with **Copy**; and
//! "Edit invite link" for Discord's expiry, use-limit and guest options.
//! Sizes and colours are taken from Discord's own modal.

use crate::app::RustCord;
use crate::backend::Command;
use crate::style::{icon, icon_font, medium, rgba, Theme, BOLD};
use discord::model::{channel_kind, Id, User};
use eframe::egui::{self, pos2, vec2, Align2, Color32, FontFamily, FontId, Key, Order, Rect, ScrollArea, Sense, Stroke, Ui};
use std::collections::{HashMap, HashSet};
use std::time::Instant;

/// Discord's "Expire After" choices (seconds, 0 = never) and "Max Number of Uses".
const EXPIRY: &[(u32, &str)] = &[
    (1800, "30 minutes"),
    (3600, "1 hour"),
    (21600, "6 hours"),
    (43200, "12 hours"),
    (86400, "1 day"),
    (604800, "7 days"),
    (2592000, "30 days"),
    (0, "Never"),
];
const USES: &[(u32, &str)] = &[(0, "No limit"), (1, "1 use"), (5, "5 uses"), (10, "10 uses"), (25, "25 uses"), (50, "50 uses"), (100, "100 uses")];

/// `api_results` tag for Discord's user affinities.
const AFFINITIES: &str = "invite_affinities";

/// Discord's defaults for a fresh invite: 30 days, no use limit.
const DEFAULT_MAX_AGE: u32 = 2_592_000;

const WIDTH: f32 = 480.0;
/// Content inset: the 1 px border plus 24 px of padding.
const PAD: f32 = 25.0;
const ROW_H: f32 = 48.0;
const LIST_MAX: f32 = 419.0;

pub struct InviteModal {
    pub channel: Id,
    /// The link: None while Discord makes it.
    pub link: Option<Result<String, String>>,
    pub max_age: u32,
    pub max_uses: u32,
    pub temporary: bool,
    pub search: String,
    /// "Invite to Server" list expanded (its header toggles it).
    pub list_open: bool,
    /// Invites sent from the list: None while sending, then whether it worked.
    pub sent: HashMap<Id, Option<bool>>,
    pub copied: Option<Instant>,
    /// "Server invite link settings" open: (expiry, uses, guest) being edited.
    pub settings: Option<(u32, u32, bool)>,
    /// Its open dropdown: 0 expiry, 1 uses.
    pub dropdown: Option<u8>,
    opened_frame: u64,
}

/// Someone the list can invite: their DM with you, if there is one.
struct Pick {
    user: User,
    dm: Option<Id>,
}

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

/// One line of text cut with "…" to `max_w`.
fn line(painter: &egui::Painter, pos: egui::Pos2, align: Align2, text: &str, font: FontId, color: Color32, max_w: f32) -> Rect {
    let mut job = egui::text::LayoutJob::simple_singleline(text.to_string(), font, color);
    job.wrap = egui::text::TextWrapping { max_width: max_w, max_rows: 1, break_anywhere: true, overflow_character: Some('…') };
    let galley = painter.layout_job(job);
    let rect = align.anchor_size(pos, galley.size());
    painter.galley(rect.min, galley, color);
    rect
}

/// Discord's grey button (`rgba(148,148,156,.12)`, lighter hovered).
fn grey(hovered: bool) -> Color32 {
    rgba(148, 148, 156, if hovered { 51 } else { 31 })
}

/// A field box: Discord's inputs (black 12 %, 1 px light border, 8 px corners).
fn field(painter: &egui::Painter, r: Rect, focused: bool, t: &Theme) {
    painter.rect(r, 8.0, Color32::from_black_alpha(31), Stroke::new(1.0_f32, if focused { t.text_link } else { rgba(145, 145, 150, 51) }));
}

impl RustCord {
    /// Open the invite modal for `channel` and ask Discord for a link.
    pub fn open_invite(&mut self, channel: Id) {
        let m = InviteModal {
            channel,
            link: None,
            max_age: DEFAULT_MAX_AGE,
            max_uses: 0,
            temporary: false,
            search: String::new(),
            list_open: true,
            sent: HashMap::new(),
            copied: None,
            settings: None,
            dropdown: None,
            opened_frame: self.ctx.cumulative_pass_nr(),
        };
        self.backend.send(Command::CreateInvite { channel, max_age: m.max_age, max_uses: m.max_uses, temporary: m.temporary });
        self.invite = Some(m);
        // Discord orders the list by who you talk to most (its user affinities).
        self.api_get_once(AFFINITIES, "/users/@me/affinities/v2/users");
    }

    /// Discord's communication probability per user (higher first in the list).
    fn affinities(&self) -> HashMap<Id, f64> {
        let Some(Ok(v)) = self.api_result(AFFINITIES) else { return HashMap::new() };
        v["user_affinities"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|a| Some((Id::from_value(&a["other_user_id"])?, a["communication_probability"].as_f64().unwrap_or(0.0))))
            .collect()
    }

    /// Recent DMs first (most recent on top), then other friends A–Z; not
    /// bots, and not people already known to be in the server.
    fn invite_picks(&self, guild: Option<Id>, query: &str) -> Vec<Pick> {
        let me = self.store.me_id();
        let mut seen = HashSet::new();
        let mut out = Vec::new();
        for id in self.store.dm_list() {
            let Some(c) = self.store.channels.get(&id).filter(|c| c.kind == channel_kind::DM) else { continue };
            let Some(u) = c.recipients.first() else { continue };
            if u.bot || u.system || Some(u.id) == me || !seen.insert(u.id) {
                continue;
            }
            out.push(Pick { user: u.clone(), dm: Some(id) });
        }
        let mut friends: Vec<User> = self
            .store
            .relationships
            .values()
            .filter(|r| r.kind == 1 && !seen.contains(&r.id))
            .filter_map(|r| r.user.clone().or_else(|| self.store.users.get(&r.id).cloned()))
            .collect();
        friends.sort_by_cached_key(|u| u.display_name().to_lowercase());
        out.extend(friends.into_iter().map(|user| Pick { user, dm: None }));
        if let Some(g) = guild {
            out.retain(|p| !self.store.members.contains_key(&(g, p.user.id)));
        }
        // Discord's affinity order on top (a stable sort keeps the rest as is).
        let aff = self.affinities();
        out.sort_by(|a, b| {
            let (x, y) = (aff.get(&a.user.id).copied().unwrap_or(-1.0), aff.get(&b.user.id).copied().unwrap_or(-1.0));
            y.total_cmp(&x)
        });
        let q = query.trim().to_lowercase();
        if !q.is_empty() {
            out.retain(|p| p.user.display_name().to_lowercase().contains(&q) || p.user.username.to_lowercase().contains(&q));
        }
        out
    }

    pub fn invite_modal_ui(&mut self, ctx: &egui::Context) {
        let Some(mut m) = self.invite.take() else { return };
        let t = self.theme.clone();
        let frame_nr = ctx.cumulative_pass_nr();
        let channel = self.store.channels.get(&m.channel).cloned();
        let guild = channel.as_ref().and_then(|c| c.guild_id);
        let place = guild
            .and_then(|g| self.store.guilds.get(&g))
            .map(|g| g.guild.name.clone())
            .or_else(|| channel.as_ref().map(|c| self.store.label(c)))
            .unwrap_or_default();
        let mut close = false;
        // Escape: an open dropdown first, then the settings view, then the modal.
        if ctx.input(|i| i.key_pressed(Key::Escape)) {
            if m.dropdown.take().is_none() && m.settings.take().is_none() {
                close = true;
            }
        }
        let screen = ctx.screen_rect();
        egui::Area::new(egui::Id::new("invite_dim")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            let (_, r) = ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha(178));
            if r.clicked() && frame_nr > m.opened_frame + 1 {
                close = true;
            }
        });

        let picks = if m.settings.is_none() { self.invite_picks(guild, &m.search) } else { Vec::new() };
        let list_h = if m.list_open { 12.0 + 36.0 + picks.len() as f32 * ROW_H + 12.0 } else { 12.0 + 36.0 + 12.0 };
        // Main view: header 85, 16, search 40, the list, 9, footer 116, 17.
        let fixed = 85.0 + 16.0 + 40.0 + 9.0 + 116.0 + 17.0;
        let list_h = list_h.min(LIST_MAX).min((screen.height() - 40.0 - fixed).max(120.0));
        let height = if m.settings.is_some() { 398.0 } else { fixed + list_h };
        let rect = Rect::from_center_size(screen.center(), vec2(WIDTH, height));
        let mut send: Vec<(Id, Option<Id>)> = Vec::new();
        let mut regenerate = None;

        egui::Area::new(egui::Id::new("invite_modal")).order(Order::Foreground).fixed_pos(rect.min).show(ctx, |ui| {
            ui.ctx().move_to_top(ui.layer_id());
            let _ = ui.allocate_rect(rect, Sense::click());
            let p = ui.painter().clone();
            // Discord: rgba(0,0,0,.24) 0 12px 24px shadow, 12 px corners, hairline border.
            p.add(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) }.as_shape(rect, 12.0));
            p.rect(rect, 12.0, t.surface_high, Stroke::new(1.0_f32, t.border_subtle));
            let left = rect.left() + PAD;
            let inner_w = WIDTH - 2.0 * PAD;
            // Close (40 × 40, 9 px in from the corner).
            let x = Rect::from_min_size(pos2(rect.right() - 49.0, rect.top() + 9.0), vec2(40.0, 40.0));
            let xr = ui.interact(x, egui::Id::new("invite_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            if xr.hovered() {
                p.rect_filled(x.shrink(1.0), 8.0, t.bg_hover);
            }
            p.text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(22.0), if xr.hovered() { t.header_primary } else { t.text_muted });
            close |= xr.clicked();

            if let Some(draft) = m.settings.as_mut() {
                if let Some(done) = settings_view(ui, &p, rect, left, inner_w, draft, &mut m.dropdown, &t) {
                    if done {
                        regenerate = Some(*draft);
                    }
                    m.settings = None;
                    m.dropdown = None;
                }
                return;
            }

            // Header: title, then "Recipients will land in <icon> channel".
            line(&p, pos2(left, rect.top() + 25.0), Align2::LEFT_TOP, &format!("Invite friends to {place}"), strong(20.0), t.header_primary, 394.0);
            let sub_y = rect.top() + 67.0;
            let lead = p.text(pos2(left, sub_y), Align2::LEFT_CENTER, "Recipients will land in", FontId::proportional(16.0), t.interactive_normal);
            if let Some(c) = &channel {
                let glyph = super::channel_icon(c.kind);
                p.text(pos2(lead.right() + 14.0, sub_y), Align2::CENTER_CENTER, glyph, icon_font(16.0), t.interactive_normal);
                line(&p, pos2(lead.right() + 24.0, sub_y), Align2::LEFT_CENTER, &self.store.label(c), FontId::proportional(16.0), t.interactive_normal, (rect.right() - PAD - lead.right() - 24.0).max(40.0));
            }

            // Search.
            let search = Rect::from_min_size(pos2(left, rect.top() + 101.0), vec2(inner_w, 40.0));
            let edit_id = egui::Id::new("invite_search");
            // (Discord shows no focus ring on this box.)
            field(&p, search, false, &t);
            p.text(pos2(search.left() + 20.0, search.center().y), Align2::CENTER_CENTER, icon::SEARCH, icon_font(16.0), t.text_normal);
            let text_r = Rect::from_min_max(pos2(search.left() + 39.0, search.top() + 1.0), pos2(search.right() - 8.0, search.bottom() - 1.0));
            ui.put(
                text_r,
                egui::TextEdit::singleline(&mut m.search)
                    .id(edit_id)
                    .frame(false)
                    .font(FontId::proportional(16.0))
                    .text_color(t.text_normal)
                    .hint_text(egui::RichText::new("Search for friends").color(t.text_muted).size(16.0))
                    .vertical_align(egui::Align::Center)
                    .desired_width(text_r.width()),
            );
            if frame_nr <= m.opened_frame + 1 {
                ui.memory_mut(|mem| mem.request_focus(edit_id));
            }

            // The list.
            let list = Rect::from_min_size(pos2(rect.left() + 1.0, search.bottom()), vec2(WIDTH - 2.0, list_h));
            ui.allocate_new_ui(egui::UiBuilder::new().max_rect(list), |ui| {
                ui.set_clip_rect(list);
                ScrollArea::vertical().id_salt("invite_list").auto_shrink([false, false]).max_height(list_h).show(ui, |ui| {
                    ui.spacing_mut().item_spacing.y = 0.0;
                    ui.add_space(12.0);
                    // "Invite to Server ⌄" (toggles the list).
                    let (hr, hresp) = ui.allocate_exact_size(vec2(list.width(), 36.0), Sense::click());
                    let label = if guild.is_some() { "Invite to Server" } else { "Invite" };
                    let hc = if hresp.hovered() { t.interactive_hover } else { t.text_muted };
                    let tr = ui.painter().text(pos2(left, hr.top() + 24.0), Align2::LEFT_CENTER, label, medium(14.0), hc);
                    ui.painter().text(pos2(tr.right() + 10.0, hr.top() + 24.0), Align2::CENTER_CENTER, if m.list_open { icon::CHEVRON_DOWN } else { icon::CHEVRON }, icon_font(9.0), hc);
                    if hresp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                        m.list_open = !m.list_open;
                    }
                    if m.list_open {
                        if picks.is_empty() {
                            let (r, _) = ui.allocate_exact_size(vec2(list.width(), ROW_H), Sense::hover());
                            let msg = if m.search.trim().is_empty() { "No friends to invite yet." } else { "No results found." };
                            ui.painter().text(pos2(left, r.center().y), Align2::LEFT_CENTER, msg, FontId::proportional(14.0), t.text_muted);
                        }
                        for pick in &picks {
                            let (r, resp) = ui.allocate_exact_size(vec2(list.width(), ROW_H), Sense::hover());
                            if !ui.is_rect_visible(r) {
                                continue;
                            }
                            let row = Rect::from_min_max(pos2(left - 8.0, r.top()), pos2(left + inner_w + 8.0, r.bottom()));
                            if resp.hovered() {
                                ui.painter().rect_filled(row, 3.0, t.bg_message_hover);
                            }
                            let av = Rect::from_min_size(pos2(left, r.top() + 8.0), vec2(32.0, 32.0));
                            super::paint_avatar(ui, av, Some(super::avatar_uri(&pick.user, 64, resp.hovered())), pick.user.display_name());
                            let btn = Rect::from_min_size(pos2(row.right() - 8.0 - 60.0, r.top() + 8.0), vec2(60.0, 32.0));
                            let text_w = btn.left() - 12.0 - (av.right() + 10.0);
                            line(ui.painter(), pos2(av.right() + 10.0, r.top() + 6.0), Align2::LEFT_TOP, pick.user.display_name(), strong(16.0), t.text_normal, text_w);
                            line(ui.painter(), pos2(av.right() + 10.0, r.top() + 27.0), Align2::LEFT_TOP, &pick.user.username, FontId::proportional(12.0), t.text_muted, text_w);
                            let state = m.sent.get(&pick.user.id).copied();
                            let br = ui.interact(btn, egui::Id::new(("invite_send", pick.user.id)), if state.is_none() { Sense::click() } else { Sense::hover() });
                            let (label, fg) = match state {
                                Some(Some(true)) => ("Sent", t.text_muted),
                                Some(None) => ("Invite", t.text_muted),
                                _ => ("Invite", t.header_primary),
                            };
                            let hot = br.hovered() && state.is_none();
                            ui.painter().rect(btn, 8.0, if matches!(state, Some(Some(true))) { Color32::TRANSPARENT } else { grey(hot) }, Stroke::new(1.0_f32, rgba(153, 153, 153, 10)));
                            ui.painter().text(btn.center(), Align2::CENTER_CENTER, label, medium(14.0), fg);
                            if state.is_none() && br.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() && matches!(m.link, Some(Ok(_))) {
                                m.sent.insert(pick.user.id, None);
                                send.push((pick.user.id, pick.dm));
                            }
                        }
                    }
                    ui.add_space(12.0);
                });
            });

            // Footer: divider, "Or send a server invite link to a friend", the link + Copy.
            let div_y = list.bottom();
            p.hline(rect.left() + 1.0..=rect.right() - 1.0, div_y + 0.5, Stroke::new(1.0_f32, t.border_subtle));
            let label_y = div_y + 9.0 + 16.0;
            let label = if guild.is_some() { "Or send a server invite link to a friend" } else { "Or send an invite link to a friend" };
            p.text(pos2(left, label_y + 10.0), Align2::LEFT_CENTER, label, medium(16.0), t.header_primary);
            let input = Rect::from_min_size(pos2(left, label_y + 28.0), vec2(inner_w, 40.0));
            field(&p, input, false, &t);
            let copied = m.copied.is_some_and(|c| c.elapsed().as_secs_f32() < 1.0);
            let copy = Rect::from_min_size(pos2(input.right() - 5.0 - 73.0, input.center().y - 15.0), vec2(73.0, 30.0));
            let (shown, fg) = match &m.link {
                Some(Ok(link)) => (link.clone(), t.text_normal),
                Some(Err(_)) => ("Couldn't create an invite".to_string(), t.danger),
                None => ("Creating an invite…".to_string(), t.text_muted),
            };
            line(&p, pos2(input.left() + 11.0, input.center().y), Align2::LEFT_CENTER, &shown, FontId::proportional(16.0), fg, copy.left() - input.left() - 20.0);
            let cr = ui.interact(copy, egui::Id::new("invite_copy"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            let ready = matches!(m.link, Some(Ok(_)));
            let fill = if copied {
                Color32::from_rgb(0x24, 0x80, 0x46)
            } else if !ready {
                t.accent.gamma_multiply(0.5)
            } else if cr.hovered() {
                Color32::from_rgb(0x47, 0x52, 0xc4)
            } else {
                t.accent
            };
            p.rect(copy, 4.0, fill, Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
            p.text(copy.center(), Align2::CENTER_CENTER, if copied { "Copied" } else { "Copy" }, medium(14.0), Color32::WHITE);
            if cr.clicked() {
                if let Some(Ok(link)) = &m.link {
                    ui.ctx().copy_text(link.clone());
                    m.copied = Some(Instant::now());
                }
            }
            if copied {
                ui.ctx().request_repaint_after(std::time::Duration::from_millis(200));
            }
            // "Your invite link expires in 30 days. Edit invite link."
            let note_y = input.bottom() + 16.0 + 8.0;
            let expiry = EXPIRY.iter().find(|(s, _)| *s == m.max_age).map(|(_, l)| *l).unwrap_or("30 days");
            let note = match (m.max_age, m.max_uses) {
                (0, 0) => "Your invite link will never expire.".to_string(),
                (0, n) => format!("Your invite link will never expire, and can be used {n} {}.", if n == 1 { "time" } else { "times" }),
                (_, 0) => format!("Your invite link expires in {expiry}."),
                (_, n) => format!("Your invite link expires in {expiry}, and can be used {n} {}.", if n == 1 { "time" } else { "times" }),
            };
            let nr = p.text(pos2(left, note_y), Align2::LEFT_CENTER, note, FontId::proportional(12.0), t.text_muted);
            let edit = p.text(pos2(nr.right() + 4.0, note_y), Align2::LEFT_CENTER, "Edit invite link.", FontId::proportional(12.0), t.text_link);
            let er = ui.interact(edit, egui::Id::new("invite_edit"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            if er.hovered() {
                p.hline(edit.x_range(), edit.bottom() - 1.0, Stroke::new(1.0_f32, t.text_link));
            }
            if er.clicked() {
                m.settings = Some((m.max_age, m.max_uses, m.temporary));
            }
        });

        for (user, dm) in send {
            if let Some(Ok(link)) = &m.link {
                let nonce = Id(Id::from_timestamp_ms(chrono::Utc::now().timestamp_millis().max(0) as u64).0 | (user.0 & 0xFFF)).to_string();
                self.backend.send(Command::SendInvite { user, dm, content: link.clone(), nonce });
            }
        }
        if let Some((max_age, max_uses, temporary)) = regenerate {
            m.max_age = max_age;
            m.max_uses = max_uses;
            m.temporary = temporary;
            m.link = None;
            m.copied = None;
            m.sent.clear();
            self.backend.send(Command::CreateInvite { channel: m.channel, max_age, max_uses, temporary });
        }
        if !close {
            self.invite = Some(m);
        }
    }
}

/// "Server invite link settings". Returns Some(true) for "Generate a New
/// Link", Some(false) for Cancel.
#[allow(clippy::too_many_arguments)]
fn settings_view(ui: &mut Ui, p: &egui::Painter, rect: Rect, left: f32, inner_w: f32, draft: &mut (u32, u32, bool), dropdown: &mut Option<u8>, t: &Theme) -> Option<bool> {
    let mut result = None;
    p.text(pos2(left, rect.top() + 37.0), Align2::LEFT_CENTER, "Server invite link settings", strong(20.0), t.header_primary);
    let mut fields: Vec<(u8, Rect)> = Vec::new();
    for (k, (label, y)) in [("Expire After", 73.0), ("Max Number of Uses", 161.0)].into_iter().enumerate() {
        let k = k as u8;
        p.text(pos2(left, rect.top() + y + 10.0), Align2::LEFT_CENTER, label, medium(16.0), t.header_primary);
        let r = Rect::from_min_size(pos2(left, rect.top() + y + 28.0), vec2(inner_w, 40.0));
        let resp = ui.interact(r, egui::Id::new(("invite_select", k)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        field(p, r, *dropdown == Some(k), t);
        let value = if k == 0 {
            EXPIRY.iter().find(|(s, _)| *s == draft.0).map(|(_, l)| *l).unwrap_or("30 days")
        } else {
            USES.iter().find(|(n, _)| *n == draft.1).map(|(_, l)| *l).unwrap_or("No limit")
        };
        p.text(pos2(r.left() + 12.0, r.center().y), Align2::LEFT_CENTER, value, FontId::proportional(16.0), t.text_normal);
        p.text(pos2(r.right() - 18.0, r.center().y), Align2::CENTER_CENTER, icon::CHEVRON_DOWN, icon_font(11.0), t.header_primary);
        if resp.clicked() {
            *dropdown = if *dropdown == Some(k) { None } else { Some(k) };
        }
        fields.push((k, r));
    }
    // Invite a Guest.
    let gy = rect.top() + 249.0;
    p.text(pos2(left, gy + 10.0), Align2::LEFT_CENTER, "Invite a Guest", medium(16.0), t.header_primary);
    let desc = p.layout(
        "Guests are automatically kicked when they leave the voice channel. They cannot see other channels in the server.".into(),
        FontId::proportional(14.0),
        t.interactive_normal,
        358.0,
    );
    p.galley(pos2(left, gy + 24.0), desc, t.interactive_normal);
    let sw = Rect::from_min_size(pos2(left + inner_w - 48.0, gy), vec2(48.0, 24.0));
    let sr = ui.interact(sw, egui::Id::new("invite_guest"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    if sr.clicked() {
        draft.2 = !draft.2;
    }
    let on = draft.2;
    p.rect(sw, 12.0, if on { t.accent } else { Color32::from_black_alpha(31) }, Stroke::new(1.0_f32, if on { Color32::TRANSPARENT } else { rgba(150, 150, 160, 51) }));
    let knob = if on { pos2(sw.right() - 12.0, sw.center().y) } else { pos2(sw.left() + 12.0, sw.center().y) };
    p.circle_filled(knob, 9.0, Color32::WHITE);
    // Cancel / Generate a New Link.
    let by = rect.top() + 333.0;
    let half = (inner_w - 8.0) / 2.0;
    for (i, (label, primary)) in [("Cancel", false), ("Generate a New Link", true)].into_iter().enumerate() {
        let r = Rect::from_min_size(pos2(left + i as f32 * (half + 8.0), by), vec2(half, 40.0));
        let resp = ui.interact(r, egui::Id::new(("invite_settings_btn", i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        let fill = match (primary, resp.hovered()) {
            (true, false) => t.accent,
            (true, true) => Color32::from_rgb(0x47, 0x52, 0xc4),
            (false, h) => grey(h),
        };
        p.rect(r, 8.0, fill, Stroke::new(1.0_f32, if primary { crate::style::rgba(255, 255, 255, 20) } else { rgba(153, 153, 153, 10) }));
        p.text(r.center(), Align2::CENTER_CENTER, label, medium(16.0), if primary { Color32::WHITE } else { t.header_primary });
        if resp.clicked() && dropdown.is_none() {
            result = Some(primary);
        }
    }
    // The open dropdown, over everything below its field.
    if let Some((k, r)) = dropdown.and_then(|d| fields.iter().find(|(k, _)| *k == d).copied()) {
        let options: Vec<(u32, &str)> = if k == 0 { EXPIRY.to_vec() } else { USES.to_vec() };
        let menu = Rect::from_min_size(pos2(r.left(), r.bottom() + 4.0), vec2(r.width(), options.len() as f32 * 36.0 + 8.0));
        let mut pick = None;
        egui::Area::new(egui::Id::new(("invite_dropdown", k))).order(Order::Tooltip).fixed_pos(menu.min).show(ui.ctx(), |ui| {
            let _ = ui.allocate_rect(menu, Sense::click());
            let p = ui.painter();
            p.rect(menu, 8.0, t.bg_floating, Stroke::new(1.0_f32, t.border_subtle));
            for (i, (value, label)) in options.iter().enumerate() {
                let row = Rect::from_min_size(pos2(menu.left() + 4.0, menu.top() + 4.0 + i as f32 * 36.0), vec2(menu.width() - 8.0, 36.0));
                let resp = ui.interact(row, egui::Id::new(("invite_option", k, i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                let selected = if k == 0 { draft.0 == *value } else { draft.1 == *value };
                if resp.hovered() || selected {
                    p.rect_filled(row, 4.0, if resp.hovered() { t.bg_hover } else { t.bg_selected });
                }
                p.text(pos2(row.left() + 8.0, row.center().y), Align2::LEFT_CENTER, *label, medium(16.0), if selected { t.header_primary } else { t.text_normal });
                if selected {
                    p.text(pos2(row.right() - 14.0, row.center().y), Align2::CENTER_CENTER, icon::CHECK, icon_font(14.0), t.accent);
                }
                if resp.clicked() {
                    pick = Some(*value);
                }
            }
        });
        if let Some(v) = pick {
            if k == 0 {
                draft.0 = v;
            } else {
                draft.1 = v;
            }
            *dropdown = None;
        }
    }
    result
}