Skip to main content

glory_render/
lib.rs

1//! A finite semantic UI contract. No HTML tags, engine types or reactive handles.
2//! Rendering adapters translate this contract into their own objects and ranges.
3
4mod anchor;
5mod viewport_layer;
6pub use viewport_layer::ViewportPlacement;
7#[cfg(feature = "conformance")]
8pub mod conformance;
9mod id;
10pub use anchor::{
11    AnchorAlign, AnchorArrow, AnchorArrowPosition, AnchorPlacement, AnchorPosition, AnchorSide,
12};
13mod node_map;
14pub use node_map::NodeMap;
15mod collapse;
16mod presence;
17pub use presence::{
18    MAX_PRESENCE_MILLIS, PresenceConfig, PresenceEffect, PresenceStyle, PresenceTiming,
19};
20mod document;
21pub use collapse::{CollapseConfig, MAX_COLLAPSE_MILLIS};
22mod graphic;
23mod graphic_transition;
24pub use graphic::{
25    GraphicFit, GraphicPoint, GraphicProps, GraphicStroke, MAX_GRAPHIC_COMMANDS,
26    MAX_GRAPHIC_COORDINATE, PathCommand, StrokeCap,
27};
28pub use graphic_transition::GraphicTransition;
29mod choice;
30pub use choice::{ChoiceCommand, ComboboxKind, OptionSemantics};
31mod context_menu;
32mod tags;
33pub use context_menu::{ContextEditPolicy, ContextPoint, ContextSource};
34pub use tags::{
35    MAX_TAG_INPUT_BYTES, MAX_TAG_PASTE_BYTES, TagHostRejection, TagKey, TagSeparators, TagsCommand,
36};
37mod select;
38pub use select::{
39    MAX_SELECT_BYTES, MAX_SELECT_GROUPS, MAX_SELECT_OPTIONS, SelectEntry, SelectGroup,
40    SelectOption, SelectProps, SelectSelection,
41};
42mod range;
43pub use range::RangeValue;
44mod progress;
45pub use progress::ProgressValue;
46mod motion;
47pub use motion::{GraphicAnimation, MotionPreference};
48mod translation;
49pub use translation::{
50    MAX_TRANSLATION_COORDINATE, TranslationKind, TranslationMotion, TranslationOffset,
51    TranslationPhase,
52};
53pub mod memory;
54mod plan;
55pub mod profile;
56mod props;
57mod semantics;
58pub use document::DocumentPart;
59mod text;
60
61pub use glory_style as style;
62pub use id::{NodeId, NodeIds, RuntimeId};
63pub use plan::{MAX_PLAN_NODES, Plan, PlanNode, WeakPlan};
64pub use props::*;
65pub use semantics::{
66    Current, Direction, DismissReason, FieldPart, FormAction, FormControl, Layer, LayerFocus,
67    LayerPlacement, LinkOpen, MenuItemKind, MenuItemSemantics, Orientation, PopupKind, SemanticId,
68    Semantics,
69};
70pub use text::normalize_text;
71mod clipboard;
72mod files;
73pub use clipboard::{ClipboardOutcome, ClipboardText, MAX_CLIPBOARD_BYTES};
74pub use files::{
75    FileCapabilities, FileChunk, FileConfig, FileDocumentId, FileEvent, FileFilter,
76    FileImageFormat, FileImageInfo, FileInfo, FileOrigin, FileOutcome, FilePreview,
77    FilePreviewError, FilePreviewLimits, FileProps, FileRead, FileRejection, FileToken,
78    MAX_FILE_BYTES, MAX_FILE_CHUNK_BYTES, MAX_FILE_COUNT, MAX_FILE_FILTER_BYTES, MAX_FILE_FILTERS,
79    MAX_FILE_HEADER_BYTES, MAX_FILE_METADATA_BYTES, MAX_FILE_MIME_BYTES, MAX_FILE_NAME_BYTES,
80    MAX_FILE_READS, MAX_PREVIEW_DIMENSION, MAX_PREVIEW_ENCODED_BYTES, MAX_PREVIEW_PIXELS,
81    inspect_file_preview,
82};
83mod keyboard;
84pub use keyboard::{KeyboardCommand, KeyboardInput};
85mod navigation_panel;
86pub use navigation_panel::{NavigationPanel, NavigationPanelCommand};
87mod grid;
88pub use grid::GridCommand;
89mod tree;
90pub use tree::{TreeCheckState, TreeCommand, TreeItem, TreeNavigation};
91mod scroll;
92pub use scroll::{ScrollAxes, ScrollCommand, ScrollMetrics, ScrollMovement};
93mod sheet;
94pub use sheet::{MAX_SHEET_SNAPS, SheetCommand, SheetConfig};
95mod slider;
96pub use slider::SliderValue;
97mod spinbutton;
98pub use spinbutton::SpinValue;
99mod input_assist;
100pub use input_assist::{
101    InputAssist, InputAutofill, InputMode, MAX_INPUT_PLACEHOLDER_BYTES, validate_input_placeholder,
102};
103mod text_selection;
104pub use text_selection::{SelectionDirection, TextSelection};
105mod focus_scope;
106pub use focus_scope::{FocusScopeConfig, MAX_FOCUS_SCOPE_NODES, MAX_FOCUS_SCOPES};
107mod input_edit;
108pub use input_edit::{
109    InputEdit, InputEditCapture, InputEditIntent, InputEditRejection, MAX_INPUT_EDIT_BYTES,
110};
111mod splitter;
112pub use splitter::RangeCommand;
113mod typeahead;
114pub use typeahead::{MAX_TYPEAHEAD_MILLIS, validate_typeahead};
115mod drag;
116pub use drag::{DragCapture, DragPhase};
117mod menu;
118pub use menu::{MenuCommand, PointerPhase};
119
120/// Optional windowed-view metadata. Engines can show a flow preview before
121/// geometry is available without changing logical ownership or identity.
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub enum VirtualPart {
124    Root,
125    Surface,
126    Row,
127}
128
129/// A patch distinguishes absence, replacement and reset to the default value.
130#[derive(Clone, Debug, Default, PartialEq, Eq)]
131pub enum Change<T> {
132    #[default]
133    Keep,
134    Set(T),
135    Clear,
136}
137
138impl<T: Default> Change<T> {
139    pub fn apply(self, target: &mut T) {
140        self.apply_or(target, T::default());
141    }
142}
143
144impl<T> Change<T> {
145    pub fn apply_or(self, target: &mut T, default: T) {
146        match self {
147            Self::Keep => {}
148            Self::Set(value) => *target = value,
149            Self::Clear => *target = default,
150        }
151    }
152}
153
154#[derive(Clone, Debug, PartialEq)]
155pub enum Mutation {
156    Create {
157        id: NodeId,
158        node: Box<Descriptor>,
159    },
160    /// One validated, detached construction unit. Internal placement belongs
161    /// to this mutation; attach/move its root with a subsequent Place.
162    CreatePlan {
163        plan: Plan,
164        ids: Vec<NodeId>,
165    },
166    Patch {
167        id: NodeId,
168        patch: Patch,
169    },
170    /// `None` parent places a root. Existing nodes move, preserving identity.
171    Place {
172        id: NodeId,
173        parent: Option<NodeId>,
174        before: Option<NodeId>,
175    },
176    /// Disconnect a range, preserving nodes and identities until Resume/Dispose.
177    Suspend {
178        id: NodeId,
179    },
180    Resume {
181        id: NodeId,
182        parent: Option<NodeId>,
183        before: Option<NodeId>,
184    },
185    /// Permanently release this subtree, including suspended descendants.
186    Dispose {
187        id: NodeId,
188    },
189}
190
191#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
192pub struct Capabilities {
193    /// Explicit text clipboard writes with terminal host observations.
194    pub clipboard_write: bool,
195    /// Current consumer identity and independently available file operations.
196    pub files: Option<FileCapabilities>,
197    pub measure: bool,
198    pub scroll: bool,
199    pub focus: bool,
200    pub input: bool,
201    /// Emits a terminal observation for each finite collapse configuration.
202    pub collapse_completion: bool,
203    /// Host supplies revisioned presence completion; static renderers settle in the component.
204    pub presence_completion: bool,
205    /// Transform presence effects in addition to fade/none.
206    pub presence_transforms: bool,
207}
208
209#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
210pub struct QueryToken(pub u64);
211
212#[derive(Clone, Copy, Debug, PartialEq, Eq)]
213pub enum Query {
214    RichSelection(NodeId),
215    FileRead(FileRead),
216    FilePreview(FileToken),
217    Bounds(NodeId),
218    Scroll(NodeId),
219    ScrollMetrics(NodeId),
220    Selection(NodeId),
221    /// Whether this node's actual control owns document focus at the request
222    /// barrier. This is neither FocusWithin nor OS/window activation.
223    Focus(NodeId),
224}
225
226impl Query {
227    pub fn node(self) -> NodeId {
228        match self {
229            Self::FileRead(read) => read.file.node,
230            Self::FilePreview(file) => file.node,
231            Self::RichSelection(id)
232            | Self::Bounds(id)
233            | Self::Scroll(id)
234            | Self::ScrollMetrics(id)
235            | Self::Selection(id)
236            | Self::Focus(id) => id,
237        }
238    }
239
240    /// Semantic target checks precede host-specific availability checks. A
241    /// boxless Group has no physical bounds/scroll/selection of its own.
242    pub fn validate_target<'a>(self, node: impl Into<DescriptorView<'a>>) -> Result<(), Error> {
243        let node = node.into();
244        if matches!(node.props, Props::Group) {
245            return Err(Error::Unsupported("group has no physical query target"));
246        }
247        if matches!(self, Self::RichSelection(_)) && !matches!(node.props, Props::RichEditor(_)) {
248            return Err(Error::Unsupported("rich selection requires a RichEditor"));
249        }
250        if let Self::FileRead(read) = self {
251            read.validate()?;
252        }
253        if let Self::FileRead(FileRead { file, .. }) | Self::FilePreview(file) = self {
254            file.validate()?;
255            let Props::File(props) = node.props else {
256                return Err(Error::Unsupported("file queries require a File control"));
257            };
258            if file.revision != props.revision {
259                return Err(Error::InputRevision {
260                    current: props.revision,
261                    incoming: file.revision,
262                });
263            }
264            if !props.enabled {
265                return Err(Error::Unsupported("file control is disabled"));
266            }
267            if matches!(self, Self::FilePreview(_)) && props.configuration.preview.is_none() {
268                return Err(Error::Unsupported("file previews are not enabled"));
269            }
270        }
271
272        if matches!(self, Self::Selection(_)) && !matches!(node.props, Props::Input(_)) {
273            return Err(Error::Unsupported("selection requires a text input"));
274        }
275        Ok(())
276    }
277
278    /// Check adapter output before it reaches application callbacks. Coordinates
279    /// use logical pixels; selection offsets use UTF-16 code units on all hosts.
280    pub fn validate_response(self, value: &QueryValue) -> Result<(), Error> {
281        match (self, value) {
282            (Self::FileRead(read), QueryValue::FileBytes(chunk)) => chunk.validate_read(read)?,
283            (Self::FilePreview(file), QueryValue::FilePreview(preview)) => {
284                if let Some(preview) = preview {
285                    preview.validate()?;
286                    if preview.file != file {
287                        return Err(Error::InvalidResponse("file preview token mismatch"));
288                    }
289                }
290            }
291            (Self::RichSelection(_), QueryValue::RichSelection(snapshot)) => snapshot.validate()?,
292            (Self::Bounds(_), QueryValue::Bounds(rect)) => {
293                if ![rect.x, rect.y, rect.width, rect.height]
294                    .into_iter()
295                    .all(f64::is_finite)
296                    || rect.width < 0.0
297                    || rect.height < 0.0
298                {
299                    return Err(Error::InvalidResponse("invalid bounds"));
300                }
301            }
302            (Self::Scroll(_), QueryValue::Scroll { x, y }) => {
303                // Native RTL and elastic scrolling can expose negative offsets.
304                if !x.is_finite() || !y.is_finite() {
305                    return Err(Error::InvalidResponse("invalid scroll offsets"));
306                }
307            }
308            (Self::ScrollMetrics(_), QueryValue::ScrollMetrics(metrics)) => metrics.validate()?,
309            (Self::Selection(_), QueryValue::Selection { start, end }) => {
310                if start > end {
311                    return Err(Error::InvalidResponse("reversed selection"));
312                }
313            }
314            (Self::Focus(_), QueryValue::Focus(_)) => {}
315            _ => return Err(Error::InvalidResponse("query result kind mismatch")),
316        }
317        Ok(())
318    }
319}
320
321#[derive(Clone, Copy, Debug, PartialEq)]
322pub enum Action {
323    PickFiles {
324        node: NodeId,
325        revision: u64,
326        request: u64,
327    },
328    ClearFiles {
329        node: NodeId,
330        revision: u64,
331    },
332    RemoveFile(FileToken),
333    CopyText {
334        node: NodeId,
335        revision: u64,
336        request: u64,
337    },
338    /// Bring a current nonmodal Dialog layer forward without moving its DOM,
339    /// editor identity or actual focus. The host's current modal still applies.
340    RaiseLayer(NodeId),
341    /// Reveal one current physical box using nearest alignment and instant
342    /// scrolling, without focus or a logical collection controller.
343    ScrollIntoView(NodeId),
344    /// Select a range in the current rich document at its accepted revision.
345    SelectRich {
346        node: NodeId,
347        revision: u64,
348        selection: RichSelection,
349    },
350    /// Select an exact UTF-16 range in the current Input value. Stale revisions
351    /// and offsets inside surrogate pairs are rejected. A host may refuse
352    /// positions inside a shaped cluster; it must never silently clamp them.
353    SelectText {
354        node: NodeId,
355        revision: u64,
356        selection: TextSelection,
357    },
358    /// Reveal a mounted option inside its nearest owning listbox, preserving
359    /// actual combobox focus and the outer document scroll position.
360    RevealOption {
361        node: NodeId,
362    },
363    /// Leave this named nonmodal Menu's tree in native Tab order, relative to
364    /// its return-focus trigger. Does not imply the controlled menu accepted a close.
365    ExitMenu {
366        node: NodeId,
367        backwards: bool,
368    },
369    /// Request focus without scrolling. Ok means the host processed the intent;
370    /// it may decline because of current layout/platform state. Query::Focus
371    /// reads the actual result; FocusChanged reports actual transitions only.
372    Focus(NodeId),
373    ScrollTo {
374        node: NodeId,
375        x: f64,
376        y: f64,
377    },
378}
379impl Action {
380    pub fn node(self) -> NodeId {
381        match self {
382            Self::PickFiles { node, .. }
383            | Self::ClearFiles { node, .. }
384            | Self::CopyText { node, .. } => node,
385            Self::RemoveFile(file) => file.node,
386            Self::Focus(node)
387            | Self::RaiseLayer(node)
388            | Self::ScrollIntoView(node)
389            | Self::ScrollTo { node, .. }
390            | Self::ExitMenu { node, .. }
391            | Self::RevealOption { node } => node,
392            Self::SelectText { node, .. } | Self::SelectRich { node, .. } => node,
393        }
394    }
395    /// Validate after checking identity, before capability checks or queuing.
396    pub fn validate_target<'a>(self, node: impl Into<DescriptorView<'a>>) -> Result<(), Error> {
397        let node = node.into();
398        if let Self::SelectRich {
399            revision,
400            selection,
401            ..
402        } = self
403        {
404            let Props::RichEditor(editor) = node.props else {
405                return Err(Error::Unsupported(
406                    "rich selection action requires a RichEditor",
407                ));
408            };
409            if revision != editor.revision {
410                return Err(Error::InputRevision {
411                    current: editor.revision,
412                    incoming: revision,
413                });
414            }
415            editor.document.validate_selection(selection)?;
416            if !editor.enabled {
417                return Err(Error::Unsupported("rich editor is disabled"));
418            }
419        }
420        if let Self::PickFiles { revision, .. }
421        | Self::ClearFiles { revision, .. }
422        | Self::RemoveFile(FileToken { revision, .. }) = self
423        {
424            let Props::File(props) = node.props else {
425                return Err(Error::Unsupported("file action requires a File control"));
426            };
427            if revision != props.revision {
428                return Err(Error::InputRevision {
429                    current: props.revision,
430                    incoming: revision,
431                });
432            }
433            if !matches!(self, Self::ClearFiles { .. }) && !props.enabled {
434                return Err(Error::Unsupported("file control is disabled"));
435            }
436            if matches!(self, Self::PickFiles { request: 0, .. }) {
437                return Err(Error::InvalidProps("file picker request must be positive"));
438            }
439            if let Self::RemoveFile(file) = self {
440                file.validate()?;
441            }
442        }
443
444        if let Self::CopyText {
445            revision, request, ..
446        } = self
447        {
448            let source = node
449                .semantics
450                .as_ref()
451                .and_then(|s| s.clipboard.as_ref())
452                .ok_or(Error::Unsupported("button has no clipboard source"))?;
453            source.validate()?;
454            if !matches!(node.props, Props::Button(_))
455                || !node.props.enabled()
456                || node.semantics.as_ref().is_some_and(|s| s.disabled)
457            {
458                return Err(Error::Unsupported("clipboard requires an enabled Button"));
459            }
460            if revision != source.revision || request == 0 {
461                return Err(Error::InvalidProps(
462                    "clipboard request requires the exact source revision and a positive identity",
463                ));
464            }
465        }
466        if matches!(self, Self::RaiseLayer(_))
467            && (node.role != Some(Role::Dialog)
468                || node.hidden()
469                || !node
470                    .semantics
471                    .as_ref()
472                    .and_then(|s| s.layer.as_ref())
473                    .is_some_and(|layer| !layer.modal))
474        {
475            return Err(Error::Unsupported(
476                "raise requires an open nonmodal dialog layer",
477            ));
478        }
479        if let Self::SelectText {
480            revision,
481            selection,
482            ..
483        } = self
484        {
485            let Props::Input(input) = node.props else {
486                return Err(Error::Unsupported("text selection requires an Input"));
487            };
488            if revision != input.revision {
489                return Err(Error::InputRevision {
490                    current: input.revision,
491                    incoming: revision,
492                });
493            }
494            selection.byte_range(&input.value)?;
495        }
496        if matches!(self, Self::Focus(_))
497            && node.semantics.as_ref().is_some_and(|s| s.menubar_item)
498            && node.focus != FocusMode::TabStop
499        {
500            return Err(Error::Unsupported(
501                "menubar focus intent no longer names the current root",
502            ));
503        }
504        if matches!(self, Self::RevealOption { .. })
505            && !node.semantics.as_ref().is_some_and(|s| s.option.is_some())
506        {
507            return Err(Error::Unsupported(
508                "option reveal requires an intrinsic listbox option",
509            ));
510        }
511        if matches!(self, Self::Focus(_))
512            && (node.role == Some(Role::Listbox)
513                || node.semantics.as_ref().is_some_and(|s| s.option.is_some()))
514        {
515            return Err(Error::Unsupported(
516                "listbox options preserve combobox focus",
517            ));
518        }
519        if matches!(self, Self::ExitMenu { .. })
520            && (node.role != Some(Role::Menu)
521                || !node
522                    .semantics
523                    .as_ref()
524                    .and_then(|s| s.layer.as_ref())
525                    .is_some_and(|layer| {
526                        !layer.modal
527                            && (layer.return_focus.is_some()
528                                || matches!(layer.placement, LayerPlacement::ContextPoint(_))
529                                    && layer.anchor.is_some())
530                    }))
531        {
532            return Err(Error::Unsupported(
533                "menu exit requires a named nonmodal menu with a return target",
534            ));
535        }
536        if let Self::ScrollTo { x, y, .. } = self
537            && (!x.is_finite() || !y.is_finite() || x < 0.0 || y < 0.0)
538        {
539            return Err(Error::InvalidProps("invalid scroll position"));
540        }
541        if matches!(self, Self::Focus(_))
542            && node.role == Some(Role::Separator)
543            && !node
544                .semantics
545                .as_ref()
546                .is_some_and(|s| s.splitter.is_some())
547        {
548            return Err(Error::Unsupported("focus on passive separator"));
549        }
550        if matches!(self, Self::Focus(_)) && node.role == Some(Role::Tooltip) {
551            return Err(Error::Unsupported("focus on passive tooltip"));
552        }
553        if matches!(self, Self::Focus(_)) && node.role == Some(Role::ProgressBar) {
554            return Err(Error::Unsupported("focus on passive progress"));
555        }
556        if matches!(node.props, Props::Group) {
557            return Err(Error::Unsupported("group has no physical action target"));
558        }
559        if matches!(self, Self::Focus(_)) && !node.props.enabled() {
560            return Err(Error::Unsupported("focus on disabled control"));
561        }
562        if matches!(self, Self::Focus(_))
563            && matches!(&node.props, Props::Image(image) if image.alternative.is_none())
564        {
565            return Err(Error::Unsupported("focus on decorative image"));
566        }
567        if matches!(self, Self::Focus(_))
568            && matches!(node.props, Props::Graphic(graphic) if graphic.alternative.is_none())
569        {
570            return Err(Error::Unsupported("focus on decorative graphic"));
571        }
572        Ok(())
573    }
574}
575
576#[derive(Clone, Copy, Debug, Default, PartialEq)]
577pub struct Rect {
578    pub x: f64,
579    pub y: f64,
580    pub width: f64,
581    pub height: f64,
582}
583
584/// Logical collection navigation, independent of a host's key codes.
585#[derive(Clone, Copy, Debug, PartialEq, Eq)]
586pub enum Navigation {
587    Previous,
588    Next,
589    First,
590    Last,
591    PagePrevious,
592    PageNext,
593    /// Reveal the originating mounted row without moving keyboard focus.
594    /// A virtual-list root or an origin outside its rows has no destination.
595    Reveal,
596}
597
598#[derive(Clone, Debug, PartialEq)]
599pub enum QueryValue {
600    RichSelection(Box<RichSnapshot>),
601    FileBytes(Box<FileChunk>),
602    FilePreview(Option<Box<FilePreview>>),
603    ScrollMetrics(ScrollMetrics),
604    Focus(bool),
605    Bounds(Rect),
606    Scroll {
607        x: f64,
608        y: f64,
609    },
610    /// UTF-16 code-unit offsets, matching Web text controls. Native adapters must
611    /// convert their engine's byte/scalar/grapheme offsets at this boundary.
612    Selection {
613        start: usize,
614        end: usize,
615    },
616}
617
618#[derive(Clone, Debug, PartialEq)]
619pub enum Event {
620    RichCommand {
621        command: RichCommand,
622        revision: u64,
623    },
624    /// Current physical content exceeded the finite rich document grammar or
625    /// budgets. The host restores its accepted value before publishing this.
626    RichRejected {
627        revision: u64,
628    },
629    RichEdit(Box<RichSnapshot>),
630    RichSelection(Box<RichSnapshot>),
631    Files(Box<FileEvent>),
632    TreeNavigate {
633        from: NodeId,
634        command: TreeCommand,
635    },
636    Clipboard {
637        revision: u64,
638        request: u64,
639        outcome: ClipboardOutcome,
640    },
641    GridNavigate {
642        from: NodeId,
643        command: GridCommand,
644    },
645    InputEdit(InputEdit),
646    /// Terminal presentation observation; valid while the closing subtree is
647    /// logically hidden/inert, without admitting business input there.
648    CollapseComplete {
649        revision: u64,
650    },
651    PresenceComplete {
652        revision: u64,
653    },
654    ContextMenu {
655        from: NodeId,
656        point: ContextPoint,
657        source: ContextSource,
658    },
659    Sheet {
660        from: NodeId,
661        revision: u64,
662        command: SheetCommand,
663    },
664    NavigationPanel {
665        from: NodeId,
666        command: NavigationPanelCommand,
667    },
668    Spin {
669        from: NodeId,
670        command: RangeCommand,
671    },
672    Range {
673        from: NodeId,
674        command: RangeCommand,
675    },
676    ScrollKeyboard {
677        from: NodeId,
678        command: ScrollCommand,
679    },
680    /// Terminal observation for one program-selected image request.
681    ImageStatus {
682        revision: u64,
683        status: ImageStatus,
684    },
685    Menu {
686        from: NodeId,
687        command: MenuCommand,
688    },
689    Pointer {
690        from: NodeId,
691        related: Option<NodeId>,
692        phase: PointerPhase,
693    },
694    /// Logical boundary observation derived from a physical pointer origin.
695    PointerWithin {
696        from: NodeId,
697        related: Option<NodeId>,
698        phase: PointerPhase,
699    },
700    /// Native form default behavior is cancelled before this queued request.
701    /// None represents a programmatic request or implicit keyboard submission.
702    Submit {
703        submitter: Option<NodeId>,
704    },
705    Reset,
706    Activate,
707    /// An activation of an explicitly declared target in a display instance.
708    DisplayClick(u16),
709    /// A request only: the application may keep controlled state open.
710    Dismiss(DismissReason),
711    /// Host preference, independent of an application's explicit appearance.
712    ColorSchemeChanged {
713        dark: bool,
714    },
715    /// Physical origin remains explicit while App routes to the nearest observer.
716    Keyboard {
717        from: NodeId,
718        command: KeyboardCommand,
719    },
720    /// Only the explicit palette chord; other application commands stay native.
721    Palette {
722        from: NodeId,
723    },
724    /// Start/Move/Cancel target the source. Drop targets a live accepting node.
725    Swipe {
726        from: NodeId,
727        phase: DragPhase,
728        x: f64,
729        y: f64,
730        revision: u64,
731    },
732    Drag {
733        from: NodeId,
734        phase: DragPhase,
735        x: f64,
736        y: f64,
737    },
738    ValueChanged {
739        value: String,
740        composing: bool,
741        revision: u64,
742    },
743    Commit {
744        value: String,
745        revision: u64,
746    },
747    CheckedChanged(bool),
748    Tags {
749        from: NodeId,
750        revision: u64,
751        command: TagsCommand,
752    },
753    Choice {
754        from: NodeId,
755        command: ChoiceCommand,
756    },
757    SelectChanged {
758        keys: Vec<SemanticId>,
759        revision: u64,
760    },
761    /// Direct focus origin. Hosts report this even if only an ancestor has a
762    /// FocusWithin interest; App derives the logical ancestor observations.
763    FocusChanged(bool),
764    /// Focus transition originating at `node`, delivered to observing logical
765    /// ancestors (including boxless Groups). FocusChanged itself stays direct.
766    FocusWithin {
767        node: NodeId,
768        focused: bool,
769    },
770    /// Origin stays explicit when routed to the nearest logical observer.
771    Navigate {
772        from: NodeId,
773        command: Navigation,
774    },
775    Typeahead {
776        from: NodeId,
777        text: String,
778        at_millis: u64,
779    },
780    Composition {
781        active: bool,
782    },
783    Scroll {
784        x: f64,
785        y: f64,
786        viewport: Rect,
787        /// Last accepted assignment, separate from current x/y (which may
788        /// already include native movement). None before any host assignment.
789        ack: Option<ScrollAck>,
790    },
791    /// Border-box size and client viewport are distinct (borders/scrollbars).
792    /// Size uses local x/y=0; adapters preserve fractional layout dimensions.
793    Resize {
794        size: Rect,
795        viewport: Rect,
796    },
797    /// Restore an existing visible row and its pixel inset at host handover.
798    Anchor {
799        row: NodeId,
800        within: f64,
801        viewport: Rect,
802    },
803}
804
805#[derive(Clone, Copy, Debug, PartialEq)]
806pub struct ScrollRequest {
807    pub x: f64,
808    pub y: f64,
809}
810/// Last accepted programmatic assignment, retained on later observations so
811/// native movement before the first acknowledgement is still distinguishable.
812#[derive(Clone, Copy, Debug, PartialEq)]
813pub struct ScrollAck {
814    pub requested: ScrollRequest,
815    pub x: f64,
816    pub y: f64,
817}
818
819#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
820pub enum EventKind {
821    DisplayClick,
822    RichCommand,
823    RichRejected,
824    RichEdit,
825    RichSelection,
826    Files,
827    TreeNavigate,
828    Clipboard,
829    GridNavigate,
830    InputEdit,
831    CollapseComplete,
832    PresenceComplete,
833    ContextMenu,
834    Tags,
835    Sheet,
836    NavigationPanel,
837    Spin,
838    Range,
839    ScrollKeyboard,
840    ImageStatus,
841    Menu,
842    Pointer,
843    PointerWithin,
844    Submit,
845    Reset,
846    Activate,
847    Dismiss,
848    ColorSchemeChanged,
849    Keyboard,
850    Palette,
851    Swipe,
852    Drag,
853    ValueChanged,
854    Commit,
855    CheckedChanged,
856    SelectChanged,
857    Choice,
858    FocusChanged,
859    FocusWithin,
860    Navigate,
861    Typeahead,
862    Composition,
863    Scroll,
864    Resize,
865    Anchor,
866}
867/// Finite event targets of one opaque display instance, not element identities.
868#[derive(Clone, Debug)]
869pub struct DisplayEvents(pub Vec<u16>);
870
871impl EventKind {
872    /// Logical bubbling/ancestor observations can target Groups; direct physical
873    /// observations cannot. Recording a valid interest does not promise the host
874    /// can produce it (SSR records handlers for later browser adoption).
875    pub fn validate_target<'a>(self, node: impl Into<DescriptorView<'a>>) -> Result<(), Error> {
876        let node = node.into();
877        if self == Self::DisplayClick
878            && (!matches!(node.props, Props::Group)
879                || node.options.get::<DisplayEvents>().is_none())
880        {
881            return Err(Error::InvalidEvent(
882                "display activation requires a declared instance",
883            ));
884        }
885        if matches!(
886            self,
887            Self::RichEdit | Self::RichSelection | Self::RichRejected | Self::RichCommand
888        ) && !matches!(node.props, Props::RichEditor(_))
889        {
890            return Err(Error::InvalidProps(
891                "rich observations require a RichEditor",
892            ));
893        }
894        if self == Self::Swipe
895            && (!matches!(node.props, Props::View)
896                || node
897                    .semantics
898                    .as_ref()
899                    .is_none_or(|s| s.swipe_capture.is_none()))
900        {
901            return Err(Error::InvalidProps(
902                "swipe observations require a declared View capture",
903            ));
904        }
905        if self == Self::Files && !matches!(node.props, Props::File(_)) {
906            return Err(Error::InvalidProps(
907                "file observations require a File control",
908            ));
909        }
910
911        if self == Self::TreeNavigate
912            && (node.role != Some(Role::Tree)
913                || !matches!(node.props, Props::View)
914                || node
915                    .semantics
916                    .as_ref()
917                    .is_none_or(|s| s.tree_navigation.is_none()))
918        {
919            return Err(Error::InvalidProps(
920                "tree navigation requires an opted-in Tree View",
921            ));
922        }
923        if self == Self::Clipboard
924            && (!matches!(node.props, Props::Button(_))
925                || node
926                    .semantics
927                    .as_ref()
928                    .is_none_or(|s| s.clipboard.is_none()))
929        {
930            return Err(Error::Unsupported(
931                "clipboard observation requires a declared Button source",
932            ));
933        }
934        if self == Self::GridNavigate
935            && (node.role != Some(Role::Grid)
936                || !matches!(node.props, Props::View)
937                || !node
938                    .semantics
939                    .as_ref()
940                    .is_some_and(|s| s.grid_navigation.is_some()))
941        {
942            return Err(Error::InvalidProps(
943                "grid navigation requires an opted-in Grid View",
944            ));
945        }
946        if self == Self::InputEdit
947            && !matches!(node.props,Props::Input(p) if !p.multiline&&node.semantics.as_ref().is_some_and(|s|s.input_edit.is_some()))
948        {
949            return Err(Error::Unsupported(
950                "InputEdit requires an opted-in single-line Input",
951            ));
952        }
953        if self == Self::PresenceComplete
954            && (!matches!(node.props, Props::View)
955                || !node
956                    .semantics
957                    .as_ref()
958                    .is_some_and(|s| s.presence.is_some()))
959        {
960            return Err(Error::InvalidProps(
961                "presence completion requires a presence View",
962            ));
963        }
964        if self == Self::CollapseComplete
965            && (!matches!(node.props, Props::View)
966                || !node
967                    .semantics
968                    .as_ref()
969                    .is_some_and(|s| s.collapse.is_some()))
970        {
971            return Err(Error::InvalidProps(
972                "collapse completion requires a collapse View",
973            ));
974        }
975        if self == Self::ContextMenu
976            && (!matches!(node.props, Props::View)
977                || !node
978                    .semantics
979                    .as_ref()
980                    .is_some_and(|s| s.context_menu.is_some()))
981        {
982            return Err(Error::InvalidProps(
983                "context requests require an opted-in region view",
984            ));
985        }
986        if self == Self::Tags
987            && !matches!(node.props,Props::Input(input) if !input.multiline && node.semantics.as_ref().is_some_and(|s|s.tags_input.is_some()))
988        {
989            return Err(Error::InvalidProps(
990                "tags commands require an opted-in single-line input",
991            ));
992        }
993        if self == Self::Sheet && !matches!(node.props, Props::View) {
994            return Err(Error::InvalidProps("sheet commands require a view"));
995        }
996        if self == Self::NavigationPanel
997            && !matches!(node.props, Props::Button(_) | Props::Link(_) | Props::View)
998        {
999            return Err(Error::InvalidProps(
1000                "navigation panel commands require a physical navigation control or content view",
1001            ));
1002        }
1003        if self == Self::Spin
1004            && !matches!(node.props, Props::Input(p) if !p.multiline && node.semantics.as_ref().is_some_and(|s| s.spinbutton.is_some()))
1005        {
1006            return Err(Error::InvalidProps(
1007                "spin commands require an opted-in single-line input",
1008            ));
1009        }
1010        if self == Self::Range
1011            && (!matches!(node.props, Props::View)
1012                || !matches!(node.role, Some(Role::Separator | Role::Slider)))
1013        {
1014            return Err(Error::InvalidProps(
1015                "range commands require a slider or splitter separator",
1016            ));
1017        }
1018        if self == Self::Choice
1019            && !node
1020                .semantics
1021                .as_ref()
1022                .is_some_and(|s| s.combobox.is_some())
1023        {
1024            return Err(Error::InvalidProps("choice commands require a combobox"));
1025        }
1026        if self == Self::SelectChanged && !matches!(node.props, Props::Select(_)) {
1027            return Err(Error::InvalidProps("selection event requires a select"));
1028        }
1029        if self == Self::ScrollKeyboard && !matches!(node.props, Props::View) {
1030            return Err(Error::InvalidProps(
1031                "scroll keyboard requires a viewport view",
1032            ));
1033        }
1034        if self == Self::ImageStatus && !matches!(node.props, Props::Image(_)) {
1035            return Err(Error::InvalidProps("image status requires an image"));
1036        }
1037        if matches!(self, Self::Submit | Self::Reset) && node.field_part() != Some(FieldPart::Form)
1038        {
1039            return Err(Error::InvalidProps("form request requires a form"));
1040        }
1041        if matches!(
1042            node.role,
1043            Some(Role::Separator | Role::Tooltip | Role::ProgressBar)
1044        ) && matches!(
1045            self,
1046            Self::Activate
1047                | Self::Keyboard
1048                | Self::Palette
1049                | Self::ScrollKeyboard
1050                | Self::Drag
1051                | Self::Navigate
1052                | Self::Typeahead
1053                | Self::Menu
1054                | Self::NavigationPanel
1055                | Self::Range
1056        ) && !(node.role == Some(Role::Separator)
1057            && node
1058                .semantics
1059                .as_ref()
1060                .is_some_and(|s| s.splitter.is_some())
1061            && matches!(self, Self::Range | Self::Drag))
1062        {
1063            return Err(Error::Unsupported("passive separator has no interaction"));
1064        }
1065        // Interests may be registered before layer metadata bindings run.
1066        if self == Self::Dismiss && !matches!(node.props, Props::View) {
1067            return Err(Error::InvalidProps("dismiss requires a view"));
1068        }
1069        if matches!(self, Self::Drag | Self::ColorSchemeChanged)
1070            && !matches!(node.props, Props::View)
1071        {
1072            return Err(Error::Unsupported(
1073                "host observation requires a semantic View",
1074            ));
1075        }
1076        if self == Self::Palette
1077            && matches!(
1078                node.props,
1079                Props::Group | Props::Input(_) | Props::Select(_)
1080            )
1081        {
1082            return Err(Error::Unsupported(
1083                "palette shortcut requires a non-editor physical scope or origin",
1084            ));
1085        }
1086        if matches!(self, Self::ValueChanged | Self::Commit)
1087            && !matches!(node.props, Props::Input(_))
1088            || self == Self::Composition
1089                && !matches!(node.props, Props::Input(_) | Props::RichEditor(_))
1090            || matches!(self, Self::CheckedChanged) && !matches!(node.props, Props::Check(_))
1091        {
1092            return Err(Error::InvalidProps("event does not belong to this control"));
1093        }
1094        if matches!(node.props, Props::Group)
1095            && matches!(
1096                self,
1097                Self::Resize
1098                    | Self::Scroll
1099                    | Self::Anchor
1100                    | Self::FocusChanged
1101                    | Self::Drag
1102                    | Self::Pointer
1103            )
1104        {
1105            return Err(Error::Unsupported("group has no physical event target"));
1106        }
1107        Ok(())
1108    }
1109}
1110
1111impl Event {
1112    /// User input is suppressed by inherited inert regions. Resource/layout
1113    /// observations and terminal cleanup remain available to live Owners.
1114    pub fn is_user_interaction(&self) -> bool {
1115        !self.is_terminal_loss()
1116            && !matches!(
1117                self,
1118                Self::Clipboard { .. }
1119                    | Self::ImageStatus { .. }
1120                    | Self::ColorSchemeChanged { .. }
1121                    | Self::Scroll { .. }
1122                    | Self::Resize { .. }
1123                    | Self::Anchor { .. }
1124            )
1125    }
1126    /// Cleanup observations still reach live scopes after suspension. Retired
1127    /// identities never become valid again because an event is terminal.
1128    pub fn is_terminal_loss(&self) -> bool {
1129        if let Self::Files(event) = self {
1130            return !matches!(event.outcome, FileOutcome::Selected(_));
1131        }
1132        matches!(
1133            self,
1134            Self::Clipboard { .. }
1135                | Self::CollapseComplete { .. }
1136                | Self::PresenceComplete { .. }
1137                | Self::FocusChanged(false)
1138                | Self::Composition { active: false }
1139                | Self::FocusWithin { focused: false, .. }
1140                | Self::Swipe {
1141                    phase: DragPhase::Cancel,
1142                    ..
1143                }
1144                | Self::Drag {
1145                    phase: DragPhase::Cancel,
1146                    ..
1147                }
1148                | Self::Pointer {
1149                    phase: PointerPhase::Leave,
1150                    ..
1151                }
1152                | Self::PointerWithin {
1153                    phase: PointerPhase::Leave,
1154                    ..
1155                }
1156        )
1157    }
1158
1159    pub(crate) fn origin(&self) -> Option<NodeId> {
1160        match self {
1161            Self::TreeNavigate { from, .. } => Some(*from),
1162            Self::GridNavigate { from, .. } => Some(*from),
1163            Self::ContextMenu { from, .. } => Some(*from),
1164            Self::Tags { from, .. } => Some(*from),
1165            Self::Submit { submitter } => *submitter,
1166            Self::FocusWithin { node, .. } => Some(*node),
1167            Self::Navigate { from, .. } => Some(*from),
1168            Self::Menu { from, .. }
1169            | Self::Pointer { from, .. }
1170            | Self::PointerWithin { from, .. } => Some(*from),
1171            Self::Typeahead { from, .. } => Some(*from),
1172            Self::Choice { from, .. } | Self::Keyboard { from, .. } | Self::Palette { from } => {
1173                Some(*from)
1174            }
1175            Self::ScrollKeyboard { from, .. } => Some(*from),
1176            Self::Spin { from, .. } | Self::Range { from, .. } => Some(*from),
1177            Self::Sheet { from, .. } => Some(*from),
1178            Self::NavigationPanel { from, .. } => Some(*from),
1179            Self::Swipe { from, .. } | Self::Drag { from, .. } => Some(*from),
1180            Self::Anchor { row, .. } => Some(*row),
1181            _ => None,
1182        }
1183    }
1184
1185    /// Check typed host input before business handlers. Embedded identities'
1186    /// liveness/ancestry require a tree and are checked by Memory::validate_event.
1187    /// Scroll offsets may be negative; local geometry must have x/y=0.
1188    pub fn validate_payload<'a>(
1189        &self,
1190        target: NodeId,
1191        node: impl Into<DescriptorView<'a>>,
1192    ) -> Result<(), Error> {
1193        self.validate_payload_view(target, node.into())
1194    }
1195
1196    // One implementation for live descriptors and borrowed construction values;
1197    // conversion at the API boundary should not duplicate all event validation.
1198    fn validate_payload_view(&self, target: NodeId, node: DescriptorView<'_>) -> Result<(), Error> {
1199        if let Self::DisplayClick(slot) = self
1200            && (*slot >= 256
1201                || !node
1202                    .options
1203                    .get::<DisplayEvents>()
1204                    .is_some_and(|events| events.0.contains(slot)))
1205        {
1206            return Err(Error::InvalidEvent("undeclared display activation slot"));
1207        }
1208        if let Self::RichRejected { revision } | Self::RichCommand { revision, .. } = self {
1209            let Props::RichEditor(editor) = node.props else {
1210                return Err(Error::InvalidEvent("rich rejection requires its editor"));
1211            };
1212            if *revision > editor.revision {
1213                return Err(Error::InputRevision {
1214                    current: editor.revision,
1215                    incoming: *revision,
1216                });
1217            }
1218        }
1219        if let Self::RichEdit(snapshot) | Self::RichSelection(snapshot) = self {
1220            let Props::RichEditor(editor) = node.props else {
1221                return Err(Error::InvalidEvent("rich input requires its RichEditor"));
1222            };
1223            snapshot.validate_input(editor)?;
1224        }
1225        if let Self::Swipe {
1226            from,
1227            x,
1228            y,
1229            revision,
1230            ..
1231        } = self
1232        {
1233            EventKind::Swipe.validate_target(node)?;
1234            if from.runtime() != target.runtime() {
1235                return Err(Error::ForeignRuntime);
1236            }
1237            if *from != target || !x.is_finite() || !y.is_finite() {
1238                return Err(Error::InvalidEvent(
1239                    "swipe requires its exact finite boxed origin",
1240                ));
1241            }
1242            let capture = node
1243                .semantics
1244                .as_ref()
1245                .and_then(|s| s.swipe_capture)
1246                .expect("validated swipe capture");
1247            if *revision > capture.revision {
1248                return Err(Error::InputRevision {
1249                    current: capture.revision,
1250                    incoming: *revision,
1251                });
1252            }
1253        }
1254        if let Self::Files(event) = self {
1255            let Props::File(props) = node.props else {
1256                return Err(Error::InvalidEvent(
1257                    "file observations require a File control",
1258                ));
1259            };
1260            event.validate_node(target, props)?;
1261        }
1262
1263        if let Self::TreeNavigate { from, command } = self {
1264            EventKind::TreeNavigate.validate_target(node)?;
1265            command.validate()?;
1266            if from.runtime() != target.runtime() {
1267                return Err(Error::ForeignRuntime);
1268            }
1269            if *from == target {
1270                return Err(Error::InvalidEvent(
1271                    "tree command requires a descendant TreeItem",
1272                ));
1273            }
1274            if matches!(command, TreeCommand::Search { .. })
1275                && node
1276                    .semantics
1277                    .as_ref()
1278                    .and_then(|s| s.tree_navigation)
1279                    .is_none_or(|s| !s.typeahead)
1280            {
1281                return Err(Error::InvalidEvent("tree search is not enabled"));
1282            }
1283        }
1284        if let Self::Clipboard {
1285            revision, request, ..
1286        } = self
1287        {
1288            EventKind::Clipboard.validate_target(node)?;
1289            let source = node
1290                .semantics
1291                .as_ref()
1292                .and_then(|s| s.clipboard.as_ref())
1293                .expect("validated source");
1294            if *request == 0 || *revision > source.revision {
1295                return Err(Error::InvalidEvent(
1296                    "clipboard completion has a future revision or zero request",
1297                ));
1298            }
1299        }
1300        if let Self::GridNavigate { from, .. } = self {
1301            EventKind::GridNavigate.validate_target(node)?;
1302            if from.runtime() != target.runtime() {
1303                return Err(Error::ForeignRuntime);
1304            }
1305            if *from == target {
1306                return Err(Error::InvalidEvent(
1307                    "grid navigation requires a real descendant Button",
1308                ));
1309            }
1310        }
1311        if let Self::InputEdit(edit) = self {
1312            EventKind::InputEdit.validate_target(node)?;
1313            let capture = node
1314                .semantics
1315                .as_ref()
1316                .and_then(|s| s.input_edit)
1317                .ok_or(Error::InvalidEvent("input edit capture is absent"))?;
1318            edit.validate(capture)?;
1319            if let Props::Input(input) = node.props
1320                && edit.revision() > input.revision
1321            {
1322                return Err(Error::InputRevision {
1323                    current: input.revision,
1324                    incoming: edit.revision(),
1325                });
1326            }
1327        }
1328        if let Self::PresenceComplete { revision } = self {
1329            let config = node
1330                .semantics
1331                .as_ref()
1332                .and_then(|s| s.presence.as_ref())
1333                .ok_or(Error::InvalidEvent(
1334                    "presence completion requires a presence View",
1335                ))?;
1336            if *revision > config.revision {
1337                return Err(Error::PresenceRevision {
1338                    current: config.revision,
1339                    incoming: *revision,
1340                });
1341            }
1342        }
1343        if let Self::CollapseComplete { revision } = self {
1344            let config = node
1345                .semantics
1346                .as_ref()
1347                .and_then(|s| s.collapse.as_ref())
1348                .ok_or(Error::InvalidEvent(
1349                    "collapse completion requires a collapse View",
1350                ))?;
1351            if *revision > config.revision {
1352                return Err(Error::CollapseRevision {
1353                    current: config.revision,
1354                    incoming: *revision,
1355                });
1356            }
1357        }
1358        if let Self::Sheet {
1359            from,
1360            revision,
1361            command,
1362        } = self
1363        {
1364            if from.runtime() != target.runtime() {
1365                return Err(Error::ForeignRuntime);
1366            }
1367            let config = node
1368                .semantics
1369                .as_ref()
1370                .and_then(|s| s.layer.as_ref())
1371                .and_then(|layer| layer.sheet.as_ref())
1372                .ok_or(Error::InvalidEvent("sheet command requires a sheet"))?;
1373            if *from != target {
1374                return Err(Error::InvalidEvent(
1375                    "sheet command origin must equal its target",
1376                ));
1377            }
1378            if *revision > config.revision {
1379                return Err(Error::SheetRevision {
1380                    current: config.revision,
1381                    incoming: *revision,
1382                });
1383            }
1384            if *revision == config.revision
1385                && match command {
1386                    SheetCommand::Snap(index) => *index >= config.fractions.len(),
1387                    SheetCommand::Dismiss => !config.dismissible,
1388                }
1389            {
1390                return Err(Error::InvalidEvent(
1391                    "sheet command exceeds its accepted configuration",
1392                ));
1393            }
1394        }
1395        if let Self::Dismiss(reason) = self {
1396            let layer = node
1397                .semantics
1398                .as_ref()
1399                .and_then(|s| s.layer.as_ref())
1400                .ok_or(Error::InvalidEvent("dismiss requires a layer"))?;
1401            if !match reason {
1402                DismissReason::Gesture => {
1403                    layer.sheet.as_ref().is_some_and(|sheet| sheet.dismissible)
1404                }
1405                DismissReason::Escape => layer.escape,
1406                DismissReason::Outside => layer.outside,
1407                DismissReason::AnchorLost => layer.anchor.is_some(),
1408            } {
1409                return Err(Error::InvalidEvent("disabled layer dismissal"));
1410            }
1411        }
1412        if self
1413            .origin()
1414            .is_some_and(|id| id.runtime() != target.runtime())
1415        {
1416            return Err(Error::ForeignRuntime);
1417        }
1418        self.kind().validate_target(node)?;
1419        if matches!(
1420            self,
1421            Self::Choice {
1422                command: ChoiceCommand::RemoveLast,
1423                ..
1424            }
1425        ) && node.semantics.as_ref().and_then(|value| value.combobox)
1426            != Some(ComboboxKind::Multiple)
1427        {
1428            return Err(Error::InvalidEvent(
1429                "remove-last requires a multiple combobox",
1430            ));
1431        }
1432        let local = |rect: &Rect| {
1433            rect.x == 0.0
1434                && rect.y == 0.0
1435                && rect.width.is_finite()
1436                && rect.height.is_finite()
1437                && rect.width >= 0.0
1438                && rect.height >= 0.0
1439        };
1440        match self {
1441            Self::ContextMenu { from, point, .. } => {
1442                if from.runtime() != target.runtime() {
1443                    return Err(Error::ForeignRuntime);
1444                }
1445                point.validate()?;
1446                EventKind::ContextMenu.validate_target(node)?;
1447            }
1448            Self::Spin { from, command } => {
1449                EventKind::Spin.validate_target(node)?;
1450                if *from != target {
1451                    return Err(Error::InvalidEvent(
1452                        "spin command requires its physical origin",
1453                    ));
1454                }
1455                let spin = node
1456                    .semantics
1457                    .as_ref()
1458                    .filter(|s| !s.disabled && !s.readonly && node.props.enabled())
1459                    .and_then(|s| s.spinbutton.as_ref())
1460                    .ok_or(Error::InvalidEvent(
1461                        "spin command requires an enabled writable input",
1462                    ))?;
1463                spin.validate_command(*command)?;
1464            }
1465            Self::Range { from, command } => {
1466                let range = node
1467                    .semantics
1468                    .as_ref()
1469                    .filter(|s| !s.disabled)
1470                    .and_then(|s| {
1471                        s.splitter
1472                            .or_else(|| s.slider.as_ref().map(|slider| slider.range))
1473                    })
1474                    .ok_or(Error::InvalidEvent(
1475                        "range command requires an enabled slider or splitter",
1476                    ))?;
1477                if *from != target {
1478                    return Err(Error::InvalidEvent(
1479                        "range command requires its physical origin",
1480                    ));
1481                }
1482                command.validate(range)?;
1483            }
1484            Self::Choice { from, .. } => {
1485                if *from != target {
1486                    return Err(Error::InvalidEvent(
1487                        "choice command requires the combobox physical origin",
1488                    ));
1489                }
1490            }
1491            Self::ScrollKeyboard { from, command } => {
1492                if *from != target
1493                    || !node
1494                        .semantics
1495                        .as_ref()
1496                        .and_then(|s| s.scroll_keyboard)
1497                        .is_some_and(|axes| axes.allows(command.axis))
1498                {
1499                    return Err(Error::InvalidEvent(
1500                        "scroll keyboard requires its opted-in physical viewport and axis",
1501                    ));
1502                }
1503            }
1504            Self::PointerWithin { related, .. } => {
1505                if related.is_some_and(|related| related.runtime() != target.runtime()) {
1506                    return Err(Error::ForeignRuntime);
1507                }
1508            }
1509            Self::NavigationPanel { from, command } => {
1510                if *from != target || matches!(node.props, Props::Group) {
1511                    return Err(Error::InvalidEvent(
1512                        "navigation panel requires its exact physical origin",
1513                    ));
1514                }
1515                let marker = node.semantics.as_ref().and_then(|s| s.navigation_panel);
1516                let member = node.semantics.as_ref().is_some_and(|s| s.navigation_item);
1517                if *command == NavigationPanelCommand::Close {
1518                    if !member && marker != Some(NavigationPanel::Content) {
1519                        return Err(Error::InvalidEvent(
1520                            "navigation close requires a content member",
1521                        ));
1522                    }
1523                } else if marker != Some(NavigationPanel::Trigger) {
1524                    return Err(Error::InvalidEvent(
1525                        "navigation entry requires a disclosure trigger",
1526                    ));
1527                }
1528            }
1529            Self::Menu { from, .. } | Self::Pointer { from, .. } => {
1530                if *from != target || matches!(node.props, Props::Group) {
1531                    return Err(Error::InvalidEvent(
1532                        "menu/pointer requires its physical origin",
1533                    ));
1534                }
1535                if matches!(self, Self::Menu { .. })
1536                    && node.role != Some(Role::Menu)
1537                    && !node.semantics.as_ref().is_some_and(|s| {
1538                        s.menu_item.is_some()
1539                            || s.menu_search.is_some()
1540                            || s.popup == Some(PopupKind::Menu)
1541                    })
1542                {
1543                    return Err(Error::InvalidEvent(
1544                        "menu command requires a menu or menu trigger/item",
1545                    ));
1546                }
1547                if matches!(
1548                    self,
1549                    Self::Menu {
1550                        command: MenuCommand::SearchNext
1551                            | MenuCommand::SearchPrevious
1552                            | MenuCommand::SearchCommit,
1553                        ..
1554                    }
1555                ) && node
1556                    .semantics
1557                    .as_ref()
1558                    .is_none_or(|s| s.menu_search.is_none())
1559                {
1560                    return Err(Error::InvalidEvent(
1561                        "search commands require a declared menu search editor",
1562                    ));
1563                }
1564                if node
1565                    .semantics
1566                    .as_ref()
1567                    .is_some_and(|s| s.menu_search.is_some())
1568                    && matches!(self, Self::Menu { command, .. } if !matches!(command, MenuCommand::SearchNext | MenuCommand::SearchPrevious | MenuCommand::SearchCommit | MenuCommand::Exit { .. }))
1569                {
1570                    return Err(Error::InvalidEvent(
1571                        "menu search editors accept search navigation and exit commands only",
1572                    ));
1573                }
1574                if let Self::Pointer {
1575                    related: Some(related),
1576                    ..
1577                } = self
1578                    && related.runtime() != target.runtime()
1579                {
1580                    return Err(Error::ForeignRuntime);
1581                }
1582            }
1583            Self::Typeahead {
1584                from,
1585                text,
1586                at_millis,
1587            } => {
1588                if *from != target || matches!(node.props, Props::Group) {
1589                    return Err(Error::InvalidEvent(
1590                        "typeahead requires its physical origin",
1591                    ));
1592                }
1593                validate_typeahead(text, *at_millis)?;
1594            }
1595            Self::Drag { from, phase, x, y } => {
1596                if !x.is_finite() || !y.is_finite() {
1597                    return Err(Error::InvalidEvent("drag coordinates must be finite"));
1598                }
1599                if *phase != DragPhase::Drop && *from != target {
1600                    return Err(Error::InvalidEvent("drag phase requires source target"));
1601                }
1602            }
1603            Self::Keyboard { from, command } => {
1604                if *from != target || matches!(node.props, Props::Group) {
1605                    return Err(Error::InvalidEvent("keyboard requires its physical origin"));
1606                }
1607                if *command == KeyboardCommand::Submit && !matches!(node.props, Props::Input(_)) {
1608                    return Err(Error::InvalidEvent("submit requires a text control"));
1609                }
1610            }
1611            Self::Palette { from } => {
1612                if from.runtime() != target.runtime() {
1613                    return Err(Error::ForeignRuntime);
1614                }
1615                if *from != target {
1616                    return Err(Error::InvalidEvent(
1617                        "palette shortcut requires its physical origin",
1618                    ));
1619                }
1620                EventKind::Palette.validate_target(node)?;
1621            }
1622            Self::Navigate { from, .. } if *from != target => {
1623                return Err(Error::InvalidEvent(
1624                    "navigation origin must match its event target",
1625                ));
1626            }
1627            Self::Scroll {
1628                x,
1629                y,
1630                viewport,
1631                ack,
1632            } => {
1633                if !x.is_finite() || !y.is_finite() || !local(viewport) {
1634                    return Err(Error::InvalidEvent("invalid scroll geometry"));
1635                }
1636                if ack.is_some_and(|ack| {
1637                    !ack.requested.x.is_finite()
1638                        || !ack.requested.y.is_finite()
1639                        || ack.requested.x < 0.0
1640                        || ack.requested.y < 0.0
1641                        || !ack.x.is_finite()
1642                        || !ack.y.is_finite()
1643                }) {
1644                    return Err(Error::InvalidEvent("invalid scroll acknowledgement"));
1645                }
1646            }
1647            Self::Resize { size, viewport } if !local(size) || !local(viewport) => {
1648                return Err(Error::InvalidEvent("invalid resize geometry"));
1649            }
1650            Self::Anchor {
1651                within, viewport, ..
1652            } if !within.is_finite() || *within < 0.0 || !local(viewport) => {
1653                return Err(Error::InvalidEvent("invalid anchor geometry"));
1654            }
1655            Self::SelectChanged { keys, revision } => {
1656                if let Props::Select(select) = node.props {
1657                    select.validate_user_selection(keys)?;
1658                    if *revision > select.selection.revision {
1659                        return Err(Error::SelectRevision {
1660                            current: select.selection.revision,
1661                            incoming: *revision,
1662                        });
1663                    }
1664                }
1665            }
1666            Self::ImageStatus { revision, .. } => {
1667                if let Props::Image(image) = node.props
1668                    && *revision > image.revision
1669                {
1670                    return Err(Error::ImageRevision {
1671                        current: image.revision,
1672                        incoming: *revision,
1673                    });
1674                }
1675            }
1676            Self::ValueChanged {
1677                value, revision, ..
1678            }
1679            | Self::Commit { value, revision } => {
1680                if matches!(&node.props, Props::Input(input) if !input.multiline && value.contains(['\r', '\n']))
1681                {
1682                    return Err(Error::InvalidEvent(
1683                        "single-line input event cannot contain line breaks",
1684                    ));
1685                }
1686                if value.contains(['\0', '\r']) {
1687                    return Err(Error::InvalidEvent("input event text is not normalized"));
1688                }
1689                if let Props::Input(input) = &node.props
1690                    && *revision > input.revision
1691                {
1692                    return Err(Error::InputRevision {
1693                        current: input.revision,
1694                        incoming: *revision,
1695                    });
1696                }
1697            }
1698            Self::Tags {
1699                from,
1700                revision,
1701                command,
1702            } => {
1703                if *from != target {
1704                    return Err(Error::InvalidEvent(
1705                        "tags command requires its exact input origin",
1706                    ));
1707                }
1708                command.validate()?;
1709                if let Props::Input(input) = node.props
1710                    && *revision > input.revision
1711                {
1712                    return Err(Error::InputRevision {
1713                        current: input.revision,
1714                        incoming: *revision,
1715                    });
1716                }
1717            }
1718            _ => {}
1719        }
1720        Ok(())
1721    }
1722
1723    pub fn kind(&self) -> EventKind {
1724        match self {
1725            Self::RichCommand { .. } => EventKind::RichCommand,
1726            Self::RichRejected { .. } => EventKind::RichRejected,
1727            Self::TreeNavigate { .. } => EventKind::TreeNavigate,
1728            Self::Files(_) => EventKind::Files,
1729            Self::Clipboard { .. } => EventKind::Clipboard,
1730            Self::GridNavigate { .. } => EventKind::GridNavigate,
1731            Self::InputEdit(_) => EventKind::InputEdit,
1732            Self::CollapseComplete { .. } => EventKind::CollapseComplete,
1733            Self::PresenceComplete { .. } => EventKind::PresenceComplete,
1734            Self::ContextMenu { .. } => EventKind::ContextMenu,
1735            Self::Tags { .. } => EventKind::Tags,
1736            Self::Spin { .. } => EventKind::Spin,
1737            Self::Range { .. } => EventKind::Range,
1738            Self::Sheet { .. } => EventKind::Sheet,
1739            Self::NavigationPanel { .. } => EventKind::NavigationPanel,
1740            Self::ScrollKeyboard { .. } => EventKind::ScrollKeyboard,
1741            Self::ImageStatus { .. } => EventKind::ImageStatus,
1742            Self::Menu { .. } => EventKind::Menu,
1743            Self::Pointer { .. } => EventKind::Pointer,
1744            Self::PointerWithin { .. } => EventKind::PointerWithin,
1745            Self::Submit { .. } => EventKind::Submit,
1746            Self::Reset => EventKind::Reset,
1747            Self::Activate => EventKind::Activate,
1748            Self::DisplayClick(_) => EventKind::DisplayClick,
1749            Self::Dismiss(_) => EventKind::Dismiss,
1750            Self::ColorSchemeChanged { .. } => EventKind::ColorSchemeChanged,
1751            Self::Keyboard { .. } => EventKind::Keyboard,
1752            Self::Palette { .. } => EventKind::Palette,
1753            Self::RichEdit(_) => EventKind::RichEdit,
1754            Self::RichSelection(_) => EventKind::RichSelection,
1755            Self::Swipe { .. } => EventKind::Swipe,
1756            Self::Drag { .. } => EventKind::Drag,
1757            Self::ValueChanged { .. } => EventKind::ValueChanged,
1758            Self::Commit { .. } => EventKind::Commit,
1759            Self::CheckedChanged(_) => EventKind::CheckedChanged,
1760            Self::SelectChanged { .. } => EventKind::SelectChanged,
1761            Self::Choice { .. } => EventKind::Choice,
1762            Self::FocusChanged(_) => EventKind::FocusChanged,
1763            Self::FocusWithin { .. } => EventKind::FocusWithin,
1764            Self::Navigate { .. } => EventKind::Navigate,
1765            Self::Typeahead { .. } => EventKind::Typeahead,
1766            Self::Composition { .. } => EventKind::Composition,
1767            Self::Scroll { .. } => EventKind::Scroll,
1768            Self::Resize { .. } => EventKind::Resize,
1769            Self::Anchor { .. } => EventKind::Anchor,
1770        }
1771    }
1772}
1773
1774#[derive(Clone, Debug, PartialEq)]
1775pub enum Input {
1776    Event {
1777        node: NodeId,
1778        event: Event,
1779    },
1780    Response {
1781        token: QueryToken,
1782        /// Applied mutation watermark observed by this request.
1783        applied: u64,
1784        result: Result<QueryValue, Error>,
1785    },
1786}
1787
1788#[derive(Clone, Debug, PartialEq, Eq)]
1789pub enum Error {
1790    Backend(String),
1791    ForeignRuntime,
1792    NodeGone(NodeId),
1793    StaleNode(NodeId),
1794    DuplicateNode(NodeId),
1795    InvalidPlacement(&'static str),
1796    InvalidProps(&'static str),
1797    Unsupported(&'static str),
1798    UnsupportedStyle {
1799        profile: &'static str,
1800        version: u32,
1801        requirement: style::Unsupported,
1802    },
1803    InvalidReceipt {
1804        previous: u64,
1805        applied: u64,
1806    },
1807    QueryWatermark {
1808        expected: u64,
1809        applied: u64,
1810    },
1811    InvalidResponse(&'static str),
1812    InvalidEvent(&'static str),
1813    InputRevision {
1814        current: u64,
1815        incoming: u64,
1816    },
1817    InputRevisionExhausted,
1818    SelectRevision {
1819        current: u64,
1820        incoming: u64,
1821    },
1822    SelectRevisionExhausted,
1823    ImageRevision {
1824        current: u64,
1825        incoming: u64,
1826    },
1827    ImageRevisionExhausted,
1828    SheetRevision {
1829        current: u64,
1830        incoming: u64,
1831    },
1832    SheetRevisionExhausted,
1833    CollapseRevision {
1834        current: u64,
1835        incoming: u64,
1836    },
1837    CollapseRevisionExhausted,
1838    PresenceRevision {
1839        current: u64,
1840        incoming: u64,
1841    },
1842    PresenceRevisionExhausted,
1843}
1844
1845impl std::fmt::Display for Error {
1846    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1847        write!(f, "{self:?}")
1848    }
1849}
1850
1851impl std::error::Error for Error {}
1852
1853/// Applying nodes does not imply pixels have been displayed.
1854/// Successful nonempty apply calls strictly advance this renderer-local
1855/// watermark; empty calls preserve it. It is not a displayed-frame sequence.
1856#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1857pub struct Receipt {
1858    pub applied: u64,
1859}
1860
1861/// Local calls are typed and require no serialization. Each request observes
1862/// every preceding successful apply; adapters must not coalesce across requests.
1863/// A response carries the watermark at request acceptance, even if delivered
1864/// after later commits. Capture results at that barrier, not from a newer tree.
1865/// Errors may leave an applied prefix; adapters do not promise rollback.
1866pub trait Render {
1867    /// Commit adapter-owned display slots after semantic mutations and before
1868    /// actions/queries. This does not allocate semantic element identities.
1869    fn flush_display(&mut self) -> Result<(), Error> {
1870        Ok(())
1871    }
1872    /// Reject descriptor-local limitations before the App changes its logical
1873    /// tree or queues output. None checks creation; Some checks a patch against
1874    /// the supplied current descriptor, including earlier uncommitted changes.
1875    /// Read only these arguments and immutable adapter configuration: no host
1876    /// calls, layout, application callbacks, or committed-tree lookups. Adapters
1877    /// must enforce the same restrictions in apply for callers without an App.
1878    /// This is not a transaction or a guarantee that later host work succeeds.
1879    fn preflight(&self, _node: DescriptorView<'_>, _patch: Option<&Patch>) -> Result<(), Error> {
1880        Ok(())
1881    }
1882    /// Validate adapter-specific ancestor/content constraints against the App's
1883    /// staged semantic tree, including uncommitted Create/Patch/Place changes.
1884    /// New children are checked before identity allocation; existing children
1885    /// before Place/Resume changes the model or output queue. Read only these
1886    /// arguments/configuration: no host tree, layout, I/O or application code.
1887    /// The App checks shared identity/placement semantics first. Default adds
1888    /// no restrictions. Direct apply must enforce the same content rules.
1889    fn preflight_place(
1890        &self,
1891        _tree: &memory::Memory,
1892        _child: memory::Subtree<'_>,
1893        _parent: Option<NodeId>,
1894    ) -> Result<(), Error> {
1895        Ok(())
1896    }
1897    /// Optional local diagnostics. Return an unused or retired handle so its
1898    /// captured clock is dropped outside the caller's renderer borrow.
1899    fn set_profile(&mut self, profile: Option<profile::Profile>) -> Option<profile::Profile> {
1900        profile
1901    }
1902    /// Another local observation can make progress without awaiting I/O, an
1903    /// animation timestamp or a future browser frame. Read-only and never runs
1904    /// application code. Hosts with asynchronous observation keep the default.
1905    fn needs_observe(&self) -> bool {
1906        false
1907    }
1908    /// Declared once per App. Default rejects nonempty inline styles; adapters
1909    /// opt into exactly the declarations/values they preserve or implement.
1910    fn style_profile(&self) -> style::Profile {
1911        style::Profile::NONE
1912    }
1913    /// Event interest is frame metadata. Hosts may use it to avoid observing
1914    /// thousands of nodes whose resize/scroll events nobody consumes.
1915    fn listen(&mut self, _node: NodeId, _kind: EventKind, _enabled: bool) -> Result<(), Error> {
1916        Ok(())
1917    }
1918    fn capabilities(&self) -> Capabilities;
1919    fn apply(&mut self, mutations: &[Mutation]) -> Result<Receipt, Error>;
1920    /// Optional immediate physical read at the caller's committed barrier.
1921    /// None means the host requires the queued Bounds query. Never call user code.
1922    fn bounds_now(&mut self, _node: NodeId) -> Option<Result<Rect, Error>> {
1923        None
1924    }
1925    fn request(&mut self, query: Query, token: QueryToken) -> Result<(), Error>;
1926    /// Actions run after a frame's mutations and before subsequent queries.
1927    /// Unsupported focus refusal leaves the semantic tree valid: App treats it
1928    /// as an unfulfilled intent and continues later intents. Backend errors remain
1929    /// fatal. Never synthesize FocusChanged(true) merely for accepting Focus.
1930    fn action(&mut self, _action: Action) -> Result<(), Error> {
1931        Err(Error::Unsupported("platform action"))
1932    }
1933    /// Return queued inputs, never synchronously reenter business closures.
1934    fn drain(&mut self, inputs: &mut Vec<Input>);
1935}
1936
1937mod environment;
1938mod table;
1939pub use environment::{Environment, LanguageTag};
1940pub use table::{MAX_CELL_HEADERS, MAX_TABLE_SPAN, SortDirection, TableMetadata};
1941
1942mod swipe;
1943pub use swipe::SwipeCapture;
1944
1945mod rich_document;
1946pub use rich_document::{
1947    MAX_RICH_BLOCKS, MAX_RICH_LINK_BYTES, MAX_RICH_METADATA_BYTES, MAX_RICH_RUNS,
1948    MAX_RICH_TEXT_BYTES, RichBlock, RichBlockKind, RichDocument, RichFormat, RichMarks, RichPoint,
1949    RichRun, RichSelection,
1950};
1951mod rich;
1952pub use rich::{RichCommand, RichEditorProps, RichSnapshot};