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