Skip to content

Truly independent web browser

LibWeb: Read an image's x and y from its box's spatial chain

Aliaksandr Kalenike3722c5906a8
diff --git a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp
index fe111ba1f63..d05e67cddbd 100644
--- a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp
+++ b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.cpp
@@ -197,14 +197,6 @@ Gfx::FloatRect AccumulatedVisualContextTree::transform_rect_to_viewport(SpatialN
return rect;
}
-Gfx::FloatPoint AccumulatedVisualContextTree::cumulative_scroll_chain_offset(SpatialNodeIndex index, ScrollStateSnapshot const& scroll_state) const
-{
- auto scroll_offsets = scroll_state.device_offsets();
- Gfx::FloatPoint offset;
- Compositing::RustFFI::visual_context_tree_cumulative_scroll_chain_offset(m_rust_tree, index, scroll_offsets.data(), scroll_offsets.size(), &offset);
- return offset;
-}
-
Gfx::FloatMatrix4x4 AccumulatedVisualContextTree::accumulated_matrix(SpatialNodeIndex index, ScrollStateSnapshot const& scroll_state, IncludeVisualViewportTransform include_visual_viewport_transform) const
{
auto scroll_offsets = scroll_state.device_offsets();
diff --git a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h
index a35efb270fe..a618d1f2aba 100644
--- a/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h
+++ b/Libraries/LibCompositing/DisplayList/AccumulatedVisualContext.h
@@ -91,7 +91,6 @@ public:
Gfx::FloatPoint inverse_transform_point(SpatialNodeIndex, Gfx::FloatPoint) const;
Gfx::FloatRect transform_rect_to_viewport(SpatialNodeIndex, Gfx::FloatRect const&, ScrollStateSnapshot const&, IncludeVisualViewportTransform = IncludeVisualViewportTransform::Yes) const;
// Sum of the snapshot entries along the scroll-parent chain from the given scroll-like node.
- Gfx::FloatPoint cumulative_scroll_chain_offset(SpatialNodeIndex, ScrollStateSnapshot const&) const;
Gfx::FloatMatrix4x4 accumulated_matrix(SpatialNodeIndex, ScrollStateSnapshot const&, IncludeVisualViewportTransform) const;
void for_each_effects_filter_image_frame_id(Function<void(u64)> const&) const;
diff --git a/Libraries/LibCompositing/Rust/src/ffi.rs b/Libraries/LibCompositing/Rust/src/ffi.rs
index 5566b3a162e..a6606159adc 100644
--- a/Libraries/LibCompositing/Rust/src/ffi.rs
+++ b/Libraries/LibCompositing/Rust/src/ffi.rs
@@ -383,23 +383,6 @@ pub unsafe extern "C" fn visual_context_tree_transform_rect_to_viewport(
);
}
-/// # Safety
-///
-/// `tree` must be a live retained tree handle; `scroll_offsets` must address `scroll_offsets_len` points.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn visual_context_tree_cumulative_scroll_chain_offset(
- tree: *const c_void,
- spatial: SpatialNodeIndex,
- scroll_offsets: *const libgfx_rust::FloatPoint,
- scroll_offsets_len: usize,
- out: &mut libgfx_rust::FloatPoint,
-) {
- let tree = unsafe { tree_from_handle(tree) };
- // SAFETY: The caller guarantees the offsets address `scroll_offsets_len` points.
- let scroll_offsets = unsafe { ak::slice_from_raw_parts(scroll_offsets, scroll_offsets_len) };
- *out = tree.cumulative_scroll_chain_offset(spatial, scroll_offsets);
-}
-
/// # Safety
///
/// `tree` must be a live retained tree handle; `scroll_offsets` must address `scroll_offsets_len` points.
diff --git a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs b/Libraries/LibCompositing/Rust/src/visual_context/queries.rs
index c9a6b236baa..577d50b4d12 100644
--- a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs
+++ b/Libraries/LibCompositing/Rust/src/visual_context/queries.rs
@@ -555,35 +555,28 @@ impl VisualContextTree {
rect
}
- pub fn cumulative_scroll_chain_offset(&self, index: SpatialNodeIndex, scroll_offsets: &[FloatPoint]) -> FloatPoint {
- let nearest_scroll_like_ancestor = |from: SpatialNodeIndex| -> Option<SpatialNodeIndex> {
- let mut current = from;
- while current != VISUAL_VIEWPORT_NODE_INDEX {
- current = self.spatial_nodes[current.0 as usize].parent;
- if current == VISUAL_VIEWPORT_NODE_INDEX {
- return None;
- }
- if self.spatial_nodes[current.0 as usize].data.is_scroll_like() {
- return Some(current);
- }
- }
- None
- };
-
+ /// How far the nodes on the spatial chain from `index` up to the viewport move a box when its transforms are left
+ /// out, in device pixels.
+ pub fn offset_to_viewport_ignoring_transforms(
+ &self,
+ index: SpatialNodeIndex,
+ scroll_offsets: &[FloatPoint],
+ ) -> FloatPoint {
let mut offset = FloatPoint::default();
- let mut current = Some(index);
- while let Some(node_index) = current
- && node_index != VISUAL_VIEWPORT_NODE_INDEX
- {
- let entry = device_offset_for_index(scroll_offsets, node_index);
- offset = FloatPoint {
- x: offset.x + entry.x,
- y: offset.y + entry.y,
- };
- current = match &self.spatial_nodes[node_index.0 as usize].data {
- SpatialData::Sticky(sticky) => Some(sticky.parent_sticky.unwrap_or(sticky.scroller)),
- _ => nearest_scroll_like_ancestor(node_index),
+ let mut current = index;
+ while current != VISUAL_VIEWPORT_NODE_INDEX {
+ let node = &self.spatial_nodes[current.0 as usize];
+ let node_offset = match &node.data {
+ SpatialData::Scroll(_) | SpatialData::Sticky(_) => device_offset_for_index(scroll_offsets, current),
+ SpatialData::AnchorScrollShift(shift) => shift.masked_offset(scroll_offsets),
+ SpatialData::Transform(_)
+ | SpatialData::Perspective(_)
+ | SpatialData::BackfaceVisibility(_)
+ | SpatialData::Dead => FloatPoint::default(),
};
+ offset.x += node_offset.x;
+ offset.y += node_offset.y;
+ current = node.parent;
}
offset
}
@@ -1430,44 +1423,6 @@ mod tests {
);
}
- #[test]
- fn the_cumulative_scroll_chain_offset_sums_entries_up_the_scroll_parent_chain() {
- let mut tree = identity_tree();
- let outer_scroll = tree.append_spatial(scroll(), VISUAL_VIEWPORT_NODE_INDEX);
- let transformed = tree.append_spatial(
- SpatialData::Transform(transform_data(FloatMatrix4x4::identity(), FloatPoint::default())),
- outer_scroll,
- );
- let inner_scroll = tree.append_spatial(scroll(), transformed);
- let sticky = tree.append_spatial(
- SpatialData::Sticky(StickyData::unconstrained(
- inner_scroll,
- None,
- NO_SCROLL_STATE_SLOT,
- NodeSlotId::INVALID,
- inner_scroll,
- )),
- inner_scroll,
- );
- let mut scroll_offsets = vec![FloatPoint::default(); 5];
- scroll_offsets[outer_scroll.0 as usize] = point(0.0, -100.0);
- scroll_offsets[inner_scroll.0 as usize] = point(0.0, -30.0);
- scroll_offsets[sticky.0 as usize] = point(0.0, 5.0);
-
- assert_eq!(
- tree.cumulative_scroll_chain_offset(sticky, &scroll_offsets),
- point(0.0, -125.0)
- );
- assert_eq!(
- tree.cumulative_scroll_chain_offset(inner_scroll, &scroll_offsets),
- point(0.0, -130.0)
- );
- assert_eq!(
- tree.cumulative_scroll_chain_offset(VISUAL_VIEWPORT_NODE_INDEX, &scroll_offsets),
- FloatPoint::default()
- );
- }
-
#[test]
fn sticky_offsets_resolve_from_the_scroller_entry_and_the_parent_sticky_chain() {
let mut tree = identity_tree();
diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.cpp b/Libraries/LibWeb/HTML/HTMLImageElement.cpp
index 4fe26ac640b..60bd6c89f57 100644
--- a/Libraries/LibWeb/HTML/HTMLImageElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLImageElement.cpp
@@ -589,6 +589,17 @@ unsigned HTMLImageElement::natural_height() const
return density_corrected_natural_width_and_height().height().to_int();
}
+// INTEROP: Scrolling the document moves the result like scrolling any other scroll container does, rather than leaving
+// it relative to the initial containing block origin.
+static CSSPixelPoint first_border_box_origin_ignoring_transforms(Layout::Node const& layout_node)
+{
+ auto& document = const_cast<DOM::Document&>(layout_node.document());
+ document.update_paint_and_hit_testing_properties_if_needed();
+ auto visual_context_tree = document.visual_context_tree();
+ auto offset = Painting::offset_to_viewport_ignoring_transforms(layout_node, Painting::rect_to_viewport_transform(document, visual_context_tree));
+ return Painting::absolute_border_box_rect(layout_node).location().translated(offset);
+}
+
// https://drafts.csswg.org/cssom-view/#dom-htmlimageelement-x
int HTMLImageElement::x() const
{
@@ -602,11 +613,7 @@ int HTMLImageElement::x() const
if (!layout_node || !Painting::has_committed_box(*layout_node))
return 0;
- // Scroll frames are created together with the visual context tree at the lazy resolution point,
- // so resolve it before reading the enclosing scroll node below.
- const_cast<DOM::Document&>(document()).update_paint_and_hit_testing_properties_if_needed();
-
- return (Painting::absolute_border_box_rect(*layout_node).x() - Painting::cumulative_scroll_compensation(*layout_node).x()).to_int();
+ return first_border_box_origin_ignoring_transforms(*layout_node).x().to_int();
}
// https://drafts.csswg.org/cssom-view/#dom-htmlimageelement-y
@@ -622,11 +629,7 @@ int HTMLImageElement::y() const
if (!layout_node || !Painting::has_committed_box(*layout_node))
return 0;
- // Scroll frames are created together with the visual context tree at the lazy resolution point,
- // so resolve it before reading the enclosing scroll node below.
- const_cast<DOM::Document&>(document()).update_paint_and_hit_testing_properties_if_needed();
-
- return (Painting::absolute_border_box_rect(*layout_node).y() - Painting::cumulative_scroll_compensation(*layout_node).y()).to_int();
+ return first_border_box_origin_ignoring_transforms(*layout_node).y().to_int();
}
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-complete
diff --git a/Libraries/LibWeb/Painting/BoxViews.cpp b/Libraries/LibWeb/Painting/BoxViews.cpp
index cc57739de52..71de7828d55 100644
--- a/Libraries/LibWeb/Painting/BoxViews.cpp
+++ b/Libraries/LibWeb/Painting/BoxViews.cpp
@@ -314,12 +314,6 @@ Compositing::ContextRef accumulated_visual_context_for_descendants(Layout::Node
return row.has_value() ? row->accumulated_visual_context_for_descendants : Compositing::ContextRef {};
}
-static Compositing::SpatialNodeIndex enclosing_scroll_node_index(Layout::Node const& node)
-{
- auto row = committed_row(node);
- return row.has_value() ? row->enclosing_scroll_node_index : Compositing::VISUAL_VIEWPORT_NODE_INDEX;
-}
-
Compositing::SpatialNodeIndex own_scroll_node_index(Layout::Node const& node)
{
auto row = committed_row(node);
@@ -898,19 +892,13 @@ CSSPixelRect bounding_client_rect(Layout::Node const& node, Layout::RustFFI::Ffi
return rect;
}
-CSSPixelPoint cumulative_scroll_compensation(Layout::Node const& node)
+CSSPixelPoint offset_to_viewport_ignoring_transforms(Layout::Node const& node, Layout::RustFFI::FfiRectToViewportTransform const& rect_to_viewport_transform)
{
- auto const& document = node.document();
- if (!document.has_committed_viewport_box())
- return {};
- // NB: Taking the tree first brings the box's scroll node up to date with it, as for the visual contexts above.
- auto visual_context_tree = document.visual_context_tree();
- auto index = enclosing_scroll_node_index(node);
- if (index == Compositing::VISUAL_VIEWPORT_NODE_INDEX)
+ Layout::RustFFI::FfiOptionalCssPixelPoint result;
+ Layout::RustFFI::layout_script_offset_to_viewport_ignoring_transforms(node.document_host(), committed_row_slot(node), rect_to_viewport_transform, &result);
+ if (!result.has_value)
return {};
- auto pixel_ratio = static_cast<float>(document.page().client().device_pixels_per_css_pixel());
- auto device_offset = visual_context_tree.cumulative_scroll_chain_offset(index, document.scroll_state_snapshot());
- return { CSSPixels::nearest_value_for(device_offset.x() / pixel_ratio), CSSPixels::nearest_value_for(device_offset.y() / pixel_ratio) };
+ return { result.x, result.y };
}
}
diff --git a/Libraries/LibWeb/Painting/BoxViews.h b/Libraries/LibWeb/Painting/BoxViews.h
index 27d6c67c10a..9cff75b0a7f 100644
--- a/Libraries/LibWeb/Painting/BoxViews.h
+++ b/Libraries/LibWeb/Painting/BoxViews.h
@@ -112,6 +112,6 @@ WEB_API CSSPixelRect bounding_client_rect(Layout::Node const&, Layout::RustFFI::
WEB_API bool has_sticky_positioned_inclusive_ancestor(Layout::Node const&);
WEB_API CSSPixelPoint accumulated_sticky_offset(Layout::Node const&, Layout::RustFFI::FfiRectToViewportTransform const&);
-WEB_API CSSPixelPoint cumulative_scroll_compensation(Layout::Node const&);
+WEB_API CSSPixelPoint offset_to_viewport_ignoring_transforms(Layout::Node const&, Layout::RustFFI::FfiRectToViewportTransform const&);
}
diff --git a/Libraries/LibWeb/Rust/src/layout/script_entries.rs b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
index 07eba4bb95f..75f89f7a44f 100644
--- a/Libraries/LibWeb/Rust/src/layout/script_entries.rs
+++ b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
@@ -446,16 +446,17 @@ pub extern "C" fn layout_script_has_sticky_positioned_inclusive_ancestor(
})
}
-/// The offset by which sticky positioning moves the box, as the sum of the offsets of the sticky positioned box and
-/// its sticky positioned ancestors.
-#[unsafe(no_mangle)]
-pub extern "C" fn layout_script_accumulated_sticky_offset(
+fn spatial_chain_offset_in_css_pixels(
host: &DocumentHost,
slot: NodeSlotId,
rect_to_viewport_transform: FfiRectToViewportTransform<'_>,
- out: &mut crate::painting::ffi::FfiOptionalCssPixelPoint,
-) {
- *out = read_rows(host, |arena| {
+ device_offset_of_spatial_chain: impl Fn(
+ &crate::painting::visual_context::VisualContextTree,
+ crate::painting::visual_context::SpatialNodeIndex,
+ &[libgfx_rust::FloatPoint],
+ ) -> libgfx_rust::FloatPoint,
+) -> crate::painting::ffi::FfiOptionalCssPixelPoint {
+ read_rows(host, |arena| {
let mut result = crate::painting::ffi::FfiOptionalCssPixelPoint {
has_value: false,
x: CssPixels::from_raw(0),
@@ -468,15 +469,46 @@ pub extern "C" fn layout_script_accumulated_sticky_offset(
return result;
}
let spatial = arena.paintable_data(slot).accumulated_visual_context.spatial;
- let offset = transform
- .visual_context_tree
- .accumulated_sticky_offset(spatial, transform.scroll_offsets);
+ let offset = device_offset_of_spatial_chain(transform.visual_context_tree, spatial, transform.scroll_offsets);
let inverse_pixel_ratio = 1.0 / transform.device_pixels_per_css_pixel;
result.has_value = true;
result.x = CssPixels::nearest_value_for_f32(offset.x * inverse_pixel_ratio);
result.y = CssPixels::nearest_value_for_f32(offset.y * inverse_pixel_ratio);
result
- });
+ })
+}
+
+/// The offset by which sticky positioning moves the box, as the sum of the offsets of the sticky positioned box and
+/// its sticky positioned ancestors.
+#[unsafe(no_mangle)]
+pub extern "C" fn layout_script_accumulated_sticky_offset(
+ host: &DocumentHost,
+ slot: NodeSlotId,
+ rect_to_viewport_transform: FfiRectToViewportTransform<'_>,
+ out: &mut crate::painting::ffi::FfiOptionalCssPixelPoint,
+) {
+ *out = spatial_chain_offset_in_css_pixels(
+ host,
+ slot,
+ rect_to_viewport_transform,
+ crate::painting::visual_context::VisualContextTree::accumulated_sticky_offset,
+ );
+}
+
+/// The offset by which scrolling, sticky positioning and anchor scroll shifts move the box, without its transforms.
+#[unsafe(no_mangle)]
+pub extern "C" fn layout_script_offset_to_viewport_ignoring_transforms(
+ host: &DocumentHost,
+ slot: NodeSlotId,
+ rect_to_viewport_transform: FfiRectToViewportTransform<'_>,
+ out: &mut crate::painting::ffi::FfiOptionalCssPixelPoint,
+) {
+ *out = spatial_chain_offset_in_css_pixels(
+ host,
+ slot,
+ rect_to_viewport_transform,
+ crate::painting::visual_context::VisualContextTree::offset_to_viewport_ignoring_transforms,
+ );
}
#[unsafe(no_mangle)]
diff --git a/Tests/LibWeb/Text/expected/HTML/image-x-y-under-scrolled-ancestors.txt b/Tests/LibWeb/Text/expected/HTML/image-x-y-under-scrolled-ancestors.txt
new file mode 100644
index 00000000000..e09034a435b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/image-x-y-under-scrolled-ancestors.txt
@@ -0,0 +1,10 @@
+document scrolled: y=200
+scroller scrolled: y=170
+scroller scrolled horizontally: x=150
+scroller scrolled past the origin: y=-80
+scale between two scrolled scrollers: y=160
+fixed in a transformed box in a scrolled scroller: y=180
+fixed in a scrolled document: y=50
+stuck sticky in a scrolled scroller: y=5
+sticky in fixed in a scrolled document: y=60
+anchored to a box in a scrolled scroller: y=180
diff --git a/Tests/LibWeb/Text/input/HTML/image-x-y-under-scrolled-ancestors.html b/Tests/LibWeb/Text/input/HTML/image-x-y-under-scrolled-ancestors.html
new file mode 100644
index 00000000000..33419937c0f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/image-x-y-under-scrolled-ancestors.html
@@ -0,0 +1,89 @@
+<!DOCTYPE html>
+<style>
+ html, body { margin: 0; }
+ img { display: block; width: 10px; height: 10px; }
+ .scroller { overflow: scroll; width: 200px; height: 100px; }
+ .tall { height: 1000px; }
+ .scaled { transform: scale(2); transform-origin: 0 0; }
+</style>
+<body>
+<div id="stage"></div>
+<script src="../include.js"></script>
+<script>
+ const scrollerAt = (id, marginTop, content) =>
+ `<div class="scroller" id="${id}" style="margin-top: ${marginTop}px"><div class="tall">${content}</div></div>`;
+
+ const scenarios = [
+ {
+ name: "document scrolled",
+ html: `<div style="height: 3000px; padding-top: 300px"><img></div>`,
+ scroll: () => window.scrollTo(0, 100),
+ },
+ {
+ name: "scroller scrolled",
+ html: scrollerAt("a", 20, `<div style="padding-top: 200px"><img></div>`),
+ scroll: () => { a.scrollTop = 50; },
+ },
+ {
+ name: "scroller scrolled horizontally",
+ axis: "x",
+ html: `<div class="scroller" id="a"><div style="width: 1000px; padding-left: 200px"><img></div></div>`,
+ scroll: () => { a.scrollLeft = 50; },
+ },
+ {
+ name: "scroller scrolled past the origin",
+ html: scrollerAt("a", 20, `<div style="padding-top: 200px"><img></div>`),
+ scroll: () => { a.scrollTop = 300; },
+ },
+ {
+ name: "scale between two scrolled scrollers",
+ html: scrollerAt("a", 20, `<div class="scaled">${scrollerAt("b", 10, `<div style="padding-top: 200px"><img></div>`)}</div>`),
+ scroll: () => { a.scrollTop = 40; b.scrollTop = 30; },
+ },
+ {
+ name: "fixed in a transformed box in a scrolled scroller",
+ html: scrollerAt("a", 20, `<div style="transform: translate(0, 0); margin-top: 200px; height: 300px"><div style="position: fixed; top: 10px; left: 0"><img></div></div>`),
+ scroll: () => { a.scrollTop = 50; },
+ },
+ {
+ name: "fixed in a scrolled document",
+ html: `<div style="height: 3000px"><div style="position: fixed; top: 50px; left: 0"><img></div></div>`,
+ scroll: () => window.scrollTo(0, 100),
+ },
+ {
+ name: "stuck sticky in a scrolled scroller",
+ html: scrollerAt("a", 0, `<div style="padding-top: 50px; height: 400px"><div style="position: sticky; top: 5px"><img></div></div>`),
+ scroll: () => { a.scrollTop = 100; },
+ },
+ {
+ name: "sticky in fixed in a scrolled document",
+ html: `<div style="height: 3000px"><div style="position: fixed; top: 60px; left: 0; height: 100px; overflow: hidden"><div style="position: sticky; top: 0"><img></div></div></div>`,
+ scroll: () => window.scrollTo(0, 100),
+ },
+ {
+ name: "anchored to a box in a scrolled scroller",
+ html: scrollerAt("a", 20, `<div style="anchor-name: --anchor; margin-top: 200px; height: 10px"></div>`)
+ + `<div style="position: absolute; position-anchor: --anchor; top: anchor(bottom); left: 0"><img></div>`,
+ scroll: () => { a.scrollTop = 50; },
+ },
+ ];
+
+ const nextFrame = () => new Promise(resolve => requestAnimationFrame(resolve));
+
+ asyncTest(async done => {
+ const stage = document.getElementById("stage");
+ const results = [];
+ for (const scenario of scenarios) {
+ stage.innerHTML = scenario.html;
+ scenario.scroll();
+ await nextFrame();
+ await nextFrame();
+ const axis = scenario.axis ?? "y";
+ results.push(`${scenario.name}: ${axis}=${stage.querySelector("img")[axis]}`);
+ stage.innerHTML = "";
+ window.scrollTo(0, 0);
+ }
+ results.forEach(line => println(line));
+ done();
+ });
+</script>