Skip to main content

djs_builders/component/
button.rs

1//! [`ButtonBuilder`] and [`PremiumButtonBuilder`].
2
3use compact_str::CompactString;
4use djs_model::{
5    component::{Button, ButtonStyle, Component, InteractiveButton, LinkButton, PremiumButton},
6    emoji::PartialEmoji,
7    id::SkuId,
8};
9
10use super::validate;
11use crate::{ValidationError, check::Path};
12
13/// Builds a [button](https://docs.discord.com/developers/components/reference#button) for an
14/// [action row](crate::ActionRowBuilder) or a section accessory.
15///
16/// Each style has its own constructor (D-197): [`primary`](Self::primary),
17/// [`secondary`](Self::secondary), [`success`](Self::success) and [`danger`](Self::danger)
18/// take the `custom_id` your app receives when the button is clicked; [`link`](Self::link)
19/// takes a URL and sends no interaction. Premium buttons have their own builder,
20/// [`PremiumButtonBuilder`] (D-202).
21///
22/// [`build`](Self::build) checks what Discord checks (D-200): a `custom_id` of 1-100
23/// characters (counted as given, not trimmed), a label of at most 80 characters that is not
24/// blank — or an emoji instead —, and for links a URL of at most 512 characters starting with
25/// `http://`, `https://` or `discord://`.
26///
27/// discord.js counterpart: `ButtonBuilder`.
28///
29/// # Examples
30///
31/// ```
32/// use djs_builders::{ActionRowBuilder, ButtonBuilder};
33/// use djs_model::emoji::PartialEmoji;
34///
35/// # fn main() -> Result<(), djs_builders::ValidationError> {
36/// let row = ActionRowBuilder::new()
37///     .component(ButtonBuilder::success("confirm").label("Confirm"))
38///     .component(ButtonBuilder::danger("cancel").label("Cancel"))
39///     .component(ButtonBuilder::secondary("like").emoji(PartialEmoji::Unicode { name: "👍".into() }))
40///     .component(ButtonBuilder::link("https://example.com/help").label("Help"))
41///     .build()?;
42/// assert_eq!(row.children().len(), 4);
43/// # Ok(())
44/// # }
45/// ```
46#[derive(Clone, Debug, PartialEq, Eq)]
47#[must_use = "a builder does nothing until it is added to a row or built"]
48pub struct ButtonBuilder {
49    button: Button,
50}
51
52impl ButtonBuilder {
53    fn interactive(style: ButtonStyle, custom_id: impl Into<CompactString>) -> Self {
54        Self {
55            button: InteractiveButton::new(style, custom_id).into(),
56        }
57    }
58
59    /// Creates a button in the most prominent style (blurple), sending `custom_id`
60    /// (1-100 characters) to your app when clicked.
61    ///
62    /// discord.js counterpart: `setStyle(ButtonStyle.Primary).setCustomId(…)`.
63    pub fn primary(custom_id: impl Into<CompactString>) -> Self {
64        Self::interactive(ButtonStyle::Primary, custom_id)
65    }
66
67    /// Creates a button in the neutral style (grey).
68    ///
69    /// discord.js counterpart: `setStyle(ButtonStyle.Secondary).setCustomId(…)`.
70    pub fn secondary(custom_id: impl Into<CompactString>) -> Self {
71        Self::interactive(ButtonStyle::Secondary, custom_id)
72    }
73
74    /// Creates a button in the confirming style (green).
75    ///
76    /// discord.js counterpart: `setStyle(ButtonStyle.Success).setCustomId(…)`.
77    pub fn success(custom_id: impl Into<CompactString>) -> Self {
78        Self::interactive(ButtonStyle::Success, custom_id)
79    }
80
81    /// Creates a button in the destructive style (red).
82    ///
83    /// discord.js counterpart: `setStyle(ButtonStyle.Danger).setCustomId(…)`.
84    pub fn danger(custom_id: impl Into<CompactString>) -> Self {
85        Self::interactive(ButtonStyle::Danger, custom_id)
86    }
87
88    /// Creates a button that opens `url` (`http://`, `https://` or `discord://`, at most 512
89    /// characters). It sends no interaction to your app.
90    ///
91    /// discord.js counterpart: `setStyle(ButtonStyle.Link).setURL(…)`.
92    pub fn link(url: impl Into<CompactString>) -> Self {
93        Self {
94            button: LinkButton::new(url).into(),
95        }
96    }
97
98    /// Creates a button to buy the SKU `sku_id`, which shows the SKU's name and price and
99    /// cannot have a label or emoji (D-202).
100    ///
101    /// discord.js counterpart: `setStyle(ButtonStyle.Premium).setSKUId(…)`.
102    pub fn premium(sku_id: SkuId) -> PremiumButtonBuilder {
103        PremiumButtonBuilder {
104            button: PremiumButton::new(sku_id),
105        }
106    }
107
108    /// Sets the text on the button (at most 80 characters, not blank). A button needs a label
109    /// or an [emoji](Self::emoji).
110    ///
111    /// discord.js counterpart: `setLabel`.
112    pub fn label(mut self, label: impl Into<CompactString>) -> Self {
113        let label = Some(label.into());
114        match &mut self.button {
115            Button::Interactive(button) => button.label = label,
116            Button::Link(button) => button.label = label,
117            _ => {}
118        }
119        self
120    }
121
122    /// Sets the emoji shown before the label (or alone).
123    ///
124    /// discord.js counterpart: `setEmoji`.
125    pub fn emoji(mut self, emoji: impl Into<PartialEmoji>) -> Self {
126        let emoji = Some(emoji.into());
127        match &mut self.button {
128            Button::Interactive(button) => button.emoji = emoji,
129            Button::Link(button) => button.emoji = emoji,
130            _ => {}
131        }
132        self
133    }
134
135    /// Sets whether the button is greyed out and cannot be clicked.
136    ///
137    /// discord.js counterpart: `setDisabled`.
138    pub fn disabled(mut self, disabled: bool) -> Self {
139        match &mut self.button {
140            Button::Interactive(button) => button.disabled = disabled,
141            Button::Link(button) => button.disabled = disabled,
142            _ => {}
143        }
144        self
145    }
146
147    /// Sets the component's numeric identifier (Discord generates one otherwise); it must be
148    /// unique in the message.
149    ///
150    /// discord.js counterpart: `setId`.
151    pub fn id(mut self, id: i32) -> Self {
152        match &mut self.button {
153            Button::Interactive(button) => button.id = Some(id),
154            Button::Link(button) => button.id = Some(id),
155            _ => {}
156        }
157        self
158    }
159
160    /// Checks the button and returns it as a [`Component`].
161    ///
162    /// discord.js counterpart: `ButtonBuilder#toJSON`.
163    ///
164    /// # Errors
165    ///
166    /// [`ValidationError::Missing`] for an empty `custom_id` or a button with neither a label
167    /// nor an emoji, [`ValidationError::TooLong`] for a `custom_id`, label or URL above its
168    /// limit, [`ValidationError::InvalidUrl`] for a link with another scheme.
169    pub fn build(self) -> Result<Component, ValidationError> {
170        validate::button(&Path::Root, &self.button)?;
171        Ok(self.into())
172    }
173
174    /// Returns the button without any check (D-180).
175    ///
176    /// discord.js counterpart: `ButtonBuilder#toJSON` with validation off (`disableValidators`).
177    #[must_use]
178    pub fn build_unchecked(self) -> Component {
179        self.into()
180    }
181}
182
183impl From<ButtonBuilder> for Component {
184    fn from(button: ButtonBuilder) -> Self {
185        Self::Button(button.button)
186    }
187}
188
189/// Builds a [premium button](https://docs.discord.com/developers/components/reference#button-button-styles),
190/// which lets users buy one of your app's SKUs; created by [`ButtonBuilder::premium`].
191///
192/// Discord shows the SKU's name, icon and price on it, so it has no label, emoji or
193/// `custom_id`, and clicking it sends no interaction. Its own type (D-202) makes adding a
194/// label a compile-time error.
195///
196/// discord.js counterpart: `ButtonBuilder` with `ButtonStyle.Premium`.
197///
198/// # Examples
199///
200/// ```
201/// use djs_builders::{ActionRowBuilder, ButtonBuilder};
202/// use djs_model::id::SkuId;
203///
204/// let row = ActionRowBuilder::new()
205///     .component(ButtonBuilder::premium(SkuId::new(1_088_510_058_284_990_888)))
206///     .build()
207///     .unwrap();
208/// assert_eq!(row.children().len(), 1);
209/// ```
210#[derive(Clone, Debug, PartialEq, Eq)]
211#[must_use = "a builder does nothing until it is added to a row or built"]
212pub struct PremiumButtonBuilder {
213    button: PremiumButton,
214}
215
216impl PremiumButtonBuilder {
217    /// Sets whether the button is greyed out and cannot be clicked.
218    ///
219    /// discord.js counterpart: `setDisabled`.
220    pub fn disabled(mut self, disabled: bool) -> Self {
221        self.button.disabled = disabled;
222        self
223    }
224
225    /// Sets the component's numeric identifier (Discord generates one otherwise); it must be
226    /// unique in the message.
227    ///
228    /// discord.js counterpart: `setId`.
229    pub fn id(mut self, id: i32) -> Self {
230        self.button.id = Some(id);
231        self
232    }
233
234    /// Returns the button as a [`Component`]. It returns a `Result` like every other builder
235    /// (D-179), so code can treat all buttons alike.
236    ///
237    /// discord.js counterpart: `ButtonBuilder#toJSON` with `setSKUId`.
238    ///
239    /// # Errors
240    ///
241    /// None: a premium button has nothing that can break a rule.
242    pub fn build(self) -> Result<Component, ValidationError> {
243        Ok(self.into())
244    }
245
246    /// Returns the button as a [`Component`] (D-180; the same as [`build`](Self::build)).
247    ///
248    /// discord.js counterpart: `ButtonBuilder#toJSON` with `setSKUId`.
249    #[must_use]
250    pub fn build_unchecked(self) -> Component {
251        self.into()
252    }
253}
254
255impl From<PremiumButtonBuilder> for Component {
256    fn from(button: PremiumButtonBuilder) -> Self {
257        button.button.into()
258    }
259}