Skip to content

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

10.3 KB
Raw Blame
//! Discord's friend nicknames: a private name for a friend, seen only by you
//! in DMs, group DMs and the Friends list (`Store::nick_in`). Set from
//! "Add Friend Nickname" / "Change Friend Nickname" in the user menus, with
//! Discord's dialog (web module 609422), saved with
//! `PATCH /users/@me/relationships/{id} {"nickname": …}`.

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

/// The dialog while it is up.
pub struct FriendNickname {
    user: User,
    /// What the field holds; empty saves "no nickname".
    value: String,
    /// They had a nickname when it opened ("Change", not "Add").
    had: bool,
    /// Frame it opened on (Save takes the keyboard focus then).
    opened: u64,
}

const TITLE_ADD: &str = "Add Friend Nickname";
const TITLE_CHANGE: &str = "Change Friend Nickname";
const SUBTITLE: &str = "Find a friend faster with a personal nickname. It will only be visible to you in your direct messages.";
/// Discord's limit on the field.
const MAX_CHARS: usize = 32;
const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);
const BRAND_HOVER: Color32 = Color32::from_rgb(0x47, 0x52, 0xc4);
/// `--text-brand` in Discord's dark themes (the "Reset Friend Nickname" link).
const TEXT_BRAND: Color32 = Color32::from_rgb(0x63, 0x74, 0xf4);
/// `--text-brand` in the light theme.
const TEXT_BRAND_LIGHT: Color32 = Color32::from_rgb(0x46, 0x4c, 0xd5);

fn tag(user: Id) -> String {
    format!("friend-nick:{user}")
}

impl RustCord {
    /// The user menus' row for `user`: "Add Friend Nickname", or "Change
    /// Friend Nickname" once they have one; None for anyone not a friend.
    pub fn friend_nickname_row(&self, user: Id) -> Option<&'static str> {
        let rel = self.store.relationships.get(&user).filter(|r| r.kind == 1)?;
        Some(if rel.nickname.as_deref().is_some_and(|n| !n.is_empty()) { TITLE_CHANGE } else { TITLE_ADD })
    }

    pub fn open_friend_nickname(&mut self, user: Id) {
        let rel_user = self.store.relationships.get(&user).and_then(|r| r.user.clone());
        let Some(u) = self.store.users.get(&user).cloned().or(rel_user) else { return };
        let current = self.store.friend_nickname(user).map(String::from);
        self.api_results.remove(&tag(user));
        self.friend_nickname = Some(FriendNickname { user: u, had: current.is_some(), value: current.unwrap_or_default(), opened: self.ctx.cumulative_pass_nr() });
    }

    /// Discord's dialog, measured on Discord web (2026-12-03): 480 px wide,
    /// 12 px corners; 20/24 semibold title 24 px in and a 40 px close button 8 px
    /// from the corner; the 16/20 subtitle (`--text-subtle`) 8 px under the
    /// title; 16 px on, the 16/20 medium "Friend Nickname" label, 8 px, the
    /// 40 px field, 8 px, the 14/18 "Reset Friend Nickname" link; 16 px on,
    /// Cancel / Save (40 px, 8 px apart) sharing the width, 24 px from the
    /// bottom. Save holds the keyboard focus as it opens, so Enter saves (from
    /// the field too); Esc, ✕, Cancel or a click on the dimmed window closes
    /// without saving.
    pub fn friend_nickname_ui(&mut self, ctx: &egui::Context) {
        self.friend_nickname_results();
        let Some(dialog) = self.friend_nickname.as_mut() else { return };
        let t = self.theme.clone();
        let uid = dialog.user.id;
        let tag = tag(uid);
        let saving = self.api_pending.contains(&tag);
        const W: f32 = 478.0;
        let field_id = egui::Id::new(("friend_nickname_field", uid.0));
        let save_id = egui::Id::new("friend_nickname_save");
        if ctx.cumulative_pass_nr() <= dialog.opened + 1 {
            ctx.memory_mut(|m| m.request_focus(save_id));
        }
        let enter = ctx.input(|i| i.key_pressed(Key::Enter));
        let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
        let mut save = enter && ctx.memory(|m| m.has_focus(save_id));
        close |= super::guild_pages::modal_frame(ctx, &t, "friend_nickname", W, |ui| {
            let mut job = egui::text::LayoutJob::single_section(
                SUBTITLE.into(),
                egui::TextFormat { font_id: FontId::proportional(16.0), color: t.header_secondary, line_height: Some(20.0), ..Default::default() },
            );
            job.wrap.max_width = W - 48.0;
            let subtitle = ui.fonts(|f| f.layout_job(job));
            let sub_h = subtitle.size().y;
            let h = 56.0 + sub_h + 8.0 + 16.0 + 20.0 + 8.0 + 40.0 + 8.0 + 18.0 + 8.0 + 16.0 + 40.0 + 8.0 + 16.0;
            let (r, _) = ui.allocate_exact_size(vec2(W, h), Sense::hover());
            let left = r.left() + 24.0;
            let title = if dialog.had { TITLE_CHANGE } else { TITLE_ADD };
            ui.painter().text(pos2(left, r.top() + 36.0), Align2::LEFT_CENTER, title, super::guild_pages::strong(20.0), t.header_primary);

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

            // The field, under its label.
            let label_top = r.top() + 56.0 + sub_h + 8.0 + 16.0;
            ui.painter().text(pos2(left, label_top + 10.0), Align2::LEFT_CENTER, "Friend Nickname", medium(16.0), t.header_primary);
            let field = Rect::from_min_size(pos2(left, label_top + 28.0), vec2(W - 48.0, 40.0));
            let focused = ui.memory(|m| m.has_focus(field_id));
            ui.painter().rect(field, 8.0, Color32::from_black_alpha(31), Stroke::new(1.0_f32, if focused { t.text_link } else { rgba(151, 151, 159, 61) }));
            let edit = TextEdit::singleline(&mut dialog.value)
                .id(field_id)
                .frame(false)
                .margin(Margin::symmetric(0.0, 0.0))
                .hint_text(egui::RichText::new(dialog.user.display_name()).color(t.text_muted))
                .char_limit(MAX_CHARS)
                .font(FontId::proportional(16.0))
                .text_color(t.text_normal)
                .vertical_align(egui::Align::Center);
            let resp = ui.put(field.shrink2(vec2(12.0, 1.0)), edit);
            save |= resp.lost_focus() && enter;

            // "Reset Friend Nickname": empties the field and gives it the focus back.
            let link_color = if t.light { TEXT_BRAND_LIGHT } else { TEXT_BRAND };
            let galley = ui.painter().layout_no_wrap("Reset Friend Nickname".into(), medium(14.0), link_color);
            let link = Rect::from_min_size(pos2(left, field.bottom() + 8.0), vec2(galley.size().x, 18.0));
            let lr = ui.interact(link, egui::Id::new("friend_nickname_reset"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            let text_pos = pos2(link.left(), link.center().y - galley.size().y / 2.0);
            if lr.hovered() {
                let y = link.bottom() - 2.0;
                ui.painter().hline(link.x_range(), y, Stroke::new(1.0_f32, link_color));
            }
            ui.painter().galley(text_pos, galley, link_color);
            if lr.clicked() {
                dialog.value.clear();
                ui.memory_mut(|m| m.request_focus(field_id));
            }

            // Cancel / Save.
            let bw = (W - 48.0 - 8.0) / 2.0;
            let no = Rect::from_min_size(pos2(left, r.bottom() - 24.0 - 40.0), vec2(bw, 40.0));
            let yes = no.translate(vec2(bw + 8.0, 0.0));
            let nr = ui.interact(no, egui::Id::new("friend_nickname_cancel"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            ui.painter().rect(no, 8.0, overlay(if nr.hovered() { 0.2 } else { 0.12 }), Stroke::new(1.0_f32, rgba(151, 151, 159, 41)));
            ui.painter().text(no.center(), Align2::CENTER_CENTER, "Cancel", medium(16.0), t.header_primary);
            close |= nr.clicked();
            let yr = ui.interact(yes, save_id, if saving { Sense::hover() } else { Sense::click() });
            let fill = if yr.hovered() && !saving { BRAND_HOVER } else { BRAND };
            ui.painter().rect(yes, 8.0, if saving { fill.gamma_multiply(0.5) } else { fill }, Stroke::new(1.0_f32, rgba(255, 255, 255, 20)));
            ui.painter().text(yes.center(), Align2::CENTER_CENTER, "Save", medium(16.0), if saving { Color32::from_white_alpha(128) } else { Color32::WHITE });
            save |= yr.on_hover_cursor(CursorIcon::PointingHand).clicked();
        });

        if save && !saving {
            let nickname = dialog.value.trim().to_string();
            let value = if nickname.is_empty() { Value::Null } else { json!(nickname) };
            self.api(&tag, reqwest::Method::PATCH, format!("/users/@me/relationships/{uid}"), Some(json!({ "nickname": value })));
        } else if close {
            ctx.memory_mut(|m| {
                m.surrender_focus(save_id);
                m.surrender_focus(field_id);
            });
            self.friend_nickname = None;
        }
    }

    /// Answers to the dialog's save: shown at once (Discord's own
    /// RELATIONSHIP_UPDATE confirms it shortly after) and the dialog closes;
    /// on an error it stays open, with the reason in a toast.
    fn friend_nickname_results(&mut self) {
        let Some(uid) = self.friend_nickname.as_ref().map(|d| d.user.id) else { return };
        match self.api_take(&tag(uid)) {
            Some(Ok(_)) => {
                let nickname = self.friend_nickname.take().map(|d| d.value.trim().to_string()).unwrap_or_default();
                self.set_friend_nickname_locally(uid, &nickname);
            }
            Some(Err(e)) => self.toast(format!("Couldn't save the friend nickname: {e}"), true),
            None => {}
        }
    }

    fn set_friend_nickname_locally(&mut self, user: Id, nickname: &str) {
        if let Some(rel) = self.store.relationships.get_mut(&user) {
            rel.nickname = (!nickname.is_empty()).then(|| nickname.to_string());
        }
    }
}