djs_builders/component/action_row.rs
1//! [`ActionRowBuilder`].
2
3use djs_model::component::{ActionRow, Component};
4
5use super::validate;
6use crate::{ValidationError, check::Path};
7
8/// Builds an [action row](https://docs.discord.com/developers/components/reference#action-row):
9/// a line of up to five buttons, or one select menu.
10///
11/// Children are added with [`component`](Self::component) — any builder of this crate or a
12/// `djs-model` [`Component`] — and [`build`](Self::build) checks the mix (D-198): 1-5 buttons,
13/// or exactly one select menu, with unique `custom_id`s; each child is checked too, with paths
14/// such as `components[2].label`. Text inputs belong in a modal's
15/// [label](crate::LabelBuilder): the old rows of text inputs are rejected (D-207).
16///
17/// A legacy message (without the Components V2 flag) has at most five rows; check a whole
18/// list with [`validate_components`](crate::validate_components).
19///
20/// discord.js counterpart: `ActionRowBuilder`.
21///
22/// # Examples
23///
24/// ```
25/// use djs_builders::{ActionRowBuilder, ButtonBuilder, ValidationError};
26///
27/// let mut row = ActionRowBuilder::new();
28/// for page in 1..=3 {
29/// row = row.component(ButtonBuilder::secondary(format!("page-{page}")).label(page.to_string()));
30/// }
31/// assert!(row.build().is_ok());
32///
33/// let error = ActionRowBuilder::new().build().unwrap_err();
34/// assert_eq!(error.to_string(), "components has too few items: 0, at least 1 required");
35/// ```
36#[derive(Clone, Debug, PartialEq, Eq)]
37#[must_use = "a builder does nothing until it is added to a message or built"]
38pub struct ActionRowBuilder {
39 row: ActionRow,
40}
41
42impl Default for ActionRowBuilder {
43 fn default() -> Self {
44 Self::new()
45 }
46}
47
48impl ActionRowBuilder {
49 /// Creates an empty row; it needs at least one component.
50 ///
51 /// discord.js counterpart: `new ActionRowBuilder()`.
52 pub fn new() -> Self {
53 Self {
54 row: ActionRow::new(Vec::new()),
55 }
56 }
57
58 /// Adds a component after those already added.
59 ///
60 /// discord.js counterpart: `addComponents`.
61 pub fn component(mut self, component: impl Into<Component>) -> Self {
62 self.row.components.push(component.into());
63 self
64 }
65
66 /// Adds several components.
67 ///
68 /// discord.js counterpart: `addComponents`.
69 pub fn components<C: Into<Component>>(
70 mut self,
71 components: impl IntoIterator<Item = C>,
72 ) -> Self {
73 self.row
74 .components
75 .extend(components.into_iter().map(Into::into));
76 self
77 }
78
79 /// Sets the component's numeric identifier (Discord generates one otherwise); it must be
80 /// unique in the message or modal.
81 ///
82 /// discord.js counterpart: `setId`.
83 pub fn id(mut self, id: i32) -> Self {
84 self.row.id = Some(id);
85 self
86 }
87
88 /// Checks the row and its children and returns it as a [`Component`].
89 ///
90 /// discord.js counterpart: `ActionRowBuilder#toJSON`.
91 ///
92 /// # Errors
93 ///
94 /// [`ValidationError::TooFew`] / [`ValidationError::TooMany`] for an empty row or more than
95 /// five components, [`ValidationError::Invalid`] for a wrong mix or a repeated
96 /// `custom_id`, then the first problem of a child.
97 pub fn build(self) -> Result<Component, ValidationError> {
98 validate::action_row(&Path::Root, &self.row)?;
99 Ok(self.into())
100 }
101
102 /// Returns the row without any check (D-180).
103 ///
104 /// discord.js counterpart: `ActionRowBuilder#toJSON` with validation off (`disableValidators`).
105 #[must_use]
106 pub fn build_unchecked(self) -> Component {
107 self.into()
108 }
109}
110
111impl From<ActionRowBuilder> for Component {
112 fn from(row: ActionRowBuilder) -> Self {
113 Self::ActionRow(row.row)
114 }
115}