Skip to main content

zaun_bot/
layout.rs

1//! Components V2 layout: [`TextDisplay`], [`Section`], [`Container`].
2
3use crate::types::{self, ContainerChild, SectionAccessory, SeparatorSpacing};
4use crate::{ActionRow, Button};
5
6/// A Components V2 text block (markdown, ≤ 4 000 per message in all).
7#[derive(Debug, Clone)]
8pub struct TextDisplay;
9
10impl TextDisplay {
11    /// A text display.
12    #[must_use]
13    #[allow(clippy::new_ret_no_self)]
14    pub fn new(content: impl Into<String>) -> types::TextDisplay {
15        types::TextDisplay {
16            id: None,
17            content: content.into(),
18        }
19    }
20}
21
22/// A Components V2 section: 1–3 text blocks with a button beside them.
23#[derive(Debug, Clone)]
24pub struct Section;
25
26impl Section {
27    /// A section of `texts` with a button accessory.
28    #[must_use]
29    #[allow(clippy::new_ret_no_self)]
30    pub fn with_button(texts: &[&str], button: Button) -> types::Section {
31        types::Section {
32            id: None,
33            components: texts.iter().map(|t| TextDisplay::new(*t)).collect(),
34            accessory: SectionAccessory::Button(button.build()),
35        }
36    }
37}
38
39/// Builds a Components V2 [`types::Container`].
40#[derive(Debug, Clone, Default)]
41pub struct Container {
42    children: Vec<ContainerChild>,
43    accent: Option<u32>,
44}
45
46impl Container {
47    /// An empty container.
48    #[must_use]
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// Accent colour, `0xRRGGBB`.
54    #[must_use]
55    pub fn accent(mut self, rgb: u32) -> Self {
56        self.accent = Some(rgb);
57        self
58    }
59
60    /// Adds a text block.
61    #[must_use]
62    pub fn text(mut self, content: impl Into<String>) -> Self {
63        self.children
64            .push(ContainerChild::TextDisplay(TextDisplay::new(content)));
65        self
66    }
67
68    /// Adds a section.
69    #[must_use]
70    pub fn section(mut self, section: types::Section) -> Self {
71        self.children.push(ContainerChild::Section(section));
72        self
73    }
74
75    /// Adds a row of buttons or a select.
76    #[must_use]
77    pub fn row(mut self, row: ActionRow) -> Self {
78        self.children.push(ContainerChild::ActionRow(row.build()));
79        self
80    }
81
82    /// Adds a divider line.
83    #[must_use]
84    pub fn separator(mut self) -> Self {
85        let sep = types::Separator {
86            id: None,
87            divider: true,
88            spacing: SeparatorSpacing::Small,
89        };
90        self.children.push(ContainerChild::Separator(sep));
91        self
92    }
93
94    /// The finished container.
95    #[must_use]
96    pub fn build(self) -> types::Container {
97        types::Container {
98            id: None,
99            components: self.children,
100            accent_color: self.accent,
101            spoiler: false,
102        }
103    }
104}