Skip to main content

strata/runtime/
types.rs

1//! Runtime data structures for active focus, scrollbars, hit targets, and editing.
2
3/// Hit-test target result representing a clickable text input element in the blueprint tree.
4#[derive(Clone)]
5pub struct InputHitTarget {
6    pub input_index: usize,
7    pub input_id: Option<String>,
8    pub entity_id: Option<strata_primitives::EntityId>,
9    pub is_multiline: bool,
10    pub current_value: String,
11    pub font_size: f32,
12    pub line_height: f32,
13    pub is_mono: bool,
14    pub font_family: strata_primitives::AtomId,
15    pub content_box_x: f32,
16    pub content_box_y: f32,
17    pub content_box_width: f32,
18    pub content_box_height: f32,
19    pub on_input: Option<std::rc::Rc<dyn Fn(strata_dom::Event)>>,
20    pub on_change: Option<std::rc::Rc<dyn Fn(strata_dom::Event)>>,
21    pub on_submit: Option<std::rc::Rc<dyn Fn(strata_dom::Event)>>,
22    pub on_focus: Option<std::rc::Rc<dyn Fn(strata_dom::Event)>>,
23    pub on_blur: Option<std::rc::Rc<dyn Fn(strata_dom::Event)>>,
24}
25
26/// Active text input state tracked by the runtime while an input has keyboard focus.
27#[derive(Clone)]
28pub struct ActiveInput {
29    pub input_index: usize,
30    pub input_id: Option<String>,
31    pub entity_id: Option<strata_primitives::EntityId>,
32    pub is_multiline: bool,
33    pub state: strata_dom::text_input::TextInputState,
34    pub on_input: Option<std::rc::Rc<dyn Fn(strata_dom::Event)>>,
35    pub on_change: Option<std::rc::Rc<dyn Fn(strata_dom::Event)>>,
36    pub on_submit: Option<std::rc::Rc<dyn Fn(strata_dom::Event)>>,
37    pub on_blur: Option<std::rc::Rc<dyn Fn(strata_dom::Event)>>,
38}
39
40impl std::fmt::Debug for ActiveInput {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("ActiveInput")
43            .field("text", &self.state.text.get())
44            .field("cursor", &self.state.cursor_index.get())
45            .finish()
46    }
47}
48
49/// Active scrollbar state for an overflow container.
50#[derive(Debug, Clone)]
51pub struct ActiveScrollbar {
52    pub bounds: strata_layout::Rect,
53    pub clip_bounds: strata_layout::Rect,
54    pub border_radius: strata_style::types::BorderRadius,
55    pub is_top_layer: bool,
56    pub track_bounds: strata_layout::Rect,
57    pub thumb_bounds: strata_layout::Rect,
58    pub scroll_y: f32,
59    pub max_scroll_y: f32,
60    pub content_h: f32,
61    pub is_id: bool,
62    pub id: String,
63    pub path: Vec<usize>,
64    pub available_travel: f32,
65}
66
67/// Active drag operation on a scrollbar thumb.
68#[derive(Debug, Clone)]
69pub struct ScrollbarDrag {
70    pub is_id: bool,
71    pub id: String,
72    pub path: Vec<usize>,
73    pub start_pointer_y: f32,
74    pub start_scroll_y: f32,
75    pub available_travel: f32,
76    pub max_scroll_y: f32,
77}
78
79/// Active kinetic smooth scroll animation tracking state.
80#[derive(Debug, Clone)]
81pub struct SmoothScrollTracker {
82    pub container_path: Vec<usize>,
83    pub container_id: String,
84    pub is_id: bool,
85    pub max_scroll_y: f32,
86    pub available_travel: f32,
87    pub bounds_y: f32,
88    /// Current interpolated scroll offset in pixels.
89    pub current_y: f32,
90    /// Target scroll position in pixels.
91    pub target_y: f32,
92    /// Initial position at the start of the current impulse.
93    pub start_y: f32,
94    /// Initial velocity in px/s at the start of the current impulse.
95    pub initial_velocity: f32,
96    /// Timestamp when the current impulse started.
97    pub start_time: std::time::Instant,
98    /// Timestamp of the last incoming wheel event (for flick velocity calculation).
99    pub last_event_time: std::time::Instant,
100    /// Critically damped angular frequency (rad/s).
101    pub omega: f32,
102}
103
104/// Internal descriptor of a scrollable target container under the cursor.
105#[derive(Debug, Clone)]
106pub struct ScrollTarget {
107    pub path: Vec<usize>,
108    pub id: Option<String>,
109    pub bounds: strata_layout::Rect,
110    pub max_scroll_x: f32,
111    pub max_scroll_y: f32,
112}
113/// Computes a deterministic 64-bit ID from a hierarchical tree path.
114pub fn path_to_node_id(path: &[usize]) -> u64 {
115    let mut hash = 0xcbf29ce484222325u64;
116    for &idx in path {
117        hash ^= idx as u64;
118        hash = hash.wrapping_mul(0x100000001b3u64);
119    }
120    hash
121}
122
123/// Editing commands that can be applied to the focused text input from any UI surface.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum EditCommand {
126    Undo,
127    Redo,
128    Cut,
129    Copy,
130    Paste,
131    SelectAll,
132}
133
134/// Action result from a pointer-down event dispatch.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum PointerDownAction {
137    /// Not handled by any element or active input.
138    Ignored,
139    /// Caret or selection inside the already-active focused input moved. Requires redraw only.
140    CaretMoved,
141    /// Focus transitioned to a new or different input. Requires layout/rebuild update.
142    FocusChanged,
143    /// DOM PointerDown or MouseDown event listener was invoked.
144    DomListenerInvoked,
145}
146
147impl PointerDownAction {
148    #[inline]
149    pub fn is_handled(self) -> bool {
150        self != PointerDownAction::Ignored
151    }
152
153    #[inline]
154    pub fn needs_rebuild(self) -> bool {
155        matches!(
156            self,
157            PointerDownAction::FocusChanged | PointerDownAction::DomListenerInvoked
158        )
159    }
160
161    #[inline]
162    pub fn needs_redraw(self) -> bool {
163        self != PointerDownAction::Ignored
164    }
165}
166
167/// Action result from a pointer-move event dispatch.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum PointerMoveAction {
170    /// Not handled.
171    Ignored,
172    /// Mouse drag text selection range updated in active input. Requires redraw only.
173    SelectionDragged,
174    /// DOM PointerMove or MouseMove event listener was invoked.
175    DomListenerInvoked,
176}
177
178impl PointerMoveAction {
179    #[inline]
180    pub fn is_handled(self) -> bool {
181        self != PointerMoveAction::Ignored
182    }
183
184    #[inline]
185    pub fn needs_rebuild(self) -> bool {
186        self == PointerMoveAction::DomListenerInvoked
187    }
188
189    #[inline]
190    pub fn needs_redraw(self) -> bool {
191        self != PointerMoveAction::Ignored
192    }
193}
194
195/// Action result from a pointer-up event dispatch.
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub enum PointerUpAction {
198    /// Not handled.
199    Ignored,
200    /// Mouse drag text selection finished. Requires redraw only.
201    SelectionEnded,
202    /// DOM PointerUp or MouseUp event listener was invoked.
203    DomListenerInvoked,
204}
205
206impl PointerUpAction {
207    #[inline]
208    pub fn is_handled(self) -> bool {
209        self != PointerUpAction::Ignored
210    }
211
212    #[inline]
213    pub fn needs_rebuild(self) -> bool {
214        self == PointerUpAction::DomListenerInvoked
215    }
216
217    #[inline]
218    pub fn needs_redraw(self) -> bool {
219        self != PointerUpAction::Ignored
220    }
221}
222
223/// Outcome of dispatching a platform keyboard or text event.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum KeyDispatchResult {
226    /// Key was not handled by any focused input or container scroll.
227    Ignored,
228    /// Caret moved, selection range updated, or page scrolled without mutating component state. Requires redraw only.
229    RedrawOnly,
230    /// Text buffer was modified or form submitted/blurred, requiring layout/signal recalculation.
231    NeedsRebuild,
232}
233
234impl KeyDispatchResult {
235    #[inline]
236    pub fn is_handled(self) -> bool {
237        self != KeyDispatchResult::Ignored
238    }
239
240    #[inline]
241    pub fn needs_rebuild(self) -> bool {
242        self == KeyDispatchResult::NeedsRebuild
243    }
244
245    #[inline]
246    pub fn needs_redraw(self) -> bool {
247        self != KeyDispatchResult::Ignored
248    }
249}
250
251/// Binding between a dynamic text closure and its target location in the layout hierarchy.
252#[derive(Clone)]
253pub struct DynamicTextBinding {
254    pub path: Vec<usize>,
255    pub closure: std::rc::Rc<dyn Fn() -> String>,
256    pub last_value: String,
257}
258
259impl std::fmt::Debug for DynamicTextBinding {
260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        f.debug_struct("DynamicTextBinding")
262            .field("path", &self.path)
263            .field("last_value", &self.last_value)
264            .finish()
265    }
266}
267
268/// Interaction context describing active pointer, keyboard focus, and theme interaction state.
269#[derive(Debug, Clone, Default, PartialEq, Eq)]
270pub struct InteractionContext<'a> {
271    pub hovered_path: Option<&'a [usize]>,
272    pub focused_path: Option<&'a [usize]>,
273    pub is_mouse_down: bool,
274    pub is_dark_mode: bool,
275}
276
277/// Element selector metadata used when matching `<style>` rules across ancestors and siblings.
278#[derive(Debug, Clone)]
279pub(crate) struct CascadeElementMeta {
280    pub tag: &'static str,
281    pub classes: Vec<String>,
282    pub id: Option<String>,
283    pub attributes: Vec<(String, String)>,
284    pub pseudo_state: strata_style::selector::PseudoState,
285}
286
287/// Active DOM drag-and-drop interaction state (`ondragstart`, `ondrag`, `ondragenter`, `ondragover`, `ondragleave`, `ondrop`, `ondragend`).
288#[derive(Debug, Clone)]
289pub struct ActiveDomDrag {
290    pub source_path: Vec<usize>,
291    pub start_pos: (f32, f32),
292    pub started: bool,
293    pub last_over_path: Option<Vec<usize>>,
294    pub data_transfer: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<String, String>>>,
295}
296
297/// Precomputed stylesheet selector dependency index using 64-bit Bloom filters and
298/// exact tag/class/id sets so static `<style>` sheets do not disable incremental
299/// layout reconciliation or fast paint-only hover restyling across unrelated subtrees.
300#[derive(Debug, Clone, Default)]
301pub(crate) struct StylesheetSelectorIndex {
302    pub hover_bloom: u64,
303    pub focus_bloom: u64,
304    pub hover_tags: std::collections::HashSet<String>,
305    pub hover_classes: std::collections::HashSet<String>,
306    pub hover_ids: std::collections::HashSet<String>,
307    pub focus_tags: std::collections::HashSet<String>,
308    pub focus_classes: std::collections::HashSet<String>,
309    pub focus_ids: std::collections::HashSet<String>,
310    pub has_any_hover_rule: bool,
311    pub has_any_focus_rule: bool,
312    pub has_unbounded_hover_rule: bool,
313    pub has_unbounded_focus_rule: bool,
314    pub has_sibling_hover_rule: bool,
315    pub has_sibling_combinator_or_positional_rules: bool,
316    pub has_descendant_combinator_rules: bool,
317}
318
319impl StylesheetSelectorIndex {
320    #[inline]
321    fn bloom_bits(s: &str) -> u64 {
322        let mut h1: u64 = 0xcbf29ce484222325;
323        let mut h2: u64 = 0x84222325cbf29ce4;
324        for b in s.bytes() {
325            let lb = b.to_ascii_lowercase() as u64;
326            h1 ^= lb;
327            h1 = h1.wrapping_mul(0x100000001b3);
328            h2 = h2.wrapping_mul(0x9e3779b97f4a7c15) ^ lb;
329        }
330        (1u64 << (h1 & 63)) | (1u64 << ((h2 >> 16) & 63))
331    }
332
333    fn compound_has_pseudo(comp: &strata_style::selector::CompoundSelector, target: &str) -> bool {
334        comp.parts.iter().any(|p| match p {
335            strata_style::selector::SelectorPart::PseudoClass(name) => {
336                let n = name.trim().to_ascii_lowercase();
337                n == target || n.contains(&format!(":{target}"))
338            }
339            _ => false,
340        })
341    }
342
343    fn compound_has_positional_pseudo(comp: &strata_style::selector::CompoundSelector) -> bool {
344        comp.parts.iter().any(|p| match p {
345            strata_style::selector::SelectorPart::PseudoClass(name) => {
346                let n = name.trim().to_ascii_lowercase();
347                n.starts_with("nth-")
348                    || n == "first-child"
349                    || n == "last-child"
350                    || n == "only-child"
351                    || n == "first-of-type"
352                    || n == "last-of-type"
353                    || n == "only-of-type"
354                    || n == "empty"
355            }
356            _ => false,
357        })
358    }
359
360    fn index_compound_keys(
361        comp: &strata_style::selector::CompoundSelector,
362        bloom: &mut u64,
363        tags: &mut std::collections::HashSet<String>,
364        classes: &mut std::collections::HashSet<String>,
365        ids: &mut std::collections::HashSet<String>,
366        unbounded: &mut bool,
367    ) {
368        let mut has_key = false;
369        for part in &comp.parts {
370            match part {
371                strata_style::selector::SelectorPart::Tag(t) => {
372                    let k = t.to_ascii_lowercase();
373                    *bloom |= Self::bloom_bits(&k);
374                    tags.insert(k);
375                    has_key = true;
376                }
377                strata_style::selector::SelectorPart::Class(c) => {
378                    let k = c.to_ascii_lowercase();
379                    *bloom |= Self::bloom_bits(&k);
380                    classes.insert(k);
381                    has_key = true;
382                }
383                strata_style::selector::SelectorPart::Id(id) => {
384                    let k = id.to_ascii_lowercase();
385                    *bloom |= Self::bloom_bits(&k);
386                    ids.insert(k);
387                    has_key = true;
388                }
389                _ => {}
390            }
391        }
392        if !has_key {
393            *unbounded = true;
394        }
395    }
396
397    pub fn from_stylesheets(sheets: &[std::sync::Arc<strata_style::StyleSheet>]) -> Self {
398        let mut idx = Self::default();
399        for sheet in sheets {
400            for rule in &sheet.rules {
401                for sel in &rule.selectors {
402                    if !sel.steps.is_empty() {
403                        idx.has_descendant_combinator_rules = true;
404                    }
405                    let has_sibling_comb = sel.steps.iter().any(|(comb, _)| {
406                        matches!(
407                            comb,
408                            strata_style::selector::Combinator::AdjacentSibling
409                                | strata_style::selector::Combinator::SubsequentSibling
410                        )
411                    });
412                    let has_positional = Self::compound_has_positional_pseudo(&sel.target)
413                        || sel
414                            .steps
415                            .iter()
416                            .any(|(_, c)| Self::compound_has_positional_pseudo(c));
417                    if has_sibling_comb || has_positional {
418                        idx.has_sibling_combinator_or_positional_rules = true;
419                    }
420
421                    if sel.has_any_hover_pseudo() {
422                        idx.has_any_hover_rule = true;
423                        if has_sibling_comb {
424                            idx.has_sibling_hover_rule = true;
425                        }
426                        if Self::compound_has_pseudo(&sel.target, "hover") {
427                            Self::index_compound_keys(
428                                &sel.target,
429                                &mut idx.hover_bloom,
430                                &mut idx.hover_tags,
431                                &mut idx.hover_classes,
432                                &mut idx.hover_ids,
433                                &mut idx.has_unbounded_hover_rule,
434                            );
435                        }
436                        for (_, step_comp) in &sel.steps {
437                            if Self::compound_has_pseudo(step_comp, "hover") {
438                                Self::index_compound_keys(
439                                    step_comp,
440                                    &mut idx.hover_bloom,
441                                    &mut idx.hover_tags,
442                                    &mut idx.hover_classes,
443                                    &mut idx.hover_ids,
444                                    &mut idx.has_unbounded_hover_rule,
445                                );
446                            }
447                        }
448                    }
449
450                    let target_focus = Self::compound_has_pseudo(&sel.target, "focus")
451                        || Self::compound_has_pseudo(&sel.target, "focus-within")
452                        || Self::compound_has_pseudo(&sel.target, "focus-visible");
453                    let step_focus = sel.steps.iter().any(|(_, c)| {
454                        Self::compound_has_pseudo(c, "focus")
455                            || Self::compound_has_pseudo(c, "focus-within")
456                            || Self::compound_has_pseudo(c, "focus-visible")
457                    });
458                    if target_focus || step_focus {
459                        idx.has_any_focus_rule = true;
460                        if target_focus {
461                            Self::index_compound_keys(
462                                &sel.target,
463                                &mut idx.focus_bloom,
464                                &mut idx.focus_tags,
465                                &mut idx.focus_classes,
466                                &mut idx.focus_ids,
467                                &mut idx.has_unbounded_focus_rule,
468                            );
469                        }
470                        for (_, step_comp) in &sel.steps {
471                            if Self::compound_has_pseudo(step_comp, "focus")
472                                || Self::compound_has_pseudo(step_comp, "focus-within")
473                                || Self::compound_has_pseudo(step_comp, "focus-visible")
474                            {
475                                Self::index_compound_keys(
476                                    step_comp,
477                                    &mut idx.focus_bloom,
478                                    &mut idx.focus_tags,
479                                    &mut idx.focus_classes,
480                                    &mut idx.focus_ids,
481                                    &mut idx.has_unbounded_focus_rule,
482                                );
483                            }
484                        }
485                    }
486                }
487            }
488        }
489        idx
490    }
491
492    #[inline]
493    pub fn node_may_match_hover(&self, tag: &str, id: Option<&str>, classes: &[String]) -> bool {
494        if !self.has_any_hover_rule {
495            return false;
496        }
497        if self.has_unbounded_hover_rule {
498            return true;
499        }
500        let tb = Self::bloom_bits(tag);
501        if (self.hover_bloom & tb) == tb && self.hover_tags.contains(&tag.to_ascii_lowercase()) {
502            return true;
503        }
504        if let Some(id_str) = id {
505            let ib = Self::bloom_bits(id_str);
506            if (self.hover_bloom & ib) == ib && self.hover_ids.contains(&id_str.to_ascii_lowercase())
507            {
508                return true;
509            }
510        }
511        for cls in classes {
512            let cb = Self::bloom_bits(cls);
513            if (self.hover_bloom & cb) == cb
514                && self.hover_classes.contains(&cls.to_ascii_lowercase())
515            {
516                return true;
517            }
518        }
519        false
520    }
521
522    #[inline]
523    #[allow(dead_code)]
524    pub fn node_may_match_focus(&self, tag: &str, id: Option<&str>, classes: &[String]) -> bool {
525        if !self.has_any_focus_rule {
526            return false;
527        }
528        if self.has_unbounded_focus_rule {
529            return true;
530        }
531        let tb = Self::bloom_bits(tag);
532        if (self.focus_bloom & tb) == tb && self.focus_tags.contains(&tag.to_ascii_lowercase()) {
533            return true;
534        }
535        if let Some(id_str) = id {
536            let ib = Self::bloom_bits(id_str);
537            if (self.focus_bloom & ib) == ib && self.focus_ids.contains(&id_str.to_ascii_lowercase())
538            {
539                return true;
540            }
541        }
542        for cls in classes {
543            let cb = Self::bloom_bits(cls);
544            if (self.focus_bloom & cb) == cb
545                && self.focus_classes.contains(&cls.to_ascii_lowercase())
546            {
547                return true;
548            }
549        }
550        false
551    }
552}
553
554/// Per-update reconciliation statistics exposed for runtime profiling and observability.
555#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
556pub struct ReconcileStats {
557    pub reused_subtrees: u32,
558    pub rebuilt_nodes: u32,
559}
560
561/// Structured attribution explaining why a frame triggered work (`Dirty`, `RepaintCanvas3D`, or `Clean`).
562#[derive(Debug, Clone, PartialEq, Eq)]
563pub enum RebuildReason {
564    Clean,
565    InitialMount,
566    SignalWrite(String),
567    PlatformEvent(String),
568    HoverFastPath,
569    HoverFastPathFailed(String),
570    LayoutReconcileBailout(String),
571    RepaintCanvas3D,
572    AnimationTick,
573    JsTimerOrMutation,
574    FrameHookDirty,
575    WindowResize,
576    McpCommand(String),
577    HmrPatch(u64),
578}
579
580impl std::fmt::Display for RebuildReason {
581    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
582        match self {
583            Self::Clean => write!(f, "Clean"),
584            Self::InitialMount => write!(f, "InitialMount"),
585            Self::SignalWrite(sig) => write!(f, "SignalWrite({sig})"),
586            Self::PlatformEvent(ev) => write!(f, "PlatformEvent({ev})"),
587            Self::HoverFastPath => write!(f, "HoverFastPath"),
588            Self::HoverFastPathFailed(r) => write!(f, "HoverFastPathFailed({r})"),
589            Self::LayoutReconcileBailout(r) => write!(f, "LayoutReconcileBailout({r})"),
590            Self::RepaintCanvas3D => write!(f, "RepaintCanvas3D"),
591            Self::AnimationTick => write!(f, "AnimationTick"),
592            Self::JsTimerOrMutation => write!(f, "JsTimerOrMutation"),
593            Self::FrameHookDirty => write!(f, "FrameHookDirty"),
594            Self::WindowResize => write!(f, "WindowResize"),
595            Self::McpCommand(cmd) => write!(f, "McpCommand({cmd})"),
596            Self::HmrPatch(epoch) => write!(f, "HmrPatch(epoch={epoch})"),
597        }
598    }
599}