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