Skip to main content

glory_render/
select.rs

1//! Finite intrinsic selection controls. Keys identify options; values are form data.
2use std::{collections::HashSet, rc::Rc};
3
4use crate::{Error, SemanticId};
5
6pub const MAX_SELECT_OPTIONS: usize = 1024;
7pub const MAX_SELECT_GROUPS: usize = 32;
8pub const MAX_SELECT_BYTES: usize = 128 * 1024;
9
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct SelectOption {
12    pub key: SemanticId,
13    pub label: String,
14    pub value: String,
15    pub disabled: bool,
16}
17
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct SelectGroup {
20    pub label: String,
21    pub disabled: bool,
22    pub options: Vec<SelectOption>,
23}
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum SelectEntry {
27    Option(SelectOption),
28    Group(SelectGroup),
29    /// A decorative, non-selectable boundary between options or groups.
30    Divider,
31}
32
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
34pub struct SelectSelection {
35    /// Unique keys in document order, independent of business option values.
36    pub keys: Vec<SemanticId>,
37    pub revision: u64,
38}
39
40impl SelectSelection {
41    pub(crate) fn validate_revision(
42        &self,
43        previous: u64,
44        previous_keys: &[SemanticId],
45    ) -> Result<(), Error> {
46        if self.revision < previous || self.revision == previous && self.keys != previous_keys {
47            return Err(Error::SelectRevision {
48                current: previous,
49                incoming: self.revision,
50            });
51        }
52        Ok(())
53    }
54}
55
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct SelectProps {
58    /// Immutable declaration shared by live instances. Selection patches never
59    /// clone labels, values or option declarations.
60    pub entries: Rc<Vec<SelectEntry>>,
61    pub selection: SelectSelection,
62    pub multiple: bool,
63    pub rows: Option<u16>,
64    pub placeholder: String,
65    pub enabled: bool,
66}
67
68impl Default for SelectProps {
69    fn default() -> Self {
70        Self {
71            entries: Rc::default(),
72            selection: SelectSelection::default(),
73            multiple: false,
74            rows: None,
75            placeholder: String::new(),
76            enabled: true,
77        }
78    }
79}
80
81impl SelectProps {
82    pub fn options(&self) -> impl Iterator<Item = (&SelectOption, bool)> {
83        self.entries.iter().flat_map(|entry| {
84            let (options, disabled) = match entry {
85                SelectEntry::Divider => (&[][..], false),
86                SelectEntry::Option(option) => (std::slice::from_ref(option), false),
87                SelectEntry::Group(group) => (group.options.as_slice(), group.disabled),
88            };
89            options.iter().map(move |option| (option, disabled))
90        })
91    }
92
93    pub fn validate(&self) -> Result<(), Error> {
94        if self.entries.len() > MAX_SELECT_OPTIONS + MAX_SELECT_GROUPS
95            || self.rows.is_some_and(|rows| !(1..=64).contains(&rows))
96            || !text(&self.placeholder, 256)
97        {
98            return Err(Error::InvalidProps("invalid select configuration"));
99        }
100        let mut count = 0;
101        let mut groups = 0;
102        let mut bytes = self.placeholder.len();
103        let mut keys = HashSet::new();
104        for entry in self.entries.iter() {
105            let options = match entry {
106                SelectEntry::Divider => continue,
107                SelectEntry::Option(option) => std::slice::from_ref(option),
108                SelectEntry::Group(group) => {
109                    groups += 1;
110                    if groups > MAX_SELECT_GROUPS
111                        || group.label.is_empty()
112                        || !text(&group.label, 256)
113                        || group.options.len() > MAX_SELECT_OPTIONS
114                    {
115                        return Err(Error::InvalidProps("invalid select group"));
116                    }
117                    bytes += group.label.len();
118                    group.options.as_slice()
119                }
120            };
121            for option in options {
122                count += 1;
123                if count > MAX_SELECT_OPTIONS
124                    || option.key.as_str().len() > 64
125                    || !option.key.as_str().is_ascii()
126                    || !text(&option.label, 256)
127                    || !text(&option.value, 4096)
128                    || !keys.insert(&option.key)
129                {
130                    return Err(Error::InvalidProps("invalid select option"));
131                }
132                bytes += option.key.as_str().len() + option.label.len() + option.value.len();
133                if bytes > MAX_SELECT_BYTES {
134                    return Err(Error::InvalidProps(
135                        "select declaration exceeds byte budget",
136                    ));
137                }
138            }
139        }
140        self.validate_selection(&self.selection.keys)
141    }
142
143    pub fn validate_selection(&self, keys: &[SemanticId]) -> Result<(), Error> {
144        if keys.len() > if self.multiple { MAX_SELECT_OPTIONS } else { 1 } {
145            return Err(Error::InvalidProps("select selection exceeds cardinality"));
146        }
147        let mut next = keys.iter();
148        let mut requested = next.next();
149        // This walks only the bounded, mounted control declaration, never an
150        // application data source or a history of previously visited options.
151        for (option, _) in self.options() {
152            if requested == Some(&option.key) {
153                requested = next.next();
154            }
155        }
156        if requested.is_some() {
157            return Err(Error::InvalidProps(
158                "select keys must be unique known keys in document order",
159            ));
160        }
161        Ok(())
162    }
163
164    pub fn validate_user_selection(&self, keys: &[SemanticId]) -> Result<(), Error> {
165        self.validate_selection(keys)?;
166        for (option, group_disabled) in self.options() {
167            if (option.disabled || group_disabled)
168                && keys.contains(&option.key)
169                && !self.selection.keys.contains(&option.key)
170            {
171                return Err(Error::InvalidEvent(
172                    "disabled select option cannot be newly selected",
173                ));
174            }
175        }
176        Ok(())
177    }
178}
179
180fn text(value: &str, limit: usize) -> bool {
181    value.len() <= limit && !value.contains(['\0', '\r'])
182}