1use super::*;
4
5impl AppRuntime {
6 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 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 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 pub fn unapply_scroll_offsets(&mut self) {
91 if !self.applied_portal_offsets.is_empty() {
92 for (path, &(dx, dy)) in &self.applied_portal_offsets {
93 if dx.abs() > 0.0001 || dy.abs() > 0.0001 {
94 if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, path) {
95 target.translate(-dx, -dy);
96 }
97 }
98 }
99 self.applied_portal_offsets.clear();
100 }
101
102 if self.applied_scroll_offsets.is_empty() {
103 return;
104 }
105 for (path, &(applied_x, applied_y)) in &self.applied_scroll_offsets {
106 if applied_x.abs() > 0.0001 || applied_y.abs() > 0.0001 {
107 if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, path) {
108 let target_fixed_cb = target.style.establishes_fixed_containing_block();
109 let target_abs_cb = target.style.position
110 != strata_style::types::Position::Static
111 || target_fixed_cb;
112 for child in &mut target.children {
113 child.translate_scrolled(
114 applied_x,
115 applied_y,
116 target_abs_cb,
117 target_fixed_cb,
118 );
119 }
120 for line in &mut target.line_boxes {
121 line.bounds.x += applied_x;
122 line.bounds.y += applied_y;
123 for frag in &mut line.text_fragments {
124 frag.bounds.x += applied_x;
125 frag.bounds.y += applied_y;
126 frag.baseline_y += applied_y;
127 }
128 for atomic in &mut line.atomic_fragments {
129 atomic.bounds.x += applied_x;
130 atomic.bounds.y += applied_y;
131 }
132 }
133 }
134 }
135 }
136 self.applied_scroll_offsets.clear();
137 }
138
139 pub fn apply_scroll_offsets(&mut self) {
142 self.active_scrollbars.clear();
143 let mut path = Vec::new();
144 Self::apply_scroll_walk(
145 &self.root_blueprint,
146 &mut self.layout_root,
147 &mut path,
148 &self.scroll_offsets,
149 &self.scroll_offsets_by_id,
150 &mut self.applied_scroll_offsets,
151 &mut self.active_scrollbars,
152 );
153 self.flush_pending_scroll_commands();
154 self.sync_scroll_animations();
155 self.resolve_top_layer_portals();
156 self.rebuild_active_scrollbars();
157 }
158
159 fn effective_screen_border_box(root: &LayoutNode, path: &[usize]) -> Option<strata_layout::Rect> {
162 let mut mat = strata_primitives::geom::Matrix4x4::identity();
163 let mut cur = root;
164 for &idx in path {
165 if cur.is_top_layer {
166 mat = strata_primitives::geom::Matrix4x4::identity();
167 }
168 if cur.style.has_transform() {
169 let bx = cur.geometry.border_box.x;
170 let by = cur.geometry.border_box.y;
171 let local_mat = cur.style.compute_transform_matrix(
172 cur.geometry.border_box.width,
173 cur.geometry.border_box.height,
174 );
175 let origin_mat = strata_primitives::geom::Matrix4x4::translation(bx, by, 0.0)
176 .multiply(&local_mat)
177 .multiply(&strata_primitives::geom::Matrix4x4::translation(-bx, -by, 0.0));
178 mat = mat.multiply(&origin_mat);
179 }
180 cur = cur.children.get(idx)?;
181 }
182 if cur.is_top_layer {
183 mat = strata_primitives::geom::Matrix4x4::identity();
184 }
185 let b = cur.geometry.border_box;
186 if !cur.style.has_transform() && mat == strata_primitives::geom::Matrix4x4::identity() {
187 return Some(b);
188 }
189 if cur.style.has_transform() {
190 let local_mat = cur.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 mat = mat.multiply(&origin_mat);
195 }
196 let corners = [
197 mat.transform_point(b.x, b.y),
198 mat.transform_point(b.x + b.width, b.y),
199 mat.transform_point(b.x, b.y + b.height),
200 mat.transform_point(b.x + b.width, b.y + b.height),
201 ];
202 let min_x = corners.iter().map(|c| c.0).fold(f32::INFINITY, f32::min);
203 let min_y = corners.iter().map(|c| c.1).fold(f32::INFINITY, f32::min);
204 let max_x = corners.iter().map(|c| c.0).fold(f32::NEG_INFINITY, f32::max);
205 let max_y = corners.iter().map(|c| c.1).fold(f32::NEG_INFINITY, f32::max);
206 Some(strata_layout::Rect::new(
207 min_x,
208 min_y,
209 (max_x - min_x).max(0.0),
210 (max_y - min_y).max(0.0),
211 ))
212 }
213
214 fn compute_container_scroll_extents(
215 layout: &LayoutNode,
216 applied_x: f32,
217 applied_y: f32,
218 ) -> (f32, f32, f32, f32) {
219 let viewport_w = layout.geometry.content_box.width;
220 let viewport_h = layout.geometry.content_box.height;
221
222 let mut max_child_x = layout.geometry.content_box.x;
223 let mut max_child_y = layout.geometry.content_box.y;
224
225 let target_fixed_cb = layout.style.establishes_fixed_containing_block();
226 let target_abs_cb =
227 layout.style.position != strata_style::types::Position::Static || target_fixed_cb;
228
229 for child in &layout.children {
230 if child.is_top_layer
231 || child.style.position == strata_style::types::Position::Fixed
232 || (child.style.position == strata_style::types::Position::Absolute
233 && !target_abs_cb)
234 {
235 continue;
236 }
237 max_child_x =
238 max_child_x.max(child.geometry.border_box.x + child.geometry.border_box.width + applied_x);
239 max_child_y =
240 max_child_y.max(child.geometry.border_box.y + child.geometry.border_box.height + applied_y);
241 }
242 for line in &layout.line_boxes {
243 max_child_x = max_child_x.max(line.bounds.x + line.bounds.width + applied_x);
244 max_child_y = max_child_y.max(line.bounds.y + line.bounds.height + applied_y);
245 }
246
247 let content_w = (max_child_x - layout.geometry.content_box.x).max(0.0);
248 let content_h = (max_child_y - layout.geometry.content_box.y).max(0.0);
249 let max_scroll_x = (content_w - viewport_w).max(0.0);
250 let max_scroll_y = (content_h - viewport_h).max(0.0);
251 (content_w, content_h, max_scroll_x, max_scroll_y)
252 }
253
254 pub(crate) fn rebuild_active_scrollbars(&mut self) {
258 self.active_scrollbars.clear();
259 let viewport_clip = if self.viewport_width > 0.0 && self.viewport_height > 0.0 {
260 Some(strata_layout::Rect::new(
261 0.0,
262 0.0,
263 self.viewport_width,
264 self.viewport_height,
265 ))
266 } else {
267 None
268 };
269 let mut path = Vec::new();
270 Self::collect_active_scrollbars_walk(
271 &self.root_blueprint,
272 &self.layout_root,
273 &mut path,
274 &[],
275 false,
276 viewport_clip,
277 &self.scroll_offsets,
278 &self.scroll_offsets_by_id,
279 &self.applied_scroll_offsets,
280 &mut self.active_scrollbars,
281 );
282 self.active_scrollbars.sort_by_key(|b| b.is_top_layer);
283 }
284
285 #[allow(clippy::too_many_arguments)]
286 fn collect_active_scrollbars_walk(
287 blueprint: &NodeBlueprint,
288 layout: &LayoutNode,
289 current_path: &mut Vec<usize>,
290 inherited_steps: &[super::hit_test::HitClipStep],
291 in_top_layer: bool,
292 viewport_clip: Option<strata_layout::Rect>,
293 scroll_offsets: &std::collections::HashMap<Vec<usize>, (f32, f32)>,
294 scroll_offsets_by_id: &std::collections::HashMap<String, (f32, f32)>,
295 applied_scroll_offsets: &std::collections::HashMap<Vec<usize>, (f32, f32)>,
296 out: &mut Vec<ActiveScrollbar>,
297 ) {
298 if current_path.len() >= 256
299 || matches!(layout.style.display, strata_style::types::Display::None)
300 {
301 return;
302 }
303
304 let node_in_top_layer = in_top_layer || layout.is_top_layer;
305 let eff_inherited = if layout.is_top_layer {
306 &[][..]
307 } else {
308 Self::effective_hit_clip_steps(layout, inherited_steps)
309 };
310
311 let is_scroll_y = matches!(
312 layout.style.overflow_y,
313 strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
314 );
315 let viewport_h = layout.geometry.content_box.height;
316 if is_scroll_y && viewport_h > 0.0 {
317 let elem_id = match blueprint {
318 NodeBlueprint::Element { attributes, .. } => attributes.iter().find_map(|a| {
319 if let strata_dom::Attribute::Property { key, value } = a {
320 if key == "id" {
321 Some(value.clone())
322 } else {
323 None
324 }
325 } else {
326 None
327 }
328 }),
329 _ => None,
330 };
331 let (applied_x, applied_y) = applied_scroll_offsets
332 .get(current_path)
333 .copied()
334 .unwrap_or((0.0, 0.0));
335 let (_, content_h, _, max_scroll_y) =
336 Self::compute_container_scroll_extents(layout, applied_x, applied_y);
337
338 if max_scroll_y > 0.0 {
339 let stored_y = if let Some(ref id) = elem_id {
340 scroll_offsets_by_id
341 .get(id)
342 .copied()
343 .or_else(|| scroll_offsets.get(current_path).copied())
344 .map(|(_, y)| y)
345 .unwrap_or(applied_y)
346 } else {
347 scroll_offsets
348 .get(current_path)
349 .copied()
350 .map(|(_, y)| y)
351 .unwrap_or(applied_y)
352 };
353 let clamped_y = stored_y.clamp(0.0, max_scroll_y);
354
355 let border_box = layout.geometry.border_box;
356 let mut clip_bounds = border_box;
357 if let Some(vp) = viewport_clip {
358 clip_bounds = clip_bounds
359 .intersect(vp)
360 .unwrap_or_else(|| strata_layout::Rect::new(0.0, 0.0, 0.0, 0.0));
361 }
362 for step in eff_inherited {
363 if let Some(c) = step.clip {
364 clip_bounds = clip_bounds
365 .intersect(c)
366 .unwrap_or_else(|| strata_layout::Rect::new(0.0, 0.0, 0.0, 0.0));
367 }
368 }
369
370 let track_width = 10.0;
371 let track_x = border_box.x + border_box.width - track_width;
372 let track_y = border_box.y;
373 let track_h = border_box.height;
374 let track_bounds =
375 strata_layout::Rect::new(track_x, track_y, track_width, track_h);
376
377 let min_thumb = 24.0_f32.min(track_h);
378 let thumb_h =
379 ((viewport_h / content_h.max(1.0)) * track_h).clamp(min_thumb, track_h);
380 let available_travel = (track_h - thumb_h).max(0.0);
381 let thumb_y = if max_scroll_y > 0.0 && available_travel > 0.0 {
382 track_y + (clamped_y / max_scroll_y) * available_travel
383 } else {
384 track_y
385 };
386 let thumb_bounds =
387 strata_layout::Rect::new(track_x, thumb_y, track_width, thumb_h);
388
389 out.push(ActiveScrollbar {
390 bounds: border_box,
391 clip_bounds,
392 border_radius: layout.style.border_radius,
393 is_top_layer: node_in_top_layer,
394 track_bounds,
395 thumb_bounds,
396 scroll_y: clamped_y,
397 max_scroll_y,
398 content_h,
399 is_id: elem_id.is_some(),
400 id: elem_id.unwrap_or_default(),
401 path: current_path.clone(),
402 available_travel,
403 });
404 }
405 }
406
407 let mut next_steps = Vec::with_capacity(eff_inherited.len() + 1);
408 next_steps.extend_from_slice(eff_inherited);
409 let own_step = Self::hit_clip_step_for(layout);
410 if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
411 next_steps.push(own_step);
412 }
413
414 for (i, child_bp, child_layout) in Self::paired_blueprint_children(blueprint, layout) {
415 current_path.push(i);
416 Self::collect_active_scrollbars_walk(
417 child_bp,
418 child_layout,
419 current_path,
420 &next_steps,
421 node_in_top_layer,
422 viewport_clip,
423 scroll_offsets,
424 scroll_offsets_by_id,
425 applied_scroll_offsets,
426 out,
427 );
428 current_path.pop();
429 }
430 }
431
432 #[inline]
433 fn matching_scrollbars_at(&self, px: f32, py: f32) -> Vec<ActiveScrollbar> {
434 self.active_scrollbars
435 .iter()
436 .filter(|bar| bar.clip_bounds.contains_point(px, py))
437 .cloned()
438 .collect()
439 }
440
441 fn subtree_has_portal_anchor(node: &LayoutNode, depth: usize) -> bool {
442 if depth >= 256 || matches!(node.style.display, strata_style::types::Display::None) {
443 return false;
444 }
445 if node.portal_anchor.is_some() {
446 return true;
447 }
448 node.children
449 .iter()
450 .any(|c| Self::subtree_has_portal_anchor(c, depth + 1))
451 }
452
453 fn insert_anchor_key(
454 map: &mut std::collections::HashMap<String, Vec<usize>>,
455 raw_key: &str,
456 path: &[usize],
457 ) {
458 let trimmed = raw_key.trim();
459 if trimmed.is_empty() {
460 return;
461 }
462 let p = path.to_vec();
463 map.insert(trimmed.to_string(), p.clone());
464 if let Some(stripped) = trimmed.strip_prefix("--") {
465 if !stripped.is_empty() {
466 map.entry(stripped.to_string()).or_insert_with(|| p.clone());
467 }
468 } else {
469 map.entry(format!("--{}", trimmed)).or_insert(p);
470 }
471 }
472
473 fn collect_anchor_paths(
474 node: &LayoutNode,
475 current_path: &mut Vec<usize>,
476 out: &mut std::collections::HashMap<String, Vec<usize>>,
477 ) {
478 if current_path.len() >= 256
479 || matches!(node.style.display, strata_style::types::Display::None)
480 {
481 return;
482 }
483 if let Some(ref id) = node.element_id {
484 Self::insert_anchor_key(out, id, current_path);
485 }
486 if let Some(ref aname) = node.anchor_name {
487 Self::insert_anchor_key(out, aname, current_path);
488 }
489 for (idx, child) in node.children.iter().enumerate() {
490 current_path.push(idx);
491 Self::collect_anchor_paths(child, current_path, out);
492 current_path.pop();
493 }
494 }
495
496 fn collect_anchored_portal_paths(
497 node: &LayoutNode,
498 current_path: &mut Vec<usize>,
499 out: &mut Vec<Vec<usize>>,
500 ) {
501 if current_path.len() >= 256
502 || matches!(node.style.display, strata_style::types::Display::None)
503 {
504 return;
505 }
506 if node.portal_anchor.is_some() {
507 out.push(current_path.clone());
508 }
509 for (idx, child) in node.children.iter().enumerate() {
510 current_path.push(idx);
511 Self::collect_anchored_portal_paths(child, current_path, out);
512 current_path.pop();
513 }
514 }
515
516 pub fn resolve_top_layer_portals(&mut self) {
520 let has_any = Self::subtree_has_portal_anchor(&self.layout_root, 0);
521 self.has_anchored_portals = has_any;
522 if !has_any {
523 return;
524 }
525
526 let mut anchor_paths = std::collections::HashMap::new();
527 let mut path_buf = Vec::new();
528 Self::collect_anchor_paths(&self.layout_root, &mut path_buf, &mut anchor_paths);
529
530 let mut portal_paths = Vec::new();
531 path_buf.clear();
532 Self::collect_anchored_portal_paths(&self.layout_root, &mut path_buf, &mut portal_paths);
533
534 let viewport_rect =
535 strata_layout::Rect::new(0.0, 0.0, self.viewport_width, self.viewport_height);
536
537 for portal_path in portal_paths {
538 let Some((spec, cur_box)) = Self::get_layout_node(&self.layout_root, &portal_path)
539 .and_then(|n| {
540 n.portal_anchor
541 .as_deref()
542 .cloned()
543 .map(|s| (s, n.geometry.border_box))
544 })
545 else {
546 continue;
547 };
548
549 let key = spec.anchor_id.trim();
550 let anchor_path_opt = anchor_paths
551 .get(key)
552 .or_else(|| key.strip_prefix("--").and_then(|s| anchor_paths.get(s)));
553 let Some(anchor_rect) = anchor_path_opt
554 .and_then(|ap| Self::effective_screen_border_box(&self.layout_root, ap))
555 else {
556 continue;
557 };
558
559 let mut active_box = cur_box;
560 if spec.match_width && (active_box.width - anchor_rect.width).abs() > 0.5 {
561 let prior = self
562 .applied_portal_offsets
563 .remove(&portal_path)
564 .unwrap_or((0.0, 0.0));
565 if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, &portal_path)
566 {
567 if prior.0.abs() > 0.0001 || prior.1.abs() > 0.0001 {
568 target.translate(-prior.0, -prior.1);
569 }
570 target.style.width = strata_style::types::Dimension::Px(anchor_rect.width);
571 strata_layout::solve_out_of_flow_box(
572 target,
573 viewport_rect,
574 viewport_rect,
575 true,
576 );
577 active_box = target.geometry.border_box;
578 }
579 }
580
581 let (target_x, target_y, _resolved_placement) = strata_layout::solve_anchored_position(
582 anchor_rect,
583 active_box.width,
584 active_box.height,
585 spec.placement,
586 spec.offset,
587 spec.flip,
588 spec.shift,
589 spec.viewport_padding,
590 viewport_rect,
591 );
592
593 let dx = target_x - active_box.x;
594 let dy = target_y - active_box.y;
595 if dx.abs() > 0.0001 || dy.abs() > 0.0001 {
596 if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, &portal_path)
597 {
598 target.translate(dx, dy);
599 }
600 let entry = self
601 .applied_portal_offsets
602 .entry(portal_path)
603 .or_insert((0.0, 0.0));
604 entry.0 += dx;
605 entry.1 += dy;
606 }
607 }
608 }
609
610 pub(crate) fn apply_scroll_walk(
611 blueprint: &NodeBlueprint,
612 layout: &mut LayoutNode,
613 current_path: &mut Vec<usize>,
614 scroll_offsets: &std::collections::HashMap<Vec<usize>, (f32, f32)>,
615 scroll_offsets_by_id: &std::collections::HashMap<String, (f32, f32)>,
616 applied_scroll_offsets: &mut std::collections::HashMap<Vec<usize>, (f32, f32)>,
617 active_scrollbars: &mut Vec<ActiveScrollbar>,
618 ) {
619 if matches!(layout.style.display, strata_style::types::Display::None) {
620 return;
621 }
622
623 let is_scroll_y = matches!(
624 layout.style.overflow_y,
625 strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
626 );
627 let is_scroll_x = matches!(
628 layout.style.overflow_x,
629 strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
630 );
631
632 let elem_id = match blueprint {
633 NodeBlueprint::Element { attributes, .. } => attributes.iter().find_map(|a| {
634 if let strata_dom::Attribute::Property { key, value } = a {
635 if key == "id" {
636 Some(value.clone())
637 } else {
638 None
639 }
640 } else {
641 None
642 }
643 }),
644 _ => None,
645 };
646
647 if is_scroll_y || is_scroll_x {
648 let (_, _, max_scroll_x, max_scroll_y) =
649 Self::compute_container_scroll_extents(layout, 0.0, 0.0);
650
651 let (stored_x, stored_y) = if let Some(ref id) = elem_id {
652 scroll_offsets_by_id
653 .get(id)
654 .copied()
655 .or_else(|| scroll_offsets.get(current_path).copied())
656 .unwrap_or((0.0, 0.0))
657 } else {
658 scroll_offsets
659 .get(current_path)
660 .copied()
661 .unwrap_or((0.0, 0.0))
662 };
663
664 let clamped_x = stored_x.clamp(0.0, max_scroll_x);
665 let clamped_y = stored_y.clamp(0.0, max_scroll_y);
666
667 if let Some(ref id) = elem_id {
668 strata_dom::hooks::set_live_scroll_offset(id, clamped_x, clamped_y);
669 }
670
671 if clamped_x > 0.0 || clamped_y > 0.0 {
672 let target_fixed_cb = layout.style.establishes_fixed_containing_block();
673 let target_abs_cb = layout.style.position != strata_style::types::Position::Static
674 || target_fixed_cb;
675 for child in &mut layout.children {
676 child.translate_scrolled(
677 -clamped_x,
678 -clamped_y,
679 target_abs_cb,
680 target_fixed_cb,
681 );
682 }
683 for line in &mut layout.line_boxes {
684 line.bounds.x -= clamped_x;
685 line.bounds.y -= clamped_y;
686 for frag in &mut line.text_fragments {
687 frag.bounds.x -= clamped_x;
688 frag.bounds.y -= clamped_y;
689 frag.baseline_y -= clamped_y;
690 }
691 for atomic in &mut line.atomic_fragments {
692 atomic.bounds.x -= clamped_x;
693 atomic.bounds.y -= clamped_y;
694 }
695 }
696 applied_scroll_offsets.insert(current_path.clone(), (clamped_x, clamped_y));
697 }
698 }
699
700 match blueprint {
702 NodeBlueprint::Element { children, .. } => {
703 let mut flat_children = Vec::new();
704 for c in children {
705 Self::flatten_blueprints(c, &mut flat_children);
706 }
707 for (i, (&child_bp, child_layout)) in flat_children
708 .iter()
709 .zip(layout.children.iter_mut())
710 .enumerate()
711 {
712 current_path.push(i);
713 Self::apply_scroll_walk(
714 child_bp,
715 child_layout,
716 current_path,
717 scroll_offsets,
718 scroll_offsets_by_id,
719 applied_scroll_offsets,
720 active_scrollbars,
721 );
722 current_path.pop();
723 }
724 }
725 NodeBlueprint::Fragment(children) => {
726 let mut flat_children = Vec::new();
727 for c in children {
728 Self::flatten_blueprints(c, &mut flat_children);
729 }
730 for (i, (&child_bp, child_layout)) in flat_children
731 .iter()
732 .zip(layout.children.iter_mut())
733 .enumerate()
734 {
735 current_path.push(i);
736 Self::apply_scroll_walk(
737 child_bp,
738 child_layout,
739 current_path,
740 scroll_offsets,
741 scroll_offsets_by_id,
742 applied_scroll_offsets,
743 active_scrollbars,
744 );
745 current_path.pop();
746 }
747 }
748 _ => {}
749 }
750 }
751
752 #[allow(clippy::too_many_arguments)]
753 pub(crate) fn apply_scroll_xy_delta_to_container(
754 &mut self,
755 path: &[usize],
756 is_id: bool,
757 id: &str,
758 new_scroll_x: f32,
759 new_scroll_y: f32,
760 dx: f32,
761 dy: f32,
762 ) {
763 if is_id && !id.is_empty() {
764 self.scroll_offsets_by_id
765 .insert(id.to_string(), (new_scroll_x, new_scroll_y));
766 strata_dom::hooks::set_live_scroll_offset(id, new_scroll_x, new_scroll_y);
767 }
768 self.scroll_offsets
769 .insert(path.to_vec(), (new_scroll_x, new_scroll_y));
770 self.applied_scroll_offsets
771 .insert(path.to_vec(), (new_scroll_x, new_scroll_y));
772
773 let mut client_w = 0.0_f32;
774 let mut client_h = 0.0_f32;
775 let mut content_h = 0.0_f32;
776 if let Some(target) = Self::get_layout_node_mut(&mut self.layout_root, path) {
777 client_w = target.geometry.content_box.width;
778 client_h = target.geometry.content_box.height;
779 let target_fixed_cb = target.style.establishes_fixed_containing_block();
780 let target_abs_cb =
781 target.style.position != strata_style::types::Position::Static || target_fixed_cb;
782 for child in &mut target.children {
783 child.translate_scrolled(-dx, -dy, target_abs_cb, target_fixed_cb);
784 }
785 for line in &mut target.line_boxes {
786 line.bounds.x -= dx;
787 line.bounds.y -= dy;
788 for frag in &mut line.text_fragments {
789 frag.bounds.x -= dx;
790 frag.bounds.y -= dy;
791 frag.baseline_y -= dy;
792 }
793 for atomic in &mut line.atomic_fragments {
794 atomic.bounds.x -= dx;
795 atomic.bounds.y -= dy;
796 }
797 }
798 let (_, ch, _, _) =
799 Self::compute_container_scroll_extents(target, new_scroll_x, new_scroll_y);
800 content_h = ch;
801 }
802 let has_descendant_scrollbar = self
803 .active_scrollbars
804 .iter()
805 .any(|b| b.path.len() > path.len() && b.path.starts_with(path));
806 if self.has_anchored_portals {
807 self.resolve_top_layer_portals();
808 }
809 if self.has_anchored_portals || has_descendant_scrollbar {
810 self.rebuild_active_scrollbars();
811 } else {
812 for bar in &mut self.active_scrollbars {
813 let matches = if is_id && !id.is_empty() && bar.is_id {
814 bar.id == id
815 } else {
816 bar.path == path
817 };
818 if matches {
819 let clamped_y = new_scroll_y.clamp(0.0, bar.max_scroll_y);
820 bar.scroll_y = clamped_y;
821 bar.thumb_bounds.y = if bar.max_scroll_y > 0.0 && bar.available_travel > 0.0 {
822 bar.track_bounds.y + (clamped_y / bar.max_scroll_y) * bar.available_travel
823 } else {
824 bar.track_bounds.y
825 };
826 }
827 }
828 }
829 self.spatial_index.sync_bounds(&self.layout_root);
830 self.fire_scroll_event(
831 path,
832 new_scroll_x,
833 new_scroll_y,
834 dx,
835 dy,
836 client_w,
837 content_h,
838 client_w,
839 client_h,
840 );
841 }
842
843 #[allow(clippy::too_many_arguments)]
845 pub(crate) fn apply_scroll_delta_to_container(
846 &mut self,
847 path: &[usize],
848 is_id: bool,
849 id: &str,
850 new_scroll_y: f32,
851 dy: f32,
852 _max_scroll_y: f32,
853 _available_travel: f32,
854 _bounds_y: f32,
855 ) {
856 let cur_x = if is_id && !id.is_empty() {
857 self.scroll_offsets_by_id
858 .get(id)
859 .map(|(x, _)| *x)
860 .unwrap_or_else(|| self.scroll_offsets.get(path).map(|(x, _)| *x).unwrap_or(0.0))
861 } else {
862 self.scroll_offsets
863 .get(path)
864 .map(|(x, _)| *x)
865 .unwrap_or(0.0)
866 };
867 self.apply_scroll_xy_delta_to_container(path, is_id, id, cur_x, new_scroll_y, 0.0, dy);
868 }
869
870 pub(crate) fn fire_scroll_event(
871 &self,
872 container_path: &[usize],
873 scroll_x: f32,
874 scroll_y: f32,
875 delta_x: f32,
876 delta_y: f32,
877 content_w: f32,
878 content_h: f32,
879 client_w: f32,
880 client_h: f32,
881 ) -> bool {
882 if let Some((handler, target_box, _)) = Self::find_event_at_or_above_path(
883 &self.root_blueprint,
884 &self.layout_root,
885 container_path,
886 strata_dom::EventType::Scroll,
887 ) {
888 let mut ev = strata_dom::Event::new(strata_dom::EventType::Scroll);
889 ev.scroll_left = scroll_x as f64;
890 ev.scroll_top = scroll_y as f64;
891 ev.scroll_width = content_w as f64;
892 ev.scroll_height = content_h as f64;
893 ev.client_width = client_w as f64;
894 ev.client_height = client_h as f64;
895 ev.delta_x = delta_x as f64;
896 ev.delta_y = delta_y as f64;
897 ev.width = target_box.width as f64;
898 ev.height = target_box.height as f64;
899 ev.value = format!("{:.1}", scroll_y);
900 handler(ev);
901 return true;
902 }
903 false
904 }
905
906 fn blueprint_has_wheel_listener(bp: &NodeBlueprint) -> bool {
907 match bp {
908 NodeBlueprint::Element {
909 attributes,
910 children,
911 ..
912 } => {
913 attributes.iter().any(|a| {
914 matches!(
915 a,
916 strata_dom::Attribute::EventListener {
917 event: strata_dom::EventType::Wheel,
918 ..
919 }
920 )
921 }) || children.iter().any(Self::blueprint_has_wheel_listener)
922 }
923 NodeBlueprint::Fragment(children) => {
924 children.iter().any(Self::blueprint_has_wheel_listener)
925 }
926 _ => false,
927 }
928 }
929
930 fn dispatch_dom_wheel_event(
931 &mut self,
932 px: f32,
933 py: f32,
934 delta_x: f32,
935 delta_y: f32,
936 ) -> (bool, bool) {
937 if !Self::blueprint_has_wheel_listener(&self.root_blueprint) {
938 return (false, false);
939 }
940 if let Some((handler, target_box)) = Self::hit_test_event_with_box(
941 &self.root_blueprint,
942 &self.layout_root,
943 px,
944 py,
945 strata_dom::EventType::Wheel,
946 ) {
947 let mut ev = self.create_mouse_event(
948 strata_dom::EventType::Wheel,
949 px,
950 py,
951 0,
952 0,
953 Some(target_box),
954 );
955 ev.delta_x = delta_x as f64;
956 ev.delta_y = delta_y as f64;
957 let prevented_cell = ev.default_prevented.clone();
958 handler(ev);
959 return (true, prevented_cell.get());
960 }
961 (false, false)
962 }
963
964 pub fn dispatch_scroll(&mut self, px: f32, py: f32, delta_x: f32, delta_y: f32) -> bool {
968 self.last_mouse_pos = (px, py);
969 self.active_smooth_scroll = None;
970
971 let (wheel_handled, default_prevented) =
972 self.dispatch_dom_wheel_event(px, py, delta_x, delta_y);
973 if default_prevented {
974 return wheel_handled;
975 }
976
977 let matching_bars = self.matching_scrollbars_at(px, py);
978
979 for bar in matching_bars.into_iter().rev() {
980 if bar.max_scroll_y <= 0.0 {
981 continue;
982 }
983
984 let cur_y = if bar.is_id {
985 self.scroll_offsets_by_id
986 .get(&bar.id)
987 .copied()
988 .or_else(|| self.scroll_offsets.get(&bar.path).copied())
989 .map(|(_, y)| y)
990 .unwrap_or(bar.scroll_y)
991 } else {
992 self.scroll_offsets
993 .get(&bar.path)
994 .copied()
995 .map(|(_, y)| y)
996 .unwrap_or(bar.scroll_y)
997 };
998
999 let candidate_y = (cur_y + delta_y).clamp(0.0, bar.max_scroll_y);
1000 let dy = candidate_y - cur_y;
1001 if dy.abs() > 0.01 {
1002 self.last_scroll_interaction = Some(std::time::Instant::now());
1003 self.apply_scroll_delta_to_container(
1004 &bar.path,
1005 bar.is_id,
1006 &bar.id,
1007 candidate_y,
1008 dy,
1009 bar.max_scroll_y,
1010 bar.available_travel,
1011 bar.bounds.y,
1012 );
1013 return true;
1014 }
1015 }
1016
1017 if delta_x.abs() >= 0.01 && self.dispatch_horizontal_wheel_at(px, py, delta_x) {
1018 return true;
1019 }
1020
1021 wheel_handled
1022 }
1023
1024 fn collect_horizontal_scroll_paths_at(
1025 blueprint: &NodeBlueprint,
1026 layout: &LayoutNode,
1027 px: f32,
1028 py: f32,
1029 current_path: &mut Vec<usize>,
1030 inherited_steps: &[super::hit_test::HitClipStep],
1031 in_top_layer: bool,
1032 out: &mut Vec<(Vec<usize>, Option<String>, f32, f32, bool)>,
1033 ) {
1034 if current_path.len() >= 256
1035 || matches!(layout.style.display, strata_style::types::Display::None)
1036 {
1037 return;
1038 }
1039 let node_in_top_layer = in_top_layer || layout.is_top_layer;
1040 let eff_inherited = if layout.is_top_layer {
1041 &[][..]
1042 } else {
1043 Self::effective_hit_clip_steps(layout, inherited_steps)
1044 };
1045 let is_scroll_x = matches!(
1046 layout.style.overflow_x,
1047 strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
1048 );
1049 if is_scroll_x
1050 && layout.geometry.border_box.contains_point(px, py)
1051 && Self::hit_clip_steps_allow(eff_inherited, px, py)
1052 {
1053 let elem_id = layout.element_id.clone().or_else(|| {
1054 if let NodeBlueprint::Element { attributes, .. } = blueprint {
1055 attributes.iter().find_map(|a| {
1056 if let strata_dom::Attribute::Property { key, value } = a {
1057 if key == "id" {
1058 Some(value.clone())
1059 } else {
1060 None
1061 }
1062 } else {
1063 None
1064 }
1065 })
1066 } else {
1067 None
1068 }
1069 });
1070 out.push((
1071 current_path.clone(),
1072 elem_id,
1073 0.0,
1074 0.0,
1075 node_in_top_layer,
1076 ));
1077 }
1078
1079 let mut next_steps = Vec::with_capacity(eff_inherited.len() + 1);
1080 next_steps.extend_from_slice(eff_inherited);
1081 let own_step = Self::hit_clip_step_for(layout);
1082 if own_step.clip.is_some() || own_step.is_abs_cb || own_step.is_fixed_cb {
1083 next_steps.push(own_step);
1084 }
1085
1086 for (i, child_bp, child_layout) in Self::paired_blueprint_children(blueprint, layout) {
1087 current_path.push(i);
1088 Self::collect_horizontal_scroll_paths_at(
1089 child_bp,
1090 child_layout,
1091 px,
1092 py,
1093 current_path,
1094 &next_steps,
1095 node_in_top_layer,
1096 out,
1097 );
1098 current_path.pop();
1099 }
1100 }
1101
1102 fn dispatch_horizontal_wheel_at(&mut self, px: f32, py: f32, delta_x: f32) -> bool {
1103 let mut hits = Vec::new();
1104 let mut path_buf = Vec::new();
1105 Self::collect_horizontal_scroll_paths_at(
1106 &self.root_blueprint,
1107 &self.layout_root,
1108 px,
1109 py,
1110 &mut path_buf,
1111 &[],
1112 false,
1113 &mut hits,
1114 );
1115 hits.sort_by_key(|h| h.4);
1116 for (path, elem_id, _, _, _) in hits.into_iter().rev() {
1117 let (cur_x, cur_y) = if let Some(ref id) = elem_id {
1118 self.scroll_offsets_by_id
1119 .get(id)
1120 .copied()
1121 .or_else(|| self.scroll_offsets.get(&path).copied())
1122 .unwrap_or((0.0, 0.0))
1123 } else {
1124 self.scroll_offsets.get(&path).copied().unwrap_or((0.0, 0.0))
1125 };
1126 let (applied_x, applied_y) = self
1127 .applied_scroll_offsets
1128 .get(&path)
1129 .copied()
1130 .unwrap_or((0.0, 0.0));
1131 let Some(node) = Self::get_layout_node(&self.layout_root, &path) else {
1132 continue;
1133 };
1134 let (_, _, max_scroll_x, _) =
1135 Self::compute_container_scroll_extents(node, applied_x, applied_y);
1136 if max_scroll_x <= 0.0 {
1137 continue;
1138 }
1139 let target_x = (cur_x + delta_x).clamp(0.0, max_scroll_x);
1140 let dx = target_x - applied_x;
1141 if dx.abs() > 0.01 {
1142 self.last_scroll_interaction = Some(std::time::Instant::now());
1143 let is_id = elem_id.is_some();
1144 let id_str = elem_id.unwrap_or_default();
1145 self.apply_scroll_xy_delta_to_container(
1146 &path,
1147 is_id,
1148 &id_str,
1149 target_x,
1150 cur_y,
1151 dx,
1152 0.0,
1153 );
1154 return true;
1155 }
1156 }
1157 false
1158 }
1159
1160 pub fn dispatch_smooth_scroll_action(
1165 &mut self,
1166 px: f32,
1167 py: f32,
1168 delta_x: f32,
1169 delta_y: f32,
1170 ) -> (bool, bool) {
1171 self.last_mouse_pos = (px, py);
1172 if delta_y.abs() < 0.01 && delta_x.abs() < 0.01 {
1173 return (false, false);
1174 }
1175
1176 let (wheel_handled, default_prevented) =
1177 self.dispatch_dom_wheel_event(px, py, delta_x, delta_y);
1178 if default_prevented {
1179 return (wheel_handled, false);
1180 }
1181 if delta_y.abs() < 0.01 {
1182 if delta_x.abs() >= 0.01 && self.dispatch_horizontal_wheel_at(px, py, delta_x) {
1183 return (wheel_handled, true);
1184 }
1185 return (wheel_handled, false);
1186 }
1187
1188 let matching_bars = self.matching_scrollbars_at(px, py);
1189 if matching_bars.is_empty() && delta_x.abs() >= 0.01 {
1190 let horiz_changed = self.dispatch_horizontal_wheel_at(px, py, delta_x);
1191 return (wheel_handled, horiz_changed);
1192 }
1193
1194 let target_bar = matching_bars
1198 .iter()
1199 .rev()
1200 .find(|b| {
1201 if b.max_scroll_y <= 0.0 {
1202 return false;
1203 }
1204 let cur_y = if b.is_id {
1205 self.scroll_offsets_by_id
1206 .get(&b.id)
1207 .copied()
1208 .or_else(|| self.scroll_offsets.get(&b.path).copied())
1209 .map(|(_, y)| y)
1210 .unwrap_or(b.scroll_y)
1211 } else {
1212 self.scroll_offsets
1213 .get(&b.path)
1214 .copied()
1215 .map(|(_, y)| y)
1216 .unwrap_or(b.scroll_y)
1217 };
1218 if delta_y < 0.0 {
1219 cur_y > 0.01
1220 } else {
1221 cur_y < b.max_scroll_y - 0.01
1222 }
1223 })
1224 .cloned()
1225 .or_else(|| matching_bars.iter().find(|b| b.max_scroll_y > 0.0).cloned());
1226
1227 let Some(bar) = target_bar else {
1228 return (wheel_handled, false);
1229 };
1230
1231 let now = std::time::Instant::now();
1232 self.last_scroll_interaction = Some(now);
1233
1234 let cur_y = if bar.is_id {
1235 self.scroll_offsets_by_id
1236 .get(&bar.id)
1237 .copied()
1238 .or_else(|| self.scroll_offsets.get(&bar.path).copied())
1239 .map(|(_, y)| y)
1240 .unwrap_or(bar.scroll_y)
1241 } else {
1242 self.scroll_offsets
1243 .get(&bar.path)
1244 .copied()
1245 .map(|(_, y)| y)
1246 .unwrap_or(bar.scroll_y)
1247 };
1248
1249 if self
1250 .active_smooth_scroll
1251 .as_ref()
1252 .is_some_and(|t| t.container_path == bar.path)
1253 {
1254 if let Some(mut tracker) = self.active_smooth_scroll.take() {
1255 let dt_flick = now.duration_since(tracker.last_event_time).as_secs_f32();
1256 let accel = if dt_flick < 0.20 {
1257 (1.0 + (0.12 / dt_flick.max(0.01)).min(2.5)).min(3.5)
1258 } else {
1259 1.0
1260 };
1261
1262 let t_prev = now.duration_since(tracker.start_time).as_secs_f32();
1263 let omega = tracker.omega;
1264 let e0 = tracker.start_y - tracker.target_y;
1265 let c2 = tracker.initial_velocity + omega * e0;
1266 let decay = (-omega * t_prev).exp();
1267 let y_now =
1268 (tracker.target_y + (e0 + c2 * t_prev) * decay).clamp(0.0, bar.max_scroll_y);
1269 let v_now = (tracker.initial_velocity - omega * c2 * t_prev) * decay;
1270
1271 let catchup_dy = y_now - tracker.current_y;
1272 if catchup_dy.abs() > 0.001 {
1273 self.apply_scroll_delta_to_container(
1274 &tracker.container_path,
1275 tracker.is_id,
1276 &tracker.container_id,
1277 y_now,
1278 catchup_dy,
1279 bar.max_scroll_y,
1280 bar.available_travel,
1281 bar.bounds.y,
1282 );
1283 tracker.current_y = y_now;
1284 }
1285
1286 let impulse = delta_y * accel;
1287 let new_target = (tracker.target_y + impulse).clamp(0.0, bar.max_scroll_y);
1288
1289 tracker.start_y = y_now;
1290 tracker.initial_velocity = v_now;
1291 tracker.target_y = new_target;
1292 tracker.start_time = now;
1293 tracker.last_event_time = now;
1294 tracker.max_scroll_y = bar.max_scroll_y;
1295 tracker.available_travel = bar.available_travel;
1296 tracker.bounds_y = bar.bounds.y;
1297 self.active_smooth_scroll = Some(tracker);
1298 return (wheel_handled, true);
1299 }
1300 }
1301
1302 let new_target = (cur_y + delta_y).clamp(0.0, bar.max_scroll_y);
1303 self.active_smooth_scroll = Some(SmoothScrollTracker {
1304 container_path: bar.path,
1305 container_id: bar.id,
1306 is_id: bar.is_id,
1307 max_scroll_y: bar.max_scroll_y,
1308 available_travel: bar.available_travel,
1309 bounds_y: bar.bounds.y,
1310 current_y: cur_y,
1311 target_y: new_target,
1312 start_y: cur_y,
1313 initial_velocity: 0.0,
1314 start_time: now,
1315 last_event_time: now,
1316 omega: 18.0,
1317 });
1318
1319 (wheel_handled, true)
1320 }
1321
1322 pub fn dispatch_smooth_scroll(&mut self, px: f32, py: f32, delta_x: f32, delta_y: f32) -> bool {
1325 let (wheel_handled, scroll_changed) =
1326 self.dispatch_smooth_scroll_action(px, py, delta_x, delta_y);
1327 wheel_handled || scroll_changed
1328 }
1329
1330 pub fn poll_smooth_scroll_at(&mut self, now: std::time::Instant) -> bool {
1333 let Some(mut tracker) = self.active_smooth_scroll.take() else {
1334 return false;
1335 };
1336
1337 let t = now.duration_since(tracker.start_time).as_secs_f32();
1338 let omega = tracker.omega;
1339 let e0 = tracker.start_y - tracker.target_y;
1340 let c2 = tracker.initial_velocity + omega * e0;
1341 let decay = (-omega * t).exp();
1342
1343 let raw_y = tracker.target_y + (e0 + c2 * t) * decay;
1344 let clamped_y = raw_y.clamp(0.0, tracker.max_scroll_y);
1345 let vel = (tracker.initial_velocity - omega * c2 * t) * decay;
1346
1347 let is_settled =
1348 t >= 0.40 || ((clamped_y - tracker.target_y).abs() < 0.25 && vel.abs() < 1.0);
1349 let new_y = if is_settled {
1350 tracker.target_y
1351 } else {
1352 clamped_y
1353 };
1354
1355 let dy = new_y - tracker.current_y;
1356 let mut redraw = false;
1357
1358 if dy.abs() > 0.001 {
1359 self.apply_scroll_delta_to_container(
1360 &tracker.container_path,
1361 tracker.is_id,
1362 &tracker.container_id,
1363 new_y,
1364 dy,
1365 tracker.max_scroll_y,
1366 tracker.available_travel,
1367 tracker.bounds_y,
1368 );
1369 tracker.current_y = new_y;
1370 redraw = true;
1371 }
1372
1373 if !is_settled {
1374 self.active_smooth_scroll = Some(tracker);
1375 redraw = true;
1376 }
1377
1378 redraw
1379 }
1380
1381 #[inline]
1383 pub fn poll_smooth_scroll(&mut self) -> bool {
1384 self.poll_smooth_scroll_at(std::time::Instant::now())
1385 }
1386
1387 pub fn scroll_to_top(&mut self, px: f32, py: f32) -> bool {
1389 self.active_smooth_scroll = None;
1390 let matching_bars = self.matching_scrollbars_at(px, py);
1391
1392 if let Some(bar) = matching_bars.into_iter().next_back() {
1393 let cur_y = bar.scroll_y;
1394 let dy = 0.0 - cur_y;
1395 if dy.abs() > 0.01 {
1396 self.last_scroll_interaction = Some(std::time::Instant::now());
1397 self.apply_scroll_delta_to_container(
1398 &bar.path,
1399 bar.is_id,
1400 &bar.id,
1401 0.0,
1402 dy,
1403 bar.max_scroll_y,
1404 bar.available_travel,
1405 bar.bounds.y,
1406 );
1407 return true;
1408 }
1409 }
1410 false
1411 }
1412
1413 pub fn scroll_to_bottom(&mut self, px: f32, py: f32) -> bool {
1415 self.active_smooth_scroll = None;
1416 let matching_bars = self.matching_scrollbars_at(px, py);
1417
1418 if let Some(bar) = matching_bars.into_iter().next_back() {
1419 if bar.max_scroll_y > 0.0 {
1420 let cur_y = bar.scroll_y;
1421 let dy = bar.max_scroll_y - cur_y;
1422 if dy.abs() > 0.01 {
1423 self.last_scroll_interaction = Some(std::time::Instant::now());
1424 self.apply_scroll_delta_to_container(
1425 &bar.path,
1426 bar.is_id,
1427 &bar.id,
1428 bar.max_scroll_y,
1429 dy,
1430 bar.max_scroll_y,
1431 bar.available_travel,
1432 bar.bounds.y,
1433 );
1434 return true;
1435 }
1436 }
1437 }
1438 false
1439 }
1440
1441 pub fn scroll_offset_by_id(&self, id: &str) -> (f32, f32) {
1443 if let Some(off) = self.scroll_offsets_by_id.get(id) {
1444 return *off;
1445 }
1446 if let Some(bar) = self
1447 .active_scrollbars
1448 .iter()
1449 .find(|b| b.is_id && b.id == id)
1450 {
1451 return (0.0, bar.scroll_y);
1452 }
1453 strata_dom::get_scroll_offset(id)
1454 }
1455
1456 pub fn scroll_to_by_id(&mut self, id: &str, scroll_x: f32, scroll_y: f32) -> bool {
1459 self.active_smooth_scroll = None;
1460 let target_path = if id.is_empty() {
1461 self.active_scrollbars
1462 .iter()
1463 .max_by(|a, b| {
1464 (a.bounds.width * a.bounds.height)
1465 .partial_cmp(&(b.bounds.width * b.bounds.height))
1466 .unwrap_or(std::cmp::Ordering::Equal)
1467 })
1468 .map(|b| b.path.clone())
1469 } else {
1470 self.active_scrollbars
1471 .iter()
1472 .find(|b| b.is_id && b.id == id)
1473 .map(|b| b.path.clone())
1474 .or_else(|| {
1475 let mut buf = Vec::new();
1476 Self::find_element_path_by_id(&self.root_blueprint, &self.layout_root, id, &mut buf)
1477 })
1478 };
1479
1480 if let Some(path) = target_path {
1481 let (applied_x, applied_y) = self
1482 .applied_scroll_offsets
1483 .get(&path)
1484 .copied()
1485 .unwrap_or((0.0, 0.0));
1486 if let Some(node) = Self::get_layout_node(&self.layout_root, &path) {
1487 let is_scroll_x = matches!(
1488 node.style.overflow_x,
1489 strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
1490 );
1491 let is_scroll_y = matches!(
1492 node.style.overflow_y,
1493 strata_style::types::Overflow::Auto | strata_style::types::Overflow::Scroll
1494 );
1495 if is_scroll_x || is_scroll_y {
1496 let (_, _, max_scroll_x, max_scroll_y) =
1497 Self::compute_container_scroll_extents(node, applied_x, applied_y);
1498 let clamped_x = if is_scroll_x {
1499 scroll_x.clamp(0.0, max_scroll_x)
1500 } else {
1501 0.0
1502 };
1503 let clamped_y = if is_scroll_y {
1504 scroll_y.clamp(0.0, max_scroll_y)
1505 } else {
1506 0.0
1507 };
1508 let dx = clamped_x - applied_x;
1509 let dy = clamped_y - applied_y;
1510 let is_id = !id.is_empty();
1511 if is_id {
1512 self.scroll_offsets_by_id
1513 .insert(id.to_string(), (clamped_x, clamped_y));
1514 strata_dom::hooks::set_live_scroll_offset(id, clamped_x, clamped_y);
1515 }
1516 if dx.abs() > 0.01 || dy.abs() > 0.01 {
1517 self.last_scroll_interaction = Some(std::time::Instant::now());
1518 self.apply_scroll_xy_delta_to_container(
1519 &path,
1520 is_id,
1521 id,
1522 clamped_x,
1523 clamped_y,
1524 dx,
1525 dy,
1526 );
1527 return true;
1528 }
1529 return false;
1530 }
1531 }
1532 }
1533
1534 if !id.is_empty() {
1535 let clamped_x = scroll_x.max(0.0);
1536 let clamped_y = scroll_y.max(0.0);
1537 self.scroll_offsets_by_id
1538 .insert(id.to_string(), (clamped_x, clamped_y));
1539 strata_dom::hooks::set_live_scroll_offset(id, clamped_x, clamped_y);
1540 }
1541 false
1542 }
1543
1544 pub fn scroll_to_top_by_id(&mut self, id: &str) -> bool {
1546 if id.is_empty() {
1547 let (px, py) = self.last_mouse_pos;
1548 return self.scroll_to_top(px, py);
1549 }
1550 self.scroll_to_by_id(id, 0.0, 0.0)
1551 }
1552
1553 pub fn scroll_to_bottom_by_id(&mut self, id: &str) -> bool {
1555 if id.is_empty() {
1556 let (px, py) = self.last_mouse_pos;
1557 return self.scroll_to_bottom(px, py);
1558 }
1559 if let Some(bar) = self
1560 .active_scrollbars
1561 .iter()
1562 .find(|b| b.is_id && b.id == id)
1563 .cloned()
1564 {
1565 return self.scroll_to_by_id(id, 0.0, bar.max_scroll_y);
1566 }
1567 false
1568 }
1569
1570 pub(crate) fn find_element_path_by_id(
1571 blueprint: &NodeBlueprint,
1572 layout: &LayoutNode,
1573 target_id: &str,
1574 current_path: &mut Vec<usize>,
1575 ) -> Option<Vec<usize>> {
1576 if layout.element_id.as_deref() == Some(target_id) {
1577 return Some(current_path.clone());
1578 }
1579 if let NodeBlueprint::Element { attributes, .. } = blueprint {
1580 for attr in attributes {
1581 if let strata_dom::Attribute::Property { key, value } = attr {
1582 if key == "id" && value == target_id {
1583 return Some(current_path.clone());
1584 }
1585 }
1586 }
1587 }
1588 for (idx, child_bp, child_layout) in Self::paired_blueprint_children(blueprint, layout) {
1589 current_path.push(idx);
1590 if let Some(found) =
1591 Self::find_element_path_by_id(child_bp, child_layout, target_id, current_path)
1592 {
1593 return Some(found);
1594 }
1595 current_path.pop();
1596 }
1597 None
1598 }
1599
1600 pub fn scroll_into_view(&mut self, target_id: &str) -> bool {
1602 if target_id.is_empty() {
1603 return false;
1604 }
1605 let mut path_buf = Vec::new();
1606 let Some(target_path) = Self::find_element_path_by_id(
1607 &self.root_blueprint,
1608 &self.layout_root,
1609 target_id,
1610 &mut path_buf,
1611 ) else {
1612 return false;
1613 };
1614
1615 let Some(target_box) =
1616 Self::get_layout_node(&self.layout_root, &target_path).map(|n| n.geometry.border_box)
1617 else {
1618 return false;
1619 };
1620
1621 let ancestor_bar = self
1623 .active_scrollbars
1624 .iter()
1625 .filter(|b| target_path.len() > b.path.len() && target_path.starts_with(&b.path))
1626 .max_by_key(|b| b.path.len())
1627 .cloned();
1628
1629 let Some(bar) = ancestor_bar else {
1630 return false;
1631 };
1632
1633 let container_box = Self::get_layout_node(&self.layout_root, &bar.path)
1634 .map(|n| n.geometry.content_box)
1635 .unwrap_or(bar.bounds);
1636
1637 let cur_y = bar.scroll_y;
1638 let new_y = if target_box.y < container_box.y {
1639 let dy = target_box.y - container_box.y;
1640 (cur_y + dy).clamp(0.0, bar.max_scroll_y)
1641 } else if target_box.y + target_box.height > container_box.y + container_box.height {
1642 let dy = (target_box.y + target_box.height) - (container_box.y + container_box.height);
1643 (cur_y + dy).clamp(0.0, bar.max_scroll_y)
1644 } else {
1645 cur_y
1646 };
1647
1648 let dy = new_y - cur_y;
1649 if dy.abs() > 0.01 {
1650 self.active_smooth_scroll = None;
1651 self.last_scroll_interaction = Some(std::time::Instant::now());
1652 self.apply_scroll_delta_to_container(
1653 &bar.path,
1654 bar.is_id,
1655 &bar.id,
1656 new_y,
1657 dy,
1658 bar.max_scroll_y,
1659 bar.available_travel,
1660 bar.bounds.y,
1661 );
1662 return true;
1663 }
1664 false
1665 }
1666
1667 pub fn flush_pending_scroll_commands(&mut self) -> bool {
1670 if !strata_dom::hooks::has_pending_scroll_commands() {
1671 return false;
1672 }
1673 let cmds = strata_dom::hooks::take_pending_scroll_commands();
1674 let mut any_changed = false;
1675 for cmd in cmds {
1676 match cmd {
1677 strata_dom::ProgrammaticScrollCommand::ScrollTo { id, x, y } => {
1678 if self.scroll_to_by_id(&id, x, y) {
1679 any_changed = true;
1680 }
1681 }
1682 strata_dom::ProgrammaticScrollCommand::ScrollToTop { id } => {
1683 if self.scroll_to_top_by_id(&id) {
1684 any_changed = true;
1685 }
1686 }
1687 strata_dom::ProgrammaticScrollCommand::ScrollToBottom { id } => {
1688 if self.scroll_to_bottom_by_id(&id) {
1689 any_changed = true;
1690 }
1691 }
1692 strata_dom::ProgrammaticScrollCommand::ScrollIntoView { target_id } => {
1693 if self.scroll_into_view(&target_id) {
1694 any_changed = true;
1695 }
1696 }
1697 }
1698 }
1699 any_changed
1700 }
1701}