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