Skip to main content

glory_render/props/
view.rs

1//! Read-only effective fields, borrowed without materializing a Descriptor.
2use super::*;
3
4#[derive(Clone, Copy, Debug, PartialEq)]
5pub struct DescriptorView<'a> {
6    pub props: &'a Props,
7    pub classes: &'a Vec<String>,
8    pub style: &'a Style,
9    pub role: Option<Role>,
10    pub name: &'a Option<String>,
11    pub focus: FocusMode,
12    pub item: Option<ItemPosition>,
13    pub options: &'a Options,
14    pub semantics: &'a Option<Box<crate::Semantics>>,
15}
16impl<'a> DescriptorView<'a> {
17    pub fn view(&self) -> Self {
18        *self
19    }
20    /// Explicit full snapshot for an owned declaration, never a patch read.
21    pub fn to_owned(self) -> Descriptor {
22        Descriptor {
23            props: self.props.clone(),
24            classes: self.classes.clone(),
25            style: self.style.clone(),
26            role: self.role,
27            name: self.name.clone(),
28            focus: self.focus,
29            item: self.item,
30            options: self.options.clone(),
31            semantics: self.semantics.clone(),
32        }
33    }
34    pub fn semantic_id(&self) -> Option<&'a crate::SemanticId> {
35        self.semantics.as_ref().and_then(|s| s.id.as_ref())
36    }
37    pub fn hidden(&self) -> bool {
38        self.semantics.as_ref().is_some_and(|s| s.hidden)
39    }
40    pub fn activation_enabled(&self) -> bool {
41        self.props.enabled() && !self.semantics.as_ref().is_some_and(|s| s.disabled)
42    }
43    pub fn readonly(&self) -> bool {
44        self.semantics.as_ref().is_some_and(|s| s.readonly)
45    }
46    pub fn field_part(&self) -> Option<crate::FieldPart> {
47        self.semantics.as_ref().and_then(|s| s.field_part)
48    }
49    pub fn document_part(&self) -> Option<crate::DocumentPart> {
50        self.semantics.as_ref().and_then(|s| s.document_part)
51    }
52    /// Naming an otherwise generic View creates an accessible group; unnamed
53    /// generic Views remain only layout boxes. Explicit structural roles win.
54    pub fn effective_role(&self) -> Option<Role> {
55        if self.document_part().is_some() {
56            return None;
57        }
58        if self.field_part() == Some(crate::FieldPart::Form) {
59            return None;
60        }
61        if matches!(self.props, Props::Input(_))
62            && self
63                .semantics
64                .as_ref()
65                .is_some_and(|s| s.spinbutton.is_some())
66        {
67            return Some(Role::SpinButton);
68        }
69        self.role.or_else(|| {
70            (matches!(self.props, Props::View)
71                && (self.name.is_some()
72                    || self
73                        .semantics
74                        .as_ref()
75                        .is_some_and(|s| s.labelled_by.is_some())))
76            .then_some(Role::Group)
77        })
78    }
79
80    pub fn validate(&self) -> Result<(), Error> {
81        if let Some(source) = self.semantics.as_ref().and_then(|s| s.clipboard.as_ref()) {
82            source.validate()?
83        }
84        self.validate_fields(true, true, true)
85    }
86
87    // Live descriptors are already canonical/validated. A field patch only
88    // needs to rescan payloads it changes; cross-field constraints always run.
89    pub(crate) fn validate_fields(
90        &self,
91        input: bool,
92        style: bool,
93        classes: bool,
94    ) -> Result<(), Error> {
95        if self.role == Some(Role::SpinButton) {
96            return Err(Error::InvalidProps(
97                "spinbutton is intrinsic to numeric Input metadata",
98            ));
99        }
100        if self.role == Some(Role::Menubar) && self.semantics.is_none() {
101            return Err(Error::InvalidProps(
102                "menubar role requires finite navigation metadata",
103            ));
104        }
105        if self.role == Some(Role::Slider)
106            && self.semantics.as_ref().is_none_or(|s| s.slider.is_none())
107        {
108            return Err(Error::InvalidProps(
109                "slider role requires finite slider metadata",
110            ));
111        }
112        if self.role == Some(Role::ProgressBar)
113            && (self.focus != FocusMode::Auto
114                || self.semantics.as_ref().is_none_or(|s| s.progress.is_none()))
115        {
116            return Err(Error::InvalidProps(
117                "progress bars require read-only progress metadata and no focus",
118            ));
119        }
120        if self.role == Some(Role::Separator)
121            && self.focus != FocusMode::Auto
122            && !self
123                .semantics
124                .as_ref()
125                .is_some_and(|s| s.splitter.is_some())
126        {
127            return Err(Error::InvalidProps(
128                "passive separators cannot be focusable",
129            ));
130        }
131        if self.role == Some(Role::Tooltip) && self.focus != FocusMode::Auto {
132            return Err(Error::InvalidProps("tooltips cannot receive focus"));
133        }
134        if let Some(semantics) = &self.semantics {
135            semantics.validate(*self)?;
136        }
137        if matches!(self.role, Some(Role::Heading(level)) if !(1..=6).contains(&level)) {
138            return Err(Error::InvalidProps("heading level must be 1..=6"));
139        }
140        if style {
141            self.style.validate().map_err(Error::InvalidProps)?;
142        }
143        if let Some(item) = self.item
144            && (self.role != Some(Role::ListItem)
145                || item.index == usize::MAX
146                || item.count.is_some_and(|count| item.index >= count))
147        {
148            return Err(Error::InvalidProps(
149                "item position requires listitem role and a valid index/total",
150            ));
151        }
152        if *self.props == Props::Group && (self.focus != FocusMode::Auto || self.item.is_some()) {
153            return Err(Error::InvalidProps(
154                "group has no focus box or item position",
155            ));
156        }
157        if matches!(&self.props, Props::Text(TextProps { kind: TextKind::Heading(level), .. }) if !(1..=6).contains(level))
158        {
159            return Err(Error::InvalidProps("heading level must be 1..=6"));
160        }
161        if matches!(&self.props, Props::Input(p) if p.multiline && p.purpose != Purpose::Text) {
162            return Err(Error::InvalidProps("multiline input requires text purpose"));
163        }
164        if input
165            && matches!(&self.props, Props::Input(p) if !p.multiline && p.value.contains(['\r', '\n']))
166        {
167            return Err(Error::InvalidProps(
168                "single-line input cannot contain line breaks",
169            ));
170        }
171        if *self.props == Props::Group
172            && (*self.style != Style::default()
173                || !self.classes.is_empty()
174                || self.role.is_some()
175                || self.name.is_some())
176        {
177            return Err(Error::InvalidProps(
178                "group has no style box or accessibility role",
179            ));
180        }
181        if self.role.is_some() && !matches!(self.props, Props::View) {
182            return Err(Error::InvalidProps("structural roles require a view"));
183        }
184        if input && let Props::RichEditor(editor) = self.props {
185            editor.validate()?;
186        }
187        if input && let Props::File(file) = self.props {
188            file.validate()?;
189        }
190        if input && let Props::Select(select) = self.props {
191            select.validate()?;
192        }
193        if input && let Props::Link(link) = self.props {
194            link.validate()?;
195        }
196        if input && let Props::Graphic(graphic) = self.props {
197            graphic.validate()?;
198        }
199        if input && let Props::Image(image) = self.props {
200            image.responsive.validate()?;
201        }
202        if matches!(self.props, Props::Graphic(graphic) if graphic.alternative.is_none())
203            && (self.name.is_some() || self.focus != FocusMode::Auto)
204        {
205            return Err(Error::InvalidProps(
206                "decorative graphics cannot be named or focusable",
207            ));
208        }
209        if self.name.is_some()
210            && matches!(&self.props, Props::Text(text) if !matches!(text.kind, TextKind::Heading(_)))
211        {
212            return Err(Error::InvalidProps(
213                "only heading text accepts an accessible name",
214            ));
215        }
216        if matches!(&self.props, Props::Image(image) if image.alternative.is_none())
217            && (self.name.is_some() || self.focus != FocusMode::Auto)
218        {
219            return Err(Error::InvalidProps(
220                "decorative image has no name or focus target",
221            ));
222        }
223        if classes
224            && self
225                .classes
226                .iter()
227                .any(|class| class.is_empty() || class.chars().any(char::is_whitespace))
228        {
229            return Err(Error::InvalidProps(
230                "classes must be individual nonempty tokens",
231            ));
232        }
233        Ok(())
234    }
235}
236impl<'a> From<&'a Descriptor> for DescriptorView<'a> {
237    fn from(d: &'a Descriptor) -> Self {
238        Self {
239            props: &d.props,
240            classes: &d.classes,
241            style: &d.style,
242            role: d.role,
243            name: &d.name,
244            focus: d.focus,
245            item: d.item,
246            options: &d.options,
247            semantics: &d.semantics,
248        }
249    }
250}
251impl<'a> From<&DescriptorView<'a>> for DescriptorView<'a> {
252    fn from(d: &DescriptorView<'a>) -> Self {
253        *d
254    }
255}
256impl PartialEq<Descriptor> for DescriptorView<'_> {
257    fn eq(&self, d: &Descriptor) -> bool {
258        *self == d.view()
259    }
260}
261impl PartialEq<DescriptorView<'_>> for Descriptor {
262    fn eq(&self, d: &DescriptorView<'_>) -> bool {
263        self.view() == *d
264    }
265}
266
267impl<'a> From<&'a Box<Descriptor>> for DescriptorView<'a> {
268    fn from(d: &'a Box<Descriptor>) -> Self {
269        d.as_ref().view()
270    }
271}