Skip to main content

glory_render/
semantics.rs

1//! Finite composite-widget metadata. Stable names are explicit document keys,
2//! independent of NodeId lifetimes and snapshot rekeying.
3
4use crate::{Error, Navigation, Props, Role};
5
6/// Structural form content, fixed for a node's lifetime on HTML adapters.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum FieldPart {
9    Form,
10    Label,
11    Fieldset,
12    Legend,
13}
14
15/// The host captures requests; application policy owns validation and transport.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum FormAction {
18    Submit,
19    Reset,
20}
21
22/// Submission metadata is separate from the accessible name. Text input values
23/// come from InputProps; Check/Button may supply an explicit successful value.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct FormControl {
26    pub name: String,
27    pub value: Option<String>,
28}
29
30/// Native links may use their current context or request a separate one.
31/// Opening a system browser remains an outer native host service.
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub enum LinkOpen {
34    #[default]
35    Current,
36    NewContext,
37}
38
39/// The current location in a related set, independent of selection or visits.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum Current {
42    Page,
43    Step,
44    Location,
45    Date,
46}
47/// The popup role is one typed value, never an independent boolean flag.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum PopupKind {
50    Dialog,
51    Menu,
52    Listbox,
53    Tree,
54}
55impl PopupKind {
56    pub fn as_str(self) -> &'static str {
57        match self {
58            Self::Dialog => "dialog",
59            Self::Menu => "menu",
60            Self::Listbox => "listbox",
61            Self::Tree => "tree",
62        }
63    }
64}
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub enum MenuItemKind {
67    Action,
68    Checkbox,
69    Radio,
70}
71/// Finite intrinsic-control refinement. Owner is a named Menu View, also used
72/// to keep menu check controls outside any enclosing successful form controls.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub struct MenuItemSemantics {
75    pub kind: MenuItemKind,
76    pub owner: SemanticId,
77}
78
79/// Host-managed top layer. Presence declares a focus scope; `hidden` controls
80/// whether it participates in the stack. Relations resolve only live names.
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82pub enum LayerFocus {
83    #[default]
84    Manage,
85    Preserve,
86}
87#[derive(Clone, Debug, PartialEq)]
88pub struct Layer {
89    pub sheet: Option<crate::SheetConfig>,
90    pub modal: bool,
91    pub escape: bool,
92    pub outside: bool,
93    pub focus: LayerFocus,
94    pub placement: LayerPlacement,
95    pub anchor: Option<SemanticId>,
96    pub initial_focus: Option<SemanticId>,
97    pub return_focus: Option<SemanticId>,
98}
99impl Default for Layer {
100    fn default() -> Self {
101        Self {
102            sheet: None,
103            modal: true,
104            escape: true,
105            outside: true,
106            focus: LayerFocus::Manage,
107            placement: LayerPlacement::Center,
108            anchor: None,
109            initial_focus: None,
110            return_focus: None,
111        }
112    }
113}
114#[derive(Clone, Copy, Debug, Default, PartialEq)]
115pub enum LayerPlacement {
116    #[default]
117    Center,
118    Left,
119    Right,
120    Top,
121    Bottom,
122    Anchor(crate::AnchorPlacement),
123    /// A context request in viewport CSS pixels, belonging to `Layer::anchor`.
124    ContextPoint(crate::ContextPoint),
125    Viewport(crate::ViewportPlacement),
126}
127impl LayerPlacement {
128    pub fn as_str(self) -> &'static str {
129        match self {
130            Self::Center => "center",
131            Self::Left => "left",
132            Self::Right => "right",
133            Self::Top => "top",
134            Self::Bottom => "bottom",
135            Self::Anchor(_) => "anchor",
136            Self::ContextPoint(_) => "context-point",
137            Self::Viewport(_) => "viewport",
138        }
139    }
140}
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub enum DismissReason {
143    Gesture,
144    Escape,
145    Outside,
146    /// The declared anchor is no longer a live visible semantic box.
147    AnchorLost,
148}
149
150#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
151pub struct SemanticId(String);
152impl SemanticId {
153    /// Names are bounded ASCII tokens. Applications must choose distinct widget
154    /// namespaces when multiple Apps share one host document.
155    pub fn new(value: impl Into<String>) -> Result<Self, Error> {
156        let value = value.into();
157        if value.is_empty()
158            || value.len() > 256
159            || !value
160                .bytes()
161                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
162        {
163            return Err(Error::InvalidProps(
164                "semantic id must be a bounded ASCII token",
165            ));
166        }
167        Ok(Self(value))
168    }
169    pub fn as_str(&self) -> &str {
170        &self.0
171    }
172}
173
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175pub enum Orientation {
176    Horizontal,
177    Vertical,
178}
179#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
180pub enum Direction {
181    #[default]
182    Ltr,
183    Rtl,
184}
185impl Orientation {
186    pub fn key_with_direction(
187        self,
188        direction: Direction,
189        input: crate::KeyboardInput<'_>,
190    ) -> Option<Navigation> {
191        let command = self.key(input)?;
192        Some(match (self, direction, input.key, command) {
193            (Self::Horizontal, Direction::Rtl, "ArrowLeft" | "ArrowRight", Navigation::Next) => {
194                Navigation::Previous
195            }
196            (
197                Self::Horizontal,
198                Direction::Rtl,
199                "ArrowLeft" | "ArrowRight",
200                Navigation::Previous,
201            ) => Navigation::Next,
202            _ => command,
203        })
204    }
205    pub fn as_str(self) -> &'static str {
206        match self {
207            Self::Horizontal => "horizontal",
208            Self::Vertical => "vertical",
209        }
210    }
211    /// Shared direction mapping. Tab, editing keys, modified/composing keys and
212    /// the perpendicular arrows remain host-native. Repeats may navigate.
213    pub fn key(self, input: crate::KeyboardInput<'_>) -> Option<Navigation> {
214        if input.composing
215            || input.editable
216            || input.control
217            || input.meta
218            || input.alt
219            || input.shift
220        {
221            return None;
222        }
223        match (self, input.key) {
224            (Self::Horizontal, "ArrowLeft") | (Self::Vertical, "ArrowUp") => {
225                Some(Navigation::Previous)
226            }
227            (Self::Horizontal, "ArrowRight") | (Self::Vertical, "ArrowDown") => {
228                Some(Navigation::Next)
229            }
230            (_, "Home") => Some(Navigation::First),
231            (_, "End") => Some(Navigation::Last),
232            _ => None,
233        }
234    }
235}
236
237/// Optional and finite: ordinary nodes allocate none of this metadata. Named
238/// relations may refer forward or to an unmounted target; adapters resolve only
239/// live names in their document. Removing a target retains no owning reference.
240#[derive(Clone, Debug, Default, PartialEq)]
241pub struct Semantics {
242    /// Explicit inherited text direction/language on an ordinary boxed View.
243    pub environment: Option<crate::Environment>,
244    /// A focus-only boundary. It has no role, top-layer paint or inert backdrop.
245    pub focus_scope: Option<crate::FocusScopeConfig>,
246    /// Nonphysical source read from the accepted semantic tree only when a
247    /// typed clipboard action is admitted. It is not duplicated into HTML.
248    pub clipboard: Option<crate::ClipboardText>,
249    /// Present only on a structural column header; actions remain intrinsic buttons.
250    pub sort: Option<crate::SortDirection>,
251    /// Replace ordinary host ValueChanged with one bounded post-edit path.
252    pub input_edit: Option<crate::InputEditCapture>,
253    /// Finite paint-only motion on an inert, independently boxed View.
254    pub translation: Option<crate::TranslationMotion>,
255    /// Finite single-line input hints; no automatic code or credential retrieval.
256    pub input_assist: Option<crate::InputAssist>,
257    /// Optional bounded presentation hint on Input, never its accessible name,
258    /// stored value, default value or composition state.
259    pub placeholder: Option<String>,
260    /// Optional intrinsic-height presentation with immediate logical hiding.
261    pub collapse: Option<crate::CollapseConfig>,
262    /// Immediate primary-pointer capture, in viewport CSS pixels.
263    pub drag_capture: Option<crate::DragCapture>,
264    /// Axis intent capture preserves orthogonal native panning.
265    pub swipe_capture: Option<crate::SwipeCapture>,
266    /// An explicit context region. Touch long-press remains host-native.
267    pub context_menu: Option<crate::ContextEditPolicy>,
268    /// Opted-in free tag entry policy; retains the Input's intrinsic textbox.
269    pub tags_input: Option<crate::TagSeparators>,
270    pub progress: Option<crate::ProgressValue>,
271    pub splitter: Option<crate::RangeValue>,
272    pub slider: Option<crate::SliderValue>,
273    pub spinbutton: Option<crate::SpinValue>,
274    /// Opt-in keyboard commands only while this viewport itself owns focus.
275    pub scroll_keyboard: Option<crate::ScrollAxes>,
276    /// An application-owned pending state on a boxed semantic node.
277    pub busy: Option<bool>,
278    pub current: Option<Current>,
279    pub separator_axis: Option<Orientation>,
280    pub link_open: Option<LinkOpen>,
281    /// Capture activation as an application request before default navigation.
282    pub link_request: bool,
283    pub document_part: Option<crate::DocumentPart>,
284    pub table: Option<crate::TableMetadata>,
285    pub form_action: Option<FormAction>,
286    pub form_control: Option<FormControl>,
287    pub field_part: Option<FieldPart>,
288    pub label_for: Option<SemanticId>,
289    pub error_message: Option<SemanticId>,
290    pub required: bool,
291    pub readonly: bool,
292    pub invalid: bool,
293    pub id: Option<SemanticId>,
294    pub controls: Option<SemanticId>,
295    pub labelled_by: Option<SemanticId>,
296    pub described_by: Option<SemanticId>,
297    pub popup: Option<PopupKind>,
298    pub combobox: Option<crate::ComboboxKind>,
299    pub option: Option<crate::OptionSemantics>,
300    pub active_descendant: Option<SemanticId>,
301    pub listbox_multiple: bool,
302    pub menu_item: Option<MenuItemSemantics>,
303    /// An intrinsic action trigger belonging to a structural Menubar.
304    pub menubar_item: bool,
305    pub layer: Option<Layer>,
306    /// Passive grip hit area; the nearest live sheet owns pointer gestures.
307    pub sheet_grip: bool,
308    pub expanded: Option<bool>,
309    pub selected: Option<bool>,
310    /// A toggle button's application-owned state; independent from disclosure.
311    pub pressed: Option<bool>,
312    /// Refine a Button's intrinsic interaction to a tab, retaining activation.
313    pub tab: bool,
314    /// Keep a control focusable, while suppressing activation (e.g. the sole
315    /// expanded header in an accordion that cannot collapse completely).
316    pub disabled: bool,
317    /// Hide a View subtree without destroying its state or removing its names.
318    pub hidden: bool,
319    /// Retain a View's content and layout while suppressing subtree interaction
320    /// and accessibility exposure. This is not a scroll lock or a modal scope.
321    pub inert: bool,
322    /// Explicit collection boundary, independent of virtual-list navigation.
323    pub navigation: Option<Orientation>,
324    /// A two-dimensional physical Button navigation boundary, independent of
325    /// the linear collection navigation protocol.
326    pub grid_navigation: Option<Direction>,
327    /// A Grid that permits more than one selected cell.
328    pub grid_multiple: bool,
329    pub tree_navigation: Option<crate::TreeNavigation>,
330    pub tree_item: Option<crate::TreeItem>,
331    /// A checkable tree item, independent from list selection and Check props.
332    pub tree_checked: Option<crate::TreeCheckState>,
333    pub navigation_item: bool,
334    pub navigation_panel: Option<crate::NavigationPanel>,
335    /// Native radio association; not an accessible name or a submission value.
336    /// HTML uses the same attribute for native grouping and successful names.
337    pub check_group: Option<SemanticId>,
338    pub navigation_direction: Direction,
339    /// Opt in to bounded character search on the collection's mounted members.
340    pub typeahead: bool,
341}
342impl Semantics {
343    pub(crate) fn validate(&self, d: crate::DescriptorView<'_>) -> Result<(), Error> {
344        if let Some(placeholder) = &self.placeholder {
345            let Props::Input(input) = d.props else {
346                return Err(Error::InvalidProps("placeholder requires an Input"));
347            };
348            crate::validate_input_placeholder(placeholder, input.multiline)?;
349        }
350        if let Some(environment) = &self.environment {
351            if !matches!(d.props, Props::View) {
352                return Err(Error::InvalidProps("environment metadata belongs to View"));
353            }
354            if self.navigation.is_some() && self.navigation_direction != environment.direction
355                || self
356                    .grid_navigation
357                    .is_some_and(|direction| direction != environment.direction)
358                || self
359                    .tree_navigation
360                    .is_some_and(|tree| tree.direction != environment.direction)
361            {
362                return Err(Error::InvalidProps(
363                    "environment and navigation directions disagree",
364                ));
365            }
366        }
367        if self.focus_scope.is_some()
368            && (!matches!(d.props, Props::View)
369                || d.focus != crate::FocusMode::Programmatic
370                || !matches!(d.role, None | Some(Role::Group))
371                || self.layer.is_some())
372        {
373            return Err(Error::InvalidProps(
374                "FocusScope requires an independent programmatic View",
375            ));
376        }
377        if self.tree_checked.is_some()
378            && (d.role != Some(Role::TreeItem)
379                || self.tree_item.is_none()
380                || self.selected.is_some())
381        {
382            return Err(Error::InvalidProps(
383                "tree checked state requires a TreeItem with coordinates, without selected state",
384            ));
385        }
386        if self.tree_navigation.is_some()
387            && (d.role != Some(Role::Tree)
388                || !matches!(d.props, Props::View)
389                || self.navigation.is_some()
390                || self.grid_navigation.is_some()
391                || self.navigation_item
392                || self.tree_item.is_some()
393                || self.typeahead)
394        {
395            return Err(Error::InvalidProps(
396                "tree navigation requires an independent Tree View",
397            ));
398        }
399        if let Some(item) = self.tree_item {
400            item.validate()?;
401            if d.role != Some(Role::TreeItem)
402                || !matches!(d.props, Props::View)
403                || self.navigation.is_some()
404                || self.grid_navigation.is_some()
405                || self.navigation_item
406                || self.table.is_some()
407                || self.typeahead
408            {
409                return Err(Error::InvalidProps(
410                    "tree coordinates require an independent TreeItem View",
411                ));
412            }
413        }
414        if self.clipboard.is_some()
415            && (!matches!(d.props, Props::Button(_))
416                || self.form_action.is_some()
417                || self.tab
418                || self.menu_item.is_some())
419        {
420            return Err(Error::InvalidProps(
421                "clipboard source requires an independent intrinsic Button",
422            ));
423        }
424        if self.grid_multiple && (d.role != Some(Role::Grid) || !matches!(d.props, Props::View)) {
425            return Err(Error::InvalidProps(
426                "multiple grid selection requires a Grid View",
427            ));
428        }
429        if self.grid_navigation.is_some()
430            && (d.role != Some(Role::Grid)
431                || !matches!(d.props, Props::View)
432                || self.navigation.is_some()
433                || self.navigation_item
434                || self.typeahead)
435        {
436            return Err(Error::InvalidProps(
437                "grid navigation requires an independent Grid View",
438            ));
439        }
440        if let Some(capture) = self.input_edit {
441            capture.validate()?;
442            if !matches!(d.props,Props::Input(p) if !p.multiline&&p.value.len()<=capture.max_bytes)
443                || self.tags_input.is_some()
444                || self.spinbutton.is_some()
445                || self.combobox.is_some()
446            {
447                return Err(Error::InvalidProps(
448                    "input edit capture requires an independent bounded single-line Input",
449                ));
450            }
451        }
452        if let Some(translation) = self.translation {
453            translation.validate()?;
454            if !matches!(d.props, Props::View)
455                || !self.inert
456                || d.role.is_some()
457                || d.name.is_some()
458                || d.focus != crate::FocusMode::Auto
459                || self.collapse.is_some()
460                || self.layer.is_some()
461                || self.drag_capture.is_some()
462                || self.document_part.is_some()
463                || self.field_part.is_some()
464            {
465                return Err(Error::InvalidProps(
466                    "translation requires an independent inert unnamed View without role, focus, layer, collapse or drag capture",
467                ));
468            }
469        }
470        if self.input_assist.is_some() && !matches!(d.props, Props::Input(p) if !p.multiline) {
471            return Err(Error::InvalidProps(
472                "input assist requires a single-line Input",
473            ));
474        }
475        if let Some(collapse) = &self.collapse {
476            collapse.validate()?;
477            collapse.validate_style(d.style)?;
478            if !matches!(d.props, Props::View)
479                || self.layer.is_some()
480                || self.document_part.is_some()
481                || self.field_part.is_some()
482                || self.hidden == collapse.open
483                || self.inert == collapse.open
484            {
485                return Err(Error::InvalidProps(
486                    "collapse requires an independent View and hidden/inert opposite to open",
487                ));
488            }
489        }
490        if self.swipe_capture.is_some()
491            && (!matches!(d.props, Props::View)
492                || d.role.is_some_and(|role| role != Role::Group)
493                || self.document_part.is_some()
494                || self.field_part.is_some()
495                || self.drag_capture.is_some()
496                || self.slider.is_some()
497                || self.splitter.is_some()
498                || self.sheet_grip
499                || self.layer.is_some()
500                || self.collapse.is_some())
501        {
502            return Err(Error::InvalidProps(
503                "swipe capture requires an independent boxed View",
504            ));
505        }
506        if self.drag_capture.is_some()
507            && (!matches!(d.props, Props::View)
508                || self.slider.is_some()
509                || self.splitter.is_some()
510                || self.sheet_grip)
511        {
512            return Err(Error::InvalidProps(
513                "press drag capture requires an independent boxed View",
514            ));
515        }
516        if self.drag_capture == Some(crate::DragCapture::PressFocus)
517            && d.focus == crate::FocusMode::Auto
518        {
519            return Err(Error::InvalidProps(
520                "focus capture requires an explicit View focus mode",
521            ));
522        }
523        if d.role == Some(Role::Menubar)
524            && (self.id.is_none()
525                || self.navigation != Some(Orientation::Horizontal)
526                || d.focus != crate::FocusMode::Auto
527                || self.layer.is_some())
528        {
529            return Err(Error::InvalidProps(
530                "menubar requires a named horizontal container with roving child focus",
531            ));
532        }
533        if self.menubar_item
534            && (!matches!(d.props, Props::Button(_))
535                || !self
536                    .menu_item
537                    .as_ref()
538                    .is_some_and(|item| item.kind == MenuItemKind::Action)
539                || self.popup != Some(PopupKind::Menu)
540                || self.controls.is_none()
541                || self.id.is_none()
542                || !self.navigation_item
543                || d.focus == crate::FocusMode::Auto)
544        {
545            return Err(Error::InvalidProps(
546                "menubar root requires an intrinsic menuitem popup button with explicit roving focus",
547            ));
548        }
549        if self.context_menu.is_some()
550            && (!matches!(d.props, Props::View)
551                || d.effective_role() != Some(Role::Group)
552                || self.id.is_none()
553                || self.layer.is_some()
554                || self.popup.is_some()
555                || self.expanded.is_some()
556                || self.navigation.is_some())
557        {
558            return Err(Error::InvalidProps(
559                "context policy requires an independent named group region",
560            ));
561        }
562        if self.tags_input.is_some()
563            && (!matches!(d.props,crate::Props::Input(input) if !input.multiline)
564                || self.combobox.is_some()
565                || self.popup.is_some()
566                || self.controls.is_some()
567                || self.active_descendant.is_some()
568                || self.form_control.is_some())
569        {
570            return Err(Error::InvalidProps(
571                "tags policy requires an independent single-line search input",
572            ));
573        }
574        if self.sheet_grip
575            && (!matches!(d.props, Props::View)
576                || d.role.is_some()
577                || d.focus != crate::FocusMode::Auto
578                || self.layer.is_some()
579                || self.navigation.is_some())
580        {
581            return Err(Error::InvalidProps(
582                "sheet grip requires a passive generic view",
583            ));
584        }
585        if let Some(panel) = self.navigation_panel {
586            let valid = match panel {
587                crate::NavigationPanel::Trigger => {
588                    matches!(d.props, Props::Button(_))
589                        && self.navigation_item
590                        && self.id.is_some()
591                        && self.controls.is_some()
592                        && self.controls != self.id
593                        && self.expanded.is_some()
594                        && self.popup.is_none()
595                        && self.menu_item.is_none()
596                        && !self.tab
597                        && self.pressed.is_none()
598                        && self.form_action.is_none()
599                }
600                crate::NavigationPanel::Content => {
601                    matches!(d.props, Props::View)
602                        && d.role == Some(Role::Group)
603                        && d.focus == crate::FocusMode::Auto
604                        && self.id.is_some()
605                        && self.navigation == Some(Orientation::Vertical)
606                        && self.menu_item.is_none()
607                        && self.popup.is_none()
608                        && self.field_part.is_none()
609                        && self.document_part.is_none()
610                        && self.scroll_keyboard.is_none()
611                }
612            };
613            if !valid {
614                return Err(Error::InvalidProps(
615                    "navigation panels require an independent disclosure button or physical group content",
616                ));
617            }
618        }
619        if self.inert && !matches!(d.props, Props::View) {
620            return Err(Error::InvalidProps("inert regions require a view"));
621        }
622        self.validate_choice(d)?;
623        if let Some(progress) = &self.progress {
624            progress.validate()?;
625            if d.role != Some(Role::ProgressBar)
626                || !matches!(d.props, Props::View)
627                || self.navigation.is_some()
628                || self.layer.is_some()
629                || self.field_part.is_some()
630                || self.document_part.is_some()
631                || self.splitter.is_some()
632                || self.menu_item.is_some()
633                || self.popup.is_some()
634                || self.pressed.is_some()
635                || self.expanded.is_some()
636                || self.scroll_keyboard.is_some()
637            {
638                return Err(Error::InvalidProps(
639                    "progress metadata requires an independent progress bar view",
640                ));
641            }
642        }
643        if let Some(spin) = &self.spinbutton {
644            spin.validate()?;
645            if !matches!(d.props, Props::Input(p) if !p.multiline && matches!(p.purpose, crate::Purpose::Text | crate::Purpose::Number))
646                || self.combobox.is_some()
647                || self.tags_input.is_some()
648                || self.popup.is_some()
649                || self.navigation.is_some()
650                || self.option.is_some()
651                || self.slider.is_some()
652                || self.splitter.is_some()
653            {
654                return Err(Error::InvalidProps(
655                    "spinbutton requires an independent single-line numeric text input",
656                ));
657            }
658            if (self.disabled || self.readonly || !d.props.enabled())
659                && (spin.can_increase || spin.can_decrease)
660            {
661                return Err(Error::InvalidProps(
662                    "disabled or readonly spinbuttons cannot advertise adjustment",
663                ));
664            }
665            if spin.value.is_some_and(|v| {
666                spin.min.is_some_and(|min| v < min) || spin.max.is_some_and(|max| v > max)
667            }) && !self.invalid
668            {
669                return Err(Error::InvalidProps(
670                    "outside spinbutton coordinates require invalid metadata",
671                ));
672            }
673        }
674        if let Some(slider) = &self.slider {
675            slider.validate()?;
676            if slider.range.min == slider.range.max && !self.readonly {
677                return Err(Error::InvalidProps(
678                    "a fixed slider interval requires readonly semantics",
679                ));
680            }
681            if !matches!(d.props, Props::View)
682                || d.role != Some(Role::Slider)
683                || d.focus == crate::FocusMode::Auto
684                || self.splitter.is_some()
685                || self.progress.is_some()
686                || self.separator_axis.is_some()
687                || self.navigation.is_some()
688                || self.navigation_item
689                || self.layer.is_some()
690                || self.field_part.is_some()
691                || self.document_part.is_some()
692                || self.tab
693                || self.pressed.is_some()
694                || self.expanded.is_some()
695                || self.popup.is_some()
696                || self.scroll_keyboard.is_some()
697                || self.menu_item.is_some()
698                || self.combobox.is_some()
699                || self.option.is_some()
700            {
701                return Err(Error::InvalidProps(
702                    "slider requires an independent focused range view",
703                ));
704            }
705        }
706        if let Some(range) = self.splitter {
707            range.validate()?;
708            if !matches!(d.props, Props::View)
709                || d.role != Some(Role::Separator)
710                || d.focus == crate::FocusMode::Auto
711                || self.separator_axis.is_none()
712                || self.controls.is_none()
713                || self.controls == self.id
714                || self.navigation.is_some()
715            {
716                return Err(Error::InvalidProps(
717                    "splitter requires a focused separator, orientation and distinct controlled pane",
718                ));
719            }
720        }
721        if self.scroll_keyboard.is_some()
722            && (!matches!(d.props, Props::View)
723                || self.navigation.is_some()
724                || self.navigation_item
725                || self.layer.is_some()
726                || self.field_part.is_some()
727                || self.document_part.is_some()
728                || d.role == Some(Role::Separator))
729        {
730            return Err(Error::InvalidProps(
731                "scroll keyboard requires an independent viewport view",
732            ));
733        }
734        if let Some(item) = &self.menu_item {
735            let valid = match (&d.props, item.kind) {
736                (Props::Button(_), MenuItemKind::Action) => {
737                    !self.tab && self.pressed.is_none() && self.form_action.is_none()
738                }
739                (Props::Check(check), MenuItemKind::Checkbox) => matches!(
740                    check.mode,
741                    crate::CheckMode::Checkbox | crate::CheckMode::Mixed
742                ),
743                (Props::Check(check), MenuItemKind::Radio) => {
744                    check.mode == crate::CheckMode::Radio && self.check_group.is_some()
745                }
746                _ => false,
747            };
748            if !valid
749                || self.form_control.is_some()
750                || self.id.as_ref() == Some(&item.owner)
751                || self.popup.is_some_and(|popup| popup != PopupKind::Menu)
752            {
753                return Err(Error::InvalidProps(
754                    "menu item requires a matching intrinsic control and distinct menu owner",
755                ));
756            }
757        }
758        if self.current.is_some()
759            && !matches!(d.props, Props::Link(_) | Props::Button(_) | Props::Text(_))
760        {
761            return Err(Error::InvalidProps("current requires link, button or text"));
762        }
763        if (self.typeahead || self.navigation_direction != Direction::Ltr)
764            && self.navigation.is_none()
765            && self.combobox != Some(crate::ComboboxKind::Select)
766        {
767            return Err(Error::InvalidProps(
768                "direction and typeahead require a navigation boundary",
769            ));
770        }
771        if self.separator_axis.is_some() && d.role != Some(Role::Separator) {
772            return Err(Error::InvalidProps(
773                "separator orientation requires a separator role",
774            ));
775        }
776        if (self.link_open.is_some() || self.link_request) && !matches!(d.props, Props::Link(_)) {
777            return Err(Error::InvalidProps("link context requires a link"));
778        }
779        if let Some(table) = &self.table {
780            table.validate(d)?;
781        }
782        if self.sort.is_some()
783            && (!matches!(d.props, Props::View)
784                || !(self.document_part == Some(crate::DocumentPart::ColumnHeader)
785                    || d.role == Some(Role::ColumnHeader)))
786        {
787            return Err(Error::InvalidProps(
788                "sort direction requires a structural column header",
789            ));
790        }
791        if self.document_part.is_some()
792            && (!matches!(d.props, Props::View)
793                || d.role.is_some()
794                || d.focus != crate::FocusMode::Auto
795                || self.field_part.is_some()
796                || self.layer.is_some()
797                || self.navigation.is_some())
798        {
799            return Err(Error::InvalidProps(
800                "document parts require an unfocused structural view",
801            ));
802        }
803        if let Some(group) = &self.check_group
804            && (!matches!(&d.props, Props::Check(check) if check.mode == crate::CheckMode::Radio)
805                || self
806                    .form_control
807                    .as_ref()
808                    .is_some_and(|control| control.name != group.as_str()))
809        {
810            return Err(Error::InvalidProps(
811                "radio association requires a radio and matching successful-control name",
812            ));
813        }
814        if self.form_action.is_some()
815            && (!matches!(d.props, Props::Button(_))
816                || self.tab
817                || self.popup.is_some()
818                || self.expanded.is_some()
819                || self.pressed.is_some())
820        {
821            return Err(Error::InvalidProps("form actions require ordinary buttons"));
822        }
823        if let Some(control) = &self.form_control
824            && (!matches!(
825                d.props,
826                Props::Input(_) | Props::Select(_) | Props::Check(_) | Props::Button(_)
827            ) && d.role != Some(Role::Slider)
828                || control.name.len() > 256
829                || control.name.contains(['\0', '\r', '\n'])
830                || control
831                    .value
832                    .as_ref()
833                    .is_some_and(|value| value.contains(['\0', '\r']))
834                || control.value.is_some() && matches!(d.props, Props::Input(_) | Props::Select(_)))
835        {
836            return Err(Error::InvalidProps("invalid successful-control metadata"));
837        }
838        if self.field_part.is_some()
839            && (!matches!(d.props, Props::View)
840                || d.role.is_some()
841                || d.focus != crate::FocusMode::Auto
842                || self.layer.is_some()
843                || self.navigation.is_some())
844        {
845            return Err(Error::InvalidProps(
846                "form parts require an unfocused structural view",
847            ));
848        }
849        if self.label_for.is_some() && self.field_part != Some(FieldPart::Label) {
850            return Err(Error::InvalidProps(
851                "label association requires a label part",
852            ));
853        }
854        if self.label_for.is_some() && self.label_for == self.id {
855            return Err(Error::InvalidProps("a label cannot target itself"));
856        }
857        if self.readonly && matches!(d.props, Props::Select(_)) {
858            return Err(Error::Unsupported("native select has no readonly state"));
859        }
860        let input_field = self.combobox.is_some()
861            || matches!(
862                d.props,
863                Props::Input(_) | Props::Select(_) | Props::Check(_) | Props::RichEditor(_)
864            )
865            || matches!(d.role, Some(Role::RadioGroup | Role::Slider));
866        if (self.required && !input_field)
867            || (self.readonly && !input_field && d.role != Some(Role::Grid))
868            || ((self.invalid || self.error_message.is_some())
869                && !input_field
870                && self.field_part != Some(FieldPart::Fieldset))
871        {
872            return Err(Error::InvalidProps(
873                "field states require an input or check",
874            ));
875        }
876        if self.popup.is_some()
877            && ((!matches!(d.props, Props::Button(_)) && self.combobox.is_none()) || self.tab)
878        {
879            return Err(Error::InvalidProps(
880                "popup triggers require a non-tab button",
881            ));
882        }
883        if self.pressed.is_some()
884            && (!matches!(d.props, Props::Button(_)) || self.tab || self.popup.is_some())
885        {
886            return Err(Error::InvalidProps(
887                "pressed requires a non-tab toggle button",
888            ));
889        }
890        if let Some(layer) = &self.layer {
891            if let LayerPlacement::Viewport(placement) = layer.placement {
892                placement.validate()?;
893                if d.role != Some(Role::Dialog) || layer.anchor.is_some() || layer.sheet.is_some() {
894                    return Err(Error::InvalidProps(
895                        "viewport positioning requires an unanchored dialog",
896                    ));
897                }
898            }
899            if let LayerPlacement::Anchor(placement) = layer.placement {
900                placement.validate()?;
901            }
902            if let LayerPlacement::ContextPoint(point) = layer.placement {
903                point
904                    .validate()
905                    .map_err(|_| Error::InvalidProps("context layer point must be finite"))?;
906                if d.role != Some(Role::Menu) {
907                    return Err(Error::InvalidProps(
908                        "context point positioning requires a menu",
909                    ));
910                }
911            }
912            if let Some(sheet) = &layer.sheet {
913                sheet.validate()?;
914                if d.style
915                    .position
916                    .is_some_and(|p| p != crate::style::Position::Fixed)
917                {
918                    return Err(Error::InvalidProps("sheet owns fixed viewport positioning"));
919                }
920                if d.role != Some(Role::Dialog)
921                    || !crate::sheet::edge(layer.placement)
922                    || layer.focus != LayerFocus::Manage
923                    || layer.anchor.is_some()
924                {
925                    return Err(Error::InvalidProps(
926                        "sheet requires an edge dialog with managed focus",
927                    ));
928                }
929            }
930            if !matches!(d.props, Props::View)
931                || !matches!(
932                    d.role,
933                    Some(
934                        Role::Dialog
935                            | Role::AlertDialog
936                            | Role::Menu
937                            | Role::Tooltip
938                            | Role::Listbox
939                            | Role::Tree
940                            | Role::Group
941                    )
942                )
943                || self.id.is_none()
944                || (!matches!(d.role, Some(Role::Tooltip | Role::Listbox))
945                    && d.focus == crate::FocusMode::Auto
946                    && d.role != Some(Role::Group))
947                || (layer.focus == LayerFocus::Preserve
948                    && (layer.modal
949                        || layer.initial_focus.is_some()
950                        || layer.return_focus.is_some()))
951                || (d.role == Some(Role::Tooltip)
952                    && (layer.focus != LayerFocus::Preserve
953                        || d.focus != crate::FocusMode::Auto
954                        || self.navigation.is_some()
955                        || self.popup.is_some()
956                        || self.expanded.is_some()))
957                || (matches!(d.role, Some(Role::Dialog | Role::AlertDialog))
958                    && self.navigation.is_some())
959                || (d.role == Some(Role::AlertDialog)
960                    && (!layer.modal
961                        || layer.focus != LayerFocus::Manage
962                        || layer.initial_focus.is_none()))
963                || (d.role == Some(Role::Listbox)
964                    && (layer.modal
965                        || layer.focus != LayerFocus::Preserve
966                        || d.focus != crate::FocusMode::Auto
967                        || self.navigation != Some(Orientation::Vertical)))
968                || (d.role == Some(Role::Tree)
969                    && (layer.modal
970                        || layer.focus != LayerFocus::Manage
971                        || self.tree_navigation.is_none()
972                        || d.focus == crate::FocusMode::Auto))
973                || (d.role == Some(Role::Menu)
974                    && (layer.modal
975                        || layer.focus != LayerFocus::Manage
976                        || self.navigation != Some(Orientation::Vertical)))
977                || (d.role == Some(Role::Group)
978                    && (self.navigation_panel != Some(crate::NavigationPanel::Content)
979                        || layer.modal
980                        || layer.focus != LayerFocus::Preserve
981                        || d.focus != crate::FocusMode::Auto))
982            {
983                return Err(Error::InvalidProps(
984                    "layers require a valid named dialog, alert decision, menu or passive tooltip focus policy",
985                ));
986            }
987            if matches!(
988                layer.placement,
989                LayerPlacement::Anchor(_) | LayerPlacement::ContextPoint(_)
990            ) != layer.anchor.is_some()
991                || layer
992                    .anchor
993                    .as_ref()
994                    .is_some_and(|id| Some(id) == self.id.as_ref())
995            {
996                return Err(Error::InvalidProps(
997                    "anchored layers require a distinct anchor",
998                ));
999            }
1000        }
1001        if matches!(d.props, Props::Group) {
1002            return Err(Error::InvalidProps(
1003                "group has no composite widget metadata",
1004            ));
1005        }
1006        if (self.tab
1007            || (self.expanded.is_some() && d.role != Some(Role::TreeItem))
1008            || (self.disabled
1009                && self.splitter.is_none()
1010                && self.slider.is_none()
1011                && self.context_menu.is_none()
1012                && self.drag_capture.is_none()
1013                && self.swipe_capture.is_none()
1014                && d.role != Some(Role::Menubar)
1015                && !matches!(d.role, Some(Role::Tree | Role::TreeItem))
1016                && !matches!(self.field_part, Some(FieldPart::Fieldset | FieldPart::Form))))
1017            && !matches!(d.props, Props::Button(_))
1018            && self.combobox.is_none()
1019        {
1020            return Err(Error::InvalidProps(
1021                "composite trigger metadata requires a button",
1022            ));
1023        }
1024        if self.navigation_item
1025            && !matches!(&d.props, Props::Button(_) | Props::Link(_))
1026            && !matches!(&d.props, Props::Check(check) if check.mode == crate::CheckMode::Radio)
1027            && self.menu_item.is_none()
1028        {
1029            return Err(Error::InvalidProps(
1030                "navigation items require a button, link or radio",
1031            ));
1032        }
1033        if self.selected.is_some()
1034            && !self.tab
1035            && self.option.is_none()
1036            && d.role != Some(Role::GridCell)
1037            && d.role != Some(Role::TreeItem)
1038            || self.tab && (self.expanded.is_some() || self.selected.is_none())
1039        {
1040            return Err(Error::InvalidProps(
1041                "selected belongs to tabs; tabs cannot be disclosures",
1042            ));
1043        }
1044        if self.navigation.is_some() && !matches!(d.props, Props::View) {
1045            return Err(Error::InvalidProps(
1046                "hidden panels and navigation boundaries require a view",
1047            ));
1048        }
1049        if self.hidden && !matches!(d.props, Props::View) && self.option.is_none() {
1050            return Err(Error::InvalidProps(
1051                "hidden content requires a view or intrinsic option",
1052            ));
1053        }
1054        if self.labelled_by.is_some()
1055            && (matches!(&d.props, Props::Text(p) if !matches!(p.kind, crate::TextKind::Heading(_)))
1056                || matches!(&d.props, Props::Image(p) if p.alternative.is_none())
1057                || matches!(d.props, Props::Graphic(p) if p.alternative.is_none()))
1058        {
1059            return Err(Error::InvalidProps(
1060                "this node cannot have a naming relation",
1061            ));
1062        }
1063        if self.controls.is_some() && self.id == self.controls {
1064            return Err(Error::InvalidProps("a control cannot control itself"));
1065        }
1066        if self.labelled_by.is_some() && self.id == self.labelled_by {
1067            return Err(Error::InvalidProps("a node cannot label itself"));
1068        }
1069        if self.navigation.is_some()
1070            && !matches!(
1071                d.role,
1072                None | Some(
1073                    Role::Group
1074                        | Role::TabList
1075                        | Role::RadioGroup
1076                        | Role::Toolbar
1077                        | Role::Menu
1078                        | Role::Menubar
1079                        | Role::Listbox
1080                )
1081            )
1082        {
1083            return Err(Error::InvalidProps(
1084                "navigation requires a generic group or tab list",
1085            ));
1086        }
1087        Ok(())
1088    }
1089}