Dezio/src/ui.rs
2026-11-06 21:39:45 -06:00

321 lines
11 KiB
Rust

//! Components V2 "cards" (the Rust twin of core/ui.py's `Card`).
//!
//! A V2 message has no content/embeds, only components. Mentions inside a text block DO ping, so
//! cards are always sent with no allowed mentions. A message holds at most 40 components and 4000
//! characters of text in total.
use twilight_model::channel::message::component::{
ActionRow, Button, ButtonStyle, SelectMenu, SelectMenuOption, SelectMenuType, Component, Container, MediaGallery, MediaGalleryItem, Section,
Separator, SeparatorSpacingSize, TextDisplay, Thumbnail, UnfurledMediaItem,
};
pub const GREEN: u32 = 0x1DB954;
pub const RED: u32 = 0xED4245;
pub const BLURPLE: u32 = 0x5865F2;
pub const GOLD: u32 = 0xF1C40F;
pub const GREY: u32 = 0x4F545C;
pub const TEXT_LIMIT: usize = 4000;
/// Trim `text` to `limit` characters, marking the cut with an ellipsis.
pub fn truncate(text: &str, limit: usize) -> String {
if text.chars().count() <= limit {
return text.to_string();
}
let cut: String = text.chars().take(limit.saturating_sub(1)).collect();
format!("{}…", cut.trim_end())
}
/// Escape markdown so user-provided names render literally. Only characters that really are markdown get a
/// backslash: Discord shows the backslash itself in front of anything else (`Go Away \(Official\)`).
pub fn escape(text: &str) -> String {
let masked_link = text.contains("](");
let mut out = String::with_capacity(text.len());
let mut line_start = true;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
let special = match c {
'\\' | '*' | '_' | '`' | '~' | '|' => true,
'>' | '#' | '-' => line_start && chars.peek().is_none_or(|n| n.is_whitespace() || (c == '#' && *n == '#') || (c == '>' && *n == '>')),
'[' | ']' => masked_link,
_ => false,
};
if special {
out.push('\\');
}
out.push(c);
line_start = c == '\n';
}
out
}
/// A file name Discord's upload checks accept: letters, digits, `.`, `-` and `_` only (twilight refuses the
/// whole request for anything else, e.g. a space in `Artist - Title.opus`).
pub fn file_name(name: &str) -> String {
let (stem, ext) = match name.rsplit_once('.') {
Some((s, e)) if !s.is_empty() && e.len() <= 8 => (s, Some(e)),
_ => (name, None),
};
let clean = |t: &str| -> String { t.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect() };
let mut stem = clean(stem);
stem = stem.trim_matches('_').chars().take(80).collect();
if stem.is_empty() {
stem = "file".into();
}
match ext.map(clean).filter(|e| !e.is_empty()) {
Some(e) => format!("{stem}.{e}"),
None => stem,
}
}
fn text_display(content: impl Into<String>) -> Component {
Component::TextDisplay(TextDisplay { id: None, content: content.into() })
}
fn media(url: &str) -> UnfurledMediaItem {
UnfurledMediaItem { url: url.to_string(), proxy_url: None, height: None, width: None, content_type: None }
}
/// Fluent builder for a single container.
#[derive(Clone)]
pub struct Card {
accent: Option<u32>,
items: Vec<Component>,
}
impl Card {
pub fn new(accent: Option<u32>) -> Self {
Self { accent, items: Vec::new() }
}
/// Up to three text blocks, with an optional thumbnail on the right.
pub fn header(mut self, texts: &[&str], thumbnail: Option<&str>) -> Self {
let texts: Vec<&str> = texts.iter().copied().filter(|t| !t.is_empty()).take(3).collect();
if texts.is_empty() {
return self;
}
match thumbnail {
Some(url) => self.items.push(Component::Section(Section {
id: None,
components: texts.iter().map(|t| text_display(*t)).collect(),
accessory: Box::new(Component::Thumbnail(Thumbnail {
id: None,
media: media(url),
description: None,
spoiler: None,
})),
})),
None => self.items.extend(texts.iter().map(|t| text_display(*t))),
}
self
}
pub fn text(mut self, content: &str) -> Self {
if !content.is_empty() {
self.items.push(text_display(truncate(content, TEXT_LIMIT)));
}
self
}
pub fn footer(mut self, content: &str) -> Self {
if !content.is_empty() {
self.items.push(text_display(format!("-# {content}")));
}
self
}
pub fn separator(mut self, visible: bool, large: bool) -> Self {
self.items.push(Component::Separator(Separator {
id: None,
divider: Some(visible),
spacing: Some(if large { SeparatorSpacingSize::Large } else { SeparatorSpacingSize::Small }),
}));
self
}
/// Images/videos by URL (a gallery holds at most 10 items).
pub fn gallery(mut self, urls: &[&str]) -> Self {
for chunk in urls.chunks(10) {
self.items.push(Component::MediaGallery(MediaGallery {
id: None,
items: chunk
.iter()
.map(|u| MediaGalleryItem { media: media(u), description: None, spoiler: None })
.collect(),
}));
}
self
}
pub fn row(mut self, buttons: Vec<Button>) -> Self {
if !buttons.is_empty() {
self.items.push(Component::ActionRow(ActionRow {
id: None,
components: buttons.into_iter().map(Component::Button).collect(),
}));
}
self
}
/// A row holding one select menu.
pub fn select(mut self, menu: SelectMenu) -> Self {
self.items.push(Component::ActionRow(ActionRow { id: None, components: vec![Component::SelectMenu(menu)] }));
self
}
pub fn build(self) -> Component {
Component::Container(Container {
id: None,
accent_color: Some(self.accent),
spoiler: None,
components: self.items,
})
}
}
/// A one-line card, handy for errors and confirmations.
pub fn notice(text: &str, accent: Option<u32>) -> Component {
Card::new(accent).text(text).build()
}
pub fn button(custom_id: &str, label: &str, style: ButtonStyle) -> Button {
Button {
id: None,
custom_id: Some(custom_id.to_string()),
disabled: false,
emoji: None,
label: Some(label.to_string()),
style,
url: None,
sku_id: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn file_names_pass_discords_check() {
assert_eq!(file_name("Artist - Title.opus"), "Artist_-_Title.opus");
assert_eq!(file_name("日本語.png"), "file.png");
assert_eq!(file_name("a b (1).mp4"), "a_b__1.mp4");
assert_eq!(file_name("noext"), "noext");
}
#[test]
fn escape_only_touches_real_markdown() {
assert_eq!(escape("Weezer - Go Away (Official Music Video)"), "Weezer - Go Away (Official Music Video)");
assert_eq!(escape("a_b *c* `d` ~e~ |f|"), "a\\_b \\*c\\* \\`d\\` \\~e\\~ \\|f\\|");
assert_eq!(escape("- item\n# head\n> quote"), "\\- item\n\\# head\n\\> quote");
assert_eq!(escape("[x](http://a)"), "\\[x\\](http://a)");
assert_eq!(escape("[tag] name"), "[tag] name");
}
#[test]
fn truncate_counts_chars() {
assert_eq!(truncate("héllo wörld", 20), "héllo wörld");
assert_eq!(truncate("abcdefghij", 5), "abcd…");
}
#[test]
fn card_json_shape() {
let c = Card::new(Some(GREEN)).header(&["### Hi", "body"], Some("https://x/y.png")).footer("small").build();
let v = serde_json::to_value(&c).unwrap();
assert_eq!(v["type"], 17);
assert_eq!(v["accent_color"], GREEN);
assert_eq!(v["components"][0]["type"], 9);
assert_eq!(v["components"][0]["accessory"]["type"], 11);
assert_eq!(v["components"][1]["content"], "-# small");
}
}
/// A user's avatar (their own, or the default one for their id).
pub fn avatar_url(id: twilight_model::id::Id<twilight_model::id::marker::UserMarker>, hash: Option<&twilight_model::util::ImageHash>) -> String {
match hash {
Some(h) => format!("https://cdn.discordapp.com/avatars/{id}/{h}.png?size=128"),
None => format!("https://cdn.discordapp.com/embed/avatars/{}.png", (id.get() >> 22) % 6),
}
}
/// `<t:unix:style>` — Discord shows it in each reader's own time zone.
pub fn timestamp(unix: i64, style: char) -> String {
format!("<t:{unix}:{style}>")
}
pub fn emoji_button(custom_id: &str, label: Option<&str>, emoji: &str, disabled: bool) -> Button {
Button {
id: None,
custom_id: Some(custom_id.to_string()),
disabled,
emoji: Some(crate::emojis::on_button(emoji)),
label: label.map(str::to_string),
style: ButtonStyle::Secondary,
url: None,
sku_id: None,
}
}
pub fn select_option(label: &str, value: &str, emoji: &str, description: &str, default: bool) -> SelectMenuOption {
SelectMenuOption {
default,
description: (!description.is_empty()).then(|| truncate(description, 100)),
emoji: Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: emoji.to_string() }),
label: truncate(label, 100),
value: value.to_string(),
}
}
pub fn select_menu(custom_id: &str, placeholder: &str, options: Vec<SelectMenuOption>) -> SelectMenu {
SelectMenu {
id: None,
channel_types: None,
custom_id: custom_id.to_string(),
default_values: None,
disabled: false,
kind: SelectMenuType::Text,
max_values: Some(1),
min_values: Some(1),
options: Some(options),
placeholder: Some(placeholder.to_string()),
required: None,
}
}
/// (component count, text length) of a built card — a message may hold 40 components and 4000 characters.
pub fn cost(card: &Component) -> (usize, usize) {
fn walk(v: &serde_json::Value, count: &mut usize, text: &mut usize) {
match v {
serde_json::Value::Object(o) => {
if o.contains_key("type") {
*count += 1;
}
if let Some(t) = o.get("content").and_then(|c| c.as_str()) {
*text += t.chars().count();
}
o.values().for_each(|x| walk(x, count, text));
}
serde_json::Value::Array(a) => a.iter().for_each(|x| walk(x, count, text)),
_ => {}
}
}
let (mut c, mut t) = (0, 0);
if let Ok(v) = serde_json::to_value(card) {
walk(&v, &mut c, &mut t);
}
(c, t)
}
pub fn file_display(attachment_name: &str) -> Component {
Component::File(twilight_model::channel::message::component::FileDisplay {
id: None,
file: media(&format!("attachment://{attachment_name}")),
spoiler: None,
})
}
impl Card {
pub fn push(mut self, c: Component) -> Self {
self.items.push(c);
self
}
}