Skip to main content

djs_builders/component/
modal.rs

1//! Modal builders: [`ModalBuilder`], [`LabelBuilder`] and the fields a label holds.
2
3use compact_str::CompactString;
4use djs_model::{
5    component::{
6        Checkbox, CheckboxGroup, Component, FileUpload, GroupOption, Label, RadioGroup,
7        TextDisplay, TextInput, TextInputStyle,
8    },
9    interaction::ModalCallbackData,
10};
11
12use super::validate;
13use crate::ValidationError;
14
15/// Builds a [modal](https://docs.discord.com/developers/interactions/receiving-and-responding#interaction-response-object-modal):
16/// a pop-up form your app shows in answer to an interaction.
17///
18/// A modal has a `custom_id`, a title (1-45 characters) and 1-5 labels and text displays
19/// (D-206, D-207). Each [label](LabelBuilder) holds one field: a
20/// [text input](TextInputBuilder), a select menu, a [file upload](FileUploadBuilder), a
21/// [radio group](RadioGroupBuilder), a [checkbox group](CheckboxGroupBuilder) or a
22/// [checkbox](CheckboxBuilder). [`label`](Self::label) adds a label without a description;
23/// [`component`](Self::component) takes a [`LabelBuilder`] with one.
24///
25/// The rules come from Discord's documentation only: a modal cannot be sent without a user's
26/// interaction, so they were not tried on the live API (D-200).
27///
28/// discord.js counterpart: `ModalBuilder`. Unlike discord.js v14, action rows with text inputs
29/// (the deprecated format) are rejected (D-207).
30///
31/// # Examples
32///
33/// ```
34/// use djs_builders::{
35///     FileUploadBuilder, LabelBuilder, ModalBuilder, RadioGroupBuilder, TextInputBuilder,
36/// };
37///
38/// # fn main() -> Result<(), djs_builders::ValidationError> {
39/// let modal = ModalBuilder::new("feedback", "Your feedback")
40///     .text("Thanks for helping!")
41///     .label("Topic", TextInputBuilder::short("topic").max_length(80))
42///     .component(
43///         LabelBuilder::new("Details", TextInputBuilder::paragraph("body").required(false))
44///             .description("Optional"),
45///     )
46///     .label(
47///         "Rating",
48///         RadioGroupBuilder::new("rating").option("Good", "good").option("Bad", "bad"),
49///     )
50///     .label("Screenshots", FileUploadBuilder::new("shots").max_values(3))
51///     .build()?;
52/// assert_eq!(modal.components.len(), 5);
53/// # Ok(())
54/// # }
55/// ```
56#[derive(Clone, Debug, PartialEq, Eq)]
57#[must_use = "a builder does nothing until `build` is called"]
58pub struct ModalBuilder {
59    modal: ModalCallbackData,
60}
61
62impl ModalBuilder {
63    /// Creates a modal sending `custom_id` (1-100 characters) back when submitted, titled
64    /// `title` (1-45 characters). It needs 1-5 labels and texts.
65    ///
66    /// discord.js counterpart: `new ModalBuilder().setCustomId(…).setTitle(…)`.
67    pub fn new(custom_id: impl Into<CompactString>, title: impl Into<CompactString>) -> Self {
68        Self {
69            modal: ModalCallbackData::new(custom_id, title, Vec::new()),
70        }
71    }
72
73    /// Adds a label `label` (1-45 characters) around `field`, without a description.
74    ///
75    /// discord.js counterpart: `addLabelComponents`.
76    pub fn label(self, label: impl Into<CompactString>, field: impl Into<Component>) -> Self {
77        self.component(LabelBuilder::new(label, field))
78    }
79
80    /// Adds a text display showing `content` (markdown, 1-4000 characters).
81    ///
82    /// discord.js counterpart: `addTextDisplayComponents`.
83    pub fn text(self, content: impl Into<CompactString>) -> Self {
84        self.component(TextDisplay::new(content))
85    }
86
87    /// Adds a component after those already added: a [`LabelBuilder`], a text display, or a
88    /// `djs-model` [`Component`] of those types.
89    ///
90    /// discord.js counterpart: `addLabelComponents` / `addTextDisplayComponents`.
91    pub fn component(mut self, component: impl Into<Component>) -> Self {
92        self.modal.components.push(component.into());
93        self
94    }
95
96    /// Checks the modal and everything in it, and returns it ready for
97    /// `InteractionResponse::Modal`.
98    ///
99    /// discord.js counterpart: `ModalBuilder#toJSON`.
100    ///
101    /// # Errors
102    ///
103    /// The first [`ValidationError`] found: the `custom_id`, the title, the number and types
104    /// of components, each label and field (paths such as `components[1].component.max_length`),
105    /// then repeated `custom_id`s.
106    pub fn build(self) -> Result<ModalCallbackData, ValidationError> {
107        validate::modal(&self.modal)?;
108        Ok(self.modal)
109    }
110
111    /// Returns the modal without any check (D-180) — also the way to send the deprecated
112    /// action-row format (D-207).
113    ///
114    /// discord.js counterpart: `ModalBuilder#toJSON` with validation off (`disableValidators`).
115    #[must_use]
116    pub fn build_unchecked(self) -> ModalCallbackData {
117        self.modal
118    }
119}
120
121/// Builds a [label](https://docs.discord.com/developers/components/reference#label): a title
122/// (1-45 characters) and an optional description (at most 100) around one field of a modal.
123///
124/// The field is given to [`new`](Self::new), like a section's accessory (D-204, D-206).
125///
126/// discord.js counterpart: `LabelBuilder`.
127#[derive(Clone, Debug, PartialEq, Eq)]
128#[must_use = "a builder does nothing until it is added to a modal or built"]
129pub struct LabelBuilder {
130    component: Label,
131}
132
133impl LabelBuilder {
134    /// Creates a label `label` around `field`: a text input, a select menu, a file upload, a
135    /// radio group, a checkbox group or a checkbox.
136    ///
137    /// discord.js counterpart: `new LabelBuilder().setLabel(…).set…Component(…)`.
138    pub fn new(label: impl Into<CompactString>, field: impl Into<Component>) -> Self {
139        Self {
140            component: Label::new(label, field.into()),
141        }
142    }
143
144    /// Sets the smaller text under the label (at most 100 characters).
145    ///
146    /// discord.js counterpart: `setDescription`.
147    pub fn description(mut self, description: impl Into<CompactString>) -> Self {
148        self.component.description = Some(description.into());
149        self
150    }
151}
152
153component_builder!(LabelBuilder => Label);
154
155/// Builds a [text input](https://docs.discord.com/developers/components/reference#text-input)
156/// for a modal's [label](LabelBuilder): one line ([`short`](Self::short)) or several
157/// ([`paragraph`](Self::paragraph)).
158///
159/// `min_length` is 0-4000, `max_length` 1-4000 and at least `min_length`; the pre-filled value
160/// has at most 4000 characters and the placeholder at most 100.
161///
162/// discord.js counterpart: `TextInputBuilder`.
163#[derive(Clone, Debug, PartialEq, Eq)]
164#[must_use = "a builder does nothing until it is added to a label or built"]
165pub struct TextInputBuilder {
166    component: TextInput,
167}
168
169impl TextInputBuilder {
170    /// Creates a one-line, required text input sending `custom_id` (1-100 characters).
171    ///
172    /// discord.js counterpart: `setStyle(TextInputStyle.Short).setCustomId(…)`.
173    pub fn short(custom_id: impl Into<CompactString>) -> Self {
174        Self {
175            component: TextInput::new(custom_id, TextInputStyle::Short),
176        }
177    }
178
179    /// Creates a multi-line, required text input sending `custom_id` (1-100 characters).
180    ///
181    /// discord.js counterpart: `setStyle(TextInputStyle.Paragraph).setCustomId(…)`.
182    pub fn paragraph(custom_id: impl Into<CompactString>) -> Self {
183        Self {
184            component: TextInput::new(custom_id, TextInputStyle::Paragraph),
185        }
186    }
187
188    /// Sets the shortest text users may enter (0-4000).
189    ///
190    /// discord.js counterpart: `setMinLength`.
191    pub fn min_length(mut self, min_length: u16) -> Self {
192        self.component.min_length = Some(min_length);
193        self
194    }
195
196    /// Sets the longest text users may enter (1-4000, at least the
197    /// [`min_length`](Self::min_length)).
198    ///
199    /// discord.js counterpart: `setMaxLength`.
200    pub fn max_length(mut self, max_length: u16) -> Self {
201        self.component.max_length = Some(max_length);
202        self
203    }
204
205    /// Sets whether the input must be filled to submit the modal (default: yes).
206    ///
207    /// discord.js counterpart: `setRequired`.
208    pub fn required(mut self, required: bool) -> Self {
209        self.component.required = required;
210        self
211    }
212
213    /// Sets the text already filled in (at most 4000 characters).
214    ///
215    /// discord.js counterpart: `setValue`.
216    pub fn value(mut self, value: impl Into<CompactString>) -> Self {
217        self.component.value = Some(value.into());
218        self
219    }
220
221    /// Sets the text shown while the input is empty (at most 100 characters).
222    ///
223    /// discord.js counterpart: `setPlaceholder`.
224    pub fn placeholder(mut self, placeholder: impl Into<CompactString>) -> Self {
225        self.component.placeholder = Some(placeholder.into());
226        self
227    }
228}
229
230component_builder!(TextInputBuilder => TextInput);
231
232/// Builds a [file upload](https://docs.discord.com/developers/components/reference#file-upload)
233/// for a modal's [label](LabelBuilder): users attach 0-10 files.
234///
235/// `min_values` is 0-10 (at least 1 while the upload is required), `max_values` 1-10 and at
236/// least `min_values`; at most 10 [file types](Self::file_types).
237///
238/// discord.js counterpart: `FileUploadBuilder`.
239#[derive(Clone, Debug, PartialEq, Eq)]
240#[must_use = "a builder does nothing until it is added to a label or built"]
241pub struct FileUploadBuilder {
242    component: FileUpload,
243}
244
245impl FileUploadBuilder {
246    /// Creates a required upload of one file, sending `custom_id` (1-100 characters).
247    ///
248    /// discord.js counterpart: `new FileUploadBuilder().setCustomId(…)`.
249    pub fn new(custom_id: impl Into<CompactString>) -> Self {
250        Self {
251            component: FileUpload::new(custom_id),
252        }
253    }
254
255    /// Sets how many files must be uploaded at least (0-10; Discord's default: 1).
256    ///
257    /// discord.js counterpart: `setMinValues`.
258    pub fn min_values(mut self, min_values: u8) -> Self {
259        self.component.min_values = Some(min_values);
260        self
261    }
262
263    /// Sets how many files can be uploaded at most (1-10; Discord's default: 1).
264    ///
265    /// discord.js counterpart: `setMaxValues`.
266    pub fn max_values(mut self, max_values: u8) -> Self {
267        self.component.max_values = Some(max_values);
268        self
269    }
270
271    /// Sets whether files must be uploaded to submit the modal (default: yes).
272    ///
273    /// discord.js counterpart: `setRequired`.
274    pub fn required(mut self, required: bool) -> Self {
275        self.component.required = required;
276        self
277    }
278
279    /// Sets the [file types](https://docs.discord.com/developers/reference#file-type-filtering)
280    /// users may pick — `image`, `video`, `audio` or extensions such as `.pdf`, at most 10 —,
281    /// replacing those set before.
282    ///
283    /// discord.js counterpart: `setFileTypes`.
284    pub fn file_types<T: Into<CompactString>>(
285        mut self,
286        file_types: impl IntoIterator<Item = T>,
287    ) -> Self {
288        self.component.file_types = file_types.into_iter().map(Into::into).collect();
289        self
290    }
291}
292
293component_builder!(FileUploadBuilder => FileUpload);
294
295/// Defines an option builder of a radio or checkbox group (`GroupOption`).
296macro_rules! group_option {
297    ($(#[$meta:meta])* $builder:ident) => {
298        $(#[$meta])*
299        #[derive(Clone, Debug, PartialEq, Eq)]
300        #[must_use = "an option does nothing until it is added to a group"]
301        pub struct $builder {
302            option: GroupOption,
303        }
304
305        impl $builder {
306            /// Creates an option showing `label` (1-100 characters) and sending `value`
307            /// (1-100 characters, unique in the group).
308            ///
309            /// discord.js counterpart: `setLabel(…).setValue(…)`.
310            pub fn new(label: impl Into<CompactString>, value: impl Into<CompactString>) -> Self {
311                Self {
312                    option: GroupOption::new(label, value),
313                }
314            }
315
316            /// Sets the smaller text under the label (at most 100 characters).
317            ///
318            /// discord.js counterpart: `setDescription`.
319            pub fn description(mut self, description: impl Into<CompactString>) -> Self {
320                self.option.description = Some(description.into());
321                self
322            }
323
324            /// Sets whether the option is selected when the modal opens.
325            ///
326            /// discord.js counterpart: `setDefault`.
327            pub fn default(mut self, default: bool) -> Self {
328                self.option.default = default;
329                self
330            }
331        }
332
333        impl From<$builder> for GroupOption {
334            fn from(option: $builder) -> Self {
335                option.option
336            }
337        }
338    };
339}
340
341group_option! {
342    /// Builds an option of a [radio group](RadioGroupBuilder) with a description or selected
343    /// by default, for [`RadioGroupBuilder::option_with`].
344    ///
345    /// discord.js counterpart: `RadioGroupOptionBuilder`.
346    RadioGroupOptionBuilder
347}
348
349group_option! {
350    /// Builds an option of a [checkbox group](CheckboxGroupBuilder) with a description or
351    /// checked by default, for [`CheckboxGroupBuilder::option_with`].
352    ///
353    /// discord.js counterpart: `CheckboxGroupOptionBuilder`.
354    CheckboxGroupOptionBuilder
355}
356
357/// Builds a [radio group](https://docs.discord.com/developers/components/reference#radio-group)
358/// for a modal's [label](LabelBuilder): users pick exactly one of 2-10 options.
359///
360/// At most one option can be selected by default.
361///
362/// discord.js counterpart: `RadioGroupBuilder`.
363#[derive(Clone, Debug, PartialEq, Eq)]
364#[must_use = "a builder does nothing until it is added to a label or built"]
365pub struct RadioGroupBuilder {
366    component: RadioGroup,
367}
368
369impl RadioGroupBuilder {
370    /// Creates a required group without options, sending `custom_id` (1-100 characters).
371    ///
372    /// discord.js counterpart: `new RadioGroupBuilder().setCustomId(…)`.
373    pub fn new(custom_id: impl Into<CompactString>) -> Self {
374        Self {
375            component: RadioGroup::new(custom_id, Vec::new()),
376        }
377    }
378
379    /// Adds an option showing `label` and sending `value`.
380    ///
381    /// discord.js counterpart: `addOptions({ label, value })`.
382    pub fn option(
383        mut self,
384        label: impl Into<CompactString>,
385        value: impl Into<CompactString>,
386    ) -> Self {
387        self.component.options.push(GroupOption::new(label, value));
388        self
389    }
390
391    /// Adds an option with a description or selected by default.
392    ///
393    /// discord.js counterpart: `addOptions(new RadioGroupOptionBuilder()…)`.
394    pub fn option_with(mut self, option: RadioGroupOptionBuilder) -> Self {
395        self.component.options.push(option.into());
396        self
397    }
398
399    /// Adds several options: option builders or `djs-model` [`GroupOption`]s.
400    ///
401    /// discord.js counterpart: `addOptions`.
402    pub fn options<O: Into<GroupOption>>(mut self, options: impl IntoIterator<Item = O>) -> Self {
403        self.component
404            .options
405            .extend(options.into_iter().map(Into::into));
406        self
407    }
408
409    /// Sets whether a choice is needed to submit the modal (default: yes).
410    ///
411    /// discord.js counterpart: `setRequired`.
412    pub fn required(mut self, required: bool) -> Self {
413        self.component.required = required;
414        self
415    }
416}
417
418component_builder!(RadioGroupBuilder => RadioGroup);
419
420/// Builds a [checkbox group](https://docs.discord.com/developers/components/reference#checkbox-group)
421/// for a modal's [label](LabelBuilder): users check some of 1-10 options.
422///
423/// `min_values` is 0-10 (at least 1 while the group is required) and `max_values` 1-10 (by
424/// default all options), with at least `max_values` options.
425///
426/// discord.js counterpart: `CheckboxGroupBuilder`.
427#[derive(Clone, Debug, PartialEq, Eq)]
428#[must_use = "a builder does nothing until it is added to a label or built"]
429pub struct CheckboxGroupBuilder {
430    component: CheckboxGroup,
431}
432
433impl CheckboxGroupBuilder {
434    /// Creates a required group without options, sending `custom_id` (1-100 characters).
435    ///
436    /// discord.js counterpart: `new CheckboxGroupBuilder().setCustomId(…)`.
437    pub fn new(custom_id: impl Into<CompactString>) -> Self {
438        Self {
439            component: CheckboxGroup::new(custom_id, Vec::new()),
440        }
441    }
442
443    /// Adds an option showing `label` and sending `value`.
444    ///
445    /// discord.js counterpart: `addOptions({ label, value })`.
446    pub fn option(
447        mut self,
448        label: impl Into<CompactString>,
449        value: impl Into<CompactString>,
450    ) -> Self {
451        self.component.options.push(GroupOption::new(label, value));
452        self
453    }
454
455    /// Adds an option with a description or checked by default.
456    ///
457    /// discord.js counterpart: `addOptions(new CheckboxGroupOptionBuilder()…)`.
458    pub fn option_with(mut self, option: CheckboxGroupOptionBuilder) -> Self {
459        self.component.options.push(option.into());
460        self
461    }
462
463    /// Adds several options: option builders or `djs-model` [`GroupOption`]s.
464    ///
465    /// discord.js counterpart: `addOptions`.
466    pub fn options<O: Into<GroupOption>>(mut self, options: impl IntoIterator<Item = O>) -> Self {
467        self.component
468            .options
469            .extend(options.into_iter().map(Into::into));
470        self
471    }
472
473    /// Sets how many options must be checked at least (0-10; Discord's default: 1).
474    ///
475    /// discord.js counterpart: `setMinValues`.
476    pub fn min_values(mut self, min_values: u8) -> Self {
477        self.component.min_values = Some(min_values);
478        self
479    }
480
481    /// Sets how many options can be checked at most (1-10; Discord's default: all).
482    ///
483    /// discord.js counterpart: `setMaxValues`.
484    pub fn max_values(mut self, max_values: u8) -> Self {
485        self.component.max_values = Some(max_values);
486        self
487    }
488
489    /// Sets whether checking is needed to submit the modal (default: yes).
490    ///
491    /// discord.js counterpart: `setRequired`.
492    pub fn required(mut self, required: bool) -> Self {
493        self.component.required = required;
494        self
495    }
496}
497
498component_builder!(CheckboxGroupBuilder => CheckboxGroup);
499
500/// Builds a [checkbox](https://docs.discord.com/developers/components/reference#checkbox) for
501/// a modal's [label](LabelBuilder): a single yes/no choice, never required (use a one-option
502/// [checkbox group](CheckboxGroupBuilder) for that).
503///
504/// discord.js counterpart: `CheckboxBuilder`.
505///
506/// # Examples
507///
508/// ```
509/// use djs_builders::{CheckboxBuilder, ModalBuilder};
510///
511/// let modal = ModalBuilder::new("signup", "Sign up")
512///     .label("Send me the newsletter", CheckboxBuilder::new("newsletter").default(true))
513///     .build()
514///     .unwrap();
515/// assert_eq!(modal.components.len(), 1);
516/// ```
517#[derive(Clone, Debug, PartialEq, Eq)]
518#[must_use = "a builder does nothing until it is added to a label or built"]
519pub struct CheckboxBuilder {
520    component: Checkbox,
521}
522
523impl CheckboxBuilder {
524    /// Creates an unchecked checkbox sending `custom_id` (1-100 characters).
525    ///
526    /// discord.js counterpart: `new CheckboxBuilder().setCustomId(…)`.
527    pub fn new(custom_id: impl Into<CompactString>) -> Self {
528        Self {
529            component: Checkbox::new(custom_id),
530        }
531    }
532
533    /// Sets whether the checkbox is checked when the modal opens.
534    ///
535    /// discord.js counterpart: `setDefault`.
536    pub fn default(mut self, default: bool) -> Self {
537        self.component.default = default;
538        self
539    }
540}
541
542component_builder!(CheckboxBuilder => Checkbox);