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
204pub const MAX_IMAGE_CANDIDATES: usize = 16;
205pub const MAX_IMAGE_SIZE_HINTS: usize = 8;
206
207#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct ImageCandidate {
209    pub source: String,
210    pub width: u16,
211}
212
213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
214pub enum ImageSlotSize {
215    Pixels(u16),
216    ViewportWidth(u8),
217}
218
219#[derive(Clone, Copy, Debug, PartialEq, Eq)]
220pub struct ImageSizeHint {
221    /// A CSS viewport-width upper bound. `None` is the required final fallback.
222    pub max_viewport_width: Option<u16>,
223    pub slot: ImageSlotSize,
224}
225
226#[derive(Clone, Debug, Default, PartialEq, Eq)]
227pub struct ResponsiveImage {
228    pub candidates: Vec<ImageCandidate>,
229    pub sizes: Vec<ImageSizeHint>,
230}
231
232impl ResponsiveImage {
233    pub fn validate(&self) -> Result<(), Error> {
234        if self.candidates.len() > MAX_IMAGE_CANDIDATES {
235            return Err(Error::InvalidProps("too many responsive image candidates"));
236        }
237        let mut previous_width = 0;
238        for candidate in &self.candidates {
239            if candidate.source.is_empty()
240                || candidate.source.len() > 4096
241                || candidate.source.chars().any(|character| {
242                    character.is_control() || character.is_whitespace() || character == ','
243                })
244                || candidate.width == 0
245                || candidate.width > 16_384
246                || candidate.width <= previous_width
247            {
248                return Err(Error::InvalidProps(
249                    "responsive image candidates require ordered unique 1..=16384 widths and bounded sources",
250                ));
251            }
252            previous_width = candidate.width;
253        }
254        if self.sizes.len() > MAX_IMAGE_SIZE_HINTS
255            || self.candidates.is_empty() != self.sizes.is_empty()
256        {
257            return Err(Error::InvalidProps(
258                "responsive image candidates and sizes must be configured together",
259            ));
260        }
261        let mut previous_breakpoint = 0;
262        for (index, hint) in self.sizes.iter().enumerate() {
263            match hint.max_viewport_width {
264                Some(width)
265                    if width > 0
266                        && width <= 16_384
267                        && width > previous_breakpoint
268                        && index + 1 < self.sizes.len() =>
269                {
270                    previous_breakpoint = width;
271                }
272                None if index + 1 == self.sizes.len() => {}
273                _ => {
274                    return Err(Error::InvalidProps(
275                        "responsive image sizes require ordered breakpoints and one final fallback",
276                    ));
277                }
278            }
279            if !matches!(
280                hint.slot,
281                ImageSlotSize::Pixels(1..=16_384) | ImageSlotSize::ViewportWidth(1..=100)
282            ) {
283                return Err(Error::InvalidProps(
284                    "responsive image slot size is outside its finite range",
285                ));
286            }
287        }
288        Ok(())
289    }
290}
291
292#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
293pub enum ImageLoading {
294    #[default]
295    Auto,
296    Eager,
297    Lazy,
298}
299
300#[derive(Clone, Debug, Default, PartialEq, Eq)]
301pub struct ImageProps {
302    pub source: String,
303    /// Monotonic program request identity, independent of URL equality.
304    pub revision: u64,
305    /// None is explicitly decorative; Some("") is an empty description.
306    pub alternative: Option<String>,
307    pub responsive: ResponsiveImage,
308    pub loading: ImageLoading,
309}
310
311#[derive(Clone, Copy, Debug, PartialEq, Eq)]
312pub enum ImageStatus {
313    Loaded,
314    Failed,
315}
316
317#[derive(Clone, Debug, Default, PartialEq, Eq)]
318pub struct LinkProps {
319    /// Relative URL or an http, https, mailto or tel URL. Custom schemes are
320    /// rejected; applications handle custom navigation through explicit host
321    /// callbacks rather than putting executable or platform URLs in href.
322    pub target: String,
323    pub label: String,
324}
325
326impl LinkProps {
327    pub fn validate(&self) -> Result<(), Error> {
328        validate_link_target(&self.target)
329    }
330}
331
332/// Validate before URL values reach any host. Percent-encoded colons remain
333/// relative path data; a scheme is possible only before the first /, ? or #.
334fn validate_link_target(target: &str) -> Result<(), Error> {
335    let invalid =
336        || Error::InvalidProps("link target requires a relative or http/https/mailto/tel URL");
337    if target
338        .chars()
339        .any(|ch| ch.is_control() || ch.is_whitespace())
340    {
341        return Err(invalid());
342    }
343    let prefix = target.split(['/', '?', '#']).next().unwrap_or_default();
344    if let Some((scheme, _)) = prefix.split_once(':')
345        && !["http", "https", "mailto", "tel"]
346            .iter()
347            .any(|allowed| scheme.eq_ignore_ascii_case(allowed))
348    {
349        return Err(invalid());
350    }
351    Ok(())
352}
353
354#[derive(Clone, Debug, Default, PartialEq)]
355pub enum Props {
356    #[default]
357    View,
358    Group,
359    Text(TextProps),
360    Button(ButtonProps),
361    Input(InputProps),
362    Select(crate::SelectProps),
363    File(crate::FileProps),
364    RichEditor(crate::RichEditorProps),
365    Check(CheckProps),
366    Image(ImageProps),
367    Graphic(crate::GraphicProps),
368    Link(LinkProps),
369}
370
371impl Props {
372    pub fn interactive(&self) -> bool {
373        matches!(
374            self,
375            Self::Button(_)
376                | Self::Input(_)
377                | Self::Select(_)
378                | Self::File(_)
379                | Self::RichEditor(_)
380                | Self::Check(_)
381                | Self::Link(_)
382        )
383    }
384
385    pub fn enabled(&self) -> bool {
386        match self {
387            Self::Button(p) => p.enabled,
388            Self::Input(p) => p.enabled,
389            Self::Select(p) => p.enabled,
390            Self::File(p) => p.enabled,
391            Self::RichEditor(p) => p.enabled,
392            Self::Check(p) => p.enabled,
393            _ => true,
394        }
395    }
396
397    pub fn accepts_children(&self) -> bool {
398        matches!(
399            self,
400            Self::View | Self::Group | Self::Button(_) | Self::Link(_)
401        )
402    }
403}
404
405#[derive(Clone, Debug, Default, PartialEq)]
406pub struct Descriptor {
407    pub props: Props,
408    pub classes: Vec<String>,
409    pub style: Style,
410    pub role: Option<Role>,
411    pub name: Option<String>,
412    pub focus: FocusMode,
413    pub item: Option<ItemPosition>,
414    pub options: Options,
415    pub semantics: Option<Box<crate::Semantics>>,
416}
417
418/// Host-native default, programmatic focus only, or a normal tab stop.
419#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
420pub enum FocusMode {
421    #[default]
422    Auto,
423    Programmatic,
424    TabStop,
425}
426
427/// Position in the logical collection, not in the mounted render window.
428#[derive(Clone, Copy, Debug, PartialEq, Eq)]
429pub struct ItemPosition {
430    pub index: usize,
431    /// None represents an unknown total. A known total must exceed index.
432    pub count: Option<usize>,
433}
434
435impl Descriptor {
436    #[inline]
437    pub fn view(&self) -> DescriptorView<'_> {
438        self.into()
439    }
440    pub fn semantic_id(&self) -> Option<&crate::SemanticId> {
441        self.view().semantic_id()
442    }
443    pub fn hidden(&self) -> bool {
444        self.view().hidden()
445    }
446    pub fn activation_enabled(&self) -> bool {
447        self.view().activation_enabled()
448    }
449    pub fn readonly(&self) -> bool {
450        self.view().readonly()
451    }
452    pub fn field_part(&self) -> Option<crate::FieldPart> {
453        self.view().field_part()
454    }
455    pub fn document_part(&self) -> Option<crate::DocumentPart> {
456        self.view().document_part()
457    }
458    pub fn effective_role(&self) -> Option<Role> {
459        self.view().effective_role()
460    }
461    pub fn validate(&self) -> Result<(), Error> {
462        self.view().validate()
463    }
464
465    pub fn new(props: Props) -> Self {
466        Self {
467            props,
468            ..Self::default()
469        }
470    }
471
472    /// Canonicalize stored editable text without changing a program's explicit
473    /// revision. Single-line declarations retain their line-break diagnostic.
474    pub fn normalize_input(&mut self) -> Result<(), Error> {
475        if let Props::Input(input) = &mut self.props {
476            if !input.multiline && input.value.contains(['\r', '\n']) {
477                return Err(Error::InvalidProps(
478                    "single-line input cannot contain line breaks",
479                ));
480            }
481            if let std::borrow::Cow::Owned(value) = normalize_text(&input.value, input.multiline) {
482                input.value = value;
483            }
484        }
485        if let Props::Image(image) = &mut self.props
486            && let std::borrow::Cow::Owned(source) = normalize_text(&image.source, true)
487        {
488            image.source = source;
489        }
490        Ok(())
491    }
492
493    fn validate_input_revision(&self, next: &Self) -> Result<(), Error> {
494        if let (Some(old), Some(next)) = (
495            self.semantics.as_ref().and_then(|s| s.clipboard.as_ref()),
496            next.semantics.as_ref().and_then(|s| s.clipboard.as_ref()),
497        ) {
498            next.validate_update(old)?;
499        }
500        crate::swipe::revision(
501            self.semantics.as_ref().and_then(|s| s.swipe_capture),
502            next.semantics.as_ref().and_then(|s| s.swipe_capture),
503        )?;
504        crate::presence::revision(
505            self.semantics.as_ref().and_then(|s| s.presence.as_deref()),
506            next.semantics.as_ref().and_then(|s| s.presence.as_deref()),
507        )?;
508        crate::collapse::revision(
509            self.semantics.as_ref().and_then(|s| s.collapse.as_ref()),
510            next.semantics.as_ref().and_then(|s| s.collapse.as_ref()),
511        )?;
512        if let (Props::RichEditor(old), Props::RichEditor(next)) = (&self.props, &next.props) {
513            next.validate_update(old)?;
514        }
515        if let (Props::File(old), Props::File(new)) = (&self.props, &next.props) {
516            new.validate_update(old)?;
517        }
518        if let (Props::Graphic(old), Props::Graphic(new)) = (&self.props, &next.props) {
519            new.transition_from(old)?;
520        }
521        crate::sheet::revision(
522            self.semantics.as_ref().and_then(|s| s.layer.as_ref()),
523            next.semantics.as_ref().and_then(|s| s.layer.as_ref()),
524        )?;
525        if let (Props::Input(old), Props::Input(next)) = (&self.props, &next.props)
526            && (next.revision < old.revision
527                || next.revision == old.revision
528                    && normalize_text(&old.value, old.multiline).as_ref() != next.value)
529        {
530            return Err(Error::InputRevision {
531                current: old.revision,
532                incoming: next.revision,
533            });
534        }
535        if let (Props::Select(old), Props::Select(next)) = (&self.props, &next.props)
536            && (next.selection.revision < old.selection.revision
537                || next.selection.revision == old.selection.revision
538                    && next.selection.keys != old.selection.keys)
539        {
540            return Err(Error::SelectRevision {
541                current: old.selection.revision,
542                incoming: next.selection.revision,
543            });
544        }
545        if let (Props::Image(old), Props::Image(next)) = (&self.props, &next.props)
546            && (next.revision < old.revision
547                || next.revision == old.revision
548                    && normalize_text(&old.source, true).as_ref() != next.source)
549        {
550            return Err(Error::ImageRevision {
551                current: old.revision,
552                incoming: next.revision,
553            });
554        }
555        Ok(())
556    }
557
558    /// Validate before replacing the live descriptor. An invalid patch does not
559    /// partially corrupt a node even though a mutation batch is not atomic.
560    pub fn patch(&mut self, patch: Patch) -> Result<(), Error> {
561        *self = self.patched(patch)?;
562        Ok(())
563    }
564
565    pub fn patched(&self, patch: Patch) -> Result<Self, Error> {
566        let mut next = self.clone();
567        next.apply_patch(patch)?;
568        next.normalize_input()?;
569        self.validate_input_revision(&next)?;
570        next.validate()?;
571        Ok(next)
572    }
573
574    /// Builder configuration is validated as a whole, so intermediate settings
575    /// (e.g. purpose then multiline) do not reject an otherwise valid final node.
576    pub fn patches(&mut self, patches: impl IntoIterator<Item = Patch>) -> Result<(), Error> {
577        let mut next = self.clone();
578        for patch in patches {
579            next.apply_patch(patch)?;
580        }
581        next.normalize_input()?;
582        self.validate_input_revision(&next)?;
583        next.validate()?;
584        *self = next;
585        Ok(())
586    }
587
588    fn apply_patch(&mut self, patch: Patch) -> Result<(), Error> {
589        match (patch, &mut self.props) {
590            (Patch::Text(change), Props::Text(p)) => change.apply(&mut p.content),
591            (Patch::TextKind(change), Props::Text(p)) => change.apply(&mut p.kind),
592            (Patch::Selectable(change), Props::Text(p)) => change.apply_or(&mut p.selectable, true),
593            (Patch::Label(change), Props::File(p)) => {
594                change.apply_or(&mut p.label, "Choose file".into())
595            }
596            (Patch::Enabled(change), Props::RichEditor(p)) => change.apply_or(&mut p.enabled, true),
597            (Patch::RichDocument { document, revision }, Props::RichEditor(p)) => {
598                if !matches!(document, Change::Keep) {
599                    document.apply_or(
600                        &mut p.document,
601                        std::rc::Rc::new(crate::RichDocument::default()),
602                    );
603                    p.revision = revision;
604                }
605            }
606            (Patch::Enabled(change), Props::File(p)) => change.apply_or(&mut p.enabled, true),
607            (
608                Patch::File {
609                    configuration,
610                    revision,
611                },
612                Props::File(p),
613            ) => {
614                if !matches!(configuration, Change::Keep) {
615                    match configuration {
616                        Change::Set(value) => p.configuration = *value,
617                        Change::Clear => p.configuration = crate::FileConfig::default(),
618                        Change::Keep => {}
619                    }
620                    p.revision = revision;
621                }
622            }
623            (Patch::Label(change), Props::Button(p)) => change.apply(&mut p.label),
624            (Patch::Label(change), Props::Check(p)) => change.apply(&mut p.label),
625            (Patch::Label(change), Props::Link(p)) => change.apply(&mut p.label),
626            (Patch::Enabled(change), Props::Button(p)) => change.apply_or(&mut p.enabled, true),
627            (Patch::Enabled(change), Props::Check(p)) => change.apply_or(&mut p.enabled, true),
628            (Patch::Enabled(change), Props::Input(p)) => change.apply_or(&mut p.enabled, true),
629            (Patch::Value { value, revision }, Props::Input(p)) => {
630                if !matches!(value, Change::Keep) {
631                    value.apply(&mut p.value);
632                    p.revision = revision;
633                }
634            }
635            (Patch::Enabled(change), Props::Select(p)) => change.apply_or(&mut p.enabled, true),
636            (Patch::SelectSelection { keys, revision }, Props::Select(p)) => {
637                if !matches!(keys, Change::Keep) {
638                    keys.apply(&mut p.selection.keys);
639                    p.selection.revision = revision;
640                }
641            }
642            (Patch::Purpose(change), Props::Input(p)) => change.apply(&mut p.purpose),
643            (Patch::Multiline(change), Props::Input(p)) => change.apply(&mut p.multiline),
644            (Patch::Checked(change), Props::Check(p)) => change.apply(&mut p.checked),
645            (Patch::CheckMode(change), Props::Check(p)) => change.apply(&mut p.mode),
646            (Patch::Source { source, revision }, Props::Image(p)) => {
647                if !matches!(source, Change::Keep) {
648                    source.apply(&mut p.source);
649                    p.revision = revision;
650                }
651            }
652            (Patch::Alternative(change), Props::Image(p)) => change.apply(&mut p.alternative),
653            (Patch::Graphic(change), Props::Graphic(p)) => match change {
654                Change::Keep => {}
655                Change::Clear => *p = crate::GraphicProps::default(),
656                Change::Set(value) => *p = *value,
657            },
658            (Patch::Target(change), Props::Link(p)) => change.apply(&mut p.target),
659            (Patch::Classes(change), _) => change.apply(&mut self.classes),
660            (Patch::Style(change), _) => match change {
661                Change::Keep => {}
662                Change::Clear => self.style = Style::default(),
663                Change::Set(style) => self.style = *style,
664            },
665            (Patch::Role(change), _) => change.apply(&mut self.role),
666            (Patch::Name(change), _) => change.apply(&mut self.name),
667            (Patch::Focus(change), _) => change.apply(&mut self.focus),
668            (Patch::Item(change), _) => change.apply(&mut self.item),
669            (Patch::Semantics(change), _) => change.apply(&mut self.semantics),
670            _ => {
671                return Err(Error::InvalidProps(
672                    "property does not belong to this widget",
673                ));
674            }
675        }
676        Ok(())
677    }
678}
679
680#[derive(Clone, Debug, PartialEq)]
681pub enum Patch {
682    Text(Change<String>),
683    TextKind(Change<TextKind>),
684    Selectable(Change<bool>),
685    Label(Change<String>),
686    Enabled(Change<bool>),
687    Value {
688        value: Change<String>,
689        revision: u64,
690    },
691    RichDocument {
692        document: Change<std::rc::Rc<crate::RichDocument>>,
693        revision: u64,
694    },
695    SelectSelection {
696        keys: Change<Vec<crate::SemanticId>>,
697        revision: u64,
698    },
699    Purpose(Change<Purpose>),
700    Multiline(Change<bool>),
701    /// An explicit Set/Clear also synchronizes the host control property when
702    /// the semantic value is equal (for example a rejected native toggle).
703    Checked(Change<bool>),
704    CheckMode(Change<CheckMode>),
705    Source {
706        source: Change<String>,
707        revision: u64,
708    },
709    Alternative(Change<Option<String>>),
710    Graphic(Change<Box<crate::GraphicProps>>),
711    File {
712        configuration: Change<Box<crate::FileConfig>>,
713        revision: u64,
714    },
715    Target(Change<String>),
716    Classes(Change<Vec<String>>),
717    Style(Change<Box<Style>>),
718    Role(Change<Option<Role>>),
719    Name(Change<Option<String>>),
720    Focus(Change<FocusMode>),
721    Item(Change<Option<ItemPosition>>),
722    Semantics(Change<Option<Box<crate::Semantics>>>),
723}