Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(layout): align viewport and scrollbar behavior
ldm0ac477b86f79b
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.mdindex fb1954513..1910bb277 100644--- a/moli-cdp-smoke/README.md+++ b/moli-cdp-smoke/README.md@@ -167,6 +167,17 @@ Covered well:- Chromium-derived proxy authentication coverage uses a real local proxy and per-browser-context proxy configuration. HTTP Basic authentication must expose the initial unauthenticated target request headers and final `200` response through ExtraInfo without leaking `Proxy-Authorization`; an HTTPS `CONNECT` challenge canceled through Fetch must expose proxy origin, a `407` response with `hasExtraInfo=false`, and `Network.loadingFailed` without treating CONNECT headers as target-request ExtraInfo.- Parser-discovered external script, link stylesheet, and parser-created `@import` stylesheet observation plus `Network.getResponseBody`; configured `20,000,000 / 2,000,000` inspector-cache budgets retain a small body while a `2,000,001`-byte body keeps its request identity and repeatedly returns the inspector-cache eviction error.- Classic WebSocket echo, WebSocket `Network.webSocket*` events, and blocked WebSocket handshake behavior.+- The focused `classic-scrollbar` group compares Chromium and Moli for+ block/flex/grid `stable both-edges` numeric sizing, default-visible root+ stable gutters, body hidden/auto/clip viewport overflow propagation,+ `overflow-body-propagation-003`'s `display:contents` exclusion, and an overlay+ that occludes a lower painted scrollbar. It also verifies Moli's consume-only+ scrollbar corner and screenshot-triggered layout freshness.+ The final workflow was calibrated on 2026-08-22 against the headed Xvfb+ build `~/chromium/src/out/Default/chrome` (`Chrome/147.0.7709.0`) and then+ passed unchanged against Moli. Chromium/Xvfb routes raw-CDP clicks on its+ native scrollbar corner through DOM input, so only that control-consumption+ assertion remains Moli-specific.- Chromium-calibrated transformed-iframe input routing through raw CDP: exactused child viewports, hover/click/wheel targets and child-local coordinates,overflow-container scrolling, focus chains, and cross-frame mouseoutdiff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/classic_scrollbar.py b/moli-cdp-smoke/moli_cdp_smoke/groups/classic_scrollbar.pyindex 0226c1ad8..567245fa3 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/classic_scrollbar.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/classic_scrollbar.py@@ -184,6 +184,8 @@ async def run_classic_scrollbar_group(state: SmokeState) -> None:)await _run_multi_scroller_drag_workflow(state, is_moli)await _run_root_scrollbar_workflow(state, is_moli)+ await _run_painted_surface_workflow(state, is_moli)+ await _run_viewport_policy_and_numeric_gutter_workflow(state, is_moli)async def _run_multi_scroller_drag_workflow(state: SmokeState, is_moli: bool) -> None:@@ -613,3 +615,307 @@ async def _run_root_scrollbar_workflow(state: SmokeState, is_moli: bool) -> None"rtlScrollbarSide": "right",},)+++async def _run_painted_surface_workflow(state: SmokeState, is_moli: bool) -> None:+ page = state.page+ cdp = state.cdp+ await page.set_viewport_size({"width": 800, "height": 600})+ await page.set_content(+ """+ <!doctype html>+ <style>+ html, body { margin: 0; }+ #scroller {+ position: absolute; left: 20px; top: 20px;+ width: 200px; height: 100px; overflow: scroll;+ }+ #large { width: 400px; height: 300px; }+ #overlay {+ position: absolute; left: 200px; top: 20px;+ width: 40px; height: 100px; z-index: 10;+ }+ </style>+ <div id="scroller"><div id="large"></div></div>+ <div id="overlay"></div>+ <script>+ window.__paintedSurfaceEvents = [];+ for (const name of [+ "pointerdown", "mousedown", "pointerup", "mouseup", "click"+ ]) {+ document.addEventListener(name, event => {+ __paintedSurfaceEvents.push(`${name}:${event.target.id || event.target.localName}`);+ }, true);+ }+ </script>+ """,+ wait_until="domcontentloaded",+ )+ await page.evaluate(+ """() => {+ scroller.scrollTop = 80;+ return [scroller.clientWidth, scroller.clientHeight, overlay.getBoundingClientRect().x];+ }"""+ )++ async def mouse(event_type: str, x: int, y: int, *, pressed: bool) -> None:+ await cdp.send(+ "Input.dispatchMouseEvent",+ {+ "type": event_type,+ "x": x,+ "y": y,+ "button": "left" if event_type != "mouseMoved" else "none",+ "buttons": 1 if pressed else 0,+ "clickCount": 1,+ },+ )++ # This point is simultaneously inside the overlay and the vertical+ # scrollbar beneath it. The ordinary painted sibling must win.+ await mouse("mousePressed", 210, 30, pressed=True)+ await mouse("mouseReleased", 210, 30, pressed=False)+ covered = await page.evaluate(+ "() => [scroller.scrollTop, __paintedSurfaceEvents.slice()]"+ )+ assert_equal(covered[0], 80, "covered scrollbar does not steal overlay input")+ assert_equal(+ covered[1],+ [+ "pointerdown:overlay",+ "mousedown:overlay",+ "pointerup:overlay",+ "mouseup:overlay",+ "click:overlay",+ ],+ "topmost painted overlay receives pointer and mouse dispatch",+ )++ await page.evaluate(+ """() => {+ overlay.style.display = "none";+ __paintedSurfaceEvents.length = 0;+ return scroller.getBoundingClientRect().width;+ }"""+ )+ # Moli intentionally caps rendering at 50 ms. A screenshot is an explicit+ # render trigger, so the second input probes the new painted state instead+ # of the still-valid throttled snapshot from the first click.+ await page.screenshot()+ # The lower-right 15x15 intersection is painted UA chrome. Moli exposes+ # it as a consume-only control surface rather than a DOM target.+ await mouse("mousePressed", 210, 110, pressed=True)+ await mouse("mouseReleased", 210, 110, pressed=False)+ corner = await page.evaluate(+ "() => [scroller.scrollTop, __paintedSurfaceEvents.slice()]"+ )+ assert_equal(corner[0], 80, "scrollbar corner has no scroll action")+ if is_moli:+ assert_equal(+ corner[1],+ [],+ "Moli painted scrollbar corner stays outside DOM dispatch",+ )++ state.record(+ "paint_ordered_scrollbar_and_corner_input_surfaces",+ {+ "engine": "moli" if is_moli else "chromium",+ "covered": covered,+ "corner": corner,+ "cornerConsumedOutsideDom": is_moli,+ },+ )+++async def _run_viewport_policy_and_numeric_gutter_workflow(+ state: SmokeState, is_moli: bool+) -> None:+ page = state.page+ cdp = state.cdp+ await page.set_viewport_size({"width": 800, "height": 600})+ await page.set_content(+ """+ <!doctype html>+ <style>+ html, body { margin: 0; }+ .scroller {+ width: 200px; height: 100px;+ overflow: scroll;+ scrollbar-gutter: stable both-edges;+ }+ .scroller > div { width: 100%; height: 100%; }+ #flex { display: flex; }+ #grid { display: grid; }+ </style>+ <div id="block" class="scroller"><div></div></div>+ <div id="flex" class="scroller"><div></div></div>+ <div id="grid" class="scroller"><div></div></div>+ """,+ wait_until="domcontentloaded",+ )+ both_edges = await page.evaluate(+ """() => ["block", "flex", "grid"].map(id => {+ const scroller = document.getElementById(id);+ const child = scroller.firstElementChild;+ return [+ scroller.clientWidth, scroller.clientHeight,+ child.offsetWidth, child.offsetHeight,+ ];+ })"""+ )+ assert_equal(+ both_edges,+ [[170, 85, 170, 85], [170, 85, 170, 85], [170, 85, 170, 85]],+ "both-edge horizontal gutter participates in block/flex/grid numeric layout",+ )++ await page.set_content(+ """+ <!doctype html>+ <style>+ html { margin: 0; overflow: visible; }+ body { margin: 0; overflow: hidden; }+ main { height: 1200px; }+ </style>+ <main></main>+ """,+ wait_until="domcontentloaded",+ )++ async def wheel(delta_y: int) -> None:+ await cdp.send(+ "Input.dispatchMouseEvent",+ {+ "type": "mouseWheel",+ "x": 10,+ "y": 10,+ "deltaX": 0,+ "deltaY": delta_y,+ },+ )++ hidden_before = await page.evaluate(+ """() => {+ scrollTo(0, 0);+ return [+ document.documentElement.clientWidth,+ document.documentElement.scrollHeight,+ scrollY,+ ];+ }"""+ )+ assert_equal(hidden_before, [800, 1200, 0], "body hidden propagates to viewport")+ await wheel(80)+ await page.wait_for_timeout(100)+ hidden_wheel = await page.evaluate("() => scrollY")+ assert_equal(hidden_wheel, 0, "body hidden disables user viewport scrolling")+ hidden_script = await page.evaluate("() => { scrollTo(0, 100); return scrollY; }")+ assert_equal(hidden_script, 100, "body hidden retains script viewport scrolling")++ auto_width = await page.evaluate(+ """() => {+ document.body.style.overflow = "auto";+ scrollTo(0, 0);+ return document.documentElement.clientWidth;+ }"""+ )+ assert_equal(auto_width, 785, "body auto exposes the viewport scrollbar")+ await wheel(80)+ await page.wait_for_function("() => scrollY > 0", timeout=2_000)+ auto_wheel = await page.evaluate("() => scrollY")+ assert_equal(auto_wheel, 80, "body auto permits user viewport scrolling")++ clip_width = await page.evaluate(+ """() => {+ document.body.style.overflow = "clip";+ void document.documentElement.clientWidth;+ scrollTo(0, 100);+ return document.documentElement.clientWidth;+ }"""+ )+ assert_equal(clip_width, 800, "body clip maps to hidden at the viewport")+ await wheel(80)+ await page.wait_for_timeout(100)+ clip_wheel = await page.evaluate("() => scrollY")+ assert_equal(clip_wheel, 100, "clip-derived viewport disables user scrolling")++ await page.set_content(+ """+ <!doctype html>+ <style>+ html { margin: 0; overflow: visible; scrollbar-gutter: stable; }+ body { margin: 0; }+ </style>+ """,+ wait_until="domcontentloaded",+ )++ async def root_gutter_metrics() -> list[float]:+ return await page.evaluate(+ """() => {+ const html = document.documentElement.getBoundingClientRect();+ const body = document.body.getBoundingClientRect();+ return [+ document.documentElement.clientWidth,+ html.x, html.width, body.x, body.width,+ ];+ }"""+ )++ stable = await root_gutter_metrics()+ assert_equal(stable, [800, 0, 785, 0, 785], "default-visible root stable gutter")+ await page.evaluate(+ "() => { document.documentElement.style.scrollbarGutter = 'stable both-edges'; }"+ )+ await page.screenshot()+ both_edge_root = await root_gutter_metrics()+ assert_equal(+ both_edge_root,+ [800, 15, 770, 15, 770],+ "default-visible root stable both-edge gutters",+ )++ await page.set_content(+ """+ <!doctype html>+ <style>+ html { margin: 0; overflow: visible; }+ body { display: contents; overflow: scroll; }+ </style>+ """,+ wait_until="domcontentloaded",+ )+ display_contents_width = await page.evaluate(+ "() => document.documentElement.getBoundingClientRect().width"+ )+ assert_equal(+ display_contents_width,+ 800,+ "display:contents body does not propagate overflow to viewport",+ )+ await page.evaluate("() => { document.body.style.display = 'block'; }")+ await page.screenshot()+ principal_body_width = await page.evaluate(+ "() => document.documentElement.getBoundingClientRect().width"+ )+ assert_equal(+ principal_body_width,+ 785,+ "principal body propagates overflow:scroll to viewport",+ )++ state.record(+ "viewport_overflow_policy_and_numeric_scrollbar_gutters",+ {+ "engine": "moli" if is_moli else "chromium",+ "bothEdges": both_edges,+ "bodyHidden": [hidden_before, hidden_wheel, hidden_script],+ "bodyAuto": [auto_width, auto_wheel],+ "bodyClip": [clip_width, clip_wheel],+ "rootStable": stable,+ "rootBothEdges": both_edge_root,+ "displayContentsBody": display_contents_width,+ "principalBody": principal_body_width,+ },+ )diff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.pyindex 5c2301c17..f3ed7f948 100644--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py@@ -165,7 +165,7 @@ PAGE_GROUPS: tuple[SmokeGroup, ...] = (),SmokeGroup("classic-scrollbar",- "Cross-engine classic scrollbar layout, paint, and raw CDP thumb dragging.",+ "Cross-engine classic scrollbar layout, viewport overflow policy, paint-ordered controls, and raw CDP input.","page",run_classic_scrollbar_group,),diff --git a/moli-layout/src/builder.rs b/moli-layout/src/builder.rsindex d5b8bd608..22d51ab3e 100644--- a/moli-layout/src/builder.rs+++ b/moli-layout/src/builder.rs@@ -16,7 +16,9 @@ use crate::{LayoutAnonymousReason, LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic, LayoutDisplay,LayoutElementCategory, LayoutElementSemantics, LayoutError, LayoutPseudo, LayoutSource,LayoutSourceKind, LayoutStyleResolver, LayoutWorld, ResolvedLayoutStyle,- replaced::ReplacedContext, style::InlineWhiteSpaceCollapse,+ replaced::ReplacedContext,+ style::{InlineWhiteSpaceCollapse, LayoutOverflowMode},+ world::{ViewportDefiningBox, ViewportScrollPolicy},};use style::values::generics::image::GenericImage;@@ -43,6 +45,9 @@ whereseen_sources: HashMap<S::NodeId, String>,seen_css_images: HashSet<(S::NodeId, String)>,css_image_references: Vec<crate::LayoutCssImageReference<S::NodeId>>,+ source_root: Option<S::NodeId>,+ root_is_html: bool,+ viewport_body_candidate: Option<ViewportBodyCandidate<S::NodeId>>,}impl<'a, S, R> BoxBuilder<'a, S, R>@@ -58,6 +63,9 @@ whereseen_sources: HashMap::new(),seen_css_images: HashSet::new(),css_image_references: Vec::new(),+ source_root: None,+ root_is_html: false,+ viewport_body_candidate: None,}}@@ -81,6 +89,8 @@ where));}let root_semantics = self.validated_element_semantics(source_root, source_kind)?;+ self.source_root = Some(source_root);+ self.root_is_html = root_semantics.is_html_element("html");let Some(mut root_style) = self.styles.primary_style(source_root)? else {return Err(LayoutError::MissingRootStyle { source_label });};@@ -136,6 +146,7 @@ where}world.compact_reachable();+ self.finalize_viewport_scroll_policy(&mut world);world.validate_invariants()?;world.css_image_references = self.css_image_references;Ok(world)@@ -217,6 +228,19 @@ wherelet Some(mut style) = self.styles.primary_style(source_node)? else {return Ok(Vec::new());};+ if self.viewport_body_candidate.is_none()+ && self.root_is_html+ && self+ .source_root+ .is_some_and(|root| self.source.flat_parent(source_node) == Some(root))+ && semantics.is_html_element("body")+ {+ self.viewport_body_candidate = Some(ViewportBodyCandidate {+ source: source_node,+ overflow: style.overflow_modes(),+ blocks_propagation: style.applies_any_viewport_containment(),+ });+ }let metrics = self.source.replaced_metrics(source_node);if semantics.is_replaced() {style.mark_replaced(natural_replaced_ratio(&semantics, metrics));@@ -268,6 +292,47 @@ whereresult}+ /// Converts the construction-only body candidate into the final viewport+ /// policy before the world crosses into numeric layout. No body computed+ /// style is retained by `LayoutWorld`.+ fn finalize_viewport_scroll_policy(&self, world: &mut LayoutWorld<S::NodeId>) {+ let root = world.root;+ let root_style = &world.boxes[root.index()].style;+ let body_box = self+ .viewport_body_candidate+ .as_ref()+ .and_then(|body| world.source_box(body.source));+ let body_can_define_viewport = self.root_is_html+ && root_style.overflow_is_visible_along_both_axes()+ && !root_style.applies_any_viewport_containment()+ && body_box.is_some()+ && self+ .viewport_body_candidate+ .as_ref()+ .is_some_and(|body| !body.blocks_propagation);+ let (defining_box, overflow) = if body_can_define_viewport {+ let body = self+ .viewport_body_candidate+ .as_ref()+ .expect("body viewport policy requires a candidate");+ (+ ViewportDefiningBox::Body(+ body_box.expect("body viewport policy requires a principal box"),+ ),+ body.overflow,+ )+ } else {+ (ViewportDefiningBox::Root, root_style.overflow_modes())+ };+ world.viewport_scroll_policy = ViewportScrollPolicy::new(+ defining_box,+ overflow.map(LayoutOverflowMode::for_viewport),+ root_style.viewport_scrollbar_width(),+ root_style.viewport_scrollbar_gutter(),+ root_style.scrollbar_colors(),+ );+ }+fn principal_box(&mut self,source_node: S::NodeId,@@ -1211,6 +1276,13 @@ where}}+/// Minimal construction-time snapshot for the first HTML body child.+struct ViewportBodyCandidate<N> {+ source: N,+ overflow: [LayoutOverflowMode; 2],+ blocks_propagation: bool,+}+fn natural_replaced_ratio(semantics: &LayoutElementSemantics,metrics: Option<crate::ReplacedMetrics>,diff --git a/moli-layout/src/layout_tree/hit_test.rs b/moli-layout/src/layout_tree/hit_test.rsindex fc0e1d4fe..fa5d417ce 100644--- a/moli-layout/src/layout_tree/hit_test.rs+++ b/moli-layout/src/layout_tree/hit_test.rs@@ -11,6 +11,22 @@ use super::{tree::FrozenLayoutTree,};+/// One point-resolved surface in the exact front-to-back paint stack.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum LayoutPaintedSurfaceHit<N> {+ Dom(LayoutHit<N>),+ Control(crate::LayoutControlSurfaceHit<N>),+}++impl<N: Copy> LayoutPaintedSurfaceHit<N> {+ pub fn paint_order(self) -> u32 {+ match self {+ Self::Dom(hit) => hit.paint_order.unwrap_or(0),+ Self::Control(hit) => hit.paint_order(),+ }+ }+}+/// One front-to-back hit-test candidate.#[derive(Clone, Debug, PartialEq)]struct LayoutHitTestEntry<N> {@@ -32,6 +48,9 @@ pub struct LayoutHit<N> {/// providers can return a source-only hit without manufacturing a/// tree-local fragment identity.pub fragment: Option<LayoutFragmentId>,+ /// Exact paint ordinal for a real frozen-tree fragment. Explicit mock+ /// providers may return a source-only hit without one.+ pub paint_order: Option<u32>,pub local_point: LayoutPoint,pub is_text: bool,/// The exact physical content box in the hit fragment's own coordinate@@ -101,34 +120,76 @@ wherehits}- /// Resolves a native classic-scrollbar control before ordinary DOM hit- /// testing. Scrollbar controls are user-agent chrome and do not dispatch a- /// pointer/mouse target into the scrolled content.+ /// Resolves every DOM or UA-control surface under one point in exact+ /// front-to-back paint order. Consumers can skip stale DOM sources without+ /// accidentally promoting a geometrically lower scrollbar over a live+ /// overlay.+ pub fn painted_surface_hits(+ &self,+ viewport_point: LayoutPoint,+ ignore_pointer_events_none: bool,+ ) -> Vec<LayoutPaintedSurfaceHit<N>> {+ let mut hits = self+ .hit_test_entries()+ .into_iter()+ .filter_map(|entry| {+ self.hit_for_entry(&entry, viewport_point, ignore_pointer_events_none)+ .map(LayoutPaintedSurfaceHit::Dom)+ })+ .chain(+ self.control_surface_hits(viewport_point)+ .into_iter()+ .map(LayoutPaintedSurfaceHit::Control),+ )+ .collect::<Vec<_>>();+ hits.sort_by_key(|hit| std::cmp::Reverse(hit.paint_order()));+ hits+ }++ /// Returns the topmost painted UA control without comparing it to DOM+ /// fragments. Input dispatch should normally use [`Self::painted_surface_hits`].+ pub fn control_surface_hit_test(+ &self,+ viewport_point: LayoutPoint,+ ) -> Option<crate::LayoutControlSurfaceHit<N>> {+ self.control_surface_hits(viewport_point)+ .into_iter()+ .max_by_key(|hit| hit.paint_order())+ }++ /// Compatibility query for the topmost scrollbar among UA controls only.+ ///+ /// This does not resolve DOM occlusion. Input dispatch must use+ /// [`Self::painted_surface_hits`] so a later-painted DOM fragment can win+ /// over a scrollbar.pub fn scrollbar_hit_test(&self,viewport_point: LayoutPoint,) -> Option<crate::LayoutScrollbarHit<N>> {- let mut candidates = self- .boxes- .iter()- .enumerate()- .filter_map(|(index, layout_box)| {- if !layout_box.visible || !layout_box.pointer_events {- return None;- }- let source = layout_box.geometry_source.or(layout_box.hit_source)?;- let paint_order = layout_box- .fragments- .iter()- .filter_map(|id| self.fragment(*id)?.paint_order)- .max()- .unwrap_or(0);- Some((std::cmp::Reverse(paint_order), index, source))+ self.control_surface_hits(viewport_point)+ .into_iter()+ .filter_map(|hit| match hit {+ crate::LayoutControlSurfaceHit::Scrollbar(hit) => Some(hit),+ crate::LayoutControlSurfaceHit::ScrollbarCorner(_) => None,})- .collect::<Vec<_>>();- candidates.sort_by_key(|candidate| candidate.0);+ .max_by_key(|hit| hit.paint_order)+ }- for (_, index, source) in candidates {+ fn control_surface_hits(+ &self,+ viewport_point: LayoutPoint,+ ) -> Vec<crate::LayoutControlSurfaceHit<N>> {+ let mut hits = Vec::new();+ for (index, layout_box) in self.boxes.iter().enumerate() {+ if !layout_box.visible || !layout_box.pointer_events {+ continue;+ }+ let Some(paint_order) = layout_box.control_paint_order else {+ continue;+ };+ let Some(source) = layout_box.geometry_source.or(layout_box.hit_source) else {+ continue;+ };let layout_box = &self.boxes[index];let is_root = layout_box.id == self.root_box;if !is_root && !self.point_passes_clip_chain(viewport_point, layout_box.clip_chain) {@@ -143,6 +204,20 @@ wherecontinue;};let local_point = viewport_to_local.map_point(viewport_point);+ if let Some(rect) = layout_box.scroll_extent.scrollbar_corner+ && rect.contains(local_point)+ {+ hits.push(crate::LayoutControlSurfaceHit::ScrollbarCorner(+ crate::LayoutScrollbarCornerHit {+ source,+ rect,+ local_point,+ viewport_to_local,+ paint_order,+ },+ ));+ continue;+ }for scrollbar in [layout_box.scroll_extent.vertical_scrollbar,layout_box.scroll_extent.horizontal_scrollbar,@@ -153,16 +228,20 @@ wherelet Some(part) = scrollbar.part_at(local_point) else {continue;};- return Some(crate::LayoutScrollbarHit {- source,- scrollbar,- part,- local_point,- viewport_to_local,- });+ hits.push(crate::LayoutControlSurfaceHit::Scrollbar(+ crate::LayoutScrollbarHit {+ source,+ scrollbar,+ part,+ local_point,+ viewport_to_local,+ paint_order,+ },+ ));+ break;}}- None+ hits}pub fn caret_position(&self, viewport_point: LayoutPoint) -> Option<LayoutCaretPosition<N>> {@@ -386,6 +465,7 @@ whereentry.local_rect.contains(local_point).then_some(LayoutHit {source: entry.source,fragment: Some(entry.fragment),+ paint_order: Some(entry.paint_order),local_point,is_text: entry.is_text,local_content_box,diff --git a/moli-layout/src/layout_tree/tree.rs b/moli-layout/src/layout_tree/tree.rsindex 9a6c2209e..800454af5 100644--- a/moli-layout/src/layout_tree/tree.rs+++ b/moli-layout/src/layout_tree/tree.rs@@ -25,6 +25,8 @@ pub struct FrozenLayoutBox<N> {pub geometry_source: Option<N>,pub principal_source: Option<N>,pub hit_source: Option<N>,+ /// Paint ordinal of this box's scrollbar/corner surface, if any.+ pub(crate) control_paint_order: Option<u32>,}/// One child browsing context owned by the same latest frozen snapshot as itsdiff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rsindex d96c6da98..0a367fb69 100644--- a/moli-layout/src/lib.rs+++ b/moli-layout/src/lib.rs@@ -50,11 +50,12 @@ pub use layout_tree::{LayoutClipChainId, LayoutClipNode, LayoutCoordinateSpaceId, LayoutCssImageReference,LayoutDocumentMetrics, LayoutElementMetrics, LayoutFlushReason, LayoutFragment,LayoutFragmentBoxModel, LayoutFragmentId, LayoutFragmentKind, LayoutHit,- LayoutIntersectionGeometry, LayoutNodeOutput, LayoutOutputBoxId, LayoutPassMetrics,- LayoutPassResult, LayoutPoint, LayoutQuad, LayoutQuery, LayoutQueryAnswer, LayoutQueryBatch,- LayoutRect, LayoutScrollContainerMetrics, LayoutScrollExtent, LayoutScrollIntoViewGeometry,- LayoutSize, LayoutTransform2D, LayoutTreeRetentionMetrics, LayoutViewport,- MAX_RETAINED_LAYOUT_BOXES, MAX_RETAINED_LAYOUT_FRAGMENTS, MAX_RETAINED_LAYOUT_TREE_BYTES,+ LayoutIntersectionGeometry, LayoutNodeOutput, LayoutOutputBoxId, LayoutPaintedSurfaceHit,+ LayoutPassMetrics, LayoutPassResult, LayoutPoint, LayoutQuad, LayoutQuery, LayoutQueryAnswer,+ LayoutQueryBatch, LayoutRect, LayoutScrollContainerMetrics, LayoutScrollExtent,+ LayoutScrollIntoViewGeometry, LayoutSize, LayoutTransform2D, LayoutTreeRetentionMetrics,+ LayoutViewport, MAX_RETAINED_LAYOUT_BOXES, MAX_RETAINED_LAYOUT_FRAGMENTS,+ MAX_RETAINED_LAYOUT_TREE_BYTES,};pub use normalize::{NormalizedBoxNode, NormalizedBoxTree, NormalizedFormattingContext};pub use normalize_source::{@@ -65,8 +66,9 @@ pub use pass::{build_layout_pass, build_layout_pass_with_embedded_frames, build_screenshot_snapshot,};pub use scrollbar::{- LayoutScrollbarAxis, LayoutScrollbarColors, LayoutScrollbarGeometry, LayoutScrollbarGutter,- LayoutScrollbarHit, LayoutScrollbarPart, LayoutScrollbarWidth,+ LayoutControlSurfaceHit, LayoutScrollbarAxis, LayoutScrollbarColors, LayoutScrollbarCornerHit,+ LayoutScrollbarGeometry, LayoutScrollbarGutter, LayoutScrollbarHit, LayoutScrollbarPart,+ LayoutScrollbarWidth,};pub use snapshot::{PaintBlendMode, PaintBorderColors, PaintBorderStyle, PaintBorderStyles, PaintBoxShadow,diff --git a/moli-layout/src/pass.rs b/moli-layout/src/pass.rsindex 21325ae56..c3a19f114 100644--- a/moli-layout/src/pass.rs+++ b/moli-layout/src/pass.rs@@ -212,6 +212,13 @@ where{let started = Instant::now();let mut world = build_layout_world(source, styles)?;+ debug_assert!(+ world+ .viewport_scroll_policy+ .defining_body()+ .is_none_or(|body| world.box_by_id(body).is_some()),+ "viewport policy must retain only a live pass-local body box identity"+ );prepare_list_markers(&mut world);prepare_form_controls(&mut world);prepare_inline_contexts(&mut world, services);@@ -276,27 +283,46 @@ fn compute_world_layout_with_scrollbars<N>() whereN: Copy + std::fmt::Debug + Eq + std::hash::Hash,{- let root = world.root.index();+ let root_id = world.root;+ let root = root_id.index();+ let defining_body = world.viewport_scroll_policy.defining_body();+ world.viewport_scroll_policy.prepare_scrollbar_layout();for (index, layout_box) in world.boxes.iter_mut().enumerate() {- layout_box.style.prepare_scrollbar_layout(index == root);+ let id = crate::LayoutBoxId::from_index(index);+ if id == root_id {+ layout_box.style.prepare_viewport_root_layout();+ } else if defining_body == Some(id) {+ layout_box.style.prepare_viewport_defining_body_layout();+ } else {+ layout_box.style.prepare_scrollbar_layout(false);+ }}loop {compute_world_layout(world, viewport);let overflow = overflowing_axes(world, viewport);- let mut changed = false;+ let (root_overflow_x, root_overflow_y) = overflow[root];+ let mut changed = world+ .viewport_scroll_policy+ .reveal_auto_scrollbar(LayoutScrollbarAxis::Horizontal, root_overflow_x);+ changed |= world+ .viewport_scroll_policy+ .reveal_auto_scrollbar(LayoutScrollbarAxis::Vertical, root_overflow_y);for (index, ((overflow_x, overflow_y), layout_box)) inoverflow.into_iter().zip(world.boxes.iter_mut()).enumerate(){- let is_root = index == root;+ let id = crate::LayoutBoxId::from_index(index);+ if id == root_id || defining_body == Some(id) {+ continue;+ }changed |= layout_box.style.reveal_auto_scrollbar(LayoutScrollbarAxis::Horizontal,- is_root,+ false,overflow_x,);changed |= layout_box.style.reveal_auto_scrollbar(LayoutScrollbarAxis::Vertical,- is_root,+ false,overflow_y,);}@@ -326,6 +352,10 @@ where// the root and its descendants after a root leading// gutter.0.0+ } else if world.is_viewport_defining_body(parent) {+ // This body's overflow/gutter has transferred to the+ // viewport and must not shift its own children.+ 0.0} else {world.boxes[parent.index()].stylediff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rsindex d6a71b1d1..73090e3fa 100644--- a/moli-layout/src/projection.rs+++ b/moli-layout/src/projection.rs@@ -214,6 +214,7 @@ wherepub(crate) coordinate_spaces: Vec<ProjectedCoordinateSpace>,pub(crate) clip_chain: Vec<LayoutClipNode>,paint_order_count: usize,+ control_paint_orders: Vec<Option<u32>>,pub(crate) diagnostics: Vec<PaintDiagnostic>,resolved_transforms: Vec<ResolvedLayoutTransform>,scrollable_overflow: Vec<LayoutRect>,@@ -258,6 +259,7 @@ wherecoordinate_spaces: Vec::with_capacity(count + 1),clip_chain: Vec::new(),paint_order_count: 0,+ control_paint_orders: vec![None; count],diagnostics: Vec::new(),resolved_transforms: vec![ResolvedLayoutTransform::IDENTITY; count],scrollable_overflow: vec![LayoutRect::ZERO; count],@@ -270,6 +272,117 @@ where}}+ fn scrollbar_gutter_thickness(&self, id: LayoutBoxId, axis: LayoutScrollbarAxis) -> f32 {+ if id == self.world.root {+ self.world+ .viewport_scroll_policy+ .scrollbar_gutter_thickness(axis)+ } else if self.world.is_viewport_defining_body(id) {+ 0.0+ } else {+ self.world.boxes[id.index()]+ .style+ .scrollbar_gutter_thickness(axis)+ }+ }++ fn scrollbar_leading_gutter_thickness(+ &self,+ id: LayoutBoxId,+ axis: LayoutScrollbarAxis,+ ) -> f32 {+ if id == self.world.root {+ self.world+ .viewport_scroll_policy+ .scrollbar_leading_gutter_thickness(axis)+ } else if self.world.is_viewport_defining_body(id) {+ 0.0+ } else {+ self.world.boxes[id.index()]+ .style+ .scrollbar_leading_gutter_thickness(axis, false)+ }+ }++ fn scrollbar_control_thickness(&self, id: LayoutBoxId) -> f32 {+ if id == self.world.root {+ self.world+ .viewport_scroll_policy+ .scrollbar_control_thickness()+ } else if self.world.is_viewport_defining_body(id) {+ 0.0+ } else {+ self.world.boxes[id.index()]+ .style+ .scrollbar_control_thickness()+ }+ }++ fn establishes_scroll_container(&self, id: LayoutBoxId) -> bool {+ if id == self.world.root {+ self.world+ .viewport_scroll_policy+ .establishes_scroll_container()+ } else if self.world.is_viewport_defining_body(id) {+ false+ } else {+ self.world.boxes[id.index()]+ .style+ .establishes_scroll_container()+ }+ }++ fn allows_user_scroll(&self, id: LayoutBoxId, axis: LayoutScrollbarAxis) -> bool {+ if id == self.world.root {+ self.world.viewport_scroll_policy.allows_user_scroll(axis)+ } else if self.world.is_viewport_defining_body(id) {+ false+ } else {+ match axis {+ LayoutScrollbarAxis::Horizontal => {+ self.world.boxes[id.index()].style.allows_user_scroll_x()+ }+ LayoutScrollbarAxis::Vertical => {+ self.world.boxes[id.index()].style.allows_user_scroll_y()+ }+ }+ }+ }++ fn clips_overflow(&self, id: LayoutBoxId) -> bool {+ if id == self.world.root {+ self.world.viewport_scroll_policy.clips_overflow()+ } else if self.world.is_viewport_defining_body(id) {+ false+ } else {+ self.world.boxes[id.index()].style.clips_overflow()+ }+ }++ fn has_scrollbar(&self, id: LayoutBoxId, axis: LayoutScrollbarAxis, overflowing: bool) -> bool {+ if id == self.world.root {+ self.world+ .viewport_scroll_policy+ .has_scrollbar(axis, overflowing)+ } else if self.world.is_viewport_defining_body(id) {+ false+ } else {+ self.world.boxes[id.index()]+ .style+ .has_scrollbar(axis, false, overflowing)+ }+ }++ fn scrollbar_colors(&self, id: LayoutBoxId) -> Option<crate::LayoutScrollbarColors> {+ if id == self.world.root {+ self.world.viewport_scroll_policy.scrollbar_colors()+ } else if self.world.is_viewport_defining_body(id) {+ None+ } else {+ self.world.boxes[id.index()].style.scrollbar_colors()+ }+ }+fn build_local_box_geometry(&mut self) {for (index, layout_box) in self.world.boxes.iter().enumerate() {for diagnostic in layout_box.capability_diagnostics() {@@ -283,8 +396,9 @@ wherePaintDiagnosticSeverity::Warning,));}+ let box_id = LayoutBoxId::from_index(index);let id = LayoutOutputBoxId::from_index(index);- let is_root = index == self.world.root.index();+ let is_root = box_id == self.world.root;let layout = layout_box.final_layout;let border_box = LayoutRect::new(0.0,@@ -299,15 +413,12 @@ wherelayout.border.bottom,layout.border.left,);- let vertical_gutter = layout_box- .style- .scrollbar_gutter_thickness(LayoutScrollbarAxis::Vertical);- let vertical_leading_gutter = layout_box- .style- .scrollbar_leading_gutter_thickness(LayoutScrollbarAxis::Vertical, is_root);- let horizontal_gutter = layout_box- .style- .scrollbar_gutter_thickness(LayoutScrollbarAxis::Horizontal);+ let vertical_gutter =+ self.scrollbar_gutter_thickness(box_id, LayoutScrollbarAxis::Vertical);+ let vertical_leading_gutter =+ self.scrollbar_leading_gutter_thickness(box_id, LayoutScrollbarAxis::Vertical);+ let horizontal_gutter =+ self.scrollbar_gutter_thickness(box_id, LayoutScrollbarAxis::Horizontal);let mut content_box = inset_rect(padding_box,layout.padding.top,@@ -463,7 +574,7 @@ wherecontinue;}let child_geometry = &self.boxes[index];- let visual_overflow = if self.world.boxes[index].style.clips_overflow() {+ let visual_overflow = if self.clips_overflow(LayoutBoxId::from_index(index)) {child_geometry.border_box} else {self.scrollable_overflow[index]@@ -485,19 +596,17 @@ where}for index in 0..self.world.boxes.len() {+ let id = LayoutBoxId::from_index(index);let geometry = &self.boxes[index];let overflow = self.scrollable_overflow[index];- let is_root = index == self.world.root.index();- let vertical_gutter = self.world.boxes[index]- .style- .scrollbar_gutter_thickness(LayoutScrollbarAxis::Vertical);- let vertical_leading_gutter = self.world.boxes[index]- .style- .scrollbar_leading_gutter_thickness(LayoutScrollbarAxis::Vertical, is_root);- let horizontal_gutter = self.world.boxes[index]- .style- .scrollbar_gutter_thickness(LayoutScrollbarAxis::Horizontal);- let scrollbar_thickness = self.world.boxes[index].style.scrollbar_control_thickness();+ let is_root = id == self.world.root;+ let vertical_gutter =+ self.scrollbar_gutter_thickness(id, LayoutScrollbarAxis::Vertical);+ let vertical_leading_gutter =+ self.scrollbar_leading_gutter_thickness(id, LayoutScrollbarAxis::Vertical);+ let horizontal_gutter =+ self.scrollbar_gutter_thickness(id, LayoutScrollbarAxis::Horizontal);+ let scrollbar_thickness = self.scrollbar_control_thickness(id);let rtl =self.world.boxes[index].style.direction() == crate::style::InlineDirection::Rtl;let local_scrollport = scrollport_for_box(@@ -528,8 +637,7 @@ where);let horizontal_range = (scroll_size.width - scrollport.width).max(0.0);let vertical_range = (scroll_size.height - scrollport.height).max(0.0);- let is_scroll_container =- is_root || self.world.boxes[index].style.establishes_scroll_container();+ let is_scroll_container = self.establishes_scroll_container(id);let requested = finite_point(self.world.boxes[index].scroll_offset);let (minimum_offset, maximum_offset) = if is_scroll_container {if self.world.boxes[index].style.direction() == crate::style::InlineDirection::Rtl {@@ -554,11 +662,10 @@ where} else {LayoutPoint::ZERO};- let horizontal_scrollbar = self.world.boxes[index]- .style+ let horizontal_scrollbar = self.has_scrollbar(+ id,LayoutScrollbarAxis::Horizontal,- is_root,horizontal_range > f32::EPSILON,).then(|| {@@ -579,11 +686,10 @@ where)}).filter(|bar| bar.frame.width > 0.0 && bar.frame.height > 0.0);- let vertical_scrollbar = self.world.boxes[index]- .style+ let vertical_scrollbar = self.has_scrollbar(+ id,LayoutScrollbarAxis::Vertical,- is_root,vertical_range > f32::EPSILON,).then(|| {@@ -625,27 +731,13 @@ whereminimum_offset,maximum_offset,is_scroll_container,- allows_user_scroll_x: self.world.boxes[index].style.allows_user_scroll_x()- || (is_root- && matches!(- self.world.boxes[index]- .style- .overflow_mode(LayoutScrollbarAxis::Horizontal),- crate::style::LayoutOverflowMode::Visible- )),- allows_user_scroll_y: self.world.boxes[index].style.allows_user_scroll_y()- || (is_root- && matches!(- self.world.boxes[index]- .style- .overflow_mode(LayoutScrollbarAxis::Vertical),- crate::style::LayoutOverflowMode::Visible- )),- clips_overflow: self.world.boxes[index].style.clips_overflow(),+ allows_user_scroll_x: self.allows_user_scroll(id, LayoutScrollbarAxis::Horizontal),+ allows_user_scroll_y: self.allows_user_scroll(id, LayoutScrollbarAxis::Vertical),+ clips_overflow: self.clips_overflow(id),horizontal_scrollbar,vertical_scrollbar,scrollbar_corner,- scrollbar_colors: self.world.boxes[index].style.scrollbar_colors(),+ scrollbar_colors: self.scrollbar_colors(id),});}self.viewport_scroll = self.scroll_extents[self.world.root.index()].applied_offset;@@ -820,10 +912,19 @@ whereself.assign_fragment_paint_metadata(fragment, self.content_clips[index]);}}+ PaintOrderEvent::BoxOutline(id) => {+ let index = id.index();+ let extent = &self.scroll_extents[index];+ if extent.horizontal_scrollbar.is_some()+ || extent.vertical_scrollbar.is_some()+ || extent.scrollbar_corner.is_some()+ {+ self.control_paint_orders[index] = Some(self.next_paint_order());+ }+ }PaintOrderEvent::BoxOutsetShadow(_)| PaintOrderEvent::PushStackingContext(_)| PaintOrderEvent::TableCollapsedBorders(_)- | PaintOrderEvent::BoxOutline(_)| PaintOrderEvent::PopStackingContext(_) => {}}}@@ -858,17 +959,19 @@ whereself.boxes[index].clip_chain = box_clip;self.background_clips[index] = box_clip;- let child_clip =- if id != self.world.root && self.world.boxes[index].clips_descendant_paint() {- Some(self.push_clip(- box_clip,- Some(LayoutOutputBoxId::from_index(index)),- self.boxes[index].coordinate_space,- self.scroll_extents[index].scrollport,- ))- } else {- box_clip- };+ let child_clip = if id != self.world.root+ && !self.world.is_viewport_defining_body(id)+ && self.world.boxes[index].clips_descendant_paint()+ {+ Some(self.push_clip(+ box_clip,+ Some(LayoutOutputBoxId::from_index(index)),+ self.boxes[index].coordinate_space,+ self.scroll_extents[index].scrollport,+ ))+ } else {+ box_clip+ };self.content_clips[index] = child_clip;for child in self.world.boxes[index].children.clone() {self.assign_box_clip_metadata(child, child_clip, viewport_clip);@@ -880,18 +983,23 @@ wherefragment_id: LayoutFragmentId,clip_chain: Option<LayoutClipChainId>,) {- let order = u32::try_from(self.paint_order_count)- .expect("one frozen layout tree exceeded the u32 paint-order limit");match self.fragments[fragment_id.index()].kind {LayoutFragmentKind::Box { .. }| LayoutFragmentKind::InlineBox { .. }| LayoutFragmentKind::Text { .. } => {}LayoutFragmentKind::Line { .. } => return,}+ let order = self.next_paint_order();let fragment = &mut self.fragments[fragment_id.index()];fragment.clip_chain = clip_chain;fragment.paint_order = Some(order);+ }++ fn next_paint_order(&mut self) -> u32 {+ let order = u32::try_from(self.paint_order_count)+ .expect("one frozen layout tree exceeded the u32 paint-order limit");self.paint_order_count = self.paint_order_count.saturating_add(1);+ order}fn push_clip(@@ -954,10 +1062,17 @@ where.zip(self.principal_sources).zip(self.hit_sources).zip(self.scroll_extents)+ .zip(self.control_paint_orders).zip(coordinate_spaces.map(FrozenCoordinateSpace::from)).map(|(- ((((geometry, geometry_source), principal_source), hit_source), scroll_extent),+ (+ (+ (((geometry, geometry_source), principal_source), hit_source),+ scroll_extent,+ ),+ control_paint_order,+ ),coordinate_space,)| FrozenLayoutBox {geometry,@@ -966,6 +1081,7 @@ wheregeometry_source,principal_source,hit_source,+ control_paint_order,},).collect();@@ -1268,14 +1384,16 @@ whereN: Copy + Debug + Eq + Hash,{let owner = &world.boxes[owner_index];+ let owner_id = LayoutBoxId::from_index(owner_index);let owner_layout = owner.final_layout;- let vertical_leading_gutter = if owner_index == world.root.index() {- 0.0- } else {- owner- .style- .scrollbar_leading_gutter_thickness(LayoutScrollbarAxis::Vertical, false)- };+ let vertical_leading_gutter =+ if owner_id == world.root || world.is_viewport_defining_body(owner_id) {+ 0.0+ } else {+ owner+ .style+ .scrollbar_leading_gutter_thickness(LayoutScrollbarAxis::Vertical, false)+ };let content_origin = LayoutPoint::new(owner_layout.border.left + owner_layout.padding.left + vertical_leading_gutter,owner_layout.border.top + owner_layout.padding.top,@@ -1285,7 +1403,7 @@ where- owner_layout.border.right- owner_layout.padding.left- owner_layout.padding.right)- - if owner_index == world.root.index() {+ - if owner_id == world.root || world.is_viewport_defining_body(owner_id) {0.0} else {ownerdiff --git a/moli-layout/src/scrollbar.rs b/moli-layout/src/scrollbar.rsindex bb39c5b80..029698408 100644--- a/moli-layout/src/scrollbar.rs+++ b/moli-layout/src/scrollbar.rs@@ -78,6 +78,35 @@ pub struct LayoutScrollbarHit<N> {pub part: LayoutScrollbarPart,pub local_point: LayoutPoint,pub viewport_to_local: LayoutTransform2D,+ /// Exact ordinal of the `BoxOutline` paint event that emitted this UA+ /// control. It shares the same order space as ordinary DOM fragments.+ pub paint_order: u32,+}++/// Consume-only input hit for the painted intersection of two classic bars.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct LayoutScrollbarCornerHit<N> {+ pub source: N,+ pub rect: LayoutRect,+ pub local_point: LayoutPoint,+ pub viewport_to_local: LayoutTransform2D,+ pub paint_order: u32,+}++/// A non-DOM control surface emitted by the normal CSS paint stack.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum LayoutControlSurfaceHit<N> {+ Scrollbar(LayoutScrollbarHit<N>),+ ScrollbarCorner(LayoutScrollbarCornerHit<N>),+}++impl<N> LayoutControlSurfaceHit<N> {+ pub fn paint_order(self) -> u32 {+ match self {+ Self::Scrollbar(hit) => hit.paint_order,+ Self::ScrollbarCorner(hit) => hit.paint_order,+ }+ }}/// One scrollbar in its owning box's local coordinate space.diff --git a/moli-layout/src/style.rs b/moli-layout/src/style.rsindex e2bac4abb..f5ec9bbcf 100644--- a/moli-layout/src/style.rs+++ b/moli-layout/src/style.rs@@ -160,13 +160,25 @@ impl LayoutOverflowMode {}}- const fn creates_scroll_container(self) -> bool {+ pub(crate) const fn creates_scroll_container(self) -> bool {matches!(self, Self::Hidden | Self::Auto | Self::Scroll)}- const fn allows_user_scroll(self) -> bool {+ pub(crate) const fn allows_user_scroll(self) -> bool {matches!(self, Self::Auto | Self::Scroll)}++ /// Overflow values propagated to a viewport use a different used-value+ /// mapping from an ordinary element. `visible` becomes the viewport's+ /// ordinary automatic scrolling behavior, while `clip` becomes `hidden`+ /// so script scrolling remains available without user scrolling or UI.+ pub(crate) const fn for_viewport(self) -> Self {+ match self {+ Self::Visible => Self::Auto,+ Self::Clip => Self::Hidden,+ Self::Hidden | Self::Auto | Self::Scroll => self,+ }+ }}#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]@@ -1610,6 +1622,56 @@ impl ResolvedLayoutStyle {self.overflow_y.allows_user_scroll()}+ pub(crate) const fn overflow_modes(&self) -> [LayoutOverflowMode; 2] {+ [self.overflow_x, self.overflow_y]+ }++ pub(crate) fn overflow_is_visible_along_both_axes(&self) -> bool {+ self.overflow_modes()+ .into_iter()+ .all(|mode| mode == LayoutOverflowMode::Visible)+ }++ pub(crate) fn applies_any_viewport_containment(&self) -> bool {+ let Some(computed) = self.computed.as_ref() else {+ return false;+ };+ !computed.clone_contain().is_empty()+ || computed.clone_container_type().is_size_container_type()+ || computed.clone_content_visibility() != StyloContentVisibility::Visible+ }++ pub(crate) const fn viewport_scrollbar_width(&self) -> LayoutScrollbarWidth {+ self.scrollbar_width+ }++ pub(crate) const fn viewport_scrollbar_gutter(&self) -> LayoutScrollbarGutter {+ self.scrollbar_gutter+ }++ /// Keeps the document element's numeric root formatting context while its+ /// scrollbar policy is represented by the synthetic viewport. Using+ /// `Visible` here would let the body's block margins collapse through the+ /// root even though the root box establishes an independent formatting+ /// context.+ pub(crate) fn prepare_viewport_root_layout(&mut self) {+ self.revealed_scrollbar_x = false;+ self.revealed_scrollbar_y = false;+ self.taffy.scrollbar_width = 0.0;+ self.taffy.overflow.x = taffy::Overflow::Hidden;+ self.taffy.overflow.y = taffy::Overflow::Hidden;+ }++ /// Removes the numeric effect of overflow transferred from the defining+ /// body to the viewport without changing that body's authored style.+ pub(crate) fn prepare_viewport_defining_body_layout(&mut self) {+ self.revealed_scrollbar_x = false;+ self.revealed_scrollbar_y = false;+ self.taffy.scrollbar_width = 0.0;+ self.taffy.overflow.x = taffy::Overflow::Visible;+ self.taffy.overflow.y = taffy::Overflow::Visible;+ }+pub(crate) fn prepare_scrollbar_layout(&mut self, is_root: bool) {self.revealed_scrollbar_x = self.overflow_x == LayoutOverflowMode::Scroll;self.revealed_scrollbar_y = self.overflow_y == LayoutOverflowMode::Scroll;@@ -1621,9 +1683,8 @@ impl ResolvedLayoutStyle {self.taffy.overflow.y = self.initial_taffy_overflow(LayoutScrollbarAxis::Vertical, is_root);// Taffy's scrollbar width is scalar. For `both-edges` it represents// the two vertical gutters together, so it must not also be used as a- // double-height horizontal scrollbar. Horizontal reservation remains- // part of Moli's projection feedback below, as it already is for the- // root scrolling element.+ // double-height horizontal scrollbar. Moli's Taffy adapter supplies+ // the missing single horizontal reservation to numeric child layout.if both_edge_gutter && self.revealed_scrollbar_x {self.taffy.overflow.x = taffy::Overflow::Hidden;}@@ -1733,6 +1794,19 @@ impl ResolvedLayoutStyle {self.scrollbar_width.thickness()}+ /// Extra block-axis reservation that Taffy's scalar scrollbar width+ /// cannot express. Under `stable both-edges` the scalar is already used+ /// for two vertical gutters, so Moli runs the container's numeric layout+ /// against a block size reduced by the real horizontal control and then+ /// restores the outer box size.+ pub(crate) fn horizontal_scrollbar_layout_compensation(&self) -> f32 {+ if self.reserves_both_edge_vertical_gutter() && self.revealed_scrollbar_x {+ self.scrollbar_width.thickness()+ } else {+ 0.0+ }+ }+pub(crate) fn scrollbar_gutter_thickness(&self, axis: LayoutScrollbarAxis) -> f32 {if self.scrollbar_width == LayoutScrollbarWidth::None {return 0.0;diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rsindex 0a494faf3..ac5f3d4f1 100644--- a/moli-layout/src/taffy_tree.rs+++ b/moli-layout/src/taffy_tree.rs@@ -49,11 +49,15 @@ whereworld.viewport_layout.cache.clear();world.viewport_layout.unrounded_layout = Layout::with_order(0);world.viewport_layout.final_layout = Layout::with_order(0);- let root_style = &world.boxes[world.root.index()].style;- let vertical_gutter = root_style.scrollbar_gutter_thickness(LayoutScrollbarAxis::Vertical);- let vertical_leading_gutter =- root_style.scrollbar_leading_gutter_thickness(LayoutScrollbarAxis::Vertical, true);- let horizontal_gutter = root_style.scrollbar_gutter_thickness(LayoutScrollbarAxis::Horizontal);+ let vertical_gutter = world+ .viewport_scroll_policy+ .scrollbar_gutter_thickness(LayoutScrollbarAxis::Vertical);+ let vertical_leading_gutter = world+ .viewport_scroll_policy+ .scrollbar_leading_gutter_thickness(LayoutScrollbarAxis::Vertical);+ let horizontal_gutter = world+ .viewport_scroll_policy+ .scrollbar_gutter_thickness(LayoutScrollbarAxis::Horizontal);world.viewport_layout.style = Style {display: Display::Block,box_sizing: BoxSizing::BorderBox,@@ -584,7 +588,9 @@ wherelet mut ancestor = world.boxes[id.index()].parent;while let Some(candidate) = ancestor {let layout_box = &world.boxes[candidate.index()];- if layout_box.style.establishes_scroll_container() {+ if !world.is_viewport_defining_body(candidate)+ && layout_box.style.establishes_scroll_container()+ {let layout = layout_box.unrounded_layout;let origin = unrounded_global_origin(world, candidate);return Some(PaintRect::new(@@ -1434,6 +1440,55 @@ wherenode_id: NodeId,inputs: LayoutInput,block_context: Option<&mut BlockContext<'_>>,+ ) -> LayoutOutput {+ let id = LayoutBoxId::from_taffy(node_id);+ let horizontal_reservation = if id == self.root || self.boxes[id.index()].is_replaced() {+ 0.0+ } else {+ self.boxes[id.index()]+ .style+ .horizontal_scrollbar_layout_compensation()+ };+ if horizontal_reservation <= 0.0 {+ return self.compute_child_layout_for_box(node_id, inputs, block_context);+ }++ // Taffy exposes one scalar scrollbar width for both axes. A+ // `stable both-edges` box needs that scalar to reserve two vertical+ // gutters, leaving no way to describe the single horizontal gutter.+ // Adapt the container's numeric block-size input here: descendants,+ // percentages, flex/grid tracks and intrinsic calculations all see+ // the reduced scrollport, while the returned outer border-box keeps+ // the size selected by the parent. The root uses the synthetic+ // viewport's axis-specific borders and never enters this adapter.+ let outer_known_height = inputs.known_dimensions.height;+ let inputs = LayoutInput {+ known_dimensions: inputs.known_dimensions.map_height(|height| {+ height.map(|height| (height - horizontal_reservation).max(0.0))+ }),+ definite_dimensions: inputs.definite_dimensions.map_height(|height| {+ height.map(|height| (height - horizontal_reservation).max(0.0))+ }),+ available_space: inputs.available_space.map_height(|height| match height {+ AvailableSpace::Definite(height) => {+ AvailableSpace::Definite((height - horizontal_reservation).max(0.0))+ }+ AvailableSpace::MinContent => AvailableSpace::MinContent,+ AvailableSpace::MaxContent => AvailableSpace::MaxContent,+ }),+ ..inputs+ };+ let mut output = self.compute_child_layout_for_box(node_id, inputs, block_context);+ output.size.height =+ outer_known_height.unwrap_or(output.size.height + horizontal_reservation);+ output+ }++ fn compute_child_layout_for_box(+ &mut self,+ node_id: NodeId,+ inputs: LayoutInput,+ block_context: Option<&mut BlockContext<'_>>,) -> LayoutOutput {let id = LayoutBoxId::from_taffy(node_id);let layout_box = &self.boxes[id.index()];diff --git a/moli-layout/src/world.rs b/moli-layout/src/world.rsindex 38c5bd80e..31b6e5d31 100644--- a/moli-layout/src/world.rs+++ b/moli-layout/src/world.rs@@ -5,7 +5,9 @@ use taffy::{Cache, Layout, Point, Style};use crate::{LayoutCssImageReference, LayoutElementSemantics, LayoutError, LayoutPoint, LayoutPseudo,+ LayoutScrollbarAxis, LayoutScrollbarColors, LayoutScrollbarGutter, LayoutScrollbarWidth,ReplacedMetrics, ResolvedLayoutStyle, inline::InlineFormattingContext,+ style::LayoutOverflowMode,};/// Dense identifier scoped to exactly one [`LayoutWorld`].@@ -258,6 +260,182 @@ pub(crate) struct ViewportLayoutState {pub(crate) final_layout: Layout,}+/// CSS box whose overflow supplies the viewport scrolling mechanism.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub(crate) enum ViewportDefiningBox {+ #[default]+ Root,+ Body(LayoutBoxId),+}++/// Independent style for the viewport scrolling mechanism.+///+/// Box construction copies overflow from the selected root/body box, while+/// scrollbar appearance continues to come from the root. The selected body's+/// authored style remains untouched; its exact box identity tells later+/// phases that those overflow properties have already transferred here.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct ViewportScrollPolicy {+ pub(crate) defining_box: ViewportDefiningBox,+ pub(crate) effective_overflow: [LayoutOverflowMode; 2],+ scrollbar_width: LayoutScrollbarWidth,+ scrollbar_gutter: LayoutScrollbarGutter,+ scrollbar_colors: Option<LayoutScrollbarColors>,+ revealed_scrollbar_x: bool,+ revealed_scrollbar_y: bool,+}++impl Default for ViewportScrollPolicy {+ fn default() -> Self {+ Self {+ defining_box: ViewportDefiningBox::Root,+ effective_overflow: [LayoutOverflowMode::Auto; 2],+ scrollbar_width: LayoutScrollbarWidth::Auto,+ scrollbar_gutter: LayoutScrollbarGutter::Auto,+ scrollbar_colors: None,+ revealed_scrollbar_x: false,+ revealed_scrollbar_y: false,+ }+ }+}++impl ViewportScrollPolicy {+ pub(crate) const fn new(+ defining_box: ViewportDefiningBox,+ effective_overflow: [LayoutOverflowMode; 2],+ scrollbar_width: LayoutScrollbarWidth,+ scrollbar_gutter: LayoutScrollbarGutter,+ scrollbar_colors: Option<LayoutScrollbarColors>,+ ) -> Self {+ Self {+ defining_box,+ effective_overflow,+ scrollbar_width,+ scrollbar_gutter,+ scrollbar_colors,+ revealed_scrollbar_x: false,+ revealed_scrollbar_y: false,+ }+ }++ pub(crate) const fn defining_body(self) -> Option<LayoutBoxId> {+ match self.defining_box {+ ViewportDefiningBox::Root => None,+ ViewportDefiningBox::Body(body) => Some(body),+ }+ }++ pub(crate) fn prepare_scrollbar_layout(&mut self) {+ self.revealed_scrollbar_x = self.effective_overflow[0] == LayoutOverflowMode::Scroll;+ self.revealed_scrollbar_y = self.effective_overflow[1] == LayoutOverflowMode::Scroll;+ }++ pub(crate) fn reveal_auto_scrollbar(+ &mut self,+ axis: LayoutScrollbarAxis,+ overflowing: bool,+ ) -> bool {+ if !overflowing+ || self.scrollbar_width == LayoutScrollbarWidth::None+ || self.overflow_mode(axis) != LayoutOverflowMode::Auto+ {+ return false;+ }+ let revealed = match axis {+ LayoutScrollbarAxis::Horizontal => &mut self.revealed_scrollbar_x,+ LayoutScrollbarAxis::Vertical => &mut self.revealed_scrollbar_y,+ };+ if *revealed {+ return false;+ }+ *revealed = true;+ true+ }++ pub(crate) const fn overflow_mode(self, axis: LayoutScrollbarAxis) -> LayoutOverflowMode {+ match axis {+ LayoutScrollbarAxis::Horizontal => self.effective_overflow[0],+ LayoutScrollbarAxis::Vertical => self.effective_overflow[1],+ }+ }++ pub(crate) fn establishes_scroll_container(self) -> bool {+ self.effective_overflow+ .into_iter()+ .any(LayoutOverflowMode::creates_scroll_container)+ }++ pub(crate) fn allows_user_scroll(self, axis: LayoutScrollbarAxis) -> bool {+ self.overflow_mode(axis).allows_user_scroll()+ }++ pub(crate) fn clips_overflow(self) -> bool {+ self.effective_overflow+ .into_iter()+ .any(|mode| mode != LayoutOverflowMode::Visible)+ }++ pub(crate) fn has_scrollbar(self, axis: LayoutScrollbarAxis, overflowing: bool) -> bool {+ if self.scrollbar_width == LayoutScrollbarWidth::None {+ return false;+ }+ match self.overflow_mode(axis) {+ LayoutOverflowMode::Scroll => true,+ LayoutOverflowMode::Auto => overflowing,+ LayoutOverflowMode::Visible | LayoutOverflowMode::Clip | LayoutOverflowMode::Hidden => {+ false+ }+ }+ }++ pub(crate) const fn scrollbar_control_thickness(self) -> f32 {+ self.scrollbar_width.thickness()+ }++ pub(crate) const fn scrollbar_colors(self) -> Option<LayoutScrollbarColors> {+ self.scrollbar_colors+ }++ pub(crate) fn scrollbar_gutter_thickness(self, axis: LayoutScrollbarAxis) -> f32 {+ if self.scrollbar_width == LayoutScrollbarWidth::None {+ return 0.0;+ }+ let revealed = match axis {+ LayoutScrollbarAxis::Horizontal => self.revealed_scrollbar_x,+ LayoutScrollbarAxis::Vertical => self.revealed_scrollbar_y,+ };+ let stable_vertical = axis == LayoutScrollbarAxis::Vertical+ && self.scrollbar_gutter != LayoutScrollbarGutter::Auto+ && self.effective_overflow[1].creates_scroll_container();+ if !revealed && !stable_vertical {+ return 0.0;+ }+ let thickness = self.scrollbar_width.thickness();+ if axis == LayoutScrollbarAxis::Vertical && self.reserves_both_edge_vertical_gutter() {+ thickness * 2.0+ } else {+ thickness+ }+ }++ pub(crate) fn scrollbar_leading_gutter_thickness(self, axis: LayoutScrollbarAxis) -> f32 {+ if axis == LayoutScrollbarAxis::Vertical+ && self.scrollbar_gutter_thickness(axis) > 0.0+ && self.reserves_both_edge_vertical_gutter()+ {+ self.scrollbar_width.thickness()+ } else {+ 0.0+ }+ }++ fn reserves_both_edge_vertical_gutter(self) -> bool {+ self.scrollbar_gutter == LayoutScrollbarGutter::StableBothEdges+ && self.effective_overflow[1].creates_scroll_container()+ && self.scrollbar_width != LayoutScrollbarWidth::None+ }+}+impl Default for ViewportLayoutState {fn default() -> Self {Self {@@ -346,6 +524,7 @@ wherepub(crate) source_mapping: HashMap<N, LayoutBoxId>,pub(crate) display_contents_mapping: HashMap<N, Vec<LayoutBoxId>>,pub(crate) root: LayoutBoxId,+ pub(crate) viewport_scroll_policy: ViewportScrollPolicy,pub(crate) viewport_layout: ViewportLayoutState,pub(crate) css_image_references: Vec<LayoutCssImageReference<N>>,}@@ -360,6 +539,7 @@ wheresource_mapping: HashMap::new(),display_contents_mapping: HashMap::new(),root: LayoutBoxId::from_index(0),+ viewport_scroll_policy: ViewportScrollPolicy::default(),viewport_layout: ViewportLayoutState::default(),css_image_references: Vec::new(),}@@ -369,6 +549,10 @@ whereself.root}+ pub(crate) fn is_viewport_defining_body(&self, id: LayoutBoxId) -> bool {+ self.viewport_scroll_policy.defining_body() == Some(id)+ }+pub fn len(&self) -> usize {self.boxes.len()}@@ -526,6 +710,23 @@ whereif let Some(index) = reachable.iter().position(|reachable| !reachable) {return Err(LayoutError::InvalidBoxReference { index });}+ if let Some(body) = self.viewport_scroll_policy.defining_body() {+ let Some(body_box) = self.box_by_id(body) else {+ return Err(LayoutError::InvalidBoxReference {+ index: body.index(),+ });+ };+ if body == self.root+ || !body_box+ .element_semantics()+ .is_some_and(|element| element.is_html_element("body"))+ {+ return Err(LayoutError::source_contract(+ &body_box.source_label,+ "viewport-defining body identity must name a principal HTML body box",+ ));+ }+ }for (index, layout_box) in self.boxes.iter().enumerate() {let id = LayoutBoxId::from_index(index);self.validate_box_provenance(id, layout_box)?;diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rsindex 57fcd8fb8..13d5e158e 100644--- a/moli-layout/tests/phase5_output_contract.rs+++ b/moli-layout/tests/phase5_output_contract.rs@@ -1,23 +1,24 @@use std::collections::HashMap;use moli_layout::{- DocumentLayoutServices, LayoutDisplay, LayoutElementCategory, LayoutElementSemantics,- LayoutError, LayoutFlushReason, LayoutFragmentKind, LayoutNamespace, LayoutPassRequest,- LayoutPassResult, LayoutPoint, LayoutQuery, LayoutQueryAnswer, LayoutQueryBatch, LayoutRect,- LayoutScrollbarColors, LayoutScrollbarGutter, LayoutScrollbarPart, LayoutScrollbarWidth,- LayoutSource, LayoutSourceKind, LayoutStyleResolver, LayoutTransform2D, LayoutViewport,- PaintBrush, PaintCaptureRequest, PaintColor, PaintFragment, PaintShape, ResolvedLayoutStyle,- build_layout_pass,+ DocumentLayoutServices, LayoutControlSurfaceHit, LayoutDisplay, LayoutElementCategory,+ LayoutElementSemantics, LayoutError, LayoutFlushReason, LayoutFragmentKind, LayoutNamespace,+ LayoutPaintedSurfaceHit, LayoutPassRequest, LayoutPassResult, LayoutPoint, LayoutQuery,+ LayoutQueryAnswer, LayoutQueryBatch, LayoutRect, LayoutScrollbarColors, LayoutScrollbarGutter,+ LayoutScrollbarPart, LayoutScrollbarWidth, LayoutSource, LayoutSourceKind, LayoutStyleResolver,+ LayoutTransform2D, LayoutViewport, PaintBrush, PaintCaptureRequest, PaintColor, PaintFragment,+ PaintShape, ResolvedLayoutStyle, build_layout_pass,};use style::Atom;use taffy::{BoxSizing, Dimension, LengthPercentageAuto, Overflow, Point, Position, Rect, Size, Style,- style_helpers::length,+ style_helpers::{length, percent},};#[derive(Clone)]struct Node {label: &'static str,+ local_name: &'static str,kind: LayoutSourceKind,text: Option<&'static str>,children: Vec<usize>,@@ -28,6 +29,18 @@ impl Node {fn element(label: &'static str, children: Vec<usize>) -> Self {Self {label,+ local_name: "div",+ kind: LayoutSourceKind::Element,+ text: None,+ children,+ scroll: LayoutPoint::ZERO,+ }+ }++ fn html_element(label: &'static str, local_name: &'static str, children: Vec<usize>) -> Self {+ Self {+ label,+ local_name,kind: LayoutSourceKind::Element,text: None,children,@@ -38,6 +51,7 @@ impl Node {fn text(label: &'static str, text: &'static str) -> Self {Self {label,+ local_name: "#text",kind: LayoutSourceKind::Text,text: Some(text),children: Vec::new(),@@ -74,7 +88,7 @@ impl LayoutSource for Source {(self.0[node].kind == LayoutSourceKind::Element).then(|| {LayoutElementSemantics::new(LayoutNamespace::Html,- "div",+ self.0[node].local_name,LayoutElementCategory::Generic,None,)@@ -239,6 +253,14 @@ fn classic_scrollbars_share_layout_paint_and_hit_test_geometry() {.expect("thumb should use the frozen paint geometry");assert_eq!(hit.source, 1);assert_eq!(hit.part, LayoutScrollbarPart::Thumb);+ let corner = output+ .control_surface_hit_test(LayoutPoint::new(190.0, 90.0))+ .expect("painted corner must consume UA-control input");+ assert!(matches!(+ corner,+ LayoutControlSurfaceHit::ScrollbarCorner(hit)+ if hit.source == 1 && hit.rect == LayoutRect::new(185.0, 85.0, 15.0, 15.0)+ ));let snapshot = output.paint_snapshot().expect("paint request");assert!(snapshot.fragments.iter().any(|fragment| matches!(@@ -274,6 +296,86 @@ fn classic_scrollbars_share_layout_paint_and_hit_test_geometry() {)));}+#[test]+fn painted_surface_order_keeps_an_overlay_above_a_scrollbar() {+ let source = Source(vec![+ Node::element("root", vec![1, 3]),+ Node::element("scroller", vec![2]),+ Node::element("oversized-content", Vec::new()),+ Node::element("overlay", Vec::new()),+ ]);+ let mut styles = Styles::default();+ styles+ .0+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));+ let positioned = |left, top, width, height| Style {+ position: Position::Absolute,+ inset: Rect {+ left: length(left),+ right: LengthPercentageAuto::auto(),+ top: length(top),+ bottom: LengthPercentageAuto::auto(),+ },+ size: Size {+ width: length(width),+ height: length(height),+ },+ ..Style::default()+ };+ let mut scroller = resolved(+ LayoutDisplay::Block,+ Style {+ overflow: Point {+ x: Overflow::Scroll,+ y: Overflow::Scroll,+ },+ ..positioned(20.0, 20.0, 200.0, 100.0)+ },+ )+ .with_position(moli_layout::LayoutPosition::Absolute);+ scroller.set_scrollbar_style(+ LayoutScrollbarWidth::Auto,+ LayoutScrollbarGutter::Auto,+ None,+ );+ styles.0.insert(1, scroller);+ styles+ .0+ .insert(2, fixed_size(LayoutDisplay::Block, 400.0, 300.0));+ styles.0.insert(+ 3,+ resolved(LayoutDisplay::Block, positioned(200.0, 20.0, 40.0, 100.0))+ .with_position(moli_layout::LayoutPosition::Absolute)+ .with_z_index(10),+ );++ let output = build(&source, &mut styles);+ let point = LayoutPoint::new(210.0, 30.0);+ assert!(matches!(+ output.control_surface_hit_test(point),+ Some(LayoutControlSurfaceHit::Scrollbar(hit)) if hit.source == 1+ ));+ let surfaces = output.painted_surface_hits(point, false);+ assert!(matches!(+ surfaces.first(),+ Some(LayoutPaintedSurfaceHit::Dom(hit)) if hit.source == 3+ ));+ let overlay_order = surfaces[0].paint_order();+ let scrollbar_order = surfaces+ .iter()+ .copied()+ .find_map(|surface| match surface {+ LayoutPaintedSurfaceHit::Control(LayoutControlSurfaceHit::Scrollbar(hit))+ if hit.source == 1 =>+ {+ Some(hit.paint_order)+ }+ _ => None,+ })+ .expect("covered scrollbar remains in the sampled paint stack");+ assert!(overlay_order > scrollbar_order);+}+#[test]fn non_viewport_captures_omit_only_the_root_scrollbars() {let source = Source(vec![@@ -482,6 +584,222 @@ fn stable_both_edges_reserves_and_offsets_both_chromium_gutters() {assert_rect(vertical.frame, LayoutRect::new(185.0, 0.0, 15.0, 100.0));}+#[test]+fn stable_both_edges_reserves_horizontal_space_during_numeric_layout() {+ for display in [+ LayoutDisplay::Block,+ LayoutDisplay::Flex,+ LayoutDisplay::Grid,+ ] {+ let source = Source(vec![+ Node::element("root", vec![1]),+ Node::element("scroller", vec![2]),+ Node::element("percentage-child", Vec::new()),+ ]);+ let mut styles = Styles::default();+ styles+ .0+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));+ let mut scroller = resolved(+ display,+ Style {+ display: match display {+ LayoutDisplay::Flex => taffy::Display::Flex,+ LayoutDisplay::Grid => taffy::Display::Grid,+ LayoutDisplay::Block => taffy::Display::Block,+ _ => unreachable!(),+ },+ size: Size {+ width: length(200.0),+ height: length(100.0),+ },+ overflow: Point {+ x: Overflow::Scroll,+ y: Overflow::Scroll,+ },+ ..Style::default()+ },+ );+ scroller.set_scrollbar_style(+ LayoutScrollbarWidth::Auto,+ LayoutScrollbarGutter::StableBothEdges,+ None,+ );+ styles.0.insert(1, scroller);+ styles.0.insert(+ 2,+ resolved(+ LayoutDisplay::Block,+ Style {+ size: Size {+ width: length(400.0),+ height: percent(1.0),+ },+ min_size: Size {+ width: length(400.0),+ height: Dimension::auto(),+ },+ ..Style::default()+ },+ ),+ );++ let output = build(&source, &mut styles);+ let scroller_metrics = output.element_metrics_for_source(1).unwrap();+ assert_eq!(+ scroller_metrics.client_size,+ moli_layout::LayoutSize::new(170.0, 85.0),+ "{display:?} scrollport"+ );+ let child_id = output.source_output(2).unwrap().principal_box.unwrap();+ let child = output.box_geometry(child_id).unwrap();+ assert_eq!(child.border_box.height, 85.0, "{display:?} child height");+ assert_eq!(child.layout_origin_in_document.x, 15.0);+ }+}++#[test]+fn html_body_overflow_is_propagated_to_the_viewport_only() {+ for (body_overflow, user_scrolls, has_scrollbar) in [+ (Overflow::Hidden, false, false),+ // Synthetic Taffy `Scroll` maps to CSS `auto` at this adapter seam.+ (Overflow::Scroll, true, true),+ // Viewport `clip` maps to hidden: script scrolling remains possible,+ // while direct user scrolling and scrollbar UI stay disabled.+ (Overflow::Clip, false, false),+ ] {+ let source = Source(vec![+ Node::html_element("html", "html", vec![1]),+ Node::html_element("body", "body", vec![2]),+ Node::element("tall", Vec::new()),+ ]);+ let mut styles = Styles::default();+ styles.0.insert(+ 0,+ resolved(+ LayoutDisplay::Block,+ Style {+ size: Size {+ width: Dimension::auto(),+ height: length(100.0),+ },+ overflow: Point {+ x: Overflow::Visible,+ y: Overflow::Visible,+ },+ ..Style::default()+ },+ ),+ );+ styles.0.insert(+ 1,+ resolved(+ LayoutDisplay::Block,+ Style {+ overflow: Point {+ x: body_overflow,+ y: body_overflow,+ },+ ..Style::default()+ },+ ),+ );+ styles+ .0+ .insert(2, fixed_size(LayoutDisplay::Block, 320.0, 480.0));++ let output = build(&source, &mut styles);+ let root_id = output.source_output(0).unwrap().principal_box.unwrap();+ let root_extent = output.scroll_extent(root_id).unwrap();+ assert!(root_extent.is_scroll_container);+ assert_eq!(root_extent.allows_user_scroll_y, user_scrolls);+ assert_eq!(root_extent.vertical_scrollbar.is_some(), has_scrollbar);+ assert!(root_extent.maximum_offset.y > 0.0);++ let body_id = output.source_output(1).unwrap().principal_box.unwrap();+ let body_extent = output.scroll_extent(body_id).unwrap();+ assert!(!body_extent.is_scroll_container);+ assert!(!body_extent.clips_overflow);+ }+}++#[test]+fn display_contents_body_cannot_define_viewport_overflow() {+ // Mirrors css/css-overflow/overflow-body-propagation-003.html: a body+ // without a principal box cannot transfer its overflow to the viewport.+ for (display, expected_user_scroll, expected_scrollbar) in [+ (LayoutDisplay::Contents, true, true),+ (LayoutDisplay::Block, false, false),+ ] {+ let source = Source(vec![+ Node::html_element("html", "html", vec![1]),+ Node::html_element("body", "body", vec![2]),+ Node::element("tall", Vec::new()),+ ]);+ let mut styles = Styles::default();+ styles+ .0+ .insert(0, resolved(LayoutDisplay::Block, Style::default()));+ styles.0.insert(+ 1,+ resolved(+ display,+ Style {+ overflow: Point {+ x: Overflow::Clip,+ y: Overflow::Clip,+ },+ ..Style::default()+ },+ ),+ );+ styles+ .0+ .insert(2, fixed_size(LayoutDisplay::Block, 320.0, 480.0));++ let output = build(&source, &mut styles);+ let root_id = output.source_output(0).unwrap().principal_box.unwrap();+ let root_extent = output.scroll_extent(root_id).unwrap();+ assert_eq!(+ root_extent.allows_user_scroll_y, expected_user_scroll,+ "{display:?} body viewport user-scroll policy"+ );+ assert_eq!(+ root_extent.vertical_scrollbar.is_some(),+ expected_scrollbar,+ "{display:?} body viewport scrollbar policy"+ );+ if display == LayoutDisplay::Block {+ let body_id = output.source_output(1).unwrap().principal_box.unwrap();+ let body_extent = output.scroll_extent(body_id).unwrap();+ assert!(!body_extent.is_scroll_container);+ assert!(!body_extent.clips_overflow);+ }+ }+}++#[test]+fn default_visible_root_reserves_stable_viewport_gutters() {+ for (gutter, expected_x, expected_width) in [+ (LayoutScrollbarGutter::Stable, 0.0, 305.0),+ (LayoutScrollbarGutter::StableBothEdges, 15.0, 290.0),+ ] {+ let source = Source(vec![Node::html_element("html", "html", Vec::new())]);+ let mut styles = Styles::default();+ let mut root = resolved(LayoutDisplay::Block, Style::default());+ root.set_scrollbar_style(LayoutScrollbarWidth::Auto, gutter, None);+ styles.0.insert(0, root);++ let output = build(&source, &mut styles);+ let metrics = output.element_metrics_for_source(0).unwrap();+ assert_eq!(metrics.client_size.width, 320.0);+ let root_id = output.source_output(0).unwrap().principal_box.unwrap();+ let geometry = output.box_geometry(root_id).unwrap();+ assert_eq!(geometry.layout_origin_in_document.x, expected_x);+ assert_eq!(geometry.border_box.width, expected_width);+ }+}+#[test]fn root_stable_gutters_are_reserved_by_the_initial_containing_block_once() {for (content_height, expected_client_width) in [(20.0, 320.0), (480.0, 305.0)] {diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/hit_test.rs b/moli-renderer-v8/src/native_bridge/element/geometry/hit_test.rsindex 6c9dc2510..b6b230f5d 100644--- a/moli-renderer-v8/src/native_bridge/element/geometry/hit_test.rs+++ b/moli-renderer-v8/src/native_bridge/element/geometry/hit_test.rs@@ -1,8 +1,12 @@use moli_layout::{- FrozenLayoutTree, LayoutError, LayoutFlushReason, LayoutHit, LayoutPoint, LayoutQuery,- LayoutQueryAnswer, LayoutQueryBatch, LayoutScrollbarHit, LayoutTransform2D, LayoutViewport,+ FrozenLayoutTree, LayoutControlSurfaceHit, LayoutError, LayoutFlushReason, LayoutHit,+ LayoutPaintedSurfaceHit, LayoutPoint, LayoutQuery, LayoutQueryAnswer, LayoutQueryBatch,+ LayoutTransform2D, LayoutViewport,};+#[cfg(test)]+use moli_layout::LayoutScrollbarHit;+use super::provider::{observable_geometry_batch, observable_hit_test_all, provider_contract_error,};@@ -22,7 +26,7 @@ pub(crate) struct InputHit {#[derive(Clone, Copy, Debug, Default, PartialEq)]pub(crate) struct InputSurfaceHit {pub(crate) input: Option<InputHit>,- pub(crate) scrollbar: Option<LayoutScrollbarHit<DomHandle>>,+ pub(crate) control: Option<LayoutControlSurfaceHit<DomHandle>>,}#[derive(Clone, Copy)]@@ -85,8 +89,12 @@ pub(crate) fn observable_scrollbar_hit_test(document: DomHandle,point: LayoutPoint,) -> Result<Option<LayoutScrollbarHit<DomHandle>>, LayoutError> {- observable_input_surface_hit_test(runtime, document, point, false, true)- .map(|hit| hit.scrollbar)+ observable_input_surface_hit_test(runtime, document, point, false, true).map(|hit| {+ match hit.control {+ Some(LayoutControlSurfaceHit::Scrollbar(scrollbar)) => Some(scrollbar),+ Some(LayoutControlSurfaceHit::ScrollbarCorner(_)) | None => None,+ }+ })}pub(crate) fn observable_input_surface_hit_test(@@ -100,7 +108,7 @@ pub(crate) fn observable_input_surface_hit_test(return input_hit_test_via_documents(runtime, document, point, ignore_pointer_events_none).map(|input| InputSurfaceHit {input,- scrollbar: None,+ control: None,});}@@ -187,17 +195,42 @@ fn input_surface_hit_test_in_tree(include_scrollbars: bool,depth: usize,) -> InputSurfaceHit {- if include_scrollbars && let Some(mut scrollbar) = tree.scrollbar_hit_test(point) {- scrollbar.viewport_to_local = scrollbar.viewport_to_local.concatenate(root_to_frame);- return InputSurfaceHit {- input: None,- scrollbar: Some(scrollbar),- };- }-- let Some((layout_hit, target)) =+ let live_dom_hit = if include_scrollbars {+ let mut live_dom_hit = None;+ for surface in tree.painted_surface_hits(point, ignore_pointer_events_none) {+ match surface {+ LayoutPaintedSurfaceHit::Control(mut control) => {+ match &mut control {+ LayoutControlSurfaceHit::Scrollbar(hit) => {+ hit.viewport_to_local =+ hit.viewport_to_local.concatenate(root_to_frame);+ }+ LayoutControlSurfaceHit::ScrollbarCorner(hit) => {+ hit.viewport_to_local =+ hit.viewport_to_local.concatenate(root_to_frame);+ }+ }+ return InputSurfaceHit {+ input: None,+ control: Some(control),+ };+ }+ LayoutPaintedSurfaceHit::Dom(layout_hit) => {+ let Some(target) = element_for_hit_source(runtime, layout_hit.source) else {+ continue;+ };+ if runtime.dom_host().is_connected(target) {+ live_dom_hit = Some((layout_hit, target));+ break;+ }+ }+ }+ }+ live_dom_hit+ } else {live_hit_in_tree(runtime, tree, point, ignore_pointer_events_none)- else {+ };+ let Some((layout_hit, target)) = live_dom_hit else {return InputSurfaceHit::default();};let target_hit = InputHit {@@ -207,13 +240,13 @@ fn input_surface_hit_test_in_tree(if depth >= CHILD_FRAME_DEPTH_LIMIT {return InputSurfaceHit {input: Some(target_hit),- scrollbar: None,+ control: None,};}let Some(child_tree) = tree.embedded_frame_tree(target) else {return InputSurfaceHit {input: Some(target_hit),- scrollbar: None,+ control: None,};};if runtime@@ -222,19 +255,19 @@ fn input_surface_hit_test_in_tree({return InputSurfaceHit {input: Some(target_hit),- scrollbar: None,+ control: None,};}let Some(content_box) = layout_hit.local_content_box else {return InputSurfaceHit {input: Some(target_hit),- scrollbar: None,+ control: None,};};if !content_box.contains(layout_hit.local_point) {return InputSurfaceHit {input: Some(target_hit),- scrollbar: None,+ control: None,};}let frame_to_child = LayoutTransform2D::translation(-content_box.x, -content_box.y)@@ -248,12 +281,12 @@ fn input_surface_hit_test_in_tree(include_scrollbars,depth + 1,);- if child_hit.input.is_some() || child_hit.scrollbar.is_some() {+ if child_hit.input.is_some() || child_hit.control.is_some() {child_hit} else {InputSurfaceHit {input: Some(target_hit),- scrollbar: None,+ control: None,}}}diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs b/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rsindex 5586ef031..1c2b49d8f 100644--- a/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs+++ b/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs@@ -87,6 +87,7 @@ pub(crate) fn answer_queries(.map(|source| LayoutHit {source,fragment: None,+ paint_order: None,local_point: *point,is_text: false,local_content_box: None,@@ -103,6 +104,7 @@ pub(crate) fn answer_queries(vec![LayoutHit {source,fragment: None,+ paint_order: None,local_point: *point,is_text: false,local_content_box: None,diff --git a/moli-renderer-v8/src/script_vm/input_dispatch.rs b/moli-renderer-v8/src/script_vm/input_dispatch.rsindex 5dee7d78d..f1865eeff 100644--- a/moli-renderer-v8/src/script_vm/input_dispatch.rs+++ b/moli-renderer-v8/src/script_vm/input_dispatch.rs@@ -489,8 +489,18 @@ impl ScriptVm {false,matches!(event_name, "mousedown" | "mouseup" | "mousemove"),)?;- if let Some(scrollbar) = surface_hit.scrollbar {- return self.dispatch_native_scrollbar_hit(scrollbar, event_name, button);+ if let Some(control) = surface_hit.control {+ return match control {+ moli_layout::LayoutControlSurfaceHit::Scrollbar(scrollbar) => {+ self.dispatch_native_scrollbar_hit(scrollbar, event_name, button)+ }+ moli_layout::LayoutControlSurfaceHit::ScrollbarCorner(_) => {+ // The painted corner is user-agent chrome. It owns no+ // scroll action, but must consume input rather than leak+ // pointer/mouse events into the DOM underneath it.+ Ok(input_dispatch_outcome(true))+ }+ };}let hit = surface_hit.input;let hit_handle = hit.map(|hit| hit.handle);diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rsindex 516fc890c..8555fb212 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs@@ -1190,6 +1190,281 @@ fn classic_scrollbar_metrics_and_thumb_drag_match_chromium_without_dom_mouse_eveassert_eq!(result["events"], serde_json::json!([]));}+#[test]+fn painted_overlay_wins_over_scrollbar_and_corner_consumes_input() {+ let mut vm = new_storage_test_vm("https://painted-scrollbar-surface.test/");+ vm.eval(+ r#"+ (() => {+ if (!document.documentElement) {+ document.appendChild(document.createElement("html"));+ }+ if (!document.body) {+ document.documentElement.appendChild(document.createElement("body"));+ }+ document.documentElement.style.margin = "0";+ document.body.style.margin = "0";+ document.body.innerHTML = `+ <div id="scroller" style="position:absolute;left:20px;top:20px;width:200px;height:100px;overflow:scroll">+ <div style="width:400px;height:300px"></div>+ </div>+ <div id="overlay" style="position:absolute;left:200px;top:20px;width:40px;height:100px;z-index:10"></div>`;+ window.__paintedSurfaceEvents = [];+ for (const name of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {+ document.addEventListener(name, event => {+ window.__paintedSurfaceEvents.push(`${name}:${event.target.id || event.target.localName}`);+ }, true);+ }+ })()+ "#,+ )+ .expect("painted surface fixture should initialize");+ refresh_layout_for_test(&mut vm);+ vm.eval("scroller.scrollTop = 80")+ .expect("scroller should move before the overlay probe");++ vm.dispatch_mouse_event_at_point(210.0, 30.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("overlay press should dispatch");+ vm.dispatch_mouse_event_at_point(210.0, 30.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("overlay release should dispatch");+ assert_eq!(+ vm.eval("JSON.stringify([scroller.scrollTop, __paintedSurfaceEvents])")+ .expect("overlay result should evaluate"),+ r#"[80,["pointerdown:overlay","mousedown:overlay","pointerup:overlay","mouseup:overlay","click:overlay"]]"#,+ "a higher painted sibling must occlude the scrollbar beneath it"+ );++ vm.eval(+ r#"+ overlay.style.display = "none";+ window.__paintedSurfaceEvents.length = 0;+ "#,+ )+ .expect("overlay should be removed before the corner probe");+ refresh_layout_for_test(&mut vm);+ let corner = vm+ ._context_host+ .borrow()+ .with_latest_layout_tree_for_document(vm.document_runtime.document_handle(), |tree| {+ tree.control_surface_hit_test(moli_layout::LayoutPoint::new(210.0, 110.0))+ })+ .flatten();+ assert!(+ matches!(+ corner,+ Some(moli_layout::LayoutControlSurfaceHit::ScrollbarCorner(_))+ ),+ "the painted lower-right scrollbar corner should be an input surface: {corner:?}"+ );++ vm.dispatch_mouse_event_at_point(210.0, 110.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("corner press should be consumed");+ vm.dispatch_mouse_event_at_point(210.0, 110.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("corner release should be consumed");+ assert_eq!(+ vm.eval("JSON.stringify([scroller.scrollTop, __paintedSurfaceEvents])")+ .expect("corner result should evaluate"),+ "[80,[]]",+ "the UA scrollbar corner must not fall through into DOM dispatch"+ );+}++#[test]+fn body_overflow_defines_viewport_scrolling_and_default_root_stable_gutters() {+ let mut vm = new_storage_test_vm("https://viewport-overflow-policy.test/");+ vm.set_viewport_surface(Some(crate::protocol_types::ViewportSurface {+ inner_width: 800,+ inner_height: 600,+ outer_width: 800,+ outer_height: 600,+ device_pixel_ratio: 1.0,+ screen_width: 800,+ screen_height: 600,+ screen_avail_width: 800,+ screen_avail_height: 600,+ }))+ .expect("viewport overflow surface should update");+ vm.eval(+ r#"+ (() => {+ if (!document.documentElement) {+ document.appendChild(document.createElement("html"));+ }+ if (!document.body) {+ document.documentElement.appendChild(document.createElement("body"));+ }+ document.documentElement.style.cssText = "margin:0;overflow:visible";+ document.body.style.cssText = "margin:0;overflow:hidden";+ document.body.innerHTML = '<main id="content" style="height:1200px"></main>';+ })()+ "#,+ )+ .expect("viewport overflow fixture should initialize");+ refresh_layout_for_test(&mut vm);+ assert_eq!(+ vm.eval(+ "JSON.stringify([document.documentElement.clientWidth, document.documentElement.scrollHeight, scrollY])"+ )+ .expect("hidden viewport metrics should evaluate"),+ "[800,1200,0]"+ );++ vm.dispatch_mouse_event_at_point(10.0, 10.0, "wheel", -1, Some(0), 0.0, 80.0)+ .expect("hidden viewport wheel should dispatch without scrolling");+ assert_eq!(+ vm.eval("String(scrollY)")+ .expect("hidden viewport wheel result should evaluate"),+ "0"+ );+ vm.eval("scrollTo(0, 100)")+ .expect("hidden viewport should remain script-scrollable");+ assert_eq!(+ vm.eval("String(scrollY)")+ .expect("hidden programmatic scroll should evaluate"),+ "100"+ );++ vm.eval("document.body.style.overflow = 'auto'; scrollTo(0, 0)")+ .expect("body auto should become the viewport policy");+ refresh_layout_for_test(&mut vm);+ assert_eq!(+ vm.eval("String(document.documentElement.clientWidth)")+ .expect("auto viewport width should evaluate"),+ "785"+ );+ vm.dispatch_mouse_event_at_point(10.0, 10.0, "wheel", -1, Some(0), 0.0, 80.0)+ .expect("auto viewport wheel should scroll");+ assert_eq!(+ vm.eval("String(scrollY)")+ .expect("auto viewport wheel result should evaluate"),+ "80"+ );++ vm.eval("document.body.style.overflow = 'clip'")+ .expect("body clip should become hidden at the viewport boundary");+ refresh_layout_for_test(&mut vm);+ vm.eval("scrollTo(0, 100)")+ .expect("clip-derived viewport should remain script-scrollable");+ vm.dispatch_mouse_event_at_point(10.0, 10.0, "wheel", -1, Some(0), 0.0, 80.0)+ .expect("clip-derived viewport wheel should not scroll");+ assert_eq!(+ vm.eval("JSON.stringify([document.documentElement.clientWidth, scrollY])")+ .expect("clip-derived viewport result should evaluate"),+ "[800,100]"+ );++ vm.eval(+ r#"+ document.documentElement.style.cssText =+ "margin:0;overflow:visible;scrollbar-gutter:stable";+ document.body.style.cssText = "margin:0;overflow:visible";+ document.body.innerHTML = "";+ "#,+ )+ .expect("stable viewport gutter fixture should initialize");+ refresh_layout_for_test(&mut vm);+ assert_eq!(+ vm.eval(+ r#"+ JSON.stringify((() => {+ const html = document.documentElement.getBoundingClientRect();+ const body = document.body.getBoundingClientRect();+ return [document.documentElement.clientWidth, html.x, html.width, body.x, body.width];+ })())+ "#,+ )+ .expect("default-visible stable viewport gutter should evaluate"),+ "[800,0,785,0,785]"+ );++ vm.eval("document.documentElement.style.scrollbarGutter = 'stable both-edges'")+ .expect("both-edge stable gutter should apply");+ refresh_layout_for_test(&mut vm);+ assert_eq!(+ vm.eval(+ r#"+ JSON.stringify((() => {+ const html = document.documentElement.getBoundingClientRect();+ const body = document.body.getBoundingClientRect();+ return [document.documentElement.clientWidth, html.x, html.width, body.x, body.width];+ })())+ "#,+ )+ .expect("default-visible both-edge viewport gutter should evaluate"),+ "[800,15,770,15,770]"+ );++ vm.eval(+ r#"+ document.documentElement.style.cssText = "margin:0;overflow:visible";+ document.body.style.cssText = "display:contents;overflow:scroll";+ document.body.innerHTML = "";+ "#,+ )+ .expect("display-contents body fixture should initialize");+ refresh_layout_for_test(&mut vm);+ assert_eq!(+ vm.eval("String(document.documentElement.getBoundingClientRect().width)")+ .expect("display-contents viewport width should evaluate"),+ "800",+ "overflow-body-propagation-003: a body without a principal box cannot define the viewport"+ );++ vm.eval("document.body.style.display = 'block'")+ .expect("principal body fixture should initialize");+ refresh_layout_for_test(&mut vm);+ assert_eq!(+ vm.eval("String(document.documentElement.getBoundingClientRect().width)")+ .expect("principal-body viewport width should evaluate"),+ "785",+ "a principal body with overflow:scroll must define the viewport"+ );+}++#[test]+fn stable_both_edges_horizontal_bar_sizes_percentage_children_in_numeric_layout() {+ let mut vm = new_storage_test_vm("https://both-edges-numeric-layout.test/");+ vm.eval(+ r#"+ (() => {+ if (!document.documentElement) {+ document.appendChild(document.createElement("html"));+ }+ if (!document.body) {+ document.documentElement.appendChild(document.createElement("body"));+ }+ document.documentElement.style.margin = "0";+ document.body.style.margin = "0";+ document.body.innerHTML = ["block", "flex", "grid"].map(display => `+ <div id="${display}" style="display:${display};width:200px;height:100px;overflow:scroll;scrollbar-gutter:stable both-edges">+ <div style="width:100%;height:100%"></div>+ </div>`).join("");+ })()+ "#,+ )+ .expect("both-edge numeric layout fixture should initialize");+ refresh_layout_for_test(&mut vm);++ assert_eq!(+ vm.eval(+ r#"+ JSON.stringify(["block", "flex", "grid"].map(id => {+ const scroller = document.getElementById(id);+ const child = scroller.firstElementChild;+ return [+ scroller.clientWidth,+ scroller.clientHeight,+ child.offsetWidth,+ child.offsetHeight,+ ];+ }))+ "#,+ )+ .expect("both-edge numeric layout metrics should evaluate"),+ "[[170,85,170,85],[170,85,170,85],[170,85,170,85]]"+ );+}+#[test]fn nested_and_sibling_scrollbar_drags_stay_bound_to_the_pressed_scroller() {let mut vm = new_storage_test_vm("https://nested-classic-scrollbar-input.test/");