djs_builders/component/list.rs
1//! [`validate_components`]: the limits only a whole list of message components shows (D-199).
2
3use djs_model::component::Component;
4
5use super::validate::{self, Totals};
6use crate::{
7 ValidationError,
8 check::{self, Path},
9};
10
11/// Which component system a message uses — the `IS_COMPONENTS_V2` message flag.
12///
13/// discord.js counterpart: `MessageFlags.IsComponentsV2`.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
15#[non_exhaustive]
16pub enum ComponentsVersion {
17 /// Without the flag: up to five action rows next to the content and embeds.
18 Legacy,
19 /// With [`MessageFlags::IS_COMPONENTS_V2`](djs_model::message::MessageFlags::IS_COMPONENTS_V2):
20 /// layout and content components replace the content and embeds, up to 40 components
21 /// and 4000 characters of text in all.
22 V2,
23}
24
25/// Legacy messages have at most five action rows.
26const LEGACY_ROWS: usize = 5;
27/// Components V2 messages have at most 40 components, nested ones included (D-200).
28const V2_COMPONENTS: usize = 40;
29/// Components V2 messages show at most 4000 characters of text in all (D-200, D-201).
30const V2_TEXT: usize = 4000;
31
32/// Checks the limits that apply to all components of one message together (D-199), and each
33/// component itself.
34///
35/// - [`Legacy`](ComponentsVersion::Legacy): at most 5 components, all action rows.
36/// - [`V2`](ComponentsVersion::V2): only layout and content components at the top level; at
37/// most 40 components counting nested ones, and at most 4000 characters (code points after
38/// trimming) across the text displays — as measured on the live API (D-200, D-201).
39/// - Both: every `custom_id` is unique in the message (D-200).
40///
41/// Discord also refuses a request that is too large in bytes (`413`) — for example a single
42/// text display of 4000 emoji —, which this does not check.
43///
44/// discord.js counterpart: none (`@discordjs/builders` checks each component alone).
45///
46/// # Errors
47///
48/// The first [`ValidationError`] found: the number or type of top-level components, a
49/// component's own rules, a repeated `custom_id`, then the V2 totals
50/// ([`TooMany`](ValidationError::TooMany) / [`TooLong`](ValidationError::TooLong) with the
51/// field `components`).
52///
53/// # Examples
54///
55/// ```
56/// use djs_builders::{ActionRowBuilder, ButtonBuilder, ComponentsVersion, validate_components};
57///
58/// let row = |id: &str| {
59/// ActionRowBuilder::new()
60/// .component(ButtonBuilder::primary(id).label("Go"))
61/// .build()
62/// .unwrap()
63/// };
64/// assert!(validate_components(&[row("a"), row("b")], ComponentsVersion::Legacy).is_ok());
65///
66/// let error = validate_components(&[row("a"), row("a")], ComponentsVersion::Legacy).unwrap_err();
67/// assert_eq!(error.field(), "components[1].components[0].custom_id");
68/// ```
69pub fn validate_components(
70 components: &[Component],
71 version: ComponentsVersion,
72) -> Result<(), ValidationError> {
73 let root = Path::Root;
74 if version == ComponentsVersion::Legacy {
75 check::count(|| "components".into(), components.len(), LEGACY_ROWS)?;
76 }
77 let mut totals = Totals::new();
78 for (index, component) in components.iter().enumerate() {
79 let here = root.item("components", index);
80 let allowed = match version {
81 ComponentsVersion::Legacy => matches!(component, Component::ActionRow(_)),
82 ComponentsVersion::V2 => matches!(
83 component,
84 Component::ActionRow(_)
85 | Component::TextDisplay(_)
86 | Component::Section(_)
87 | Component::MediaGallery(_)
88 | Component::File(_)
89 | Component::Separator(_)
90 | Component::Container(_)
91 ),
92 };
93 if !allowed {
94 return Err(ValidationError::Invalid {
95 field: here.this(),
96 reason: match version {
97 ComponentsVersion::Legacy => {
98 "a message without the Components V2 flag can only have action rows"
99 }
100 ComponentsVersion::V2 => {
101 "this component cannot be at the top level of a message"
102 }
103 },
104 });
105 }
106 validate::component(&here, component)?;
107 totals.walk(&here, component)?;
108 if version == ComponentsVersion::V2 && totals.components > V2_COMPONENTS {
109 // The list is rejected for its size below; the remaining components are still
110 // checked and counted, but their `custom_id`s no longer compared.
111 totals.stop_comparing_ids();
112 }
113 }
114 if version == ComponentsVersion::V2 {
115 check::count(|| "components".into(), totals.components, V2_COMPONENTS)?;
116 if totals.text > V2_TEXT {
117 return Err(ValidationError::TooLong {
118 field: "components".into(),
119 max: V2_TEXT,
120 actual: totals.text,
121 });
122 }
123 }
124 Ok(())
125}