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
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct SelectProps {
42    /// Immutable declaration shared by live instances. Selection patches never
43    /// clone labels, values or option declarations.
44    pub entries: Rc<Vec<SelectEntry>>,
45    pub selection: SelectSelection,
46    pub multiple: bool,
47    pub rows: Option<u16>,
48    pub placeholder: String,
49    pub enabled: bool,
50}
51
52impl Default for SelectProps {
53    fn default() -> Self {
54        Self {
55            entries: Rc::default(),
56            selection: SelectSelection::default(),
57            multiple: false,
58            rows: None,
59            placeholder: String::new(),
60            enabled: true,
61        }
62    }
63}
64
65impl SelectProps {
66    pub fn options(&self) -> impl Iterator<Item = (&SelectOption, bool)> {
67        self.entries.iter().flat_map(|entry| {
68            let (options, disabled) = match entry {
69                SelectEntry::Divider => (&[][..], false),
70                SelectEntry::Option(option) => (std::slice::from_ref(option), false),
71                SelectEntry::Group(group) => (group.options.as_slice(), group.disabled),
72            };
73            options.iter().map(move |option| (option, disabled))
74        })
75    }
76
77    pub fn validate(&self) -> Result<(), Error> {
78        if self.entries.len() > MAX_SELECT_OPTIONS + MAX_SELECT_GROUPS
79            || self.rows.is_some_and(|rows| !(1..=64).contains(&rows))
80            || !text(&self.placeholder, 256)
81        {
82            return Err(Error::InvalidProps("invalid select configuration"));
83        }
84        let mut count = 0;
85        let mut groups = 0;
86        let mut bytes = self.placeholder.len();
87        let mut keys = HashSet::new();
88        for entry in self.entries.iter() {
89            let options = match entry {
90                SelectEntry::Divider => continue,
91                SelectEntry::Option(option) => std::slice::from_ref(option),
92                SelectEntry::Group(group) => {
93                    groups += 1;
94                    if groups > MAX_SELECT_GROUPS
95                        || group.label.is_empty()
96                        || !text(&group.label, 256)
97                        || group.options.len() > MAX_SELECT_OPTIONS
98                    {
99                        return Err(Error::InvalidProps("invalid select group"));
100                    }
101                    bytes += group.label.len();
102                    group.options.as_slice()
103                }
104            };
105            for option in options {
106                count += 1;
107                if count > MAX_SELECT_OPTIONS
108                    || option.key.as_str().len() > 64
109                    || !option.key.as_str().is_ascii()
110                    || !text(&option.label, 256)
111                    || !text(&option.value, 4096)
112                    || !keys.insert(&option.key)
113                {
114                    return Err(Error::InvalidProps("invalid select option"));
115                }
116                bytes += option.key.as_str().len() + option.label.len() + option.value.len();
117                if bytes > MAX_SELECT_BYTES {
118                    return Err(Error::InvalidProps(
119                        "select declaration exceeds byte budget",
120                    ));
121                }
122            }
123        }
124        self.validate_selection(&self.selection.keys)
125    }
126
127    pub fn validate_selection(&self, keys: &[SemanticId]) -> Result<(), Error> {
128        if keys.len() > if self.multiple { MAX_SELECT_OPTIONS } else { 1 } {
129            return Err(Error::InvalidProps("select selection exceeds cardinality"));
130        }
131        let mut next = keys.iter();
132        let mut requested = next.next();
133        // This walks only the bounded, mounted control declaration, never an
134        // application data source or a history of previously visited options.
135        for (option, _) in self.options() {
136            if requested == Some(&option.key) {
137                requested = next.next();
138            }
139        }
140        if requested.is_some() {
141            return Err(Error::InvalidProps(
142                "select keys must be unique known keys in document order",
143            ));
144        }
145        Ok(())
146    }
147
148    pub fn validate_user_selection(&self, keys: &[SemanticId]) -> Result<(), Error> {
149        self.validate_selection(keys)?;
150        for (option, group_disabled) in self.options() {
151            if (option.disabled || group_disabled)
152                && keys.contains(&option.key)
153                && !self.selection.keys.contains(&option.key)
154            {
155                return Err(Error::InvalidEvent(
156                    "disabled select option cannot be newly selected",
157                ));
158            }
159        }
160        Ok(())
161    }
162}
163
164fn text(value: &str, limit: usize) -> bool {
165    value.len() <= limit && !value.contains(['\0', '\r'])
166}