Skip to main content

glory_render/
props.rs

1use std::any::{Any, TypeId};
2use std::collections::HashMap;
3use std::rc::Rc;
4
5use glory_style::Style;
6
7use crate::{Change, Error, normalize_text};
8mod live;
9pub use live::LiveDescriptor;
10mod view;
11pub use view::DescriptorView;
12
13/// Process-local, typed mapping metadata. It is deliberately not a wire format.
14#[derive(Clone, Default)]
15pub struct Options(HashMap<TypeId, Rc<dyn Any>>);
16
17impl Options {
18    pub fn insert<T: 'static>(&mut self, value: T) {
19        self.0.insert(TypeId::of::<T>(), Rc::new(value));
20    }
21    pub fn get<T: 'static>(&self) -> Option<&T> {
22        self.0.get(&TypeId::of::<T>())?.downcast_ref()
23    }
24}
25
26impl std::fmt::Debug for Options {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        f.debug_struct("Options")
29            .field("types", &self.0.len())
30            .finish()
31    }
32}
33
34impl PartialEq for Options {
35    fn eq(&self, other: &Self) -> bool {
36        self.0.len() == other.0.len()
37            && self.0.iter().all(|(key, value)| {
38                other
39                    .0
40                    .get(key)
41                    .is_some_and(|other| Rc::ptr_eq(value, other))
42            })
43    }
44}
45
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
47pub enum TextKind {
48    #[default]
49    Inline,
50    Paragraph,
51    Heading(u8),
52    Code,
53    Kbd,
54    Mark,
55}
56impl TextKind {
57    pub const fn is_inline(self) -> bool {
58        matches!(self, Self::Inline | Self::Code | Self::Kbd | Self::Mark)
59    }
60}
61
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
63pub enum Purpose {
64    #[default]
65    Text,
66    Password,
67    Email,
68    Search,
69    Url,
70    Tel,
71    Number,
72}
73
74/// Structural roles belong to View. Other widgets keep their intrinsic
75/// control/text/image semantics rather than impersonating unrelated widgets.
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub enum Role {
78    /// Interactive numeric range control; finite configuration is required.
79    Slider,
80    /// Intrinsic editable numeric input; use spinbutton metadata on Input.
81    SpinButton,
82    /// Read-only numeric or indeterminate progress, never a range input.
83    ProgressBar,
84    /// Passive document boundary; resizing/focus belongs to a future splitter.
85    Separator,
86    Group,
87    Main,
88    Banner,
89    ContentInfo,
90    Section,
91    Navigation,
92    List,
93    ListItem,
94    Status,
95    Alert,
96    /// Read-only tabular data; rows contain column headers or cells.
97    Table,
98    Grid,
99    GridCell,
100    Tree,
101    TreeItem,
102    Row,
103    ColumnHeader,
104    Cell,
105    /// A named dialog. Modality and focus management belong to the host.
106    Dialog,
107    /// A modal decision with an explicit safe initial action.
108    AlertDialog,
109    /// Passive supplemental description; its descendants cannot be interactive.
110    Tooltip,
111    TabList,
112    TabPanel,
113    RadioGroup,
114    Toolbar,
115    Menu,
116    Menubar,
117    Listbox,
118    Heading(u8),
119}
120
121#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct TextProps {
123    pub content: String,
124    pub kind: TextKind,
125    pub selectable: bool,
126}
127
128impl Default for TextProps {
129    fn default() -> Self {
130        Self {
131            content: String::new(),
132            kind: TextKind::Inline,
133            selectable: true,
134        }
135    }
136}
137
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct ButtonProps {
140    pub label: String,
141    pub enabled: bool,
142}
143
144impl Default for ButtonProps {
145    fn default() -> Self {
146        Self {
147            label: String::new(),
148            enabled: true,
149        }
150    }
151}
152
153#[derive(Clone, Debug, PartialEq, Eq)]
154pub struct InputProps {
155    pub value: String,
156    pub revision: u64,
157    pub purpose: Purpose,
158    pub multiline: bool,
159    pub enabled: bool,
160}
161
162impl Default for InputProps {
163    fn default() -> Self {
164        Self {
165            value: String::new(),
166            revision: 0,
167            purpose: Purpose::Text,
168            multiline: false,
169            enabled: true,
170        }
171    }
172}
173
174/// Finite native check semantics. Mixed preserves indeterminacy independently
175/// of the stored checked bit; Switch and Radio never expose a mixed state.
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
177pub enum CheckMode {
178    #[default]
179    Checkbox,
180    Mixed,
181    Switch,
182    Radio,
183}
184
185#[derive(Clone, Debug, PartialEq, Eq)]
186pub struct CheckProps {
187    pub mode: CheckMode,
188    pub checked: bool,
189    pub label: String,
190    pub enabled: bool,
191}
192
193impl Default for CheckProps {
194    fn default() -> Self {
195        Self {
196            mode: CheckMode::Checkbox,
197            checked: false,
198            label: String::new(),
199            enabled: true,
200        }
201    }
202}
203
204#[derive(Clone, Debug, Default, PartialEq, Eq)]
205pub struct ImageProps {
206    pub source: String,
207    /// Monotonic program request identity, independent of URL equality.
208    pub revision: u64,
209    /// None is explicitly decorative; Some("") is an empty description.
210    pub alternative: Option<String>,
211}
212
213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
214pub enum ImageStatus {
215    Loaded,
216    Failed,
217}
218
219#[derive(Clone, Debug, Default, PartialEq, Eq)]
220pub struct LinkProps {
221    pub target: String,
222    pub label: String,
223}
224
225#[derive(Clone, Debug, Default, PartialEq)]
226pub enum Props {
227    #[default]
228    View,
229    Group,
230    Text(TextProps),
231    Button(ButtonProps),
232    Input(InputProps),
233    Select(crate::SelectProps),
234    File(crate::FileProps),
235    RichEditor(crate::RichEditorProps),
236    Check(CheckProps),
237    Image(ImageProps),
238    Graphic(crate::GraphicProps),
239    Link(LinkProps),
240}
241
242impl Props {
243    pub fn interactive(&self) -> bool {
244        matches!(
245            self,
246            Self::Button(_)
247                | Self::Input(_)
248                | Self::Select(_)
249                | Self::File(_)
250                | Self::RichEditor(_)
251                | Self::Check(_)
252                | Self::Link(_)
253        )
254    }
255
256    pub fn enabled(&self) -> bool {
257        match self {
258            Self::Button(p) => p.enabled,
259            Self::Input(p) => p.enabled,
260            Self::Select(p) => p.enabled,
261            Self::File(p) => p.enabled,
262            Self::RichEditor(p) => p.enabled,
263            Self::Check(p) => p.enabled,
264            _ => true,
265        }
266    }
267
268    pub fn accepts_children(&self) -> bool {
269        matches!(
270            self,
271            Self::View | Self::Group | Self::Button(_) | Self::Link(_)
272        )
273    }
274}
275
276#[derive(Clone, Debug, Default, PartialEq)]
277pub struct Descriptor {
278    pub props: Props,
279    pub classes: Vec<String>,
280    pub style: Style,
281    pub role: Option<Role>,
282    pub name: Option<String>,
283    pub focus: FocusMode,
284    pub item: Option<ItemPosition>,
285    pub options: Options,
286    pub semantics: Option<Box<crate::Semantics>>,
287}
288
289/// Host-native default, programmatic focus only, or a normal tab stop.
290#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
291pub enum FocusMode {
292    #[default]
293    Auto,
294    Programmatic,
295    TabStop,
296}
297
298/// Position in the logical collection, not in the mounted render window.
299#[derive(Clone, Copy, Debug, PartialEq, Eq)]
300pub struct ItemPosition {
301    pub index: usize,
302    /// None represents an unknown total. A known total must exceed index.
303    pub count: Option<usize>,
304}
305
306impl Descriptor {
307    #[inline]
308    pub fn view(&self) -> DescriptorView<'_> {
309        self.into()
310    }
311    pub fn semantic_id(&self) -> Option<&crate::SemanticId> {
312        self.view().semantic_id()
313    }
314    pub fn hidden(&self) -> bool {
315        self.view().hidden()
316    }
317    pub fn activation_enabled(&self) -> bool {
318        self.view().activation_enabled()
319    }
320    pub fn readonly(&self) -> bool {
321        self.view().readonly()
322    }
323    pub fn field_part(&self) -> Option<crate::FieldPart> {
324        self.view().field_part()
325    }
326    pub fn document_part(&self) -> Option<crate::DocumentPart> {
327        self.view().document_part()
328    }
329    pub fn effective_role(&self) -> Option<Role> {
330        self.view().effective_role()
331    }
332    pub fn validate(&self) -> Result<(), Error> {
333        self.view().validate()
334    }
335
336    pub fn new(props: Props) -> Self {
337        Self {
338            props,
339            ..Self::default()
340        }
341    }
342
343    /// Canonicalize stored editable text without changing a program's explicit
344    /// revision. Single-line declarations retain their line-break diagnostic.
345    pub fn normalize_input(&mut self) -> Result<(), Error> {
346        if let Props::Input(input) = &mut self.props {
347            if !input.multiline && input.value.contains(['\r', '\n']) {
348                return Err(Error::InvalidProps(
349                    "single-line input cannot contain line breaks",
350                ));
351            }
352            if let std::borrow::Cow::Owned(value) = normalize_text(&input.value, input.multiline) {
353                input.value = value;
354            }
355        }
356        if let Props::Image(image) = &mut self.props
357            && let std::borrow::Cow::Owned(source) = normalize_text(&image.source, true)
358        {
359            image.source = source;
360        }
361        Ok(())
362    }
363
364    fn validate_input_revision(&self, next: &Self) -> Result<(), Error> {
365        if let (Some(old), Some(next)) = (
366            self.semantics.as_ref().and_then(|s| s.clipboard.as_ref()),
367            next.semantics.as_ref().and_then(|s| s.clipboard.as_ref()),
368        ) {
369            next.validate_update(old)?;
370        }
371        crate::swipe::revision(
372            self.semantics.as_ref().and_then(|s| s.swipe_capture),
373            next.semantics.as_ref().and_then(|s| s.swipe_capture),
374        )?;
375        crate::collapse::revision(
376            self.semantics.as_ref().and_then(|s| s.collapse.as_ref()),
377            next.semantics.as_ref().and_then(|s| s.collapse.as_ref()),
378        )?;
379        if let (Props::RichEditor(old), Props::RichEditor(next)) = (&self.props, &next.props) {
380            next.validate_update(old)?;
381        }
382        if let (Props::File(old), Props::File(new)) = (&self.props, &next.props) {
383            new.validate_update(old)?;
384        }
385        if let (Props::Graphic(old), Props::Graphic(new)) = (&self.props, &next.props) {
386            new.transition_from(old)?;
387        }
388        crate::sheet::revision(
389            self.semantics.as_ref().and_then(|s| s.layer.as_ref()),
390            next.semantics.as_ref().and_then(|s| s.layer.as_ref()),
391        )?;
392        if let (Props::Input(old), Props::Input(next)) = (&self.props, &next.props)
393            && (next.revision < old.revision
394                || next.revision == old.revision
395                    && normalize_text(&old.value, old.multiline).as_ref() != next.value)
396        {
397            return Err(Error::InputRevision {
398                current: old.revision,
399                incoming: next.revision,
400            });
401        }
402        if let (Props::Select(old), Props::Select(next)) = (&self.props, &next.props)
403            && (next.selection.revision < old.selection.revision
404                || next.selection.revision == old.selection.revision
405                    && next.selection.keys != old.selection.keys)
406        {
407            return Err(Error::SelectRevision {
408                current: old.selection.revision,
409                incoming: next.selection.revision,
410            });
411        }
412        if let (Props::Image(old), Props::Image(next)) = (&self.props, &next.props)
413            && (next.revision < old.revision
414                || next.revision == old.revision
415                    && normalize_text(&old.source, true).as_ref() != next.source)
416        {
417            return Err(Error::ImageRevision {
418                current: old.revision,
419                incoming: next.revision,
420            });
421        }
422        Ok(())
423    }
424
425    /// Validate before replacing the live descriptor. An invalid patch does not
426    /// partially corrupt a node even though a mutation batch is not atomic.
427    pub fn patch(&mut self, patch: Patch) -> Result<(), Error> {
428        *self = self.patched(patch)?;
429        Ok(())
430    }
431
432    pub fn patched(&self, patch: Patch) -> Result<Self, Error> {
433        let mut next = self.clone();
434        next.apply_patch(patch)?;
435        next.normalize_input()?;
436        self.validate_input_revision(&next)?;
437        next.validate()?;
438        Ok(next)
439    }
440
441    /// Builder configuration is validated as a whole, so intermediate settings
442    /// (e.g. purpose then multiline) do not reject an otherwise valid final node.
443    pub fn patches(&mut self, patches: impl IntoIterator<Item = Patch>) -> Result<(), Error> {
444        let mut next = self.clone();
445        for patch in patches {
446            next.apply_patch(patch)?;
447        }
448        next.normalize_input()?;
449        self.validate_input_revision(&next)?;
450        next.validate()?;
451        *self = next;
452        Ok(())
453    }
454
455    fn apply_patch(&mut self, patch: Patch) -> Result<(), Error> {
456        match (patch, &mut self.props) {
457            (Patch::Text(change), Props::Text(p)) => change.apply(&mut p.content),
458            (Patch::TextKind(change), Props::Text(p)) => change.apply(&mut p.kind),
459            (Patch::Selectable(change), Props::Text(p)) => change.apply_or(&mut p.selectable, true),
460            (Patch::Label(change), Props::File(p)) => {
461                change.apply_or(&mut p.label, "Choose file".into())
462            }
463            (Patch::Enabled(change), Props::RichEditor(p)) => change.apply_or(&mut p.enabled, true),
464            (Patch::RichDocument { document, revision }, Props::RichEditor(p)) => {
465                if !matches!(document, Change::Keep) {
466                    document.apply_or(
467                        &mut p.document,
468                        std::rc::Rc::new(crate::RichDocument::default()),
469                    );
470                    p.revision = revision;
471                }
472            }
473            (Patch::Enabled(change), Props::File(p)) => change.apply_or(&mut p.enabled, true),
474            (
475                Patch::File {
476                    configuration,
477                    revision,
478                },
479                Props::File(p),
480            ) => {
481                if !matches!(configuration, Change::Keep) {
482                    match configuration {
483                        Change::Set(value) => p.configuration = *value,
484                        Change::Clear => p.configuration = crate::FileConfig::default(),
485                        Change::Keep => {}
486                    }
487                    p.revision = revision;
488                }
489            }
490            (Patch::Label(change), Props::Button(p)) => change.apply(&mut p.label),
491            (Patch::Label(change), Props::Check(p)) => change.apply(&mut p.label),
492            (Patch::Label(change), Props::Link(p)) => change.apply(&mut p.label),
493            (Patch::Enabled(change), Props::Button(p)) => change.apply_or(&mut p.enabled, true),
494            (Patch::Enabled(change), Props::Check(p)) => change.apply_or(&mut p.enabled, true),
495            (Patch::Enabled(change), Props::Input(p)) => change.apply_or(&mut p.enabled, true),
496            (Patch::Value { value, revision }, Props::Input(p)) => {
497                if !matches!(value, Change::Keep) {
498                    value.apply(&mut p.value);
499                    p.revision = revision;
500                }
501            }
502            (Patch::Enabled(change), Props::Select(p)) => change.apply_or(&mut p.enabled, true),
503            (Patch::SelectSelection { keys, revision }, Props::Select(p)) => {
504                if !matches!(keys, Change::Keep) {
505                    keys.apply(&mut p.selection.keys);
506                    p.selection.revision = revision;
507                }
508            }
509            (Patch::Purpose(change), Props::Input(p)) => change.apply(&mut p.purpose),
510            (Patch::Multiline(change), Props::Input(p)) => change.apply(&mut p.multiline),
511            (Patch::Checked(change), Props::Check(p)) => change.apply(&mut p.checked),
512            (Patch::CheckMode(change), Props::Check(p)) => change.apply(&mut p.mode),
513            (Patch::Source { source, revision }, Props::Image(p)) => {
514                if !matches!(source, Change::Keep) {
515                    source.apply(&mut p.source);
516                    p.revision = revision;
517                }
518            }
519            (Patch::Alternative(change), Props::Image(p)) => change.apply(&mut p.alternative),
520            (Patch::Graphic(change), Props::Graphic(p)) => match change {
521                Change::Keep => {}
522                Change::Clear => *p = crate::GraphicProps::default(),
523                Change::Set(value) => *p = *value,
524            },
525            (Patch::Target(change), Props::Link(p)) => change.apply(&mut p.target),
526            (Patch::Classes(change), _) => change.apply(&mut self.classes),
527            (Patch::Style(change), _) => match change {
528                Change::Keep => {}
529                Change::Clear => self.style = Style::default(),
530                Change::Set(style) => self.style = *style,
531            },
532            (Patch::Role(change), _) => change.apply(&mut self.role),
533            (Patch::Name(change), _) => change.apply(&mut self.name),
534            (Patch::Focus(change), _) => change.apply(&mut self.focus),
535            (Patch::Item(change), _) => change.apply(&mut self.item),
536            (Patch::Semantics(change), _) => change.apply(&mut self.semantics),
537            _ => {
538                return Err(Error::InvalidProps(
539                    "property does not belong to this widget",
540                ));
541            }
542        }
543        Ok(())
544    }
545}
546
547#[derive(Clone, Debug, PartialEq)]
548pub enum Patch {
549    Text(Change<String>),
550    TextKind(Change<TextKind>),
551    Selectable(Change<bool>),
552    Label(Change<String>),
553    Enabled(Change<bool>),
554    Value {
555        value: Change<String>,
556        revision: u64,
557    },
558    RichDocument {
559        document: Change<std::rc::Rc<crate::RichDocument>>,
560        revision: u64,
561    },
562    SelectSelection {
563        keys: Change<Vec<crate::SemanticId>>,
564        revision: u64,
565    },
566    Purpose(Change<Purpose>),
567    Multiline(Change<bool>),
568    /// An explicit Set/Clear also synchronizes the host control property when
569    /// the semantic value is equal (for example a rejected native toggle).
570    Checked(Change<bool>),
571    CheckMode(Change<CheckMode>),
572    Source {
573        source: Change<String>,
574        revision: u64,
575    },
576    Alternative(Change<Option<String>>),
577    Graphic(Change<Box<crate::GraphicProps>>),
578    File {
579        configuration: Change<Box<crate::FileConfig>>,
580        revision: u64,
581    },
582    Target(Change<String>),
583    Classes(Change<Vec<String>>),
584    Style(Change<Box<Style>>),
585    Role(Change<Option<Role>>),
586    Name(Change<Option<String>>),
587    Focus(Change<FocusMode>),
588    Item(Change<Option<ItemPosition>>),
589    Semantics(Change<Option<Box<crate::Semantics>>>),
590}