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                    if Self::is_multiline_text_scroll_leaf(target) {
109                        target.geometry.scroll_offset.y = 0.0;
110                    } else {
111                        let target_fixed_cb = target.style.establishes_fixed_containing_block();
112                        let target_abs_cb = target.style.position
113                            != strata_style::types::Position::Static
114                            || target_fixed_cb;
115                        for child in &mut target.children {
116                            child.translate_scrolled(
117                                applied_x,
118                                applied_y,
119                                target_abs_cb,
120                                target_fixed_cb,
121                            );
122                        }
123                        for line in &mut target.line_boxes {
124                            line.bounds.x += applied_x;
125                            line.bounds.y += applied_y;
126                            for frag in &mut line.text_fragments {
127                                frag.bounds.x += applied_x;
128                                frag.bounds.y += applied_y;
129                                frag.baseline_y += applied_y;
130                            }
131                            for atomic in &mut line.atomic_fragments {
132                                atomic.bounds.x += applied_x;
133                                atomic.bounds.y += applied_y;
134                            }
135                        }
136                    }
137                }
138            }
139        }
140        self.applied_scroll_offsets.clear();
141    }
142
143    /// Discovers scrollable containers, clamps offsets, translates children, computes scrollbars,
144    /// and anchors top-layer `<Portal>` overlays to their trigger elements' live post-scroll bounds.
145    pub fn apply_scroll_offsets(&mut self) {
146        self.active_scrollbars.clear();
147        let mut path = Vec::new();
148        Self::apply_scroll_walk(
149            &self.root_blueprint,
150            &mut self.layout_root,
151            &mut path,
152            &self.scroll_offsets,
153            &self.scroll_offsets_by_id,
154            &mut self.applied_scroll_offsets,
155        );
156        self.flush_pending_scroll_commands();
157        self.sync_scroll_animations();
158        self.resolve_top_layer_portals();
159        self.rebuild_active_scrollbars();
160    }
161
162    fn transform_rect_aabb(
163        mat: &strata_primitives::geom::Matrix4x4,
164        b: strata_layout::Rect,
165    ) -> strata_layout::Rect {
166        if *mat == strata_primitives::geom::Matrix4x4::identity() {
167            return b;
168        }
169        let corners = [
170            mat.transform_point(b.x, b.y),
171            mat.transform_point(b.x + b.width, b.y),
172            mat.transform_point(b.x, b.y + b.height),
173            mat.transform_point(b.x + b.width, b.y + b.height),
174        ];
175        let min_x = corners.iter().map(|c| c.0).fold(f32::INFINITY, f32::min);
176        let min_y = corners.iter().map(|c| c.1).fold(f32::INFINITY, f32::min);
177        let max_x = corners.iter().map(|c| c.0).fold(f32::NEG_INFINITY, f32::max);
178        let max_y = corners.iter().map(|c| c.1).fold(f32::NEG_INFINITY, f32::max);
179        strata_layout::Rect::new(min_x, min_y, (max_x - min_x).max(0.0), (max_y - min_y).max(0.0))
180    }
181
182    fn apply_node_transform(
183        parent_mat: &strata_primitives::geom::Matrix4x4,
184        node: &LayoutNode,
185    ) -> strata_primitives::geom::Matrix4x4 {
186        if !node.style.has_transform() {
187            return *parent_mat;
188        }
189        let b = node.geometry.border_box;
190        let local_mat = node.style.compute_transform_matrix(b.width, b.height);
191        let origin_mat = strata_primitives::geom::Matrix4x4::translation(b.x, b.y, 0.0)
192            .multiply(&local_mat)
193            .multiply(&strata_primitives::geom::Matrix4x4::translation(-b.x, -b.y, 0.0));
194        parent_mat.multiply(&origin_mat)
195    }
196
197    /// Walks from `root` to `path`, accumulating CSS `style.transform` matrices and returning the
198    /// screen-space axis-aligned bounding box of the target node.
199    fn effective_screen_border_box(root: &LayoutNode, path: &[usize]) -> Option<strata_layout::Rect> {
200        let mut mat = strata_primitives::geom::Matrix4x4::identity();
201        let mut cur = root;
202        for &idx in path {
203            if cur.is_top_layer {
204                mat = strata_primitives::geom::Matrix4x4::identity();
205            }
206            mat = Self::apply_node_transform(&mat, cur);
207            cur = cur.children.get(idx)?;
208        }
209        if cur.is_top_layer {
210            mat = strata_primitives::geom::Matrix4x4::identity();
211        }
212        mat = Self::apply_node_transform(&mat, cur);
213        Some(Self::transform_rect_aabb(&mat, cur.geometry.border_box))
214    }
215
216    #[inline]
217    pub(crate) fn is_multiline_text_scroll_leaf(layout: &LayoutNode) -> bool {
218        layout.children.is_empty()
219            && layout.line_boxes.is_empty()
220            && layout.text.is_some()
221            && matches!(
222                layout.style.white_space,
223                strata_style::types::WhiteSpace::PreWrap
224                    | strata_style::types::WhiteSpace::PreLine
225                    | strata_style::types::WhiteSpace::Pre
226            )
227    }
228
229    fn compute_container_scroll_extents(
230        layout: &LayoutNode,
231        applied_x: f32,
232        applied_y: f32,
233    ) -> (f32, f32, f32, f32) {
234        let viewport_w = layout.geometry.content_box.width;
235        let viewport_h = layout.geometry.content_box.height;
236
237        let mut max_child_x = layout.geometry.content_box.x;
238        let mut max_child_y = layout.geometry.content_box.y;
239
240        let target_fixed_cb = layout.style.establishes_fixed_containing_block();
241        let target_abs_cb =
242            layout.style.position != strata_style::types::Position::Static || target_fixed_cb;
243
244        for child in &layout.children {
245            if child.is_top_layer
246                || child.style.position == strata_style::types::Position::Fixed
247                || (child.style.position == strata_style::types::Position::Absolute
248                    && !target_abs_cb)
249            {
250                continue;
251            }
252            max_child_x =
253                max_child_x.max(child.geometry.border_box.x + child.geometry.border_box.width + applied_x);
254            max_child_y =
255                max_child_y.max(child.geometry.border_box.y + child.geometry.border_box.height + applied_y);
256        }
257        for line in &layout.line_boxes {
258            max_child_x = max_child_x.max(line.bounds.x + line.bounds.width + applied_x);
259            max_child_y = max_child_y.max(line.bounds.y + line.bounds.height + applied_y);
260        }
261        if Self::is_multiline_text_scroll_leaf(layout) {
262            if let Some(ref text) = layout.text {
263                let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
264                let (lines, line_step) = Self::layout_visual_lines(
265                    text,
266                    viewport_w,
267                    layout.style.font_size,
268                    layout.style.line_height,
269                    is_mono,
270                    layout.style.font_family,
271                );
272                let text_h = lines.len().max(1) as f32 * line_step;
273                max_child_y = max_child_y.max(layout.geometry.content_box.y + text_h);
274            }
275        }
276
277        let content_w = (max_child_x - layout.geometry.content_box.x).max(0.0);
278        let content_h = (max_child_y - layout.geometry.content_box.y).max(0.0);
279        let max_scroll_x = (content_w - viewport_w).max(0.0);
280        let max_scroll_y = (content_h - viewport_h).max(0.0);
281        (content_w, content_h, max_scroll_x, max_scroll_y)
282    }
283
284    /// Recomputes `active_scrollbars` in final post-scroll, post-portal coordinates along with
285    /// each scrollbar's clipped viewport rect so top-layer `<Portal>` scrollbars render and
286    /// hit-test in their translated, clipped coordinates.
287    pub(crate) fn rebuild_active_scrollbars(&mut self) {
288        self.active_scrollbars.clear();
289        let viewport_clip = if self.viewport_width > 0.0 && self.viewport_height > 0.0 {
290            Some(strata_layout::Rect::new(
291                0.0,
292                0.0,
293                self.viewport_width,
294                self.viewport_height,
295            ))
296        } else {
297            None
298        };
299        let mut path = Vec::new();
300        let identity = strata_primitives::geom::Matrix4x4::identity();
301        Self::collect_active_scrollbars_walk(
302            &self.root_blueprint,
303            &self.layout_root,
304            &mut path,
305            &[],
306            &identity,
307            false,
308            viewport_clip,
309            &self.scroll_offsets,
310            &self.scroll_offsets_by_id,
311            &self.applied_scroll_offsets,
312            &mut self.active_scrollbars,
313        );
314        self.active_scrollbars.sort_by_key(|b| b.is_top_layer);
315    }
316
317    #[allow(clippy::too_many_arguments)]
318    fn collect_active_scrollbars_walk(
319        blueprint: &NodeBlueprint,
320        layout: &LayoutNode,
321        current_path: &mut Vec<usize>,
322        inherited_steps: &[super::hit_test::HitClipStep],
323        parent_transform: &strata_primitives::geom::Matrix4x4,
324        in_top_layer: bool,
325        viewport_clip: Option<strata_layout::Rect>,
326        scroll_offsets: &std::collections::HashMap<Vec<usize>, (f32, f32)>,
327        scroll_offsets_by_id: &std::collections::HashMap<String, (f32, f32)>,
328        applied_scroll_offsets: &std::collections::HashMap<Vec<usize>, (f32, f32)>,
329        out: &mut Vec<ActiveScrollbar>,
330    ) {
331        if current_path.len() >= 256
332            || matches!(layout.style.display, strata_style::types::Display::None)
333        {
334            return;
335        }
336
337        let node_in_top_layer = in_top_layer || layout.is_top_layer;
338        let eff_inherited = if layout.is_top_layer {
339            &[][..]
340        } else {
341            Self::effective_hit_clip_steps(layout, inherited_steps)
342        };
343        let base_transform = if layout.is_top_layer {
344            strata_primitives::geom::Matrix4x4::identity()
345        } else {
346            *parent_transform
347        };
348        let node_transform = Self::apply_node_transform(&base_transform, layout);
349
350        let is_scroll_y = matches!(
351            layout.style.overflow_y,
352            strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
353        );
354        let viewport_h = layout.geometry.content_box.height;
355        if is_scroll_y && viewport_h > 0.0 {
356            let elem_id = match blueprint {
357                NodeBlueprint::Element { attributes, .. } => attributes.iter().find_map(|a| {
358                    if let strata_dom::Attribute::Property { key, value } = a {
359                        if key == "id" {
360                            Some(value.clone())
361                        } else {
362                            None
363                        }
364                    } else {
365                        None
366                    }
367                }),
368                _ => None,
369            };
370            let (applied_x, applied_y) = applied_scroll_offsets
371                .get(current_path)
372                .copied()
373                .unwrap_or((0.0, 0.0));
374            let (_, content_h, _, max_scroll_y) =
375                Self::compute_container_scroll_extents(layout, applied_x, applied_y);
376
377            if max_scroll_y > 0.0 {
378                let stored_y = if let Some(ref id) = elem_id {
379                    scroll_offsets_by_id
380                        .get(id)
381                        .copied()
382                        .or_else(|| scroll_offsets.get(current_path).copied())
383                        .map(|(_, y)| y)
384                        .unwrap_or(applied_y)
385                } else {
386                    scroll_offsets
387                        .get(current_path)
388                        .copied()
389                        .map(|(_, y)| y)
390                        .unwrap_or(applied_y)
391                };
392                let clamped_y = stored_y.clamp(0.0, max_scroll_y);
393
394                let border_box = Self::transform_rect_aabb(&node_transform, layout.geometry.border_box);
395                let padding_box = Self::transform_rect_aabb(&node_transform, layout.geometry.padding_box);
396                let mut clip_bounds = border_box;
397                if let Some(vp) = viewport_clip {
398                    clip_bounds = clip_bounds
399                        .intersect(vp)
400                        .unwrap_or_else(|| strata_layout::Rect::new(0.0, 0.0, 0.0, 0.0));
401                }
402                for step in eff_inherited {
403                    if let Some(c) = step.clip {
404                        clip_bounds = clip_bounds
405                            .intersect(c)
406                            .unwrap_or_else(|| strata_layout::Rect::new(0.0, 0.0, 0.0, 0.0));
407                    }
408                }
409
410                let track_width = 10.0;
411                let inner_track_box = if padding_box.width > 0.0 && padding_box.height > 0.0 {
412                    padding_box
413                } else {
414                    border_box
415                };
416                let track_x =
417                    (inner_track_box.x + inner_track_box.width - track_width).max(inner_track_box.x);
418                let track_y = inner_track_box.y;
419                let track_h = inner_track_box.height;
420                let track_bounds =
421                    strata_layout::Rect::new(track_x, track_y, track_width, track_h);
422
423                let min_thumb = 24.0_f32.min(track_h);
424                let thumb_h =
425                    ((viewport_h / content_h.max(1.0)) * track_h).clamp(min_thumb, track_h);
426                let available_travel = (track_h - thumb_h).max(0.0);
427                let thumb_y = if max_scroll_y > 0.0 && available_travel > 0.0 {
428                    track_y + (clamped_y / max_scroll_y) * available_travel
429                } else {
430                    track_y
431                };
432                let thumb_bounds =
433                    strata_layout::Rect::new(track_x, thumb_y, track_width, thumb_h);
434
435                out.push(ActiveScrollbar {
436                    bounds: border_box,
437                    clip_bounds,
438                    border_radius: layout.style.border_radius,
439                    is_top_layer: node_in_top_layer,
440                    track_bounds,
441                    thumb_bounds,
442                    scroll_y: clamped_y,
443                    max_scroll_y,
444                    content_h,
445                    is_id: elem_id.is_some(),
446                    id: elem_id.unwrap_or_default(),
447                    path: current_path.clone(),
448                    available_travel,
449                });
450            }
451        }
452
453        let mut next_steps = Vec::with_capacity(eff_inherited.len() + 1);
454        next_steps.extend_from_slice(eff_inherited);
455        let own_step = Self::hit_clip_step_for(layout);
456        if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
457            next_steps.push(own_step);
458        }
459
460        for (i, child_bp, child_layout) in Self::paired_blueprint_children(blueprint, layout) {
461            current_path.push(i);
462            Self::collect_active_scrollbars_walk(
463                child_bp,
464                child_layout,
465                current_path,
466                &next_steps,
467                &node_transform,
468                node_in_top_layer,
469                viewport_clip,
470                scroll_offsets,
471                scroll_offsets_by_id,
472                applied_scroll_offsets,
473                out,
474            );
475            current_path.pop();
476        }
477    }
478
479    fn hit_path_and_canvas_depth(&self, px: f32, py: f32) -> (Option<Vec<usize>>, Option<usize>) {
480        let hit_path = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py);
481        let canvas_depth = hit_path.as_ref().and_then(|hp| {
482            let mut cur_bp = &self.root_blueprint;
483            let mut deepest = None;
484            if matches!(
485                cur_bp,
486                NodeBlueprint::Element {
487                    tag: Tag::Canvas | Tag::Custom("Canvas3D"),
488                    ..
489                }
490            ) {
491                deepest = Some(0);
492            }
493            for (depth, &idx) in hp.iter().enumerate() {
494                let mut flat = Vec::new();
495                match cur_bp {
496                    NodeBlueprint::Element { children, .. }
497                    | NodeBlueprint::Fragment(children) => {
498                        for c in children {
499                            Self::flatten_blueprints(c, &mut flat);
500                        }
501                    }
502                    _ => break,
503                }
504                let Some(next) = flat.get(idx).copied() else {
505                    break;
506                };
507                cur_bp = next;
508                if matches!(
509                    cur_bp,
510                    NodeBlueprint::Element {
511                        tag: Tag::Canvas | Tag::Custom("Canvas3D"),
512                        ..
513                    }
514                ) {
515                    deepest = Some(depth + 1);
516                }
517            }
518            deepest
519        });
520        (hit_path, canvas_depth)
521    }
522
523    #[inline]
524    fn matching_scrollbars_at(&self, px: f32, py: f32) -> Vec<ActiveScrollbar> {
525        let (hit_path, canvas_depth) = self.hit_path_and_canvas_depth(px, py);
526        let Some(ref hp) = hit_path else {
527            return Vec::new();
528        };
529        self.active_scrollbars
530            .iter()
531            .filter(|bar| {
532                bar.clip_bounds.contains_point(px, py)
533                    && hp.starts_with(&bar.path)
534                    && canvas_depth.is_none_or(|cd| bar.path.len() > cd)
535            })
536            .cloned()
537            .collect()
538    }
539
540    fn subtree_has_portal_anchor(node: &LayoutNode, depth: usize) -> bool {
541        if depth >= 256 || matches!(node.style.display, strata_style::types::Display::None) {
542            return false;
543        }
544        if node.portal_anchor.is_some() {
545            return true;
546        }
547        node.children
548            .iter()
549            .any(|c| Self::subtree_has_portal_anchor(c, depth + 1))
550    }
551
552    fn insert_anchor_key(
553        map: &mut std::collections::HashMap<String, Vec<usize>>,
554        raw_key: &str,
555        path: &[usize],
556    ) {
557        let trimmed = raw_key.trim();
558        if trimmed.is_empty() {
559            return;
560        }
561        let p = path.to_vec();
562        map.insert(trimmed.to_string(), p.clone());
563        if let Some(stripped) = trimmed.strip_prefix("--") {
564            if !stripped.is_empty() {
565                map.entry(stripped.to_string()).or_insert_with(|| p.clone());
566            }
567        } else {
568            map.entry(format!("--{}", trimmed)).or_insert(p);
569        }
570    }
571
572    fn collect_anchor_paths(
573        node: &LayoutNode,
574        current_path: &mut Vec<usize>,
575        out: &mut std::collections::HashMap<String, Vec<usize>>,
576    ) {
577        if current_path.len() >= 256
578            || matches!(node.style.display, strata_style::types::Display::None)
579        {
580            return;
581        }
582        if let Some(ref id) = node.element_id {
583            Self::insert_anchor_key(out, id, current_path);
584        }
585        if let Some(ref aname) = node.anchor_name {
586            Self::insert_anchor_key(out, aname, current_path);
587        }
588        for (idx, child) in node.children.iter().enumerate() {
589            current_path.push(idx);
590            Self::collect_anchor_paths(child, current_path, out);
591            current_path.pop();
592        }
593    }
594
595    fn collect_anchored_portal_paths(
596        node: &LayoutNode,
597        current_path: &mut Vec<usize>,
598        out: &mut Vec<Vec<usize>>,
599    ) {
600        if current_path.len() >= 256
601            || matches!(node.style.display, strata_style::types::Display::None)
602        {
603            return;
604        }
605        if node.portal_anchor.is_some() {
606            out.push(current_path.clone());
607        }
608        for (idx, child) in node.children.iter().enumerate() {
609            current_path.push(idx);
610            Self::collect_anchored_portal_paths(child, current_path, out);
611            current_path.pop();
612        }
613    }
614
615    /// Resolves anchored `<Portal>` / CSS `position-anchor` nodes against their trigger elements'
616    /// live post-scroll bounding boxes with automatic viewport collision flipping (`bottom-end <-> top-end`)
617    /// and viewport margin shifting.
618    pub fn resolve_top_layer_portals(&mut self) {
619        let has_any = Self::subtree_has_portal_anchor(&self.layout_root, 0);
620        self.has_anchored_portals = has_any;
621        if !has_any {
622            return;
623        }
624
625        let mut anchor_paths = std::collections::HashMap::new();
626        let mut path_buf = Vec::new();
627        Self::collect_anchor_paths(&self.layout_root, &mut path_buf, &mut anchor_paths);
628
629        let mut portal_paths = Vec::new();
630        path_buf.clear();
631        Self::collect_anchored_portal_paths(&self.layout_root, &mut path_buf, &mut portal_paths);
632
633        let viewport_rect =
634            strata_layout::Rect::new(0.0, 0.0, self.viewport_width, self.viewport_height);
635
636        for portal_path in portal_paths {
637            let Some((spec, cur_box)) = Self::get_layout_node(&self.layout_root, &portal_path)
638                .and_then(|n| {
639                    n.portal_anchor
640                        .as_deref()
641                        .cloned()
642                        .map(|s| (s, n.geometry.border_box))
643                })
644            else {
645                continue;
646            };
647
648            let key = spec.anchor_id.trim();
649            let anchor_path_opt = anchor_paths
650                .get(key)
651                .or_else(|| key.strip_prefix("--").and_then(|s| anchor_paths.get(s)));
652            let Some(anchor_rect) = anchor_path_opt
653                .and_then(|ap| Self::effective_screen_border_box(&self.layout_root, ap))
654            else {
655                continue;
656            };
657
658            let mut active_box = cur_box;
659            let mut portal_relayout = false;
660            let max_vp_width = (viewport_rect.width - 2.0 * spec.viewport_padding).max(0.0);
661            if spec.match_width && (active_box.width - anchor_rect.width).abs() > 0.5 {
662                let prior = self
663                    .applied_portal_offsets
664                    .remove(&portal_path)
665                    .unwrap_or((0.0, 0.0));
666                if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, &portal_path)
667                {
668                    if prior.0.abs() > 0.0001 || prior.1.abs() > 0.0001 {
669                        target.translate(-prior.0, -prior.1);
670                    }
671                    target.style.width = strata_style::types::Dimension::Px(anchor_rect.width);
672                    strata_layout::solve_out_of_flow_box(
673                        target,
674                        viewport_rect,
675                        viewport_rect,
676                        true,
677                    );
678                    active_box = target.geometry.border_box;
679                    portal_relayout = true;
680                }
681            } else if !spec.match_width && spec.min_width_from_anchor {
682                let target_min_w = if max_vp_width > 0.0 {
683                    anchor_rect.width.min(max_vp_width)
684                } else {
685                    anchor_rect.width
686                };
687                let existing_min_px =
688                    match Self::get_layout_node_mut(&mut self.layout_root, &portal_path)
689                        .map(|n| n.style.min_width)
690                    {
691                        Some(strata_style::types::Dimension::Px(px)) => px,
692                        _ => 0.0,
693                    };
694                let needs_min_resize = active_box.width + 0.5 < target_min_w
695                    || (existing_min_px - target_min_w).abs() > 0.5;
696                let needs_max_cap = max_vp_width > 0.0 && active_box.width > max_vp_width + 0.5;
697                if needs_min_resize || needs_max_cap {
698                    let prior = self
699                        .applied_portal_offsets
700                        .remove(&portal_path)
701                        .unwrap_or((0.0, 0.0));
702                    if let Some(target) =
703                        Self::get_layout_node_mut(&mut self.layout_root, &portal_path)
704                    {
705                        if prior.0.abs() > 0.0001 || prior.1.abs() > 0.0001 {
706                            target.translate(-prior.0, -prior.1);
707                        }
708                        target.style.min_width = strata_style::types::Dimension::Px(target_min_w);
709                        if max_vp_width > 0.0
710                            && matches!(
711                                target.style.max_width,
712                                strata_style::types::Dimension::Auto
713                            )
714                        {
715                            target.style.max_width =
716                                strata_style::types::Dimension::Px(max_vp_width);
717                        }
718                        strata_layout::solve_out_of_flow_box(
719                            target,
720                            viewport_rect,
721                            viewport_rect,
722                            true,
723                        );
724                        active_box = target.geometry.border_box;
725                        portal_relayout = true;
726                    }
727                }
728            }
729
730            if portal_relayout {
731                self.applied_scroll_offsets
732                    .retain(|p, _| !p.starts_with(&portal_path));
733                let mut cur_bp = Some(&self.root_blueprint);
734                for &idx in &portal_path {
735                    cur_bp = cur_bp.and_then(|bp| {
736                        let mut flat = Vec::new();
737                        match bp {
738                            NodeBlueprint::Element { children, .. }
739                            | NodeBlueprint::Fragment(children) => {
740                                for c in children {
741                                    Self::flatten_blueprints(c, &mut flat);
742                                }
743                            }
744                            _ => {}
745                        }
746                        flat.get(idx).copied()
747                    });
748                }
749                if let (Some(bp), Some(target)) = (
750                    cur_bp,
751                    Self::get_layout_node_mut(&mut self.layout_root, &portal_path),
752                ) {
753                    let mut pbuf = portal_path.clone();
754                    Self::apply_scroll_walk(
755                        bp,
756                        target,
757                        &mut pbuf,
758                        &self.scroll_offsets,
759                        &self.scroll_offsets_by_id,
760                        &mut self.applied_scroll_offsets,
761                    );
762                    target.refresh_subtree_hit_metadata();
763                    active_box = target.geometry.border_box;
764                }
765            }
766
767            let (target_x, target_y, _resolved_placement) = strata_layout::solve_anchored_position(
768                anchor_rect,
769                active_box.width,
770                active_box.height,
771                spec.placement,
772                spec.offset,
773                spec.flip,
774                spec.shift,
775                spec.viewport_padding,
776                viewport_rect,
777            );
778
779            let dx = target_x - active_box.x;
780            let dy = target_y - active_box.y;
781            if dx.abs() > 0.0001 || dy.abs() > 0.0001 {
782                if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, &portal_path)
783                {
784                    target.translate(dx, dy);
785                }
786                let entry = self
787                    .applied_portal_offsets
788                    .entry(portal_path)
789                    .or_insert((0.0, 0.0));
790                entry.0 += dx;
791                entry.1 += dy;
792            }
793        }
794    }
795
796    pub(crate) fn apply_scroll_walk(
797        blueprint: &NodeBlueprint,
798        layout: &mut LayoutNode,
799        current_path: &mut Vec<usize>,
800        scroll_offsets: &std::collections::HashMap<Vec<usize>, (f32, f32)>,
801        scroll_offsets_by_id: &std::collections::HashMap<String, (f32, f32)>,
802        applied_scroll_offsets: &mut std::collections::HashMap<Vec<usize>, (f32, f32)>,
803    ) {
804        if matches!(layout.style.display, strata_style::types::Display::None) {
805            return;
806        }
807
808        let is_scroll_y = matches!(
809            layout.style.overflow_y,
810            strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
811        );
812        let is_scroll_x = matches!(
813            layout.style.overflow_x,
814            strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
815        );
816
817        let elem_id = match blueprint {
818            NodeBlueprint::Element { attributes, .. } => attributes.iter().find_map(|a| {
819                if let strata_dom::Attribute::Property { key, value } = a {
820                    if key == "id" {
821                        Some(value.clone())
822                    } else {
823                        None
824                    }
825                } else {
826                    None
827                }
828            }),
829            _ => None,
830        };
831
832        if is_scroll_y || is_scroll_x {
833            let (_, _, max_scroll_x, max_scroll_y) =
834                Self::compute_container_scroll_extents(layout, 0.0, 0.0);
835
836            let (stored_x, stored_y) = if let Some(ref id) = elem_id {
837                scroll_offsets_by_id
838                    .get(id)
839                    .copied()
840                    .or_else(|| scroll_offsets.get(current_path).copied())
841                    .unwrap_or((0.0, 0.0))
842            } else {
843                scroll_offsets
844                    .get(current_path)
845                    .copied()
846                    .unwrap_or((0.0, 0.0))
847            };
848
849            let clamped_x = stored_x.clamp(0.0, max_scroll_x);
850            let clamped_y = stored_y.clamp(0.0, max_scroll_y);
851
852            if let Some(ref id) = elem_id {
853                strata_dom::hooks::set_live_scroll_offset(id, clamped_x, clamped_y);
854            }
855
856            if Self::is_multiline_text_scroll_leaf(layout) {
857                layout.geometry.scroll_offset.y = clamped_y;
858                if clamped_y > 0.0 {
859                    applied_scroll_offsets.insert(current_path.clone(), (0.0, clamped_y));
860                }
861            } else if clamped_x > 0.0 || clamped_y > 0.0 {
862                let target_fixed_cb = layout.style.establishes_fixed_containing_block();
863                let target_abs_cb = layout.style.position != strata_style::types::Position::Static
864                    || target_fixed_cb;
865                for child in &mut layout.children {
866                    child.translate_scrolled(
867                        -clamped_x,
868                        -clamped_y,
869                        target_abs_cb,
870                        target_fixed_cb,
871                    );
872                }
873                for line in &mut layout.line_boxes {
874                    line.bounds.x -= clamped_x;
875                    line.bounds.y -= clamped_y;
876                    for frag in &mut line.text_fragments {
877                        frag.bounds.x -= clamped_x;
878                        frag.bounds.y -= clamped_y;
879                        frag.baseline_y -= clamped_y;
880                    }
881                    for atomic in &mut line.atomic_fragments {
882                        atomic.bounds.x -= clamped_x;
883                        atomic.bounds.y -= clamped_y;
884                    }
885                }
886                applied_scroll_offsets.insert(current_path.clone(), (clamped_x, clamped_y));
887            }
888        }
889
890        // Recursively walk children
891        match blueprint {
892            NodeBlueprint::Element { children, .. } => {
893                let mut flat_children = Vec::new();
894                for c in children {
895                    Self::flatten_blueprints(c, &mut flat_children);
896                }
897                for (i, (&child_bp, child_layout)) in flat_children
898                    .iter()
899                    .zip(layout.children.iter_mut())
900                    .enumerate()
901                {
902                    current_path.push(i);
903                    Self::apply_scroll_walk(
904                        child_bp,
905                        child_layout,
906                        current_path,
907                        scroll_offsets,
908                        scroll_offsets_by_id,
909                        applied_scroll_offsets,
910                    );
911                    current_path.pop();
912                }
913            }
914            NodeBlueprint::Fragment(children) => {
915                let mut flat_children = Vec::new();
916                for c in children {
917                    Self::flatten_blueprints(c, &mut flat_children);
918                }
919                for (i, (&child_bp, child_layout)) in flat_children
920                    .iter()
921                    .zip(layout.children.iter_mut())
922                    .enumerate()
923                {
924                    current_path.push(i);
925                    Self::apply_scroll_walk(
926                        child_bp,
927                        child_layout,
928                        current_path,
929                        scroll_offsets,
930                        scroll_offsets_by_id,
931                        applied_scroll_offsets,
932                    );
933                    current_path.pop();
934                }
935            }
936            _ => {}
937        }
938    }
939
940    #[allow(clippy::too_many_arguments)]
941    pub(crate) fn apply_scroll_xy_delta_to_container(
942        &mut self,
943        path: &[usize],
944        is_id: bool,
945        id: &str,
946        new_scroll_x: f32,
947        new_scroll_y: f32,
948        dx: f32,
949        dy: f32,
950    ) {
951        if is_id && !id.is_empty() {
952            self.scroll_offsets_by_id
953                .insert(id.to_string(), (new_scroll_x, new_scroll_y));
954            strata_dom::hooks::set_live_scroll_offset(id, new_scroll_x, new_scroll_y);
955        }
956        self.scroll_offsets
957            .insert(path.to_vec(), (new_scroll_x, new_scroll_y));
958        self.applied_scroll_offsets
959            .insert(path.to_vec(), (new_scroll_x, new_scroll_y));
960
961        let mut client_w = 0.0_f32;
962        let mut client_h = 0.0_f32;
963        let mut content_h = 0.0_f32;
964        let mut is_text_leaf = false;
965        let mut target_entity_id: Option<strata_primitives::EntityId> = None;
966        if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, path) {
967            client_w = target.geometry.content_box.width;
968            client_h = target.geometry.content_box.height;
969            target_entity_id = Some(target.entity_id);
970            if Self::is_multiline_text_scroll_leaf(target) {
971                is_text_leaf = true;
972                target.geometry.scroll_offset.y = new_scroll_y;
973            } else {
974                let target_fixed_cb = target.style.establishes_fixed_containing_block();
975                let target_abs_cb =
976                    target.style.position != strata_style::types::Position::Static
977                        || target_fixed_cb;
978                for child in &mut target.children {
979                    child.translate_scrolled(-dx, -dy, target_abs_cb, target_fixed_cb);
980                }
981                for line in &mut target.line_boxes {
982                    line.bounds.x -= dx;
983                    line.bounds.y -= dy;
984                    for frag in &mut line.text_fragments {
985                        frag.bounds.x -= dx;
986                        frag.bounds.y -= dy;
987                        frag.baseline_y -= dy;
988                    }
989                    for atomic in &mut line.atomic_fragments {
990                        atomic.bounds.x -= dx;
991                        atomic.bounds.y -= dy;
992                    }
993                }
994            }
995            let (_, ch, _, _) =
996                Self::compute_container_scroll_extents(target, new_scroll_x, new_scroll_y);
997            content_h = ch;
998        }
999        if is_text_leaf {
1000            if let Some(ref active) = self.active_focus {
1001                if active.is_multiline {
1002                    let matches_active = (is_id
1003                        && !id.is_empty()
1004                        && active.input_id.as_deref() == Some(id))
1005                        || (target_entity_id.is_some() && active.entity_id == target_entity_id)
1006                        || Self::find_layout_path_for_focus(
1007                            &self.root_blueprint,
1008                            &self.layout_root,
1009                            active.input_index,
1010                            active.input_id.as_deref(),
1011                            active.entity_id,
1012                        )
1013                        .as_deref()
1014                            == Some(path);
1015                    if matches_active {
1016                        active.state.scroll_y.set(new_scroll_y);
1017                    }
1018                }
1019            }
1020            if is_id && !id.is_empty() {
1021                if let Some(saved) = self.input_states.get(id) {
1022                    saved.scroll_y.set(new_scroll_y);
1023                }
1024            }
1025        }
1026        let has_descendant_scrollbar = self
1027            .active_scrollbars
1028            .iter()
1029            .any(|b| b.path.len() > path.len() && b.path.starts_with(path));
1030        if self.has_anchored_portals {
1031            self.resolve_top_layer_portals();
1032        }
1033        if self.has_anchored_portals || has_descendant_scrollbar {
1034            self.rebuild_active_scrollbars();
1035        } else {
1036            for bar in &mut self.active_scrollbars {
1037                let matches = if is_id && !id.is_empty() && bar.is_id {
1038                    bar.id == id
1039                } else {
1040                    bar.path == path
1041                };
1042                if matches {
1043                    let clamped_y = new_scroll_y.clamp(0.0, bar.max_scroll_y);
1044                    bar.scroll_y = clamped_y;
1045                    bar.thumb_bounds.y = if bar.max_scroll_y > 0.0 && bar.available_travel > 0.0 {
1046                        bar.track_bounds.y + (clamped_y / bar.max_scroll_y) * bar.available_travel
1047                    } else {
1048                        bar.track_bounds.y
1049                    };
1050                }
1051            }
1052        }
1053        if self.has_anchored_portals {
1054            self.spatial_index.sync_bounds(&self.layout_root);
1055        } else {
1056            self.spatial_index
1057                .sync_bounds_for_prefix(&self.layout_root, path);
1058        }
1059        self.fire_scroll_event(
1060            path,
1061            new_scroll_x,
1062            new_scroll_y,
1063            dx,
1064            dy,
1065            client_w,
1066            content_h,
1067            client_w,
1068            client_h,
1069        );
1070    }
1071
1072    /// Helper translating children and line fragments in an overflowing container by `-dy` and recording offsets.
1073    #[allow(clippy::too_many_arguments)]
1074    pub(crate) fn apply_scroll_delta_to_container(
1075        &mut self,
1076        path: &[usize],
1077        is_id: bool,
1078        id: &str,
1079        new_scroll_y: f32,
1080        dy: f32,
1081        _max_scroll_y: f32,
1082        _available_travel: f32,
1083        _bounds_y: f32,
1084    ) {
1085        let cur_x = if is_id && !id.is_empty() {
1086            self.scroll_offsets_by_id
1087                .get(id)
1088                .map(|(x, _)| *x)
1089                .unwrap_or_else(|| self.scroll_offsets.get(path).map(|(x, _)| *x).unwrap_or(0.0))
1090        } else {
1091            self.scroll_offsets
1092                .get(path)
1093                .map(|(x, _)| *x)
1094                .unwrap_or(0.0)
1095        };
1096        self.apply_scroll_xy_delta_to_container(path, is_id, id, cur_x, new_scroll_y, 0.0, dy);
1097    }
1098
1099    pub(crate) fn fire_scroll_event(
1100        &self,
1101        container_path: &[usize],
1102        scroll_x: f32,
1103        scroll_y: f32,
1104        delta_x: f32,
1105        delta_y: f32,
1106        content_w: f32,
1107        content_h: f32,
1108        client_w: f32,
1109        client_h: f32,
1110    ) -> bool {
1111        if let Some((handler, target_box, _)) = Self::find_event_at_or_above_path(
1112            &self.root_blueprint,
1113            &self.layout_root,
1114            container_path,
1115            strata_dom::EventType::Scroll,
1116        ) {
1117            let mut ev = strata_dom::Event::new(strata_dom::EventType::Scroll);
1118            ev.scroll_left = scroll_x as f64;
1119            ev.scroll_top = scroll_y as f64;
1120            ev.scroll_width = content_w as f64;
1121            ev.scroll_height = content_h as f64;
1122            ev.client_width = client_w as f64;
1123            ev.client_height = client_h as f64;
1124            ev.delta_x = delta_x as f64;
1125            ev.delta_y = delta_y as f64;
1126            ev.width = target_box.width as f64;
1127            ev.height = target_box.height as f64;
1128            ev.value = format!("{:.1}", scroll_y);
1129            handler(ev);
1130            return true;
1131        }
1132        false
1133    }
1134
1135    fn blueprint_has_wheel_listener(bp: &NodeBlueprint) -> bool {
1136        match bp {
1137            NodeBlueprint::Element {
1138                attributes,
1139                children,
1140                ..
1141            } => {
1142                attributes.iter().any(|a| {
1143                    matches!(
1144                        a,
1145                        strata_dom::Attribute::EventListener {
1146                            event: strata_dom::EventType::Wheel,
1147                            ..
1148                        }
1149                    )
1150                }) || children.iter().any(Self::blueprint_has_wheel_listener)
1151            }
1152            NodeBlueprint::Fragment(children) => {
1153                children.iter().any(Self::blueprint_has_wheel_listener)
1154            }
1155            _ => false,
1156        }
1157    }
1158
1159    fn dispatch_dom_wheel_event(
1160        &mut self,
1161        px: f32,
1162        py: f32,
1163        delta_x: f32,
1164        delta_y: f32,
1165    ) -> (bool, bool) {
1166        if !Self::blueprint_has_wheel_listener(&self.root_blueprint) {
1167            return (false, false);
1168        }
1169        self.dispatch_bubbling_event_at(
1170            strata_dom::EventType::Wheel,
1171            px,
1172            py,
1173            0,
1174            0,
1175            |ev| {
1176                ev.delta_x = delta_x as f64;
1177                ev.delta_y = delta_y as f64;
1178            },
1179        )
1180    }
1181
1182    /// Dispatches an immediate synchronous scroll wheel delta to the innermost scrollable container under (px, py).
1183    /// Cancels any active kinetic smooth scroll animation.
1184    /// Returns true if a scroll offset changed or a DOM wheel listener handled the event.
1185    pub fn dispatch_scroll(&mut self, px: f32, py: f32, delta_x: f32, delta_y: f32) -> bool {
1186        self.last_mouse_pos = (px, py);
1187        self.active_smooth_scroll = None;
1188
1189        let (wheel_handled, default_prevented) =
1190            self.dispatch_dom_wheel_event(px, py, delta_x, delta_y);
1191        if default_prevented {
1192            return wheel_handled;
1193        }
1194
1195        let matching_bars = self.matching_scrollbars_at(px, py);
1196
1197        for bar in matching_bars.into_iter().rev() {
1198            if bar.max_scroll_y <= 0.0 {
1199                continue;
1200            }
1201
1202            let cur_y = if bar.is_id {
1203                self.scroll_offsets_by_id
1204                    .get(&bar.id)
1205                    .copied()
1206                    .or_else(|| self.scroll_offsets.get(&bar.path).copied())
1207                    .map(|(_, y)| y)
1208                    .unwrap_or(bar.scroll_y)
1209            } else {
1210                self.scroll_offsets
1211                    .get(&bar.path)
1212                    .copied()
1213                    .map(|(_, y)| y)
1214                    .unwrap_or(bar.scroll_y)
1215            };
1216
1217            let candidate_y = (cur_y + delta_y).clamp(0.0, bar.max_scroll_y);
1218            let dy = candidate_y - cur_y;
1219            if dy.abs() > 0.01 {
1220                self.last_scroll_interaction = Some(self.now());
1221                self.apply_scroll_delta_to_container(
1222                    &bar.path,
1223                    bar.is_id,
1224                    &bar.id,
1225                    candidate_y,
1226                    dy,
1227                    bar.max_scroll_y,
1228                    bar.available_travel,
1229                    bar.bounds.y,
1230                );
1231                return true;
1232            }
1233        }
1234
1235        if delta_x.abs() >= 0.01 && self.dispatch_horizontal_wheel_at(px, py, delta_x) {
1236            return true;
1237        }
1238
1239        wheel_handled
1240    }
1241
1242    fn collect_horizontal_scroll_paths_at(
1243        blueprint: &NodeBlueprint,
1244        layout: &LayoutNode,
1245        px: f32,
1246        py: f32,
1247        current_path: &mut Vec<usize>,
1248        inherited_steps: &[super::hit_test::HitClipStep],
1249        in_top_layer: bool,
1250        out: &mut Vec<(Vec<usize>, Option<String>, f32, f32, bool)>,
1251    ) {
1252        if current_path.len() >= 256
1253            || matches!(layout.style.display, strata_style::types::Display::None)
1254        {
1255            return;
1256        }
1257        let node_in_top_layer = in_top_layer || layout.is_top_layer;
1258        let eff_inherited = if layout.is_top_layer {
1259            &[][..]
1260        } else {
1261            Self::effective_hit_clip_steps(layout, inherited_steps)
1262        };
1263        let is_scroll_x = matches!(
1264            layout.style.overflow_x,
1265            strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
1266        );
1267        if is_scroll_x
1268            && layout.geometry.border_box.contains_point(px, py)
1269            && Self::hit_clip_steps_allow(eff_inherited, px, py)
1270        {
1271            let elem_id = layout.element_id.clone().or_else(|| {
1272                if let NodeBlueprint::Element { attributes, .. } = blueprint {
1273                    attributes.iter().find_map(|a| {
1274                        if let strata_dom::Attribute::Property { key, value } = a {
1275                            if key == "id" {
1276                                Some(value.clone())
1277                            } else {
1278                                None
1279                            }
1280                        } else {
1281                            None
1282                        }
1283                    })
1284                } else {
1285                    None
1286                }
1287            });
1288            out.push((
1289                current_path.clone(),
1290                elem_id,
1291                0.0,
1292                0.0,
1293                node_in_top_layer,
1294            ));
1295        }
1296
1297        let mut next_steps = Vec::with_capacity(eff_inherited.len() + 1);
1298        next_steps.extend_from_slice(eff_inherited);
1299        let own_step = Self::hit_clip_step_for(layout);
1300        if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
1301            next_steps.push(own_step);
1302        }
1303
1304        for (i, child_bp, child_layout) in Self::paired_blueprint_children(blueprint, layout) {
1305            current_path.push(i);
1306            Self::collect_horizontal_scroll_paths_at(
1307                child_bp,
1308                child_layout,
1309                px,
1310                py,
1311                current_path,
1312                &next_steps,
1313                node_in_top_layer,
1314                out,
1315            );
1316            current_path.pop();
1317        }
1318    }
1319
1320    fn dispatch_horizontal_wheel_at(&mut self, px: f32, py: f32, delta_x: f32) -> bool {
1321        let (hit_path, canvas_depth) = self.hit_path_and_canvas_depth(px, py);
1322        let Some(ref hp) = hit_path else {
1323            return false;
1324        };
1325        let mut hits = Vec::new();
1326        let mut path_buf = Vec::new();
1327        Self::collect_horizontal_scroll_paths_at(
1328            &self.root_blueprint,
1329            &self.layout_root,
1330            px,
1331            py,
1332            &mut path_buf,
1333            &[],
1334            false,
1335            &mut hits,
1336        );
1337        hits.retain(|(path, _, _, _, _)| {
1338            hp.starts_with(path) && canvas_depth.is_none_or(|cd| path.len() > cd)
1339        });
1340        hits.sort_by_key(|h| h.4);
1341        for (path, elem_id, _, _, _) in hits.into_iter().rev() {
1342            let (cur_x, cur_y) = if let Some(ref id) = elem_id {
1343                self.scroll_offsets_by_id
1344                    .get(id)
1345                    .copied()
1346                    .or_else(|| self.scroll_offsets.get(&path).copied())
1347                    .unwrap_or((0.0, 0.0))
1348            } else {
1349                self.scroll_offsets.get(&path).copied().unwrap_or((0.0, 0.0))
1350            };
1351            let (applied_x, applied_y) = self
1352                .applied_scroll_offsets
1353                .get(&path)
1354                .copied()
1355                .unwrap_or((0.0, 0.0));
1356            let Some(node) = Self::get_layout_node(&self.layout_root, &path) else {
1357                continue;
1358            };
1359            let (_, _, max_scroll_x, _) =
1360                Self::compute_container_scroll_extents(node, applied_x, applied_y);
1361            if max_scroll_x <= 0.0 {
1362                continue;
1363            }
1364            let target_x = (cur_x + delta_x).clamp(0.0, max_scroll_x);
1365            let dx = target_x - applied_x;
1366            if dx.abs() > 0.01 {
1367                self.last_scroll_interaction = Some(self.now());
1368                let is_id = elem_id.is_some();
1369                let id_str = elem_id.unwrap_or_default();
1370                self.apply_scroll_xy_delta_to_container(
1371                    &path,
1372                    is_id,
1373                    &id_str,
1374                    target_x,
1375                    cur_y,
1376                    dx,
1377                    0.0,
1378                );
1379                return true;
1380            }
1381        }
1382        false
1383    }
1384
1385    /// Dispatches a smooth kinetic scroll impulse to the innermost scrollable container under (px, py).
1386    /// Accumulates velocity for rapid consecutive wheel events and initiates a critically damped
1387    /// kinetic transition curve with Chromium Blink parity.
1388    /// Dispatches a smooth scroll or DOM wheel event, returning `(wheel_handled, scroll_changed)`.
1389    pub fn dispatch_smooth_scroll_action(
1390        &mut self,
1391        px: f32,
1392        py: f32,
1393        delta_x: f32,
1394        delta_y: f32,
1395    ) -> (bool, bool) {
1396        self.last_mouse_pos = (px, py);
1397        if delta_y.abs() < 0.01 && delta_x.abs() < 0.01 {
1398            return (false, false);
1399        }
1400
1401        let (wheel_handled, default_prevented) =
1402            self.dispatch_dom_wheel_event(px, py, delta_x, delta_y);
1403        if default_prevented {
1404            return (wheel_handled, false);
1405        }
1406        if delta_y.abs() < 0.01 {
1407            if delta_x.abs() >= 0.01 && self.dispatch_horizontal_wheel_at(px, py, delta_x) {
1408                return (wheel_handled, true);
1409            }
1410            return (wheel_handled, false);
1411        }
1412
1413        let mut matching_bars = self.matching_scrollbars_at(px, py);
1414        if matching_bars.is_empty() && !wheel_handled {
1415            if let Some(ref active) = self.active_focus {
1416                if active.is_multiline {
1417                    let (_, canvas_depth) = self.hit_path_and_canvas_depth(px, py);
1418                    if canvas_depth.is_none() {
1419                        if let Some(focus_path) = Self::find_layout_path_for_focus(
1420                            &self.root_blueprint,
1421                            &self.layout_root,
1422                            active.input_index,
1423                            active.input_id.as_deref(),
1424                            active.entity_id,
1425                        ) {
1426                            let covered_by_top_layer =
1427                                self.point_hits_non_backdrop_top_layer_portal(px, py);
1428                            let focused_bars: Vec<ActiveScrollbar> = self
1429                                .active_scrollbars
1430                                .iter()
1431                                .filter(|bar| {
1432                                    focus_path.starts_with(&bar.path)
1433                                        && (!covered_by_top_layer || bar.is_top_layer)
1434                                })
1435                                .cloned()
1436                                .collect();
1437                            if focused_bars.iter().any(|b| b.path == focus_path) {
1438                                matching_bars = focused_bars;
1439                            }
1440                        }
1441                    }
1442                }
1443            }
1444        }
1445        if matching_bars.is_empty() && delta_x.abs() >= 0.01 {
1446            let horiz_changed = self.dispatch_horizontal_wheel_at(px, py, delta_x);
1447            return (wheel_handled, horiz_changed);
1448        }
1449
1450        // Scroll chaining: target the innermost container that can still absorb the delta.
1451        // When every matching container is already at its limit, fall back to the outermost
1452        // container so the event is not trapped by the innermost saturated scroller.
1453        let target_bar = matching_bars
1454            .iter()
1455            .rev()
1456            .find(|b| {
1457                if b.max_scroll_y <= 0.0 {
1458                    return false;
1459                }
1460                let cur_y = if b.is_id {
1461                    self.scroll_offsets_by_id
1462                        .get(&b.id)
1463                        .copied()
1464                        .or_else(|| self.scroll_offsets.get(&b.path).copied())
1465                        .map(|(_, y)| y)
1466                        .unwrap_or(b.scroll_y)
1467                } else {
1468                    self.scroll_offsets
1469                        .get(&b.path)
1470                        .copied()
1471                        .map(|(_, y)| y)
1472                        .unwrap_or(b.scroll_y)
1473                };
1474                if delta_y < 0.0 {
1475                    cur_y > 0.01
1476                } else {
1477                    cur_y < b.max_scroll_y - 0.01
1478                }
1479            })
1480            .cloned()
1481            .or_else(|| matching_bars.iter().find(|b| b.max_scroll_y > 0.0).cloned());
1482
1483        let Some(bar) = target_bar else {
1484            return (wheel_handled, false);
1485        };
1486
1487        let now = self.now();
1488        self.last_scroll_interaction = Some(now);
1489
1490        let cur_y = if bar.is_id {
1491            self.scroll_offsets_by_id
1492                .get(&bar.id)
1493                .copied()
1494                .or_else(|| self.scroll_offsets.get(&bar.path).copied())
1495                .map(|(_, y)| y)
1496                .unwrap_or(bar.scroll_y)
1497        } else {
1498            self.scroll_offsets
1499                .get(&bar.path)
1500                .copied()
1501                .map(|(_, y)| y)
1502                .unwrap_or(bar.scroll_y)
1503        };
1504
1505        if self
1506            .active_smooth_scroll
1507            .as_ref()
1508            .is_some_and(|t| t.container_path == bar.path)
1509        {
1510            if let Some(mut tracker) = self.active_smooth_scroll.take() {
1511                let dt_flick = now.duration_since(tracker.last_event_time).as_secs_f32();
1512                let remaining = tracker.target_y - tracker.current_y;
1513                let same_dir = remaining == 0.0 || (remaining > 0.0) == (delta_y > 0.0);
1514                // Continuous touchpad / high-resolution streams emit <48px packets or arrive on a
1515                // 2-18ms (60-500Hz) HID cadence; only discrete wheel flicks receive momentum.
1516                let is_continuous_hid_cadence = (0.002..0.018).contains(&dt_flick);
1517                let is_discrete_flick =
1518                    same_dir && delta_y.abs() >= 48.0 && !is_continuous_hid_cadence;
1519                let accel = if is_discrete_flick && dt_flick < 0.20 {
1520                    (1.0 + (0.05 / dt_flick.max(0.02)).min(1.3)).min(2.3)
1521                } else {
1522                    1.0
1523                };
1524
1525                let t_prev = now.duration_since(tracker.start_time).as_secs_f32();
1526                let omega = tracker.omega;
1527                let e0 = tracker.start_y - tracker.target_y;
1528                let c2 = tracker.initial_velocity + omega * e0;
1529                let decay = (-omega * t_prev).exp();
1530                let y_now =
1531                    (tracker.target_y + (e0 + c2 * t_prev) * decay).clamp(0.0, bar.max_scroll_y);
1532                let v_now = (tracker.initial_velocity - omega * c2 * t_prev) * decay;
1533
1534                let catchup_dy = y_now - tracker.current_y;
1535                if catchup_dy.abs() > 0.001 {
1536                    self.apply_scroll_delta_to_container(
1537                        &tracker.container_path,
1538                        tracker.is_id,
1539                        &tracker.container_id,
1540                        y_now,
1541                        catchup_dy,
1542                        bar.max_scroll_y,
1543                        bar.available_travel,
1544                        bar.bounds.y,
1545                    );
1546                    tracker.current_y = y_now;
1547                }
1548
1549                let impulse = delta_y * accel;
1550                let new_target = (tracker.target_y + impulse).clamp(0.0, bar.max_scroll_y);
1551
1552                tracker.start_y = y_now;
1553                tracker.initial_velocity = v_now;
1554                tracker.target_y = new_target;
1555                tracker.start_time = now;
1556                tracker.last_event_time = now;
1557                tracker.max_scroll_y = bar.max_scroll_y;
1558                tracker.available_travel = bar.available_travel;
1559                tracker.bounds_y = bar.bounds.y;
1560                self.active_smooth_scroll = Some(tracker);
1561                return (wheel_handled, true);
1562            }
1563        }
1564
1565        let new_target = (cur_y + delta_y).clamp(0.0, bar.max_scroll_y);
1566        self.active_smooth_scroll = Some(SmoothScrollTracker {
1567            container_path: bar.path,
1568            container_id: bar.id,
1569            is_id: bar.is_id,
1570            max_scroll_y: bar.max_scroll_y,
1571            available_travel: bar.available_travel,
1572            bounds_y: bar.bounds.y,
1573            current_y: cur_y,
1574            target_y: new_target,
1575            start_y: cur_y,
1576            initial_velocity: 0.0,
1577            start_time: now,
1578            last_event_time: now,
1579            omega: 18.0,
1580        });
1581
1582        (wheel_handled, true)
1583    }
1584
1585    /// Dispatches a smooth kinetic scroll impulse to the innermost scrollable container under (px, py).
1586    /// Returns `true` if either a DOM `wheel` listener handled the event or a scroll animation updated.
1587    pub fn dispatch_smooth_scroll(&mut self, px: f32, py: f32, delta_x: f32, delta_y: f32) -> bool {
1588        let (wheel_handled, scroll_changed) =
1589            self.dispatch_smooth_scroll_action(px, py, delta_x, delta_y);
1590        wheel_handled || scroll_changed
1591    }
1592
1593    /// Polls and updates active kinetic smooth scroll animation at a specific timestamp.
1594    /// Returns true if a position changed and a redraw is required.
1595    pub fn poll_smooth_scroll_at(&mut self, now: std::time::Instant) -> bool {
1596        let Some(mut tracker) = self.active_smooth_scroll.take() else {
1597            return false;
1598        };
1599
1600        let t = now.duration_since(tracker.start_time).as_secs_f32();
1601        let omega = tracker.omega;
1602        let e0 = tracker.start_y - tracker.target_y;
1603        let c2 = tracker.initial_velocity + omega * e0;
1604        let decay = (-omega * t).exp();
1605
1606        let raw_y = tracker.target_y + (e0 + c2 * t) * decay;
1607        let clamped_y = raw_y.clamp(0.0, tracker.max_scroll_y);
1608        let vel = (tracker.initial_velocity - omega * c2 * t) * decay;
1609
1610        let is_settled =
1611            t >= 0.40 || ((clamped_y - tracker.target_y).abs() < 0.25 && vel.abs() < 1.0);
1612        let new_y = if is_settled {
1613            tracker.target_y
1614        } else {
1615            clamped_y
1616        };
1617
1618        let dy = new_y - tracker.current_y;
1619        let mut redraw = false;
1620
1621        if dy.abs() > 0.001 {
1622            self.apply_scroll_delta_to_container(
1623                &tracker.container_path,
1624                tracker.is_id,
1625                &tracker.container_id,
1626                new_y,
1627                dy,
1628                tracker.max_scroll_y,
1629                tracker.available_travel,
1630                tracker.bounds_y,
1631            );
1632            tracker.current_y = new_y;
1633            redraw = true;
1634        }
1635
1636        if !is_settled {
1637            self.active_smooth_scroll = Some(tracker);
1638        }
1639
1640        redraw
1641    }
1642
1643    /// Evaluates active smooth scroll animation at the current instant.
1644    #[inline]
1645    pub fn poll_smooth_scroll(&mut self) -> bool {
1646        self.poll_smooth_scroll_at(self.now())
1647    }
1648
1649    /// Scrolls the innermost scroll container under (px, py) to the very top.
1650    pub fn scroll_to_top(&mut self, px: f32, py: f32) -> bool {
1651        self.active_smooth_scroll = None;
1652        let matching_bars = self.matching_scrollbars_at(px, py);
1653
1654        if let Some(bar) = matching_bars.into_iter().next_back() {
1655            let cur_y = bar.scroll_y;
1656            let dy = 0.0 - cur_y;
1657            if dy.abs() > 0.01 {
1658                self.last_scroll_interaction = Some(self.now());
1659                self.apply_scroll_delta_to_container(
1660                    &bar.path,
1661                    bar.is_id,
1662                    &bar.id,
1663                    0.0,
1664                    dy,
1665                    bar.max_scroll_y,
1666                    bar.available_travel,
1667                    bar.bounds.y,
1668                );
1669                return true;
1670            }
1671        }
1672        false
1673    }
1674
1675    /// Scrolls the innermost scroll container under (px, py) to the very bottom.
1676    pub fn scroll_to_bottom(&mut self, px: f32, py: f32) -> bool {
1677        self.active_smooth_scroll = None;
1678        let matching_bars = self.matching_scrollbars_at(px, py);
1679
1680        if let Some(bar) = matching_bars.into_iter().next_back() {
1681            if bar.max_scroll_y > 0.0 {
1682                let cur_y = bar.scroll_y;
1683                let dy = bar.max_scroll_y - cur_y;
1684                if dy.abs() > 0.01 {
1685                    self.last_scroll_interaction = Some(self.now());
1686                    self.apply_scroll_delta_to_container(
1687                        &bar.path,
1688                        bar.is_id,
1689                        &bar.id,
1690                        bar.max_scroll_y,
1691                        dy,
1692                        bar.max_scroll_y,
1693                        bar.available_travel,
1694                        bar.bounds.y,
1695                    );
1696                    return true;
1697                }
1698            }
1699        }
1700        false
1701    }
1702
1703    /// Returns the live `(scroll_left, scroll_top)` offset for a scrollable element `id`.
1704    pub fn scroll_offset_by_id(&self, id: &str) -> (f32, f32) {
1705        if let Some(off) = self.scroll_offsets_by_id.get(id) {
1706            return *off;
1707        }
1708        if let Some(bar) = self
1709            .active_scrollbars
1710            .iter()
1711            .find(|b| b.is_id && b.id == id)
1712        {
1713            return (0.0, bar.scroll_y);
1714        }
1715        strata_dom::get_scroll_offset(id)
1716    }
1717
1718    /// Scrolls the scroll container with element `id` (or the primary scroll container if `id` is empty)
1719    /// to `(scroll_x, scroll_y)`, clamping to the container's maximum scroll bounds and firing `EventType::Scroll`.
1720    pub fn scroll_to_by_id(&mut self, id: &str, scroll_x: f32, scroll_y: f32) -> bool {
1721        self.active_smooth_scroll = None;
1722        let target_path = if id.is_empty() {
1723            self.active_scrollbars
1724                .iter()
1725                .max_by(|a, b| {
1726                    (a.bounds.width * a.bounds.height)
1727                        .partial_cmp(&(b.bounds.width * b.bounds.height))
1728                        .unwrap_or(std::cmp::Ordering::Equal)
1729                })
1730                .map(|b| b.path.clone())
1731        } else {
1732            self.active_scrollbars
1733                .iter()
1734                .find(|b| b.is_id && b.id == id)
1735                .map(|b| b.path.clone())
1736                .or_else(|| {
1737                    let mut buf = Vec::new();
1738                    Self::find_element_path_by_id(&self.root_blueprint, &self.layout_root, id, &mut buf)
1739                })
1740        };
1741
1742        if let Some(path) = target_path {
1743            let (applied_x, applied_y) = self
1744                .applied_scroll_offsets
1745                .get(&path)
1746                .copied()
1747                .unwrap_or((0.0, 0.0));
1748            if let Some(node) = Self::get_layout_node(&self.layout_root, &path) {
1749                let is_scroll_x = matches!(
1750                    node.style.overflow_x,
1751                    strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
1752                );
1753                let is_scroll_y = matches!(
1754                    node.style.overflow_y,
1755                    strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
1756                );
1757                if is_scroll_x || is_scroll_y {
1758                    let (_, _, max_scroll_x, max_scroll_y) =
1759                        Self::compute_container_scroll_extents(node, applied_x, applied_y);
1760                    let clamped_x = if is_scroll_x {
1761                        scroll_x.clamp(0.0, max_scroll_x)
1762                    } else {
1763                        0.0
1764                    };
1765                    let clamped_y = if is_scroll_y {
1766                        scroll_y.clamp(0.0, max_scroll_y)
1767                    } else {
1768                        0.0
1769                    };
1770                    let dx = clamped_x - applied_x;
1771                    let dy = clamped_y - applied_y;
1772                    let is_id = !id.is_empty();
1773                    if is_id {
1774                        self.scroll_offsets_by_id
1775                            .insert(id.to_string(), (clamped_x, clamped_y));
1776                        strata_dom::hooks::set_live_scroll_offset(id, clamped_x, clamped_y);
1777                    }
1778                    if dx.abs() > 0.01 || dy.abs() > 0.01 {
1779                        self.last_scroll_interaction = Some(self.now());
1780                        self.apply_scroll_xy_delta_to_container(
1781                            &path,
1782                            is_id,
1783                            id,
1784                            clamped_x,
1785                            clamped_y,
1786                            dx,
1787                            dy,
1788                        );
1789                        return true;
1790                    }
1791                    return false;
1792                }
1793            }
1794        }
1795
1796        if !id.is_empty() {
1797            let clamped_x = scroll_x.max(0.0);
1798            let clamped_y = scroll_y.max(0.0);
1799            self.scroll_offsets_by_id
1800                .insert(id.to_string(), (clamped_x, clamped_y));
1801            strata_dom::hooks::set_live_scroll_offset(id, clamped_x, clamped_y);
1802        }
1803        false
1804    }
1805
1806    /// Scrolls the scroll container with element `id` (or the primary scroll container if `id` is empty) to the top.
1807    pub fn scroll_to_top_by_id(&mut self, id: &str) -> bool {
1808        if id.is_empty() {
1809            let (px, py) = self.last_mouse_pos;
1810            return self.scroll_to_top(px, py);
1811        }
1812        self.scroll_to_by_id(id, 0.0, 0.0)
1813    }
1814
1815    /// Scrolls the scroll container with element `id` (or the primary scroll container if `id` is empty) to the bottom.
1816    pub fn scroll_to_bottom_by_id(&mut self, id: &str) -> bool {
1817        if id.is_empty() {
1818            let (px, py) = self.last_mouse_pos;
1819            return self.scroll_to_bottom(px, py);
1820        }
1821        if let Some(bar) = self
1822            .active_scrollbars
1823            .iter()
1824            .find(|b| b.is_id && b.id == id)
1825            .cloned()
1826        {
1827            return self.scroll_to_by_id(id, 0.0, bar.max_scroll_y);
1828        }
1829        false
1830    }
1831
1832    pub(crate) fn find_element_path_by_id(
1833        blueprint: &NodeBlueprint,
1834        layout: &LayoutNode,
1835        target_id: &str,
1836        current_path: &mut Vec<usize>,
1837    ) -> Option<Vec<usize>> {
1838        if layout.element_id.as_deref() == Some(target_id) {
1839            return Some(current_path.clone());
1840        }
1841        if let NodeBlueprint::Element { attributes, .. } = blueprint {
1842            for attr in attributes {
1843                if let strata_dom::Attribute::Property { key, value } = attr {
1844                    if key == "id" && value == target_id {
1845                        return Some(current_path.clone());
1846                    }
1847                }
1848            }
1849        }
1850        for (idx, child_bp, child_layout) in Self::paired_blueprint_children(blueprint, layout) {
1851            current_path.push(idx);
1852            if let Some(found) =
1853                Self::find_element_path_by_id(child_bp, child_layout, target_id, current_path)
1854            {
1855                return Some(found);
1856            }
1857            current_path.pop();
1858        }
1859        None
1860    }
1861
1862    /// Scrolls the nearest enclosing scroll container so that the descendant element with `target_id` is visible.
1863    pub fn scroll_into_view(&mut self, target_id: &str) -> bool {
1864        if target_id.is_empty() {
1865            return false;
1866        }
1867        let mut path_buf = Vec::new();
1868        let Some(target_path) = Self::find_element_path_by_id(
1869            &self.root_blueprint,
1870            &self.layout_root,
1871            target_id,
1872            &mut path_buf,
1873        ) else {
1874            return false;
1875        };
1876
1877        let Some(target_box) =
1878            Self::get_layout_node(&self.layout_root, &target_path).map(|n| n.geometry.border_box)
1879        else {
1880            return false;
1881        };
1882
1883        // Find the deepest active scrollbar that is a strict ancestor of `target_path`
1884        let ancestor_bar = self
1885            .active_scrollbars
1886            .iter()
1887            .filter(|b| target_path.len() > b.path.len() && target_path.starts_with(&b.path))
1888            .max_by_key(|b| b.path.len())
1889            .cloned();
1890
1891        let Some(bar) = ancestor_bar else {
1892            return false;
1893        };
1894
1895        let container_box = Self::get_layout_node(&self.layout_root, &bar.path)
1896            .map(|n| n.geometry.content_box)
1897            .unwrap_or(bar.bounds);
1898
1899        let cur_y = bar.scroll_y;
1900        let new_y = if target_box.y < container_box.y {
1901            let dy = target_box.y - container_box.y;
1902            (cur_y + dy).clamp(0.0, bar.max_scroll_y)
1903        } else if target_box.y + target_box.height > container_box.y + container_box.height {
1904            let dy = (target_box.y + target_box.height) - (container_box.y + container_box.height);
1905            (cur_y + dy).clamp(0.0, bar.max_scroll_y)
1906        } else {
1907            cur_y
1908        };
1909
1910        let dy = new_y - cur_y;
1911        if dy.abs() > 0.01 {
1912            self.active_smooth_scroll = None;
1913            self.last_scroll_interaction = Some(self.now());
1914            self.apply_scroll_delta_to_container(
1915                &bar.path,
1916                bar.is_id,
1917                &bar.id,
1918                new_y,
1919                dy,
1920                bar.max_scroll_y,
1921                bar.available_travel,
1922                bar.bounds.y,
1923            );
1924            return true;
1925        }
1926        false
1927    }
1928
1929    /// Drains and executes any programmatic scroll commands queued via `strata_dom::scroll_to`,
1930    /// `scroll_to_top`, `scroll_to_bottom`, or `scroll_into_view`.
1931    pub fn flush_pending_scroll_commands(&mut self) -> bool {
1932        if !strata_dom::hooks::has_pending_scroll_commands() {
1933            return false;
1934        }
1935        let cmds = strata_dom::hooks::take_pending_scroll_commands();
1936        let mut any_changed = false;
1937        for cmd in cmds {
1938            match cmd {
1939                strata_dom::ProgrammaticScrollCommand::ScrollTo { id, x, y } => {
1940                    if self.scroll_to_by_id(&id, x, y) {
1941                        any_changed = true;
1942                    }
1943                }
1944                strata_dom::ProgrammaticScrollCommand::ScrollToTop { id } => {
1945                    if self.scroll_to_top_by_id(&id) {
1946                        any_changed = true;
1947                    }
1948                }
1949                strata_dom::ProgrammaticScrollCommand::ScrollToBottom { id } => {
1950                    if self.scroll_to_bottom_by_id(&id) {
1951                        any_changed = true;
1952                    }
1953                }
1954                strata_dom::ProgrammaticScrollCommand::ScrollIntoView { target_id } => {
1955                    if self.scroll_into_view(&target_id) {
1956                        any_changed = true;
1957                    }
1958                }
1959            }
1960        }
1961        any_changed
1962    }
1963}