djs_builders/component/select.rs
1//! The select menu builders: [`StringSelectMenuBuilder`] with
2//! [`StringSelectMenuOptionBuilder`], and the menus Discord fills itself (users, roles,
3//! mentionables, channels).
4
5use compact_str::CompactString;
6use djs_model::{
7 channel::ChannelType,
8 component::{
9 AutoPopulatedSelect, ChannelSelect, Component, SelectDefaultValue, SelectDefaultValueType,
10 SelectOption, StringSelect,
11 },
12 emoji::PartialEmoji,
13 id::{ChannelId, RoleId, UserId},
14};
15
16use super::validate;
17use crate::{ValidationError, check::Path};
18
19/// Implements the setters every select menu has on a builder whose model value is
20/// `self.select`, and `build` / `build_unchecked` / the conversion into [`Component`].
21macro_rules! select_menu {
22 ($builder:ident => $variant:ident) => {
23 impl $builder {
24 /// Sets the text shown while nothing is selected (at most 150 characters).
25 ///
26 /// discord.js counterpart: `setPlaceholder`.
27 pub fn placeholder(mut self, placeholder: impl Into<CompactString>) -> Self {
28 self.select.placeholder = Some(placeholder.into());
29 self
30 }
31
32 /// Sets how many items must be chosen at least (0-25; Discord's default: 1).
33 ///
34 /// discord.js counterpart: `setMinValues`.
35 pub fn min_values(mut self, min_values: u8) -> Self {
36 self.select.min_values = Some(min_values);
37 self
38 }
39
40 /// Sets how many items can be chosen at most (1-25, at least
41 /// [`min_values`](Self::min_values); Discord's default: 1).
42 ///
43 /// discord.js counterpart: `setMaxValues`.
44 pub fn max_values(mut self, max_values: u8) -> Self {
45 self.select.max_values = Some(max_values);
46 self
47 }
48
49 /// Sets whether the menu is greyed out (messages only; modals reject it).
50 ///
51 /// discord.js counterpart: `setDisabled`.
52 pub fn disabled(mut self, disabled: bool) -> Self {
53 self.select.disabled = disabled;
54 self
55 }
56
57 /// Sets whether an answer is required when the menu is in a modal (default: yes;
58 /// ignored in messages).
59 ///
60 /// discord.js counterpart: `setRequired`.
61 pub fn required(mut self, required: bool) -> Self {
62 self.select.required = required;
63 self
64 }
65
66 /// Sets the component's numeric identifier (Discord generates one otherwise); it
67 /// must be unique in the message or modal.
68 ///
69 /// discord.js counterpart: `setId`.
70 pub fn id(mut self, id: i32) -> Self {
71 self.select.id = Some(id);
72 self
73 }
74
75 /// Checks the menu and returns it as a [`Component`].
76 ///
77 /// discord.js counterpart: `toJSON` of the select menu builders.
78 ///
79 /// # Errors
80 ///
81 /// The first [`ValidationError`] found: the `custom_id` (1-100 characters), the
82 /// placeholder (at most 150), `min_values` (0-25) and `max_values` (1-25,
83 /// at least `min_values`), then what the menu offers (see the type docs).
84 pub fn build(self) -> Result<Component, ValidationError> {
85 let component = Component::from(self);
86 validate::component(&Path::Root, &component)?;
87 Ok(component)
88 }
89
90 /// Returns the menu without any check (D-180).
91 ///
92 /// discord.js counterpart: `toJSON` of the select menu builders with validation off (`disableValidators`).
93 #[must_use]
94 pub fn build_unchecked(self) -> Component {
95 self.into()
96 }
97 }
98
99 impl From<$builder> for Component {
100 fn from(menu: $builder) -> Self {
101 Self::$variant(menu.select)
102 }
103 }
104 };
105}
106
107/// Builds a [string select menu](https://docs.discord.com/developers/components/reference#string-select):
108/// a drop-down of up to 25 options you define, sending the chosen values to your app.
109///
110/// Add plain options with [`option`](Self::option) and detailed ones with
111/// [`option_with`](Self::option_with) (D-203). [`build`](Self::build) checks what Discord
112/// checks (D-200): 1-25 options and at least [`max_values`](Self::max_values) of them, labels
113/// of 1-100 characters, unique values of 1-100 characters, descriptions of at most 100.
114///
115/// discord.js counterpart: `StringSelectMenuBuilder`.
116///
117/// # Examples
118///
119/// ```
120/// use djs_builders::{ActionRowBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder};
121///
122/// let menu = StringSelectMenuBuilder::new("color")
123/// .placeholder("Pick colors")
124/// .option("Red", "red")
125/// .option("Green", "green")
126/// .option_with(
127/// StringSelectMenuOptionBuilder::new("Blue", "blue")
128/// .description("Like the sky")
129/// .default(true),
130/// )
131/// .max_values(2);
132/// let row = ActionRowBuilder::new().component(menu).build().unwrap();
133/// assert_eq!(row.children().len(), 1);
134/// ```
135#[derive(Clone, Debug, PartialEq, Eq)]
136#[must_use = "a builder does nothing until it is added to a row or built"]
137pub struct StringSelectMenuBuilder {
138 select: StringSelect,
139}
140
141impl StringSelectMenuBuilder {
142 /// Creates a menu without options, sending `custom_id` (1-100 characters) to your app.
143 ///
144 /// discord.js counterpart: `new StringSelectMenuBuilder().setCustomId(…)`.
145 pub fn new(custom_id: impl Into<CompactString>) -> Self {
146 Self {
147 select: StringSelect::new(custom_id, Vec::new()),
148 }
149 }
150
151 /// Adds an option showing `label` (1-100 characters) and sending `value` (1-100
152 /// characters, unique in the menu).
153 ///
154 /// discord.js counterpart: `addOptions({ label, value })`.
155 pub fn option(
156 mut self,
157 label: impl Into<CompactString>,
158 value: impl Into<CompactString>,
159 ) -> Self {
160 self.select.options.push(SelectOption::new(label, value));
161 self
162 }
163
164 /// Adds an option with a description, an emoji or selected by default.
165 ///
166 /// discord.js counterpart: `addOptions(new StringSelectMenuOptionBuilder()…)`.
167 pub fn option_with(mut self, option: StringSelectMenuOptionBuilder) -> Self {
168 self.select.options.push(option.option);
169 self
170 }
171
172 /// Adds several options: [`StringSelectMenuOptionBuilder`]s or `djs-model`
173 /// [`SelectOption`]s.
174 ///
175 /// discord.js counterpart: `addOptions`.
176 pub fn options<O: Into<SelectOption>>(mut self, options: impl IntoIterator<Item = O>) -> Self {
177 self.select
178 .options
179 .extend(options.into_iter().map(Into::into));
180 self
181 }
182}
183
184select_menu!(StringSelectMenuBuilder => StringSelect);
185
186/// Builds an [option of a string select menu](https://docs.discord.com/developers/components/reference#string-select-select-option-structure)
187/// with more than a label and a value, for [`StringSelectMenuBuilder::option_with`].
188///
189/// discord.js counterpart: `StringSelectMenuOptionBuilder`.
190#[derive(Clone, Debug, PartialEq, Eq)]
191#[must_use = "an option does nothing until it is added to a menu"]
192pub struct StringSelectMenuOptionBuilder {
193 option: SelectOption,
194}
195
196impl StringSelectMenuOptionBuilder {
197 /// Creates an option showing `label` (1-100 characters) and sending `value` (1-100
198 /// characters).
199 ///
200 /// discord.js counterpart: `new StringSelectMenuOptionBuilder().setLabel(…).setValue(…)`.
201 pub fn new(label: impl Into<CompactString>, value: impl Into<CompactString>) -> Self {
202 Self {
203 option: SelectOption::new(label, value),
204 }
205 }
206
207 /// Sets the smaller text under the label (at most 100 characters).
208 ///
209 /// discord.js counterpart: `setDescription`.
210 pub fn description(mut self, description: impl Into<CompactString>) -> Self {
211 self.option.description = Some(description.into());
212 self
213 }
214
215 /// Sets the emoji shown before the label.
216 ///
217 /// discord.js counterpart: `setEmoji`.
218 pub fn emoji(mut self, emoji: impl Into<PartialEmoji>) -> Self {
219 self.option.emoji = Some(emoji.into());
220 self
221 }
222
223 /// Sets whether the option is selected when the menu appears.
224 ///
225 /// discord.js counterpart: `setDefault`.
226 pub fn default(mut self, default: bool) -> Self {
227 self.option.default = default;
228 self
229 }
230}
231
232impl From<StringSelectMenuOptionBuilder> for SelectOption {
233 fn from(option: StringSelectMenuOptionBuilder) -> Self {
234 option.option
235 }
236}
237
238/// Implements the default-value setter `$method` adding IDs of type `$id` as `$kind`.
239macro_rules! default_values {
240 ($method:ident, $id:ty, $kind:ident, $what:literal, $djs:literal) => {
241 #[doc = concat!("Adds ", $what, " selected when the menu appears; their number must be within")]
242 /// [`min_values`](Self::min_values) and [`max_values`](Self::max_values).
243 ///
244 #[doc = concat!("discord.js counterpart: `", $djs, "`.")]
245 pub fn $method(mut self, ids: impl IntoIterator<Item = $id>) -> Self {
246 self.select.default_values.extend(
247 ids.into_iter()
248 .map(|id| SelectDefaultValue::new(id.cast(), SelectDefaultValueType::$kind)),
249 );
250 self
251 }
252 };
253}
254
255/// Builds a [user select menu](https://docs.discord.com/developers/components/reference#user-select),
256/// which Discord fills with the server's members.
257///
258/// discord.js counterpart: `UserSelectMenuBuilder`.
259///
260/// # Examples
261///
262/// ```
263/// use djs_builders::UserSelectMenuBuilder;
264/// use djs_model::id::UserId;
265///
266/// let menu = UserSelectMenuBuilder::new("invite")
267/// .max_values(3)
268/// .default_users([UserId::new(80_351_110_224_678_912)])
269/// .build()
270/// .unwrap();
271/// assert_eq!(menu.custom_id(), Some("invite"));
272/// ```
273#[derive(Clone, Debug, PartialEq, Eq)]
274#[must_use = "a builder does nothing until it is added to a row or built"]
275pub struct UserSelectMenuBuilder {
276 select: AutoPopulatedSelect,
277}
278
279impl UserSelectMenuBuilder {
280 /// Creates a menu sending `custom_id` (1-100 characters) to your app.
281 ///
282 /// discord.js counterpart: `new UserSelectMenuBuilder().setCustomId(customId)`.
283 pub fn new(custom_id: impl Into<CompactString>) -> Self {
284 Self {
285 select: AutoPopulatedSelect::new(custom_id),
286 }
287 }
288
289 default_values!(default_users, UserId, User, "users", "addDefaultUsers");
290}
291
292select_menu!(UserSelectMenuBuilder => UserSelect);
293
294/// Builds a [role select menu](https://docs.discord.com/developers/components/reference#role-select),
295/// which Discord fills with the server's roles.
296///
297/// discord.js counterpart: `RoleSelectMenuBuilder`.
298#[derive(Clone, Debug, PartialEq, Eq)]
299#[must_use = "a builder does nothing until it is added to a row or built"]
300pub struct RoleSelectMenuBuilder {
301 select: AutoPopulatedSelect,
302}
303
304impl RoleSelectMenuBuilder {
305 /// Creates a menu sending `custom_id` (1-100 characters) to your app.
306 ///
307 /// discord.js counterpart: `new RoleSelectMenuBuilder().setCustomId(customId)`.
308 pub fn new(custom_id: impl Into<CompactString>) -> Self {
309 Self {
310 select: AutoPopulatedSelect::new(custom_id),
311 }
312 }
313
314 default_values!(default_roles, RoleId, Role, "roles", "addDefaultRoles");
315}
316
317select_menu!(RoleSelectMenuBuilder => RoleSelect);
318
319/// Builds a [mentionable select menu](https://docs.discord.com/developers/components/reference#mentionable-select),
320/// which Discord fills with the server's members and roles.
321///
322/// discord.js counterpart: `MentionableSelectMenuBuilder`.
323#[derive(Clone, Debug, PartialEq, Eq)]
324#[must_use = "a builder does nothing until it is added to a row or built"]
325pub struct MentionableSelectMenuBuilder {
326 select: AutoPopulatedSelect,
327}
328
329impl MentionableSelectMenuBuilder {
330 /// Creates a menu sending `custom_id` (1-100 characters) to your app.
331 ///
332 /// discord.js counterpart: `new MentionableSelectMenuBuilder().setCustomId(customId)`.
333 pub fn new(custom_id: impl Into<CompactString>) -> Self {
334 Self {
335 select: AutoPopulatedSelect::new(custom_id),
336 }
337 }
338
339 default_values!(default_users, UserId, User, "users", "addDefaultUsers");
340 default_values!(default_roles, RoleId, Role, "roles", "addDefaultRoles");
341}
342
343select_menu!(MentionableSelectMenuBuilder => MentionableSelect);
344
345/// Builds a [channel select menu](https://docs.discord.com/developers/components/reference#channel-select),
346/// which Discord fills with the server's channels, optionally only of some
347/// [types](Self::channel_types).
348///
349/// discord.js counterpart: `ChannelSelectMenuBuilder`.
350#[derive(Clone, Debug, PartialEq, Eq)]
351#[must_use = "a builder does nothing until it is added to a row or built"]
352pub struct ChannelSelectMenuBuilder {
353 select: ChannelSelect,
354}
355
356impl ChannelSelectMenuBuilder {
357 /// Creates a menu sending `custom_id` (1-100 characters) to your app.
358 ///
359 /// discord.js counterpart: `new ChannelSelectMenuBuilder().setCustomId(customId)`.
360 pub fn new(custom_id: impl Into<CompactString>) -> Self {
361 Self {
362 select: ChannelSelect::new(custom_id),
363 }
364 }
365
366 /// Sets the channel types offered (all when not set), replacing those set before.
367 ///
368 /// discord.js counterpart: `setChannelTypes`.
369 pub fn channel_types(mut self, channel_types: impl IntoIterator<Item = ChannelType>) -> Self {
370 self.select.channel_types = channel_types.into_iter().collect();
371 self
372 }
373
374 default_values!(
375 default_channels,
376 ChannelId,
377 Channel,
378 "channels",
379 "addDefaultChannels"
380 );
381}
382
383select_menu!(ChannelSelectMenuBuilder => ChannelSelect);