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