Skip to main content

zaun_community_protocol/command/object/component/
check.rs

1//! Where each component may appear, and the limits of a message's or modal's components
2//! (§8.14).
3
4mod fields;
5
6use std::collections::BTreeSet;
7
8use super::Component;
9use crate::command::{BodyError, check};
10use crate::ids::AttachmentId;
11use crate::limits::{
12    COMPONENT_ROW_BUTTONS, COMPONENT_ROWS, COMPONENTS_TOTAL, MODAL_ITEMS, MODAL_TITLE,
13    SECTION_TEXTS, TEXT_DISPLAY_TOTAL,
14};
15
16/// Where a component sits; decides which kinds may appear there.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18enum Place {
19    Top { v2: bool },
20    Row,
21    Container,
22    SectionText,
23    Accessory,
24    ModalTop,
25    LabelInput,
26}
27
28impl Place {
29    const fn allows(self, kind: u8) -> bool {
30        match self {
31            Self::Top { v2: false } => kind == 1,
32            Self::Top { v2: true } => matches!(kind, 1 | 9 | 10 | 12 | 13 | 14 | 17),
33            Self::Row => matches!(kind, 2 | 3 | 5..=8),
34            Self::Container => matches!(kind, 1 | 9 | 10 | 12 | 13 | 14),
35            Self::SectionText => kind == 10,
36            Self::Accessory => matches!(kind, 2 | 11),
37            Self::ModalTop => matches!(kind, 10 | 18),
38            Self::LabelInput => matches!(kind, 3..=8 | 19 | 21..=23),
39        }
40    }
41
42    const fn in_modal(self) -> bool {
43        matches!(self, Self::ModalTop | Self::LabelInput)
44    }
45}
46
47/// The running totals of one message or modal.
48#[derive(Default)]
49struct Walk<'a> {
50    total: usize,
51    text: usize,
52    custom_ids: BTreeSet<&'a str>,
53    ids: BTreeSet<u32>,
54}
55
56impl<'a> Walk<'a> {
57    fn visit(&mut self, c: &'a Component, place: Place) -> Result<(), BodyError> {
58        if !place.allows(c.kind()) {
59            return Err(BodyError::bad(
60                "components.type",
61                format!("type {} is not allowed here", c.kind()),
62            ));
63        }
64        self.total += 1;
65        check::count("components", self.total, COMPONENTS_TOTAL)?;
66        if let Some(id) = fields::id(c)
67            && !self.ids.insert(id)
68        {
69            return Err(BodyError::bad("components.id", "contains a duplicate"));
70        }
71        if let Some(custom_id) = c.custom_id()
72            && !self.custom_ids.insert(custom_id)
73        {
74            return Err(BodyError::bad(
75                "components.custom_id",
76                "contains a duplicate",
77            ));
78        }
79        self.text += fields::check(c, place.in_modal())?;
80        if self.text > TEXT_DISPLAY_TOTAL {
81            return Err(BodyError::too_large(
82                "components.content",
83                TEXT_DISPLAY_TOTAL,
84            ));
85        }
86        self.children(c)
87    }
88
89    fn children(&mut self, c: &'a Component) -> Result<(), BodyError> {
90        match c {
91            Component::ActionRow(row) => {
92                let buttons = row.components.iter().filter(|c| c.kind() == 2).count();
93                let ok = match row.components.len() {
94                    1 => true,
95                    n => buttons == n && n <= COMPONENT_ROW_BUTTONS,
96                };
97                if !ok || row.components.is_empty() {
98                    return Err(BodyError::bad(
99                        "components.components",
100                        "an action row holds 1–5 buttons or one select",
101                    ));
102                }
103                self.all(&row.components, Place::Row)
104            }
105            Component::Container(box_) => self.all(&box_.components, Place::Container),
106            Component::Section(section) => {
107                let (min, max) = SECTION_TEXTS;
108                if !(min..=max).contains(&section.components.len()) {
109                    return Err(BodyError::bad(
110                        "components.components",
111                        "a section holds 1–3 texts",
112                    ));
113                }
114                self.all(&section.components, Place::SectionText)?;
115                self.visit(&section.accessory, Place::Accessory)
116            }
117            Component::Label(label) => self.visit(&label.component, Place::LabelInput),
118            _ => Ok(()),
119        }
120    }
121
122    fn all(&mut self, list: &'a [Component], place: Place) -> Result<(), BodyError> {
123        list.iter().try_for_each(|c| self.visit(c, place))
124    }
125}
126
127/// A message's components: at most five action rows without `IS_COMPONENTS_V2`, the V2
128/// layout kinds with it; at most 40 in all, unique `id`s and `custom_id`s.
129///
130/// # Errors
131/// `BAD_REQUEST` naming the field, or `PAYLOAD_TOO_LARGE` for a count or text over its limit.
132pub fn check_message_components(components: &[Component], v2: bool) -> Result<(), BodyError> {
133    if !v2 {
134        check::count("components", components.len(), COMPONENT_ROWS)?;
135    }
136    Walk::default().all(components, Place::Top { v2 })
137}
138
139/// A modal (`MODAL` response): `custom_id`, `title` 1–45 and 1–5 labels or text displays.
140///
141/// # Errors
142/// As [`check_message_components`].
143pub fn check_modal(
144    custom_id: &str,
145    title: &str,
146    components: &[Component],
147) -> Result<(), BodyError> {
148    fields::custom_id(custom_id)?;
149    check::text("title", title, MODAL_TITLE)?;
150    let (min, max) = MODAL_ITEMS;
151    check::count("components", components.len(), max)?;
152    if components.len() < min {
153        return Err(BodyError::bad("components", "a modal needs a field"));
154    }
155    Walk::default().all(components, Place::ModalTop)
156}
157
158/// Every attachment the components show (thumbnails, gallery pictures, files), with the
159/// field naming it; each must be an attachment of the same message.
160#[must_use]
161pub fn component_attachments(components: &[Component]) -> Vec<(&'static str, AttachmentId)> {
162    let mut out = Vec::new();
163    let mut stack: Vec<&Component> = components.iter().collect();
164    while let Some(c) = stack.pop() {
165        match c {
166            Component::Thumbnail(t) => out.push(("components.media", t.media)),
167            Component::MediaGallery(g) => {
168                out.extend(g.items.iter().map(|i| ("components.items.media", i.media)));
169            }
170            Component::File(f) => out.push(("components.file", f.file)),
171            _ => stack.extend(c.children()),
172        }
173    }
174    out
175}