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 widget.
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            // Disabling selection does not revoke an already selected file.
269            // Reads/previews retain their token and configuration checks;
270            // picker/removal actions still enforce the enabled state.
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        /// Source inputs capture the exact selection at keydown; rich editors
628        /// continue to use their independently accepted rich selection.
629        selection: Option<TextSelection>,
630    },
631    /// Current physical content exceeded the finite rich document grammar or
632    /// budgets. The host restores its accepted value before publishing this.
633    RichRejected {
634        revision: u64,
635    },
636    RichEdit(Box<RichSnapshot>),
637    RichSelection(Box<RichSnapshot>),
638    Files(Box<FileEvent>),
639    TreeNavigate {
640        from: NodeId,
641        command: TreeCommand,
642    },
643    Clipboard {
644        revision: u64,
645        request: u64,
646        outcome: ClipboardOutcome,
647    },
648    GridNavigate {
649        from: NodeId,
650        command: GridCommand,
651    },
652    InputEdit(InputEdit),
653    /// Terminal presentation observation; valid while the closing subtree is
654    /// logically hidden/inert, without admitting business input there.
655    CollapseComplete {
656        revision: u64,
657    },
658    PresenceComplete {
659        revision: u64,
660    },
661    ContextMenu {
662        from: NodeId,
663        point: ContextPoint,
664        source: ContextSource,
665    },
666    Sheet {
667        from: NodeId,
668        revision: u64,
669        command: SheetCommand,
670    },
671    NavigationPanel {
672        from: NodeId,
673        command: NavigationPanelCommand,
674    },
675    Spin {
676        from: NodeId,
677        command: RangeCommand,
678    },
679    Range {
680        from: NodeId,
681        command: RangeCommand,
682    },
683    ScrollKeyboard {
684        from: NodeId,
685        command: ScrollCommand,
686    },
687    /// Terminal observation for one program-selected image request.
688    ImageStatus {
689        revision: u64,
690        status: ImageStatus,
691    },
692    Menu {
693        from: NodeId,
694        command: MenuCommand,
695    },
696    /// A queued observation in an explicitly observed View's local border box.
697    PlotPointer {
698        from: NodeId,
699        pointer: PlotPointer,
700    },
701    Pointer {
702        from: NodeId,
703        related: Option<NodeId>,
704        phase: PointerPhase,
705    },
706    /// Logical boundary observation derived from a physical pointer origin.
707    PointerWithin {
708        from: NodeId,
709        related: Option<NodeId>,
710        phase: PointerPhase,
711    },
712    /// Native form default behavior is cancelled before this queued request.
713    /// None represents a programmatic request or implicit keyboard submission.
714    Submit {
715        submitter: Option<NodeId>,
716    },
717    Reset,
718    Activate,
719    /// An activation of an explicitly declared target in a display instance.
720    DisplayClick(u16),
721    /// A request only: the application may keep controlled state open.
722    Dismiss(DismissReason),
723    /// Host preference, independent of an application's explicit appearance.
724    ColorSchemeChanged {
725        dark: bool,
726    },
727    /// Physical origin remains explicit while App routes to the nearest observer.
728    Keyboard {
729        from: NodeId,
730        command: KeyboardCommand,
731    },
732    /// Only the explicit palette chord; other application commands stay native.
733    Palette {
734        from: NodeId,
735    },
736    /// Start/Move/Cancel target the source. Drop targets a live accepting node.
737    Swipe {
738        from: NodeId,
739        phase: DragPhase,
740        x: f64,
741        y: f64,
742        revision: u64,
743    },
744    Drag {
745        from: NodeId,
746        phase: DragPhase,
747        x: f64,
748        y: f64,
749    },
750    ValueChanged {
751        value: String,
752        composing: bool,
753        revision: u64,
754    },
755    Commit {
756        value: String,
757        revision: u64,
758    },
759    CheckedChanged(bool),
760    Tags {
761        from: NodeId,
762        revision: u64,
763        command: TagsCommand,
764    },
765    Choice {
766        from: NodeId,
767        command: ChoiceCommand,
768    },
769    SelectChanged {
770        keys: Vec<SemanticId>,
771        revision: u64,
772    },
773    /// Direct focus origin. Hosts report this even if only an ancestor has a
774    /// FocusWithin interest; App derives the logical ancestor observations.
775    FocusChanged(bool),
776    /// Focus transition originating at `node`, delivered to observing logical
777    /// ancestors (including boxless Groups). FocusChanged itself stays direct.
778    FocusWithin {
779        node: NodeId,
780        focused: bool,
781    },
782    /// Origin stays explicit when routed to the nearest logical observer.
783    Navigate {
784        from: NodeId,
785        command: Navigation,
786    },
787    Typeahead {
788        from: NodeId,
789        text: String,
790        at_millis: u64,
791    },
792    Composition {
793        active: bool,
794    },
795    Scroll {
796        x: f64,
797        y: f64,
798        viewport: Rect,
799        /// Last accepted assignment, separate from current x/y (which may
800        /// already include native movement). None before any host assignment.
801        ack: Option<ScrollAck>,
802    },
803    /// Border-box size and client viewport are distinct (borders/scrollbars).
804    /// Size uses local x/y=0; adapters preserve fractional layout dimensions.
805    Resize {
806        size: Rect,
807        viewport: Rect,
808    },
809    /// Restore an existing visible row and its pixel inset at host handover.
810    Anchor {
811        row: NodeId,
812        within: f64,
813        viewport: Rect,
814    },
815}
816
817#[derive(Clone, Copy, Debug, PartialEq)]
818pub struct ScrollRequest {
819    pub x: f64,
820    pub y: f64,
821}
822/// Last accepted programmatic assignment, retained on later observations so
823/// native movement before the first acknowledgement is still distinguishable.
824#[derive(Clone, Copy, Debug, PartialEq)]
825pub struct ScrollAck {
826    pub requested: ScrollRequest,
827    pub x: f64,
828    pub y: f64,
829}
830
831#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
832pub enum EventKind {
833    DisplayClick,
834    RichCommand,
835    RichRejected,
836    RichEdit,
837    RichSelection,
838    Files,
839    TreeNavigate,
840    Clipboard,
841    GridNavigate,
842    InputEdit,
843    CollapseComplete,
844    PresenceComplete,
845    ContextMenu,
846    Tags,
847    Sheet,
848    NavigationPanel,
849    Spin,
850    Range,
851    ScrollKeyboard,
852    ImageStatus,
853    Menu,
854    PlotPointer,
855    Pointer,
856    PointerWithin,
857    Submit,
858    Reset,
859    Activate,
860    Dismiss,
861    ColorSchemeChanged,
862    Keyboard,
863    Palette,
864    Swipe,
865    Drag,
866    ValueChanged,
867    Commit,
868    CheckedChanged,
869    SelectChanged,
870    Choice,
871    FocusChanged,
872    FocusWithin,
873    Navigate,
874    Typeahead,
875    Composition,
876    Scroll,
877    Resize,
878    Anchor,
879}
880/// Finite event targets of one opaque display instance, not element identities.
881#[derive(Clone, Debug)]
882pub struct DisplayEvents(pub Vec<u16>);
883
884impl EventKind {
885    /// Logical bubbling/ancestor observations can target Groups; direct physical
886    /// observations cannot. Recording a valid interest does not promise the host
887    /// can produce it (SSR records handlers for later browser adoption).
888    pub fn validate_target<'a>(self, node: impl Into<DescriptorView<'a>>) -> Result<(), Error> {
889        let node = node.into();
890        if self == Self::PlotPointer && !matches!(node.props, Props::View) {
891            return Err(Error::Unsupported(
892                "plot pointer requires a physical View viewport",
893            ));
894        }
895        if self == Self::DisplayClick
896            && (!matches!(node.props, Props::Group)
897                || node.options.get::<DisplayEvents>().is_none())
898        {
899            return Err(Error::InvalidEvent(
900                "display activation requires a declared instance",
901            ));
902        }
903        if matches!(
904            self,
905            Self::RichEdit | Self::RichSelection | Self::RichRejected
906        ) && !matches!(node.props, Props::RichEditor(_))
907        {
908            return Err(Error::InvalidProps(
909                "rich observations require a RichEditor",
910            ));
911        }
912        if self == Self::RichCommand
913            && !matches!(
914                node.props,
915                Props::RichEditor(_)
916                    | Props::Input(InputProps {
917                        multiline: true,
918                        ..
919                    })
920            )
921        {
922            return Err(Error::InvalidProps(
923                "formatting commands require a rich editor or multiline input",
924            ));
925        }
926        if self == Self::Swipe
927            && (!matches!(node.props, Props::View)
928                || node
929                    .semantics
930                    .as_ref()
931                    .is_none_or(|s| s.swipe_capture.is_none()))
932        {
933            return Err(Error::InvalidProps(
934                "swipe observations require a declared View capture",
935            ));
936        }
937        if self == Self::Files && !matches!(node.props, Props::File(_)) {
938            return Err(Error::InvalidProps(
939                "file observations require a File control",
940            ));
941        }
942
943        if self == Self::TreeNavigate
944            && (node.role != Some(Role::Tree)
945                || !matches!(node.props, Props::View)
946                || node
947                    .semantics
948                    .as_ref()
949                    .is_none_or(|s| s.tree_navigation.is_none()))
950        {
951            return Err(Error::InvalidProps(
952                "tree navigation requires an opted-in Tree View",
953            ));
954        }
955        if self == Self::Clipboard
956            && (!matches!(node.props, Props::Button(_))
957                || node
958                    .semantics
959                    .as_ref()
960                    .is_none_or(|s| s.clipboard.is_none()))
961        {
962            return Err(Error::Unsupported(
963                "clipboard observation requires a declared Button source",
964            ));
965        }
966        if self == Self::GridNavigate
967            && (node.role != Some(Role::Grid)
968                || !matches!(node.props, Props::View)
969                || !node
970                    .semantics
971                    .as_ref()
972                    .is_some_and(|s| s.grid_navigation.is_some()))
973        {
974            return Err(Error::InvalidProps(
975                "grid navigation requires an opted-in Grid View",
976            ));
977        }
978        if self == Self::InputEdit
979            && !matches!(node.props,Props::Input(p) if !p.multiline&&node.semantics.as_ref().is_some_and(|s|s.input_edit.is_some()))
980        {
981            return Err(Error::Unsupported(
982                "InputEdit requires an opted-in single-line Input",
983            ));
984        }
985        if self == Self::PresenceComplete
986            && (!matches!(node.props, Props::View)
987                || !node
988                    .semantics
989                    .as_ref()
990                    .is_some_and(|s| s.presence.is_some()))
991        {
992            return Err(Error::InvalidProps(
993                "presence completion requires a presence View",
994            ));
995        }
996        if self == Self::CollapseComplete
997            && (!matches!(node.props, Props::View)
998                || !node
999                    .semantics
1000                    .as_ref()
1001                    .is_some_and(|s| s.collapse.is_some()))
1002        {
1003            return Err(Error::InvalidProps(
1004                "collapse completion requires a collapse View",
1005            ));
1006        }
1007        if self == Self::ContextMenu
1008            && (!matches!(node.props, Props::View)
1009                || !node
1010                    .semantics
1011                    .as_ref()
1012                    .is_some_and(|s| s.context_menu.is_some()))
1013        {
1014            return Err(Error::InvalidProps(
1015                "context requests require an opted-in region view",
1016            ));
1017        }
1018        if self == Self::Tags
1019            && !matches!(node.props,Props::Input(input) if !input.multiline && node.semantics.as_ref().is_some_and(|s|s.tags_input.is_some()))
1020        {
1021            return Err(Error::InvalidProps(
1022                "tags commands require an opted-in single-line input",
1023            ));
1024        }
1025        if self == Self::Sheet && !matches!(node.props, Props::View) {
1026            return Err(Error::InvalidProps("sheet commands require a view"));
1027        }
1028        if self == Self::NavigationPanel
1029            && !matches!(node.props, Props::Button(_) | Props::Link(_) | Props::View)
1030        {
1031            return Err(Error::InvalidProps(
1032                "navigation panel commands require a physical navigation control or content view",
1033            ));
1034        }
1035        if self == Self::Spin
1036            && !matches!(node.props, Props::Input(p) if !p.multiline && node.semantics.as_ref().is_some_and(|s| s.spinbutton.is_some()))
1037        {
1038            return Err(Error::InvalidProps(
1039                "spin commands require an opted-in single-line input",
1040            ));
1041        }
1042        if self == Self::Range
1043            && (!matches!(node.props, Props::View)
1044                || !matches!(node.role, Some(Role::Separator | Role::Slider)))
1045        {
1046            return Err(Error::InvalidProps(
1047                "range commands require a slider or splitter separator",
1048            ));
1049        }
1050        if self == Self::Choice
1051            && !node
1052                .semantics
1053                .as_ref()
1054                .is_some_and(|s| s.combobox.is_some())
1055        {
1056            return Err(Error::InvalidProps("choice commands require a combobox"));
1057        }
1058        if self == Self::SelectChanged && !matches!(node.props, Props::Select(_)) {
1059            return Err(Error::InvalidProps("selection event requires a select"));
1060        }
1061        if self == Self::ScrollKeyboard && !matches!(node.props, Props::View) {
1062            return Err(Error::InvalidProps(
1063                "scroll keyboard requires a viewport view",
1064            ));
1065        }
1066        if self == Self::ImageStatus && !matches!(node.props, Props::Image(_)) {
1067            return Err(Error::InvalidProps("image status requires an image"));
1068        }
1069        if matches!(self, Self::Submit | Self::Reset) && node.field_part() != Some(FieldPart::Form)
1070        {
1071            return Err(Error::InvalidProps("form request requires a form"));
1072        }
1073        if matches!(
1074            node.role,
1075            Some(Role::Separator | Role::Tooltip | Role::ProgressBar)
1076        ) && matches!(
1077            self,
1078            Self::Activate
1079                | Self::Keyboard
1080                | Self::Palette
1081                | Self::ScrollKeyboard
1082                | Self::Drag
1083                | Self::Navigate
1084                | Self::Typeahead
1085                | Self::Menu
1086                | Self::NavigationPanel
1087                | Self::Range
1088        ) && !(node.role == Some(Role::Separator)
1089            && node
1090                .semantics
1091                .as_ref()
1092                .is_some_and(|s| s.splitter.is_some())
1093            && matches!(self, Self::Range | Self::Drag))
1094        {
1095            return Err(Error::Unsupported("passive separator has no interaction"));
1096        }
1097        // Interests may be registered before layer metadata bindings run.
1098        if self == Self::Dismiss && !matches!(node.props, Props::View) {
1099            return Err(Error::InvalidProps("dismiss requires a view"));
1100        }
1101        if matches!(self, Self::Drag | Self::ColorSchemeChanged)
1102            && !matches!(node.props, Props::View)
1103        {
1104            return Err(Error::Unsupported(
1105                "host observation requires a semantic View",
1106            ));
1107        }
1108        if self == Self::Palette
1109            && matches!(
1110                node.props,
1111                Props::Group | Props::Input(_) | Props::Select(_)
1112            )
1113        {
1114            return Err(Error::Unsupported(
1115                "palette shortcut requires a non-editor physical scope or origin",
1116            ));
1117        }
1118        if matches!(self, Self::ValueChanged | Self::Commit)
1119            && !matches!(node.props, Props::Input(_))
1120            || self == Self::Composition
1121                && !matches!(node.props, Props::Input(_) | Props::RichEditor(_))
1122            || matches!(self, Self::CheckedChanged) && !matches!(node.props, Props::Check(_))
1123        {
1124            return Err(Error::InvalidProps("event does not belong to this control"));
1125        }
1126        if matches!(node.props, Props::Group)
1127            && matches!(
1128                self,
1129                Self::Resize
1130                    | Self::Scroll
1131                    | Self::Anchor
1132                    | Self::FocusChanged
1133                    | Self::Drag
1134                    | Self::Pointer
1135            )
1136        {
1137            return Err(Error::Unsupported("group has no physical event target"));
1138        }
1139        Ok(())
1140    }
1141}
1142
1143impl Event {
1144    /// User input is suppressed by inherited inert regions. Resource/layout
1145    /// observations and terminal cleanup remain available to live Owners.
1146    pub fn is_user_interaction(&self) -> bool {
1147        !self.is_terminal_loss()
1148            && !matches!(
1149                self,
1150                Self::Clipboard { .. }
1151                    | Self::ImageStatus { .. }
1152                    | Self::ColorSchemeChanged { .. }
1153                    | Self::Scroll { .. }
1154                    | Self::Resize { .. }
1155                    | Self::Anchor { .. }
1156            )
1157    }
1158    /// Cleanup observations still reach live scopes after suspension. Retired
1159    /// identities never become valid again because an event is terminal.
1160    pub fn is_terminal_loss(&self) -> bool {
1161        if let Self::Files(event) = self {
1162            return !matches!(event.outcome, FileOutcome::Selected(_));
1163        }
1164        matches!(
1165            self,
1166            Self::Clipboard { .. }
1167                | Self::CollapseComplete { .. }
1168                | Self::PresenceComplete { .. }
1169                | Self::FocusChanged(false)
1170                | Self::Composition { active: false }
1171                | Self::FocusWithin { focused: false, .. }
1172                | Self::Swipe {
1173                    phase: DragPhase::Cancel,
1174                    ..
1175                }
1176                | Self::Drag {
1177                    phase: DragPhase::Cancel,
1178                    ..
1179                }
1180                | Self::PlotPointer {
1181                    pointer: PlotPointer {
1182                        phase: PlotPointerPhase::Leave | PlotPointerPhase::Cancel,
1183                        ..
1184                    },
1185                    ..
1186                }
1187                | Self::Pointer {
1188                    phase: PointerPhase::Leave,
1189                    ..
1190                }
1191                | Self::PointerWithin {
1192                    phase: PointerPhase::Leave,
1193                    ..
1194                }
1195        )
1196    }
1197
1198    pub(crate) fn origin(&self) -> Option<NodeId> {
1199        match self {
1200            Self::TreeNavigate { from, .. } => Some(*from),
1201            Self::GridNavigate { from, .. } => Some(*from),
1202            Self::ContextMenu { from, .. } => Some(*from),
1203            Self::Tags { from, .. } => Some(*from),
1204            Self::Submit { submitter } => *submitter,
1205            Self::FocusWithin { node, .. } => Some(*node),
1206            Self::Navigate { from, .. } => Some(*from),
1207            Self::Menu { from, .. }
1208            | Self::PlotPointer { from, .. }
1209            | Self::Pointer { from, .. }
1210            | Self::PointerWithin { from, .. } => Some(*from),
1211            Self::Typeahead { from, .. } => Some(*from),
1212            Self::Choice { from, .. } | Self::Keyboard { from, .. } | Self::Palette { from } => {
1213                Some(*from)
1214            }
1215            Self::ScrollKeyboard { from, .. } => Some(*from),
1216            Self::Spin { from, .. } | Self::Range { from, .. } => Some(*from),
1217            Self::Sheet { from, .. } => Some(*from),
1218            Self::NavigationPanel { from, .. } => Some(*from),
1219            Self::Swipe { from, .. } | Self::Drag { from, .. } => Some(*from),
1220            Self::Anchor { row, .. } => Some(*row),
1221            _ => None,
1222        }
1223    }
1224
1225    /// Check typed host input before business handlers. Embedded identities'
1226    /// liveness/ancestry require a tree and are checked by Memory::validate_event.
1227    /// Scroll offsets may be negative; local geometry must have x/y=0.
1228    pub fn validate_payload<'a>(
1229        &self,
1230        target: NodeId,
1231        node: impl Into<DescriptorView<'a>>,
1232    ) -> Result<(), Error> {
1233        self.validate_payload_view(target, node.into())
1234    }
1235
1236    // One implementation for live descriptors and borrowed construction values;
1237    // conversion at the API boundary should not duplicate all event validation.
1238    fn validate_payload_view(&self, target: NodeId, node: DescriptorView<'_>) -> Result<(), Error> {
1239        if let Self::DisplayClick(slot) = self
1240            && (*slot >= 256
1241                || !node
1242                    .options
1243                    .get::<DisplayEvents>()
1244                    .is_some_and(|events| events.0.contains(slot)))
1245        {
1246            return Err(Error::InvalidEvent("undeclared display activation slot"));
1247        }
1248        if let Self::RichRejected { revision } | Self::RichCommand { revision, .. } = self {
1249            let current = match node.props {
1250                Props::RichEditor(editor) => {
1251                    if let Self::RichCommand { command, .. } = self
1252                        && command.source_only()
1253                    {
1254                        return Err(Error::InvalidEvent(
1255                            "source command requires a multiline input",
1256                        ));
1257                    }
1258                    if let Self::RichCommand {
1259                        selection: Some(_), ..
1260                    } = self
1261                    {
1262                        return Err(Error::InvalidEvent(
1263                            "rich command cannot carry a source selection",
1264                        ));
1265                    }
1266                    editor.revision
1267                }
1268                Props::Input(input)
1269                    if input.multiline && matches!(self, Self::RichCommand { .. }) =>
1270                {
1271                    if let Self::RichCommand {
1272                        selection: Some(selection),
1273                        ..
1274                    } = self
1275                    {
1276                        selection.validate(1_048_576)?;
1277                    }
1278                    input.revision
1279                }
1280                _ => {
1281                    return Err(Error::InvalidEvent(
1282                        "formatting command requires its editor",
1283                    ));
1284                }
1285            };
1286            if *revision > current {
1287                return Err(Error::InputRevision {
1288                    current,
1289                    incoming: *revision,
1290                });
1291            }
1292        }
1293        if let Self::RichEdit(snapshot) | Self::RichSelection(snapshot) = self {
1294            let Props::RichEditor(editor) = node.props else {
1295                return Err(Error::InvalidEvent("rich input requires its RichEditor"));
1296            };
1297            snapshot.validate_input(editor)?;
1298        }
1299        if let Self::Swipe {
1300            from,
1301            x,
1302            y,
1303            revision,
1304            ..
1305        } = self
1306        {
1307            EventKind::Swipe.validate_target(node)?;
1308            if from.runtime() != target.runtime() {
1309                return Err(Error::ForeignRuntime);
1310            }
1311            if *from != target || !x.is_finite() || !y.is_finite() {
1312                return Err(Error::InvalidEvent(
1313                    "swipe requires its exact finite boxed origin",
1314                ));
1315            }
1316            let capture = node
1317                .semantics
1318                .as_ref()
1319                .and_then(|s| s.swipe_capture)
1320                .expect("validated swipe capture");
1321            if *revision > capture.revision {
1322                return Err(Error::InputRevision {
1323                    current: capture.revision,
1324                    incoming: *revision,
1325                });
1326            }
1327        }
1328        if let Self::Files(event) = self {
1329            let Props::File(props) = node.props else {
1330                return Err(Error::InvalidEvent(
1331                    "file observations require a File control",
1332                ));
1333            };
1334            event.validate_node(target, props)?;
1335        }
1336
1337        if let Self::TreeNavigate { from, command } = self {
1338            EventKind::TreeNavigate.validate_target(node)?;
1339            command.validate()?;
1340            if from.runtime() != target.runtime() {
1341                return Err(Error::ForeignRuntime);
1342            }
1343            if *from == target {
1344                return Err(Error::InvalidEvent(
1345                    "tree command requires a descendant TreeItem",
1346                ));
1347            }
1348            if matches!(command, TreeCommand::Search { .. })
1349                && node
1350                    .semantics
1351                    .as_ref()
1352                    .and_then(|s| s.tree_navigation)
1353                    .is_none_or(|s| !s.typeahead)
1354            {
1355                return Err(Error::InvalidEvent("tree search is not enabled"));
1356            }
1357        }
1358        if let Self::Clipboard {
1359            revision, request, ..
1360        } = self
1361        {
1362            EventKind::Clipboard.validate_target(node)?;
1363            let source = node
1364                .semantics
1365                .as_ref()
1366                .and_then(|s| s.clipboard.as_ref())
1367                .expect("validated source");
1368            if *request == 0 || *revision > source.revision {
1369                return Err(Error::InvalidEvent(
1370                    "clipboard completion has a future revision or zero request",
1371                ));
1372            }
1373        }
1374        if let Self::GridNavigate { from, .. } = self {
1375            EventKind::GridNavigate.validate_target(node)?;
1376            if from.runtime() != target.runtime() {
1377                return Err(Error::ForeignRuntime);
1378            }
1379            if *from == target {
1380                return Err(Error::InvalidEvent(
1381                    "grid navigation requires a real descendant Button",
1382                ));
1383            }
1384        }
1385        if let Self::InputEdit(edit) = self {
1386            EventKind::InputEdit.validate_target(node)?;
1387            let capture = node
1388                .semantics
1389                .as_ref()
1390                .and_then(|s| s.input_edit)
1391                .ok_or(Error::InvalidEvent("input edit capture is absent"))?;
1392            edit.validate(capture)?;
1393            if let Props::Input(input) = node.props
1394                && edit.revision() > input.revision
1395            {
1396                return Err(Error::InputRevision {
1397                    current: input.revision,
1398                    incoming: edit.revision(),
1399                });
1400            }
1401        }
1402        if let Self::PresenceComplete { revision } = self {
1403            let config = node
1404                .semantics
1405                .as_ref()
1406                .and_then(|s| s.presence.as_ref())
1407                .ok_or(Error::InvalidEvent(
1408                    "presence completion requires a presence View",
1409                ))?;
1410            if *revision > config.revision {
1411                return Err(Error::PresenceRevision {
1412                    current: config.revision,
1413                    incoming: *revision,
1414                });
1415            }
1416        }
1417        if let Self::CollapseComplete { revision } = self {
1418            let config = node
1419                .semantics
1420                .as_ref()
1421                .and_then(|s| s.collapse.as_ref())
1422                .ok_or(Error::InvalidEvent(
1423                    "collapse completion requires a collapse View",
1424                ))?;
1425            if *revision > config.revision {
1426                return Err(Error::CollapseRevision {
1427                    current: config.revision,
1428                    incoming: *revision,
1429                });
1430            }
1431        }
1432        if let Self::Sheet {
1433            from,
1434            revision,
1435            command,
1436        } = self
1437        {
1438            if from.runtime() != target.runtime() {
1439                return Err(Error::ForeignRuntime);
1440            }
1441            let config = node
1442                .semantics
1443                .as_ref()
1444                .and_then(|s| s.layer.as_ref())
1445                .and_then(|layer| layer.sheet.as_ref())
1446                .ok_or(Error::InvalidEvent("sheet command requires a sheet"))?;
1447            if *from != target {
1448                return Err(Error::InvalidEvent(
1449                    "sheet command origin must equal its target",
1450                ));
1451            }
1452            if *revision > config.revision {
1453                return Err(Error::SheetRevision {
1454                    current: config.revision,
1455                    incoming: *revision,
1456                });
1457            }
1458            if *revision == config.revision
1459                && match command {
1460                    SheetCommand::Snap(index) => *index >= config.fractions.len(),
1461                    SheetCommand::Dismiss => !config.dismissible,
1462                }
1463            {
1464                return Err(Error::InvalidEvent(
1465                    "sheet command exceeds its accepted configuration",
1466                ));
1467            }
1468        }
1469        if let Self::Dismiss(reason) = self {
1470            let layer = node
1471                .semantics
1472                .as_ref()
1473                .and_then(|s| s.layer.as_ref())
1474                .ok_or(Error::InvalidEvent("dismiss requires a layer"))?;
1475            if !match reason {
1476                DismissReason::Gesture => {
1477                    layer.sheet.as_ref().is_some_and(|sheet| sheet.dismissible)
1478                }
1479                DismissReason::Escape => layer.escape,
1480                DismissReason::Outside => layer.outside,
1481                DismissReason::AnchorLost => layer.anchor.is_some(),
1482            } {
1483                return Err(Error::InvalidEvent("disabled layer dismissal"));
1484            }
1485        }
1486        if self
1487            .origin()
1488            .is_some_and(|id| id.runtime() != target.runtime())
1489        {
1490            return Err(Error::ForeignRuntime);
1491        }
1492        self.kind().validate_target(node)?;
1493        if matches!(
1494            self,
1495            Self::Choice {
1496                command: ChoiceCommand::RemoveLast,
1497                ..
1498            }
1499        ) && node.semantics.as_ref().and_then(|value| value.combobox)
1500            != Some(ComboboxKind::Multiple)
1501        {
1502            return Err(Error::InvalidEvent(
1503                "remove-last requires a multiple combobox",
1504            ));
1505        }
1506        let local = |rect: &Rect| {
1507            rect.x == 0.0
1508                && rect.y == 0.0
1509                && rect.width.is_finite()
1510                && rect.height.is_finite()
1511                && rect.width >= 0.0
1512                && rect.height >= 0.0
1513        };
1514        match self {
1515            Self::PlotPointer { from, pointer } => {
1516                if *from != target {
1517                    return Err(Error::InvalidEvent(
1518                        "plot pointer requires its observed viewport origin",
1519                    ));
1520                }
1521                pointer.validate()?;
1522            }
1523            Self::ContextMenu { from, point, .. } => {
1524                if from.runtime() != target.runtime() {
1525                    return Err(Error::ForeignRuntime);
1526                }
1527                point.validate()?;
1528                EventKind::ContextMenu.validate_target(node)?;
1529            }
1530            Self::Spin { from, command } => {
1531                EventKind::Spin.validate_target(node)?;
1532                if *from != target {
1533                    return Err(Error::InvalidEvent(
1534                        "spin command requires its physical origin",
1535                    ));
1536                }
1537                let spin = node
1538                    .semantics
1539                    .as_ref()
1540                    .filter(|s| !s.disabled && !s.readonly && node.props.enabled())
1541                    .and_then(|s| s.spinbutton.as_ref())
1542                    .ok_or(Error::InvalidEvent(
1543                        "spin command requires an enabled writable input",
1544                    ))?;
1545                spin.validate_command(*command)?;
1546            }
1547            Self::Range { from, command } => {
1548                let range = node
1549                    .semantics
1550                    .as_ref()
1551                    .filter(|s| !s.disabled)
1552                    .and_then(|s| {
1553                        s.splitter
1554                            .or_else(|| s.slider.as_ref().map(|slider| slider.range))
1555                    })
1556                    .ok_or(Error::InvalidEvent(
1557                        "range command requires an enabled slider or splitter",
1558                    ))?;
1559                if *from != target {
1560                    return Err(Error::InvalidEvent(
1561                        "range command requires its physical origin",
1562                    ));
1563                }
1564                command.validate(range)?;
1565            }
1566            Self::Choice { from, .. } => {
1567                if *from != target {
1568                    return Err(Error::InvalidEvent(
1569                        "choice command requires the combobox physical origin",
1570                    ));
1571                }
1572            }
1573            Self::ScrollKeyboard { from, command } => {
1574                if *from != target
1575                    || !node
1576                        .semantics
1577                        .as_ref()
1578                        .and_then(|s| s.scroll_keyboard)
1579                        .is_some_and(|axes| axes.allows(command.axis))
1580                {
1581                    return Err(Error::InvalidEvent(
1582                        "scroll keyboard requires its opted-in physical viewport and axis",
1583                    ));
1584                }
1585            }
1586            Self::PointerWithin { related, .. } => {
1587                if related.is_some_and(|related| related.runtime() != target.runtime()) {
1588                    return Err(Error::ForeignRuntime);
1589                }
1590            }
1591            Self::NavigationPanel { from, command } => {
1592                if *from != target || matches!(node.props, Props::Group) {
1593                    return Err(Error::InvalidEvent(
1594                        "navigation panel requires its exact physical origin",
1595                    ));
1596                }
1597                let marker = node.semantics.as_ref().and_then(|s| s.navigation_panel);
1598                let member = node.semantics.as_ref().is_some_and(|s| s.navigation_item);
1599                if *command == NavigationPanelCommand::Close {
1600                    if !member && marker != Some(NavigationPanel::Content) {
1601                        return Err(Error::InvalidEvent(
1602                            "navigation close requires a content member",
1603                        ));
1604                    }
1605                } else if marker != Some(NavigationPanel::Trigger) {
1606                    return Err(Error::InvalidEvent(
1607                        "navigation entry requires a disclosure trigger",
1608                    ));
1609                }
1610            }
1611            Self::Menu { from, .. } | Self::Pointer { from, .. } => {
1612                if *from != target || matches!(node.props, Props::Group) {
1613                    return Err(Error::InvalidEvent(
1614                        "menu/pointer requires its physical origin",
1615                    ));
1616                }
1617                if matches!(self, Self::Menu { .. })
1618                    && node.role != Some(Role::Menu)
1619                    && !node.semantics.as_ref().is_some_and(|s| {
1620                        s.menu_item.is_some()
1621                            || s.menu_search.is_some()
1622                            || s.popup == Some(PopupKind::Menu)
1623                    })
1624                {
1625                    return Err(Error::InvalidEvent(
1626                        "menu command requires a menu or menu trigger/item",
1627                    ));
1628                }
1629                if matches!(
1630                    self,
1631                    Self::Menu {
1632                        command: MenuCommand::SearchNext
1633                            | MenuCommand::SearchPrevious
1634                            | MenuCommand::SearchCommit,
1635                        ..
1636                    }
1637                ) && node
1638                    .semantics
1639                    .as_ref()
1640                    .is_none_or(|s| s.menu_search.is_none())
1641                {
1642                    return Err(Error::InvalidEvent(
1643                        "search commands require a declared menu search editor",
1644                    ));
1645                }
1646                if node
1647                    .semantics
1648                    .as_ref()
1649                    .is_some_and(|s| s.menu_search.is_some())
1650                    && matches!(self, Self::Menu { command, .. } if !matches!(command, MenuCommand::SearchNext | MenuCommand::SearchPrevious | MenuCommand::SearchCommit | MenuCommand::Exit { .. }))
1651                {
1652                    return Err(Error::InvalidEvent(
1653                        "menu search editors accept search navigation and exit commands only",
1654                    ));
1655                }
1656                if let Self::Pointer {
1657                    related: Some(related),
1658                    ..
1659                } = self
1660                    && related.runtime() != target.runtime()
1661                {
1662                    return Err(Error::ForeignRuntime);
1663                }
1664            }
1665            Self::Typeahead {
1666                from,
1667                text,
1668                at_millis,
1669            } => {
1670                if *from != target || matches!(node.props, Props::Group) {
1671                    return Err(Error::InvalidEvent(
1672                        "typeahead requires its physical origin",
1673                    ));
1674                }
1675                validate_typeahead(text, *at_millis)?;
1676            }
1677            Self::Drag { from, phase, x, y } => {
1678                if !x.is_finite() || !y.is_finite() {
1679                    return Err(Error::InvalidEvent("drag coordinates must be finite"));
1680                }
1681                if *phase != DragPhase::Drop && *from != target {
1682                    return Err(Error::InvalidEvent("drag phase requires source target"));
1683                }
1684            }
1685            Self::Keyboard { from, command } => {
1686                if *from != target || matches!(node.props, Props::Group) {
1687                    return Err(Error::InvalidEvent("keyboard requires its physical origin"));
1688                }
1689                if *command == KeyboardCommand::Submit && !matches!(node.props, Props::Input(_)) {
1690                    return Err(Error::InvalidEvent("submit requires a text control"));
1691                }
1692            }
1693            Self::Palette { from } => {
1694                if from.runtime() != target.runtime() {
1695                    return Err(Error::ForeignRuntime);
1696                }
1697                if *from != target {
1698                    return Err(Error::InvalidEvent(
1699                        "palette shortcut requires its physical origin",
1700                    ));
1701                }
1702                EventKind::Palette.validate_target(node)?;
1703            }
1704            Self::Navigate { from, .. } if *from != target => {
1705                return Err(Error::InvalidEvent(
1706                    "navigation origin must match its event target",
1707                ));
1708            }
1709            Self::Scroll {
1710                x,
1711                y,
1712                viewport,
1713                ack,
1714            } => {
1715                if !x.is_finite() || !y.is_finite() || !local(viewport) {
1716                    return Err(Error::InvalidEvent("invalid scroll geometry"));
1717                }
1718                if ack.is_some_and(|ack| {
1719                    !ack.requested.x.is_finite()
1720                        || !ack.requested.y.is_finite()
1721                        || ack.requested.x < 0.0
1722                        || ack.requested.y < 0.0
1723                        || !ack.x.is_finite()
1724                        || !ack.y.is_finite()
1725                }) {
1726                    return Err(Error::InvalidEvent("invalid scroll acknowledgement"));
1727                }
1728            }
1729            Self::Resize { size, viewport } if !local(size) || !local(viewport) => {
1730                return Err(Error::InvalidEvent("invalid resize geometry"));
1731            }
1732            Self::Anchor {
1733                within, viewport, ..
1734            } if !within.is_finite() || *within < 0.0 || !local(viewport) => {
1735                return Err(Error::InvalidEvent("invalid anchor geometry"));
1736            }
1737            Self::SelectChanged { keys, revision } => {
1738                if let Props::Select(select) = node.props {
1739                    select.validate_user_selection(keys)?;
1740                    if *revision > select.selection.revision {
1741                        return Err(Error::SelectRevision {
1742                            current: select.selection.revision,
1743                            incoming: *revision,
1744                        });
1745                    }
1746                }
1747            }
1748            Self::ImageStatus { revision, .. } => {
1749                if let Props::Image(image) = node.props
1750                    && *revision > image.revision
1751                {
1752                    return Err(Error::ImageRevision {
1753                        current: image.revision,
1754                        incoming: *revision,
1755                    });
1756                }
1757            }
1758            Self::ValueChanged {
1759                value, revision, ..
1760            }
1761            | Self::Commit { value, revision } => {
1762                if matches!(&node.props, Props::Input(input) if !input.multiline && value.contains(['\r', '\n']))
1763                {
1764                    return Err(Error::InvalidEvent(
1765                        "single-line input event cannot contain line breaks",
1766                    ));
1767                }
1768                if value.contains(['\0', '\r']) {
1769                    return Err(Error::InvalidEvent("input event text is not normalized"));
1770                }
1771                if let Props::Input(input) = &node.props
1772                    && *revision > input.revision
1773                {
1774                    return Err(Error::InputRevision {
1775                        current: input.revision,
1776                        incoming: *revision,
1777                    });
1778                }
1779            }
1780            Self::Tags {
1781                from,
1782                revision,
1783                command,
1784            } => {
1785                if *from != target {
1786                    return Err(Error::InvalidEvent(
1787                        "tags command requires its exact input origin",
1788                    ));
1789                }
1790                command.validate()?;
1791                if let Props::Input(input) = node.props
1792                    && *revision > input.revision
1793                {
1794                    return Err(Error::InputRevision {
1795                        current: input.revision,
1796                        incoming: *revision,
1797                    });
1798                }
1799            }
1800            _ => {}
1801        }
1802        Ok(())
1803    }
1804
1805    pub fn kind(&self) -> EventKind {
1806        match self {
1807            Self::RichCommand { .. } => EventKind::RichCommand,
1808            Self::RichRejected { .. } => EventKind::RichRejected,
1809            Self::TreeNavigate { .. } => EventKind::TreeNavigate,
1810            Self::Files(_) => EventKind::Files,
1811            Self::Clipboard { .. } => EventKind::Clipboard,
1812            Self::GridNavigate { .. } => EventKind::GridNavigate,
1813            Self::InputEdit(_) => EventKind::InputEdit,
1814            Self::CollapseComplete { .. } => EventKind::CollapseComplete,
1815            Self::PresenceComplete { .. } => EventKind::PresenceComplete,
1816            Self::ContextMenu { .. } => EventKind::ContextMenu,
1817            Self::Tags { .. } => EventKind::Tags,
1818            Self::Spin { .. } => EventKind::Spin,
1819            Self::Range { .. } => EventKind::Range,
1820            Self::Sheet { .. } => EventKind::Sheet,
1821            Self::NavigationPanel { .. } => EventKind::NavigationPanel,
1822            Self::ScrollKeyboard { .. } => EventKind::ScrollKeyboard,
1823            Self::ImageStatus { .. } => EventKind::ImageStatus,
1824            Self::Menu { .. } => EventKind::Menu,
1825            Self::PlotPointer { .. } => EventKind::PlotPointer,
1826            Self::Pointer { .. } => EventKind::Pointer,
1827            Self::PointerWithin { .. } => EventKind::PointerWithin,
1828            Self::Submit { .. } => EventKind::Submit,
1829            Self::Reset => EventKind::Reset,
1830            Self::Activate => EventKind::Activate,
1831            Self::DisplayClick(_) => EventKind::DisplayClick,
1832            Self::Dismiss(_) => EventKind::Dismiss,
1833            Self::ColorSchemeChanged { .. } => EventKind::ColorSchemeChanged,
1834            Self::Keyboard { .. } => EventKind::Keyboard,
1835            Self::Palette { .. } => EventKind::Palette,
1836            Self::RichEdit(_) => EventKind::RichEdit,
1837            Self::RichSelection(_) => EventKind::RichSelection,
1838            Self::Swipe { .. } => EventKind::Swipe,
1839            Self::Drag { .. } => EventKind::Drag,
1840            Self::ValueChanged { .. } => EventKind::ValueChanged,
1841            Self::Commit { .. } => EventKind::Commit,
1842            Self::CheckedChanged(_) => EventKind::CheckedChanged,
1843            Self::SelectChanged { .. } => EventKind::SelectChanged,
1844            Self::Choice { .. } => EventKind::Choice,
1845            Self::FocusChanged(_) => EventKind::FocusChanged,
1846            Self::FocusWithin { .. } => EventKind::FocusWithin,
1847            Self::Navigate { .. } => EventKind::Navigate,
1848            Self::Typeahead { .. } => EventKind::Typeahead,
1849            Self::Composition { .. } => EventKind::Composition,
1850            Self::Scroll { .. } => EventKind::Scroll,
1851            Self::Resize { .. } => EventKind::Resize,
1852            Self::Anchor { .. } => EventKind::Anchor,
1853        }
1854    }
1855}
1856
1857#[derive(Clone, Debug, PartialEq)]
1858pub enum Input {
1859    Event {
1860        node: NodeId,
1861        event: Event,
1862    },
1863    Response {
1864        token: QueryToken,
1865        /// Applied mutation watermark observed by this request.
1866        applied: u64,
1867        result: Result<QueryValue, Error>,
1868    },
1869}
1870
1871#[derive(Clone, Debug, PartialEq, Eq)]
1872pub enum Error {
1873    Backend(String),
1874    ForeignRuntime,
1875    NodeGone(NodeId),
1876    StaleNode(NodeId),
1877    DuplicateNode(NodeId),
1878    InvalidPlacement(&'static str),
1879    InvalidProps(&'static str),
1880    Unsupported(&'static str),
1881    UnsupportedStyle {
1882        profile: &'static str,
1883        version: u32,
1884        requirement: style::Unsupported,
1885    },
1886    InvalidReceipt {
1887        previous: u64,
1888        applied: u64,
1889    },
1890    QueryWatermark {
1891        expected: u64,
1892        applied: u64,
1893    },
1894    InvalidResponse(&'static str),
1895    InvalidEvent(&'static str),
1896    InputRevision {
1897        current: u64,
1898        incoming: u64,
1899    },
1900    InputRevisionExhausted,
1901    SelectRevision {
1902        current: u64,
1903        incoming: u64,
1904    },
1905    SelectRevisionExhausted,
1906    ImageRevision {
1907        current: u64,
1908        incoming: u64,
1909    },
1910    ImageRevisionExhausted,
1911    SheetRevision {
1912        current: u64,
1913        incoming: u64,
1914    },
1915    SheetRevisionExhausted,
1916    CollapseRevision {
1917        current: u64,
1918        incoming: u64,
1919    },
1920    CollapseRevisionExhausted,
1921    PresenceRevision {
1922        current: u64,
1923        incoming: u64,
1924    },
1925    PresenceRevisionExhausted,
1926}
1927
1928impl std::fmt::Display for Error {
1929    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1930        write!(f, "{self:?}")
1931    }
1932}
1933
1934impl std::error::Error for Error {}
1935
1936/// Applying nodes does not imply pixels have been displayed.
1937/// Successful nonempty apply calls strictly advance this renderer-local
1938/// watermark; empty calls preserve it. It is not a displayed-frame sequence.
1939#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1940pub struct Receipt {
1941    pub applied: u64,
1942}
1943
1944/// Local calls are typed and require no serialization. Each request observes
1945/// every preceding successful apply; adapters must not coalesce across requests.
1946/// A response carries the watermark at request acceptance, even if delivered
1947/// after later commits. Capture results at that barrier, not from a newer tree.
1948/// Errors may leave an applied prefix; adapters do not promise rollback.
1949pub trait Render {
1950    /// Commit adapter-owned display slots after semantic mutations and before
1951    /// actions/queries. This does not allocate semantic element identities.
1952    fn flush_display(&mut self) -> Result<(), Error> {
1953        Ok(())
1954    }
1955    /// Reject descriptor-local limitations before the App changes its logical
1956    /// tree or queues output. None checks creation; Some checks a patch against
1957    /// the supplied current descriptor, including earlier uncommitted changes.
1958    /// Read only these arguments and immutable adapter configuration: no host
1959    /// calls, layout, application callbacks, or committed-tree lookups. Adapters
1960    /// must enforce the same restrictions in apply for callers without an App.
1961    /// This is not a transaction or a guarantee that later host work succeeds.
1962    fn preflight(&self, _node: DescriptorView<'_>, _patch: Option<&Patch>) -> Result<(), Error> {
1963        Ok(())
1964    }
1965    /// Validate adapter-specific ancestor/content constraints against the App's
1966    /// staged semantic tree, including uncommitted Create/Patch/Place changes.
1967    /// New children are checked before identity allocation; existing children
1968    /// before Place/Resume changes the model or output queue. Read only these
1969    /// arguments/configuration: no host tree, layout, I/O or application code.
1970    /// The App checks shared identity/placement semantics first. Default adds
1971    /// no restrictions. Direct apply must enforce the same content rules.
1972    fn preflight_place(
1973        &self,
1974        _tree: &memory::Memory,
1975        _child: memory::Subtree<'_>,
1976        _parent: Option<NodeId>,
1977    ) -> Result<(), Error> {
1978        Ok(())
1979    }
1980    /// Optional local diagnostics. Return an unused or retired handle so its
1981    /// captured clock is dropped outside the caller's renderer borrow.
1982    fn set_profile(&mut self, profile: Option<profile::Profile>) -> Option<profile::Profile> {
1983        profile
1984    }
1985    /// Another local observation can make progress without awaiting I/O, an
1986    /// animation timestamp or a future browser frame. Read-only and never runs
1987    /// application code. Hosts with asynchronous observation keep the default.
1988    fn needs_observe(&self) -> bool {
1989        false
1990    }
1991    /// Declared once per App. Default rejects nonempty inline styles; adapters
1992    /// opt into exactly the declarations/values they preserve or implement.
1993    fn style_profile(&self) -> style::Profile {
1994        style::Profile::NONE
1995    }
1996    /// Event interest is frame metadata. Hosts may use it to avoid observing
1997    /// thousands of nodes whose resize/scroll events nobody consumes.
1998    fn listen(&mut self, _node: NodeId, _kind: EventKind, _enabled: bool) -> Result<(), Error> {
1999        Ok(())
2000    }
2001    /// Whether this host implements the finite local-coordinate plot channel.
2002    /// Static adapters may record interests for later adoption; input adapters
2003    /// must opt in explicitly. This does not enable ordinary Pointer events.
2004    fn supports_plot_pointer(&self) -> bool {
2005        false
2006    }
2007    fn capabilities(&self) -> Capabilities;
2008    fn apply(&mut self, mutations: &[Mutation]) -> Result<Receipt, Error>;
2009    /// Optional immediate physical read at the caller's committed barrier.
2010    /// None means the host requires the queued Bounds query. Never call user code.
2011    fn bounds_now(&mut self, _node: NodeId) -> Option<Result<Rect, Error>> {
2012        None
2013    }
2014    fn request(&mut self, query: Query, token: QueryToken) -> Result<(), Error>;
2015    /// Actions run after a frame's mutations and before subsequent queries.
2016    /// Unsupported focus refusal leaves the semantic tree valid: App treats it
2017    /// as an unfulfilled intent and continues later intents. Backend errors remain
2018    /// fatal. Never synthesize FocusChanged(true) merely for accepting Focus.
2019    fn action(&mut self, _action: Action) -> Result<(), Error> {
2020        Err(Error::Unsupported("platform action"))
2021    }
2022    /// Return queued inputs, never synchronously reenter business closures.
2023    fn drain(&mut self, inputs: &mut Vec<Input>);
2024}
2025
2026mod environment;
2027mod table;
2028pub use environment::{Environment, LanguageTag};
2029pub use table::{MAX_CELL_HEADERS, MAX_TABLE_SPAN, SortDirection, TableMetadata};
2030
2031mod swipe;
2032pub use swipe::SwipeCapture;
2033
2034mod rich_document;
2035pub use rich_document::{
2036    MAX_RICH_BLOCKS, MAX_RICH_LINK_BYTES, MAX_RICH_METADATA_BYTES, MAX_RICH_RUNS,
2037    MAX_RICH_TEXT_BYTES, RichBlock, RichBlockKind, RichDocument, RichFormat, RichMarks, RichPoint,
2038    RichRun, RichSelection,
2039};
2040mod rich;
2041pub use rich::{RichCommand, RichEditorProps, RichSnapshot};