Skip to main content

strata/runtime/
scroll.rs

1//! Viewport clamping, scroll offsets, smooth scrolling, and scroll event dispatch.
2
3use super::*;
4
5impl AppRuntime {
6    /// Shifts every `data-clamp-viewport` element (popups such as context menus) back inside the
7    /// viewport with an 8px margin, using the live viewport size rather than any hardcoded value.
8    pub fn apply_viewport_clamps(&mut self) {
9        let (vw, vh) = (self.viewport_width, self.viewport_height);
10        Self::clamp_walk(&self.root_blueprint, &mut self.layout_root, vw, vh);
11    }
12
13    pub(crate) fn clamp_walk(blueprint: &NodeBlueprint, layout: &mut LayoutNode, vw: f32, vh: f32) {
14        const MARGIN: f32 = 8.0;
15        match blueprint {
16            NodeBlueprint::Element {
17                attributes,
18                children,
19                ..
20            } => {
21                let clamp = attributes.iter().any(|a| {
22                    matches!(a, strata_dom::Attribute::Property { key, .. } if key == "data-clamp-viewport")
23                });
24                if clamp {
25                    let b = layout.geometry.border_box;
26                    let mut dx = 0.0;
27                    let mut dy = 0.0;
28                    if b.x + b.width > vw - MARGIN {
29                        dx = vw - MARGIN - b.width - b.x;
30                    }
31                    if b.x + dx < MARGIN {
32                        dx = MARGIN - b.x;
33                    }
34                    if b.y + b.height > vh - MARGIN {
35                        dy = vh - MARGIN - b.height - b.y;
36                    }
37                    if b.y + dy < MARGIN {
38                        dy = MARGIN - b.y;
39                    }
40                    strata_layout::box_model::translate_node_and_descendants(layout, dx, dy);
41                    return;
42                }
43                let mut flat_children = Vec::new();
44                for c in children {
45                    Self::flatten_blueprints(c, &mut flat_children);
46                }
47                for (&child_bp, child_layout) in
48                    flat_children.iter().zip(layout.children.iter_mut())
49                {
50                    Self::clamp_walk(child_bp, child_layout, vw, vh);
51                }
52            }
53            NodeBlueprint::Fragment(children) => {
54                for (child_bp, child_layout) in children.iter().zip(layout.children.iter_mut()) {
55                    Self::clamp_walk(child_bp, child_layout, vw, vh);
56                }
57            }
58            _ => {}
59        }
60    }
61
62    /// Traverses the LayoutNode hierarchy down a slice of child indices in O(depth).
63    pub fn get_layout_node_mut<'a>(
64        root: &'a mut LayoutNode,
65        path: &[usize],
66    ) -> Option<&'a mut LayoutNode> {
67        let mut current = root;
68        for &idx in path {
69            if idx < current.children.len() {
70                current = &mut current.children[idx];
71            } else {
72                return None;
73            }
74        }
75        Some(current)
76    }
77
78    /// Traverses the LayoutNode hierarchy down a slice of child indices in O(depth).
79    pub fn get_layout_node<'a>(root: &'a LayoutNode, path: &[usize]) -> Option<&'a LayoutNode> {
80        let mut current = root;
81        for &idx in path {
82            current = current.children.get(idx)?;
83        }
84        Some(current)
85    }
86
87    /// Restores any scrollable containers and anchored `<Portal>` nodes previously translated by
88    /// `apply_scroll_offsets` back to their baseline unshifted coordinates so layout computations
89    /// and metric measurements remain invariant.
90    pub fn unapply_scroll_offsets(&mut self) {
91        if !self.applied_portal_offsets.is_empty() {
92            for (path, &(dx, dy)) in &self.applied_portal_offsets {
93                if dx.abs() > 0.0001 || dy.abs() > 0.0001 {
94                    if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, path) {
95                        target.translate(-dx, -dy);
96                    }
97                }
98            }
99            self.applied_portal_offsets.clear();
100        }
101
102        if self.applied_scroll_offsets.is_empty() {
103            return;
104        }
105        for (path, &(applied_x, applied_y)) in &self.applied_scroll_offsets {
106            if applied_x.abs() > 0.0001 || applied_y.abs() > 0.0001 {
107                if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, path) {
108                    let target_fixed_cb = target.style.establishes_fixed_containing_block();
109                    let target_abs_cb = target.style.position
110                        != strata_style::types::Position::Static
111                        || target_fixed_cb;
112                    for child in &mut target.children {
113                        child.translate_scrolled(
114                            applied_x,
115                            applied_y,
116                            target_abs_cb,
117                            target_fixed_cb,
118                        );
119                    }
120                    for line in &mut target.line_boxes {
121                        line.bounds.x += applied_x;
122                        line.bounds.y += applied_y;
123                        for frag in &mut line.text_fragments {
124                            frag.bounds.x += applied_x;
125                            frag.bounds.y += applied_y;
126                            frag.baseline_y += applied_y;
127                        }
128                        for atomic in &mut line.atomic_fragments {
129                            atomic.bounds.x += applied_x;
130                            atomic.bounds.y += applied_y;
131                        }
132                    }
133                }
134            }
135        }
136        self.applied_scroll_offsets.clear();
137    }
138
139    /// Discovers scrollable containers, clamps offsets, translates children, computes scrollbars,
140    /// and anchors top-layer `<Portal>` overlays to their trigger elements' live post-scroll bounds.
141    pub fn apply_scroll_offsets(&mut self) {
142        self.active_scrollbars.clear();
143        let mut path = Vec::new();
144        Self::apply_scroll_walk(
145            &self.root_blueprint,
146            &mut self.layout_root,
147            &mut path,
148            &self.scroll_offsets,
149            &self.scroll_offsets_by_id,
150            &mut self.applied_scroll_offsets,
151            &mut self.active_scrollbars,
152        );
153        self.flush_pending_scroll_commands();
154        self.sync_scroll_animations();
155        self.resolve_top_layer_portals();
156    }
157
158    fn subtree_has_portal_anchor(node: &LayoutNode, depth: usize) -> bool {
159        if depth >= 256 || matches!(node.style.display, strata_style::types::Display::None) {
160            return false;
161        }
162        if node.portal_anchor.is_some() {
163            return true;
164        }
165        node.children
166            .iter()
167            .any(|c| Self::subtree_has_portal_anchor(c, depth + 1))
168    }
169
170    fn insert_anchor_key(
171        map: &mut std::collections::HashMap<String, Vec<usize>>,
172        raw_key: &str,
173        path: &[usize],
174    ) {
175        let trimmed = raw_key.trim();
176        if trimmed.is_empty() {
177            return;
178        }
179        let p = path.to_vec();
180        map.insert(trimmed.to_string(), p.clone());
181        if let Some(stripped) = trimmed.strip_prefix("--") {
182            if !stripped.is_empty() {
183                map.entry(stripped.to_string()).or_insert_with(|| p.clone());
184            }
185        } else {
186            map.entry(format!("--{}", trimmed)).or_insert(p);
187        }
188    }
189
190    fn collect_anchor_paths(
191        node: &LayoutNode,
192        current_path: &mut Vec<usize>,
193        out: &mut std::collections::HashMap<String, Vec<usize>>,
194    ) {
195        if current_path.len() >= 256
196            || matches!(node.style.display, strata_style::types::Display::None)
197        {
198            return;
199        }
200        if let Some(ref id) = node.element_id {
201            Self::insert_anchor_key(out, id, current_path);
202        }
203        if let Some(ref aname) = node.anchor_name {
204            Self::insert_anchor_key(out, aname, current_path);
205        }
206        for (idx, child) in node.children.iter().enumerate() {
207            current_path.push(idx);
208            Self::collect_anchor_paths(child, current_path, out);
209            current_path.pop();
210        }
211    }
212
213    fn collect_anchored_portal_paths(
214        node: &LayoutNode,
215        current_path: &mut Vec<usize>,
216        out: &mut Vec<Vec<usize>>,
217    ) {
218        if current_path.len() >= 256
219            || matches!(node.style.display, strata_style::types::Display::None)
220        {
221            return;
222        }
223        if node.portal_anchor.is_some() {
224            out.push(current_path.clone());
225        }
226        for (idx, child) in node.children.iter().enumerate() {
227            current_path.push(idx);
228            Self::collect_anchored_portal_paths(child, current_path, out);
229            current_path.pop();
230        }
231    }
232
233    /// Resolves anchored `<Portal>` / CSS `position-anchor` nodes against their trigger elements'
234    /// live post-scroll bounding boxes with automatic viewport collision flipping (`bottom-end <-> top-end`)
235    /// and viewport margin shifting.
236    pub fn resolve_top_layer_portals(&mut self) {
237        let has_any = Self::subtree_has_portal_anchor(&self.layout_root, 0);
238        self.has_anchored_portals = has_any;
239        if !has_any {
240            return;
241        }
242
243        let mut anchor_paths = std::collections::HashMap::new();
244        let mut path_buf = Vec::new();
245        Self::collect_anchor_paths(&self.layout_root, &mut path_buf, &mut anchor_paths);
246
247        let mut portal_paths = Vec::new();
248        path_buf.clear();
249        Self::collect_anchored_portal_paths(&self.layout_root, &mut path_buf, &mut portal_paths);
250
251        let viewport_rect =
252            strata_layout::Rect::new(0.0, 0.0, self.viewport_width, self.viewport_height);
253
254        for portal_path in portal_paths {
255            let Some((spec, cur_box)) = Self::get_layout_node(&self.layout_root, &portal_path)
256                .and_then(|n| {
257                    n.portal_anchor
258                        .as_deref()
259                        .cloned()
260                        .map(|s| (s, n.geometry.border_box))
261                })
262            else {
263                continue;
264            };
265
266            let key = spec.anchor_id.trim();
267            let anchor_path_opt = anchor_paths
268                .get(key)
269                .or_else(|| key.strip_prefix("--").and_then(|s| anchor_paths.get(s)));
270            let Some(anchor_rect) = anchor_path_opt
271                .and_then(|ap| Self::get_layout_node(&self.layout_root, ap))
272                .map(|n| n.geometry.border_box)
273            else {
274                continue;
275            };
276
277            let mut active_box = cur_box;
278            if spec.match_width && (active_box.width - anchor_rect.width).abs() > 0.5 {
279                let prior = self
280                    .applied_portal_offsets
281                    .remove(&portal_path)
282                    .unwrap_or((0.0, 0.0));
283                if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, &portal_path)
284                {
285                    if prior.0.abs() > 0.0001 || prior.1.abs() > 0.0001 {
286                        target.translate(-prior.0, -prior.1);
287                    }
288                    target.style.width = strata_style::types::Dimension::Px(anchor_rect.width);
289                    strata_layout::solve_out_of_flow_box(
290                        target,
291                        viewport_rect,
292                        viewport_rect,
293                        true,
294                    );
295                    active_box = target.geometry.border_box;
296                }
297            }
298
299            let (target_x, target_y, _resolved_placement) = strata_layout::solve_anchored_position(
300                anchor_rect,
301                active_box.width,
302                active_box.height,
303                spec.placement,
304                spec.offset,
305                spec.flip,
306                spec.shift,
307                spec.viewport_padding,
308                viewport_rect,
309            );
310
311            let dx = target_x - active_box.x;
312            let dy = target_y - active_box.y;
313            if dx.abs() > 0.0001 || dy.abs() > 0.0001 {
314                if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, &portal_path)
315                {
316                    target.translate(dx, dy);
317                }
318                let entry = self
319                    .applied_portal_offsets
320                    .entry(portal_path)
321                    .or_insert((0.0, 0.0));
322                entry.0 += dx;
323                entry.1 += dy;
324            }
325        }
326    }
327
328    pub(crate) fn apply_scroll_walk(
329        blueprint: &NodeBlueprint,
330        layout: &mut LayoutNode,
331        current_path: &mut Vec<usize>,
332        scroll_offsets: &std::collections::HashMap<Vec<usize>, (f32, f32)>,
333        scroll_offsets_by_id: &std::collections::HashMap<String, (f32, f32)>,
334        applied_scroll_offsets: &mut std::collections::HashMap<Vec<usize>, (f32, f32)>,
335        active_scrollbars: &mut Vec<ActiveScrollbar>,
336    ) {
337        if matches!(layout.style.display, strata_style::types::Display::None) {
338            return;
339        }
340
341        let is_scroll_y = matches!(
342            layout.style.overflow_y,
343            strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
344        );
345        let is_scroll_x = matches!(
346            layout.style.overflow_x,
347            strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
348        );
349
350        let elem_id = match blueprint {
351            NodeBlueprint::Element { attributes, .. } => attributes.iter().find_map(|a| {
352                if let strata_dom::Attribute::Property { key, value } = a {
353                    if key == "id" {
354                        Some(value.clone())
355                    } else {
356                        None
357                    }
358                } else {
359                    None
360                }
361            }),
362            _ => None,
363        };
364
365        if is_scroll_y || is_scroll_x {
366            let viewport_w = layout.geometry.content_box.width;
367            let viewport_h = layout.geometry.content_box.height;
368
369            let mut max_child_x = layout.geometry.content_box.x;
370            let mut max_child_y = layout.geometry.content_box.y;
371
372            for child in &layout.children {
373                if child.style.position == strata_style::types::Position::Absolute
374                    || child.style.position == strata_style::types::Position::Fixed
375                {
376                    continue;
377                }
378                max_child_x =
379                    max_child_x.max(child.geometry.border_box.x + child.geometry.border_box.width);
380                max_child_y =
381                    max_child_y.max(child.geometry.border_box.y + child.geometry.border_box.height);
382            }
383            for line in &layout.line_boxes {
384                max_child_x = max_child_x.max(line.bounds.x + line.bounds.width);
385                max_child_y = max_child_y.max(line.bounds.y + line.bounds.height);
386            }
387
388            let content_w = (max_child_x - layout.geometry.content_box.x).max(0.0);
389            let content_h = (max_child_y - layout.geometry.content_box.y).max(0.0);
390            let max_scroll_x = (content_w - viewport_w).max(0.0);
391            let max_scroll_y = (content_h - viewport_h).max(0.0);
392
393            let (stored_x, stored_y) = if let Some(ref id) = elem_id {
394                scroll_offsets_by_id
395                    .get(id)
396                    .copied()
397                    .or_else(|| scroll_offsets.get(current_path).copied())
398                    .unwrap_or((0.0, 0.0))
399            } else {
400                scroll_offsets
401                    .get(current_path)
402                    .copied()
403                    .unwrap_or((0.0, 0.0))
404            };
405
406            let clamped_x = stored_x.clamp(0.0, max_scroll_x);
407            let clamped_y = stored_y.clamp(0.0, max_scroll_y);
408
409            if let Some(ref id) = elem_id {
410                strata_dom::hooks::set_live_scroll_offset(id, clamped_x, clamped_y);
411            }
412
413            if clamped_x > 0.0 || clamped_y > 0.0 {
414                let target_fixed_cb = layout.style.establishes_fixed_containing_block();
415                let target_abs_cb = layout.style.position != strata_style::types::Position::Static
416                    || target_fixed_cb;
417                for child in &mut layout.children {
418                    child.translate_scrolled(
419                        -clamped_x,
420                        -clamped_y,
421                        target_abs_cb,
422                        target_fixed_cb,
423                    );
424                }
425                for line in &mut layout.line_boxes {
426                    line.bounds.x -= clamped_x;
427                    line.bounds.y -= clamped_y;
428                    for frag in &mut line.text_fragments {
429                        frag.bounds.x -= clamped_x;
430                        frag.bounds.y -= clamped_y;
431                        frag.baseline_y -= clamped_y;
432                    }
433                    for atomic in &mut line.atomic_fragments {
434                        atomic.bounds.x -= clamped_x;
435                        atomic.bounds.y -= clamped_y;
436                    }
437                }
438                applied_scroll_offsets.insert(current_path.clone(), (clamped_x, clamped_y));
439            }
440
441            if is_scroll_y && max_scroll_y > 0.0 && viewport_h > 0.0 {
442                let border_box = layout.geometry.border_box;
443                let track_width = 10.0;
444                let track_x = border_box.x + border_box.width - track_width;
445                let track_y = border_box.y;
446                let track_h = border_box.height;
447                let track_bounds = strata_layout::Rect::new(track_x, track_y, track_width, track_h);
448
449                let min_thumb = 24.0_f32.min(track_h);
450                let thumb_h = ((viewport_h / content_h.max(1.0)) * track_h).clamp(min_thumb, track_h);
451                let available_travel = (track_h - thumb_h).max(0.0);
452                let thumb_y = if max_scroll_y > 0.0 && available_travel > 0.0 {
453                    track_y + (clamped_y / max_scroll_y) * available_travel
454                } else {
455                    track_y
456                };
457
458                let thumb_bounds = strata_layout::Rect::new(track_x, thumb_y, track_width, thumb_h);
459                active_scrollbars.push(ActiveScrollbar {
460                    bounds: border_box,
461                    track_bounds,
462                    thumb_bounds,
463                    scroll_y: clamped_y,
464                    max_scroll_y,
465                    content_h,
466                    is_id: elem_id.is_some(),
467                    id: elem_id.clone().unwrap_or_default(),
468                    path: current_path.clone(),
469                    available_travel,
470                });
471            }
472        }
473
474        // Recursively walk children
475        match blueprint {
476            NodeBlueprint::Element { children, .. } => {
477                let mut flat_children = Vec::new();
478                for c in children {
479                    Self::flatten_blueprints(c, &mut flat_children);
480                }
481                for (i, (&child_bp, child_layout)) in flat_children
482                    .iter()
483                    .zip(layout.children.iter_mut())
484                    .enumerate()
485                {
486                    current_path.push(i);
487                    Self::apply_scroll_walk(
488                        child_bp,
489                        child_layout,
490                        current_path,
491                        scroll_offsets,
492                        scroll_offsets_by_id,
493                        applied_scroll_offsets,
494                        active_scrollbars,
495                    );
496                    current_path.pop();
497                }
498            }
499            NodeBlueprint::Fragment(children) => {
500                let mut flat_children = Vec::new();
501                for c in children {
502                    Self::flatten_blueprints(c, &mut flat_children);
503                }
504                for (i, (&child_bp, child_layout)) in flat_children
505                    .iter()
506                    .zip(layout.children.iter_mut())
507                    .enumerate()
508                {
509                    current_path.push(i);
510                    Self::apply_scroll_walk(
511                        child_bp,
512                        child_layout,
513                        current_path,
514                        scroll_offsets,
515                        scroll_offsets_by_id,
516                        applied_scroll_offsets,
517                        active_scrollbars,
518                    );
519                    current_path.pop();
520                }
521            }
522            _ => {}
523        }
524    }
525
526    /// Helper translating children and line fragments in an overflowing container by `-dy` and recording offsets.
527    pub(crate) fn apply_scroll_delta_to_container(
528        &mut self,
529        path: &[usize],
530        is_id: bool,
531        id: &str,
532        new_scroll_y: f32,
533        dy: f32,
534        max_scroll_y: f32,
535        available_travel: f32,
536        bounds_y: f32,
537    ) {
538        let cur_x = self
539            .scroll_offsets
540            .get(path)
541            .map(|(x, _)| *x)
542            .unwrap_or(0.0);
543        if is_id && !id.is_empty() {
544            self.scroll_offsets_by_id
545                .insert(id.to_string(), (cur_x, new_scroll_y));
546            strata_dom::hooks::set_live_scroll_offset(id, cur_x, new_scroll_y);
547        }
548        self.scroll_offsets
549            .insert(path.to_vec(), (cur_x, new_scroll_y));
550        self.applied_scroll_offsets
551            .insert(path.to_vec(), (cur_x, new_scroll_y));
552
553        let mut content_h = 0.0_f32;
554        if let Some(b) = self.active_scrollbars.iter_mut().find(|b| b.path == path) {
555            b.scroll_y = new_scroll_y;
556            content_h = b.content_h;
557            if max_scroll_y > 0.0 && available_travel > 0.0 {
558                b.thumb_bounds.y = bounds_y + (new_scroll_y / max_scroll_y) * available_travel;
559            }
560        }
561
562        let mut client_w = 0.0_f32;
563        let mut client_h = 0.0_f32;
564        if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, path) {
565            client_w = target.geometry.content_box.width;
566            client_h = target.geometry.content_box.height;
567            if content_h <= 0.0 {
568                content_h = client_h + max_scroll_y;
569            }
570            let target_fixed_cb = target.style.establishes_fixed_containing_block();
571            let target_abs_cb =
572                target.style.position != strata_style::types::Position::Static || target_fixed_cb;
573            for child in &mut target.children {
574                child.translate_scrolled(0.0, -dy, target_abs_cb, target_fixed_cb);
575            }
576            for line in &mut target.line_boxes {
577                line.bounds.y -= dy;
578                for frag in &mut line.text_fragments {
579                    frag.bounds.y -= dy;
580                    frag.baseline_y -= dy;
581                }
582                for atomic in &mut line.atomic_fragments {
583                    atomic.bounds.y -= dy;
584                }
585            }
586        }
587        if self.has_anchored_portals {
588            self.resolve_top_layer_portals();
589        }
590        self.spatial_index.sync_bounds(&self.layout_root);
591        self.fire_scroll_event(
592            path,
593            cur_x,
594            new_scroll_y,
595            0.0,
596            dy,
597            client_w,
598            content_h,
599            client_w,
600            client_h,
601        );
602    }
603
604    pub(crate) fn fire_scroll_event(
605        &self,
606        container_path: &[usize],
607        scroll_x: f32,
608        scroll_y: f32,
609        delta_x: f32,
610        delta_y: f32,
611        content_w: f32,
612        content_h: f32,
613        client_w: f32,
614        client_h: f32,
615    ) -> bool {
616        if let Some((handler, target_box, _)) = Self::find_event_at_or_above_path(
617            &self.root_blueprint,
618            &self.layout_root,
619            container_path,
620            strata_dom::EventType::Scroll,
621        ) {
622            let mut ev = strata_dom::Event::new(strata_dom::EventType::Scroll);
623            ev.scroll_left = scroll_x as f64;
624            ev.scroll_top = scroll_y as f64;
625            ev.scroll_width = content_w as f64;
626            ev.scroll_height = content_h as f64;
627            ev.client_width = client_w as f64;
628            ev.client_height = client_h as f64;
629            ev.delta_x = delta_x as f64;
630            ev.delta_y = delta_y as f64;
631            ev.width = target_box.width as f64;
632            ev.height = target_box.height as f64;
633            ev.value = format!("{:.1}", scroll_y);
634            handler(ev);
635            return true;
636        }
637        false
638    }
639
640    fn blueprint_has_wheel_listener(bp: &NodeBlueprint) -> bool {
641        match bp {
642            NodeBlueprint::Element {
643                attributes,
644                children,
645                ..
646            } => {
647                attributes.iter().any(|a| {
648                    matches!(
649                        a,
650                        strata_dom::Attribute::EventListener {
651                            event: strata_dom::EventType::Wheel,
652                            ..
653                        }
654                    )
655                }) || children.iter().any(Self::blueprint_has_wheel_listener)
656            }
657            NodeBlueprint::Fragment(children) => {
658                children.iter().any(Self::blueprint_has_wheel_listener)
659            }
660            _ => false,
661        }
662    }
663
664    fn dispatch_dom_wheel_event(
665        &mut self,
666        px: f32,
667        py: f32,
668        delta_x: f32,
669        delta_y: f32,
670    ) -> (bool, bool) {
671        if !Self::blueprint_has_wheel_listener(&self.root_blueprint) {
672            return (false, false);
673        }
674        if let Some((handler, target_box)) = Self::hit_test_event_with_box(
675            &self.root_blueprint,
676            &self.layout_root,
677            px,
678            py,
679            strata_dom::EventType::Wheel,
680        ) {
681            let mut ev = self.create_mouse_event(
682                strata_dom::EventType::Wheel,
683                px,
684                py,
685                0,
686                0,
687                Some(target_box),
688            );
689            ev.delta_x = delta_x as f64;
690            ev.delta_y = delta_y as f64;
691            let prevented_cell = ev.default_prevented.clone();
692            handler(ev);
693            return (true, prevented_cell.get());
694        }
695        (false, false)
696    }
697
698    /// Dispatches an immediate synchronous scroll wheel delta to the innermost scrollable container under (px, py).
699    /// Cancels any active kinetic smooth scroll animation.
700    /// Returns true if a scroll offset changed or a DOM wheel listener handled the event.
701    pub fn dispatch_scroll(&mut self, px: f32, py: f32, delta_x: f32, delta_y: f32) -> bool {
702        self.last_mouse_pos = (px, py);
703        self.active_smooth_scroll = None;
704
705        let (wheel_handled, default_prevented) =
706            self.dispatch_dom_wheel_event(px, py, delta_x, delta_y);
707        if default_prevented {
708            return true;
709        }
710
711        let mut matching_bars: Vec<ActiveScrollbar> = self
712            .active_scrollbars
713            .iter()
714            .filter(|bar| bar.bounds.contains_point(px, py))
715            .cloned()
716            .collect();
717
718        // If mouse is not directly over an active scroll container, fallback to the largest scrollable container
719        if matching_bars.is_empty() {
720            if let Some(largest) = self.active_scrollbars.iter().max_by(|a, b| {
721                (a.bounds.width * a.bounds.height)
722                    .partial_cmp(&(b.bounds.width * b.bounds.height))
723                    .unwrap_or(std::cmp::Ordering::Equal)
724            }) {
725                matching_bars.push(largest.clone());
726            }
727        }
728
729        for bar in matching_bars.into_iter().rev() {
730            if bar.max_scroll_y <= 0.0 {
731                continue;
732            }
733
734            let cur_y = if bar.is_id {
735                self.scroll_offsets_by_id
736                    .get(&bar.id)
737                    .copied()
738                    .or_else(|| self.scroll_offsets.get(&bar.path).copied())
739                    .map(|(_, y)| y)
740                    .unwrap_or(bar.scroll_y)
741            } else {
742                self.scroll_offsets
743                    .get(&bar.path)
744                    .copied()
745                    .map(|(_, y)| y)
746                    .unwrap_or(bar.scroll_y)
747            };
748
749            let candidate_y = (cur_y + delta_y).clamp(0.0, bar.max_scroll_y);
750            let dy = candidate_y - cur_y;
751            if dy.abs() > 0.01 {
752                self.last_scroll_interaction = Some(std::time::Instant::now());
753                self.apply_scroll_delta_to_container(
754                    &bar.path,
755                    bar.is_id,
756                    &bar.id,
757                    candidate_y,
758                    dy,
759                    bar.max_scroll_y,
760                    bar.available_travel,
761                    bar.bounds.y,
762                );
763                return true;
764            }
765        }
766
767        wheel_handled
768    }
769
770    /// Dispatches a smooth kinetic scroll impulse to the innermost scrollable container under (px, py).
771    /// Accumulates velocity for rapid consecutive wheel events and initiates a critically damped
772    /// kinetic transition curve with Chromium Blink parity.
773    /// Dispatches a smooth scroll or DOM wheel event, returning `(wheel_handled, scroll_changed)`.
774    pub fn dispatch_smooth_scroll_action(
775        &mut self,
776        px: f32,
777        py: f32,
778        delta_x: f32,
779        delta_y: f32,
780    ) -> (bool, bool) {
781        self.last_mouse_pos = (px, py);
782        if delta_y.abs() < 0.01 && delta_x.abs() < 0.01 {
783            return (false, false);
784        }
785
786        let (wheel_handled, default_prevented) =
787            self.dispatch_dom_wheel_event(px, py, delta_x, delta_y);
788        if default_prevented {
789            return (wheel_handled, false);
790        }
791        if delta_y.abs() < 0.01 {
792            return (wheel_handled, false);
793        }
794
795        let mut matching_bars: Vec<ActiveScrollbar> = self
796            .active_scrollbars
797            .iter()
798            .filter(|bar| bar.bounds.contains_point(px, py))
799            .cloned()
800            .collect();
801
802        if matching_bars.is_empty() {
803            if let Some(largest) = self.active_scrollbars.iter().max_by(|a, b| {
804                (a.bounds.width * a.bounds.height)
805                    .partial_cmp(&(b.bounds.width * b.bounds.height))
806                    .unwrap_or(std::cmp::Ordering::Equal)
807            }) {
808                matching_bars.push(largest.clone());
809            }
810        }
811
812        // Scroll chaining: target the innermost container that can still absorb the delta.
813        // When every matching container is already at its limit, fall back to the outermost
814        // container so the event is not trapped by the innermost saturated scroller.
815        let target_bar = matching_bars
816            .iter()
817            .rev()
818            .find(|b| {
819                if b.max_scroll_y <= 0.0 {
820                    return false;
821                }
822                let cur_y = if b.is_id {
823                    self.scroll_offsets_by_id
824                        .get(&b.id)
825                        .copied()
826                        .or_else(|| self.scroll_offsets.get(&b.path).copied())
827                        .map(|(_, y)| y)
828                        .unwrap_or(b.scroll_y)
829                } else {
830                    self.scroll_offsets
831                        .get(&b.path)
832                        .copied()
833                        .map(|(_, y)| y)
834                        .unwrap_or(b.scroll_y)
835                };
836                if delta_y < 0.0 {
837                    cur_y > 0.01
838                } else {
839                    cur_y < b.max_scroll_y - 0.01
840                }
841            })
842            .cloned()
843            .or_else(|| matching_bars.iter().find(|b| b.max_scroll_y > 0.0).cloned());
844
845        let Some(bar) = target_bar else {
846            return (wheel_handled, false);
847        };
848
849        let now = std::time::Instant::now();
850        self.last_scroll_interaction = Some(now);
851
852        let cur_y = if bar.is_id {
853            self.scroll_offsets_by_id
854                .get(&bar.id)
855                .copied()
856                .or_else(|| self.scroll_offsets.get(&bar.path).copied())
857                .map(|(_, y)| y)
858                .unwrap_or(bar.scroll_y)
859        } else {
860            self.scroll_offsets
861                .get(&bar.path)
862                .copied()
863                .map(|(_, y)| y)
864                .unwrap_or(bar.scroll_y)
865        };
866
867        if self
868            .active_smooth_scroll
869            .as_ref()
870            .is_some_and(|t| t.container_path == bar.path)
871        {
872            if let Some(mut tracker) = self.active_smooth_scroll.take() {
873                let dt_flick = now.duration_since(tracker.last_event_time).as_secs_f32();
874                let accel = if dt_flick < 0.20 {
875                    (1.0 + (0.12 / dt_flick.max(0.01)).min(2.5)).min(3.5)
876                } else {
877                    1.0
878                };
879
880                let t_prev = now.duration_since(tracker.start_time).as_secs_f32();
881                let omega = tracker.omega;
882                let e0 = tracker.start_y - tracker.target_y;
883                let c2 = tracker.initial_velocity + omega * e0;
884                let decay = (-omega * t_prev).exp();
885                let y_now =
886                    (tracker.target_y + (e0 + c2 * t_prev) * decay).clamp(0.0, bar.max_scroll_y);
887                let v_now = (tracker.initial_velocity - omega * c2 * t_prev) * decay;
888
889                let catchup_dy = y_now - tracker.current_y;
890                if catchup_dy.abs() > 0.001 {
891                    self.apply_scroll_delta_to_container(
892                        &tracker.container_path,
893                        tracker.is_id,
894                        &tracker.container_id,
895                        y_now,
896                        catchup_dy,
897                        bar.max_scroll_y,
898                        bar.available_travel,
899                        bar.bounds.y,
900                    );
901                    tracker.current_y = y_now;
902                }
903
904                let impulse = delta_y * accel;
905                let new_target = (tracker.target_y + impulse).clamp(0.0, bar.max_scroll_y);
906
907                tracker.start_y = y_now;
908                tracker.initial_velocity = v_now;
909                tracker.target_y = new_target;
910                tracker.start_time = now;
911                tracker.last_event_time = now;
912                tracker.max_scroll_y = bar.max_scroll_y;
913                tracker.available_travel = bar.available_travel;
914                tracker.bounds_y = bar.bounds.y;
915                self.active_smooth_scroll = Some(tracker);
916                return (wheel_handled, true);
917            }
918        }
919
920        let new_target = (cur_y + delta_y).clamp(0.0, bar.max_scroll_y);
921        self.active_smooth_scroll = Some(SmoothScrollTracker {
922            container_path: bar.path,
923            container_id: bar.id,
924            is_id: bar.is_id,
925            max_scroll_y: bar.max_scroll_y,
926            available_travel: bar.available_travel,
927            bounds_y: bar.bounds.y,
928            current_y: cur_y,
929            target_y: new_target,
930            start_y: cur_y,
931            initial_velocity: 0.0,
932            start_time: now,
933            last_event_time: now,
934            omega: 18.0,
935        });
936
937        (wheel_handled, true)
938    }
939
940    /// Dispatches a smooth kinetic scroll impulse to the innermost scrollable container under (px, py).
941    /// Returns `true` if either a DOM `wheel` listener handled the event or a scroll animation updated.
942    pub fn dispatch_smooth_scroll(&mut self, px: f32, py: f32, delta_x: f32, delta_y: f32) -> bool {
943        let (wheel_handled, scroll_changed) =
944            self.dispatch_smooth_scroll_action(px, py, delta_x, delta_y);
945        wheel_handled || scroll_changed
946    }
947
948    /// Polls and updates active kinetic smooth scroll animation at a specific timestamp.
949    /// Returns true if a position changed and a redraw is required.
950    pub fn poll_smooth_scroll_at(&mut self, now: std::time::Instant) -> bool {
951        let Some(mut tracker) = self.active_smooth_scroll.take() else {
952            return false;
953        };
954
955        let t = now.duration_since(tracker.start_time).as_secs_f32();
956        let omega = tracker.omega;
957        let e0 = tracker.start_y - tracker.target_y;
958        let c2 = tracker.initial_velocity + omega * e0;
959        let decay = (-omega * t).exp();
960
961        let raw_y = tracker.target_y + (e0 + c2 * t) * decay;
962        let clamped_y = raw_y.clamp(0.0, tracker.max_scroll_y);
963        let vel = (tracker.initial_velocity - omega * c2 * t) * decay;
964
965        let is_settled =
966            t >= 0.40 || ((clamped_y - tracker.target_y).abs() < 0.25 && vel.abs() < 1.0);
967        let new_y = if is_settled {
968            tracker.target_y
969        } else {
970            clamped_y
971        };
972
973        let dy = new_y - tracker.current_y;
974        let mut redraw = false;
975
976        if dy.abs() > 0.001 {
977            self.apply_scroll_delta_to_container(
978                &tracker.container_path,
979                tracker.is_id,
980                &tracker.container_id,
981                new_y,
982                dy,
983                tracker.max_scroll_y,
984                tracker.available_travel,
985                tracker.bounds_y,
986            );
987            tracker.current_y = new_y;
988            redraw = true;
989        }
990
991        if !is_settled {
992            self.active_smooth_scroll = Some(tracker);
993            redraw = true;
994        }
995
996        redraw
997    }
998
999    /// Evaluates active smooth scroll animation at the current instant.
1000    #[inline]
1001    pub fn poll_smooth_scroll(&mut self) -> bool {
1002        self.poll_smooth_scroll_at(std::time::Instant::now())
1003    }
1004
1005    /// Scrolls the innermost scroll container under (px, py) to the very top.
1006    pub fn scroll_to_top(&mut self, px: f32, py: f32) -> bool {
1007        self.active_smooth_scroll = None;
1008        let mut matching_bars: Vec<ActiveScrollbar> = self
1009            .active_scrollbars
1010            .iter()
1011            .filter(|bar| bar.bounds.contains_point(px, py))
1012            .cloned()
1013            .collect();
1014
1015        if matching_bars.is_empty() {
1016            if let Some(largest) = self.active_scrollbars.iter().max_by(|a, b| {
1017                (a.bounds.width * a.bounds.height)
1018                    .partial_cmp(&(b.bounds.width * b.bounds.height))
1019                    .unwrap_or(std::cmp::Ordering::Equal)
1020            }) {
1021                matching_bars.push(largest.clone());
1022            }
1023        }
1024
1025        if let Some(bar) = matching_bars.into_iter().next_back() {
1026            let cur_y = bar.scroll_y;
1027            let dy = 0.0 - cur_y;
1028            if dy.abs() > 0.01 {
1029                self.last_scroll_interaction = Some(std::time::Instant::now());
1030                self.apply_scroll_delta_to_container(
1031                    &bar.path,
1032                    bar.is_id,
1033                    &bar.id,
1034                    0.0,
1035                    dy,
1036                    bar.max_scroll_y,
1037                    bar.available_travel,
1038                    bar.bounds.y,
1039                );
1040                return true;
1041            }
1042        }
1043        false
1044    }
1045
1046    /// Scrolls the innermost scroll container under (px, py) to the very bottom.
1047    pub fn scroll_to_bottom(&mut self, px: f32, py: f32) -> bool {
1048        self.active_smooth_scroll = None;
1049        let mut matching_bars: Vec<ActiveScrollbar> = self
1050            .active_scrollbars
1051            .iter()
1052            .filter(|bar| bar.bounds.contains_point(px, py))
1053            .cloned()
1054            .collect();
1055
1056        if matching_bars.is_empty() {
1057            if let Some(largest) = self.active_scrollbars.iter().max_by(|a, b| {
1058                (a.bounds.width * a.bounds.height)
1059                    .partial_cmp(&(b.bounds.width * b.bounds.height))
1060                    .unwrap_or(std::cmp::Ordering::Equal)
1061            }) {
1062                matching_bars.push(largest.clone());
1063            }
1064        }
1065
1066        if let Some(bar) = matching_bars.into_iter().next_back() {
1067            if bar.max_scroll_y > 0.0 {
1068                let cur_y = bar.scroll_y;
1069                let dy = bar.max_scroll_y - cur_y;
1070                if dy.abs() > 0.01 {
1071                    self.last_scroll_interaction = Some(std::time::Instant::now());
1072                    self.apply_scroll_delta_to_container(
1073                        &bar.path,
1074                        bar.is_id,
1075                        &bar.id,
1076                        bar.max_scroll_y,
1077                        dy,
1078                        bar.max_scroll_y,
1079                        bar.available_travel,
1080                        bar.bounds.y,
1081                    );
1082                    return true;
1083                }
1084            }
1085        }
1086        false
1087    }
1088
1089    /// Returns the live `(scroll_left, scroll_top)` offset for a scrollable element `id`.
1090    pub fn scroll_offset_by_id(&self, id: &str) -> (f32, f32) {
1091        if let Some(off) = self.scroll_offsets_by_id.get(id) {
1092            return *off;
1093        }
1094        if let Some(bar) = self
1095            .active_scrollbars
1096            .iter()
1097            .find(|b| b.is_id && b.id == id)
1098        {
1099            return (0.0, bar.scroll_y);
1100        }
1101        strata_dom::get_scroll_offset(id)
1102    }
1103
1104    /// Scrolls the scroll container with element `id` (or the primary scroll container if `id` is empty)
1105    /// to `(scroll_x, scroll_y)`, clamping to the container's maximum scroll bounds and firing `EventType::Scroll`.
1106    pub fn scroll_to_by_id(&mut self, id: &str, scroll_x: f32, scroll_y: f32) -> bool {
1107        self.active_smooth_scroll = None;
1108        let bar_opt = if id.is_empty() {
1109            self.active_scrollbars
1110                .iter()
1111                .max_by(|a, b| {
1112                    (a.bounds.width * a.bounds.height)
1113                        .partial_cmp(&(b.bounds.width * b.bounds.height))
1114                        .unwrap_or(std::cmp::Ordering::Equal)
1115                })
1116                .cloned()
1117        } else {
1118            self.active_scrollbars
1119                .iter()
1120                .find(|b| b.is_id && b.id == id)
1121                .cloned()
1122        };
1123
1124        if let Some(bar) = bar_opt {
1125            let clamped_y = scroll_y.clamp(0.0, bar.max_scroll_y);
1126            let dy = clamped_y - bar.scroll_y;
1127            if !id.is_empty() {
1128                self.scroll_offsets_by_id
1129                    .insert(id.to_string(), (scroll_x.max(0.0), clamped_y));
1130                strata_dom::hooks::set_live_scroll_offset(id, scroll_x.max(0.0), clamped_y);
1131            }
1132            if dy.abs() > 0.01 {
1133                self.last_scroll_interaction = Some(std::time::Instant::now());
1134                self.apply_scroll_delta_to_container(
1135                    &bar.path,
1136                    bar.is_id,
1137                    &bar.id,
1138                    clamped_y,
1139                    dy,
1140                    bar.max_scroll_y,
1141                    bar.available_travel,
1142                    bar.bounds.y,
1143                );
1144                return true;
1145            }
1146            return false;
1147        }
1148
1149        if !id.is_empty() {
1150            let clamped_x = scroll_x.max(0.0);
1151            let clamped_y = scroll_y.max(0.0);
1152            self.scroll_offsets_by_id
1153                .insert(id.to_string(), (clamped_x, clamped_y));
1154            strata_dom::hooks::set_live_scroll_offset(id, clamped_x, clamped_y);
1155        }
1156        false
1157    }
1158
1159    /// Scrolls the scroll container with element `id` (or the primary scroll container if `id` is empty) to the top.
1160    pub fn scroll_to_top_by_id(&mut self, id: &str) -> bool {
1161        if id.is_empty() {
1162            let (px, py) = self.last_mouse_pos;
1163            return self.scroll_to_top(px, py);
1164        }
1165        self.scroll_to_by_id(id, 0.0, 0.0)
1166    }
1167
1168    /// Scrolls the scroll container with element `id` (or the primary scroll container if `id` is empty) to the bottom.
1169    pub fn scroll_to_bottom_by_id(&mut self, id: &str) -> bool {
1170        if id.is_empty() {
1171            let (px, py) = self.last_mouse_pos;
1172            return self.scroll_to_bottom(px, py);
1173        }
1174        if let Some(bar) = self
1175            .active_scrollbars
1176            .iter()
1177            .find(|b| b.is_id && b.id == id)
1178            .cloned()
1179        {
1180            return self.scroll_to_by_id(id, 0.0, bar.max_scroll_y);
1181        }
1182        false
1183    }
1184
1185    pub(crate) fn find_element_path_by_id(
1186        blueprint: &NodeBlueprint,
1187        layout: &LayoutNode,
1188        target_id: &str,
1189        current_path: &mut Vec<usize>,
1190    ) -> Option<Vec<usize>> {
1191        if layout.element_id.as_deref() == Some(target_id) {
1192            return Some(current_path.clone());
1193        }
1194        if let NodeBlueprint::Element { attributes, .. } = blueprint {
1195            for attr in attributes {
1196                if let strata_dom::Attribute::Property { key, value } = attr {
1197                    if key == "id" && value == target_id {
1198                        return Some(current_path.clone());
1199                    }
1200                }
1201            }
1202        }
1203        for (idx, child_bp, child_layout) in Self::paired_blueprint_children(blueprint, layout) {
1204            current_path.push(idx);
1205            if let Some(found) =
1206                Self::find_element_path_by_id(child_bp, child_layout, target_id, current_path)
1207            {
1208                return Some(found);
1209            }
1210            current_path.pop();
1211        }
1212        None
1213    }
1214
1215    /// Scrolls the nearest enclosing scroll container so that the descendant element with `target_id` is visible.
1216    pub fn scroll_into_view(&mut self, target_id: &str) -> bool {
1217        if target_id.is_empty() {
1218            return false;
1219        }
1220        let mut path_buf = Vec::new();
1221        let Some(target_path) = Self::find_element_path_by_id(
1222            &self.root_blueprint,
1223            &self.layout_root,
1224            target_id,
1225            &mut path_buf,
1226        ) else {
1227            return false;
1228        };
1229
1230        let Some(target_box) =
1231            Self::get_layout_node(&self.layout_root, &target_path).map(|n| n.geometry.border_box)
1232        else {
1233            return false;
1234        };
1235
1236        // Find the deepest active scrollbar that is a strict ancestor of `target_path`
1237        let ancestor_bar = self
1238            .active_scrollbars
1239            .iter()
1240            .filter(|b| target_path.len() > b.path.len() && target_path.starts_with(&b.path))
1241            .max_by_key(|b| b.path.len())
1242            .cloned();
1243
1244        let Some(bar) = ancestor_bar else {
1245            return false;
1246        };
1247
1248        let container_box = Self::get_layout_node(&self.layout_root, &bar.path)
1249            .map(|n| n.geometry.content_box)
1250            .unwrap_or(bar.bounds);
1251
1252        let cur_y = bar.scroll_y;
1253        let new_y = if target_box.y < container_box.y {
1254            let dy = target_box.y - container_box.y;
1255            (cur_y + dy).clamp(0.0, bar.max_scroll_y)
1256        } else if target_box.y + target_box.height > container_box.y + container_box.height {
1257            let dy = (target_box.y + target_box.height) - (container_box.y + container_box.height);
1258            (cur_y + dy).clamp(0.0, bar.max_scroll_y)
1259        } else {
1260            cur_y
1261        };
1262
1263        let dy = new_y - cur_y;
1264        if dy.abs() > 0.01 {
1265            self.active_smooth_scroll = None;
1266            self.last_scroll_interaction = Some(std::time::Instant::now());
1267            self.apply_scroll_delta_to_container(
1268                &bar.path,
1269                bar.is_id,
1270                &bar.id,
1271                new_y,
1272                dy,
1273                bar.max_scroll_y,
1274                bar.available_travel,
1275                bar.bounds.y,
1276            );
1277            return true;
1278        }
1279        false
1280    }
1281
1282    /// Drains and executes any programmatic scroll commands queued via `strata_dom::scroll_to`,
1283    /// `scroll_to_top`, `scroll_to_bottom`, or `scroll_into_view`.
1284    pub fn flush_pending_scroll_commands(&mut self) -> bool {
1285        if !strata_dom::hooks::has_pending_scroll_commands() {
1286            return false;
1287        }
1288        let cmds = strata_dom::hooks::take_pending_scroll_commands();
1289        let mut any_changed = false;
1290        for cmd in cmds {
1291            match cmd {
1292                strata_dom::ProgrammaticScrollCommand::ScrollTo { id, x, y } => {
1293                    if self.scroll_to_by_id(&id, x, y) {
1294                        any_changed = true;
1295                    }
1296                }
1297                strata_dom::ProgrammaticScrollCommand::ScrollToTop { id } => {
1298                    if self.scroll_to_top_by_id(&id) {
1299                        any_changed = true;
1300                    }
1301                }
1302                strata_dom::ProgrammaticScrollCommand::ScrollToBottom { id } => {
1303                    if self.scroll_to_bottom_by_id(&id) {
1304                        any_changed = true;
1305                    }
1306                }
1307                strata_dom::ProgrammaticScrollCommand::ScrollIntoView { target_id } => {
1308                    if self.scroll_into_view(&target_id) {
1309                        any_changed = true;
1310                    }
1311                }
1312            }
1313        }
1314        any_changed
1315    }
1316}