Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! The composer's extras, like Discord's: the "+" menu (Upload a File,
//! Create Thread, Create Poll, Use Apps, Schedule Message), polls in
//! messages, the New Thread panel, scheduled messages and the app launcher
//! for slash commands. (The sticker picker is a tab of the expression
//! picker: expression.rs.)
use super::chat::UiAction;
use super::SizedOffScreen;
use crate::app::RustCord;
use crate::features::{CommandDraft, PickedEmoji, PickerTarget, PollDraft, ScheduleDraft, ThreadDraft};
use crate::style::{icon, icon_font, overlay, Theme};
use chrono::{DateTime, Datelike, Duration, Local, NaiveDate, TimeZone, Timelike};
use discord::model::{Id, Message, Poll};
use eframe::egui::{
self, pos2, vec2, Align2, Color32, ComboBox, FontId, Frame, Key, Margin, Order, Pos2, Rect, RichText, ScrollArea, Sense, Shadow, Stroke,
TextEdit, Ui,
};
use reqwest::Method;
use serde_json::{json, Value};
const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);
const USE_APPLICATION_COMMANDS: u64 = 1 << 31;
const CREATE_PUBLIC_THREADS: u64 = 1 << 35;
const CREATE_PRIVATE_THREADS: u64 = 1 << 36;
const SEND_POLLS: u64 = 1 << 49;
/// Segoe Fluent glyphs for the "+" menu.
const GLYPH_UPLOAD: &str = "\u{E898}";
const GLYPH_THREAD: &str = crate::style::icon::THREAD;
const GLYPH_POLL: &str = "\u{E8FD}";
const GLYPH_APPS: &str = "\u{E71D}";
const GLYPH_CALENDAR: &str = "\u{E787}";
/// Poll lengths Discord offers, in hours.
const POLL_HOURS: &[(u32, &str)] = &[(1, "1 hour"), (4, "4 hours"), (8, "8 hours"), (24, "24 hours"), (72, "3 days"), (168, "1 week"), (336, "2 weeks")];
fn strong(s: f32) -> FontId {
FontId::new(s, egui::FontFamily::Name(crate::style::BOLD.into()))
}
fn shadow() -> Shadow {
Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) }
}
/// "9:00 AM" (menus) — or "09:00" with the 24-hour clock on.
fn clock_upper(t: &DateTime<Local>) -> String {
if super::hour24() { t.format("%H:%M").to_string() } else { t.format("%-I:%M %p").to_string() }
}
/// "6 November at 1:00 pm", for the bar above the composer.
pub(super) fn schedule_label(t: &DateTime<Local>) -> String {
let time = if super::hour24() { t.format("%H:%M").to_string() } else { t.format("%-I:%M %P").to_string() };
format!("{} at {time}", t.format("%-d %B"))
}
/// Discord's quick picks: the next 9 AM and 1 PM, and Monday 9 AM.
fn schedule_presets(now: DateTime<Local>) -> Vec<(String, DateTime<Local>)> {
let at = |d: NaiveDate, h: u32| d.and_hms_opt(h, 0, 0).and_then(|n| Local.from_local_datetime(&n).earliest());
let today = now.date_naive();
let mut out: Vec<(String, DateTime<Local>)> = Vec::new();
for h in [9, 13] {
let (day, label) = if now.hour() < h { (today, "Today") } else { (today + Duration::days(1), "Tomorrow") };
if let Some(t) = at(day, h) {
out.push((format!("{label} at {}", clock_upper(&t)), t));
}
}
let ahead = match 7 - today.weekday().num_days_from_monday() {
7 => 7,
n => n,
};
if let Some(t) = at(today + Duration::days(ahead as i64), 9) {
if !out.iter().any(|(_, o)| *o == t) {
out.push((format!("Monday at {}", clock_upper(&t)), t));
}
}
out
}
/// Discord's gift icon (20px), centred on `c`.
pub(super) fn paint_gift(p: &egui::Painter, c: Pos2, color: Color32) {
super::paint_icon(p, Rect::from_center_size(c, vec2(20.0, 20.0)), crate::style::icon::GIFT, color);
}
/// Discord's sticker icon (20px), centred on `c`.
pub(super) fn paint_sticker(p: &egui::Painter, c: Pos2, color: Color32) {
super::paint_icon(p, Rect::from_center_size(c, vec2(20.0, 20.0)), crate::style::icon::STICKER, color);
}
/// Discord's Apps icon (20px) centred on `c`: a rounded square, a triangle,
/// a dot and a four-point sparkle in a 2 × 2 grid.
pub(super) fn paint_apps(p: &egui::Painter, c: Pos2, color: Color32) {
let (tl, tr, bl, br) = (c + vec2(-4.8, -4.6), c + vec2(4.8, -4.6), c + vec2(-4.8, 4.8), c + vec2(4.8, 4.8));
p.rect_filled(Rect::from_center_size(tl, vec2(8.0, 8.0)), 2.6, color);
p.add(egui::Shape::convex_polygon(vec![tr + vec2(0.0, -4.4), tr + vec2(4.4, 3.4), tr + vec2(-4.4, 3.4)], color, Stroke::new(1.2_f32, color)));
p.circle_filled(bl, 4.0, color);
let mut star = Vec::new();
for i in 0..8 {
let a = i as f32 * std::f32::consts::FRAC_PI_4 - std::f32::consts::FRAC_PI_2;
let r = if i % 2 == 0 { 4.6 } else { 1.7 };
star.push(br + vec2(a.cos() * r, a.sin() * r));
}
// (Not convex: drawn as a fan from the centre.)
let mut mesh = egui::Mesh::default();
mesh.colored_vertex(br, color);
for q in &star {
mesh.colored_vertex(*q, color);
}
for i in 0..8u32 {
mesh.add_triangle(0, 1 + i, 1 + (i + 1) % 8);
}
p.add(egui::Shape::mesh(mesh));
}
/// A Discord menu row: glyph, label, optional chevron. Returns the response.
fn menu_row(ui: &mut Ui, t: &Theme, glyph: Option<&str>, label: &str, chevron: bool, width: f32) -> egui::Response {
let (r, resp) = ui.allocate_exact_size(vec2(width, 36.0), Sense::click());
let hot = resp.hovered();
if hot {
ui.painter().rect_filled(r, 4.0, t.bg_hover);
}
let fg = if hot { t.header_primary } else { t.text_normal };
let mut x = r.left() + 8.0;
if let Some(g) = glyph {
ui.painter().text(pos2(x + 10.0, r.center().y), Align2::CENTER_CENTER, g, icon_font(18.0), fg);
x += 30.0;
}
ui.painter().text(pos2(x, r.center().y), Align2::LEFT_CENTER, label, FontId::proportional(14.0), fg);
if chevron {
ui.painter().text(pos2(r.right() - 12.0, r.center().y), Align2::CENTER_CENTER, icon::CHEVRON, icon_font(10.0), fg);
}
resp.on_hover_cursor(egui::CursorIcon::PointingHand)
}
/// A dark, rounded single-line input like Discord's forms.
fn form_input(ui: &mut Ui, t: &Theme, text: &mut String, hint: &str, max: usize, id: egui::Id) -> egui::Response {
let out = Frame::none()
.fill(t.input_bg)
.rounding(8.0)
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.inner_margin(Margin::symmetric(10.0, 9.0))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.add(
TextEdit::singleline(text)
.id(id)
.frame(false)
.desired_width(ui.available_width())
.hint_text(RichText::new(hint).color(t.text_muted))
.font(FontId::proportional(15.0))
.text_color(t.text_normal)
.char_limit(max),
)
});
if out.inner.has_focus() {
ui.painter().rect_stroke(out.response.rect, 8.0, Stroke::new(1.0_f32, BRAND));
}
out.inner
}
/// Buttons and combo boxes styled as Discord's form inputs.
fn input_look(ui: &mut Ui, t: &Theme) {
ui.style_mut().spacing.button_padding = vec2(12.0, 11.0);
let w = &mut ui.visuals_mut().widgets;
for s in [&mut w.inactive, &mut w.hovered, &mut w.active, &mut w.open] {
s.weak_bg_fill = t.input_bg;
s.bg_fill = t.input_bg;
s.rounding = egui::Rounding::same(8.0);
s.expansion = 0.0;
}
w.inactive.bg_stroke = Stroke::new(1.0_f32, t.border_subtle);
w.hovered.bg_stroke = Stroke::new(1.0_f32, t.interactive_muted);
w.open.bg_stroke = Stroke::new(1.0_f32, BRAND);
}
fn checkbox(ui: &mut Ui, t: &Theme, on: &mut bool, label: &str) -> egui::Response {
let g = ui.painter().layout_no_wrap(label.to_string(), FontId::proportional(14.0), t.text_normal);
let (r, resp) = ui.allocate_exact_size(vec2(26.0 + g.size().x, 24.0), Sense::click());
let b = Rect::from_center_size(pos2(r.left() + 10.0, r.center().y), vec2(20.0, 20.0));
if *on {
ui.painter().rect_filled(b, 5.0, BRAND);
ui.painter().text(b.center(), Align2::CENTER_CENTER, icon::CHECK, icon_font(11.0), Color32::WHITE);
} else {
ui.painter().rect_stroke(b, 5.0, Stroke::new(1.5_f32, if resp.hovered() { t.interactive_hover } else { t.interactive_normal }));
}
ui.painter().galley(pos2(r.left() + 28.0, r.center().y - g.size().y / 2.0), g, t.text_normal);
if resp.clicked() {
*on = !*on;
}
resp.on_hover_cursor(egui::CursorIcon::PointingHand)
}
fn button(ui: &mut Ui, label: &str, fill: Color32, fg: Color32, size: egui::Vec2, enabled: bool) -> egui::Response {
let (r, resp) = ui.allocate_exact_size(size, if enabled { Sense::click() } else { Sense::hover() });
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
let fill = if !enabled { fill.gamma_multiply(0.5) } else if resp.hovered() { fill.lerp_to_gamma(Color32::BLACK, 0.12) } else { fill };
ui.painter().rect_filled(r, 8.0, fill);
ui.painter().text(r.center(), Align2::CENTER_CENTER, label, strong(14.0), if enabled { fg } else { fg.gamma_multiply(0.6) });
resp
}
/// Modal chrome: dimmed app, centred card, title, close. Returns false on close
/// (`click_off`: a click on the dimmed app closes it too).
fn modal(ctx: &egui::Context, t: &Theme, id: &str, title: &str, width: f32, click_off: bool, body: impl FnOnce(&mut Ui)) -> bool {
let mut open = !ctx.input(|i| i.key_pressed(Key::Escape));
let screen = ctx.screen_rect();
egui::Area::new(egui::Id::new((id, "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(170));
// (The dim itself: a click in a drop-down or date picker isn't one.)
open &= !(click_off && r.clicked() && !ctx.memory(|m| m.any_popup_open()));
});
egui::Area::new(egui::Id::new(id)).order(Order::Foreground).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
ui.ctx().move_to_top(ui.layer_id());
// Discord's modal card (2026-11-22): surface-high, 1 px border-normal
// (rgba(143,143,152,.2)), 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::same(16.0))
.show(ui, |ui| {
ui.set_width(width);
ui.spacing_mut().item_spacing.y = 0.0;
let top = ui.cursor().min;
ui.label(RichText::new(title).font(strong(20.0)).color(t.header_primary));
let x = Rect::from_center_size(pos2(top.x + width - 10.0, top.y + 12.0), vec2(26.0, 26.0));
let xr = ui.interact(x, egui::Id::new((id, "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 });
open &= !xr.clicked();
ui.add_space(20.0);
body(ui);
});
});
open
}
fn section_label(ui: &mut Ui, t: &Theme, text: &str) {
ui.label(RichText::new(text).font(strong(14.0)).color(t.header_primary));
ui.add_space(8.0);
}
/// "23h left" / "3d left" / "Poll closed".
fn time_left(poll: &Poll) -> String {
if poll.finalized() {
return "Poll closed".into();
}
let Some(end) = poll.expiry.as_deref().and_then(|e| chrono::DateTime::parse_from_rfc3339(e).ok()) else { return String::new() };
let left = end.with_timezone(&Local) - Local::now();
if left.num_seconds() <= 0 {
"Poll closed".into()
} else if left.num_days() >= 1 {
format!("{}d left", left.num_days())
} else if left.num_hours() >= 1 {
format!("{}h left", left.num_hours())
} else {
format!("{}m left", left.num_minutes().max(1))
}
}
fn emoji_json(e: &PickedEmoji) -> Value {
match e {
PickedEmoji::Unicode(s) => json!({ "name": s }),
PickedEmoji::Custom { id, name, animated } => json!({ "id": id.to_string(), "name": name, "animated": animated }),
}
}
fn emoji_image(e: &PickedEmoji) -> String {
match e {
PickedEmoji::Unicode(s) => crate::emoji::twemoji_url(s),
PickedEmoji::Custom { id, animated, .. } => format!("https://cdn.discordapp.com/emojis/{id}.{}?size=48", if *animated { "gif" } else { "png" }),
}
}
fn reaction_image(e: &discord::model::ReactionEmoji) -> Option<String> {
match (e.id, e.name.as_deref()) {
(Some(id), _) => Some(format!("https://cdn.discordapp.com/emojis/{id}.{}?size=48", if e.animated { "gif" } else { "png" })),
(None, Some(n)) if !n.is_empty() => Some(crate::emoji::twemoji_url(n)),
_ => None,
}
}
/// A slash command (or one of its subcommands) as the launcher lists it.
struct CommandEntry {
app: String,
app_icon: Option<String>,
cmd: Value,
path: Vec<String>,
description: String,
}
impl CommandEntry {
fn label(&self) -> String {
let mut s = format!("/{}", self.cmd["name"].as_str().unwrap_or(""));
for p in &self.path {
s.push(' ');
s.push_str(p);
}
s
}
}
/// Chat-input commands from an application-command-index reply, with
/// subcommands spread out like Discord's list.
fn command_entries(index: &Value) -> Vec<CommandEntry> {
let apps: Vec<&Value> = index["applications"].as_array().map(|a| a.iter().collect()).unwrap_or_default();
let app_of = |id: &str| apps.iter().find(|a| a["id"].as_str() == Some(id));
let mut out = Vec::new();
for cmd in index["application_commands"].as_array().into_iter().flatten() {
if cmd["type"].as_u64().unwrap_or(1) != 1 {
continue;
}
let app_id = cmd["application_id"].as_str().unwrap_or("");
let app = app_of(app_id);
let app_name = app.and_then(|a| a["name"].as_str()).unwrap_or("App").to_string();
let app_icon = app.and_then(|a| a["icon"].as_str()).map(|h| format!("https://cdn.discordapp.com/app-icons/{app_id}/{h}.png?size=64"));
let entry = |path: Vec<String>, desc: &Value| CommandEntry {
app: app_name.clone(),
app_icon: app_icon.clone(),
cmd: cmd.clone(),
path,
description: desc.as_str().unwrap_or("").to_string(),
};
let opts = cmd["options"].as_array().cloned().unwrap_or_default();
let subs: Vec<&Value> = opts.iter().filter(|o| matches!(o["type"].as_u64(), Some(1 | 2))).collect();
if subs.is_empty() {
out.push(entry(Vec::new(), &cmd["description"]));
continue;
}
for s in subs {
let name = s["name"].as_str().unwrap_or("").to_string();
if s["type"].as_u64() == Some(2) {
for leaf in s["options"].as_array().into_iter().flatten().filter(|o| o["type"].as_u64() == Some(1)) {
out.push(entry(vec![name.clone(), leaf["name"].as_str().unwrap_or("").to_string()], &leaf["description"]));
}
} else {
out.push(entry(vec![name], &s["description"]));
}
}
}
out
}
/// Discord's built-in commands: they only change your message's text.
fn builtin_commands() -> Vec<CommandEntry> {
[
("shrug", "Appends ¯\\_(ツ)_/¯ to your message."),
("tableflip", "Appends (╯°□°)╯︵ ┻━┻ to your message."),
("unflip", "Appends ┬─┬ノ( º _ ºノ) to your message."),
("me", "Displays text with emphasis."),
("spoiler", "Marks your message as a spoiler."),
]
.into_iter()
.map(|(name, desc)| {
let required = matches!(name, "me" | "spoiler");
CommandEntry {
app: "Built-in".into(),
app_icon: None,
cmd: json!({
"name": name,
"builtin": true,
"description": desc,
"options": [{ "type": 3, "name": "message", "description": "Your message", "required": required }],
}),
path: Vec::new(),
description: desc.to_string(),
}
})
.collect()
}
/// The words that start a linked account's commands: the platform's own name
/// first (the one listed), then what people call it ("/fortnite" for Epic
/// Games), which show up once you start typing them.
fn connection_words(kind: &str) -> Vec<&str> {
match kind {
"epicgames" => vec!["epicgames", "fortnite"],
"twitter" => vec!["twitter", "x"],
"riotgames" => vec!["riotgames", "riot", "valorant"],
"leagueoflegends" => vec!["leagueoflegends", "league", "lol"],
"playstation" => vec!["playstation", "psn"],
"battlenet" => vec!["battlenet", "bnet"],
"youtube" => vec!["youtube", "yt"],
other => vec![other],
}
}
/// The commands for your linked accounts (`/users/@me/connections`): for each
/// one "/platform username" and, where the platform has profile pages,
/// "/platform profile"; Spotify also gets "/spotify playlist <name>" per
/// playlist (`playlists`: None while they load). Picking one puts its text in
/// the message box instead of sending anything.
fn connection_commands(connections: &Value, playlists: Option<&Result<Value, String>>) -> Vec<CommandEntry> {
let mut out = Vec::new();
for c in connections.as_array().into_iter().flatten() {
let Ok(a) = serde_json::from_value::<discord::model::ConnectedAccount>(c.clone()) else { continue };
if a.kind.is_empty() || a.name.trim().is_empty() || a.kind.contains(char::is_whitespace) {
continue;
}
let platform = super::brand_icons::platform_name(&a.kind);
for (i, word) in connection_words(&a.kind).into_iter().enumerate() {
// Each linked account is its own section with its own icon on the rail,
// like an app's commands.
let entry = |path: &[&str], insert: Option<&str>, description: String| CommandEntry {
app: platform.clone(),
app_icon: None,
cmd: json!({ "name": word, "connection": a.kind, "insert": insert, "alias": i > 0 }),
path: path.iter().map(|s| s.to_string()).collect(),
description,
};
out.push(entry(&["username"], Some(&a.name), format!("Your {platform} username: {}", a.name)));
if let Some(link) = a.link() {
out.push(entry(&["profile"], Some(&link), format!("A link to your {platform} profile")));
}
if a.kind == "spotify" {
match playlists {
Some(Ok(list)) => {
let list: Vec<(&str, &str)> = list.as_array().into_iter().flatten().filter_map(|p| Some((p.get(0)?.as_str()?, p.get(1)?.as_str()?))).collect();
if list.is_empty() {
out.push(entry(&["playlist"], None, "No public playlists on your Spotify profile".into()));
}
for (name, url) in list {
out.push(entry(&["playlist", name], Some(url), "A link to this playlist".into()));
}
}
Some(Err(e)) => out.push(entry(&["playlist"], None, format!("Couldn't load your playlists: {e}"))),
None => out.push(entry(&["playlist"], None, "Loading your playlists…".into())),
}
}
}
}
out
}
/// Whether the launcher lists this entry for what's typed after "/" (`q`,
/// lowercase): names that start with it first, then anything containing it.
/// Nicknames ("/fortnite") only once they're being typed.
fn entry_matches(e: &CommandEntry, q: &str) -> bool {
let label = e.label().trim_start_matches('/').to_lowercase();
if e.cmd["alias"].as_bool() == Some(true) {
return !q.is_empty() && label.starts_with(q);
}
q.is_empty() || label.contains(q)
}
/// The value options of a command at `path` (below its subcommands).
fn option_defs(cmd: &Value, path: &[String]) -> Vec<Value> {
let mut opts = cmd["options"].as_array().cloned().unwrap_or_default();
for seg in path {
opts = opts
.iter()
.find(|o| o["name"].as_str() == Some(seg.as_str()))
.and_then(|o| o["options"].as_array().cloned())
.unwrap_or_default();
}
opts.into_iter().filter(|o| !matches!(o["type"].as_u64(), Some(1 | 2))).collect()
}
impl RustCord {
// ---- "+" menu -----------------------------------------------------------
/// The "+" button was clicked: toggle the menu above it.
pub(super) fn toggle_plus_menu(&mut self, ch: Id, button: Rect) {
if self.compose.plus_menu.is_some_and(|(c, _, _)| c == ch) {
self.compose.plus_menu = None;
} else {
self.compose.plus_menu = Some((ch, button, self.ctx.cumulative_pass_nr()));
}
}
pub(super) fn plus_menu_ui(&mut self, ctx: &egui::Context) {
let Some((ch, button, opened)) = self.compose.plus_menu else { return };
let Some(channel) = self.store.channels.get(&ch).cloned() else {
self.compose.plus_menu = None;
return;
};
let t = self.theme.clone();
let perms = self.store.channel_perms(&channel);
let has = |bit: u64| perms.map_or(true, |p| p & bit != 0);
let guild_text = channel.guild_id.is_some() && matches!(channel.kind, 0 | 5);
enum Pick {
Upload,
Thread,
Poll,
Apps,
Schedule(DateTime<Local>),
Custom,
}
let mut pick = None;
let sub_id = egui::Id::new("plus_schedule_sub");
let mut sub_open = ctx.data(|d| d.get_temp::<bool>(sub_id).unwrap_or(false));
let mut sched_row = Rect::NOTHING;
const W: f32 = 185.0;
let menu = egui::Area::new(egui::Id::new("plus_menu"))
.order(Order::Foreground)
.pivot(Align2::LEFT_BOTTOM)
.fixed_pos(button.left_top() + vec2(0.0, -8.0))
.sized_off_screen(ctx)
.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::same(8.0))
.show(ui, |ui| {
ui.set_width(W);
ui.spacing_mut().item_spacing.y = 2.0;
let mut other = false;
if has(discord::model::permissions::ATTACH_FILES) {
let r = menu_row(ui, &t, Some(GLYPH_UPLOAD), "Upload a File", false, W);
other |= r.hovered();
if r.clicked() {
pick = Some(Pick::Upload);
}
}
if guild_text && has(CREATE_PUBLIC_THREADS) {
let r = menu_row(ui, &t, Some(GLYPH_THREAD), "Create Thread", false, W);
other |= r.hovered();
if r.clicked() {
pick = Some(Pick::Thread);
}
}
if has(SEND_POLLS) {
let r = menu_row(ui, &t, Some(GLYPH_POLL), "Create Poll", false, W);
other |= r.hovered();
if r.clicked() {
pick = Some(Pick::Poll);
}
}
if has(USE_APPLICATION_COMMANDS) {
let r = menu_row(ui, &t, Some(GLYPH_APPS), "Use Apps", false, W);
other |= r.hovered();
if r.clicked() {
pick = Some(Pick::Apps);
}
}
let r = menu_row(ui, &t, Some(GLYPH_CALENDAR), "Schedule Message", true, W);
if r.hovered() || r.clicked() {
sub_open = true;
}
if other {
sub_open = false;
}
sched_row = r.rect;
});
});
let mut sub_rect = Rect::NOTHING;
if sub_open {
let presets = schedule_presets(Local::now());
let area = egui::Area::new(egui::Id::new("plus_schedule_menu"))
.order(Order::Foreground)
.pivot(Align2::LEFT_CENTER)
.fixed_pos(pos2(sched_row.right() + 12.0, sched_row.center().y))
.constrain(true)
.show(ctx, |ui| {
ui.ctx().move_to_top(ui.layer_id());
Frame::none()
.fill(t.bg_floating)
.rounding(8.0)
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.shadow(shadow())
.inner_margin(Margin::same(8.0))
.show(ui, |ui| {
ui.set_width(172.0);
ui.spacing_mut().item_spacing.y = 2.0;
for (label, at) in &presets {
if menu_row(ui, &t, None, label, false, 172.0).clicked() {
pick = Some(Pick::Schedule(*at));
}
}
ui.add_space(4.0);
let y = ui.cursor().top();
ui.painter().hline((ui.max_rect().left() + 4.0)..=(ui.max_rect().right() - 4.0), y, Stroke::new(1.0_f32, t.border_subtle));
ui.add_space(6.0);
if menu_row(ui, &t, None, "Custom...", false, 172.0).clicked() {
pick = Some(Pick::Custom);
}
});
});
sub_rect = area.response.rect;
}
let pressed_outside = ctx.cumulative_pass_nr() > opened + 1
&& ctx.input(|i| i.pointer.any_pressed())
&& ctx
.input(|i| i.pointer.interact_pos())
.is_some_and(|p| !menu.response.rect.contains(p) && !sub_rect.contains(p) && !button.contains(p));
if pick.is_some() || pressed_outside || ctx.input(|i| i.key_pressed(Key::Escape)) {
self.compose.plus_menu = None;
sub_open = false;
}
ctx.data_mut(|d| d.insert_temp(sub_id, sub_open));
match pick {
Some(Pick::Upload) => self.pick_files(ch),
Some(Pick::Thread) => {
self.compose.new_thread = Some(ThreadDraft { channel: ch, name: String::new(), message: String::new(), private: false });
}
Some(Pick::Poll) => {
self.compose.poll = Some(PollDraft { channel: ch, question: String::new(), answers: vec![(String::new(), None), (String::new(), None)], hours: 24, multi: false });
}
Some(Pick::Apps) => {
self.drafts.insert(ch, "/".into());
self.compose.apps_dismissed = None;
self.compose.focus_composer = true;
}
Some(Pick::Schedule(at)) => self.compose.schedule = Some((ch, at)),
Some(Pick::Custom) => {
let soon = Local::now() + Duration::minutes(15);
let minutes = ((soon.hour() * 60 + soon.minute()) / 15 + 1) * 15;
let (date, minutes) = if minutes >= 1440 { (soon.date_naive() + Duration::days(1), 0) } else { (soon.date_naive(), minutes) };
self.compose.schedule_dialog = Some(ScheduleDraft { channel: ch, date, minutes });
}
None => {}
}
}
// ---- scheduled messages -------------------------------------------------
/// "Scheduling message for 6 November at 1:00 pm ✕" above the composer.
pub(super) fn schedule_bar(&mut self, ui: &mut Ui, ch: Id) {
let Some((_, at)) = self.compose.schedule.filter(|(c, _)| *c == ch) else { return };
let t = self.theme.clone();
let mut clear = false;
Frame::none()
.fill(t.bg_secondary)
.rounding(egui::Rounding { nw: 8.0, ne: 8.0, sw: 0.0, se: 0.0 })
.inner_margin(Margin::symmetric(14.0, 7.0))
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(format!("Scheduling message for {}", schedule_label(&at))).size(14.0).color(t.text_normal));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
ui.painter().circle_filled(r.center(), 8.0, if resp.hovered() { t.interactive_hover } else { t.interactive_normal });
ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(8.0), t.bg_secondary);
clear = resp.on_hover_text("Cancel scheduling").clicked();
});
});
});
if clear {
self.compose.schedule = None;
}
}
/// Enter in a composer with a time set: hand the text to Discord's scheduler.
pub(super) fn send_scheduled(&mut self, ch: Id, text: String) {
let Some((_, at)) = self.compose.schedule.take() else { return };
if at <= Local::now() {
self.toast("That time has already passed.", true);
return;
}
let content = self.expand_shortcodes(&text, ch);
let content = self.resolve_mentions(&content, ch);
let ts =at.with_timezone(&chrono::Utc).format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
self.ctx.data_mut(|d| d.insert_temp(egui::Id::new("sched_label"), schedule_label(&at)));
let body = json!({ "channel_id": ch.to_string(), "content": content, "scheduled_timestamp": ts, "flags": 0, "attachments": [] });
self.api("sched:create", Method::POST, "/users/@me/scheduled-messages", Some(body));
}
/// "Schedule Message" (Custom…): date and time, then Set Schedule.
pub(super) fn schedule_dialog_ui(&mut self, ctx: &egui::Context) {
let Some(mut d) = self.compose.schedule_dialog.take() else { return };
let t = self.theme.clone();
let mut set = false;
let mut cancel = false;
let open = modal(ctx, &t, "schedule_dialog", "Schedule Message", 420.0, true, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 12.0;
let half = (ui.available_width() - 12.0) / 2.0;
ui.vertical(|ui| {
ui.set_width(half);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
ui.label(RichText::new("Date").font(strong(14.0)).color(t.header_primary));
ui.label(RichText::new("*").font(strong(14.0)).color(t.danger));
});
ui.add_space(8.0);
ui.scope(|ui| {
input_look(ui, &t);
let r = ui.add_sized(
vec2(half, 40.0),
egui_extras::DatePickerButton::new(&mut d.date).id_salt("schedule_date").calendar_week(false).show_icon(false).format("%-d %b %Y"),
);
ui.painter().text(pos2(r.rect.right() - 16.0, r.rect.center().y), Align2::CENTER_CENTER, GLYPH_CALENDAR, icon_font(15.0), t.interactive_normal);
});
});
ui.vertical(|ui| {
ui.set_width(half);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
ui.label(RichText::new("Time").font(strong(14.0)).color(t.header_primary));
ui.label(RichText::new("*").font(strong(14.0)).color(t.danger));
});
ui.add_space(8.0);
let fmt = |m: u32| {
let tt = chrono::NaiveTime::from_hms_opt(m / 60, m % 60, 0).unwrap_or_default();
if super::hour24() { tt.format("%H:%M").to_string() } else { tt.format("%I:%M %P").to_string() }
};
ui.scope(|ui| {
input_look(ui, &t);
ComboBox::from_id_salt("schedule_time").width(half - 24.0).selected_text(RichText::new(fmt(d.minutes)).size(15.0)).height(260.0).show_ui(ui, |ui| {
for m in (0..1440).step_by(15) {
ui.selectable_value(&mut d.minutes, m, fmt(m));
}
});
});
});
});
ui.add_space(20.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 12.0;
let w = (ui.available_width() - 12.0) / 2.0;
cancel = button(ui, "Cancel", overlay(0.12), t.header_primary, vec2(w, 38.0), true).clicked();
set = button(ui, "Set Schedule", BRAND, Color32::WHITE, vec2(w, 38.0), true).clicked();
});
});
if set {
let at = d.date.and_hms_opt(d.minutes / 60, d.minutes % 60, 0).and_then(|n| Local.from_local_datetime(&n).earliest());
match at {
Some(at) if at > Local::now() => {
self.compose.schedule = Some((d.channel, at));
return;
}
_ => self.toast("Pick a time in the future.", true),
}
}
if open && !cancel {
self.compose.schedule_dialog = Some(d);
}
}
// ---- polls --------------------------------------------------------------
/// Discord's "Create a Poll" dialog.
pub(super) fn poll_dialog_ui(&mut self, ctx: &egui::Context) {
let Some(mut d) = self.compose.poll.take() else { return };
let t = self.theme.clone();
let mut post = false;
let mut pick_emoji: Option<(usize, Pos2)> = None;
let busy = self.api_busy("poll:create");
// Clicking off closes it only while nothing is written (and not while
// its emoji picker, which sits outside the card, is open).
let empty = d.question.is_empty() && d.answers.iter().all(|(a, e)| a.is_empty() && e.is_none());
let click_off = empty && !busy && self.emoji_picker.is_none();
let open = modal(ctx, &t, "poll_dialog", "Create a Poll", 448.0, click_off, |ui| {
section_label(ui, &t, "Question");
form_input(ui, &t, &mut d.question, "What question do you want to ask?", 300, egui::Id::new("poll_question"));
ui.add_space(4.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
ui.label(RichText::new(format!("{} / 300", d.question.chars().count())).size(12.0).color(t.text_muted));
});
ui.add_space(14.0);
section_label(ui, &t, "Answers");
let mut remove = None;
let n = d.answers.len();
let full = ui.available_width() - 16.0;
for (i, (text, emoji)) in d.answers.iter_mut().enumerate() {
let row = Frame::none()
.fill(t.input_bg)
.rounding(8.0)
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.inner_margin(Margin::symmetric(8.0, 6.0))
.show(ui, |ui| {
ui.set_width(full);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
let (er, eresp) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click());
let eresp = eresp.on_hover_cursor(egui::CursorIcon::PointingHand);
match emoji.as_ref() {
Some(e) => egui::Image::new(emoji_image(e)).paint_at(ui, er.shrink(2.0)),
None => {
let c = if eresp.hovered() { t.interactive_hover } else { t.interactive_normal };
ui.painter().text(er.center(), Align2::CENTER_CENTER, icon::EMOJI, icon_font(17.0), c);
}
}
if eresp.on_hover_text("Add an emoji").clicked() {
pick_emoji = Some((i, er.right_bottom()));
}
ui.add(
TextEdit::singleline(text)
.id(egui::Id::new(("poll_answer", i)))
.frame(false)
.desired_width(full - 24.0 - 24.0 - 16.0)
.hint_text(RichText::new("Type your answer").color(t.text_muted))
.font(FontId::proportional(15.0))
.text_color(t.text_normal)
.char_limit(55),
);
let (tr, tresp) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click());
let tresp = tresp.on_hover_cursor(egui::CursorIcon::PointingHand);
let c = if tresp.hovered() { t.danger } else { t.interactive_normal };
ui.painter().text(tr.center(), Align2::CENTER_CENTER, icon::DELETE, icon_font(15.0), c);
if tresp.on_hover_text("Remove answer").clicked() {
remove = Some(i);
}
});
});
let _ = row;
if i + 1 < n {
ui.add_space(8.0);
}
}
if let Some(i) = remove {
if d.answers.len() > 2 {
d.answers.remove(i);
} else {
d.answers[i] = (String::new(), None);
}
}
if d.answers.len() < 10 {
ui.add_space(10.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
let g = ui.painter().layout_no_wrap("Add another answer".into(), strong(14.0), t.header_primary);
let (r, resp) = ui.allocate_exact_size(vec2(g.size().x + 44.0, 36.0), Sense::click());
ui.painter().rect_filled(r, 8.0, if resp.hovered() { overlay(0.2) } else { overlay(0.12) });
ui.painter().text(pos2(r.left() + 18.0, r.center().y), Align2::CENTER_CENTER, icon::ADD, icon_font(12.0), t.header_primary);
ui.painter().galley(pos2(r.left() + 32.0, r.center().y - g.size().y / 2.0), g, t.header_primary);
if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
d.answers.push((String::new(), None));
}
});
}
ui.add_space(16.0);
section_label(ui, &t, "Duration");
let label = POLL_HOURS.iter().find(|(h, _)| *h == d.hours).map(|(_, l)| *l).unwrap_or("24 hours");
ui.scope(|ui| {
input_look(ui, &t);
ComboBox::from_id_salt("poll_duration").width(ui.available_width() - 8.0).selected_text(RichText::new(label).size(15.0)).show_ui(ui, |ui| {
for (h, l) in POLL_HOURS {
ui.selectable_value(&mut d.hours, *h, *l);
}
});
});
ui.add_space(20.0);
ui.horizontal(|ui| {
checkbox(ui, &t, &mut d.multi, "Allow Multiple Answers");
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let ready = !d.question.trim().is_empty() && d.answers.iter().filter(|(a, _)| !a.trim().is_empty()).count() >= 1 && !busy;
post = button(ui, if busy { "Posting…" } else { "Post" }, BRAND, Color32::WHITE, vec2(80.0, 38.0), ready).clicked();
});
});
});
if let Some((i, at)) = pick_emoji {
self.open_emoji_picker(PickerTarget::PollAnswer(i), at + vec2(8.0, -200.0));
}
if post {
let answers: Vec<Value> = d
.answers
.iter()
.filter(|(a, _)| !a.trim().is_empty())
.map(|(a, e)| {
let mut media = json!({ "text": a.trim() });
if let Some(e) = e {
media["emoji"] = emoji_json(e);
}
json!({ "poll_media": media })
})
.collect();
let body = json!({
"content": "",
"nonce": Id::from_timestamp_ms(crate::app::now_ms()).0.to_string(),
"poll": {
"question": { "text": d.question.trim() },
"answers": answers,
"duration": d.hours,
"allow_multiselect": d.multi,
"layout_type": 1,
},
});
self.api("poll:create", Method::POST, format!("/channels/{}/messages", d.channel), Some(body));
}
if open {
self.compose.poll = Some(d);
}
}
/// Vote (or take your votes back with an empty list).
pub(super) fn vote_poll(&mut self, ch: Id, msg: Id, answers: Vec<u32>) {
if let Some(poll) = self.store.message_mut(ch, msg).and_then(|m| m.poll.as_mut()) {
let mine: Vec<u32> = poll.results.as_ref().map(|r| r.answer_counts.iter().filter(|c| c.me_voted).map(|c| c.id).collect()).unwrap_or_default();
for a in mine.iter().filter(|a| !answers.contains(a)) {
poll.apply_vote(*a, false, true);
}
for a in answers.iter().filter(|a| !mine.contains(a)) {
poll.apply_vote(*a, true, true);
}
}
let ids: Vec<String> = answers.iter().map(|a| a.to_string()).collect();
self.api("poll:vote", Method::PUT, format!("/channels/{ch}/polls/{msg}/answers/@me"), Some(json!({ "answer_ids": ids })));
}
/// A poll in a message, Discord's card: question, answers to pick (then
/// Vote), or the results with bars once you've voted or it's closed.
pub(super) fn poll_ui(&self, ui: &mut Ui, m: &Message, poll: &Poll, actions: &mut Vec<UiAction>) {
let t = &self.theme;
let sel_id = egui::Id::new(("poll_sel", m.id.0));
let res_id = egui::Id::new(("poll_res", m.id.0));
let mut sel: Vec<u32> = ui.data(|d| d.get_temp(sel_id).unwrap_or_default());
let mut peek = ui.data(|d| d.get_temp::<bool>(res_id).unwrap_or(false));
let closed = poll.finalized() || time_left(poll) == "Poll closed";
let voted = poll.voted();
let results = voted || closed || peek;
let total = poll.total_votes();
let top = poll.answers.iter().map(|a| poll.votes(a.answer_id).0).max().unwrap_or(0);
let w = ui.available_width().min(460.0);
Frame::none()
.fill(t.bg_secondary)
.rounding(8.0)
.stroke(Stroke::new(1.0_f32, t.border_subtle))
.inner_margin(Margin::same(16.0))
.show(ui, |ui| {
ui.set_width(w - 32.0);
ui.spacing_mut().item_spacing.y = 0.0;
ui.add(egui::Label::new(RichText::new(poll.question.text.as_deref().unwrap_or("")).font(strong(17.0)).color(t.header_primary)).wrap());
ui.add_space(4.0);
let sub = if poll.allow_multiselect { "Select one or more answers" } else { "Select one answer" };
ui.label(RichText::new(sub).size(13.0).color(t.text_muted));
ui.add_space(12.0);
for (i, a) in poll.answers.iter().enumerate() {
if i > 0 {
ui.add_space(8.0);
}
let (votes, mine) = poll.votes(a.answer_id);
let picked = sel.contains(&a.answer_id);
let (row, resp) = ui.allocate_exact_size(vec2(w - 32.0, 46.0), if results { Sense::hover() } else { Sense::click() });
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
let p = ui.painter();
if results {
p.rect_filled(row, 8.0, overlay(0.05));
let pct = if total == 0 { 0.0 } else { votes as f32 / total as f32 };
if pct > 0.0 {
let fill = Rect::from_min_size(row.min, vec2(row.width() * pct, row.height()));
let c = if mine { BRAND.gamma_multiply(0.45) } else if closed && votes == top { overlay(0.18) } else { overlay(0.1) };
p.rect_filled(fill, 8.0, c);
}
if mine {
p.rect_stroke(row, 8.0, Stroke::new(1.5_f32, BRAND));
}
} else {
p.rect_filled(row, 8.0, if resp.hovered() { overlay(0.1) } else { overlay(0.05) });
if picked {
p.rect_stroke(row, 8.0, Stroke::new(1.5_f32, BRAND));
}
}
let mut x = row.left() + 14.0;
if let Some(url) = a.poll_media.emoji.as_ref().and_then(reaction_image) {
egui::Image::new(url).paint_at(ui, Rect::from_center_size(pos2(x + 11.0, row.center().y), vec2(22.0, 22.0)));
x += 32.0;
}
let right_w = if results { 120.0 } else { 36.0 };
let g = ui.painter().layout(a.poll_media.text.clone().unwrap_or_default(), strong(15.0), t.header_primary, row.right() - right_w - x);
ui.painter().galley(pos2(x, row.center().y - g.size().y / 2.0), g, t.header_primary);
if results {
let pct = if total == 0 { 0 } else { (votes as f32 * 100.0 / total as f32).round() as u32 };
let r = ui.painter().text(pos2(row.right() - 14.0, row.center().y), Align2::RIGHT_CENTER, format!("{pct}%"), strong(14.0), t.header_primary);
let label = if votes == 1 { "1 vote".to_string() } else { format!("{votes} votes") };
let r2 = ui.painter().text(pos2(r.left() - 8.0, row.center().y), Align2::RIGHT_CENTER, label, FontId::proportional(13.0), t.text_muted);
if mine {
let c = pos2(r2.left() - 14.0, row.center().y);
ui.painter().circle_filled(c, 8.0, BRAND);
ui.painter().text(c, Align2::CENTER_CENTER, icon::CHECK, icon_font(8.0), Color32::WHITE);
}
} else {
let c = pos2(row.right() - 22.0, row.center().y);
if poll.allow_multiselect {
let b = Rect::from_center_size(c, vec2(18.0, 18.0));
if picked {
ui.painter().rect_filled(b, 4.0, BRAND);
ui.painter().text(c, Align2::CENTER_CENTER, icon::CHECK, icon_font(10.0), Color32::WHITE);
} else {
ui.painter().rect_stroke(b, 4.0, Stroke::new(1.5_f32, t.interactive_normal));
}
} else if picked {
ui.painter().circle_filled(c, 9.0, BRAND);
ui.painter().circle_filled(c, 3.5, Color32::WHITE);
} else {
ui.painter().circle_stroke(c, 8.5, Stroke::new(1.5_f32, t.interactive_normal));
}
if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
if picked {
sel.retain(|s| *s != a.answer_id);
} else if poll.allow_multiselect {
sel.push(a.answer_id);
} else {
sel = vec![a.answer_id];
}
}
}
}
ui.add_space(14.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
let votes = if total == 1 { "1 vote".to_string() } else { format!("{total} votes") };
let left = time_left(poll);
let info = if left.is_empty() { votes } else { format!("{votes} • {left}") };
ui.label(RichText::new(info).size(13.0).color(t.text_muted));
let link = if voted && !closed {
Some("Remove Vote")
} else if !closed && peek {
Some("Go back to vote")
} else if !closed && !voted {
Some("Show results")
} else {
None
};
if let Some(l) = link {
ui.label(RichText::new("•").size(13.0).color(t.text_muted));
let r = ui.add(egui::Label::new(RichText::new(l).size(13.0).color(t.text_normal)).selectable(false).sense(Sense::click()));
let r = r.on_hover_cursor(egui::CursorIcon::PointingHand);
if r.hovered() {
ui.painter().hline(r.rect.x_range(), r.rect.bottom(), Stroke::new(1.0_f32, t.text_normal));
}
if r.clicked() {
if l == "Remove Vote" {
actions.push(UiAction::PollVote { channel: m.channel_id, msg: m.id, answers: Vec::new() });
sel.clear();
} else {
peek = !peek;
}
}
}
if !results {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if button(ui, "Vote", BRAND, Color32::WHITE, vec2(72.0, 34.0), !sel.is_empty()).clicked() {
actions.push(UiAction::PollVote { channel: m.channel_id, msg: m.id, answers: sel.clone() });
sel.clear();
peek = false;
}
});
}
});
});
ui.data_mut(|d| {
d.insert_temp(sel_id, sel);
d.insert_temp(res_id, peek);
});
}
// ---- threads ------------------------------------------------------------
/// Discord's "New Thread" side panel: name, private toggle, first message.
pub(super) fn new_thread_panel(&mut self, ui: &mut Ui) {
let Some(mut d) = self.compose.new_thread.take() else { return };
let t = self.theme.clone();
let busy = self.api_busy("thread:create");
let channel = self.store.channels.get(&d.channel).cloned();
let can_private = channel.as_ref().is_some_and(|c| c.kind == 0 && self.store.channel_perms(c).map_or(true, |p| p & CREATE_PRIVATE_THREADS != 0));
let mut close = false;
let mut submit = false;
let (head, _) = ui.allocate_exact_size(vec2(ui.available_width(), 48.0), Sense::hover());
ui.painter().hline(head.x_range(), head.bottom(), Stroke::new(1.0_f32, t.border_subtle));
ui.painter().text(pos2(head.left() + 22.0, head.center().y), Align2::CENTER_CENTER, GLYPH_THREAD, icon_font(18.0), t.interactive_normal);
ui.painter().text(pos2(head.left() + 42.0, head.center().y), Align2::LEFT_CENTER, "New Thread", strong(16.0), t.header_primary);
let x = Rect::from_center_size(pos2(head.right() - 24.0, head.center().y), vec2(28.0, 28.0));
let xr = ui.interact(x, egui::Id::new("new_thread_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(14.0), if xr.hovered() { t.header_primary } else { t.interactive_normal });
close |= xr.clicked();
let body_h = if can_private { 330.0 } else { 262.0 };
ui.add_space((ui.available_height() - body_h).max(12.0));
Frame::none().inner_margin(Margin { left: 16.0, right: 16.0, top: 0.0, bottom: 16.0 }).show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
let (c, _) = ui.allocate_exact_size(vec2(64.0, 64.0), Sense::hover());
ui.painter().circle_filled(c.center(), 32.0, overlay(0.12));
ui.painter().text(c.center(), Align2::CENTER_CENTER, GLYPH_THREAD, icon_font(28.0), t.header_primary);
ui.add_space(16.0);
section_label(ui, &t, "Thread Name");
form_input(ui, &t, &mut d.name, "New Thread", 100, egui::Id::new("new_thread_name"));
if can_private {
ui.add_space(20.0);
section_label(ui, &t, "Private Thread");
checkbox(ui, &t, &mut d.private, "Only people you invite and moderators can see");
}
ui.add_space(20.0);
let id = egui::Id::new("new_thread_message");
let enter = ui.memory(|m| m.has_focus(id)) && ui.input_mut(|i| !i.modifiers.shift && i.consume_key(egui::Modifiers::NONE, Key::Enter));
Frame::none().fill(t.input_bg).rounding(8.0).stroke(Stroke::new(1.0_f32, t.border_subtle)).inner_margin(Margin::symmetric(12.0, 11.0)).show(ui, |ui| {
ui.horizontal(|ui| {
let r = ui.add(
TextEdit::multiline(&mut d.message)
.id(id)
.frame(false)
.desired_rows(1)
.desired_width(ui.available_width() - 30.0)
.hint_text(RichText::new(if busy { "Creating thread…" } else { "Enter a message to start the conversation!" }).color(t.text_muted))
.font(FontId::proportional(15.0))
.text_color(t.text_normal),
);
if !busy && ui.memory(|m| m.focused().is_none()) {
r.request_focus();
}
ui.label(RichText::new(icon::EMOJI).font(icon_font(20.0)).color(t.interactive_normal));
});
});
submit = enter && !busy && !d.message.trim().is_empty();
});
if submit {
let name = match d.name.trim() {
"" => d.message.trim().chars().take(40).collect::<String>(),
n => n.to_string(),
};
let body = json!({
"name": name,
"type": if d.private { 12 } else { 11 },
"auto_archive_duration": 4320,
"location": "Plus Button",
});
self.api("thread:create", Method::POST, format!("/channels/{}/threads", d.channel), Some(body));
}
if !close && !ui.input(|i| i.key_pressed(Key::Escape)) {
self.compose.new_thread = Some(d);
}
}
// ---- apps / slash commands ----------------------------------------------
/// The command list Discord shows while the message starts with "/":
/// as wide as the composer, an app rail on the left, arrow keys and
/// Enter/Tab to pick. Built-in commands (/shrug, /me…) come last.
/// Your linked accounts' commands (empty until the list has loaded).
fn connection_entries(&self) -> Vec<CommandEntry> {
match self.api_results.get("us:connections") {
Some(Ok(list)) => connection_commands(list, self.api_results.get("spotify:playlists")),
_ => Vec::new(),
}
}
/// Whether the command list is up for this draft: "/word" as on Discord,
/// and also "/word more words" while that's still on its way to one of
/// your account commands ("/fortnite username", "/spotify playlist …").
pub(super) fn slash_listing(&self, draft: &str) -> bool {
if !draft.starts_with('/') || draft.contains('\n') {
return false;
}
if !draft.contains(char::is_whitespace) {
return true;
}
let d = draft.to_lowercase();
self.connection_entries().iter().any(|e| e.label().to_lowercase().starts_with(&d))
}
pub(super) fn app_launcher_ui(&mut self, ctx: &egui::Context) {
let Some((ch, composer)) = self.compose.composer_rect else { return };
if Some(ch) != self.current_channel || self.compose.command.is_some() {
return;
}
let draft = self.drafts.get(&ch).cloned().unwrap_or_default();
if draft.starts_with('/') {
// Your linked accounts, and (once "/spotify" is being typed) the
// playlists on your Spotify profile.
self.api_get_once("us:connections", "/users/@me/connections");
let d = draft.to_lowercase();
let spotify = d.starts_with("/spotify") || (d.len() >= 3 && "/spotify".starts_with(&d));
let linked = matches!(self.api_results.get("us:connections"), Some(Ok(Value::Array(a))) if a.iter().any(|c| c["type"] == "spotify"));
if spotify && linked && !self.api_results.contains_key("spotify:playlists") && self.api_pending.insert("spotify:playlists".into()) {
self.backend.send(crate::backend::Command::SpotifyPlaylists);
}
}
let open = self.slash_listing(&draft);
if !open || self.compose.apps_dismissed.as_ref().is_some_and(|(c, d)| *c == ch && *d == draft) {
self.compose.apps_nav = 0;
self.compose.apps_pick = false;
return;
}
let t = self.theme.clone();
let guild = self.store.channels.get(&ch).and_then(|c| c.guild_id);
let tags: Vec<(String, String)> = match guild {
Some(g) => vec![(format!("apps:g:{g}"), format!("/guilds/{g}/application-command-index"))],
None => vec![(format!("apps:c:{ch}"), format!("/channels/{ch}/application-command-index"))],
}
.into_iter()
.chain(std::iter::once(("apps:me".to_string(), "/users/@me/application-command-index".to_string())))
.collect();
for (tag, path) in &tags {
self.api_get_once(tag, path.clone());
}
let mut entries: Vec<CommandEntry> = self.connection_entries();
let mut loading = false;
let mut error = None;
for (tag, _) in &tags {
match self.api_result(tag) {
Some(Ok(v)) => {
for e in command_entries(v) {
if !entries.iter().any(|o| o.cmd["id"] == e.cmd["id"] && o.path == e.path) {
entries.push(e);
}
}
}
Some(Err(e)) => error = Some(e.clone()),
None => loading = true,
}
}
entries.extend(builtin_commands());
let q = draft.trim_start_matches('/').to_lowercase();
let filter_id = egui::Id::new("apps_filter");
let mut app_filter: Option<String> = ctx.data(|d| d.get_temp(filter_id)).flatten();
let shown: Vec<&CommandEntry> = entries
.iter()
.filter(|e| entry_matches(e, &q))
.filter(|e| app_filter.as_ref().map_or(true, |a| *a == e.app))
.collect();
// Keyboard: arrows move the highlight, Enter/Tab picks it.
let n = shown.len().max(1);
let sel = (self.compose.apps_sel as i64 + self.compose.apps_nav as i64).rem_euclid(n as i64) as usize;
self.compose.apps_sel = sel;
self.compose.apps_nav = 0;
let mut chosen = if std::mem::take(&mut self.compose.apps_pick) { shown.get(sel).map(|e| (e.cmd.clone(), e.app.clone(), e.path.clone())) } else { None };
let mut rail: Vec<(String, Option<String>)> = Vec::new();
for e in &entries {
if !rail.iter().any(|(a, _)| *a == e.app) {
rail.push((e.app.clone(), e.app_icon.clone()));
}
}
let height = (shown.len() as f32 * 50.0 + 40.0 * 3.0).clamp(140.0, 420.0);
let rect = Rect::from_min_max(pos2(composer.left(), composer.top() - 8.0 - height), pos2(composer.right(), composer.top() - 8.0));
let area = egui::Area::new(egui::Id::new("app_launcher")).order(Order::Foreground).fixed_pos(rect.min).show(ctx, |ui| {
ui.expand_to_include_rect(rect);
ui.painter().add(egui::Shape::rect_filled(rect, 8.0, t.bg_secondary));
ui.painter().rect_stroke(rect, 8.0, Stroke::new(1.0_f32, t.border_subtle));
// App rail.
let rail_rect = Rect::from_min_size(rect.min, vec2(52.0, rect.height()));
ui.painter().rect_filled(rail_rect, egui::Rounding { nw: 8.0, sw: 8.0, ne: 0.0, se: 0.0 }, t.bg_tertiary);
let mut y = rail_rect.top() + 12.0;
for (app, icon_url) in &rail {
let r = Rect::from_center_size(pos2(rail_rect.center().x, y + 16.0), vec2(32.0, 32.0));
if r.bottom() > rail_rect.bottom() - 4.0 {
break;
}
let resp = ui.interact(r, egui::Id::new(("apps_rail", app.as_str())), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
let active = app_filter.as_deref() == Some(app.as_str());
if active || resp.hovered() {
ui.painter().rect_filled(r.expand(3.0), 8.0, overlay(if active { 0.16 } else { 0.08 }));
}
// A linked account's section: the platform's own logo.
let brand = entries.iter().find(|e| e.app == *app).and_then(|e| e.cmd["connection"].as_str()).and_then(super::brand_icons::connection);
match icon_url {
_ if brand.is_some() => {
if let Some(src) = brand {
egui::Image::new(src).paint_at(ui, r.shrink(6.0));
}
}
Some(u) => egui::Image::new(u.as_str()).rounding(16.0).paint_at(ui, r.shrink(4.0)),
None if app == "Built-in" => {
ui.painter().rect_filled(r.shrink(5.0), 5.0, t.interactive_normal);
ui.painter().text(r.center(), Align2::CENTER_CENTER, "/", strong(14.0), t.bg_tertiary);
}
None => {
ui.painter().circle_filled(r.center(), 12.0, BRAND);
}
}
if resp.on_hover_text(app).clicked() {
app_filter = if active { None } else { Some(app.clone()) };
}
y += 40.0;
}
// Commands.
let list = Rect::from_min_max(pos2(rail_rect.right() + 8.0, rect.top() + 8.0), pos2(rect.right() - 8.0, rect.bottom() - 8.0));
let mut lui = ui.new_child(egui::UiBuilder::new().max_rect(list).layout(egui::Layout::top_down(egui::Align::Min)));
ScrollArea::vertical().auto_shrink([false, false]).show(&mut lui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
if shown.is_empty() {
ui.add_space(20.0);
let msg = if loading {
"Loading commands…".to_string()
} else if let Some(e) = &error {
format!("Couldn't load commands: {e}")
} else {
"No commands match that".to_string()
};
ui.label(RichText::new(msg).size(14.0).color(t.text_muted));
}
let mut last_app = String::new();
for (i, e) in shown.iter().enumerate() {
if e.app != last_app {
last_app = e.app.clone();
ui.add_space(6.0);
ui.label(RichText::new(&e.app).font(strong(12.0)).color(t.header_secondary));
ui.add_space(4.0);
}
let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 50.0), Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
if resp.hovered() && ui.input(|inp| inp.pointer.delta() != egui::Vec2::ZERO) {
self.compose.apps_sel = i;
}
if i == self.compose.apps_sel {
ui.painter().rect_filled(row, 6.0, t.bg_hover);
if self.compose.apps_scroll {
ui.scroll_to_rect(row, None);
}
}
let ic = Rect::from_center_size(pos2(row.left() + 20.0, row.center().y), vec2(24.0, 24.0));
let brand = e.cmd["connection"].as_str().and_then(super::brand_icons::connection);
match &e.app_icon {
_ if brand.is_some() => {
if let Some(src) = brand {
egui::Image::new(src).paint_at(ui, ic.shrink(2.0));
}
}
Some(u) => egui::Image::new(u.as_str()).rounding(12.0).paint_at(ui, ic),
None if e.app == "Built-in" => {
ui.painter().rect_filled(ic.shrink(1.0), 5.0, t.interactive_normal);
ui.painter().text(ic.center(), Align2::CENTER_CENTER, "/", strong(13.0), t.bg_secondary);
}
None => {
ui.painter().circle_filled(ic.center(), 12.0, BRAND);
}
}
let p = ui.painter_at(row);
let name_r = p.text(pos2(ic.right() + 12.0, row.top() + 16.0), Align2::LEFT_CENTER, e.label(), strong(14.0), t.header_primary);
let mut x = name_r.right() + 8.0;
for opt in option_defs(&e.cmd, &e.path).iter().filter(|o| o["required"].as_bool().unwrap_or(false)) {
let g = p.layout_no_wrap(opt["name"].as_str().unwrap_or("").to_string(), FontId::proportional(12.0), t.text_normal);
let chip = Rect::from_min_size(pos2(x, row.top() + 7.0), vec2(g.size().x + 10.0, 18.0));
p.rect_filled(chip, 4.0, overlay(0.12));
p.galley(pos2(chip.left() + 5.0, chip.center().y - g.size().y / 2.0), g, t.text_normal);
x = chip.right() + 4.0;
}
p.text(pos2(ic.right() + 12.0, row.top() + 35.0), Align2::LEFT_CENTER, &e.description, FontId::proportional(12.5), t.text_muted);
p.text(pos2(row.right() - 10.0, row.center().y), Align2::RIGHT_CENTER, &e.app, FontId::proportional(12.0), t.text_muted);
if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
chosen = Some((e.cmd.clone(), e.app.clone(), e.path.clone()));
}
}
});
});
self.compose.apps_scroll = false;
let _ = area;
ctx.data_mut(|d| d.insert_temp(filter_id, app_filter));
if let Some((cmd, _, _)) = chosen.as_ref().filter(|(cmd, _, _)| cmd["connection"].is_string()) {
// An account command: its text goes into the message box, caret
// after it, for you to send or keep writing. (A row with nothing
// to insert, such as "Loading your playlists…", does nothing.)
if let Some(text) = cmd["insert"].as_str() {
let id = egui::Id::new(("composer", ch.0));
let mut st = egui::TextEdit::load_state(ctx, id).unwrap_or_default();
st.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(text.chars().count()))));
st.store(ctx, id);
self.drafts.insert(ch, text.to_string());
self.compose.apps_sel = 0;
self.compose.focus_composer = true;
}
} else if let Some((cmd, app_name, path)) = chosen {
self.drafts.insert(ch, String::new());
self.compose.apps_sel = 0;
self.compose.command = Some(CommandDraft { channel: ch, cmd, app_name, path, values: Vec::new() });
} else if ctx.input(|i| i.key_pressed(Key::Escape)) {
self.compose.apps_dismissed = Some((ch, draft));
}
}
/// Enter in the composer while a command is filled in.
pub(super) fn submit_command(&mut self, ch: Id) {
let Some(d) = self.compose.command.take().filter(|d| d.channel == ch) else { return };
match self.run_command(&d) {
Ok(()) => {}
Err(e) => {
self.toast(e, true);
self.compose.command = Some(d);
}
}
}
/// The chosen command, filled in above the composer: one field per
/// option, then Send (or Enter).
pub(super) fn command_bar(&mut self, ui: &mut Ui, ch: Id) {
let Some(mut d) = self.compose.command.take().filter(|d| d.channel == ch) else { return };
let t = self.theme.clone();
let guild = self.store.channels.get(&ch).and_then(|c| c.guild_id);
let defs = option_defs(&d.cmd, &d.path);
let mut run = false;
let mut cancel = false;
let channels: Vec<(String, String)> = guild
.map(|g| {
let mut v: Vec<(String, String)> = self
.store
.channels
.values()
.filter(|c| c.guild_id == Some(g) && !discord::model::channel_kind::is_thread(c.kind) && c.kind != 4)
.map(|c| (c.id.to_string(), c.name.clone().unwrap_or_default()))
.collect();
v.sort_by(|a, b| a.1.cmp(&b.1));
v
})
.unwrap_or_default();
let roles: Vec<(String, String)> = guild
.and_then(|g| self.store.guilds.get(&g))
.map(|g| g.guild.roles.iter().map(|r| (r.id.to_string(), r.name.clone())).collect())
.unwrap_or_default();
let label = {
let mut s = format!("/{}", d.cmd["name"].as_str().unwrap_or(""));
for p in &d.path {
s.push(' ');
s.push_str(p);
}
s
};
Frame::none()
.fill(t.bg_secondary)
.rounding(egui::Rounding { nw: 8.0, ne: 8.0, sw: 0.0, se: 0.0 })
.inner_margin(Margin::symmetric(14.0, 10.0))
.show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 6.0;
ui.horizontal(|ui| {
ui.label(RichText::new(&label).font(strong(15.0)).color(t.header_primary));
ui.label(RichText::new(format!("— {}", d.app_name)).size(13.0).color(t.text_muted));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
run = button(ui, "Send", BRAND, Color32::WHITE, vec2(64.0, 30.0), true).clicked();
let x = ui.add(egui::Label::new(RichText::new(icon::CLOSE).font(icon_font(12.0)).color(t.interactive_normal)).selectable(false).sense(Sense::click()));
cancel = x.on_hover_text("Cancel").clicked();
});
});
for def in &defs {
let name = def["name"].as_str().unwrap_or("").to_string();
let kind = def["type"].as_u64().unwrap_or(3);
let required = def["required"].as_bool().unwrap_or(false);
let idx = match d.values.iter().position(|(n, _)| *n == name) {
Some(i) => i,
None => {
d.values.push((name.clone(), String::new()));
d.values.len() - 1
}
};
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
let (lr, _) = ui.allocate_exact_size(vec2(130.0, 26.0), Sense::hover());
let text = if required { format!("{name}*") } else { name.clone() };
ui.painter().text(lr.left_center(), Align2::LEFT_CENTER, text, strong(13.0), t.header_primary);
let value = &mut d.values[idx].1;
let hint = def["description"].as_str().unwrap_or("").to_string();
let choices: Vec<(String, String)> = def["choices"]
.as_array()
.map(|a| a.iter().map(|c| (c["value"].to_string().trim_matches('"').to_string(), c["name"].as_str().unwrap_or("").to_string())).collect())
.unwrap_or_default();
let combo = |ui: &mut Ui, list: &[(String, String)], value: &mut String, salt: &str| {
let shown = list.iter().find(|(v, _)| v == value).map(|(_, n)| n.clone()).unwrap_or_else(|| hint.clone());
ComboBox::from_id_salt((salt, name.as_str())).width(ui.available_width() - 8.0).selected_text(shown).height(240.0).show_ui(ui, |ui| {
for (v, n) in list {
ui.selectable_value(value, v.clone(), n.as_str());
}
});
};
if !choices.is_empty() {
combo(ui, &choices, value, "cmd_choice");
} else if kind == 5 {
let mut on = value == "true";
checkbox(ui, &t, &mut on, "");
*value = if on { "true".into() } else if value.is_empty() { String::new() } else { "false".into() };
} else if kind == 7 {
let list: Vec<(String, String)> = channels.iter().map(|(i, n)| (i.clone(), format!("#{n}"))).collect();
combo(ui, &list, value, "cmd_channel");
} else if kind == 8 {
combo(ui, &roles, value, "cmd_role");
} else if kind == 11 {
ui.label(RichText::new("File options aren't supported yet").size(13.0).color(t.text_muted));
} else {
let hint = if matches!(kind, 6 | 9) { format!("{hint} (user ID or username)") } else { hint.clone() };
let r = ui.add(
TextEdit::singleline(value)
.desired_width(ui.available_width())
.hint_text(RichText::new(hint).color(t.text_muted))
.font(FontId::proportional(14.0)),
);
if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) {
run = true;
}
}
});
}
});
if run {
match self.run_command(&d) {
Ok(()) => return,
Err(e) => self.toast(e, true),
}
}
if !cancel {
self.compose.command = Some(d);
}
}
fn run_command(&mut self, d: &CommandDraft) -> Result<(), String> {
if d.cmd["builtin"].as_bool() == Some(true) {
let msg = d.values.iter().find(|(n, _)| n == "message").map(|(_, v)| v.trim().to_string()).unwrap_or_default();
let join = |tail: &str| if msg.is_empty() { tail.to_string() } else { format!("{msg} {tail}") };
let text = match d.cmd["name"].as_str().unwrap_or("") {
"shrug" => join("¯\\_(ツ)_/¯"),
"tableflip" => join("(╯°□°)╯︵ ┻━┻"),
"unflip" => join("┬─┬ノ( º _ ºノ)"),
"me" if !msg.is_empty() => format!("_{msg}_"),
"spoiler" if !msg.is_empty() => format!("||{msg}||"),
_ => return Err("Fill in message first.".into()),
};
self.send_message(d.channel, text);
return Ok(());
}
let guild = self.store.channels.get(&d.channel).and_then(|c| c.guild_id);
let session_id = self.store.session_id.clone().ok_or("Not connected yet, try again in a moment.")?;
let mut opts = Vec::new();
for def in option_defs(&d.cmd, &d.path) {
let name = def["name"].as_str().unwrap_or("");
let kind = def["type"].as_u64().unwrap_or(3);
let raw = d.values.iter().find(|(n, _)| n == name).map(|(_, v)| v.trim()).filter(|v| !v.is_empty());
let Some(v) = raw else {
if def["required"].as_bool().unwrap_or(false) {
return Err(format!("Fill in {name} first."));
}
continue;
};
let value = match kind {
4 => json!(v.parse::<i64>().map_err(|_| format!("{name} needs a whole number."))?),
10 => json!(v.parse::<f64>().map_err(|_| format!("{name} needs a number."))?),
5 => json!(v == "true"),
6 | 9 => {
let id = v.trim_start_matches("<@").trim_start_matches('!').trim_end_matches('>').trim_start_matches('@');
if id.chars().all(|c| c.is_ascii_digit()) {
json!(id)
} else {
let lower = id.to_lowercase();
let found = self.store.users.values().find(|u| u.username.to_lowercase() == lower || u.display_name().to_lowercase() == lower);
json!(found.map(|u| u.id.to_string()).ok_or(format!("Couldn't find a user called {id}."))?)
}
}
_ if !def["choices"].is_null() => def["choices"]
.as_array()
.and_then(|a| a.iter().find(|c| c["value"].to_string().trim_matches('"') == v))
.map(|c| c["value"].clone())
.unwrap_or(json!(v)),
_ => json!(v),
};
opts.push(json!({ "type": kind, "name": name, "value": value }));
}
let mut options = Value::Array(opts);
for (i, seg) in d.path.iter().enumerate().rev() {
let kind = if i + 1 == d.path.len() { 1 } else { 2 };
options = json!([{ "type": kind, "name": seg, "options": options }]);
}
let body = json!({
"type": 2,
"application_id": d.cmd["application_id"],
"guild_id": guild.map(|g| g.to_string()),
"channel_id": d.channel.to_string(),
"session_id": session_id,
"nonce": Id::from_timestamp_ms(crate::app::now_ms()).0.to_string(),
"analytics_location": "slash_ui",
"data": {
"version": d.cmd["version"],
"id": d.cmd["id"],
"name": d.cmd["name"],
"type": d.cmd["type"].as_u64().unwrap_or(1),
"options": options,
"application_command": d.cmd,
"attachments": [],
},
});
let mut body = body;
// Server commands name their server, as Discord's client sends them.
if let Some(g) = d.cmd["guild_id"].as_str() {
body["data"]["guild_id"] = json!(g);
}
self.api("cmd:run", Method::POST, "/interactions", Some(body));
Ok(())
}
// ---- results ------------------------------------------------------------
/// Finish what the tools started once Discord answers.
pub(super) fn compose_tick(&mut self) {
if let Some(r) = self.api_take("poll:create") {
match r {
Ok(_) => self.compose.poll = None,
Err(e) => self.toast(format!("Couldn't post the poll: {e}"), true),
}
}
if let Some(Err(e)) = self.api_take("poll:vote") {
self.toast(format!("Couldn't vote: {e}"), true);
}
if let Some(Err(e)) = self.api_take("sticker:send") {
self.toast(format!("Couldn't send the sticker: {e}"), true);
}
if let Some(Err(e)) = self.api_take("cmd:run") {
self.toast(format!("Couldn't run the command: {e}"), true);
}
if let Some(r) = self.api_take("sched:create") {
match r {
Ok(_) => {
let when: String = self.ctx.data(|d| d.get_temp(egui::Id::new("sched_label")).unwrap_or_default());
self.toast(format!("Message scheduled for {when}."), false);
}
Err(e) => self.toast(format!("Couldn't schedule the message: {e}"), true),
}
}
if let Some(r) = self.api_take("thread:create") {
match r {
Ok(v) => {
self.store.upsert_channel(&v);
if let (Some(id), Some(d)) = (Id::from_value(&v["id"]), self.compose.new_thread.take()) {
let text = d.message.trim().to_string();
self.select_channel(Some(id));
self.send_message(id, text);
}
}
Err(e) => self.toast(format!("Couldn't create the thread: {e}"), true),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn labels(list: &[CommandEntry], q: &str) -> Vec<String> {
list.iter().filter(|e| entry_matches(e, q)).map(|e| e.label()).collect()
}
#[test]
fn linked_accounts_become_commands() {
let conns = json!([
{ "type": "epicgames", "id": "e1", "name": "CrabbyBuilder" },
{ "type": "roblox", "id": "156", "name": "builderman" },
{ "type": "spotify", "id": "abc", "name": "You" },
{ "type": "steam", "id": "1", "name": "" },
]);
let playlists = Ok(json!([["Crab Rave", "https://open.spotify.com/playlist/p1"]]));
let list = connection_commands(&conns, Some(&playlists));
// Everything, by the platforms' own names (no nicknames, no nameless account).
assert_eq!(
labels(&list, ""),
["/epicgames username", "/roblox username", "/roblox profile", "/spotify username", "/spotify profile", "/spotify playlist Crab Rave"]
);
// "/fortnite" is Epic Games; Epic has no profile pages to link.
assert_eq!(labels(&list, "fort"), ["/fortnite username"]);
assert_eq!(labels(&list, "fortnite user"), ["/fortnite username"]);
let insert = |label: &str| list.iter().find(|e| e.label() == label).and_then(|e| e.cmd["insert"].as_str().map(String::from));
assert_eq!(insert("/fortnite username").as_deref(), Some("CrabbyBuilder"));
// (Discord's own link for Roblox has no "www.".)
assert_eq!(insert("/roblox profile").as_deref(), Some("https://roblox.com/users/156/profile"));
assert_eq!(insert("/spotify profile").as_deref(), Some("https://open.spotify.com/user/abc"));
assert_eq!(insert("/spotify playlist Crab Rave").as_deref(), Some("https://open.spotify.com/playlist/p1"));
}
#[test]
fn playlists_say_when_they_are_not_there_yet() {
let conns = json!([{ "type": "spotify", "id": "abc", "name": "You" }]);
let row = |p: Option<&Result<Value, String>>| {
let list = connection_commands(&conns, p);
let e = list.iter().find(|e| e.path.first().map(String::as_str) == Some("playlist")).unwrap();
(e.description.clone(), e.cmd["insert"].is_null())
};
assert_eq!(row(None), ("Loading your playlists…".to_string(), true));
assert_eq!(row(Some(&Ok(json!([])))), ("No public playlists on your Spotify profile".to_string(), true));
assert_eq!(row(Some(&Err("Spotify returned 500".into()))), ("Couldn't load your playlists: Spotify returned 500".to_string(), true));
}
}