Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
Implement classic scrollbars
ldm03a8e52ba99bf
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/classic_scrollbar.py b/moli-cdp-smoke/moli_cdp_smoke/groups/classic_scrollbar.pynew file mode 100644index 000000000..aa7509928--- /dev/null+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/classic_scrollbar.py@@ -0,0 +1,410 @@+from __future__ import annotations++from . import SmokeState+from ..assertions import SmokeError, assert_equal+from ..png_image import decode_png+from ..raw_cdp import discover_websocket_url+++async def run_classic_scrollbar_group(state: SmokeState) -> None:+ page = state.page+ cdp = state.cdp+ websocket_url = await discover_websocket_url(state.endpoint)+ is_moli = websocket_url.endswith("/devtools/browser/moli-browser")+ await page.set_content(+ """+ <!doctype html>+ <style>+ html, body { margin: 0; }+ #scroller {+ width: 200px;+ height: 100px;+ overflow: auto;+ scrollbar-color: rgb(255, 0, 0) rgb(0, 0, 255);+ }+ #content { width: 400px; height: 300px; background: rgb(0, 255, 0); }+ .probe { width: 200px; height: 100px; overflow: scroll; }+ #thin { scrollbar-width: thin; }+ #none { scrollbar-width: none; }+ .gutter-probe { width: 200px; height: 100px; overflow: auto; }+ .gutter-probe > div { height: 20px; }+ #stable { scrollbar-gutter: stable; }+ #both-edges { scrollbar-gutter: stable both-edges; }+ #rtl { direction: rtl; scrollbar-color: rgb(255, 0, 0) rgb(0, 0, 255); }+ </style>+ <div id="scroller"><div id="content"></div></div>+ <div id="thin" class="probe"><div></div></div>+ <div id="none" class="probe"><div></div></div>+ <div id="stable" class="gutter-probe"><div></div></div>+ <div id="both-edges" class="gutter-probe"><div></div></div>+ <div id="feedback" class="gutter-probe"><div style="width:200px;height:200px"></div></div>+ <div id="rtl" class="probe"><div style="width:400px;height:300px"></div></div>+ <script>+ thin.firstElementChild.style.cssText = none.firstElementChild.style.cssText =+ "width:400px;height:300px";+ window.__scrollbarDomEvents = [];+ for (const name of [+ "pointerdown", "pointermove", "pointerup",+ "mousedown", "mousemove", "mouseup", "click"+ ]) {+ document.addEventListener(name, () => __scrollbarDomEvents.push(name), true);+ }+ </script>+ """,+ wait_until="domcontentloaded",+ )+ metrics = await page.evaluate(+ """() => [+ scroller.clientWidth, scroller.clientHeight,+ thin.clientWidth, thin.clientHeight,+ none.clientWidth, none.clientHeight,+ scroller.scrollWidth, scroller.scrollHeight,+ stable.clientWidth, stable.clientLeft, stable.firstElementChild.offsetWidth,+ Math.round(stable.firstElementChild.getBoundingClientRect().left),+ document.getElementById("both-edges").clientWidth,+ document.getElementById("both-edges").clientLeft,+ document.getElementById("both-edges").firstElementChild.offsetWidth,+ Math.round(+ document.getElementById("both-edges").firstElementChild.getBoundingClientRect().left+ ),+ feedback.clientWidth, feedback.clientHeight,+ rtl.clientWidth, rtl.clientLeft, rtl.scrollWidth, rtl.scrollLeft,+ ]"""+ )+ assert_equal(+ metrics,+ [+ 185, 85, 190, 90, 200, 100, 400, 300,+ 185, 0, 185, 0, 170, 15, 170, 15,+ 185, 85, 185, 15, 400, 0,+ ],+ "Chromium classic scrollbar client and scroll geometry",+ )++ image = decode_png(await page.screenshot())+ assert_equal(image.pixel(192, 8), (255, 0, 0, 255), "custom up-arrow paint")+ assert_equal(image.pixel(190, 30), (255, 0, 0, 255), "custom vertical thumb paint")+ assert_equal(image.pixel(190, 60), (0, 0, 255, 255), "custom vertical track paint")+ assert_equal(image.pixel(190, 90), (0, 0, 255, 255), "custom scrollbar corner paint")+ assert_equal(image.pixel(192, 508), (139, 139, 139, 255), "default up-arrow paint")+ assert_equal(image.pixel(186, 508), (252, 252, 252, 255), "default button paint")+ assert_equal(image.pixel(5, 620), (255, 0, 0, 255), "RTL vertical thumb paint")++ 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,+ },+ )++ await mouse("mousePressed", 190, 30, pressed=True)+ await mouse("mouseMoved", 190, 50, pressed=True)+ await mouse("mouseReleased", 190, 50, pressed=False)+ await mouse("mousePressed", 50, 90, pressed=True)+ await mouse("mouseMoved", 90, 90, pressed=True)+ await mouse("mouseReleased", 90, 90, pressed=False)++ state_after_drag = await page.evaluate(+ """() => ({+ left: scroller.scrollLeft,+ top: scroller.scrollTop,+ events: __scrollbarDomEvents,+ })"""+ )+ control_scroll = None+ if is_moli:+ if state_after_drag.get("left", 0) <= 50 or state_after_drag.get("top", 0) <= 100:+ raise SmokeError(+ f"classic scrollbar thumb drag did not scroll both axes: {state_after_drag!r}"+ )+ assert_equal(+ state_after_drag.get("events"),+ [],+ "Moli UA scrollbar controls stay outside DOM pointer/mouse dispatch",+ )+ before_controls = float(state_after_drag["top"])+ await mouse("mousePressed", 190, 5, pressed=True)+ await mouse("mouseReleased", 190, 5, pressed=False)+ after_back = float(await page.evaluate("() => scroller.scrollTop"))+ await mouse("mousePressed", 190, 80, pressed=True)+ await mouse("mouseReleased", 190, 80, pressed=False)+ after_forward = float(await page.evaluate("() => scroller.scrollTop"))+ await mouse("mousePressed", 190, 60, pressed=True)+ await mouse("mouseReleased", 190, 60, pressed=False)+ after_track = float(await page.evaluate("() => scroller.scrollTop"))+ control_scroll = [before_controls, after_back, after_forward, after_track]+ expected_track = before_controls + 85 * 0.875+ if (+ abs(after_back - (before_controls - 40)) > 0.01+ or abs(after_forward - before_controls) > 0.01+ or abs(after_track - expected_track) > 0.01+ ):+ raise SmokeError(f"classic scrollbar button/track steps diverged: {control_scroll!r}")+ assert_equal(+ await page.evaluate("() => __scrollbarDomEvents"),+ [],+ "Moli scrollbar button and track stay outside DOM dispatch",+ )+ else:+ # Chromium 145 on Linux/Xvfb routes synthetic raw-CDP mouse input at+ # this painted control through DOM hit testing instead of its native+ # scrollbar widget. Keep that executable comparison explicit while+ # retaining Moli's useful CDP thumb-drag capability above.+ assert_equal(+ [state_after_drag.get("left"), state_after_drag.get("top")],+ [0, 0],+ "Chromium raw-CDP input does not drag the native scrollbar",+ )+ if not state_after_drag.get("events"):+ raise SmokeError(+ "Chromium raw-CDP scrollbar probe should route through DOM mouse events"+ )+ state.record(+ "classic_scrollbar_layout_paint_and_cdp_drag",+ {+ "engine": "moli" if is_moli else "chromium",+ "methods": ["Input.dispatchMouseEvent", "Page.captureScreenshot"],+ "metrics": metrics,+ "scroll": [state_after_drag.get("left"), state_after_drag.get("top")],+ "controlScroll": control_scroll,+ "cdpNativeDrag": is_moli,+ },+ )+ await _run_root_scrollbar_workflow(state, is_moli)+++async def _run_root_scrollbar_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; }+ html { scrollbar-color: rgb(255, 0, 0) rgb(0, 0, 255); }+ </style>+ <div style="width:200vw;height:200vh"></div>+ <script>+ window.__rootScrollbarDomEvents = [];+ for (const name of [+ "pointerdown", "pointermove", "pointerup",+ "mousedown", "mousemove", "mouseup", "click"+ ]) {+ document.addEventListener(name, () => __rootScrollbarDomEvents.push(name), true);+ }+ </script>+ """,+ wait_until="domcontentloaded",+ )+ metrics = await page.evaluate(+ """() => ({+ innerWidth,+ innerHeight,+ clientWidth: document.documentElement.clientWidth,+ clientHeight: document.documentElement.clientHeight,+ scrollWidth: document.documentElement.scrollWidth,+ scrollHeight: document.documentElement.scrollHeight,+ })"""+ )+ assert_equal(+ [+ metrics["innerWidth"] - metrics["clientWidth"],+ metrics["innerHeight"] - metrics["clientHeight"],+ ],+ [15, 15],+ "root classic scrollbar gutters",+ )+ if (+ metrics["scrollWidth"] <= metrics["clientWidth"]+ or metrics["scrollHeight"] <= metrics["clientHeight"]+ ):+ raise SmokeError(f"root scrollbar fixture did not overflow: {metrics!r}")++ image = decode_png(await page.screenshot())+ right = metrics["innerWidth"] - 5+ bottom = metrics["innerHeight"] - 5+ assert_equal(image.pixel(right, 30), (255, 0, 0, 255), "root vertical thumb paint")+ assert_equal(image.pixel(right, 500), (0, 0, 255, 255), "root vertical track paint")+ assert_equal(image.pixel(30, bottom), (255, 0, 0, 255), "root horizontal thumb paint")+ assert_equal(image.pixel(right, bottom), (0, 0, 255, 255), "root scrollbar corner paint")++ scroll = None+ if is_moli:+ x = metrics["innerWidth"] - 5+ y = metrics["innerHeight"] - 5++ async def mouse(event_type: str, mouse_x: int, mouse_y: int, *, pressed: bool) -> None:+ await cdp.send(+ "Input.dispatchMouseEvent",+ {+ "type": event_type,+ "x": mouse_x,+ "y": mouse_y,+ "button": "left" if event_type != "mouseMoved" else "none",+ "buttons": 1 if pressed else 0,+ "clickCount": 1,+ },+ )++ await mouse("mousePressed", x, 30, pressed=True)+ await mouse("mouseMoved", x, 100, pressed=True)+ await mouse("mouseReleased", x, 100, pressed=False)+ await mouse("mousePressed", 30, y, pressed=True)+ await mouse("mouseMoved", 100, y, pressed=True)+ await mouse("mouseReleased", 100, y, pressed=False)+ state_after_drag = await page.evaluate(+ "() => [window.scrollX, window.scrollY, __rootScrollbarDomEvents]"+ )+ if state_after_drag[0] <= 50 or state_after_drag[1] <= 50:+ raise SmokeError(+ f"root scrollbar thumb drag did not scroll both axes: {state_after_drag!r}"+ )+ assert_equal(+ state_after_drag[2],+ [],+ "Moli root scrollbar stays outside DOM pointer/mouse dispatch",+ )+ scroll = state_after_drag[:2]++ state.record(+ "root_classic_scrollbar_layout_and_cdp_drag",+ {"engine": "moli" if is_moli else "chromium", "metrics": metrics, "scroll": scroll},+ )++ await page.set_content(+ """+ <!doctype html>+ <style>+ html, body { margin: 0; height: 100%; }+ #wide { width: 1600px; height: 50%; }+ #fixed {+ position: fixed;+ right: 0;+ bottom: 0;+ width: 10px;+ height: 10px;+ }+ </style>+ <div id="wide"></div><div id="fixed"></div>+ """,+ wait_until="domcontentloaded",+ )+ containing_block = await page.evaluate(+ """() => {+ const html = document.documentElement.getBoundingClientRect();+ const body = document.body.getBoundingClientRect();+ const wide = document.getElementById("wide").getBoundingClientRect();+ const fixed = document.getElementById("fixed").getBoundingClientRect();+ return [+ document.documentElement.clientWidth,+ document.documentElement.clientHeight,+ document.documentElement.scrollWidth,+ document.documentElement.scrollHeight,+ html.x, html.width, html.height,+ body.x, body.width, body.height,+ wide.width, wide.height,+ fixed.x, fixed.y,+ ];+ }"""+ )+ assert_equal(+ containing_block,+ [800, 585, 1600, 585, 0, 800, 585, 0, 800, 585, 1600, 292.5, 790, 575],+ "root scrollbar resizes the initial containing block",+ )++ await page.set_content(+ """+ <!doctype html>+ <style>+ html, body { margin: 0; height: 100%; }+ html { overflow: auto; scrollbar-gutter: stable both-edges; }+ </style>+ <div id="content"></div>+ """,+ wait_until="domcontentloaded",+ )++ async def stable_metrics() -> list[float]:+ return await page.evaluate(+ """() => {+ const html = document.documentElement.getBoundingClientRect();+ const body = document.body.getBoundingClientRect();+ return [+ document.documentElement.clientWidth,+ document.documentElement.clientHeight,+ document.documentElement.scrollWidth,+ document.documentElement.scrollHeight,+ html.x, html.width, body.x, body.width,+ ];+ }"""+ )++ stable_empty = await stable_metrics()+ assert_equal(+ stable_empty,+ [800, 600, 770, 600, 15, 770, 15, 770],+ "empty root stable both-edges gutter",+ )+ await page.set_content(+ """+ <!doctype html>+ <style>+ html, body { margin: 0; height: 100%; }+ html { overflow: auto; scrollbar-gutter: stable both-edges; }+ #content { height: 1200px; }+ </style>+ <div id="content"></div>+ """,+ wait_until="domcontentloaded",+ )+ stable_overflow = await stable_metrics()+ assert_equal(+ stable_overflow,+ [785, 600, 770, 1200, 15, 770, 15, 770],+ "overflowing root stable both-edges gutter",+ )++ await page.set_content(+ """+ <!doctype html>+ <style>+ html, body { margin: 0; height: 100%; }+ html {+ direction: rtl;+ scrollbar-color: rgb(255, 0, 0) rgb(0, 0, 255);+ }+ #content { height: 1200px; }+ </style>+ <div id="content"></div>+ """,+ wait_until="domcontentloaded",+ )+ rtl_image = decode_png(await page.screenshot())+ assert_equal(+ rtl_image.pixel(795, 30),+ (255, 0, 0, 255),+ "RTL root scrollbar remains on the physical right",+ )+ assert_equal(+ rtl_image.pixel(5, 30),+ (255, 255, 255, 255),+ "RTL root does not paint a left-edge viewport scrollbar",+ )+ state.record(+ "root_scrollbar_initial_containing_block_and_gutters",+ {+ "engine": "moli" if is_moli else "chromium",+ "containingBlock": containing_block,+ "stableEmpty": stable_empty,+ "stableOverflow": stable_overflow,+ "rtlScrollbarSide": "right",+ },+ )diff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.pyindex 91d375e09..29c65fd26 100644--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py@@ -21,6 +21,7 @@ from .groups.action_window import run_action_window_groupfrom .groups.agent_browser import run_agent_browser_groupfrom .groups.agent_episode import run_agent_episode_groupfrom .groups.browser_semantics import run_browser_semantics_group, run_target_semantics_group+from .groups.classic_scrollbar import run_classic_scrollbar_groupfrom .groups.cdp_use import run_cdp_use_groupfrom .groups.chrome_remote_interface import run_chrome_remote_interface_groupfrom .groups.chromium_cdp import run_chromium_cdp_group, run_computed_style_group@@ -155,6 +156,12 @@ RAW_GROUPS: tuple[SmokeGroup, ...] = ()PAGE_GROUPS: tuple[SmokeGroup, ...] = (+ SmokeGroup(+ "classic-scrollbar",+ "Cross-engine classic scrollbar layout, paint, and raw CDP thumb dragging.",+ "page",+ run_classic_scrollbar_group,+ ),SmokeGroup("xhr-sync-semantics","Cross-engine Chromium/WPT synchronous XHR events, restrictions, failures, reset, and CDP Network projection.",diff --git a/moli-core/tests/web_apis.rs b/moli-core/tests/web_apis.rsindex bfc696729..18afe945c 100644--- a/moli-core/tests/web_apis.rs+++ b/moli-core/tests/web_apis.rs@@ -5827,7 +5827,7 @@ async fn root_client_metrics_track_window_surface_profile() -> Result<()> {assert_eq!(snapshot,Some(- r#"{"innerWidth":1920,"innerHeight":1080,"documentElementClientWidth":1920,"documentElementClientHeight":1080,"bodyClientWidth":1904,"bodyClientHeight":19,"documentElementRectWidth":1920,"documentElementRectHeight":19}"#+ r#"{"innerWidth":1920,"innerHeight":1080,"documentElementClientWidth":1920,"documentElementClientHeight":1080,"bodyClientWidth":1904,"bodyClientHeight":19,"documentElementRectWidth":1920,"documentElementRectHeight":35}"#));diff --git a/moli-layout/src/capture.rs b/moli-layout/src/capture.rsindex 0d97ab79e..fe3e29bfc 100644--- a/moli-layout/src/capture.rs+++ b/moli-layout/src/capture.rs@@ -24,6 +24,13 @@ pub struct PaintCaptureRequest {pub region: PaintCaptureRegion,/// Whether CSS background colors and images are included in paint.pub include_backgrounds: bool,+ /// Whether compositor-owned viewport controls are included in this capture.+ ///+ /// A bounded CDP clip can still capture the live viewport surface, while a+ /// capture-beyond-viewport clip paints page content only. Keep that+ /// distinction outside [`PaintCaptureRegion`], because both use the same+ /// document-coordinate raster rectangle.+ pub include_viewport_controls: bool,/// Maximum encoded image width in device pixels.pub max_width: Option<u32>,/// Maximum encoded image height in device pixels.@@ -36,6 +43,7 @@ impl PaintCaptureRequest {Self {region: PaintCaptureRegion::Viewport,include_backgrounds: true,+ include_viewport_controls: true,max_width: None,max_height: None,}@@ -46,6 +54,7 @@ impl PaintCaptureRequest {Self {region: PaintCaptureRegion::Viewport,include_backgrounds: true,+ include_viewport_controls: true,max_width,max_height,}@@ -56,6 +65,7 @@ impl PaintCaptureRequest {Self {region: PaintCaptureRegion::FullDocument,include_backgrounds: true,+ include_viewport_controls: false,max_width: None,max_height: None,}@@ -66,6 +76,7 @@ impl PaintCaptureRequest {Self {region: PaintCaptureRegion::PageClip { rect, scale },include_backgrounds: true,+ include_viewport_controls: false,max_width: None,max_height: None,}@@ -110,6 +121,10 @@ pub(crate) struct ResolvedPaintCapture {pub(crate) viewport_to_surface: LayoutTransform2D,pub(crate) surface: PaintCaptureSurface,pub(crate) include_backgrounds: bool,+ /// Viewport captures include the root viewport's native controls. Full+ /// document and page-clip captures paint page content only, matching+ /// Chromium's compositor capture behavior.+ pub(crate) paint_root_scrollbars: bool,}impl PaintCaptureRequest {@@ -120,6 +135,7 @@ impl PaintCaptureRequest {content_size: LayoutSize,) -> Result<ResolvedPaintCapture, LayoutError> {validate_viewport(viewport)?;+ let paint_root_scrollbars = self.include_viewport_controls;let (viewport_rect, capture_scale) = match self.region {PaintCaptureRegion::Viewport => (LayoutRect::new(@@ -184,6 +200,7 @@ impl PaintCaptureRequest {device_scale,),include_backgrounds: self.include_backgrounds,+ paint_root_scrollbars,})}}@@ -271,6 +288,7 @@ mod tests {.map_point(LayoutPoint::new(-10.0, -25.0)),LayoutPoint::ZERO);+ assert!(!capture.paint_root_scrollbars);}#[test]@@ -281,6 +299,7 @@ mod tests {scale: 1.5,},include_backgrounds: true,+ include_viewport_controls: false,max_width: Some(500),max_height: Some(200),}@@ -296,6 +315,20 @@ mod tests {LayoutRect::new(100.0, 200.0, 200.0, 100.0));assert_eq!(capture.surface, PaintCaptureSurface::new(200.0, 100.0, 2.0));+ assert!(!capture.paint_root_scrollbars);+ }++ #[test]+ fn viewport_capture_includes_root_scrollbars() {+ let capture = PaintCaptureRequest::viewport()+ .resolve(+ LayoutViewport::new(800, 600, 1.0),+ LayoutPoint::ZERO,+ LayoutSize::new(1200.0, 900.0),+ )+ .expect("viewport capture");++ assert!(capture.paint_root_scrollbars);}#[test]diff --git a/moli-layout/src/layout_tree/hit_test.rs b/moli-layout/src/layout_tree/hit_test.rsindex 12f1f13c5..0918a57e3 100644--- a/moli-layout/src/layout_tree/hit_test.rs+++ b/moli-layout/src/layout_tree/hit_test.rs@@ -6,6 +6,7 @@ use super::{model::{LayoutBoxModel, LayoutClipChainId, LayoutCoordinateSpaceId, LayoutFragmentId,LayoutFragmentKind, LayoutOutputBoxId, LayoutPoint, LayoutQuad, LayoutRect,+ LayoutTransform2D,},tree::FrozenLayoutTree,};@@ -88,6 +89,70 @@ 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.+ 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))+ })+ .collect::<Vec<_>>();+ candidates.sort_by_key(|candidate| candidate.0);++ for (_, index, source) in candidates {+ 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) {+ continue;+ }+ let local_to_viewport = if is_root {+ LayoutTransform2D::IDENTITY+ } else {+ layout_box.coordinate_space.local_to_viewport+ };+ let Some(viewport_to_local) = local_to_viewport.inverse() else {+ continue;+ };+ let local_point = viewport_to_local.map_point(viewport_point);+ for scrollbar in [+ layout_box.scroll_extent.vertical_scrollbar,+ layout_box.scroll_extent.horizontal_scrollbar,+ ] {+ let Some(scrollbar) = scrollbar else {+ continue;+ };+ let Some(part) = scrollbar.part_at(local_point) else {+ continue;+ };+ return Some(crate::LayoutScrollbarHit {+ source,+ scrollbar,+ part,+ local_point,+ viewport_to_local,+ });+ }+ }+ None+ }+pub fn caret_position(&self, viewport_point: LayoutPoint) -> Option<LayoutCaretPosition<N>> {let entries = self.hit_test_entries();let top_entry = entriesdiff --git a/moli-layout/src/layout_tree/model.rs b/moli-layout/src/layout_tree/model.rsindex a6aed75c2..197a24ad0 100644--- a/moli-layout/src/layout_tree/model.rs+++ b/moli-layout/src/layout_tree/model.rs@@ -304,6 +304,12 @@ pub struct LayoutScrollExtent {pub allows_user_scroll_x: bool,pub allows_user_scroll_y: bool,pub clips_overflow: bool,+ /// Classic scrollbar controls. Geometry is canonical and consumed by both+ /// paint and input hit testing.+ pub horizontal_scrollbar: Option<crate::LayoutScrollbarGeometry>,+ pub vertical_scrollbar: Option<crate::LayoutScrollbarGeometry>,+ pub scrollbar_corner: Option<LayoutRect>,+ pub scrollbar_colors: Option<crate::LayoutScrollbarColors>,}/// Geometry retained for one tree-local box.diff --git a/moli-layout/src/layout_tree/source_query.rs b/moli-layout/src/layout_tree/source_query.rsindex 29651dd05..1be7351d4 100644--- a/moli-layout/src/layout_tree/source_query.rs+++ b/moli-layout/src/layout_tree/source_query.rs@@ -121,21 +121,26 @@ where}).unwrap_or(geometry.layout_origin_in_document);let client_size = if is_root {+ // CSSOM defines root client dimensions from the viewport and only+ // subtracts an actually-present viewport scrollbar. Stable empty+ // gutters still reduce root layout/scrollWidth, but not+ // documentElement.clientWidth/clientHeight.LayoutSize::new(- self.viewport.css_width as f32,- self.viewport.css_height as f32,+ (self.viewport.css_width as f32+ - extent+ .vertical_scrollbar+ .map_or(0.0, |scrollbar| scrollbar.frame.width))+ .max(0.0),+ (self.viewport.css_height as f32+ - extent+ .horizontal_scrollbar+ .map_or(0.0, |scrollbar| scrollbar.frame.height))+ .max(0.0),)} else {- LayoutSize::new(geometry.padding_box.width, geometry.padding_box.height)- };- let scroll_size = if is_root {- LayoutSize::new(- extent.scroll_size.width.max(self.content_size.width),- extent.scroll_size.height.max(self.content_size.height),- )- } else {- extent.scroll_size+ LayoutSize::new(extent.scrollport.width, extent.scrollport.height)};+ let scroll_size = extent.scroll_size;Some(LayoutElementMetrics {offset_parent,offset_position: LayoutPoint::new(@@ -146,16 +151,28 @@ wherecontent_size: LayoutSize::new(geometry.content_box.width, geometry.content_box.height),client_size,client_border: LayoutPoint::new(- geometry.padding_box.x - geometry.border_box.x,- geometry.padding_box.y - geometry.border_box.y,+ if is_root {+ 0.0+ } else {+ extent.scrollport.x - geometry.border_box.x+ },+ if is_root {+ 0.0+ } else {+ extent.scrollport.y - geometry.border_box.y+ },),scroll_size,scroll_offset: extent.applied_offset,minimum_scroll_offset: extent.minimum_offset,maximum_scroll_offset: extent.maximum_offset,- scrollport: coordinate_space- .local_to_viewport- .map_rect(extent.scrollport),+ scrollport: if is_root {+ LayoutTransform2D::IDENTITY.map_rect(extent.scrollport)+ } else {+ coordinate_space+ .local_to_viewport+ .map_rect(extent.scrollport)+ },scrollable_overflow: coordinate_space.local_to_viewport.map_rect(extent.scrollable_overflow),diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rsindex 09a01f782..d4871e891 100644--- a/moli-layout/src/lib.rs+++ b/moli-layout/src/lib.rs@@ -26,6 +26,7 @@ mod pass;mod positioned;mod projection;mod replaced;+mod scrollbar;mod snapshot;mod source;mod stacking;@@ -62,6 +63,10 @@ pub use pass::{EmbeddedFrameRenderer, LayoutPassRequest, ScreenshotLayoutRequest, build_layout_pass,build_layout_pass_with_embedded_frames, build_screenshot_snapshot,};+pub use scrollbar::{+ LayoutScrollbarAxis, LayoutScrollbarColors, LayoutScrollbarGeometry, LayoutScrollbarGutter,+ LayoutScrollbarHit, LayoutScrollbarPart, LayoutScrollbarWidth,+};pub use snapshot::{PaintBlendMode, PaintBorderColors, PaintBorderStyle, PaintBorderStyles, PaintBoxShadow,PaintBrush, PaintColor, PaintCompositeMode, PaintConicGradient, PaintCornerRadii,diff --git a/moli-layout/src/paint/mod.rs b/moli-layout/src/paint/mod.rsindex 25f5c3fda..1b4b7cd99 100644--- a/moli-layout/src/paint/mod.rs+++ b/moli-layout/src/paint/mod.rs@@ -6,6 +6,7 @@ mod geometry;mod image;mod inline_boxes;mod mask;+mod scrollbar;mod table;mod text;@@ -19,6 +20,7 @@ use geometry::{BoxAreas, BoxModelBox, canonical_shape, inset_radii};use image::project_replaced_image;use inline_boxes::project_inline_box_fragments;use mask::{CssMaskPlan, inspect_css_mask, project_css_mask};+use scrollbar::project_scrollbars;use style::values::generics::image::GenericImage;use table::project_collapsed_table_borders;use text::{TextClipMaskScope, project_text, project_text_clip_mask};@@ -298,6 +300,14 @@ wherepop_clips(clip_count, &mut snapshot);}PaintOrderEvent::BoxOutline(id) => {+ if id != projection.world.root || capture.paint_root_scrollbars {+ let scrollbar_clip = (id != projection.world.root)+ .then_some(projection.background_clips[id.index()])+ .flatten();+ let clip_count = push_clip_chain(projection, scrollbar_clip, &mut snapshot);+ project_scrollbars(projection, id, &mut snapshot);+ pop_clips(clip_count, &mut snapshot);+ }let clip_count = push_clip_chain(projection,projection.background_clips[id.index()],diff --git a/moli-layout/src/paint/scrollbar.rs b/moli-layout/src/paint/scrollbar.rsnew file mode 100644index 000000000..bdb389b2b--- /dev/null+++ b/moli-layout/src/paint/scrollbar.rs@@ -0,0 +1,253 @@+use std::{fmt::Debug, hash::Hash};++use crate::{+ LayoutBoxId, LayoutPoint, LayoutRect, LayoutScrollbarAxis, LayoutScrollbarGeometry, PaintBrush,+ PaintColor, PaintCornerRadii, PaintCornerRadius, PaintFragment, PaintPath, PaintPathElement,+ PaintShape, PaintSnapshot,+ projection::{OutputProjection, PaintSpace},+};++const DEFAULT_TRACK: PaintColor = PaintColor::new(252.0 / 255.0, 252.0 / 255.0, 252.0 / 255.0, 1.0);+const DEFAULT_THUMB: PaintColor = PaintColor::new(139.0 / 255.0, 139.0 / 255.0, 139.0 / 255.0, 1.0);+const FLUENT_BUTTON_LENGTH: f32 = 18.0;+const FLUENT_ARROW_SIDE: f32 = 9.0;++pub(super) fn project_scrollbars<N>(+ projection: &OutputProjection<'_, N>,+ id: LayoutBoxId,+ snapshot: &mut PaintSnapshot,+) where+ N: Copy + Debug + Eq + Hash,+{+ let index = id.index();+ if !projection.world.boxes[index].style.is_visible() {+ return;+ }+ let extent = &projection.scroll_extents[index];+ let colors = extent.scrollbar_colors;+ let track = colors.map_or(DEFAULT_TRACK, |colors| colors.track);+ let thumb = colors.map_or(DEFAULT_THUMB, |colors| colors.thumb);+ let paint_space = if id == projection.world.root {+ PaintSpace::ROOT.with_outer_transform(snapshot.viewport_to_surface)+ } else {+ let geometry = &projection.boxes[index];+ projection.coordinate_spaces[geometry.coordinate_space.index()]+ .paint_space(snapshot.viewport_to_surface)+ };++ for scrollbar in [extent.horizontal_scrollbar, extent.vertical_scrollbar]+ .into_iter()+ .flatten()+ {+ paint_rect(snapshot, paint_space, scrollbar.frame, track);+ paint_thumb(snapshot, paint_space, scrollbar, thumb);+ paint_button_arrow(snapshot, paint_space, scrollbar, false, thumb);+ paint_button_arrow(snapshot, paint_space, scrollbar, true, thumb);+ }+ if let Some(corner) = extent.scrollbar_corner {+ paint_rect(snapshot, paint_space, corner, track);+ }+}++fn paint_thumb(+ snapshot: &mut PaintSnapshot,+ paint_space: PaintSpace,+ scrollbar: LayoutScrollbarGeometry,+ color: PaintColor,+) {+ let rect = scrollbar.painted_thumb;+ if rect.width <= 0.0 || rect.height <= 0.0 {+ return;+ }+ let rect = paint_space.pre_transform_rect(rect);+ snapshot.push_fragment(PaintFragment::Fill {+ shape: PaintShape::RoundedRect {+ rect,+ // NativeThemeFluent uses an intentionally oversized radius and+ // lets Skia normalize it to the largest possible pill.+ radii: PaintCornerRadii::all(PaintCornerRadius::new(999.0, 999.0)),+ },+ brush: PaintBrush::Solid(color),+ transform: paint_space.property_transform(),+ });+}++fn paint_button_arrow(+ snapshot: &mut PaintSnapshot,+ paint_space: PaintSpace,+ scrollbar: LayoutScrollbarGeometry,+ forward: bool,+ color: PaintColor,+) {+ let button = if forward {+ scrollbar.forward_button+ } else {+ scrollbar.back_button+ };+ let Some(path) = fluent_arrow_path(+ paint_space.pre_transform_rect(button),+ scrollbar.axis,+ forward,+ ) else {+ return;+ };+ snapshot.push_fragment(PaintFragment::Fill {+ shape: PaintShape::Path(path),+ brush: PaintBrush::Solid(color),+ transform: paint_space.property_transform(),+ });+}++/// Ports NativeThemeFluent::GetArrowRect and NativeThemeBase::PathForArrow.+fn fluent_arrow_path(+ button: LayoutRect,+ axis: LayoutScrollbarAxis,+ forward: bool,+) -> Option<PaintPath> {+ if button.width <= 0.0 || button.height <= 0.0 {+ return None;+ }+ let min_side = button.width.min(button.height).round();+ let max_side = button.width.max(button.height).round();+ let scale = max_side / FLUENT_BUTTON_LENGTH;+ let mut side = (FLUENT_ARROW_SIDE * scale).ceil().min(min_side);+ let difference = min_side - side;+ if difference.rem_euclid(2.0) >= 1.0 {+ side += 1.0;+ }+ if side <= 0.0 {+ return None;+ }++ let mut arrow = LayoutRect::new(+ (button.x + (button.width - side) / 2.0).floor(),+ (button.y + (button.height - side) / 2.0).floor(),+ side,+ side,+ );+ let direction = if forward { 1.0 } else { -1.0 };+ let offset = (direction * scale).round();+ match axis {+ LayoutScrollbarAxis::Horizontal => arrow.x += offset,+ LayoutScrollbarAxis::Vertical => arrow.y += offset,+ }++ let half = side / 2.0;+ let (mut first, mut second, mut tip) = match axis {+ LayoutScrollbarAxis::Vertical => {+ let arrow_height = (side.round() / 2.0).floor() + 1.0;+ let base_y = arrow.bottom() - (arrow_height / 2.0).floor() + 1.0;+ (+ LayoutPoint::new(arrow.x, base_y),+ LayoutPoint::new(arrow.right(), base_y),+ LayoutPoint::new(arrow.x + half, base_y - arrow_height),+ )+ }+ LayoutScrollbarAxis::Horizontal => {+ let arrow_width = (side.round() / 2.0).floor() + 1.0;+ let base_x = arrow.x + (arrow_width / 2.0).floor();+ (+ LayoutPoint::new(base_x, arrow.y),+ LayoutPoint::new(base_x, arrow.bottom()),+ LayoutPoint::new(base_x + arrow_width, arrow.y + half),+ )+ }+ };+ if matches!(axis, LayoutScrollbarAxis::Vertical) && forward {+ let center = arrow.y + half;+ for point in [&mut first, &mut second, &mut tip] {+ point.y = center * 2.0 - point.y;+ }+ } else if matches!(axis, LayoutScrollbarAxis::Horizontal) && !forward {+ let center = arrow.x + half;+ for point in [&mut first, &mut second, &mut tip] {+ point.x = center * 2.0 - point.x;+ }+ }+ Some(PaintPath {+ elements: vec![+ PaintPathElement::MoveTo(first),+ PaintPathElement::LineTo(second),+ PaintPathElement::LineTo(tip),+ PaintPathElement::Close,+ ],+ bounds: arrow,+ })+}++fn paint_rect(+ snapshot: &mut PaintSnapshot,+ paint_space: PaintSpace,+ rect: LayoutRect,+ color: PaintColor,+) {+ if rect.width <= 0.0 || rect.height <= 0.0 || color.alpha <= 0.0 {+ return;+ }+ snapshot.push_fragment(PaintFragment::Fill {+ shape: PaintShape::Rect(paint_space.pre_transform_rect(rect)),+ brush: PaintBrush::Solid(color),+ transform: paint_space.property_transform(),+ });+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn fallback_arrow_paths_match_chromiums_fluent_geometry() {+ let vertical_button = LayoutRect::new(0.0, 0.0, 15.0, 18.0);+ assert_arrow(+ fluent_arrow_path(vertical_button, LayoutScrollbarAxis::Vertical, false).unwrap(),+ LayoutRect::new(3.0, 3.0, 9.0, 9.0),+ [+ LayoutPoint::new(3.0, 11.0),+ LayoutPoint::new(12.0, 11.0),+ LayoutPoint::new(7.5, 6.0),+ ],+ );+ assert_arrow(+ fluent_arrow_path(vertical_button, LayoutScrollbarAxis::Vertical, true).unwrap(),+ LayoutRect::new(3.0, 5.0, 9.0, 9.0),+ [+ LayoutPoint::new(3.0, 6.0),+ LayoutPoint::new(12.0, 6.0),+ LayoutPoint::new(7.5, 11.0),+ ],+ );++ let horizontal_button = LayoutRect::new(0.0, 0.0, 18.0, 15.0);+ assert_arrow(+ fluent_arrow_path(horizontal_button, LayoutScrollbarAxis::Horizontal, false).unwrap(),+ LayoutRect::new(3.0, 3.0, 9.0, 9.0),+ [+ LayoutPoint::new(10.0, 3.0),+ LayoutPoint::new(10.0, 12.0),+ LayoutPoint::new(5.0, 7.5),+ ],+ );+ assert_arrow(+ fluent_arrow_path(horizontal_button, LayoutScrollbarAxis::Horizontal, true).unwrap(),+ LayoutRect::new(5.0, 3.0, 9.0, 9.0),+ [+ LayoutPoint::new(7.0, 3.0),+ LayoutPoint::new(7.0, 12.0),+ LayoutPoint::new(12.0, 7.5),+ ],+ );+ }++ fn assert_arrow(path: PaintPath, bounds: LayoutRect, points: [LayoutPoint; 3]) {+ assert_eq!(path.bounds, bounds);+ assert_eq!(+ path.elements,+ vec![+ PaintPathElement::MoveTo(points[0]),+ PaintPathElement::LineTo(points[1]),+ PaintPathElement::LineTo(points[2]),+ PaintPathElement::Close,+ ]+ );+ }+}diff --git a/moli-layout/src/pass.rs b/moli-layout/src/pass.rsindex b9a89f92d..84650ee22 100644--- a/moli-layout/src/pass.rs+++ b/moli-layout/src/pass.rs@@ -1,8 +1,12 @@use crate::{- DocumentLayoutServices, LayoutError, LayoutFlushReason, LayoutPassResult, LayoutSource,- LayoutStyleResolver, LayoutViewport, PaintCaptureRequest, PaintSnapshot, PaintViewport,- build_layout_world, form::prepare_form_controls, inline::prepare_inline_contexts,- list::prepare_list_markers, projection::finish_layout_pass, taffy_tree::compute_world_layout,+ DocumentLayoutServices, LayoutError, LayoutFlushReason, LayoutPassResult, LayoutScrollbarAxis,+ LayoutSource, LayoutStyleResolver, LayoutViewport, PaintCaptureRequest, PaintSnapshot,+ PaintViewport, build_layout_world,+ form::prepare_form_controls,+ inline::prepare_inline_contexts,+ list::prepare_list_markers,+ projection::{finish_layout_pass, overflowing_axes},+ taffy_tree::compute_world_layout,};use std::collections::HashMap;use std::time::Instant;@@ -168,7 +172,7 @@ whereprepare_list_markers(&mut world);prepare_form_controls(&mut world);prepare_inline_contexts(&mut world, services);- compute_world_layout(&mut world, request.viewport);+ compute_world_layout_with_scrollbars(&mut world, request.viewport);let mut embedded_frames = HashMap::new();if request.requests_paint() {for index in 0..world.boxes.len() {@@ -217,6 +221,79 @@ where)}+/// Resolves `overflow:auto` with the same monotonic feedback loop used by+/// classic browser scrollbars: lay out without an automatic gutter, reveal+/// every axis that overflows, then repeat because one gutter can make the+/// perpendicular axis overflow. Each axis changes at most once.+fn compute_world_layout_with_scrollbars<N>(+ world: &mut crate::LayoutWorld<N>,+ viewport: LayoutViewport,+) where+ N: Copy + std::fmt::Debug + Eq + std::hash::Hash,+{+ let root = world.root.index();+ for (index, layout_box) in world.boxes.iter_mut().enumerate() {+ layout_box.style.prepare_scrollbar_layout(index == root);+ }++ loop {+ compute_world_layout(world, viewport);+ let overflow = overflowing_axes(world, viewport);+ let mut changed = false;+ for (index, ((overflow_x, overflow_y), layout_box)) in+ overflow.into_iter().zip(world.boxes.iter_mut()).enumerate()+ {+ let is_root = index == root;+ changed |= layout_box.style.reveal_auto_scrollbar(+ LayoutScrollbarAxis::Horizontal,+ is_root,+ overflow_x,+ );+ changed |= layout_box.style.reveal_auto_scrollbar(+ LayoutScrollbarAxis::Vertical,+ is_root,+ overflow_y,+ );+ }+ if !changed {+ break;+ }+ }+ offset_leading_scrollbar_gutter_children(world);+}++/// Taffy's scalar scrollbar reservation shrinks the available inline size but+/// always leaves its origin at zero. Move direct numeric children into a+/// physical leading gutter (RTL classic bars and `both-edges`) after the final+/// layout, preserving all of Taffy's percentage and flex/grid sizing work.+fn offset_leading_scrollbar_gutter_children<N>(world: &mut crate::LayoutWorld<N>)+where+ N: Copy + std::fmt::Debug + Eq + std::hash::Hash,+{+ let root = world.root;+ let offsets = world+ .boxes+ .iter()+ .map(|layout_box| {+ layout_box.layout_parent.map_or(0.0, |parent| {+ if parent == root {+ // The synthetic initial containing block already places+ // the root and its descendants after a root leading+ // gutter.+ 0.0+ } else {+ world.boxes[parent.index()]+ .style+ .scrollbar_leading_gutter_thickness(LayoutScrollbarAxis::Vertical, false)+ }+ })+ })+ .collect::<Vec<_>>();+ for (layout_box, offset) in world.boxes.iter_mut().zip(offsets) {+ layout_box.final_layout.location.x += offset;+ }+}+fn css_viewport_dimension(value: f32) -> u32 {if !value.is_finite() {return 0;diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rsindex b8be32019..0a6cbe87e 100644--- a/moli-layout/src/projection.rs+++ b/moli-layout/src/projection.rs@@ -10,8 +10,9 @@ use crate::{LayoutBoxGeometry, LayoutBoxId, LayoutClipChainId, LayoutClipNode, LayoutCoordinateSpaceId,LayoutError, LayoutFlushReason, LayoutFragment, LayoutFragmentBoxModel, LayoutFragmentId,LayoutFragmentKind, LayoutOutputBoxId, LayoutPassMetrics, LayoutPassResult, LayoutPoint,- LayoutRect, LayoutScrollExtent, LayoutSize, LayoutTransform2D, LayoutViewport, LayoutWorld,- PaintCaptureRequest, PaintDiagnostic, PaintDiagnosticSeverity,+ LayoutRect, LayoutScrollExtent, LayoutScrollbarAxis, LayoutScrollbarGeometry, LayoutSize,+ LayoutTransform2D, LayoutViewport, LayoutWorld, PaintCaptureRequest, PaintDiagnostic,+ PaintDiagnosticSeverity,};pub(crate) fn finish_layout_pass<N>(@@ -81,6 +82,31 @@ where))}+/// Samples overflow from the same projection that will freeze scroll extents.+/// This keeps `overflow:auto` discovery correct for positioned descendants,+/// transforms, and nested clips without maintaining a second approximation.+pub(crate) fn overflowing_axes<N>(+ world: &LayoutWorld<N>,+ viewport: LayoutViewport,+) -> Vec<(bool, bool)>+where+ N: Copy + Debug + Eq + Hash,+{+ let mut projection = OutputProjection::new(world, viewport);+ projection.build_local_box_geometry();+ projection.resolve_scrollable_overflow();+ projection+ .scroll_extents+ .into_iter()+ .map(|extent| {+ (+ extent.maximum_offset.x - extent.minimum_offset.x > f32::EPSILON,+ extent.maximum_offset.y - extent.minimum_offset.y > f32::EPSILON,+ )+ })+ .collect()+}+/// Blink-like linear paint space for one projected coordinate space.////// Chromium describes this space as the combination of a transform and a@@ -235,6 +261,7 @@ where));}let id = LayoutOutputBoxId::from_index(index);+ let is_root = index == self.world.root.index();let layout = layout_box.final_layout;let border_box = LayoutRect::new(0.0,@@ -249,13 +276,27 @@ wherelayout.border.bottom,layout.border.left,);- let content_box = inset_rect(+ 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 mut content_box = inset_rect(padding_box,layout.padding.top,layout.padding.right,layout.padding.bottom,layout.padding.left,);+ if !is_root {+ content_box.width = (content_box.width - vertical_gutter).max(0.0);+ content_box.height = (content_box.height - horizontal_gutter).max(0.0);+ content_box.x += vertical_leading_gutter;+ }let margin_box = outset_rect(border_box,layout.margin.top,@@ -277,21 +318,48 @@ wherePaintDiagnosticSeverity::Warning,));}- // Scrollable overflow starts at the padding box. The box's own border is visual- // geometry, not descendant content that can be reached by scrolling. Taffy's- // `content_size` is measured from the padding-box origin and already includes the- // end padding, so keep that coordinate space when projecting its extent.- let mut overflow = padding_box;- let content_extent = LayoutRect::new(- padding_box.x,- padding_box.y,- padding_box.width.max(layout.content_size.width).max(0.0),- padding_box.height.max(layout.content_size.height).max(0.0),+ let local_scrollport = scrollport_for_box(+ is_root,+ self.viewport,+ padding_box,+ vertical_gutter,+ vertical_leading_gutter,+ horizontal_gutter,+ );+ // Scrollable overflow starts at the padding-derived scrollport. A+ // box's own border is visual geometry, not reachable descendant+ // content, while starting after reserved gutters keeps a+ // perpendicular scrollbar from manufacturing overflow on its own.+ // Taffy's content_size is expressed from the padding edge and+ // equals CSSOM scrollWidth/scrollHeight when it is larger than the+ // client area.+ let mut overflow = LayoutRect::new(+ local_scrollport.x,+ local_scrollport.y,+ local_scrollport+ .width+ .max(layout.content_size.width)+ .max(0.0),+ local_scrollport+ .height+ .max(layout.content_size.height)+ .max(0.0),);- overflow = overflow.union(content_extent);+ if is_root {+ // The synthetic viewport has already removed root gutters,+ // so the root's own used padding box can safely contribute+ // without manufacturing perpendicular overflow.+ overflow = overflow.union(padding_box);+ }if let Some(context) = layout_box.inline_layout.as_ref() {let origin = LayoutPoint::new(- layout.border.left + layout.padding.left,+ layout.border.left+ + layout.padding.left+ + if is_root {+ 0.0+ } else {+ vertical_leading_gutter+ },layout.border.top + layout.padding.top,);for line in &context.fragments.lines {@@ -397,23 +465,43 @@ wherelet 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 rtl =+ self.world.boxes[index].style.direction() == crate::style::InlineDirection::Rtl;+ let local_scrollport = scrollport_for_box(+ is_root,+ self.viewport,+ geometry.padding_box,+ vertical_gutter,+ vertical_leading_gutter,+ horizontal_gutter,+ );let scrollport = if is_root {LayoutRect::new(+ vertical_leading_gutter,0.0,- 0.0,- self.viewport.css_width as f32,- self.viewport.css_height as f32,+ local_scrollport.width,+ local_scrollport.height,)} else {- geometry.padding_box+ local_scrollport};let scroll_size = LayoutSize::new(- scrollport+ local_scrollport.width- .max((overflow.right() - scrollport.x).max(0.0)),- scrollport+ .max((overflow.right() - local_scrollport.x).max(0.0)),+ local_scrollport.height- .max((overflow.bottom() - scrollport.y).max(0.0)),+ .max((overflow.bottom() - local_scrollport.y).max(0.0)),);let horizontal_range = (scroll_size.width - scrollport.width).max(0.0);let vertical_range = (scroll_size.height - scrollport.height).max(0.0);@@ -443,6 +531,69 @@ where} else {LayoutPoint::ZERO};+ let horizontal_scrollbar = self.world.boxes[index]+ .style+ .has_scrollbar(+ LayoutScrollbarAxis::Horizontal,+ is_root,+ horizontal_range > f32::EPSILON,+ )+ .then(|| {+ let frame = LayoutRect::new(+ scrollport.x,+ scrollport.bottom(),+ scrollport.width,+ horizontal_gutter,+ );+ LayoutScrollbarGeometry::new(+ LayoutScrollbarAxis::Horizontal,+ frame,+ minimum_offset.x,+ maximum_offset.x,+ applied.x,+ scrollport.width,+ scroll_size.width,+ )+ })+ .filter(|bar| bar.frame.width > 0.0 && bar.frame.height > 0.0);+ let vertical_scrollbar = self.world.boxes[index]+ .style+ .has_scrollbar(+ LayoutScrollbarAxis::Vertical,+ is_root,+ vertical_range > f32::EPSILON,+ )+ .then(|| {+ let x = if rtl && !is_root {+ scrollport.x - scrollbar_thickness+ } else {+ scrollport.right()+ };+ let frame =+ LayoutRect::new(x, scrollport.y, scrollbar_thickness, scrollport.height);+ LayoutScrollbarGeometry::new(+ LayoutScrollbarAxis::Vertical,+ frame,+ minimum_offset.y,+ maximum_offset.y,+ applied.y,+ scrollport.height,+ scroll_size.height,+ )+ })+ .filter(|bar| bar.frame.width > 0.0 && bar.frame.height > 0.0);+ let scrollbar_corner = (vertical_gutter > 0.0 && horizontal_gutter > 0.0).then(|| {+ LayoutRect::new(+ if rtl && !is_root {+ scrollport.x - scrollbar_thickness+ } else {+ scrollport.right()+ },+ scrollport.bottom(),+ scrollbar_thickness,+ horizontal_gutter,+ )+ });self.scroll_extents.push(LayoutScrollExtent {scrollport,scrollable_overflow: overflow,@@ -451,11 +602,27 @@ whereminimum_offset,maximum_offset,is_scroll_container,- allows_user_scroll_x: is_root- || self.world.boxes[index].style.allows_user_scroll_x(),- allows_user_scroll_y: is_root- || self.world.boxes[index].style.allows_user_scroll_y(),+ 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(),+ horizontal_scrollbar,+ vertical_scrollbar,+ scrollbar_corner,+ scrollbar_colors: self.world.boxes[index].style.scrollbar_colors(),});}self.viewport_scroll = self.scroll_extents[self.world.root.index()].applied_offset;@@ -527,8 +694,15 @@ wherecontinue;};let layout = layout_box.final_layout;+ let vertical_leading_gutter = if index == self.world.root.index() {+ 0.0+ } else {+ layout_box+ .style+ .scrollbar_leading_gutter_thickness(LayoutScrollbarAxis::Vertical, false)+ };let content_origin = LayoutPoint::new(- layout.border.left + layout.padding.left,+ layout.border.left + layout.padding.left + vertical_leading_gutter,layout.border.top + layout.padding.top,);for line in &context.fragments.lines {@@ -605,12 +779,7 @@ whereNone,None,viewport_space,- LayoutRect::new(- 0.0,- 0.0,- self.viewport.css_width as f32,- self.viewport.css_height as f32,- ),+ self.scroll_extents[self.world.root.index()].scrollport,);self.assign_box_clip_metadata(self.world.root, Some(viewport_clip), viewport_clip);self.paint_events = build_paint_order(self.world);@@ -672,7 +841,7 @@ wherebox_clip,Some(LayoutOutputBoxId::from_index(index)),self.boxes[index].coordinate_space,- self.boxes[index].padding_box,+ self.scroll_extents[index].scrollport,))} else {box_clip@@ -1035,6 +1204,29 @@ fn finite_point(point: LayoutPoint) -> LayoutPoint {)}+fn scrollport_for_box(+ is_root: bool,+ viewport: LayoutViewport,+ padding_box: LayoutRect,+ vertical_gutter: f32,+ vertical_leading_gutter: f32,+ horizontal_gutter: f32,+) -> LayoutRect {+ if is_root {+ return LayoutRect::new(+ 0.0,+ 0.0,+ (viewport.css_width as f32 - vertical_gutter).max(0.0),+ (viewport.css_height as f32 - horizontal_gutter).max(0.0),+ );+ }+ let mut scrollport = padding_box;+ scrollport.width = (scrollport.width - vertical_gutter).max(0.0);+ scrollport.height = (scrollport.height - horizontal_gutter).max(0.0);+ scrollport.x += vertical_leading_gutter;+ scrollport+}+fn inline_fragment_box_model<N>(world: &LayoutWorld<N>,owner_index: usize,@@ -1045,8 +1237,15 @@ where{let owner = &world.boxes[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 content_origin = LayoutPoint::new(- owner_layout.border.left + owner_layout.padding.left,+ owner_layout.border.left + owner_layout.padding.left + vertical_leading_gutter,owner_layout.border.top + owner_layout.padding.top,);let containing_width = (owner_layout.size.width@@ -1054,7 +1253,14 @@ where- owner_layout.border.right- owner_layout.padding.left- owner_layout.padding.right)- .max(0.0);+ - if owner_index == world.root.index() {+ 0.0+ } else {+ owner+ .style+ .scrollbar_gutter_thickness(LayoutScrollbarAxis::Vertical)+ };+ let containing_width = containing_width.max(0.0);let inline_box = &world.boxes[fragment.box_id.index()];let style = &inline_box.style;let padding = style.taffy.padding.resolve_or_zero(diff --git a/moli-layout/src/scrollbar.rs b/moli-layout/src/scrollbar.rsnew file mode 100644index 000000000..bb39c5b80--- /dev/null+++ b/moli-layout/src/scrollbar.rs@@ -0,0 +1,443 @@+//! Canonical classic-scrollbar geometry shared by layout, paint, and input.+//!+//! Chromium's `ScrollbarTheme` computes the control parts once and uses the+//! same result for painting and hit testing. This follows Blitz's useful+//! shared-geometry model while freezing the result outside its DOM-bound+//! overlay-scrollbar implementation.++use crate::{LayoutPoint, LayoutRect, LayoutTransform2D, PaintColor};++pub(crate) const DEFAULT_SCROLLBAR_THICKNESS: f32 = 15.0;+pub(crate) const THIN_SCROLLBAR_THICKNESS: f32 = 10.0;+const FLUENT_SCROLLBAR_BUTTON_LENGTH: f32 = 18.0;+const FLUENT_SCROLLBAR_THUMB_THICKNESS: f32 = 9.0;+const FLUENT_SCROLLBAR_MINIMUM_THUMB_LENGTH: f32 = 17.0;+const LINE_SCROLL_STEP: f32 = 40.0;++/// Computed `scrollbar-width` projected at the layout boundary.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum LayoutScrollbarWidth {+ #[default]+ Auto,+ Thin,+ None,+}++impl LayoutScrollbarWidth {+ pub(crate) const fn thickness(self) -> f32 {+ match self {+ Self::Auto => DEFAULT_SCROLLBAR_THICKNESS,+ Self::Thin => THIN_SCROLLBAR_THICKNESS,+ Self::None => 0.0,+ }+ }+}++/// Computed `scrollbar-gutter` projected at the layout boundary.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum LayoutScrollbarGutter {+ #[default]+ Auto,+ Stable,+ StableBothEdges,+}++/// Colors used for one author-colored classic scrollbar.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct LayoutScrollbarColors {+ pub thumb: PaintColor,+ pub track: PaintColor,+}++impl LayoutScrollbarColors {+ pub const fn new(thumb: PaintColor, track: PaintColor) -> Self {+ Self { thumb, track }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LayoutScrollbarAxis {+ Horizontal,+ Vertical,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LayoutScrollbarPart {+ BackButton,+ BackTrack,+ Thumb,+ ForwardTrack,+ ForwardButton,+}++/// Input hit resolved from the same frozen geometry paint consumes.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct LayoutScrollbarHit<N> {+ pub source: N,+ pub scrollbar: LayoutScrollbarGeometry,+ pub part: LayoutScrollbarPart,+ pub local_point: LayoutPoint,+ pub viewport_to_local: LayoutTransform2D,+}++/// One scrollbar in its owning box's local coordinate space.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct LayoutScrollbarGeometry {+ pub axis: LayoutScrollbarAxis,+ pub frame: LayoutRect,+ pub track: LayoutRect,+ /// Full-cross-axis thumb geometry used by Chromium's track hit testing.+ pub thumb: LayoutRect,+ /// Fluent's centered, pill-shaped visual nested inside `thumb`.+ pub painted_thumb: LayoutRect,+ pub back_button: LayoutRect,+ pub forward_button: LayoutRect,+ pub minimum_offset: f32,+ pub maximum_offset: f32,+ pub current_offset: f32,+}++impl LayoutScrollbarGeometry {+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn new(+ axis: LayoutScrollbarAxis,+ frame: LayoutRect,+ minimum_offset: f32,+ maximum_offset: f32,+ current_offset: f32,+ visible_length: f32,+ total_length: f32,+ ) -> Self {+ let frame_length = axis_length(axis, frame).max(0.0);+ // Fluent keeps both buttons present on a short scrollbar by splitting+ // the available length evenly between them. Using the full thickness+ // for each would make the controls overlap and leave the whole frame+ // owned by the back button during hit testing.+ let cross_length = axis_cross_length(axis, frame).max(0.0);+ let proportion = cross_length / DEFAULT_SCROLLBAR_THICKNESS;+ let desired_button_length = (FLUENT_SCROLLBAR_BUTTON_LENGTH * proportion).round();+ let button_length = desired_button_length.min(frame_length / 2.0).floor();+ let (back_button, forward_button, track) = axis_parts(axis, frame, button_length);+ let track_length = axis_length(axis, track).max(0.0);+ let proportional = if total_length > 0.0 {+ track_length * (visible_length / total_length).clamp(0.0, 1.0)+ } else {+ track_length+ };+ // NativeThemeFluent reports a 17px minimum auto thumb. The thin+ // variant scales by 2/3 and Chromium's integer return truncates it.+ let minimum_thumb_length = (FLUENT_SCROLLBAR_MINIMUM_THUMB_LENGTH * proportion).floor();+ let thumb_length = proportional+ .round()+ .max(minimum_thumb_length.min(track_length))+ .min(track_length);+ let range = maximum_offset - minimum_offset;+ let progress = if range > f32::EPSILON {+ ((current_offset - minimum_offset) / range).clamp(0.0, 1.0)+ } else {+ 0.0+ };+ let raw_thumb_position = (track_length - thumb_length) * progress;+ // `ScrollbarTheme::ThumbPosition` keeps a non-zero subpixel move+ // visible as one pixel, then stores all later positions as integers.+ let thumb_position = if raw_thumb_position > 0.0 && raw_thumb_position < 1.0 {+ 1.0+ } else {+ raw_thumb_position.trunc()+ };+ let thumb_start = axis_start(axis, track) + thumb_position;+ let thumb = axis_rect(axis, track, thumb_start, thumb_length);+ let mut painted_thumb_thickness = (FLUENT_SCROLLBAR_THUMB_THICKNESS * proportion).round();+ let thickness_difference = cross_length.round() - painted_thumb_thickness;+ if thickness_difference.rem_euclid(2.0) >= 1.0 {+ painted_thumb_thickness = (painted_thumb_thickness - 1.0).max(0.0);+ }+ let painted_thumb = inset_cross_axis(+ axis,+ thumb,+ ((cross_length - painted_thumb_thickness) / 2.0).max(0.0),+ );+ Self {+ axis,+ frame,+ track,+ thumb,+ painted_thumb,+ back_button,+ forward_button,+ minimum_offset,+ maximum_offset,+ current_offset,+ }+ }++ pub fn part_at(self, point: LayoutPoint) -> Option<LayoutScrollbarPart> {+ if !self.frame.contains(point) {+ return None;+ }+ if self.back_button.contains(point) {+ return Some(LayoutScrollbarPart::BackButton);+ }+ if self.forward_button.contains(point) {+ return Some(LayoutScrollbarPart::ForwardButton);+ }+ if self.thumb.contains(point) {+ return Some(LayoutScrollbarPart::Thumb);+ }+ let coordinate = axis_coordinate(self.axis, point);+ if coordinate < axis_start(self.axis, self.thumb) {+ Some(LayoutScrollbarPart::BackTrack)+ } else {+ Some(LayoutScrollbarPart::ForwardTrack)+ }+ }++ /// CSS scroll units advanced by one local CSS pixel of thumb motion.+ pub fn drag_ratio(self) -> f32 {+ let thumb_travel = axis_length(self.axis, self.track) - axis_length(self.axis, self.thumb);+ if thumb_travel <= f32::EPSILON {+ 0.0+ } else {+ (self.maximum_offset - self.minimum_offset) / thumb_travel+ }+ }++ pub fn line_target(self, forward: bool) -> f32 {+ let delta = if forward {+ LINE_SCROLL_STEP+ } else {+ -LINE_SCROLL_STEP+ };+ (self.current_offset + delta).clamp(self.minimum_offset, self.maximum_offset)+ }++ /// Chromium's Linux classic scrollbar advances seven eighths of the+ /// visible scrollport for a track click.+ pub fn page_target(self, forward: bool) -> f32 {+ let step = (axis_length(self.axis, self.frame) * 0.875).max(1.0);+ let delta = if forward { step } else { -step };+ (self.current_offset + delta).clamp(self.minimum_offset, self.maximum_offset)+ }++ pub fn local_axis_coordinate(self, point: LayoutPoint) -> f32 {+ axis_coordinate(self.axis, point)+ }+}++fn inset_cross_axis(axis: LayoutScrollbarAxis, rect: LayoutRect, inset: f32) -> LayoutRect {+ match axis {+ LayoutScrollbarAxis::Horizontal => LayoutRect::new(+ rect.x,+ rect.y + inset,+ rect.width,+ (rect.height - inset * 2.0).max(0.0),+ ),+ LayoutScrollbarAxis::Vertical => LayoutRect::new(+ rect.x + inset,+ rect.y,+ (rect.width - inset * 2.0).max(0.0),+ rect.height,+ ),+ }+}++fn axis_parts(+ axis: LayoutScrollbarAxis,+ frame: LayoutRect,+ button_length: f32,+) -> (LayoutRect, LayoutRect, LayoutRect) {+ let start = axis_start(axis, frame);+ let length = axis_length(axis, frame);+ let back = axis_rect(axis, frame, start, button_length);+ let forward = axis_rect(+ axis,+ frame,+ start + (length - button_length).max(0.0),+ button_length,+ );+ let track = axis_rect(+ axis,+ frame,+ start + button_length,+ (length - button_length * 2.0).max(0.0),+ );+ (back, forward, track)+}++fn axis_rect(+ axis: LayoutScrollbarAxis,+ cross_axis: LayoutRect,+ start: f32,+ length: f32,+) -> LayoutRect {+ match axis {+ LayoutScrollbarAxis::Horizontal => LayoutRect::new(+ start,+ cross_axis.y,+ length.max(0.0),+ cross_axis.height.max(0.0),+ ),+ LayoutScrollbarAxis::Vertical => LayoutRect::new(+ cross_axis.x,+ start,+ cross_axis.width.max(0.0),+ length.max(0.0),+ ),+ }+}++pub(crate) fn axis_coordinate(axis: LayoutScrollbarAxis, point: LayoutPoint) -> f32 {+ match axis {+ LayoutScrollbarAxis::Horizontal => point.x,+ LayoutScrollbarAxis::Vertical => point.y,+ }+}++pub(crate) fn axis_start(axis: LayoutScrollbarAxis, rect: LayoutRect) -> f32 {+ match axis {+ LayoutScrollbarAxis::Horizontal => rect.x,+ LayoutScrollbarAxis::Vertical => rect.y,+ }+}++pub(crate) fn axis_length(axis: LayoutScrollbarAxis, rect: LayoutRect) -> f32 {+ match axis {+ LayoutScrollbarAxis::Horizontal => rect.width,+ LayoutScrollbarAxis::Vertical => rect.height,+ }+}++fn axis_cross_length(axis: LayoutScrollbarAxis, rect: LayoutRect) -> f32 {+ match axis {+ LayoutScrollbarAxis::Horizontal => rect.height,+ LayoutScrollbarAxis::Vertical => rect.width,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn thumb_geometry_and_parts_share_one_chromium_style_model() {+ let bar = LayoutScrollbarGeometry::new(+ LayoutScrollbarAxis::Vertical,+ LayoutRect::new(185.0, 0.0, 15.0, 100.0),+ 0.0,+ 300.0,+ 150.0,+ 100.0,+ 400.0,+ );+ assert_eq!(bar.back_button, LayoutRect::new(185.0, 0.0, 15.0, 18.0));+ assert_eq!(bar.forward_button, LayoutRect::new(185.0, 82.0, 15.0, 18.0));+ assert_eq!(bar.track, LayoutRect::new(185.0, 18.0, 15.0, 64.0));+ assert_eq!(bar.thumb, LayoutRect::new(185.0, 41.0, 15.0, 17.0));+ assert_eq!(bar.painted_thumb, LayoutRect::new(188.0, 41.0, 9.0, 17.0));+ assert_eq!(+ bar.part_at(LayoutPoint::new(190.0, 5.0)),+ Some(LayoutScrollbarPart::BackButton)+ );+ assert_eq!(+ bar.part_at(LayoutPoint::new(190.0, 25.0)),+ Some(LayoutScrollbarPart::BackTrack)+ );+ assert_eq!(+ bar.part_at(LayoutPoint::new(190.0, 45.0)),+ Some(LayoutScrollbarPart::Thumb)+ );+ assert_eq!(+ bar.part_at(LayoutPoint::new(190.0, 75.0)),+ Some(LayoutScrollbarPart::ForwardTrack)+ );+ assert_eq!(+ bar.part_at(LayoutPoint::new(190.0, 90.0)),+ Some(LayoutScrollbarPart::ForwardButton)+ );+ assert!((bar.drag_ratio() - 300.0 / 47.0).abs() < f32::EPSILON);+ }++ #[test]+ fn rtl_range_places_zero_offset_at_the_forward_end() {+ let bar = LayoutScrollbarGeometry::new(+ LayoutScrollbarAxis::Horizontal,+ LayoutRect::new(0.0, 85.0, 200.0, 15.0),+ -200.0,+ 0.0,+ 0.0,+ 200.0,+ 400.0,+ );+ assert_eq!(bar.thumb.right(), bar.track.right());+ assert_eq!(bar.line_target(false), -40.0);+ assert_eq!(bar.line_target(true), 0.0);+ }++ #[test]+ fn short_scrollbar_splits_its_frame_between_non_overlapping_buttons() {+ let bar = LayoutScrollbarGeometry::new(+ LayoutScrollbarAxis::Vertical,+ LayoutRect::new(0.0, 0.0, 15.0, 20.0),+ 0.0,+ 100.0,+ 0.0,+ 20.0,+ 120.0,+ );+ assert_eq!(bar.back_button, LayoutRect::new(0.0, 0.0, 15.0, 10.0));+ assert_eq!(bar.forward_button, LayoutRect::new(0.0, 10.0, 15.0, 10.0));+ assert_eq!(bar.track, LayoutRect::new(0.0, 10.0, 15.0, 0.0));+ assert_eq!(+ bar.part_at(LayoutPoint::new(7.5, 5.0)),+ Some(LayoutScrollbarPart::BackButton)+ );+ assert_eq!(+ bar.part_at(LayoutPoint::new(7.5, 15.0)),+ Some(LayoutScrollbarPart::ForwardButton)+ );+ }++ #[test]+ fn thin_fluent_parts_scale_before_integer_geometry_is_frozen() {+ let bar = LayoutScrollbarGeometry::new(+ LayoutScrollbarAxis::Vertical,+ LayoutRect::new(190.0, 0.0, 10.0, 100.0),+ 0.0,+ 900.0,+ 0.0,+ 100.0,+ 1_000.0,+ );+ assert_eq!(bar.back_button, LayoutRect::new(190.0, 0.0, 10.0, 12.0));+ assert_eq!(bar.forward_button, LayoutRect::new(190.0, 88.0, 10.0, 12.0));+ assert_eq!(bar.track, LayoutRect::new(190.0, 12.0, 10.0, 76.0));+ assert_eq!(bar.thumb, LayoutRect::new(190.0, 12.0, 10.0, 11.0));+ assert_eq!(bar.painted_thumb, LayoutRect::new(192.0, 12.0, 6.0, 11.0));++ let first_subpixel_move = LayoutScrollbarGeometry::new(+ LayoutScrollbarAxis::Vertical,+ bar.frame,+ 0.0,+ 900.0,+ 1.0,+ 100.0,+ 1_000.0,+ );+ assert_eq!(first_subpixel_move.thumb.y, 13.0);+ }++ #[test]+ fn track_click_uses_chromiums_linux_page_step() {+ let bar = LayoutScrollbarGeometry::new(+ LayoutScrollbarAxis::Vertical,+ LayoutRect::new(0.0, 0.0, 15.0, 200.0),+ 0.0,+ 1_000.0,+ 400.0,+ 200.0,+ 1_200.0,+ );+ assert_eq!(bar.page_target(true), 575.0);+ assert_eq!(bar.page_target(false), 225.0);+ }+}diff --git a/moli-layout/src/style.rs b/moli-layout/src/style.rsindex 45617cc32..e2bac4abb 100644--- a/moli-layout/src/style.rs+++ b/moli-layout/src/style.rs@@ -14,6 +14,7 @@ use style::{},properties::ComputedValues,properties::generated::longhands::position::computed_value::T as StyloPosition,+ properties::generated::longhands::scrollbar_width::computed_value::T as StyloScrollbarWidth,properties::generated::longhands::{direction::computed_value::T as StyloDirection,unicode_bidi::computed_value::T as StyloUnicodeBidi,@@ -36,6 +37,7 @@ use style::{length::{GenericMaxSize, GenericSize},position::PreferredRatio,transform::{Rotate, Scale, Translate},+ ui::GenericScrollbarColor,},specified::box_::{DisplayInside, DisplayOutside},specified::{@@ -47,9 +49,10 @@ use style::{use taffy::{BoxSizing, Display as TaffyDisplay, Position as TaffyPosition, Size, Style};use crate::{- LayoutPoint, LayoutRect, LayoutTransform2D, PaintBlendMode, PaintBorderColors,- PaintBorderStyle, PaintBorderStyles, PaintBoxShadow, PaintColor, PaintCornerRadii,- PaintCornerRadius, PaintEdgeSizes, PaintFragment,+ LayoutPoint, LayoutRect, LayoutScrollbarAxis, LayoutScrollbarColors, LayoutScrollbarGutter,+ LayoutScrollbarWidth, LayoutTransform2D, PaintBlendMode, PaintBorderColors, PaintBorderStyle,+ PaintBorderStyles, PaintBoxShadow, PaintColor, PaintCornerRadii, PaintCornerRadius,+ PaintEdgeSizes, PaintFragment,};/// Marker families implemented by the Phase 4 list formatter.@@ -125,6 +128,47 @@ pub(crate) enum InlineDirection {Rtl,}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub(crate) enum LayoutOverflowMode {+ #[default]+ Visible,+ Clip,+ Hidden,+ Auto,+ Scroll,+}++impl LayoutOverflowMode {+ fn from_stylo(value: Overflow) -> Self {+ match value {+ Overflow::Visible => Self::Visible,+ Overflow::Clip => Self::Clip,+ Overflow::Hidden => Self::Hidden,+ Overflow::Auto => Self::Auto,+ Overflow::Scroll => Self::Scroll,+ }+ }++ fn from_taffy(value: taffy::Overflow) -> Self {+ match value {+ taffy::Overflow::Visible => Self::Visible,+ taffy::Overflow::Clip => Self::Clip,+ taffy::Overflow::Hidden => Self::Hidden,+ // Synthetic tests historically used Taffy's `Scroll` as CSS+ // `auto`, because the adapter previously had zero-width bars.+ taffy::Overflow::Scroll => Self::Auto,+ }+ }++ const fn creates_scroll_container(self) -> bool {+ matches!(self, Self::Hidden | Self::Auto | Self::Scroll)+ }++ const fn allows_user_scroll(self) -> bool {+ matches!(self, Self::Auto | Self::Scroll)+ }+}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub(crate) enum InlineUnicodeBidi {#[default]@@ -417,6 +461,13 @@ pub struct ResolvedLayoutStyle {vertical_align: InlineVerticalAlign,text_projection_deferred: bool,overflow_clips: bool,+ overflow_x: LayoutOverflowMode,+ overflow_y: LayoutOverflowMode,+ scrollbar_width: LayoutScrollbarWidth,+ scrollbar_gutter: LayoutScrollbarGutter,+ scrollbar_colors: Option<LayoutScrollbarColors>,+ revealed_scrollbar_x: bool,+ revealed_scrollbar_y: bool,out_of_flow: bool,position: LayoutPosition,sticky_inset: taffy::Rect<taffy::LengthPercentageAuto>,@@ -564,6 +615,32 @@ impl ResolvedLayoutStyle {|| text_transform_value.intersects(TextTransform::FULL_SIZE_KANA)|| vertical_align_deferred;let overflow_clips = stylo_overflow_clips(&computed);+ let overflow_x = LayoutOverflowMode::from_stylo(computed.clone_overflow_x());+ let overflow_y = LayoutOverflowMode::from_stylo(computed.clone_overflow_y());+ let scrollbar_width = match computed.clone_scrollbar_width() {+ StyloScrollbarWidth::Auto => LayoutScrollbarWidth::Auto,+ StyloScrollbarWidth::Thin => LayoutScrollbarWidth::Thin,+ StyloScrollbarWidth::None => LayoutScrollbarWidth::None,+ };+ let computed_gutter = computed.clone_scrollbar_gutter();+ let scrollbar_gutter =+ if computed_gutter.contains(style::values::computed::ScrollbarGutter::BOTH_EDGES) {+ LayoutScrollbarGutter::StableBothEdges+ } else if computed_gutter.contains(style::values::computed::ScrollbarGutter::STABLE) {+ LayoutScrollbarGutter::Stable+ } else {+ LayoutScrollbarGutter::Auto+ };+ let scrollbar_colors = match computed.clone_scrollbar_color() {+ GenericScrollbarColor::Auto => None,+ GenericScrollbarColor::Colors { thumb, track } => {+ let current = computed.clone_color();+ Some(LayoutScrollbarColors::new(+ absolute_paint_color(thumb.resolve_to_absolute(¤t)),+ absolute_paint_color(track.resolve_to_absolute(¤t)),+ ))+ }+ };let stylo_position = computed.clone_position();let position = match stylo_position {StyloPosition::Static => LayoutPosition::Static,@@ -752,6 +829,13 @@ impl ResolvedLayoutStyle {vertical_align,text_projection_deferred,overflow_clips,+ overflow_x,+ overflow_y,+ scrollbar_width,+ scrollbar_gutter,+ scrollbar_colors,+ revealed_scrollbar_x: false,+ revealed_scrollbar_y: false,out_of_flow,position,sticky_inset,@@ -791,6 +875,8 @@ impl ResolvedLayoutStyle {taffy.item_is_table = matches!(display, LayoutDisplay::Table | LayoutDisplay::InlineTable);let overflow_clips = taffy.overflow.x != taffy::Overflow::Visible|| taffy.overflow.y != taffy::Overflow::Visible;+ let overflow_x = LayoutOverflowMode::from_taffy(taffy.overflow.x);+ let overflow_y = LayoutOverflowMode::from_taffy(taffy.overflow.y);let out_of_flow = taffy.position == TaffyPosition::Absolute;let position = if out_of_flow {LayoutPosition::Absolute@@ -818,6 +904,13 @@ impl ResolvedLayoutStyle {vertical_align: InlineVerticalAlign::default(),text_projection_deferred: false,overflow_clips,+ overflow_x,+ overflow_y,+ scrollbar_width: LayoutScrollbarWidth::Auto,+ scrollbar_gutter: LayoutScrollbarGutter::Auto,+ scrollbar_colors: None,+ revealed_scrollbar_x: false,+ revealed_scrollbar_y: false,out_of_flow,position,sticky_inset,@@ -877,6 +970,19 @@ impl ResolvedLayoutStyle {self}+ /// Supplies the CSS scrollbar properties not yet exposed through Stylo's+ /// typed standalone embedding API.+ pub fn set_scrollbar_style(+ &mut self,+ width: LayoutScrollbarWidth,+ gutter: LayoutScrollbarGutter,+ colors: Option<LayoutScrollbarColors>,+ ) {+ self.scrollbar_width = width;+ self.scrollbar_gutter = gutter;+ self.scrollbar_colors = colors;+ }+/// Overrides the alignment keyword for a synthetic inline style.pub fn with_inline_alignment(mut self, alignment: LayoutInlineAlignment) -> Self {self.vertical_align.kind = alignment;@@ -1491,17 +1597,192 @@ impl ResolvedLayoutStyle {pub(crate) fn establishes_scroll_container(&self) -> bool {// `overflow: clip` clips paint but deliberately does not create the// scrolling mechanism that selects a sticky scrollport.- [self.taffy.overflow.x, self.taffy.overflow.y]+ [self.overflow_x, self.overflow_y].into_iter()- .any(|overflow| matches!(overflow, taffy::Overflow::Hidden | taffy::Overflow::Scroll))+ .any(LayoutOverflowMode::creates_scroll_container)}pub(crate) fn allows_user_scroll_x(&self) -> bool {- self.taffy.overflow.x == taffy::Overflow::Scroll+ self.overflow_x.allows_user_scroll()}pub(crate) fn allows_user_scroll_y(&self) -> bool {- self.taffy.overflow.y == taffy::Overflow::Scroll+ self.overflow_y.allows_user_scroll()+ }++ 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;+ let both_edge_gutter = self.reserves_both_edge_vertical_gutter();+ self.taffy.scrollbar_width =+ self.scrollbar_width.thickness() * if both_edge_gutter { 2.0 } else { 1.0 };+ self.taffy.overflow.x =+ self.initial_taffy_overflow(LayoutScrollbarAxis::Horizontal, is_root);+ 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.+ if both_edge_gutter && self.revealed_scrollbar_x {+ self.taffy.overflow.x = taffy::Overflow::Hidden;+ }+ // In horizontal writing modes a stable gutter is reserved on the+ // inline end whenever vertical overflow could create a scrollbar.+ if !is_root+ && !matches!(self.scrollbar_gutter, LayoutScrollbarGutter::Auto)+ && self.overflow_y.creates_scroll_container()+ && self.scrollbar_width != LayoutScrollbarWidth::None+ {+ self.taffy.overflow.y = taffy::Overflow::Scroll;+ }+ }++ fn initial_taffy_overflow(&self, axis: LayoutScrollbarAxis, is_root: bool) -> taffy::Overflow {+ let mode = self.overflow_mode(axis);+ // The root scrollbar belongs to the initial containing block. Its+ // gutter is reserved on Moli's synthetic viewport node so percentage+ // sizing and fixed positioning see the reduced layout viewport without+ // making the root element reserve the same gutter a second time.+ if is_root {+ return match mode {+ LayoutOverflowMode::Clip => taffy::Overflow::Clip,+ LayoutOverflowMode::Visible+ | LayoutOverflowMode::Hidden+ | LayoutOverflowMode::Auto+ | LayoutOverflowMode::Scroll => taffy::Overflow::Hidden,+ };+ }+ match mode {+ LayoutOverflowMode::Visible => taffy::Overflow::Visible,+ LayoutOverflowMode::Clip => taffy::Overflow::Clip,+ LayoutOverflowMode::Hidden | LayoutOverflowMode::Auto => taffy::Overflow::Hidden,+ LayoutOverflowMode::Scroll => taffy::Overflow::Scroll,+ }+ }++ pub(crate) fn reveal_auto_scrollbar(+ &mut self,+ axis: LayoutScrollbarAxis,+ is_root: bool,+ overflowing: bool,+ ) -> bool {+ if !overflowing || self.scrollbar_width == LayoutScrollbarWidth::None {+ return false;+ }+ let mode = self.overflow_mode(axis);+ if !(matches!(mode, LayoutOverflowMode::Auto)+ || is_root && matches!(mode, LayoutOverflowMode::Visible))+ {+ 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;+ if !(is_root+ || axis == LayoutScrollbarAxis::Horizontal && self.reserves_both_edge_vertical_gutter())+ {+ match axis {+ LayoutScrollbarAxis::Horizontal => {+ self.taffy.overflow.x = taffy::Overflow::Scroll;+ }+ LayoutScrollbarAxis::Vertical => {+ self.taffy.overflow.y = taffy::Overflow::Scroll;+ }+ }+ }+ true+ }++ pub(crate) fn has_scrollbar(+ &self,+ axis: LayoutScrollbarAxis,+ is_root: bool,+ overflowing: bool,+ ) -> bool {+ if self.scrollbar_width == LayoutScrollbarWidth::None {+ return false;+ }+ match self.overflow_mode(axis) {+ LayoutOverflowMode::Scroll => true,+ LayoutOverflowMode::Auto => overflowing,+ LayoutOverflowMode::Visible if is_root => overflowing,+ LayoutOverflowMode::Visible | LayoutOverflowMode::Clip | LayoutOverflowMode::Hidden => {+ false+ }+ }+ }++ pub(crate) fn overflow_mode(&self, axis: LayoutScrollbarAxis) -> LayoutOverflowMode {+ match axis {+ LayoutScrollbarAxis::Horizontal => self.overflow_x,+ LayoutScrollbarAxis::Vertical => self.overflow_y,+ }+ }++ pub(crate) const fn scrollbar_colors(&self) -> Option<LayoutScrollbarColors> {+ self.scrollbar_colors+ }++ pub(crate) fn scrollbar_control_thickness(&self) -> f32 {+ self.scrollbar_width.thickness()+ }++ 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+ && !matches!(self.scrollbar_gutter, LayoutScrollbarGutter::Auto)+ && self.overflow_y.creates_scroll_container();+ if revealed || stable_vertical {+ let thickness = self.scrollbar_width.thickness();+ if axis == LayoutScrollbarAxis::Vertical && self.reserves_both_edge_vertical_gutter() {+ thickness * 2.0+ } else {+ thickness+ }+ } else {+ 0.0+ }+ }++ /// Physical gutter before the scrollport. Classic vertical scrollbars are+ /// on the left in RTL, while `both-edges` adds the matching left gutter in+ /// LTR as well.+ pub(crate) fn scrollbar_leading_gutter_thickness(+ &self,+ axis: LayoutScrollbarAxis,+ is_root: bool,+ ) -> f32 {+ if axis != LayoutScrollbarAxis::Vertical || self.scrollbar_gutter_thickness(axis) == 0.0 {+ return 0.0;+ }+ // Chromium keeps the viewport scrollbar on the physical right even+ // when the root element is RTL. `both-edges` still reserves its+ // matching gutter on the physical left.+ if self.reserves_both_edge_vertical_gutter()+ || (!is_root && self.direction == InlineDirection::Rtl)+ {+ self.scrollbar_width.thickness()+ } else {+ 0.0+ }+ }++ fn reserves_both_edge_vertical_gutter(&self) -> bool {+ self.scrollbar_gutter == LayoutScrollbarGutter::StableBothEdges+ && self.overflow_y.creates_scroll_container()+ && self.scrollbar_width != LayoutScrollbarWidth::None}pub(crate) fn text_leaf_from(parent: &Self) -> Self {@@ -1528,6 +1809,13 @@ impl ResolvedLayoutStyle {vertical_align: parent.vertical_align,text_projection_deferred: parent.text_projection_deferred,overflow_clips: false,+ overflow_x: LayoutOverflowMode::Visible,+ overflow_y: LayoutOverflowMode::Visible,+ scrollbar_width: parent.scrollbar_width,+ scrollbar_gutter: LayoutScrollbarGutter::Auto,+ scrollbar_colors: parent.scrollbar_colors,+ revealed_scrollbar_x: false,+ revealed_scrollbar_y: false,out_of_flow: false,position: LayoutPosition::Static,sticky_inset: taffy::Rect {@@ -1586,6 +1874,13 @@ impl ResolvedLayoutStyle {vertical_align: parent.vertical_align,text_projection_deferred: parent.text_projection_deferred,overflow_clips: false,+ overflow_x: LayoutOverflowMode::Visible,+ overflow_y: LayoutOverflowMode::Visible,+ scrollbar_width: parent.scrollbar_width,+ scrollbar_gutter: LayoutScrollbarGutter::Auto,+ scrollbar_colors: parent.scrollbar_colors,+ revealed_scrollbar_x: false,+ revealed_scrollbar_y: false,out_of_flow: false,position: LayoutPosition::Static,sticky_inset: taffy::Rect {diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rsindex aca68804c..0a494faf3 100644--- a/moli-layout/src/taffy_tree.rs+++ b/moli-layout/src/taffy_tree.rs@@ -13,7 +13,8 @@ use taffy::{};use crate::{- LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic, LayoutWorld, PaintRect, PaintViewport,+ LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic, LayoutScrollbarAxis, LayoutWorld,+ PaintRect, PaintViewport,form::form_control_context,inline::{InlineFormattingContext, InlineFragments, InlineLinePlacement, InlineObjectRole,@@ -48,8 +49,14 @@ 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);world.viewport_layout.style = Style {display: Display::Block,+ box_sizing: BoxSizing::BorderBox,size: Size {width: Dimension::length(viewport.css_width as f32),height: Dimension::length(viewport.css_height as f32),@@ -62,6 +69,19 @@ wherewidth: Dimension::length(viewport.css_width as f32),height: Dimension::length(viewport.css_height as f32),},+ // The synthetic viewport is the initial containing block. Model UA+ // scrollbar gutters as its non-painted border: in-flow root content+ // and fixed-position descendants then share the same inner rectangle.+ // Padding would be wrong here because an absolute/fixed containing+ // block is its padding box and would still extend underneath the bars.+ border: taffy::Rect {+ left: taffy::LengthPercentage::length(vertical_leading_gutter),+ right: taffy::LengthPercentage::length(+ (vertical_gutter - vertical_leading_gutter).max(0.0),+ ),+ top: taffy::LengthPercentage::length(0.0),+ bottom: taffy::LengthPercentage::length(horizontal_gutter),+ },..Style::default()};let positioned_static_placeholders = prepare_layout_tree(world);diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rsindex e3b10b970..af26d4b45 100644--- a/moli-layout/tests/phase5_output_contract.rs+++ b/moli-layout/tests/phase5_output_contract.rs@@ -4,8 +4,10 @@ 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,- PaintColor, ResolvedLayoutStyle, build_layout_pass,+ PaintBrush, PaintCaptureRequest, PaintColor, PaintFragment, PaintShape, ResolvedLayoutStyle,+ build_layout_pass,};use style::Atom;use taffy::{@@ -156,6 +158,474 @@ fn assert_rect(actual: LayoutRect, expected: LayoutRect) {assert_close(actual.height, expected.height);}+#[test]+fn classic_scrollbars_share_layout_paint_and_hit_test_geometry() {+ let source = Source(vec![+ Node::element("root", vec![1]),+ Node::element("scroller", vec![2]),+ Node::element("oversized-content", Vec::new()),+ ]);+ let mut styles = Styles::default();+ styles+ .0+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));+ let scroller = Style {+ size: Size {+ width: length(200.0),+ height: length(100.0),+ },+ overflow: Point {+ x: Overflow::Scroll,+ y: Overflow::Scroll,+ },+ ..Style::default()+ };+ let mut scroller = resolved(LayoutDisplay::Block, scroller);+ let thumb = PaintColor::new(1.0, 0.0, 0.0, 1.0);+ let track = PaintColor::new(0.0, 0.0, 1.0, 1.0);+ scroller.set_scrollbar_style(+ LayoutScrollbarWidth::Auto,+ moli_layout::LayoutScrollbarGutter::Auto,+ Some(LayoutScrollbarColors::new(thumb, track)),+ );+ styles.0.insert(1, scroller);+ styles+ .0+ .insert(2, fixed_size(LayoutDisplay::Block, 400.0, 300.0));++ let output = build_with_request(+ &source,+ &mut styles,+ LayoutPassRequest::with_paint(LayoutViewport::new(320, 240, 1.0), LayoutFlushReason::Test),+ );+ let metrics = output.element_metrics_for_source(1).unwrap();+ assert_eq!(+ metrics.client_size,+ moli_layout::LayoutSize::new(185.0, 85.0)+ );+ assert_eq!(+ metrics.scroll_size,+ moli_layout::LayoutSize::new(400.0, 300.0)+ );+ assert_eq!(+ metrics.maximum_scroll_offset,+ LayoutPoint::new(215.0, 215.0)+ );++ let box_id = output.source_output(1).unwrap().principal_box.unwrap();+ let extent = output.scroll_extent(box_id).unwrap();+ let horizontal = extent.horizontal_scrollbar.expect("horizontal control");+ let vertical = extent.vertical_scrollbar.expect("vertical control");+ assert_rect(horizontal.frame, LayoutRect::new(0.0, 85.0, 185.0, 15.0));+ assert_rect(vertical.frame, LayoutRect::new(185.0, 0.0, 15.0, 85.0));+ assert_rect(horizontal.track, LayoutRect::new(18.0, 85.0, 149.0, 15.0));+ assert_rect(horizontal.thumb, LayoutRect::new(18.0, 85.0, 69.0, 15.0));+ assert_rect(+ horizontal.painted_thumb,+ LayoutRect::new(18.0, 88.0, 69.0, 9.0),+ );+ assert_rect(vertical.track, LayoutRect::new(185.0, 18.0, 15.0, 49.0));+ assert_rect(vertical.thumb, LayoutRect::new(185.0, 18.0, 15.0, 17.0));+ assert_rect(+ vertical.painted_thumb,+ LayoutRect::new(188.0, 18.0, 9.0, 17.0),+ );+ assert_rect(+ extent.scrollbar_corner.expect("two-axis corner"),+ LayoutRect::new(185.0, 85.0, 15.0, 15.0),+ );+ let hit = output+ .scrollbar_hit_test(LayoutPoint::new(190.0, 30.0))+ .expect("thumb should use the frozen paint geometry");+ assert_eq!(hit.source, 1);+ assert_eq!(hit.part, LayoutScrollbarPart::Thumb);++ let snapshot = output.paint_snapshot().expect("paint request");+ assert!(snapshot.fragments.iter().any(|fragment| matches!(+ fragment,+ PaintFragment::Fill {+ shape: PaintShape::RoundedRect { .. },+ brush: PaintBrush::Solid(color),+ ..+ } if *color == thumb+ )));+ assert_eq!(+ snapshot+ .fragments+ .iter()+ .filter(|fragment| matches!(+ fragment,+ PaintFragment::Fill {+ shape: PaintShape::Path(_),+ brush: PaintBrush::Solid(color),+ ..+ } if *color == thumb+ ))+ .count(),+ 4,+ "each axis paints Chromium's back and forward arrow glyphs"+ );+ assert!(snapshot.fragments.iter().any(|fragment| matches!(+ fragment,+ PaintFragment::Fill {+ brush: PaintBrush::Solid(color),+ ..+ } if *color == track+ )));+}++#[test]+fn non_viewport_captures_omit_only_the_root_scrollbars() {+ let source = Source(vec![+ Node::element("root", vec![1]),+ Node::element("oversized-content", Vec::new()),+ ]);+ let mut styles = Styles::default();+ let mut root = fixed_size(LayoutDisplay::Block, 320.0, 240.0);+ let thumb = PaintColor::new(1.0, 0.0, 0.0, 1.0);+ let track = PaintColor::new(0.0, 0.0, 1.0, 1.0);+ root.set_scrollbar_style(+ LayoutScrollbarWidth::Auto,+ LayoutScrollbarGutter::Auto,+ Some(LayoutScrollbarColors::new(thumb, track)),+ );+ styles.0.insert(0, root);+ styles+ .0+ .insert(1, fixed_size(LayoutDisplay::Block, 640.0, 480.0));++ let scrollbar_fill_count = |snapshot: &moli_layout::PaintSnapshot| {+ snapshot+ .fragments+ .iter()+ .filter(|fragment| {+ matches!(+ fragment,+ PaintFragment::Fill {+ brush: PaintBrush::Solid(color),+ ..+ } if *color == thumb || *color == track+ )+ })+ .count()+ };+ let viewport = build_with_request(+ &source,+ &mut styles,+ LayoutPassRequest::with_paint(LayoutViewport::new(320, 240, 1.0), LayoutFlushReason::Test),+ );+ assert!(+ scrollbar_fill_count(viewport.paint_snapshot().expect("viewport paint")) >= 4,+ "the viewport capture includes both root controls"+ );++ for capture in [+ PaintCaptureRequest::full_document(),+ PaintCaptureRequest::page_clip(LayoutRect::new(0.0, 0.0, 320.0, 240.0), 1.0),+ ] {+ let output = build_with_request(+ &source,+ &mut styles,+ LayoutPassRequest::with_capture(+ LayoutViewport::new(320, 240, 1.0),+ LayoutFlushReason::Test,+ capture,+ ),+ );+ assert_eq!(+ scrollbar_fill_count(output.paint_snapshot().expect("non-viewport paint")),+ 0,+ "full-document and page-clip captures omit root viewport controls"+ );+ }+}++#[test]+fn auto_scrollbar_feedback_reveals_the_perpendicular_axis() {+ let source = Source(vec![+ Node::element("root", vec![1]),+ Node::element("scroller", vec![2]),+ Node::element("content", Vec::new()),+ ]);+ let mut styles = Styles::default();+ styles+ .0+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));+ // Synthetic Taffy `Scroll` maps to CSS `auto` at this adapter boundary.+ let scroller = Style {+ size: Size {+ width: length(200.0),+ height: length(100.0),+ },+ overflow: Point {+ x: Overflow::Scroll,+ y: Overflow::Scroll,+ },+ ..Style::default()+ };+ styles.0.insert(1, resolved(LayoutDisplay::Block, scroller));+ styles+ .0+ .insert(2, fixed_size(LayoutDisplay::Block, 200.0, 200.0));++ let output = build(&source, &mut styles);+ let metrics = output.element_metrics_for_source(1).unwrap();+ assert_eq!(+ metrics.client_size,+ moli_layout::LayoutSize::new(185.0, 85.0)+ );+ assert_eq!(+ metrics.scroll_size,+ moli_layout::LayoutSize::new(200.0, 200.0)+ );+ let box_id = output.source_output(1).unwrap().principal_box.unwrap();+ let extent = output.scroll_extent(box_id).unwrap();+ assert!(extent.horizontal_scrollbar.is_some());+ assert!(extent.vertical_scrollbar.is_some());+}++#[test]+fn thin_and_hidden_scrollbars_match_chromium_client_geometry() {+ let source = Source(vec![+ Node::element("root", vec![1]),+ Node::element("scroller", vec![2]),+ Node::element("content", Vec::new()),+ ]);+ for (width, expected_client, has_controls) in [+ (LayoutScrollbarWidth::Auto, (185.0, 85.0), true),+ (LayoutScrollbarWidth::Thin, (190.0, 90.0), true),+ (LayoutScrollbarWidth::None, (200.0, 100.0), false),+ ] {+ let mut styles = Styles::default();+ styles+ .0+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));+ let style = Style {+ size: Size {+ width: length(200.0),+ height: length(100.0),+ },+ overflow: Point {+ x: Overflow::Scroll,+ y: Overflow::Scroll,+ },+ ..Style::default()+ };+ let mut style = resolved(LayoutDisplay::Block, style);+ style.set_scrollbar_style(width, moli_layout::LayoutScrollbarGutter::Auto, None);+ styles.0.insert(1, style);+ styles+ .0+ .insert(2, fixed_size(LayoutDisplay::Block, 400.0, 300.0));++ let output = build(&source, &mut styles);+ let metrics = output.element_metrics_for_source(1).unwrap();+ assert_eq!(+ metrics.client_size,+ moli_layout::LayoutSize::new(expected_client.0, expected_client.1)+ );+ let box_id = output.source_output(1).unwrap().principal_box.unwrap();+ let extent = output.scroll_extent(box_id).unwrap();+ assert_eq!(extent.horizontal_scrollbar.is_some(), has_controls);+ assert_eq!(extent.vertical_scrollbar.is_some(), has_controls);+ }+}++#[test]+fn stable_both_edges_reserves_and_offsets_both_chromium_gutters() {+ let source = Source(vec![+ Node::element("root", vec![1]),+ Node::element("scroller", vec![2]),+ Node::element("auto-width-child", Vec::new()),+ ]);+ let mut styles = Styles::default();+ styles+ .0+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));+ let scroller = Style {+ size: Size {+ width: length(200.0),+ height: length(100.0),+ },+ overflow: Point {+ x: Overflow::Visible,+ y: Overflow::Scroll,+ },+ ..Style::default()+ };+ let mut scroller = resolved(LayoutDisplay::Block, scroller);+ scroller.set_scrollbar_style(+ LayoutScrollbarWidth::Auto,+ LayoutScrollbarGutter::StableBothEdges,+ None,+ );+ styles.0.insert(1, scroller);+ let mut child = Style::default();+ child.size.height = length(200.0);+ styles.0.insert(2, resolved(LayoutDisplay::Block, child));++ let output = build(&source, &mut styles);+ let metrics = output.element_metrics_for_source(1).unwrap();+ assert_eq!(metrics.client_size.width, 170.0);+ assert_eq!(metrics.client_border.x, 15.0);+ let child_id = output.source_output(2).unwrap().principal_box.unwrap();+ let child_geometry = output.box_geometry(child_id).unwrap();+ assert_eq!(child_geometry.border_box.width, 170.0);+ assert_eq!(child_geometry.layout_origin_in_document.x, 15.0);++ let scroller_id = output.source_output(1).unwrap().principal_box.unwrap();+ let vertical = output+ .scroll_extent(scroller_id)+ .unwrap()+ .vertical_scrollbar+ .expect("overflowing content keeps the end-edge control");+ assert_rect(vertical.frame, LayoutRect::new(185.0, 0.0, 15.0, 100.0));+}++#[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)] {+ let source = Source(vec![+ Node::element("root", vec![1]),+ Node::element("auto-width-child", Vec::new()),+ ]);+ let mut styles = Styles::default();+ let mut root = Style {+ overflow: Point {+ x: Overflow::Visible,+ // Synthetic Taffy `Scroll` maps to CSS `auto` at this adapter boundary.+ y: Overflow::Scroll,+ },+ ..Style::default()+ };+ root.size.height = length(240.0);+ let mut root = resolved(LayoutDisplay::Block, root);+ root.set_scrollbar_style(+ LayoutScrollbarWidth::Auto,+ LayoutScrollbarGutter::StableBothEdges,+ None,+ );+ styles.0.insert(0, root);+ let mut child = Style::default();+ child.size.height = length(content_height);+ styles.0.insert(1, resolved(LayoutDisplay::Block, child));++ let output = build(&source, &mut styles);+ let root_metrics = output.element_metrics_for_source(0).unwrap();+ assert_eq!(root_metrics.client_size.width, expected_client_width);+ assert_eq!(root_metrics.scroll_size.width, 290.0);+ let root_id = output.source_output(0).unwrap().principal_box.unwrap();+ let root_geometry = output.box_geometry(root_id).unwrap();+ assert_rect(+ root_geometry.border_box,+ LayoutRect::new(0.0, 0.0, 290.0, 240.0),+ );+ assert_eq!(root_geometry.layout_origin_in_document.x, 15.0);+ let child_id = output.source_output(1).unwrap().principal_box.unwrap();+ let child_geometry = output.box_geometry(child_id).unwrap();+ assert_eq!(child_geometry.border_box.width, 290.0);+ assert_eq!(child_geometry.layout_origin_in_document.x, 15.0);+ }+}++#[test]+fn scrollbar_hit_test_honors_the_same_ancestor_clip_as_paint() {+ let source = Source(vec![+ Node::element("root", vec![1]),+ Node::element("clipper", vec![2]),+ Node::element("scroller", vec![3]),+ Node::element("oversized-content", Vec::new()),+ ]);+ let mut styles = Styles::default();+ styles+ .0+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));+ let clipper = Style {+ size: Size {+ width: length(50.0),+ height: length(50.0),+ },+ overflow: Point {+ x: Overflow::Hidden,+ y: Overflow::Hidden,+ },+ ..Style::default()+ };+ styles.0.insert(1, resolved(LayoutDisplay::Block, clipper));+ let scroller = Style {+ size: Size {+ width: length(200.0),+ height: length(100.0),+ },+ overflow: Point {+ x: Overflow::Scroll,+ y: Overflow::Scroll,+ },+ ..Style::default()+ };+ styles.0.insert(2, resolved(LayoutDisplay::Block, scroller));+ styles+ .0+ .insert(3, fixed_size(LayoutDisplay::Block, 400.0, 300.0));++ let output = build(&source, &mut styles);+ let scroller_id = output.source_output(2).unwrap().principal_box.unwrap();+ assert!(+ output+ .scroll_extent(scroller_id)+ .unwrap()+ .vertical_scrollbar+ .is_some()+ );+ assert_eq!(+ output.scrollbar_hit_test(LayoutPoint::new(190.0, 30.0)),+ None,+ "a control clipped out of paint must not intercept input"+ );+}++#[test]+fn non_invertible_descendant_does_not_hide_a_valid_root_scrollbar_hit() {+ let source = Source(vec![+ Node::element("root", vec![1, 3]),+ Node::element("singular-scroller", vec![2]),+ Node::element("nested-content", Vec::new()),+ Node::element("root-overflow", Vec::new()),+ ]);+ let mut styles = Styles::default();+ styles+ .0+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));+ let scroller = Style {+ size: Size {+ width: length(200.0),+ height: length(100.0),+ },+ overflow: Point {+ x: Overflow::Scroll,+ y: Overflow::Scroll,+ },+ ..Style::default()+ };+ styles.0.insert(+ 1,+ resolved(LayoutDisplay::Block, scroller)+ .with_2d_transform(LayoutTransform2D::scale(0.0, 0.0)),+ );+ styles+ .0+ .insert(2, fixed_size(LayoutDisplay::Block, 400.0, 300.0));+ styles+ .0+ .insert(3, fixed_size(LayoutDisplay::Block, 500.0, 500.0));++ let output = build(&source, &mut styles);+ let hit = output+ .scrollbar_hit_test(LayoutPoint::new(310.0, 100.0))+ .expect("root scrollbar remains hittable past a singular candidate");+ assert_eq!(hit.source, 0);+}+#[test]fn display_none_root_uses_an_unmapped_internal_carrier() {let source = Source(vec![@@ -416,11 +886,11 @@ fn initial_containing_block_absolute_box_expands_root_scrollable_overflow() {assert_eq!(root_metrics.scroll_size.height, 450.0);assert_rect(root_metrics.scrollport.bounding_rect(),- LayoutRect::new(0.0, 0.0, 320.0, 240.0),+ LayoutRect::new(0.0, 0.0, 305.0, 225.0),);assert_eq!(root_metrics.maximum_scroll_offset,- LayoutPoint::new(230.0, 210.0)+ LayoutPoint::new(245.0, 225.0));}diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rsindex ff219e4b1..b1c23a361 100644--- a/moli-protocol/src/domains/page.rs+++ b/moli-protocol/src/domains/page.rs@@ -6673,13 +6673,18 @@ fn start_devtools_capture_screenshot_command(};let region = match command.clip.as_ref() {Some(DevToolsCaptureScreenshotClip::Box(clip)) => {- RendererScreenshotRegion::PageClip(RendererScreenshotClip {+ let clip = RendererScreenshotClip {x: clip.x,y: clip.y,width: clip.width,height: clip.height,scale: clip.scale,- })+ };+ if command.capture_beyond_viewport {+ RendererScreenshotRegion::PageClip(clip)+ } else {+ RendererScreenshotRegion::ViewportClip(clip)+ }}Some(DevToolsCaptureScreenshotClip::Element(_)) => {return PageCommandTaskStep::Complete(CommandOutputPlan::from_devtools_error(diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rsindex 560e76be5..0e6832920 100644--- a/moli-renderer-v8/src/native_bridge/element.rs+++ b/moli-renderer-v8/src/native_bridge/element.rs@@ -389,7 +389,8 @@ pub(crate) use geometry::{apply_scroll_observable_effects, observable_bounding_client_rect, observable_caret_position,observable_deep_hit_test, observable_event_offset, observable_geometry_batch,observable_hit_test_all, observable_input_hit_test, observable_scroll_adjusted_client_rect,- observable_sources_with_fragments, perform_wheel_scroll_default_action,+ observable_scrollbar_hit_test, observable_sources_with_fragments,+ perform_scrollbar_scroll_default_action, perform_wheel_scroll_default_action,queue_scroll_observable_effects, scroll_node_into_view_at_start,};pub(super) use geometry::{diff --git a/moli-renderer-v8/src/native_bridge/element/geometry.rs b/moli-renderer-v8/src/native_bridge/element/geometry.rsindex cec2de3e8..566ab229e 100644--- a/moli-renderer-v8/src/native_bridge/element/geometry.rs+++ b/moli-renderer-v8/src/native_bridge/element/geometry.rs@@ -9,9 +9,9 @@ pub(crate) use layout::{compute_mock_intersection_scrollport_client_rect,};pub(crate) use metrics::{- apply_scroll_observable_effects, perform_wheel_scroll_default_action,- queue_scroll_observable_effects, scroll_node_into_view_at_start,- scroll_node_into_view_if_needed,+ apply_scroll_observable_effects, perform_scrollbar_scroll_default_action,+ perform_wheel_scroll_default_action, queue_scroll_observable_effects,+ scroll_node_into_view_at_start, scroll_node_into_view_if_needed,};pub(in crate::native_bridge) use metrics::{node_client_height_getter_function, node_client_left_getter_function,@@ -29,7 +29,8 @@ pub(crate) use provider::{observable_client_rects, observable_deep_hit_test, observable_element_metrics,observable_event_offset, observable_geometry_batch, observable_hit_test_all,observable_input_hit_test, observable_scroll_adjusted_client_rect,- observable_scroll_into_view_geometry, observable_sources_with_fragments,+ observable_scroll_into_view_geometry, observable_scrollbar_hit_test,+ observable_sources_with_fragments,};pub(in crate::native_bridge) use rects::{node_get_bounding_client_rect_callback, node_get_client_rects_callback,diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/metrics.rs b/moli-renderer-v8/src/native_bridge/element/geometry/metrics.rsindex 6e1f633b4..fbf858225 100644--- a/moli-renderer-v8/src/native_bridge/element/geometry/metrics.rs+++ b/moli-renderer-v8/src/native_bridge/element/geometry/metrics.rs@@ -158,7 +158,7 @@ fn set_node_scroll_position(left: f64,top: f64,queue_observable_effects: bool,-) {+) -> bool {let (changed, document) = {let runtime = unsafe { &mut *runtime_ptr };let document = runtime.dom_host().owner_document_handle(handle);@@ -167,7 +167,7 @@ fn set_node_scroll_position(.node_mut(handle).and_then(|node| node.data_mut().as_element_mut())else {- return;+ return false;};(element.set_scroll_left(left) | element.set_scroll_top(top),@@ -177,6 +177,44 @@ fn set_node_scroll_position(if changed && queue_observable_effects {queue_scroll_observable_effects(scope, runtime_ptr, document, false);}+ changed+}++pub(crate) fn perform_scrollbar_scroll_default_action(+ scope: &mut v8::PinScope<'_, '_>,+ runtime_ptr: *mut JsContextHost,+ source: DomHandle,+ axis: moli_layout::LayoutScrollbarAxis,+ target: f64,+) -> bool {+ let (current_x, current_y) = node_scroll_position(unsafe { &*runtime_ptr }, source);+ let (target_x, target_y) = match axis {+ moli_layout::LayoutScrollbarAxis::Horizontal => (target, current_y),+ moli_layout::LayoutScrollbarAxis::Vertical => (current_x, target),+ };+ let document = unsafe { &*runtime_ptr }+ .dom_host()+ .owner_document_handle(source);+ let is_document_scroller = document.is_some_and(|document| {+ unsafe { &*runtime_ptr }+ .dom_host()+ .dom()+ .document_element_handle_for_document(document)+ == Some(source)+ });+ if is_document_scroller {+ apply_observable_window_scroll(+ scope,+ runtime_ptr,+ source,+ target_x,+ target_y,+ current_x,+ current_y,+ )+ } else {+ set_node_scroll_position(scope, runtime_ptr, source, target_x, target_y, true)+ }}pub(crate) fn queue_scroll_observable_effects(diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs b/moli-renderer-v8/src/native_bridge/element/geometry/provider.rsindex d9f67af89..4fcde0474 100644--- a/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs+++ b/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs@@ -4,7 +4,7 @@ use moli_layout::{LayoutAnswers, LayoutBoxModel, LayoutCaretPosition, LayoutDocumentMetrics,LayoutElementMetrics, LayoutError, LayoutFlushReason, LayoutHit, LayoutIntersectionGeometry,LayoutPassMetrics, LayoutPoint, LayoutQuad, LayoutQuery, LayoutQueryAnswer, LayoutQueryBatch,- LayoutScrollContainerMetrics, LayoutScrollIntoViewGeometry, LayoutSize,+ LayoutScrollContainerMetrics, LayoutScrollIntoViewGeometry, LayoutScrollbarHit, LayoutSize,};use super::layout::{@@ -299,6 +299,27 @@ pub(crate) fn observable_input_hit_test(observable_deep_hit_test(runtime, document, point, false)}+pub(crate) fn observable_scrollbar_hit_test(+ runtime: &JsContextHost,+ document: DomHandle,+ point: LayoutPoint,+) -> Result<Option<LayoutScrollbarHit<DomHandle>>, LayoutError> {+ if !runtime.layout_policy().uses_real_layout() {+ return Ok(None);+ }+ // Publish a current tree through the normal on-demand layout boundary;+ // the control hit itself deliberately does not become another query model.+ let _ = observable_geometry_batch(+ runtime,+ document,+ LayoutFlushReason::HitTest,+ &LayoutQueryBatch::new(vec![LayoutQuery::DocumentMetrics]),+ )?;+ Ok(runtime+ .with_latest_layout_tree_for_document(document, |tree| tree.scrollbar_hit_test(point))+ .flatten())+}+pub(crate) fn observable_deep_hit_test(runtime: &JsContextHost,document: DomHandle,diff --git a/moli-renderer-v8/src/runtime/page_screenshot.rs b/moli-renderer-v8/src/runtime/page_screenshot.rsindex f1cb9053e..7795de2dc 100644--- a/moli-renderer-v8/src/runtime/page_screenshot.rs+++ b/moli-renderer-v8/src/runtime/page_screenshot.rs@@ -32,6 +32,10 @@ pub struct RendererScreenshotClip {pub enum RendererScreenshotRegion {Viewport,FullDocument,+ /// A document-coordinate clip of the live viewport compositor surface.+ /// Root viewport controls remain present, matching CDP when+ /// `captureBeyondViewport` is false.+ ViewportClip(RendererScreenshotClip),PageClip(RendererScreenshotClip),}@@ -154,18 +158,25 @@ impl PageVm {impl RendererCaptureScreenshotRequest {fn paint_capture_request(&self) -> anyhow::Result<PaintCaptureRequest> {+ let include_viewport_controls = matches!(+ self.region,+ RendererScreenshotRegion::Viewport | RendererScreenshotRegion::ViewportClip(_)+ );let region = match self.region {RendererScreenshotRegion::Viewport => moli_layout::PaintCaptureRegion::Viewport,RendererScreenshotRegion::FullDocument => moli_layout::PaintCaptureRegion::FullDocument,- RendererScreenshotRegion::PageClip(clip) => moli_layout::PaintCaptureRegion::PageClip {- rect: LayoutRect::new(- finite_f32("clip x", clip.x)?,- finite_f32("clip y", clip.y)?,- finite_f32("clip width", clip.width)?,- finite_f32("clip height", clip.height)?,- ),- scale: finite_f32("clip scale", clip.scale)?,- },+ RendererScreenshotRegion::ViewportClip(clip)+ | RendererScreenshotRegion::PageClip(clip) => {+ moli_layout::PaintCaptureRegion::PageClip {+ rect: LayoutRect::new(+ finite_f32("clip x", clip.x)?,+ finite_f32("clip y", clip.y)?,+ finite_f32("clip width", clip.width)?,+ finite_f32("clip height", clip.height)?,+ ),+ scale: finite_f32("clip scale", clip.scale)?,+ }+ }};Ok(PaintCaptureRequest {region,@@ -175,6 +186,7 @@ impl RendererCaptureScreenshotRequest {true}},+ include_viewport_controls,max_width: self.max_width,max_height: self.max_height,})diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rsindex 70438ab0b..73a6e3668 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs@@ -442,7 +442,7 @@ frame.style.cssText = 'position:absolute;left:20px;top:10px;display:block;box-sidocument.body.appendChild(frame);const child = frame.contentDocument;-child.documentElement.style.cssText = 'margin:0;padding:0;background:rgb(0,255,255)';+child.documentElement.style.cssText = 'margin:0;padding:0;background:rgb(0,255,255);scrollbar-width:none';child.body.style.cssText = 'position:relative;margin:0;padding:0;width:200px;height:120px';const viewportSized = child.createElement('div');@@ -473,7 +473,7 @@ const nested = child.createElement('iframe');nested.style.cssText = 'position:absolute;left:10px;top:35px;display:block;box-sizing:border-box;width:40px;height:20px;margin:0;border:2px solid rgb(0,0,255);padding:2px;background:rgb(255,255,0)';child.body.appendChild(nested);const nestedDocument = nested.contentDocument;-nestedDocument.documentElement.style.cssText = 'margin:0;padding:0;background:rgb(255,0,255)';+nestedDocument.documentElement.style.cssText = 'margin:0;padding:0;background:rgb(255,0,255);scrollbar-width:none';nestedDocument.body.style.cssText = 'position:relative;margin:0;padding:0;width:80px;height:40px';const nestedViewportSized = nestedDocument.createElement('div');nestedViewportSized.style.cssText = 'width:50vw;height:100vh;background:rgb(0,0,0)';diff --git a/moli-renderer-v8/src/runtime/phase_one/mod.rs b/moli-renderer-v8/src/runtime/phase_one/mod.rsindex c22a49215..0694fb3ca 100644--- a/moli-renderer-v8/src/runtime/phase_one/mod.rs+++ b/moli-renderer-v8/src/runtime/phase_one/mod.rs@@ -561,6 +561,7 @@ html, body, main { display: block; margin: 0 }let mut page_vm = parse_phase_one_html_into_page_vm_for_test(r#"<!doctype html><html><head><style>html, body { display: block; margin: 0; padding: 0 }+html { scrollbar-width: none }body { background: rgb(0, 0, 255) }#grid { display: grid; width: 400px; height: 200px; gap: 20px 10px;grid-template-columns: 100px 1fr; grid-template-rows: 50px 1fr; grid-auto-rows: 30px }diff --git a/moli-renderer-v8/src/runtime/tests.rs b/moli-renderer-v8/src/runtime/tests.rsindex 706213bdd..45795e25a 100644--- a/moli-renderer-v8/src/runtime/tests.rs+++ b/moli-renderer-v8/src/runtime/tests.rs@@ -380,7 +380,7 @@ async fn capture_screenshot_uses_current_root_computed_background_and_viewport()&runtime,&loader,url,- "<!doctype html><style>html { background-color: rgb(255, 0, 0) }</style>",+ "<!doctype html><style>html { background-color: rgb(255, 0, 0); scrollbar-width: none }</style>",).await;let viewport = crate::protocol_types::ViewportSurface {@@ -872,6 +872,96 @@ async fn capture_screenshot_clip_and_full_document_keep_the_live_layout_viewportassert_eq!(decoded_png_pixel(&clip.bytes, 10, 10), [0, 255, 0, 255]);}+#[tokio::test(flavor = "multi_thread")]+async fn bounded_viewport_clip_keeps_root_controls_while_page_clip_omits_them() {+ let runtime = initialize_layout_test_runtime();+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default())+ .expect("default resource request client");+ let url = url::Url::parse("https://example.test/viewport-control-capture").unwrap();+ let page = create_test_html_page(+ &runtime,+ &loader,+ url,+ concat!(+ "<!doctype html><style>",+ "html,body{margin:0}",+ "html{scrollbar-color:rgb(255,0,0) rgb(0,0,255)}",+ "#content{width:200px;height:200px}",+ "</style><div id='content'></div>",+ ),+ )+ .await;+ let viewport = crate::protocol_types::ViewportSurface {+ inner_width: 100,+ inner_height: 100,+ outer_width: 100,+ outer_height: 100,+ device_pixel_ratio: 1.0,+ screen_width: 100,+ screen_height: 100,+ screen_avail_width: 100,+ screen_avail_height: 100,+ };+ page.run_async_command(RendererPageCommand::SetViewportSurface(Some(viewport)))+ .await+ .expect("viewport should update");+ let clip = super::RendererScreenshotClip {+ x: 0.0,+ y: 0.0,+ width: 100.0,+ height: 100.0,+ scale: 1.0,+ };++ let viewport_clip = capture_screenshot_with_request(+ &page,+ super::RendererCaptureScreenshotRequest {+ purpose: super::RendererScreenshotPurpose::Screenshot,+ format: super::RendererScreenshotFormat::Png,+ quality: 100,+ region: super::RendererScreenshotRegion::ViewportClip(clip),+ optimize_for_speed: false,+ max_width: None,+ max_height: None,+ },+ )+ .await;+ assert_eq!(+ decoded_png_pixel(&viewport_clip.bytes, 95, 30),+ [255, 0, 0, 255],+ "a bounded live-viewport capture includes its fixed root thumb"+ );+ assert_eq!(+ decoded_png_pixel(&viewport_clip.bytes, 92, 8),+ [255, 0, 0, 255],+ "the root control paints Chromium's up-arrow glyph"+ );+ assert_eq!(+ decoded_png_pixel(&viewport_clip.bytes, 87, 8),+ [0, 0, 255, 255],+ "the arrow remains centered inside its author-colored button"+ );++ let page_clip = capture_screenshot_with_request(+ &page,+ super::RendererCaptureScreenshotRequest {+ purpose: super::RendererScreenshotPurpose::Screenshot,+ format: super::RendererScreenshotFormat::Png,+ quality: 100,+ region: super::RendererScreenshotRegion::PageClip(clip),+ optimize_for_speed: false,+ max_width: None,+ max_height: None,+ },+ )+ .await;+ assert_eq!(+ decoded_png_pixel(&page_clip.bytes, 95, 30),+ [255, 255, 255, 255],+ "a capture-beyond-viewport page clip omits compositor controls"+ );+}+#[tokio::test(flavor = "multi_thread")]async fn capture_screenshot_rejects_full_document_at_the_128k_css_boundary() {let runtime = initialize_layout_test_runtime();@@ -12580,6 +12670,7 @@ async fn screenshot_and_screencast_flush_pending_wheel_actions_before_paint() {r#"<!doctype html><style>html, body { margin: 0; background: white; }+html { scrollbar-width: none; }body { height: 1200px; }#witness { position: fixed; inset: 0; background: white; }</style>diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rsindex b7dcd5638..c4b108a8c 100644--- a/moli-renderer-v8/src/script_vm.rs+++ b/moli-renderer-v8/src/script_vm.rs@@ -930,6 +930,7 @@ pub(super) struct ScriptVm {active_touch_point: Option<crate::runtime::RendererTouchPoint>,active_touch_points: BTreeMap<i32, ActiveTouchPoint>,suppress_compat_mouse_events: bool,+ active_scrollbar_drag: Option<ActiveScrollbarDrag>,active_drag_session: Option<ActiveDragSession>,promise_reject_dispatch: PromiseRejectDispatchSlot,next_internal_runtime_evaluate_call_id: i32,@@ -1012,6 +1013,14 @@ pub(super) struct ActiveDragSession {pub drop_allowed: bool,}+#[derive(Clone, Copy, Debug, PartialEq)]+pub(super) struct ActiveScrollbarDrag {+ pub source: DomHandle,+ pub scrollbar: moli_layout::LayoutScrollbarGeometry,+ pub pointer_origin: f32,+ pub viewport_to_local: moli_layout::LayoutTransform2D,+}+struct PageRuntimeObservableContext {execution_context_id: Option<i64>,context_token: RuntimeObservableContextToken,@@ -2306,6 +2315,7 @@ impl ScriptVmDefaultWorldBootstrap {active_touch_point: None,active_touch_points: BTreeMap::new(),suppress_compat_mouse_events: false,+ active_scrollbar_drag: None,active_drag_session: None,promise_reject_dispatch,next_internal_runtime_evaluate_call_id: 1,diff --git a/moli-renderer-v8/src/script_vm/input_dispatch.rs b/moli-renderer-v8/src/script_vm/input_dispatch.rsindex 50b42a868..821cefe5a 100644--- a/moli-renderer-v8/src/script_vm/input_dispatch.rs+++ b/moli-renderer-v8/src/script_vm/input_dispatch.rs@@ -8,7 +8,7 @@ use super::inspector::{current_selection_range, current_selection_state, is_space_key, key_target_info,option_is_disabled, radio_group_members,};-use super::{ActiveDragSession, ActiveTouchPoint, ScriptVm};+use super::{ActiveDragSession, ActiveScrollbarDrag, ActiveTouchPoint, ScriptVm};use crate::document_runtime::DomHandle;use crate::dom::native::{Node, SelectedFile};use crate::native_bridge::PointerCaptureDispatchEvent;@@ -22,10 +22,10 @@ use crate::native_bridge::element::{construct_pointer_event_with_related_target_and_modifiers, construct_simple_event,construct_touch_event, construct_touch_event_with_points, construct_wheel_event,contenteditable_editing_host, dispatch_public_event, observable_input_hit_test,- perform_drop_default_action, perform_mouse_focus_default_action,- perform_wheel_scroll_default_action, replace_contenteditable_selection,- replace_text_control_selection, select_contenteditable_contents,- text_control_set_selection_range_internal,+ observable_scrollbar_hit_test, perform_drop_default_action, perform_mouse_focus_default_action,+ perform_scrollbar_scroll_default_action, perform_wheel_scroll_default_action,+ replace_contenteditable_selection, replace_text_control_selection,+ select_contenteditable_contents, text_control_set_selection_range_internal,text_control_set_selection_range_with_direction_internal, text_control_value, update_focus,};use crate::runtime::{@@ -474,6 +474,12 @@ impl ScriptVm {}let buttons = buttons.unwrap_or(self.pressed_mouse_buttons);+ if let Some(outcome) =+ self.dispatch_native_scrollbar_mouse_event(x, y, event_name, button, buttons)?+ {+ return Ok(outcome);+ }+let hit_handle = observable_input_hit_test(&self._context_host.borrow(),self.document_runtime.document_handle(),@@ -932,6 +938,104 @@ impl ScriptVm {result}+ fn dispatch_native_scrollbar_mouse_event(+ &mut self,+ x: f64,+ y: f64,+ event_name: &str,+ button: i32,+ buttons: i32,+ ) -> Result<Option<RendererInputDispatchOutcome>> {+ if let Some(drag) = self.active_scrollbar_drag {+ match event_name {+ "mousemove" if buttons & 1 != 0 => {+ let local = drag+ .viewport_to_local+ .map_point(moli_layout::LayoutPoint::new(x as f32, y as f32));+ let coordinate = match drag.scrollbar.axis {+ moli_layout::LayoutScrollbarAxis::Horizontal => local.x,+ moli_layout::LayoutScrollbarAxis::Vertical => local.y,+ };+ let target = (drag.scrollbar.current_offset+ + (coordinate - drag.pointer_origin) * drag.scrollbar.drag_ratio())+ .clamp(drag.scrollbar.minimum_offset, drag.scrollbar.maximum_offset);+ self.with_default_context_scope(|scope, runtime_ptr| {+ perform_scrollbar_scroll_default_action(+ scope,+ runtime_ptr,+ drag.source,+ drag.scrollbar.axis,+ f64::from(target),+ );+ Ok(())+ })?;+ return Ok(Some(input_dispatch_outcome(true)));+ }+ "mouseup" if button == 0 => {+ self.active_scrollbar_drag = None;+ return Ok(Some(input_dispatch_outcome(true)));+ }+ "mousemove" => {+ self.active_scrollbar_drag = None;+ }+ _ => return Ok(Some(input_dispatch_outcome(true))),+ }+ }++ if !matches!(event_name, "mousedown" | "mouseup" | "mousemove") {+ return Ok(None);+ }+ let document = self.document_runtime.document_handle();+ let Some(hit) = observable_scrollbar_hit_test(+ &self._context_host.borrow(),+ document,+ moli_layout::LayoutPoint::new(x as f32, y as f32),+ )?+ else {+ return Ok(None);+ };+ if event_name == "mousedown" && button == 0 {+ match hit.part {+ moli_layout::LayoutScrollbarPart::Thumb => {+ self.active_scrollbar_drag = Some(ActiveScrollbarDrag {+ source: hit.source,+ scrollbar: hit.scrollbar,+ pointer_origin: hit.scrollbar.local_axis_coordinate(hit.local_point),+ viewport_to_local: hit.viewport_to_local,+ });+ }+ part => {+ let target = match part {+ moli_layout::LayoutScrollbarPart::BackButton => {+ hit.scrollbar.line_target(false)+ }+ moli_layout::LayoutScrollbarPart::ForwardButton => {+ hit.scrollbar.line_target(true)+ }+ moli_layout::LayoutScrollbarPart::BackTrack => {+ hit.scrollbar.page_target(false)+ }+ moli_layout::LayoutScrollbarPart::ForwardTrack => {+ hit.scrollbar.page_target(true)+ }+ moli_layout::LayoutScrollbarPart::Thumb => unreachable!(),+ };+ self.with_default_context_scope(|scope, runtime_ptr| {+ perform_scrollbar_scroll_default_action(+ scope,+ runtime_ptr,+ hit.source,+ hit.scrollbar.axis,+ f64::from(target),+ );+ Ok(())+ })?;+ }+ }+ }+ Ok(Some(input_dispatch_outcome(true)))+ }+pub(crate) fn dispatch_touch_event_at_point(&mut self,x: f64,diff --git a/moli-renderer-v8/src/script_vm/input_helpers.rs b/moli-renderer-v8/src/script_vm/input_helpers.rsindex a7659e40c..99e2cb2ec 100644--- a/moli-renderer-v8/src/script_vm/input_helpers.rs+++ b/moli-renderer-v8/src/script_vm/input_helpers.rs@@ -60,6 +60,7 @@ pub(super) fn clear_input_dispatch_state(vm: &mut ScriptVm) {vm.active_touch_point = None;vm.active_touch_points.clear();vm.active_drag_session = None;+ vm.active_scrollbar_drag = None;vm.suppress_compat_mouse_events = false;vm._context_host.borrow_mut().clear_pointer_capture_state();}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 00cd8c931..8e8450f03 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@@ -418,6 +418,391 @@ fn wheel_default_action_scrolls_the_innermost_container_then_chains_to_the_root();}+#[test]+fn classic_scrollbar_metrics_and_thumb_drag_match_chromium_without_dom_mouse_events() {+ let mut vm = new_storage_test_vm("https://classic-scrollbar-input.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="width:200px;height:100px;overflow:auto">+ <div style="width:400px;height:300px"></div>+ </div>+ <div id="thin" style="width:200px;height:100px;overflow:scroll;scrollbar-width:thin">+ <div style="width:400px;height:300px"></div>+ </div>+ <div id="none" style="width:200px;height:100px;overflow:scroll;scrollbar-width:none">+ <div style="width:400px;height:300px"></div>+ </div>+ <div id="stable" style="width:200px;height:100px;overflow:auto;scrollbar-gutter:stable">+ <div style="height:20px"></div>+ </div>+ <div id="both" style="width:200px;height:100px;overflow:auto;scrollbar-gutter:stable both-edges">+ <div style="height:20px"></div>+ </div>+ <div id="feedback" style="width:200px;height:100px;overflow:auto">+ <div style="width:200px;height:200px"></div>+ </div>+ <div id="rtl" style="width:200px;height:100px;overflow:auto;direction:rtl;scrollbar-color:red blue">+ <div style="width:400px;height:300px"></div>+ </div>`;+ window.__scrollbarDomEvents = [];+ for (const name of ["pointerdown", "pointermove", "pointerup", "mousedown", "mousemove", "mouseup", "click"]) {+ document.addEventListener(name, () => window.__scrollbarDomEvents.push(name), true);+ }+ })()+ "#,+ )+ .expect("scrollbar fixture should initialize");+ refresh_layout_for_test(&mut vm);++ assert_eq!(+ vm.eval(+ r#"JSON.stringify([+ scroller.clientWidth, scroller.clientHeight,+ thin.clientWidth, thin.clientHeight,+ none.clientWidth, none.clientHeight,+ scroller.scrollWidth, scroller.scrollHeight,+ stable.clientWidth, stable.clientLeft, stable.firstElementChild.offsetWidth,+ Math.round(stable.firstElementChild.getBoundingClientRect().left),+ both.clientWidth, both.clientLeft, both.firstElementChild.offsetWidth,+ Math.round(both.firstElementChild.getBoundingClientRect().left),+ feedback.clientWidth, feedback.clientHeight,+ rtl.clientWidth, rtl.clientLeft, rtl.scrollWidth, rtl.scrollLeft+ ])"#,+ )+ .expect("classic scrollbar metrics should evaluate"),+ "[185,85,190,90,200,100,400,300,185,0,185,0,170,15,170,15,185,85,185,15,400,0]"+ );++ vm.dispatch_mouse_event_at_point(190.0, 30.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("vertical thumb press should dispatch");+ vm.dispatch_mouse_event_at_point(190.0, 50.0, "mousemove", -1, Some(1), 0.0, 0.0)+ .expect("vertical thumb drag should dispatch");+ vm.dispatch_mouse_event_at_point(190.0, 50.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("vertical thumb release should dispatch");++ vm.dispatch_mouse_event_at_point(50.0, 90.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("horizontal thumb press should dispatch");+ vm.dispatch_mouse_event_at_point(90.0, 90.0, "mousemove", -1, Some(1), 0.0, 0.0)+ .expect("horizontal thumb drag should dispatch");+ vm.dispatch_mouse_event_at_point(90.0, 90.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("horizontal thumb release should dispatch");++ let before_controls = vm+ .eval("scroller.scrollTop")+ .expect("pre-control scrollTop should evaluate")+ .parse::<f64>()+ .expect("pre-control scrollTop should be numeric");+ vm.dispatch_mouse_event_at_point(190.0, 5.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("back button press should dispatch");+ vm.dispatch_mouse_event_at_point(190.0, 5.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("back button release should dispatch");+ let after_back = vm+ .eval("scroller.scrollTop")+ .expect("back-button scrollTop should evaluate")+ .parse::<f64>()+ .expect("back-button scrollTop should be numeric");+ assert!((after_back - (before_controls - 40.0)).abs() < 0.01);++ vm.dispatch_mouse_event_at_point(190.0, 80.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("forward button press should dispatch");+ vm.dispatch_mouse_event_at_point(190.0, 80.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("forward button release should dispatch");+ let after_forward = vm+ .eval("scroller.scrollTop")+ .expect("forward-button scrollTop should evaluate")+ .parse::<f64>()+ .expect("forward-button scrollTop should be numeric");+ assert!((after_forward - before_controls).abs() < 0.01);++ vm.dispatch_mouse_event_at_point(190.0, 60.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("forward track press should dispatch");+ vm.dispatch_mouse_event_at_point(190.0, 60.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("forward track release should dispatch");+ let after_track = vm+ .eval("scroller.scrollTop")+ .expect("track scrollTop should evaluate")+ .parse::<f64>()+ .expect("track scrollTop should be numeric");+ assert!((after_track - (before_controls + 85.0 * 0.875)).abs() < 0.01);++ let result = vm+ .eval(+ r#"JSON.stringify({+ left: scroller.scrollLeft,+ top: scroller.scrollTop,+ events: window.__scrollbarDomEvents+ })"#,+ )+ .expect("post-drag scroll state should evaluate");+ let result: serde_json::Value = serde_json::from_str(&result).expect("scroll result JSON");+ assert!(result["left"].as_f64().is_some_and(|value| value > 50.0));+ assert!(result["top"].as_f64().is_some_and(|value| value > 100.0));+ assert_eq!(result["events"], serde_json::json!([]));+}++#[test]+fn root_classic_scrollbars_stay_viewport_fixed_and_drive_window_scroll() {+ let mut vm = new_storage_test_vm("https://root-classic-scrollbar.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: 1920,+ screen_height: 1080,+ screen_avail_width: 1920,+ screen_avail_height: 1040,+ }))+ .expect("root scrollbar viewport 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.margin = "0";+ document.body.style.margin = "0";+ document.body.innerHTML = '<div style="width:1600px;height:1200px"></div>';+ window.__rootScrollbarDomEvents = [];+ for (const name of ["pointerdown", "pointermove", "pointerup", "mousedown", "mousemove", "mouseup", "click"]) {+ document.addEventListener(name, () => __rootScrollbarDomEvents.push(name), true);+ }+ })()+ "#,+ )+ .expect("root scrollbar fixture should initialize");+ refresh_layout_for_test(&mut vm);+ assert_eq!(+ vm.eval(+ "JSON.stringify([document.documentElement.clientWidth, document.documentElement.clientHeight, document.documentElement.scrollWidth, document.documentElement.scrollHeight])"+ )+ .expect("root scrollbar metrics should evaluate"),+ "[785,585,1600,1200]"+ );++ let horizontal_hit = crate::native_bridge::element::observable_scrollbar_hit_test(+ &vm._context_host.borrow(),+ vm.document_runtime.document_handle(),+ moli_layout::LayoutPoint::new(30.0, 590.0),+ )+ .expect("root horizontal scrollbar hit test should succeed");+ assert!(+ horizontal_hit.is_some_and(|hit| {+ hit.scrollbar.axis == moli_layout::LayoutScrollbarAxis::Horizontal+ && hit.part == moli_layout::LayoutScrollbarPart::Thumb+ }),+ "root horizontal thumb should own its viewport-fixed coordinates: {horizontal_hit:?}"+ );++ vm.dispatch_mouse_event_at_point(790.0, 30.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("root vertical thumb press should dispatch");+ vm.dispatch_mouse_event_at_point(790.0, 100.0, "mousemove", -1, Some(1), 0.0, 0.0)+ .expect("root vertical thumb drag should dispatch");+ vm.dispatch_mouse_event_at_point(790.0, 100.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("root vertical thumb release should dispatch");+ let horizontal_hit_after_vertical_drag =+ crate::native_bridge::element::observable_scrollbar_hit_test(+ &vm._context_host.borrow(),+ vm.document_runtime.document_handle(),+ moli_layout::LayoutPoint::new(30.0, 590.0),+ )+ .expect("post-scroll root horizontal scrollbar hit test should succeed");+ let root_extent_after_vertical_drag = vm+ ._context_host+ .borrow()+ .with_latest_layout_tree_for_document(vm.document_runtime.document_handle(), |tree| {+ tree.scroll_extent(tree.root_box).cloned()+ })+ .flatten();+ assert!(+ horizontal_hit_after_vertical_drag.is_some_and(|hit| {+ hit.scrollbar.axis == moli_layout::LayoutScrollbarAxis::Horizontal+ && hit.part == moli_layout::LayoutScrollbarPart::Thumb+ }),+ "root horizontal thumb should stay viewport-fixed after vertical scrolling: hit={horizontal_hit_after_vertical_drag:?}, extent={root_extent_after_vertical_drag:?}"+ );+ vm.dispatch_mouse_event_at_point(30.0, 590.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("root horizontal thumb press should dispatch");+ vm.dispatch_mouse_event_at_point(100.0, 590.0, "mousemove", -1, Some(1), 0.0, 0.0)+ .expect("root horizontal thumb drag should dispatch");+ vm.dispatch_mouse_event_at_point(100.0, 590.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("root horizontal thumb release should dispatch");++ let result = vm+ .eval("JSON.stringify([window.scrollX, window.scrollY, __rootScrollbarDomEvents])")+ .expect("root post-drag state should evaluate");+ let result: serde_json::Value = serde_json::from_str(&result).expect("root scroll JSON");+ assert!(+ result[0].as_f64().is_some_and(|value| value > 100.0),+ "root horizontal thumb drag should advance scrollX: {result}"+ );+ assert!(+ result[1].as_f64().is_some_and(|value| value > 100.0),+ "root vertical thumb drag should advance scrollY: {result}"+ );+ assert_eq!(result[2], serde_json::json!([]));+}++#[test]+fn root_scrollbar_gutters_size_the_initial_containing_block_once() {+ let mut vm = new_storage_test_vm("https://root-scrollbar-containing-block.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: 1920,+ screen_height: 1080,+ screen_avail_width: 1920,+ screen_avail_height: 1040,+ }))+ .expect("root gutter viewport 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;height:100%";+ document.body.style.cssText = "margin:0;height:100%";+ document.body.innerHTML = `+ <div id="wide" style="width:1600px;height:50%"></div>+ <div id="fixed" style="position:fixed;right:0;bottom:0;width:10px;height:10px"></div>`;+ })()+ "#,+ )+ .expect("percentage root overflow 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();+ const wideRect = wide.getBoundingClientRect();+ const fixedRect = fixed.getBoundingClientRect();+ return [+ document.documentElement.clientWidth,+ document.documentElement.clientHeight,+ document.documentElement.scrollWidth,+ document.documentElement.scrollHeight,+ html.x, html.width, html.height,+ body.x, body.width, body.height,+ wideRect.width, wideRect.height,+ fixedRect.x, fixedRect.y+ ];+ })())+ "#,+ )+ .expect("percentage root overflow metrics should evaluate"),+ "[800,585,1600,585,0,800,585,0,800,585,1600,292.5,790,575]"+ );++ vm.eval(+ r#"+ document.documentElement.style.cssText =+ "margin:0;height:100%;overflow:auto;scrollbar-gutter:stable both-edges";+ document.body.style.cssText = "margin:0;height:100%";+ document.body.innerHTML = '<div id="content"></div>';+ "#,+ )+ .expect("stable root 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,+ document.documentElement.clientHeight,+ document.documentElement.scrollWidth,+ document.documentElement.scrollHeight,+ html.x, html.width, body.x, body.width+ ];+ })())+ "#,+ )+ .expect("empty stable root gutter metrics should evaluate"),+ "[800,600,770,600,15,770,15,770]"+ );++ vm.eval("content.style.height = '1200px'")+ .expect("stable root fixture should overflow vertically");+ 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,+ document.documentElement.clientHeight,+ document.documentElement.scrollWidth,+ document.documentElement.scrollHeight,+ html.x, html.width, body.x, body.width+ ];+ })())+ "#,+ )+ .expect("overflowing stable root gutter metrics should evaluate"),+ "[785,600,770,1200,15,770,15,770]"+ );++ vm.eval(+ r#"+ document.documentElement.style.cssText =+ "margin:0;height:100%;overflow:auto;direction:rtl";+ document.body.style.cssText = "margin:0;height:100%";+ content.style.height = "1200px";+ "#,+ )+ .expect("RTL root scrollbar fixture should initialize");+ refresh_layout_for_test(&mut vm);+ let right = crate::native_bridge::element::observable_scrollbar_hit_test(+ &vm._context_host.borrow(),+ vm.document_runtime.document_handle(),+ moli_layout::LayoutPoint::new(790.0, 30.0),+ )+ .expect("RTL root right-edge hit test should succeed");+ assert!(+ right.is_some_and(|hit| {+ hit.scrollbar.axis == moli_layout::LayoutScrollbarAxis::Vertical+ })+ );+ let left = crate::native_bridge::element::observable_scrollbar_hit_test(+ &vm._context_host.borrow(),+ vm.document_runtime.document_handle(),+ moli_layout::LayoutPoint::new(5.0, 30.0),+ )+ .expect("RTL root left-edge hit test should succeed");+ assert_eq!(+ left, None,+ "the root viewport scrollbar stays physical-right"+ );+}+#[test]fn dom_core_prototype_accessors_brand_check_live_and_detached_receivers() {let mut vm = new_storage_test_vm("https://example.com/");