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