djs_builders/component/layout.rs
1//! Components V2 layout builders: [`ContainerBuilder`], [`SectionBuilder`] and
2//! [`SeparatorBuilder`].
3
4use compact_str::CompactString;
5use djs_model::component::{
6 Component, Container, Section, Separator, SeparatorSpacing, TextDisplay,
7};
8
9/// Builds a [container](https://docs.discord.com/developers/components/reference#container):
10/// a box around 1-40 components with an optional accent color, like an embed made of
11/// components.
12///
13/// It holds action rows, text displays (or [`text`](Self::text)), sections, media galleries,
14/// separators and files (D-198, D-204); [`build`](Self::build) checks the mix, each child, the
15/// accent color (at most `0xFFFFFF`) and that `custom_id`s inside are unique.
16///
17/// discord.js counterpart: `ContainerBuilder`.
18///
19/// # Examples
20///
21/// ```
22/// use djs_builders::{
23/// ActionRowBuilder, ButtonBuilder, ContainerBuilder, MediaGalleryBuilder, SectionBuilder,
24/// SeparatorBuilder, ThumbnailBuilder,
25/// };
26///
27/// # fn main() -> Result<(), djs_builders::ValidationError> {
28/// let card = ContainerBuilder::new()
29/// .accent_color(0x58_65F2)
30/// .text("## New release")
31/// .component(
32/// SectionBuilder::new(ThumbnailBuilder::new("attachment://logo.png"))
33/// .text("djs-rs 0.1 is out")
34/// .text("-# November 12"),
35/// )
36/// .component(SeparatorBuilder::new())
37/// .component(MediaGalleryBuilder::new().item("https://example.com/a.png"))
38/// .component(
39/// ActionRowBuilder::new()
40/// .component(ButtonBuilder::link("https://example.com").label("Download")),
41/// )
42/// .build()?;
43/// assert_eq!(card.children().len(), 5);
44/// # Ok(())
45/// # }
46/// ```
47#[derive(Clone, Debug, PartialEq, Eq)]
48#[must_use = "a builder does nothing until it is added to a message or built"]
49pub struct ContainerBuilder {
50 component: Container,
51}
52
53impl Default for ContainerBuilder {
54 fn default() -> Self {
55 Self::new()
56 }
57}
58
59impl ContainerBuilder {
60 /// Creates an empty container; it needs 1-40 components.
61 ///
62 /// discord.js counterpart: `new ContainerBuilder()`.
63 pub fn new() -> Self {
64 Self {
65 component: Container::new(Vec::new()),
66 }
67 }
68
69 /// Adds a text display showing `content` (markdown, 1-4000 characters).
70 ///
71 /// discord.js counterpart: `addTextDisplayComponents`.
72 pub fn text(self, content: impl Into<CompactString>) -> Self {
73 self.component(TextDisplay::new(content))
74 }
75
76 /// Adds a component after those already added: an action row, text display, section,
77 /// media gallery, separator or file — a builder of this crate or a `djs-model`
78 /// [`Component`].
79 ///
80 /// discord.js counterpart: `addActionRowComponents`, `addSectionComponents`, … (one per
81 /// type).
82 pub fn component(mut self, component: impl Into<Component>) -> Self {
83 self.component.components.push(component.into());
84 self
85 }
86
87 /// Adds several components.
88 ///
89 /// discord.js counterpart: `ContainerBuilder#addTextDisplayComponents` and its siblings.
90 pub fn components<C: Into<Component>>(
91 mut self,
92 components: impl IntoIterator<Item = C>,
93 ) -> Self {
94 self.component
95 .components
96 .extend(components.into_iter().map(Into::into));
97 self
98 }
99
100 /// Sets the color of the left border as an RGB integer (`0xRRGGBB`, at most `0xFFFFFF`).
101 ///
102 /// discord.js counterpart: `setAccentColor`.
103 pub fn accent_color(mut self, color: u32) -> Self {
104 self.component.accent_color = Some(color);
105 self
106 }
107
108 /// Sets whether the whole container is blurred until clicked.
109 ///
110 /// discord.js counterpart: `setSpoiler`.
111 pub fn spoiler(mut self, spoiler: bool) -> Self {
112 self.component.spoiler = spoiler;
113 self
114 }
115}
116
117component_builder!(ContainerBuilder => Container);
118
119/// Builds a [section](https://docs.discord.com/developers/components/reference#section): 1-3
120/// text displays next to an accessory — a [button](crate::ButtonBuilder) or a
121/// [thumbnail](crate::ThumbnailBuilder).
122///
123/// The accessory is given to [`new`](Self::new), so it cannot be forgotten (D-204).
124///
125/// discord.js counterpart: `SectionBuilder`.
126///
127/// # Examples
128///
129/// ```
130/// use djs_builders::{ButtonBuilder, SectionBuilder};
131///
132/// let section = SectionBuilder::new(ButtonBuilder::secondary("settings").label("Settings"))
133/// .text("**Notifications** are on")
134/// .build()
135/// .unwrap();
136/// assert_eq!(section.children().len(), 1);
137/// ```
138#[derive(Clone, Debug, PartialEq, Eq)]
139#[must_use = "a builder does nothing until it is added to a message or built"]
140pub struct SectionBuilder {
141 component: Section,
142}
143
144impl SectionBuilder {
145 /// Creates a section with `accessory` (a button or a thumbnail) and no text yet; it needs
146 /// 1-3 texts.
147 ///
148 /// discord.js counterpart: `new SectionBuilder().setButtonAccessory(…)` /
149 /// `setThumbnailAccessory(…)`.
150 pub fn new(accessory: impl Into<Component>) -> Self {
151 Self {
152 component: Section::new(Vec::new(), accessory.into()),
153 }
154 }
155
156 /// Adds a text display showing `content` (markdown, 1-4000 characters).
157 ///
158 /// discord.js counterpart: `addTextDisplayComponents`.
159 pub fn text(self, content: impl Into<CompactString>) -> Self {
160 self.component(TextDisplay::new(content))
161 }
162
163 /// Adds a text display (a [`TextDisplayBuilder`](crate::TextDisplayBuilder) or a
164 /// `djs-model` value).
165 ///
166 /// discord.js counterpart: `addTextDisplayComponents`.
167 pub fn component(mut self, component: impl Into<Component>) -> Self {
168 self.component.components.push(component.into());
169 self
170 }
171}
172
173component_builder!(SectionBuilder => Section);
174
175/// Builds a [separator](https://docs.discord.com/developers/components/reference#separator):
176/// vertical space between components, with a line by default.
177///
178/// discord.js counterpart: `SeparatorBuilder`.
179///
180/// # Examples
181///
182/// ```
183/// use djs_builders::SeparatorBuilder;
184/// use djs_model::component::SeparatorSpacing;
185///
186/// let gap = SeparatorBuilder::new().divider(false).spacing(SeparatorSpacing::Large).build().unwrap();
187/// assert_eq!(
188/// serde_json::to_string(&gap).unwrap(),
189/// r#"{"type":14,"divider":false,"spacing":2}"#
190/// );
191/// ```
192#[derive(Clone, Debug, Default, PartialEq, Eq)]
193#[must_use = "a builder does nothing until it is added to a message or built"]
194pub struct SeparatorBuilder {
195 component: Separator,
196}
197
198impl SeparatorBuilder {
199 /// Creates a separator with a line and small spacing.
200 ///
201 /// discord.js counterpart: `new SeparatorBuilder()`.
202 pub fn new() -> Self {
203 Self::default()
204 }
205
206 /// Sets whether a line is drawn (default: yes).
207 ///
208 /// discord.js counterpart: `setDivider`.
209 pub fn divider(mut self, divider: bool) -> Self {
210 self.component.divider = divider;
211 self
212 }
213
214 /// Sets the amount of space (default: small).
215 ///
216 /// discord.js counterpart: `setSpacing`.
217 pub fn spacing(mut self, spacing: SeparatorSpacing) -> Self {
218 self.component.spacing = Some(spacing);
219 self
220 }
221}
222
223component_builder!(SeparatorBuilder => Separator);