The headless browser for AI agents and web scraping
fix(browser): improve CDP compatibility and concurrency
SGavrla156914446e0
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex 78f4f4ec..0fadfee7 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -4564,6 +4564,12 @@ impl Page {}}+ pub fn has_pending_navigation(&self) -> bool {+ self.js+ .as_ref()+ .is_some_and(|js| js.has_pending_navigation())+ }+pub fn take_pending_binding_calls(&self) -> Vec<(String, String)> {if let Some(js) = &self.js {js.take_pending_binding_calls()diff --git a/crates/obscura-cdp/src/domains/input.rs b/crates/obscura-cdp/src/domains/input.rsindex be9060cb..382d8e98 100644--- a/crates/obscura-cdp/src/domains/input.rs+++ b/crates/obscura-cdp/src/domains/input.rs@@ -141,8 +141,32 @@ pub async fn handle(if (!target) return;\globalThis.__obscura_click_target = target;\globalThis.__obscura_mouse_down = {{target:target,button:{button_code},clickCount:{click_count}}};\- var evt = globalThis.__obscura_markTrusted(new MouseEvent('mousedown', {{bubbles:true,cancelable:true,view:globalThis,clientX:{x},clientY:{y},button:{button_code},buttons:{buttons},detail:{click_count},altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\+ var previousTarget = globalThis.__obscura_mouse_over_target || null;\+ if (previousTarget !== target) {{\+ function ancestry(node) {{ var path=[]; while (node) {{ path.push(node); node=node.parentNode || null; }} return path; }}\+ function pointerEvent(node,type,bubbles,related) {{ node.dispatchEvent(globalThis.__obscura_markTrusted(new PointerEvent(type, {{bubbles:bubbles,cancelable:bubbles,composed:bubbles,view:globalThis,clientX:{x},clientY:{y},button:{button_code},buttons:{buttons},detail:0,pointerId:1,pointerType:'mouse',isPrimary:true,pressure:{pointer_pressure},relatedTarget:related,altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}))); }}\+ function mouseEvent(node,type,bubbles,related) {{ node.dispatchEvent(globalThis.__obscura_markTrusted(new MouseEvent(type, {{bubbles:bubbles,cancelable:bubbles,composed:bubbles,view:globalThis,clientX:{x},clientY:{y},button:{button_code},buttons:{buttons},detail:0,relatedTarget:related,altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}))); }}\+ var oldPath = previousTarget && previousTarget.isConnected ? ancestry(previousTarget) : [];\+ var newPath = ancestry(target);\+ var common = newPath.find(function(node) {{ return oldPath.includes(node); }}) || null;\+ var exited = common ? oldPath.slice(0, oldPath.indexOf(common)) : oldPath;\+ var entered = common ? newPath.slice(0, newPath.indexOf(common)) : newPath;\+ if (previousTarget && previousTarget.isConnected) pointerEvent(previousTarget,'pointerout',true,target);\+ for (var pi=0; pi<exited.length; pi++) pointerEvent(exited[pi],'pointerleave',false,target);\+ pointerEvent(target,'pointerover',true,previousTarget);\+ for (var pe=entered.length-1; pe>=0; pe--) pointerEvent(entered[pe],'pointerenter',false,previousTarget);\+ if (previousTarget && previousTarget.isConnected) mouseEvent(previousTarget,'mouseout',true,target);\+ for (var mi=0; mi<exited.length; mi++) mouseEvent(exited[mi],'mouseleave',false,target);\+ mouseEvent(target,'mouseover',true,previousTarget);\+ for (var me=entered.length-1; me>=0; me--) mouseEvent(entered[me],'mouseenter',false,previousTarget);\+ globalThis.__obscura_mouse_over_target = target;\+ }}\+ var focusTarget = target.closest && target.closest('input,select,textarea,button,a[href],[tabindex],[contenteditable]');\+ var pointer = globalThis.__obscura_markTrusted(new PointerEvent('pointerdown', {{bubbles:true,cancelable:true,composed:true,view:globalThis,clientX:{x},clientY:{y},button:{button_code},buttons:{buttons},detail:0,pointerId:1,pointerType:'mouse',isPrimary:true,pressure:{pointer_pressure},altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\+ target.dispatchEvent(pointer);\+ var evt = globalThis.__obscura_markTrusted(new MouseEvent('mousedown', {{bubbles:true,cancelable:true,composed:true,view:globalThis,clientX:{x},clientY:{y},button:{button_code},buttons:{buttons},detail:{click_count},altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\target.dispatchEvent(evt);\+ if (focusTarget && !globalThis.__obscura_isDisabled(focusTarget)) focusTarget.focus();\}})()",x = x,y = y,@@ -153,6 +177,7 @@ pub async fn handle(ctrl_key = ctrl_key,meta_key = meta_key,shift_key = shift_key,+ pointer_pressure = if buttons == 0 { 0.0 } else { 0.5 },);page.evaluate(&code);}@@ -164,7 +189,9 @@ pub async fn handle(if (!target) return;\var down = globalThis.__obscura_mouse_down;\globalThis.__obscura_mouse_down = null;\- var evt = globalThis.__obscura_markTrusted(new MouseEvent('mouseup', {{bubbles:true,cancelable:true,view:globalThis,clientX:{x},clientY:{y},button:{button_code},buttons:0,detail:{click_count},altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\+ var pointer = globalThis.__obscura_markTrusted(new PointerEvent('pointerup', {{bubbles:true,cancelable:true,composed:true,view:globalThis,clientX:{x},clientY:{y},button:{button_code},buttons:0,detail:0,pointerId:1,pointerType:'mouse',isPrimary:true,pressure:0,altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\+ target.dispatchEvent(pointer);\+ var evt = globalThis.__obscura_markTrusted(new MouseEvent('mouseup', {{bubbles:true,cancelable:true,composed:true,view:globalThis,clientX:{x},clientY:{y},button:{button_code},buttons:0,detail:{click_count},altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\target.dispatchEvent(evt);\if (!down || down.button !== {button_code} || {button_code} !== 0) return;\var clickTarget = down.target;\@@ -196,7 +223,7 @@ pub async fn handle(clickTarget.checked = !oldChecked;\clickTarget.indeterminate = false;\}}\- var click = globalThis.__obscura_markTrusted(new MouseEvent('click', {{bubbles:true,cancelable:true,view:globalThis,clientX:{x},clientY:{y},button:0,buttons:0,detail:{click_count},altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\+ var click = globalThis.__obscura_markTrusted(new MouseEvent('click', {{bubbles:true,cancelable:true,composed:true,view:globalThis,clientX:{x},clientY:{y},button:0,buttons:0,detail:{click_count},altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\var cancelled = !clickTarget.dispatchEvent(click);\if (cancelled) {{\if (radioStates) {{\@@ -242,17 +269,8 @@ pub async fn handle(shift_key = shift_key,);page.evaluate(&code);- let moved = page- .process_pending_navigation()- .await- .map_err(|e| e.to_string())?;- // Fork: a single page app answers a click by routing itself,- // with no document fetch. The client still has to be told the- // frame moved, or the click looks like it did nothing.- if moved {- let url = page.url_string();- let frame_id = page.frame_id.clone();- Some((page.id.clone(), frame_id, url))+ if !page.has_pending_navigation() && page.sync_virtual_url() {+ Some((page.id.clone(), page.frame_id.clone(), page.url_string()))} else {None}diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex b877d199..a4276956 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -89,34 +89,43 @@ fn bearer_authorized(head: &str, expected: Option<&str>) -> bool {}}-fn host_matches_bind(host_header: &str, bind_ip: std::net::IpAddr, port: u16) -> bool {- if bind_ip.is_unspecified() {- return true;- }+fn host_matches_bind(+ host_header: &str,+ bind_ip: std::net::IpAddr,+ port: u16,+ forwarded: Option<(std::net::IpAddr, u16)>,+) -> bool {let Ok(url) = url::Url::parse(&format!("http://{host_header}/")) else {return false;};- if url.port_or_known_default() != Some(port) {- return false;- }- match (url.host(), bind_ip) {- (Some(url::Host::Ipv4(address)), std::net::IpAddr::V4(bind)) => {- address == bind || (bind.is_loopback() && address.is_loopback())- }- (Some(url::Host::Ipv6(address)), std::net::IpAddr::V6(bind)) => {- address == bind || (bind.is_loopback() && address.is_loopback())- }- (Some(url::Host::Ipv4(address)), std::net::IpAddr::V6(bind)) => {- bind.is_loopback() && address.is_loopback()- }- (Some(url::Host::Ipv6(address)), std::net::IpAddr::V4(bind)) => {- bind.is_loopback() && address.is_loopback()+ fn host_matches_ip(url: &url::Url, bind_ip: std::net::IpAddr) -> bool {+ if bind_ip.is_unspecified() {+ return true;}- (Some(url::Host::Domain(domain)), _) => {- bind_ip.is_loopback() && domain.eq_ignore_ascii_case("localhost")+ match (url.host(), bind_ip) {+ (Some(url::Host::Ipv4(address)), std::net::IpAddr::V4(bind)) => {+ address == bind || (bind.is_loopback() && address.is_loopback())+ }+ (Some(url::Host::Ipv6(address)), std::net::IpAddr::V6(bind)) => {+ address == bind || (bind.is_loopback() && address.is_loopback())+ }+ (Some(url::Host::Ipv4(address)), std::net::IpAddr::V6(bind)) => {+ bind.is_loopback() && address.is_loopback()+ }+ (Some(url::Host::Ipv6(address)), std::net::IpAddr::V4(bind)) => {+ bind.is_loopback() && address.is_loopback()+ }+ (Some(url::Host::Domain(domain)), _) => {+ bind_ip.is_loopback() && domain.eq_ignore_ascii_case("localhost")+ }+ (None, _) => false,}- (None, _) => false,}+ (url.port_or_known_default() == Some(port) && host_matches_ip(&url, bind_ip))+ || forwarded.is_some_and(|(forwarded_ip, forwarded_port)| {+ url.port_or_known_default() == Some(forwarded_port)+ && host_matches_ip(&url, forwarded_ip)+ })}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -131,12 +140,15 @@ fn control_refusal(head: &str,bind_ip: std::net::IpAddr,port: u16,+ forwarded: Option<(std::net::IpAddr, u16)>,auth_token: Option<&str>,) -> Option<ControlRefusal> {if header_value(head, "origin").is_some() {return Some(ControlRefusal::BrowserOrigin);}- if !header_value(head, "host").is_some_and(|host| host_matches_bind(host, bind_ip, port)) {+ if !header_value(head, "host")+ .is_some_and(|host| host_matches_bind(host, bind_ip, port, forwarded))+ {return Some(ControlRefusal::ForeignHost);}if !bearer_authorized(head, auth_token) {@@ -289,7 +301,28 @@ pub async fn start_with_serve_options_and_limit(.map_err(|e| anyhow::anyhow!("invalid --host '{}': {}", host, e))?;let addr = SocketAddr::new(ip, port);let auth_token = control_token_from_env()?;- if !ip.is_loopback() && auth_token.is_none() {+ let forwarded_host = std::env::var("OBSCURA_CDP_FORWARDED_HOST").ok();+ let forwarded_port = std::env::var("OBSCURA_CDP_FORWARDED_PORT").ok();+ let forwarded = match (forwarded_host, forwarded_port) {+ (None, None) => None,+ (Some(host), Some(port)) => Some((+ host.parse::<std::net::IpAddr>().map_err(|error| {+ anyhow::anyhow!("invalid OBSCURA_CDP_FORWARDED_HOST '{}': {}", host, error)+ })?,+ port.parse::<u16>().map_err(|error| {+ anyhow::anyhow!("invalid OBSCURA_CDP_FORWARDED_PORT '{}': {}", port, error)+ })?,+ )),+ _ => anyhow::bail!(+ "OBSCURA_CDP_FORWARDED_HOST and OBSCURA_CDP_FORWARDED_PORT must be set together"+ ),+ };+ if forwarded.is_some() && !ip.is_loopback() {+ anyhow::bail!("forwarded CDP authority is only valid for loopback workers");+ }+ let publicly_reachable = !ip.is_loopback()+ || forwarded.is_some_and(|(forwarded_ip, _)| !forwarded_ip.is_loopback());+ if publicly_reachable && auth_token.is_none() {anyhow::bail!("refusing to expose CDP without authentication; set OBSCURA_CDP_TOKEN to at least 32 bytes");@@ -414,6 +447,7 @@ pub async fn start_with_serve_options_and_limit(stream,ip,port,+ forwarded,accept_auth_token.as_deref(),&ws_tx,&head,@@ -907,11 +941,12 @@ fn accept_dispatch(stream: std::net::TcpStream,bind_ip: std::net::IpAddr,port: u16,+ forwarded: Option<(std::net::IpAddr, u16)>,auth_token: Option<&str>,ws_tx: &mpsc::Sender<std::net::TcpStream>,head: &str,) -> anyhow::Result<()> {- if let Some(refusal) = control_refusal(head, bind_ip, port, auth_token) {+ if let Some(refusal) = control_refusal(head, bind_ip, port, forwarded, auth_token) {refuse_control_connection(stream, refusal);return Ok(());}@@ -2000,7 +2035,7 @@ mod tests {fn native_loopback_cdp_request_is_allowed() {let head = native_head("127.0.0.1:9222");assert_eq!(- control_refusal(&head, "127.0.0.1".parse().unwrap(), 9222, None),+ control_refusal(&head, "127.0.0.1".parse().unwrap(), 9222, None, None),None);}@@ -2012,7 +2047,13 @@ mod tests {"Origin: https://evil.example\r\nUpgrade: websocket",);assert_eq!(- control_refusal(&with_origin, "127.0.0.1".parse().unwrap(), 9222, None),+ control_refusal(+ &with_origin,+ "127.0.0.1".parse().unwrap(),+ 9222,+ None,+ None,+ ),Some(ControlRefusal::BrowserOrigin));assert_eq!(@@ -2021,9 +2062,45 @@ mod tests {"127.0.0.1".parse().unwrap(),9222,None,+ None,+ ),+ Some(ControlRefusal::ForeignHost)+ );+ }++ #[test]+ fn loopback_worker_accepts_only_its_forwarded_public_port() {+ let bind = "127.0.0.1".parse().unwrap();+ let forwarded = Some((bind, 9222));+ assert_eq!(+ control_refusal(&native_head("127.0.0.1:9222"), bind, 9223, forwarded, None),+ None+ );+ assert_eq!(+ control_refusal(+ &native_head("rebind.example:9222"),+ bind,+ 9223,+ forwarded,+ None,),Some(ControlRefusal::ForeignHost));+ assert_eq!(+ control_refusal(&native_head("127.0.0.1:9444"), bind, 9223, forwarded, None),+ Some(ControlRefusal::ForeignHost)+ );+ }++ #[test]+ fn public_worker_authority_still_requires_authentication() {+ let bind = "127.0.0.1".parse().unwrap();+ let public = Some(("0.0.0.0".parse().unwrap(), 9222));+ let head = native_head("cdp.example.test:9222");+ assert_eq!(+ control_refusal(&head, bind, 9223, public, Some("secret")),+ Some(ControlRefusal::Unauthorized)+ );}#[test]@@ -2187,6 +2264,138 @@ mod tests {.await;}+ #[tokio::test(flavor = "current_thread")]+ async fn click_navigation_acknowledges_input_before_navigation_events() {+ tokio::task::LocalSet::new()+ .run_until(async {+ let (server_tx, server_rx) = tokio::sync::mpsc::unbounded_channel();+ let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();+ let shutdown = std::sync::Arc::new(tokio::sync::Notify::new());+ let default_context = crate::dispatch::CdpContext::new().default_context;+ let processor = tokio::task::spawn_local(super::cdp_processor(+ server_rx,+ default_context,+ shutdown,+ ));++ server_tx+ .send(super::ServerMessage::NewConnection {+ reply_tx: reply_tx.clone(),+ })+ .unwrap();+ reply_rx.recv().await.expect("processor init");++ let send = |value: serde_json::Value| {+ server_tx+ .send(super::ServerMessage::Cdp(super::CdpMessage {+ text: value.to_string(),+ reply_tx: reply_tx.clone(),+ }))+ .unwrap();+ };+ send(json!({+ "id": 1,+ "method": "Target.createTarget",+ "params": {"url": "about:blank"},+ }));++ let mut session_id = None;+ loop {+ let value: serde_json::Value = serde_json::from_str(+ &tokio::time::timeout(std::time::Duration::from_secs(2), reply_rx.recv())+ .await+ .expect("create target timeout")+ .expect("create target response"),+ )+ .unwrap();+ if session_id.is_none() {+ session_id = value["params"]["sessionId"].as_str().map(str::to_string);+ }+ if value["id"] == 1 {+ break;+ }+ }+ let session_id = session_id.expect("attached page session");++ send(json!({+ "id": 2,+ "method": "Runtime.evaluate",+ "sessionId": session_id,+ "params": {"expression": "document.body.innerHTML='<a id=route href=\"data:text/html,navigated\">go</a>';document.elementFromPoint=()=>route"},+ }));+ loop {+ let value: serde_json::Value = serde_json::from_str(+ &tokio::time::timeout(std::time::Duration::from_secs(2), reply_rx.recv())+ .await+ .expect("setup timeout")+ .expect("setup response"),+ )+ .unwrap();+ if value["id"] == 2 {+ break;+ }+ }++ for (id, event_type) in [(3, "mousePressed"), (4, "mouseReleased")] {+ send(json!({+ "id": id,+ "method": "Input.dispatchMouseEvent",+ "sessionId": session_id,+ "params": {"type": event_type, "x": 0, "y": 0, "button": "left"},+ }));+ if id == 3 {+ loop {+ let value: serde_json::Value = serde_json::from_str(+ &tokio::time::timeout(+ std::time::Duration::from_secs(2),+ reply_rx.recv(),+ )+ .await+ .expect("mouse press timeout")+ .expect("mouse press response"),+ )+ .unwrap();+ if value["id"] == 3 {+ break;+ }+ }+ }+ }++ let mut input_acknowledged = false;+ loop {+ let value: serde_json::Value = serde_json::from_str(+ &tokio::time::timeout(std::time::Duration::from_secs(2), reply_rx.recv())+ .await+ .expect("click navigation timeout")+ .expect("click navigation response"),+ )+ .unwrap();+ if value["id"] == 4 {+ input_acknowledged = true;+ }+ if value["method"] == "Page.frameNavigated"+ && value["params"]["frame"]["url"]+ .as_str()+ .is_some_and(|url| url.starts_with("data:text/html,navigated"))+ {+ assert!(+ input_acknowledged,+ "Input.dispatchMouseEvent must be acknowledged before click navigation events"+ );+ break;+ }+ }++ drop(server_tx);+ tokio::time::timeout(std::time::Duration::from_secs(2), processor)+ .await+ .expect("processor shutdown timeout")+ .expect("processor task");+ })+ .await;+ }+#[test]fn cookie_delta_merges_changes_without_reverting_other_connections() {let destination = CookieJar::new();diff --git a/crates/obscura-cdp/tests/iframe_event_dispatch.rs b/crates/obscura-cdp/tests/iframe_event_dispatch.rsindex e68d3d1d..c029bf9e 100644--- a/crates/obscura-cdp/tests/iframe_event_dispatch.rs+++ b/crates/obscura-cdp/tests/iframe_event_dispatch.rs@@ -168,3 +168,55 @@ async fn iframe_load_reaches_onload_and_addeventlistener() {"both onload property and addEventListener('load') run exactly once, in order");}++#[tokio::test(flavor = "current_thread")]+async fn dom_events_follow_capture_target_and_bubble_order() {+ let (mut ctx, sid) = setup().await;+ let v = eval(+ &mut ctx,+ 2,+ r#"(function () {+ const outer = document.createElement('div');+ const target = document.createElement('button');+ outer.appendChild(target);+ document.body.appendChild(outer);+ const calls = [];+ const listen = (node, name, capture) => node.addEventListener('probe', (event) => {+ calls.push([name, event.eventPhase, event.currentTarget === node, event.target === target]);+ }, capture);+ listen(window, 'window-capture', true);+ listen(document, 'document-capture', true);+ listen(outer, 'outer-capture', true);+ listen(target, 'target-capture', true);+ listen(target, 'target-bubble', false);+ listen(outer, 'outer-bubble', false);+ listen(document, 'document-bubble', false);+ listen(window, 'window-bubble', false);+ target.dispatchEvent(new Event('probe', { bubbles: true }));+ let redispatches = 0;+ target.addEventListener('reused', () => redispatches++);+ const reused = new Event('reused');+ target.dispatchEvent(reused);+ target.dispatchEvent(reused);+ return JSON.stringify({ calls, redispatches, reusedTarget: reused.target === target });+ })()"#,+ &sid,+ )+ .await;+ let val = serde_json::from_str::<Value>(v["result"]["value"].as_str().unwrap()).unwrap();+ assert_eq!(+ val["calls"],+ json!([+ ["window-capture", 1, true, true],+ ["document-capture", 1, true, true],+ ["outer-capture", 1, true, true],+ ["target-capture", 2, true, true],+ ["target-bubble", 2, true, true],+ ["outer-bubble", 3, true, true],+ ["document-bubble", 3, true, true],+ ["window-bubble", 3, true, true]+ ])+ );+ assert_eq!(val["redispatches"], 2);+ assert_eq!(val["reusedTarget"], true);+}diff --git a/crates/obscura-cdp/tests/input_mouse_event_parity.rs b/crates/obscura-cdp/tests/input_mouse_event_parity.rsindex 08ce1b25..8d0b34e5 100644--- a/crates/obscura-cdp/tests/input_mouse_event_parity.rs+++ b/crates/obscura-cdp/tests/input_mouse_event_parity.rs@@ -19,9 +19,32 @@ async fn serve_fixture() -> String {#box { position: absolute; left: 20px; top: 20px; width: 180px;height: 120px; overflow: auto; border: 10px solid black; }#inner { width: 700px; height: 800px; }+ #hidden-y { position: absolute; left: 240px; top: 20px; width: 180px;+ height: 120px; overflow: auto hidden; border: 10px solid black; }+ #hidden-inner { width: 700px; height: 800px; }+ #hit-target { position: absolute; left: 500px; top: 20px; width: 120px;+ height: 60px; }+ #hit-overlay { position: absolute; inset: 0; pointer-events: none; }+ #offset-parent { position: relative; margin: 180px 0 0 40px;+ width: 120px; height: 80px; border: 3px solid black; }+ #offset-child { position: absolute; left: -1px; top: -1px;+ width: 20px; height: 20px; }+ #stack-root { position: absolute; z-index: 0; left: 650px; top: 20px;+ width: 120px; height: 60px; }+ #stack-input { display: block; width: 120px; height: 60px; }+ #stack-behind { position: absolute; z-index: -1; inset: 0; }+ #deep-context { position: fixed; z-index: 0; left: 800px; top: 20px;+ width: 120px; height: 60px; }+ #deep-target { width: 120px; height: 60px; }+ #deep-child { display: block; width: 100%; height: 100%; }</style></head><body><div id="page"></div><div id="box"><div id="inner"></div></div>+ <div id="hidden-y"><div id="hidden-inner"></div></div>+ <button id="hit-target">Target<span id="hit-overlay"></span></button>+ <div id="offset-parent"><div id="offset-child"></div></div>+ <div id="stack-root"><input id="stack-input"><div id="stack-behind"></div></div>+ <div id="deep-context"><button id="deep-target"><span id="deep-child">Target</span></button></div><input id="check" type="checkbox"><form id="radio-form"><input id="radio-a" type="radio" name="choice" checked>@@ -140,6 +163,41 @@ async fn wheel_over_nested_overflow_scrolls_the_nested_container() {assert_eq!(state["rootY"], 0.0, "nested wheel must not leak to the viewport");}+#[tokio::test(flavor = "current_thread")]+async fn wheel_does_not_scroll_an_overflow_hidden_axis() {+ let (mut ctx, sid) = setup().await;+ let computed = evaluate(+ &mut ctx,+ 2,+ r#"JSON.stringify((() => {+ const box = document.getElementById('hidden-y');+ const style = getComputedStyle(box);+ return { x: style.overflowX, y: style.overflowY };+ })())"#,+ &sid,+ )+ .await;+ let computed: Value =+ serde_json::from_str(computed["result"]["value"].as_str().unwrap()).unwrap();+ assert_eq!(computed, json!({"x": "auto", "y": "hidden"}));++ wheel(&mut ctx, 3, &sid, 270.0, 50.0, 0.0, 110.0).await;+ let result = evaluate(+ &mut ctx,+ 4,+ r#"JSON.stringify({+ rootY: scrollY,+ hiddenY: document.getElementById('hidden-y').scrollTop+ })"#,+ &sid,+ )+ .await;+ let state: Value =+ serde_json::from_str(result["result"]["value"].as_str().unwrap()).unwrap();+ assert_eq!(state["rootY"], 110.0, "hidden Y overflow must chain to the viewport");+ assert_eq!(state["hiddenY"], 0.0, "wheel input must not scroll a hidden axis");+}+#[tokio::test(flavor = "current_thread")]async fn wheel_offsets_clamp_to_nested_scroll_extents() {let (mut ctx, sid) = setup().await;@@ -222,9 +280,17 @@ async fn canceling_wheel_prevents_its_scroll_default() {#[tokio::test(flavor = "current_thread")]async fn hit_testing_clips_scrolled_children_at_overflow_padding_edge() {let (mut ctx, sid) = setup().await;- let result = evaluate(+ let visible = evaluate(&mut ctx,2,+ "document.elementFromPoint(50, 50).id",+ &sid,+ )+ .await;+ assert_eq!(visible["result"]["value"], "inner");+ let result = evaluate(+ &mut ctx,+ 3,r#"(() => {const box = document.getElementById('box');box.scrollLeft = 50;@@ -245,6 +311,77 @@ async fn hit_testing_clips_scrolled_children_at_overflow_padding_edge() {assert_eq!(result["hit"], "box", "content hidden behind the border cannot win hit testing");}+#[tokio::test(flavor = "current_thread")]+async fn hit_testing_ignores_pointer_events_none_overlay() {+ let (mut ctx, sid) = setup().await;+ let result = evaluate(+ &mut ctx,+ 2,+ r#"JSON.stringify({+ hit: document.elementFromPoint(550, 50).id,+ overlayPointerEvents: getComputedStyle(document.getElementById('hit-overlay')).pointerEvents+ })"#,+ &sid,+ )+ .await;+ let result: Value = serde_json::from_str(result["result"]["value"].as_str().unwrap()).unwrap();+ assert_eq!(result, json!({"hit": "hit-target", "overlayPointerEvents": "none"}));+}++#[tokio::test(flavor = "current_thread")]+async fn hit_testing_respects_negative_stacking_layers() {+ let (mut ctx, sid) = setup().await;+ let result = evaluate(+ &mut ctx,+ 2,+ "document.elementFromPoint(710, 50).id",+ &sid,+ )+ .await;+ assert_eq!(result["result"]["value"], "stack-input");++ let nested = evaluate(+ &mut ctx,+ 3,+ "document.elementFromPoint(860, 50).id",+ &sid,+ )+ .await;+ assert_eq!(nested["result"]["value"], "deep-child");+}++#[tokio::test(flavor = "current_thread")]+async fn offset_geometry_is_relative_to_the_positioned_ancestor() {+ let (mut ctx, sid) = setup().await;+ let result = evaluate(+ &mut ctx,+ 2,+ r#"JSON.stringify((() => {+ const parent = document.getElementById('offset-parent');+ const child = document.getElementById('offset-child');+ const parentRect = parent.getBoundingClientRect();+ const childRect = child.getBoundingClientRect();+ return {+ parent: child.offsetParent === parent,+ left: child.offsetLeft,+ top: child.offsetTop,+ expectedLeft: Math.round(childRect.left - parentRect.left - parent.clientLeft),+ expectedTop: Math.round(childRect.top - parentRect.top - parent.clientTop),+ clientLeft: parent.clientLeft,+ clientTop: parent.clientTop+ };+ })())"#,+ &sid,+ )+ .await;+ let result: Value = serde_json::from_str(result["result"]["value"].as_str().unwrap()).unwrap();+ assert_eq!(result["parent"], true);+ assert_eq!(result["left"], result["expectedLeft"]);+ assert_eq!(result["top"], result["expectedTop"]);+ assert_eq!(result["clientLeft"], 3);+ assert_eq!(result["clientTop"], 3);+}+#[tokio::test(flavor = "current_thread")]async fn press_release_orders_events_and_defers_click_activation() {let (mut ctx, sid) = setup().await;@@ -255,10 +392,16 @@ async fn press_release_orders_events_and_defers_click_activation() {const target = document.getElementById('check');document.elementFromPoint = () => target;globalThis.mouseLog = [];- for (const type of ['mousedown', 'mouseup', 'click', 'input', 'change']) {+ for (const type of ['pointerover', 'pointerenter', 'mouseover', 'mouseenter',+ 'pointerdown', 'mousedown', 'focus', 'focusin',+ 'pointerup', 'mouseup', 'click', 'input', 'change']) {target.addEventListener(type, event => mouseLog.push({type, checked: target.checked, x: event.clientX,- ctrl: event.ctrlKey, shift: event.shiftKey, trusted: event.isTrusted+ pointerType: event.pointerType || '',+ ctrl: event.ctrlKey, shift: event.shiftKey, trusted: event.isTrusted,+ detail: event.detail, which: event.which,+ offsetX: event.offsetX, offsetY: event.offsetY,+ modifierCtrl: event.getModifierState?.('Control')}));}})()"#,@@ -286,8 +429,33 @@ async fn press_release_orders_events_and_defers_click_activation() {.await;let pressed: Value = serde_json::from_str(pressed["result"]["value"].as_str().unwrap()).unwrap();assert_eq!(pressed["checked"], false, "checkbox activation must wait for release");- assert_eq!(pressed["log"][0]["type"], "mousedown");- assert_eq!(pressed["log"].as_array().unwrap().len(), 1, "press must not synthesize click");+ let pressed_types: Vec<&str> = pressed["log"]+ .as_array()+ .unwrap()+ .iter()+ .map(|entry| entry["type"].as_str().unwrap())+ .collect();+ assert_eq!(+ pressed_types,+ [+ "pointerover",+ "pointerenter",+ "mouseover",+ "mouseenter",+ "pointerdown",+ "mousedown",+ "focus",+ "focusin"+ ]+ );+ assert_eq!(pressed["log"][4]["pointerType"], "mouse");+ assert_eq!(pressed["log"][4]["detail"], 0);+ assert_eq!(pressed["log"][5]["detail"], 1);+ assert_eq!(pressed["log"][5]["which"], 1);+ assert!(pressed["log"][5]["offsetX"].is_number());+ assert!(pressed["log"][5]["offsetY"].is_number());+ assert_eq!(pressed["log"][5]["modifierCtrl"], true);+ assert_eq!(pressed["log"][6]["trusted"], true);cdp(&mut ctx,@@ -314,13 +482,30 @@ async fn press_release_orders_events_and_defers_click_activation() {.iter().map(|entry| entry["type"].as_str().unwrap()).collect();- assert_eq!(types, ["mousedown", "mouseup", "click", "input", "change"]);+ assert_eq!(+ types,+ [+ "pointerover",+ "pointerenter",+ "mouseover",+ "mouseenter",+ "pointerdown",+ "mousedown",+ "focus",+ "focusin",+ "pointerup",+ "mouseup",+ "click",+ "input",+ "change"+ ]+ );assert_eq!(released["checked"], true);- assert_eq!(released["log"][2]["checked"], true, "click sees checkbox pre-activation");- assert_eq!(released["log"][2]["x"], 31.0);- assert_eq!(released["log"][2]["ctrl"], true);- assert_eq!(released["log"][2]["shift"], true);- assert_eq!(released["log"][2]["trusted"], true);+ assert_eq!(released["log"][10]["checked"], true, "click sees checkbox pre-activation");+ assert_eq!(released["log"][10]["x"], 31.0);+ assert_eq!(released["log"][10]["ctrl"], true);+ assert_eq!(released["log"][10]["shift"], true);+ assert_eq!(released["log"][10]["trusted"], true);}#[tokio::test(flavor = "current_thread")]diff --git a/crates/obscura-cdp/tests/window_conformance_parity.rs b/crates/obscura-cdp/tests/window_conformance_parity.rsindex cda11f9d..6f700328 100644--- a/crates/obscura-cdp/tests/window_conformance_parity.rs+++ b/crates/obscura-cdp/tests/window_conformance_parity.rs@@ -134,3 +134,31 @@ async fn document_adopt_node_moves_node() {assert_eq!(val["sameNode"], true);assert_eq!(val["ownerDoc"], true);}++#[tokio::test(flavor = "current_thread")]+async fn assignment_shadows_window_named_element_property() {+ let (mut ctx, sid) = setup().await;+ let v = eval(+ &mut ctx,+ 2,+ r#"(function () {+ 'use strict';+ const named = window.a;+ window.a = 42;+ const descriptor = Object.getOwnPropertyDescriptor(window, 'a');+ return JSON.stringify({+ startedAsElement: named === document.getElementById('a'),+ value: window.a,+ writable: descriptor.writable,+ hasGetter: typeof descriptor.get === 'function',+ });+ })()"#,+ &sid,+ )+ .await;+ let val = serde_json::from_str::<Value>(v["result"]["value"].as_str().unwrap()).unwrap();+ assert_eq!(val["startedAsElement"], true);+ assert_eq!(val["value"], 42);+ assert_eq!(val["writable"], true);+ assert_eq!(val["hasGetter"], false);+}diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rsindex 183ba2e3..7eaafc43 100644--- a/crates/obscura-cli/src/main.rs+++ b/crates/obscura-cli/src/main.rs@@ -601,15 +601,33 @@ async fn run_multi_worker_serve(font_dirs: Vec<std::path::PathBuf>,) -> anyhow::Result<()> {use tokio::io::AsyncWriteExt as _;- use tokio::net::TcpListener;+ use tokio::net::{TcpListener, TcpStream};let exe = std::env::current_exe()?;+ // Claim the public port before starting children so another process cannot+ // take it during worker startup.+ let listener = TcpListener::bind((host.as_str(), port)).await?;+ // Internal worker ports are implementation details. Asking the OS for+ // free ports avoids assuming that every port adjacent to the public one is+ // available (or that `port + workers` cannot overflow).+ let mut reservations = Vec::with_capacity(workers as usize);+ for _ in 0..workers {+ let reservation = std::net::TcpListener::bind(("127.0.0.1", 0))?;+ let worker_port = reservation.local_addr()?.port();+ reservations.push((worker_port, reservation));+ }let mut children = Vec::new();+ let mut worker_ports = Vec::with_capacity(workers as usize);- for i in 0..workers {- let worker_port = port + 1 + i;+ for (index, (worker_port, reservation)) in reservations.into_iter().enumerate() {+ drop(reservation);let mut cmd = std::process::Command::new(&exe);cmd.arg("serve").arg("--port").arg(worker_port.to_string());+ // Workers receive the client-facing Host header through the TCP+ // load balancer. Let their CDP security gate accept that public port+ // while it continues to reject foreign hosts and browser origins.+ cmd.env("OBSCURA_CDP_FORWARDED_HOST", &host);+ cmd.env("OBSCURA_CDP_FORWARDED_PORT", port.to_string());if let Some(ref p) = proxy {// Pass the proxy (which may embed credentials) via the environment,// not argv. A --proxy flag is visible in `ps`/`/proc/<pid>/cmdline`@@ -630,41 +648,86 @@ async fn run_multi_worker_serve(cmd.stderr(std::process::Stdio::null());let child = cmd.spawn()?;- tracing::info!("Worker {} on port {}", i + 1, worker_port);+ tracing::info!("Worker {} on port {}", index + 1, worker_port);children.push(child);+ worker_ports.push(worker_port);}- tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;+ // Wait only until every worker has bound its control port. The old fixed+ // 500 ms sleep dominated multi-worker startup even when workers were ready+ // in a few milliseconds.+ let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);+ for (index, (child, &worker_port)) in children.iter_mut().zip(&worker_ports).enumerate() {+ loop {+ if let Some(status) = child.try_wait()? {+ anyhow::bail!("worker {} exited during startup: {}", index + 1, status);+ }+ match TcpStream::connect(("127.0.0.1", worker_port)).await {+ Ok(stream) => {+ drop(stream);+ break;+ }+ Err(_) if tokio::time::Instant::now() < deadline => {+ tokio::time::sleep(tokio::time::Duration::from_millis(5)).await;+ }+ Err(error) => {+ return Err(error.into());+ }+ }+ }+ }- // Bind the load balancer to the requested host, not hardcoded loopback.+ // The load balancer is bound to the requested host, not hardcoded loopback.// With --host 0.0.0.0 (e.g. in Docker) the single-worker path already binds// all interfaces; the multi-worker balancer must too, or the mapped port is// refused from outside the container (issue #336). Workers stay on loopback// and are only reached by the balancer.- let listener = TcpListener::bind((host.as_str(), port)).await?;tracing::info!("Load balancer on {}:{}, {} workers", host, port, workers);- let mut next_worker: u16 = 0;+ let mut next_worker = 0usize;loop {let (client_stream, peer_addr) = listener.accept().await?;- let worker_port = port + 1 + (next_worker % workers);+ if let Err(error) = client_stream.set_nodelay(true) {+ tracing::warn!("client {} TCP_NODELAY failed: {}", peer_addr, error);+ }+ let worker_port = worker_ports[next_worker % worker_ports.len()];next_worker = next_worker.wrapping_add(1);tracing::debug!("Routing {} to worker port {}", peer_addr, worker_port);let mut peek_buf = [0u8; 4];- client_stream.peek(&mut peek_buf).await?;+ match client_stream.peek(&mut peek_buf).await {+ Ok(0) => continue,+ Ok(_) => {}+ Err(error) => {+ tracing::debug!("client {} closed before dispatch: {}", peer_addr, error);+ continue;+ }+ }if &peek_buf == b"GET " {let mut full_peek = [0u8; 256];- let n = client_stream.peek(&mut full_peek).await?;+ let n = match client_stream.peek(&mut full_peek).await {+ Ok(n) => n,+ Err(error) => {+ tracing::debug!("client {} closed before dispatch: {}", peer_addr, error);+ continue;+ }+ };let request_line = String::from_utf8_lossy(&full_peek[..n]);if request_line.contains("/json") {let worker_addr = format!("127.0.0.1:{}", worker_port);match tokio::net::TcpStream::connect(&worker_addr).await {Ok(mut worker_stream) => {+ if let Err(error) = worker_stream.set_nodelay(true) {+ tracing::warn!(+ "worker {} TCP_NODELAY failed: {}",+ worker_addr,+ error+ );+ }tokio::spawn(async move {let std_stream = match client_stream.into_std() {Ok(s) => s,@@ -709,6 +772,10 @@ async fn run_multi_worker_serve(tokio::spawn(async move {match tokio::net::TcpStream::connect(&worker_addr).await {Ok(mut worker_stream) => {+ if let Err(error) = worker_stream.set_nodelay(true) {+ tracing::warn!("worker {} TCP_NODELAY failed: {}", worker_addr, error);+ return;+ }let mut client = client_stream;let _ = tokio::io::copy_bidirectional(&mut client, &mut worker_stream).await;}diff --git a/crates/obscura-dom/src/selector.rs b/crates/obscura-dom/src/selector.rsindex 09ecb31e..962cbaa2 100644--- a/crates/obscura-dom/src/selector.rs+++ b/crates/obscura-dom/src/selector.rs@@ -732,6 +732,13 @@ impl DomTree {NeedsSelectorFlags::No,MatchingForInvalidation::No,);+ // Element.querySelector() scopes :scope to the element on which it was+ // called. Leaving this unset makes the selector crate use the document+ // element, so `root.querySelector(':scope .nested .item')` can treat+ // `root` itself as `.nested` and return direct children incorrectly.+ if self.with_node(root, |node| node.is_element()).unwrap_or(false) {+ context.scope_element = Some(DomElement::new(self, root).opaque());+ }for desc_id in self.descendants(root) {let is_element = self.with_node(desc_id, |n| n.is_element()).unwrap_or(false);@@ -774,6 +781,9 @@ impl DomTree {NeedsSelectorFlags::No,MatchingForInvalidation::No,);+ if self.with_node(root, |node| node.is_element()).unwrap_or(false) {+ context.scope_element = Some(DomElement::new(self, root).opaque());+ }let mut results = Vec::new();for desc_id in self.descendants(root) {@@ -811,6 +821,7 @@ impl DomTree {NeedsSelectorFlags::No,MatchingForInvalidation::No,);+ context.scope_element = Some(DomElement::new(self, nid).opaque());Ok(selectors::matching::matches_selector_list(&selector_list,&DomElement::new(self, nid),@@ -1692,6 +1703,31 @@ mod tests {assert!(tree.query_selector_from(root, "span").unwrap().is_some());}+ #[test]+ fn scoped_queries_bind_scope_to_the_element_root() {+ let tree = parse_html(+ r#"<ul id="root" class="menu">+ <li id="direct" class="item">direct</li>+ <li><ul class="menu"><li id="nested" class="item">nested</li></ul></li>+ </ul>"#,+ );+ let root = tree.get_element_by_id("root").expect("ul#root");+ let direct = tree.get_element_by_id("direct").expect("li#direct");+ let nested = tree.get_element_by_id("nested").expect("li#nested");++ assert_eq!(+ tree.query_selector_all_from(root, ":scope > .item")+ .unwrap(),+ vec![direct]+ );+ assert_eq!(+ tree.query_selector_all_from(root, ":scope .menu .item")+ .unwrap(),+ vec![nested]+ );+ assert!(tree.matches_selector(root, ":scope").unwrap());+ }+#[test]fn selectors_respect_native_shadow_tree_scopes_and_host_hooks() {let tree = parse_html(diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 82576e07..e18d4da4 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -101,21 +101,14 @@ globalThis.onunhandledrejection = function(e) { if (e?.preventDefault) e.preventglobalThis.onerror = function(msg, src, line, col, error) {globalThis.__obscura_errors.push({msg: String(msg), src: String(src||""), line, error: String(error||"")});};-globalThis.__windowListeners = {};-globalThis.addEventListener = function(type, fn) {- if (!globalThis.__windowListeners[type]) globalThis.__windowListeners[type] = [];- globalThis.__windowListeners[type].push(fn);+globalThis.addEventListener = function(type, fn, options) {+ _eventTargetAdd(globalThis, type, fn, options);};-globalThis.removeEventListener = function(type, fn) {- if (globalThis.__windowListeners[type]) {- globalThis.__windowListeners[type] = globalThis.__windowListeners[type].filter(h => h !== fn);- }+globalThis.removeEventListener = function(type, fn, options) {+ _eventTargetRemove(globalThis, type, fn, options);};globalThis.dispatchEvent = function(event) {- if (!event) return true;- const handlers = globalThis.__windowListeners[event.type] || [];- for (const h of handlers) { try { h.call(globalThis, event); } catch(e) { console.error(e); } }- return !event.defaultPrevented;+ return _eventTargetDispatch(globalThis, event);};let _domMutationEpoch = 0;@@ -1914,26 +1907,129 @@ function _eventTargetDispatch(target, event) {if (String(event.type) === "") {throw new DOMException("The event's type was not specified.", "InvalidStateError");}- if (!event.target) event.target = target;+ if (event._dispatching) {+ throw new DOMException("The event is already being dispatched.", "InvalidStateError");+ }+ event._dispatching = true;+ event._propagationStopped = false;+ event._immediatePropagationStopped = false;+ event.target = target;event.currentTarget = target;event.eventPhase = 2;+ try {+ const listeners = (_eventTargetListeners.get(target)?.get(String(event.type)) || []).slice();+ for (const entry of listeners) {+ const current = _eventTargetListeners.get(target)?.get(String(event.type));+ if (!current || !current.includes(entry)) continue;+ if (entry.once) _eventTargetRemove(target, event.type, entry.callback, entry.capture);+ const callback = entry.callback;+ try {+ if (typeof callback === "function") callback.call(target, event);+ else callback.handleEvent.call(callback, event);+ } catch (error) {+ console.error(error);+ }+ if (event._immediatePropagationStopped) break;+ }+ return !event.defaultPrevented;+ } finally {+ event.currentTarget = null;+ event.eventPhase = 0;+ event._dispatching = false;+ }+}++function _domEventInvoke(target, event, capture, phase) {+ event.currentTarget = target;+ event.eventPhase = phase;++ // Content attributes and IDL event handlers participate in the non-capture+ // listener group. Keep their existing position ahead of listeners installed+ // through addEventListener; changing that ordering here would be an unrelated+ // compatibility change.+ if (!capture && typeof target._resolveInlineHandler === "function") {+ const handlerName = "on" + event.type;+ const inlineFn = target[handlerName] || target._resolveInlineHandler(handlerName);+ if (typeof inlineFn === "function") {+ try {+ if (inlineFn.call(target, event) === false) event.preventDefault();+ } catch (error) {+ console.error(error);+ }+ }+ }+const listeners = (_eventTargetListeners.get(target)?.get(String(event.type)) || []).slice();for (const entry of listeners) {+ if (entry.capture !== capture) continue;const current = _eventTargetListeners.get(target)?.get(String(event.type));if (!current || !current.includes(entry)) continue;if (entry.once) _eventTargetRemove(target, event.type, entry.callback, entry.capture);- const callback = entry.callback;try {- if (typeof callback === "function") callback.call(target, event);- else callback.handleEvent.call(callback, event);+ if (typeof entry.callback === "function") entry.callback.call(target, event);+ else entry.callback.handleEvent.call(entry.callback, event);} catch (error) {console.error(error);}if (event._immediatePropagationStopped) break;}- event.currentTarget = null;- event.eventPhase = 0;- return !event.defaultPrevented;+}++// DOM events have one propagation path. The old Element implementation+// recursively called parent.dispatchEvent(), which discarded capture options+// and left eventPhase at NONE. Delegated framework handlers depend on capture+// running before target/bubble listeners, so build the path once and dispatch+// each phase explicitly.+function _domEventDispatch(target, event) {+ if (!event || typeof event.type === "undefined") {+ throw new TypeError("Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.");+ }+ if (String(event.type) === "") {+ throw new DOMException("The event's type was not specified.", "InvalidStateError");+ }+ if (event._dispatching) {+ throw new DOMException("The event is already being dispatched.", "InvalidStateError");+ }++ event._dispatching = true;+ event._propagationStopped = false;+ event._immediatePropagationStopped = false;+ event.target = target;+ const path = [];+ let ancestor = target.parentNode || null;+ while (ancestor) {+ path.push(ancestor);+ ancestor = ancestor.parentNode || null;+ }+ if (target !== globalThis && path[path.length - 1] !== globalThis) {+ path.push(globalThis);+ }++ try {+ for (let index = path.length - 1; index >= 0; index--) {+ _domEventInvoke(path[index], event, true, 1);+ if (event._propagationStopped) break;+ }++ if (!event._propagationStopped) {+ _domEventInvoke(target, event, true, 2);+ if (!event._immediatePropagationStopped) {+ _domEventInvoke(target, event, false, 2);+ }+ }++ if (event.bubbles && !event._propagationStopped) {+ for (const currentTarget of path) {+ _domEventInvoke(currentTarget, event, false, 3);+ if (event._propagationStopped) break;+ }+ }+ return !event.defaultPrevented;+ } finally {+ event.currentTarget = null;+ event.eventPhase = 0;+ event._dispatching = false;+ }}// During custom-element upgrade, HTMLElement's constructor must return the@@ -3773,44 +3869,13 @@ class Element extends Node {return null;}addEventListener(type, handler, opts) {- const key = this._nid;- if (!_eventRegistry[key]) _eventRegistry[key] = {};- if (!_eventRegistry[key][type]) _eventRegistry[key][type] = [];- _eventRegistry[key][type].push(handler);+ _eventTargetAdd(this, type, handler, opts);}- removeEventListener(type, handler) {- const key = this._nid;- if (_eventRegistry[key] && _eventRegistry[key][type]) {- _eventRegistry[key][type] = _eventRegistry[key][type].filter(h => h !== handler);- }+ removeEventListener(type, handler, opts) {+ _eventTargetRemove(this, type, handler, opts);}dispatchEvent(event) {- if (!event) return true;- if (!event.target) event.target = this;- event.currentTarget = this;- // Spec: inline `onclick="..."` content attributes are event handlers- // for the matching event type. Fire them alongside any- // addEventListener handlers. Also honor the IDL property- // `el.onclick = fn` if set. Without this, b.click() never invokes- // the inline handler and forms with onsubmit / buttons with onclick- // are silently dead.- const handlerName = 'on' + event.type;- const inlineFn = this[handlerName] || this._resolveInlineHandler(handlerName);- if (typeof inlineFn === 'function') {- try {- const ret = inlineFn.call(this, event);- if (ret === false) event.preventDefault();- } catch(e) { console.error(e); }- }- const handlers = (_eventRegistry[this._nid] || {})[event.type] || [];- for (const h of handlers) {- try { h.call(this, event); } catch(e) { console.error(e); }- if (event._immediatePropagationStopped) break;- }- if (event.bubbles && !event._propagationStopped && this.parentNode) {- this.parentNode.dispatchEvent(event);- }- return !event.defaultPrevented;+ return _domEventDispatch(this, event);}_resolveInlineHandler(name) {// name = 'onclick' / 'onsubmit' / etc. Compile the content attribute@@ -3926,8 +3991,24 @@ class Element extends Node {}}}- focus() { globalThis.__obscura_focused = this; globalThis.__obscura_click_target = this; }- blur() { if (globalThis.__obscura_focused === this) globalThis.__obscura_focused = null; }+ focus() {+ const previous = globalThis.__obscura_focused || null;+ if (previous === this) return;+ if (previous) {+ previous.dispatchEvent(globalThis.__obscura_markTrusted(new FocusEvent('blur', { relatedTarget: this })));+ previous.dispatchEvent(globalThis.__obscura_markTrusted(new FocusEvent('focusout', { bubbles: true, composed: true, relatedTarget: this })));+ }+ globalThis.__obscura_focused = this;+ globalThis.__obscura_click_target = this;+ this.dispatchEvent(globalThis.__obscura_markTrusted(new FocusEvent('focus', { relatedTarget: previous })));+ this.dispatchEvent(globalThis.__obscura_markTrusted(new FocusEvent('focusin', { bubbles: true, composed: true, relatedTarget: previous })));+ }+ blur() {+ if (globalThis.__obscura_focused !== this) return;+ globalThis.__obscura_focused = null;+ this.dispatchEvent(globalThis.__obscura_markTrusted(new FocusEvent('blur', { relatedTarget: null })));+ this.dispatchEvent(globalThis.__obscura_markTrusted(new FocusEvent('focusout', { bubbles: true, composed: true, relatedTarget: null })));+ }// --- Popover API (HTML "popover") ---------------------------------------// Read the popover content attribute case-insensitively. The HTML parser@@ -4699,8 +4780,48 @@ class Element extends Node {if (this._isViewportRoot()) return globalThis.innerHeight || 720;return this.getBoundingClientRect().height;}- get offsetTop() { return this.getBoundingClientRect().top; }- get offsetLeft() { return this.getBoundingClientRect().left; }+ get offsetParent() {+ if (!this.isConnected || this._renderBoxGeometry() === null) return null;+ const ownStyle = globalThis.getComputedStyle(this);+ if (ownStyle.position === 'fixed') return null;++ for (let ancestor = this.parentElement; ancestor; ancestor = ancestor.parentElement) {+ if (ancestor.tagName === 'HTML') break;+ const style = globalThis.getComputedStyle(ancestor);+ if (style.display === 'none') return null;+ if (ancestor.tagName === 'BODY' || style.position !== 'static'+ || style.display === 'table-cell' || style.display === 'table') {+ return ancestor;+ }+ }+ return document.body || null;+ }+ get offsetTop() {+ if (!this.isConnected || this._renderBoxGeometry() === null) return 0;+ const rect = this.getBoundingClientRect();+ const parent = this.offsetParent;+ const value = parent+ ? rect.top - parent.getBoundingClientRect().top - parent.clientTop+ : rect.top + (globalThis.scrollY || 0);+ return Math.round(value);+ }+ get offsetLeft() {+ if (!this.isConnected || this._renderBoxGeometry() === null) return 0;+ const rect = this.getBoundingClientRect();+ const parent = this.offsetParent;+ const value = parent+ ? rect.left - parent.getBoundingClientRect().left - parent.clientLeft+ : rect.left + (globalThis.scrollX || 0);+ return Math.round(value);+ }+ get clientTop() {+ if (!this.isConnected || this._renderBoxGeometry() === null) return 0;+ return Math.round(Math.max(0, parseFloat(globalThis.getComputedStyle(this).borderTopWidth) || 0));+ }+ get clientLeft() {+ if (!this.isConnected || this._renderBoxGeometry() === null) return 0;+ return Math.round(Math.max(0, parseFloat(globalThis.getComputedStyle(this).borderLeftWidth) || 0));+ }// In standards mode documentElement exposes viewport client geometry.// Puppeteer's #clickableBox clips boxes to those dimensions; returning the// non-render fallback 100x20 there makes every element appear off-screen.@@ -4770,6 +4891,10 @@ class Element extends Node {value: !!geometry.viewportFixed,enumerable: false,});+ Object.defineProperty(rect, "__obscuraPointerEventsNone", {+ value: !!geometry.pointerEventsNone,+ enumerable: false,+ });return rect;}get scrollWidth() {@@ -5630,21 +5755,13 @@ class Document extends Node {}createRange() { return new Range(); }addEventListener(type, fn, opts) {- if (typeof fn !== 'function') return;- if (!this._listeners) this._listeners = {};- if (!this._listeners[type]) this._listeners[type] = [];- if (!this._listeners[type].includes(fn)) this._listeners[type].push(fn);+ _eventTargetAdd(this, type, fn, opts);}- removeEventListener(type, fn) {- if (this._listeners?.[type]) {- this._listeners[type] = this._listeners[type].filter(h => h !== fn);- }+ removeEventListener(type, fn, opts) {+ _eventTargetRemove(this, type, fn, opts);}dispatchEvent(event) {- if (!event) return true;- const handlers = (this._listeners?.[event.type] || []).slice();- for (const h of handlers) { try { h.call(this, event); } catch(e) { console.error('document event error:', e); } }- return !event.defaultPrevented;+ return _domEventDispatch(this, event);}createTreeWalker(root, whatToShow, filter) {// whatToShow is unsigned long; default SHOW_ALL only when the arg is omitted.@@ -10047,7 +10164,7 @@ globalThis.__obscura_setInputFiles = function(el, specs) {try { el.dispatchEvent(globalThis.__obscura_markTrusted(new Event("change", { bubbles: true }))); } catch (_e) {}};globalThis.Event = class Event {- constructor(t,o={}) { if (arguments.length < 1) throw new TypeError("Failed to construct 'Event': 1 argument required, but only 0 present."); this.type=String(t);this.bubbles=!!o.bubbles;this.cancelable=!!o.cancelable;this.composed=!!o.composed;this.defaultPrevented=false;this.target=null;this.currentTarget=null;this.eventPhase=0;this.timeStamp=Date.now();this._propagationStopped=false;this._immediatePropagationStopped=false; }+ constructor(t,o={}) { if (arguments.length < 1) throw new TypeError("Failed to construct 'Event': 1 argument required, but only 0 present."); this.type=String(t);this.bubbles=!!o.bubbles;this.cancelable=!!o.cancelable;this.composed=!!o.composed;this.defaultPrevented=false;this.target=null;this.currentTarget=null;this.eventPhase=0;this.timeStamp=performance.now();this._dispatching=false;this._propagationStopped=false;this._immediatePropagationStopped=false; }get isTrusted() { return _trustedEvents.has(this); }preventDefault() { if (this.cancelable) this.defaultPrevented=true; } stopPropagation(){ this._propagationStopped=true; } stopImmediatePropagation(){ this._propagationStopped=true; this._immediatePropagationStopped=true; }initEvent(type,bubbles,cancelable) { if (arguments.length < 1) throw new TypeError("Failed to execute 'initEvent' on 'Event': 1 argument required, but only 0 present."); this.type=String(type);this.bubbles=!!bubbles;this.cancelable=!!cancelable;this.defaultPrevented=false;this._propagationStopped=false;this._immediatePropagationStopped=false; }@@ -10074,7 +10191,29 @@ globalThis.CustomEvent = class extends Event {}};globalThis.MouseEvent = class extends Event {- constructor(t,o={}) { super(t,o);this.view=o.view||null;this.detail=o.detail||0;this.screenX=o.screenX||0;this.screenY=o.screenY||0;this.clientX=o.clientX||0;this.clientY=o.clientY||0;this.ctrlKey=!!o.ctrlKey;this.altKey=!!o.altKey;this.shiftKey=!!o.shiftKey;this.metaKey=!!o.metaKey;this.button=o.button||0;this.buttons=o.buttons||0;this.relatedTarget=o.relatedTarget||null; }+ constructor(t,o={}) { super(t,o);this.view=o.view||null;this.detail=o.detail||0;this.screenX=o.screenX||0;this.screenY=o.screenY||0;this.clientX=o.clientX||0;this.clientY=o.clientY||0;this.ctrlKey=!!o.ctrlKey;this.altKey=!!o.altKey;this.shiftKey=!!o.shiftKey;this.metaKey=!!o.metaKey;this.button=o.button||0;this.buttons=o.buttons||0;this.relatedTarget=o.relatedTarget||null;this.movementX=o.movementX||0;this.movementY=o.movementY||0; }+ get pageX() { return this.clientX + (globalThis.scrollX || 0); }+ get pageY() { return this.clientY + (globalThis.scrollY || 0); }+ get x() { return this.clientX; }+ get y() { return this.clientY; }+ get which() { return this.button + 1; }+ get offsetX() {+ const rect = this.target?.getBoundingClientRect?.();+ return rect ? this.clientX - rect.left : this.clientX;+ }+ get offsetY() {+ const rect = this.target?.getBoundingClientRect?.();+ return rect ? this.clientY - rect.top : this.clientY;+ }+ getModifierState(key) {+ switch (String(key)) {+ case 'Alt': return this.altKey;+ case 'Control': return this.ctrlKey;+ case 'Meta': return this.metaKey;+ case 'Shift': return this.shiftKey;+ default: return false;+ }+ }// Legacy DOM Level 2 initializer. Positional signature per UI Events spec.initMouseEvent(type,canBubble,cancelable,view,detail,screenX,screenY,clientX,clientY,ctrlKey,altKey,shiftKey,metaKey,button,relatedTarget) {if (arguments.length < 1) throw new TypeError("Failed to execute 'initMouseEvent' on 'MouseEvent': 1 argument required, but only 0 present.");@@ -10095,6 +10234,15 @@ globalThis.MouseEvent = class extends Event {};globalThis.KeyboardEvent = class extends Event {constructor(t,o={}) { super(t,o);this.view=o.view||null;this.detail=o.detail||0;this.key=o.key||"";this.code=o.code||"";this.location=o.location||0;this.ctrlKey=!!o.ctrlKey;this.altKey=!!o.altKey;this.shiftKey=!!o.shiftKey;this.metaKey=!!o.metaKey;this.repeat=!!o.repeat; }+ getModifierState(key) {+ switch (String(key)) {+ case 'Alt': return this.altKey;+ case 'Control': return this.ctrlKey;+ case 'Meta': return this.metaKey;+ case 'Shift': return this.shiftKey;+ default: return false;+ }+ }// Legacy DOM Level 3 initializer. Positional signature per the WebKit/Gecko form.initKeyboardEvent(type,canBubble,cancelable,view,key,location,ctrlKey,altKey,shiftKey,metaKey) {if (arguments.length < 1) throw new TypeError("Failed to execute 'initKeyboardEvent' on 'KeyboardEvent': 1 argument required, but only 0 present.");@@ -10111,7 +10259,19 @@ globalThis.KeyboardEvent = class extends Event {globalThis.FocusEvent = class extends Event { constructor(t,o={}) { super(t,o);this.relatedTarget=o.relatedTarget||null; } };globalThis.InputEvent = class extends Event { constructor(t,o={}) { super(t,o);this.data=o.data||null;this.inputType=o.inputType||""; } };globalThis.ErrorEvent = class extends Event { constructor(t,o={}) { super(t,o);this.message=o.message||"";this.error=o.error||null; } };-globalThis.PointerEvent = class extends Event { constructor(t,o={}) { super(t,o); } };+globalThis.PointerEvent = class extends MouseEvent {+ constructor(t,o={}) {+ super(t,o);+ this.pointerId=o.pointerId===undefined?0:o.pointerId;+ this.width=o.width===undefined?1:o.width;+ this.height=o.height===undefined?1:o.height;+ this.pressure=o.pressure===undefined?0:o.pressure;+ this.tangentialPressure=o.tangentialPressure||0;+ this.tiltX=o.tiltX||0;this.tiltY=o.tiltY||0;this.twist=o.twist||0;+ this.pointerType=o.pointerType===undefined?'':String(o.pointerType);+ this.isPrimary=!!o.isPrimary;+ }+};globalThis.AnimationEvent = class extends Event {};globalThis.TransitionEvent = class extends Event {};globalThis.UIEvent = class extends Event {@@ -12167,6 +12327,18 @@ function _ensureWindowNamedProperty(name) {try {Object.defineProperty(globalThis, name, {get() { return _windowNamedValue(name); },+ set(value) {+ // A named element is a legacy platform property, not a read-only+ // Window attribute. An ordinary assignment shadows it with an own+ // data property, including in strict-mode bootstrap scripts.+ _windowNamedPropertyNames.delete(name);+ Object.defineProperty(globalThis, name, {+ value,+ writable: true,+ configurable: true,+ enumerable: true,+ });+ },configurable: true,enumerable: true,});@@ -15359,10 +15531,8 @@ if (typeof Element !== 'undefined' && !Element.prototype.toggleAttribute) {};}-// Document.elementFromPoint / elementsFromPoint — no layout engine, so this is a stub:-// in-viewport coords return <body> (or <html> as fallback), out-of-viewport returns null.-// Wrong-but-non-throwing beats "undefined", which traps ad/analytics bootstraps in retry loops-// (see issue #63).+// Document.elementFromPoint / elementsFromPoint. Render builds use the retained+// layout tree; no-render builds keep the synthetic-geometry fallback below.if (typeof Document !== 'undefined' && !Document.prototype.elementFromPoint) {// Real hit testing against the synthetic bboxes from getBoundingClientRect.// Flat iteration over every element, NOT a tree walk: our synthetic rects@@ -15378,6 +15548,17 @@ if (typeof Document !== 'undefined' && !Document.prototype.elementFromPoint) {var w = (typeof window !== 'undefined' && window.innerWidth) || 1280;var h = (typeof window !== 'undefined' && window.innerHeight) || 720;if (x < 0 || y < 0 || x > w || y > h) return null;+ if (typeof __obscuraCore.ops.op_layout_hit_test === 'function') {+ var hitNid = __obscuraCore.ops.op_layout_hit_test(x, y);+ if (hitNid >= 0) {+ var hit = _wrapEl(hitNid);+ return hit === this.documentElement && this.body ? this.body : hit;+ }+ // The root canvas still belongs to the document when no descendant box+ // is hit. Preserve the long-standing in-viewport fallback used by pages+ // before renderer-backed hit testing was available.+ return this.body || this.documentElement || null;+ }var all = this.querySelectorAll('*');var best = null;var bestNid = -1;@@ -15389,6 +15570,10 @@ if (typeof Document !== 'undefined' && !Document.prototype.elementFromPoint) {if (el === this.documentElement || el === this.body) continue;var r = el.getBoundingClientRect();if (r.width === 0 || r.height === 0) continue;+ // The renderer resolves this inherited property and carries it with the+ // existing geometry read, avoiding another native call per candidate.+ if (r.__obscuraPointerEventsNone ||+ (!('__obscuraPointerEventsNone' in r) && el.style?.pointerEvents === 'none')) continue;if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) {// A descendant's layout rect can extend beyond an overflow clip. It// must not win hit testing where its scrolling ancestor hides it —diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 2c175680..18564d24 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -3,22 +3,22 @@ use std::collections::{HashMap, HashSet, VecDeque};use std::rc::Rc;use std::sync::Arc;-use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};-use deno_core::op2;+use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};use deno_core::Extension;use deno_core::JsBuffer;-use deno_core::v8;use deno_core::OpState;-use obscura_dom::{DomTree, NodeData, NodeId};+use deno_core::op2;+use deno_core::v8;use obscura_dom::tree::{AttachShadowError, ShadowRootMode};-#[cfg(feature = "render")]-use obscura_net::{RequestCredentials, RequestMode, ResourceRequest};+use obscura_dom::{DomTree, NodeData, NodeId};#[cfg(feature = "stealth")]use obscura_net::StealthHttpClient;use obscura_net::{- same_site, CallbackRegistry, CookieJar, ObscuraHttpClient, RequestInfo, ResourceType, Response,- SameSiteContext,+ CallbackRegistry, CookieJar, ObscuraHttpClient, RequestInfo, ResourceType, Response,+ SameSiteContext, same_site,};+#[cfg(feature = "render")]+use obscura_net::{RequestCredentials, RequestMode, ResourceRequest};use tokio::sync::Mutex;#[cfg(feature = "render")]@@ -760,12 +760,13 @@ fn render_mutation_impact(};let actual_change = match cmd {"set_form_value" => !dom.form_control_value_matches(target, arg2),- "set_form_checked" => {- dom.form_control_checked(target) != Some(arg2 == "true")- }+ "set_form_checked" => dom.form_control_checked(target) != Some(arg2 == "true"),_ => dom.form_control_indeterminate(target) != (arg2 == "true"),};- RenderMutationImpact { connected: node_is_connected(dom, target), actual_change }+ RenderMutationImpact {+ connected: node_is_connected(dom, target),+ actual_change,+ }}"set_attribute" => {let Some(target) = node(arg1) else {@@ -948,20 +949,20 @@ fn retained_style_mutation(return None;}let keeps_selector_value = !name.eq_ignore_ascii_case("style");- Some(obscura_render::AttributeStyleMutation {+ Some(+ obscura_render::AttributeStyleMutation {node,name: name.to_string(),old_value: keeps_selector_value.then(|| {- dom.with_node(node, |node| {- node.get_attribute(name).map(str::to_owned)- })+ dom.with_node(node, |node| node.get_attribute(name).map(str::to_owned)).flatten()}).flatten(),new_value: keeps_selector_value.then(|| value.to_string()),}- .into())+ .into(),+ )}"remove_attribute" => {if obscura_render::dom::retained_attribute_mutation_kind(dom, node, arg2)@@ -970,20 +971,20 @@ fn retained_style_mutation(return None;}let keeps_selector_value = !arg2.eq_ignore_ascii_case("style");- Some(obscura_render::AttributeStyleMutation {+ Some(+ obscura_render::AttributeStyleMutation {node,name: arg2.to_string(),old_value: keeps_selector_value.then(|| {- dom.with_node(node, |node| {- node.get_attribute(arg2).map(str::to_owned)- })+ dom.with_node(node, |node| node.get_attribute(arg2).map(str::to_owned)).flatten()}).flatten(),new_value: None,}- .into())+ .into(),+ )}"append_child" => {let child = NodeId::new(arg2.parse::<u32>().ok()?);@@ -1000,9 +1001,7 @@ fn retained_style_mutation(}"remove_child" => {let old_parent = dom.get_node(node)?.parent?;- Some(- obscura_render::TreeStyleMutation::Remove { node, old_parent }.into(),- )+ Some(obscura_render::TreeStyleMutation::Remove { node, old_parent }.into())}"insert_before" => {let reference = NodeId::new(arg2.parse::<u32>().ok()?);@@ -1242,7 +1241,14 @@ fn fragment_context_and_html(arg: &str) -> (html5ever::QualName, &str) {Some((prefix, local)) if !prefix.is_empty() && !local.is_empty() => {(Some(html5ever::Prefix::from(prefix)), local)}- _ => (None, if qualified.is_empty() { "body" } else { qualified }),+ _ => (+ None,+ if qualified.is_empty() {+ "body"+ } else {+ qualified+ },+ ),};(html5ever::QualName::new(@@ -1531,6 +1537,13 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->state.activity_generation = state.activity_generation.wrapping_add(1);}#[cfg(feature = "render")]+ // Native text values and indeterminate checkbox marks are consumed+ // directly by paint. They do not participate in the selector surface+ // or intrinsic control sizing, so keep the existing geometry. Checked+ // state is deliberately excluded because `:checked` can affect style.+ let invalidate_geometry =+ invalidate && !matches!(cmd.as_str(), "set_form_value" | "set_form_indeterminate");+ #[cfg(feature = "render")]if !reset_nodes.is_empty() {state.element_scroll_offsets@@ -1543,7 +1556,7 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->#[cfg(feature = "render")]let had_prepared_render = state.prepared_render.is_some();#[cfg(feature = "render")]- if invalidate {+ if invalidate_geometry {let mutation_time_ms = (state.animation_timeline_origin.elapsed().as_secs_f64()* 1_000.0).min(f64::from(f32::MAX)) as f32;@@ -1580,9 +1593,7 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->.parse::<u32>().ok().map(NodeId::new)- .and_then(|reference| {- state.dom.as_ref()?.get_node(reference)?.parent- }),+ .and_then(|reference| state.dom.as_ref()?.get_node(reference)?.parent),"remove_child" => arg1.parse::<u32>().ok()@@ -1600,10 +1611,7 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->}if let Some(mutation) = retained_style_mutation {let retained = state.prepared_render.is_some()- && queue_retained_style_mutation(- &mut state.pending_style_mutations,- mutation,- );+ && queue_retained_style_mutation(&mut state.pending_style_mutations, mutation);if !retained {state.prepared_render = None;state.pending_style_mutations.clear();@@ -1626,7 +1634,13 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->};eprintln!("[timing] render-cache mutation sequence={} cmd={} node={} detail={} connected={} actual_change={} invalidated={}",- sequence, cmd, arg1, detail, impact.connected, impact.actual_change, invalidate+ sequence,+ cmd,+ arg1,+ detail,+ impact.connected,+ impact.actual_change,+ invalidate_geometry);}}@@ -1989,9 +2003,15 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->Err(_) => return "false".into(),};let child = NodeId::new(child);- let had_parent = dom.get_node(child).is_some_and(|node| node.parent.is_some());+ let had_parent = dom+ .get_node(child)+ .is_some_and(|node| node.parent.is_some());dom.remove_child(child);- (had_parent && dom.get_node(child).is_some_and(|node| node.parent.is_none())).to_string()+ (had_parent+ && dom+ .get_node(child)+ .is_some_and(|node| node.parent.is_none()))+ .to_string()}"insert_before" => {let new_node = match arg1.parse::<u32>() {@@ -2039,7 +2059,9 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->let nid = arg1.parse::<u32>().unwrap_or(0);let (ns, local) = arg2.split_once('\0').unwrap_or(("", arg2.as_str()));let val = dom- .with_node(NodeId::new(nid), |n| n.get_attribute_ns(ns, local).map(|s| s.to_string()))+ .with_node(NodeId::new(nid), |n| {+ n.get_attribute_ns(ns, local).map(|s| s.to_string())+ }).flatten();serde_json::to_string(&val).unwrap_or("null".into())}@@ -2442,7 +2464,10 @@ fn compare_node_order(dom: &DomTree, a: NodeId, b: NodeId) -> i32 {#[op2(fast)]fn op_runtime_events_enabled(state: &OpState) -> bool {- state.borrow::<SharedState>().borrow().runtime_events_enabled+ state+ .borrow::<SharedState>()+ .borrow()+ .runtime_events_enabled}#[op2(fast)]@@ -2661,8 +2686,19 @@ fn is_cors_unsafe_request_header_byte(byte: u8) -> bool {(byte < 0x20 && byte != b'\t')|| matches!(byte,- b'"' | b'(' | b')' | b':' | b'<' | b'>' | b'?' | b'@' | b'[' | b'\\'- | b']' | b'{' | b'}' | 0x7f+ b'"' | b'('+ | b')'+ | b':'+ | b'<'+ | b'>'+ | b'?'+ | b'@'+ | b'['+ | b'\\'+ | b']'+ | b'{'+ | b'}'+ | 0x7f)}@@ -2670,8 +2706,20 @@ fn is_http_token_byte(byte: u8) -> bool {byte.is_ascii_alphanumeric()|| matches!(byte,- b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+' | b'-' | b'.'- | b'^' | b'_' | b'`' | b'|' | b'~'+ b'!' | b'#'+ | b'$'+ | b'%'+ | b'&'+ | b'\''+ | b'*'+ | b'+'+ | b'-'+ | b'.'+ | b'^'+ | b'_'+ | b'`'+ | b'|'+ | b'~')}@@ -2732,11 +2780,11 @@ fn is_cors_safelisted_request_header(name: &str, value: &str) -> bool {if name.eq_ignore_ascii_case("accept") {return !value.bytes().any(is_cors_unsafe_request_header_byte);}- if name.eq_ignore_ascii_case("accept-language")- || name.eq_ignore_ascii_case("content-language")+ if name.eq_ignore_ascii_case("accept-language") || name.eq_ignore_ascii_case("content-language"){return value.bytes().all(|byte| {- byte.is_ascii_alphanumeric() || matches!(byte, b' ' | b'*' | b',' | b'-' | b'.' | b';' | b'=')+ byte.is_ascii_alphanumeric()+ || matches!(byte, b' ' | b'*' | b',' | b'-' | b'.' | b';' | b'=')});}if name.eq_ignore_ascii_case("content-type") {@@ -2795,18 +2843,16 @@ fn parse_cors_header_list<'a>(fn preflight_allows_method(method: &reqwest::Method, allowed: &[&str], credentialed: bool) -> bool {is_cors_safelisted_method(method)- || allowed.iter().any(|allowed| {- *allowed == method.as_str() || (*allowed == "*" && !credentialed)- })+ || allowed+ .iter()+ .any(|allowed| *allowed == method.as_str() || (*allowed == "*" && !credentialed))}fn preflight_allows_header(name: &str, allowed: &[&str], credentialed: bool) -> bool {allowed.iter().any(|allowed| allowed.eq_ignore_ascii_case(name))- || (!name.eq_ignore_ascii_case("authorization")- && !credentialed- && allowed.contains(&"*"))+ || (!name.eq_ignore_ascii_case("authorization") && !credentialed && allowed.contains(&"*"))}fn visible_response_headers(@@ -3153,10 +3199,7 @@ async fn op_fetch_url(unsafe_header_names.join(","),);}- let preflight = preflight_request- .send()- .await- .map_err(|e| {+ let preflight = preflight_request.send().await.map_err(|e| {deno_error::JsErrorBox::generic(format!("CORS preflight failed: {}", e))})?;@@ -3187,19 +3230,15 @@ async fn op_fetch_url()));}- let allowed_methods = parse_cors_header_list(- preflight.headers(),- "access-control-allow-methods",- )+ let allowed_methods =+ parse_cors_header_list(preflight.headers(), "access-control-allow-methods").ok_or_else(|| {deno_error::JsErrorBox::generic("CORS preflight returned an invalid Access-Control-Allow-Methods value",)})?;- let allowed_headers = parse_cors_header_list(- preflight.headers(),- "access-control-allow-headers",- )+ let allowed_headers =+ parse_cors_header_list(preflight.headers(), "access-control-allow-headers").ok_or_else(|| {deno_error::JsErrorBox::generic("CORS preflight returned an invalid Access-Control-Allow-Headers value",@@ -3426,8 +3465,7 @@ async fn op_fetch_url(// Browser semantics: 301/302/303 downgrade to GET with no body.// 307/308 preserve method and body.let status_code = resp.status().as_u16();- let downgraded_to_get =- status_code == 301 || status_code == 302 || status_code == 303;+ let downgraded_to_get = status_code == 301 || status_code == 302 || status_code == 303;if downgraded_to_get {current_method = reqwest::Method::GET;current_body.clear();@@ -3845,10 +3883,10 @@ pub(crate) fn glob_match(pattern: &str, url: &str) -> bool {#[cfg(test)]mod tests {use super::{- cors_response_allows, cors_unsafe_request_header_names, glob_match,- is_cors_safelisted_content_type, is_cors_safelisted_request_header,+ FetchCredentials, ObscuraState, cors_response_allows, cors_unsafe_request_header_names,+ glob_match, is_cors_safelisted_content_type, is_cors_safelisted_request_header,parse_cors_header_list, preflight_allows_header, preflight_allows_method,- sanitize_redirect_headers, validate_fetch_url, FetchCredentials, ObscuraState,+ sanitize_redirect_headers, validate_fetch_url,};use crate::runtime::ObscuraJsRuntime;use obscura_dom::parse_html;@@ -3870,21 +3908,37 @@ mod tests {// keep the body header and any custom header.let mut cross = base();sanitize_redirect_headers(&mut cross, true, false);- assert!(!cross.contains_key("Authorization"), "Authorization must be stripped cross-origin");- assert!(!cross.contains_key("Cookie"), "explicit Cookie must be stripped cross-origin");+ assert!(+ !cross.contains_key("Authorization"),+ "Authorization must be stripped cross-origin"+ );+ assert!(+ !cross.contains_key("Cookie"),+ "explicit Cookie must be stripped cross-origin"+ );assert!(cross.contains_key("Content-Type"));assert!(cross.contains_key("X-Keep"));// Same-origin 301/302/303 GET downgrade: keep credentials, drop body headers.let mut downgrade = base();sanitize_redirect_headers(&mut downgrade, false, true);- assert!(downgrade.contains_key("Authorization"), "Authorization kept on same-origin redirect");- assert!(!downgrade.contains_key("Content-Type"), "Content-Type dropped on GET downgrade");+ assert!(+ downgrade.contains_key("Authorization"),+ "Authorization kept on same-origin redirect"+ );+ assert!(+ !downgrade.contains_key("Content-Type"),+ "Content-Type dropped on GET downgrade"+ );// Same-origin, method preserved: nothing stripped.let mut same = base();sanitize_redirect_headers(&mut same, false, false);- assert_eq!(same.len(), 4, "nothing stripped when same-origin and method preserved");+ assert_eq!(+ same.len(),+ 4,+ "nothing stripped when same-origin and method preserved"+ );}use std::cell::RefCell;use std::collections::HashMap;@@ -3892,18 +3946,18 @@ mod tests {#[cfg(feature = "render")]use super::{- ensure_prepared_geometry, ensure_prepared_render, node_is_connected,- queue_retained_style_mutation, retained_style_mutation,- shadow_including_connected_nodes, MAX_PENDING_STYLE_MUTATIONS,+ MAX_PENDING_STYLE_MUTATIONS, ensure_prepared_geometry, ensure_prepared_render,+ node_is_connected, queue_retained_style_mutation, retained_style_mutation,+ shadow_including_connected_nodes,};#[cfg(feature = "render")]use obscura_dom::ShadowRootMode;use super::read_body_capped;- use super::{intercept_fulfill_response, visible_response_headers};use super::url_set_inner;- use super::{pbkdf2_derive, push_capped, PBKDF2_MAX_ITERATIONS, PBKDF2_MAX_OUTPUT_BYTES};- use base64::{engine::general_purpose::STANDARD as FULFILL_BASE64, Engine as _};+ use super::{PBKDF2_MAX_ITERATIONS, PBKDF2_MAX_OUTPUT_BYTES, pbkdf2_derive, push_capped};+ use super::{intercept_fulfill_response, visible_response_headers};+ use base64::{Engine as _, engine::general_purpose::STANDARD as FULFILL_BASE64};// #1008: URL property setters must follow WHATWG — search/hash keep a bare// delimiter as an empty component, and port parses the leading digits.@@ -3952,10 +4006,7 @@ mod tests {assert!(is_cors_safelisted_request_header("Range", "bytes=500-"));assert!(!is_cors_safelisted_request_header("Range", "bytes=-500"));assert!(!is_cors_safelisted_request_header("Range", "bytes=500-499"));- assert!(!is_cors_safelisted_request_header(- "Range",- "bytes=0-1,4-5"- ));+ assert!(!is_cors_safelisted_request_header("Range", "bytes=0-1,4-5"));}#[test]@@ -3994,11 +4045,7 @@ mod tests {#[test]fn cors_preflight_permissions_follow_credentials_and_authorization_rules() {- assert!(preflight_allows_method(- &reqwest::Method::POST,- &[],- true- ));+ assert!(preflight_allows_method(&reqwest::Method::POST, &[], true));assert!(preflight_allows_method(&reqwest::Method::DELETE,&["DELETE"],@@ -4025,11 +4072,7 @@ mod tests {&["authorization"],true));- assert!(!preflight_allows_header(- "Authorization",- &["*"],- false- ));+ assert!(!preflight_allows_header("Authorization", &["*"], false));assert!(preflight_allows_header("X-Trace", &["*"], false));assert!(!preflight_allows_header("X-Trace", &["*"], true));}@@ -4041,19 +4084,13 @@ mod tests {"access-control-allow-methods","GET, DELETE".parse().unwrap(),);- headers.append(- "access-control-allow-methods",- "PATCH".parse().unwrap(),- );+ headers.append("access-control-allow-methods", "PATCH".parse().unwrap());assert_eq!(parse_cors_header_list(&headers, "access-control-allow-methods"),Some(vec!["GET", "DELETE", "PATCH"]));- headers.append(- "access-control-allow-methods",- "@invalid".parse().unwrap(),- );+ headers.append("access-control-allow-methods", "@invalid".parse().unwrap());assert!(parse_cors_header_list(&headers, "access-control-allow-methods").is_none());}@@ -4061,7 +4098,9 @@ mod tests {// `bodyBase64`, not be silently corrupted by the lossy `body` text view.#[test]fn intercept_fulfill_carries_binary_body_as_base64() {- let raw = [0x89u8, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0xFF, 0xFE, 0x00];+ let raw = [+ 0x89u8, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0xFF, 0xFE, 0x00,+ ];let b64 = FULFILL_BASE64.encode(raw);let lossy = String::from_utf8_lossy(&raw).to_string();let result = intercept_fulfill_response(@@ -4182,7 +4221,13 @@ mod tests {#[test]fn pbkdf2_rejects_excessive_output_length() {- let err = pbkdf2_derive("SHA-256", b"pw", b"salt", 1_000, PBKDF2_MAX_OUTPUT_BYTES + 1)+ let err = pbkdf2_derive(+ "SHA-256",+ b"pw",+ b"salt",+ 1_000,+ PBKDF2_MAX_OUTPUT_BYTES + 1,+ ).expect_err("output length above the cap must be rejected");assert!(err.to_string().contains("length"),@@ -4201,11 +4246,17 @@ mod tests {// buffer straight from an untrusted u32 length. Each must reject a length// above its fixed maximum before allocating, and still work for ordinary// inputs. See #910.- use super::{hkdf_derive, random_bytes, HKDF_MAX_OUTPUT_BYTES, RANDOM_BYTES_MAX};+ use super::{HKDF_MAX_OUTPUT_BYTES, RANDOM_BYTES_MAX, hkdf_derive, random_bytes};#[test]fn hkdf_rejects_excessive_output_length() {- let err = hkdf_derive("SHA-256", b"ikm", b"salt", b"info", HKDF_MAX_OUTPUT_BYTES + 1)+ let err = hkdf_derive(+ "SHA-256",+ b"ikm",+ b"salt",+ b"info",+ HKDF_MAX_OUTPUT_BYTES + 1,+ ).expect_err("output length above the cap must be rejected");assert!(err.to_string().contains("exceeds"),@@ -4222,8 +4273,8 @@ mod tests {#[test]fn random_bytes_rejects_excessive_length() {- let err = random_bytes(RANDOM_BYTES_MAX + 1)- .expect_err("a draw above the cap must be rejected");+ let err =+ random_bytes(RANDOM_BYTES_MAX + 1).expect_err("a draw above the cap must be rejected");assert!(err.to_string().contains("exceeds"),"error should name the length cap: {err}"@@ -4236,7 +4287,6 @@ mod tests {assert_eq!(buf.len(), 32, "draw must return the requested length");}-// SEC-005 / #581 — op_fetch_url must not buffer an unbounded response body.// read_body_capped streams the body and refuses anything larger than the// cap, covering a server that just keeps sending with no Content-Length.@@ -4456,11 +4506,15 @@ mod tests {.unwrap();let values = result.as_array().unwrap();assert!(- values[..3].iter().all(|value| value.as_f64() == Some(100.0)),+ values[..3]+ .iter()+ .all(|value| value.as_f64() == Some(100.0)),"posted-task chains did not finish inside the 100ms pump: {result}",);assert!(- values[3].as_f64().is_some_and(|elapsed| elapsed >= 0.0 && elapsed < 75.0),+ values[3]+ .as_f64()+ .is_some_and(|elapsed| elapsed >= 0.0 && elapsed < 75.0),"300 chained posted-task deliveries retained timer-wheel latency: {result}",);}@@ -4680,15 +4734,18 @@ mod tests {let host = dom.get_element_by_id("host").unwrap();let source = dom.get_element_by_id("source").unwrap();let child = dom.get_element_by_id("shadow-child").unwrap();- let root = dom- .attach_shadow_root(host, ShadowRootMode::Open)- .unwrap();+ let root = dom.attach_shadow_root(host, ShadowRootMode::Open).unwrap();dom.append_child(root, child);assert!(node_is_connected(&dom, child));assert!(shadow_including_connected_nodes(&dom).contains(&child));assert!(- retained_style_mutation(&dom, "set_attribute", &child.index().to_string(), "class\0changed")+ retained_style_mutation(+ &dom,+ "set_attribute",+ &child.index().to_string(),+ "class\0changed"+ ).is_none(),"shadow mutations require a full scoped cascade");@@ -5060,7 +5117,9 @@ fn op_post_frame_message();return;}- gs.pending_frame_message_bytes = gs.pending_frame_message_bytes.saturating_add(data_json.len());+ gs.pending_frame_message_bytes = gs+ .pending_frame_message_bytes+ .saturating_add(data_json.len());gs.pending_frame_messages.push(PendingFrameMessage {target_frame_id,source_frame_id,@@ -5173,7 +5232,10 @@ fn op_posted_task(let callback = v8::Local::new(scope, callback);let receiver = v8::undefined(scope).into();let current_generation = v8::Number::new(scope, current_generation);- if callback.call(scope, receiver, &[current_generation.into()]).is_none() {+ if callback+ .call(scope, receiver, &[current_generation.into()])+ .is_none()+ {let message = scope.exception().map(|exception| exception.to_rust_string_lossy(scope))@@ -5193,9 +5255,7 @@ enum PostedTaskOwnerStatus {Generation(u64),}-fn posted_task_owner_status(- owner: &std::rc::Weak<RefCell<ObscuraState>>,-) -> PostedTaskOwnerStatus {+fn posted_task_owner_status(owner: &std::rc::Weak<RefCell<ObscuraState>>) -> PostedTaskOwnerStatus {let Some(owner) = owner.upgrade() else {return PostedTaskOwnerStatus::Gone;};@@ -5427,7 +5487,7 @@ fn op_subtle_aes_ctr(_ => {return Err(crypto_err("AES-CTR supports counter lengths of 32, 64, or 128 bits",- ))+ ));}}Ok(buf)@@ -5956,11 +6016,16 @@ fn op_canvas_register_surface(if !is_canvas {return false;}- let replacing = state.canvas_surfaces.get(&node).map(|surface| surface.pixels.len());+ let replacing = state+ .canvas_surfaces+ .get(&node)+ .map(|surface| surface.pixels.len());let retained_bytes = state.canvas_surfaces.values()- .try_fold(0usize, |total, surface| total.checked_add(surface.pixels.len()))+ .try_fold(0usize, |total, surface| {+ total.checked_add(surface.pixels.len())+ }).and_then(|total| total.checked_sub(replacing.unwrap_or(0))).and_then(|total| total.checked_add(expected));if retained_bytes.is_none_or(|bytes| bytes > MAX_CANVAS_SURFACE_BYTES) {@@ -6050,6 +6115,7 @@ pub fn build_extension() -> Extension {ops.push(op_image_metadata());ops.push(op_load_image_metadata());ops.push(op_layout_geometry());+ ops.push(op_layout_hit_test());ops.push(op_resize_observer_measurements());ops.push(op_intersection_observer_measurements());ops.push(op_computed_style());@@ -6138,7 +6204,12 @@ fn op_waapi_create(state: &OpState, #[string] input: &str) -> bool {let shared = state.borrow::<SharedState>().clone();let mut state = shared.borrow_mut();let node = NodeId::new(input.node);- if state.dom.as_ref().and_then(|dom| dom.get_node(node)).is_none() {+ if state+ .dom+ .as_ref()+ .and_then(|dom| dom.get_node(node))+ .is_none()+ {return false;}let start_time_ms = waapi_document_time_ms(&state);@@ -6159,14 +6230,20 @@ fn op_waapi_create(state: &OpState, #[string] input: &str) -> bool {} else {input.iterations};- state.animation_timeline.register_waapi(obscura_render::WaapiAnimation {+ state+ .animation_timeline+ .register_waapi(obscura_render::WaapiAnimation {id: input.id,node,- keyframes: input.keyframes.into_iter().map(|frame| obscura_render::WaapiKeyframe {+ keyframes: input+ .keyframes+ .into_iter()+ .map(|frame| obscura_render::WaapiKeyframe {offset: frame.offset.clamp(0.0, 1.0),opacity: frame.opacity.map(|value| value.clamp(0.0, 1.0)),transform: frame.transform,- }).collect(),+ })+ .collect(),timing: obscura_render::AnimationTiming {duration_ms: input.duration,delay_ms: input.delay,@@ -6187,12 +6264,7 @@ fn op_waapi_create(state: &OpState, #[string] input: &str) -> bool {#[cfg(feature = "render")]#[op2(fast)]-fn op_waapi_control(- state: &OpState,- id: f64,- #[string] action: &str,- value: f64,-) -> bool {+fn op_waapi_control(state: &OpState, id: f64, #[string] action: &str, value: f64) -> bool {if !id.is_finite() || id < 0.0 {return false;}@@ -6216,11 +6288,11 @@ fn op_waapi_control(obscura_render::WaapiPlayState::Running,document_time,),- "currentTime" if value.is_finite() => state.animation_timeline.set_waapi_current_time(- id,- document_time,- value as f32,- ),+ "currentTime" if value.is_finite() => {+ state+ .animation_timeline+ .set_waapi_current_time(id, document_time, value as f32)+ }_ => false,};if changed {@@ -6320,17 +6392,14 @@ pub(crate) fn ensure_prepared_render(let render_media = state.render_media;let animation_sample = state.animation_sample;let incompatible = state.prepared_render.as_ref().is_some_and(|prepared| {- prepared.viewport() != viewport- || prepared.base_url() != base_url.as_deref()+ prepared.viewport() != viewport || prepared.base_url() != base_url.as_deref()});let needs_rebuild = state.prepared_render.as_ref().map_or(true, |prepared| {incompatible || prepared.animation_sample() != animation_sample}) || !state.pending_style_mutations.is_empty();if needs_rebuild {if let Some(dom) = state.dom.as_ref() {- state- .animation_timeline- .materialize_start_candidates(dom);+ state.animation_timeline.materialize_start_candidates(dom);}let previous = (!incompatible && render_media == obscura_render::CssMediaType::Screen).then(|| state.prepared_render.take())@@ -6391,10 +6460,7 @@ pub(crate) fn ensure_prepared_render(if animation_sample.mode == obscura_render::AnimationSampleMode::DocumentTime {state.animation_timeline.clear_start_candidates();}- let connected = state- .dom- .as_ref()- .map(shadow_including_connected_nodes);+ let connected = state.dom.as_ref().map(shadow_including_connected_nodes);if let Some(connected) = connected {state.animation_timeline@@ -6411,9 +6477,7 @@ pub(crate) fn ensure_prepared_render(/// styles. `animation_sample` on PreparedRender remains behind intentionally,/// making a later paint or computed-style consumer take the exact path above.#[cfg(feature = "render")]-fn ensure_prepared_geometry(- state: &mut ObscuraState,-) -> Option<&obscura_render::PreparedRender> {+fn ensure_prepared_geometry(state: &mut ObscuraState) -> Option<&obscura_render::PreparedRender> {let base_url = document_base_url(state);let reusable = state.pending_style_mutations.is_empty()&& !state.animation_timeline.has_pending_start_candidates()@@ -6436,8 +6500,8 @@ pub(crate) fn sample_live_document_animations(state: &mut ObscuraState) {}state.animation_sampled_task_generation = state.animation_task_generation;let sample = obscura_render::AnimationSample::document(- (state.animation_timeline_origin.elapsed().as_secs_f64() * 1_000.0)- .min(f64::from(f32::MAX)) as f32,+ (state.animation_timeline_origin.elapsed().as_secs_f64() * 1_000.0).min(f64::from(f32::MAX))+ as f32,);if state.animation_sample == sample {return;@@ -6445,15 +6509,15 @@ pub(crate) fn sample_live_document_animations(state: &mut ObscuraState) {if sample.time.milliseconds > state.animation_sample.time.milliseconds&& state.animation_sample.mode == obscura_render::AnimationSampleMode::DocumentTime&& state.pending_style_mutations.is_empty()- && state.prepared_render.as_mut().is_some_and(|prepared| {- prepared.advance_inactive_animation_sample_time(sample.time)- })+ && state+ .prepared_render+ .as_mut()+ .is_some_and(|prepared| prepared.advance_inactive_animation_sample_time(sample.time)){state.animation_sample = sample;return;}- let forward_document_sample =- sample.mode == obscura_render::AnimationSampleMode::DocumentTime+ let forward_document_sample = sample.mode == obscura_render::AnimationSampleMode::DocumentTime&& state.animation_sample.mode == obscura_render::AnimationSampleMode::DocumentTime&& sample.time.milliseconds > state.animation_sample.time.milliseconds;state.animation_sample = sample;@@ -6648,12 +6712,10 @@ fn load_image_metadata_without_page_transport(gs: &mut ObscuraState, node_id: Nolet Some(dom) = gs.dom.as_ref() else {return serde_json::json!({ "ok": false, "currentSrc": "" }).to_string();};- let Some((current_src, density, dimensions)) = gs.render_resources.image_element_metadata(- dom,- node_id,- viewport,- base_url.as_deref(),- ) else {+ let Some((current_src, density, dimensions)) =+ gs.render_resources+ .image_element_metadata(dom, node_id, viewport, base_url.as_deref())+ else {return serde_json::json!({"state": "error","ok": false,@@ -6677,22 +6739,18 @@ fn finish_async_image_metadata() -> String {let gs = shared.borrow();if gs.document_generation != document_generation {- return serde_json::json!({ "state": "stale", "currentSrc": expected_url })- .to_string();+ return serde_json::json!({ "state": "stale", "currentSrc": expected_url }).to_string();}let Some(dom) = gs.dom.as_ref() else {- return serde_json::json!({ "state": "stale", "currentSrc": expected_url })- .to_string();+ return serde_json::json!({ "state": "stale", "currentSrc": expected_url }).to_string();};if image_request_profile(dom, node_id) != request_profile {- return serde_json::json!({ "state": "stale", "currentSrc": expected_url })- .to_string();+ return serde_json::json!({ "state": "stale", "currentSrc": expected_url }).to_string();}let Some((current_src, density, known, dimensions)) =profiled_cached_image_metadata(&gs, node_id)else {- return serde_json::json!({ "state": "stale", "currentSrc": expected_url })- .to_string();+ return serde_json::json!({ "state": "stale", "currentSrc": expected_url }).to_string();};if current_src != expected_url {return serde_json::json!({ "state": "stale", "currentSrc": current_src }).to_string();@@ -6735,9 +6793,7 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> Stringreturn serde_json::json!({ "state": "stale", "currentSrc": "" }).to_string();}let profile = image_request_profile(dom, node_id);- let Some((selected_url, _, known, _)) =- profiled_cached_image_metadata(&gs, node_id)- else {+ let Some((selected_url, _, known, _)) = profiled_cached_image_metadata(&gs, node_id) else {return serde_json::json!({ "state": "error", "ok": false, "currentSrc": "" }).to_string();};@@ -6793,7 +6849,8 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> Stringwaiters.push(sender);Some(receiver)} else {- gs.render_image_in_flight.insert(request_key.clone(), Vec::new());+ gs.render_image_in_flight+ .insert(request_key.clone(), Vec::new());None}};@@ -6851,11 +6908,7 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> Stringhttp_client.as_ref().unwrap()- .fetch_resource_with_callbacks(- parsed_url,- resource_request,- callbacks.as_deref(),- )+ .fetch_resource_with_callbacks(parsed_url, resource_request, callbacks.as_deref()).await.ok()}@@ -6913,10 +6966,7 @@ pub(crate) fn clamp_scroll_offset(state: &mut ObscuraState, requested: (f32, f32}#[cfg(feature = "render")]-fn clamp_scroll_offset_for_geometry(- state: &mut ObscuraState,- requested: (f32, f32),-) -> (f32, f32) {+fn clamp_scroll_offset_for_geometry(state: &mut ObscuraState, requested: (f32, f32)) -> (f32, f32) {clamp_scroll_offset_for_consumer(state, requested, true)}@@ -6989,6 +7039,7 @@ fn op_layout_geometry(state: &OpState, #[string] nid_str: String) -> String {}).collect::<Vec<_>>();let viewport_fixed = prepared.viewport_fixed_nodes().contains(&nid);+ let pointer_events_none = prepared.pointer_events_none(nid);return serde_json::json!({"x": rect.x,"y": rect.y,@@ -6998,12 +7049,38 @@ fn op_layout_geometry(state: &OpState, #[string] nid_str: String) -> String {"clientHeight": client_height,"clientRects": client_rects,"viewportFixed": viewport_fixed,+ "pointerEventsNone": pointer_events_none,}).to_string();}String::new()}+/// Renderer-backed CSSOM hit test. Returns the native node id or -1 when the+/// point is outside the viewport or no rendered element contains it.+#[cfg(feature = "render")]+#[op2(fast)]+fn op_layout_hit_test(state: &OpState, x: f64, y: f64) -> i32 {+ let shared = state.borrow::<SharedState>().clone();+ let mut gs = shared.borrow_mut();+ sample_live_document_animations(&mut gs);+ if ensure_resolved_scroll_for_geometry(&mut gs).is_none() {+ return -1;+ }+ let Some((_, scroll)) = gs.resolved_scroll.as_ref() else {+ return -1;+ };+ let Some(prepared) = gs.prepared_render.as_ref() else {+ return -1;+ };+ let Some(dom) = gs.dom.as_ref() else {+ return -1;+ };+ prepared+ .hit_test(dom, scroll, x as f32, y as f32)+ .map_or(-1, |id| id.index() as i32)+}+/// Measure every target in one ResizeObserver rendering opportunity.////// ResizeObserver gathers all observations before it invokes any callback.@@ -7039,8 +7116,8 @@ fn op_resize_observer_measurements(state: &OpState, #[string] nids_json: String).unwrap_or_else(|_| "[]".to_string());};- let style_value =- |snapshot: &std::collections::HashMap<&'static str, String>, name: &'static str| {+ let style_value = |snapshot: &std::collections::HashMap<&'static str, String>,+ name: &'static str| {snapshot.get(name).cloned().unwrap_or_default()};let measurements = nids@@ -7082,10 +7159,7 @@ fn op_resize_observer_measurements(state: &OpState, #[string] nids_json: String)#[cfg(feature = "render")]#[op2]#[string]-fn op_intersection_observer_measurements(- state: &OpState,- #[string] nids_json: String,-) -> String {+fn op_intersection_observer_measurements(state: &OpState, #[string] nids_json: String) -> String {let nids = serde_json::from_str::<Vec<u32>>(&nids_json).unwrap_or_default();if nids.is_empty() {return "[]".to_string();@@ -7107,8 +7181,8 @@ fn op_intersection_observer_measurements(.unwrap_or_else(|_| "[]".to_string());};- let style_value =- |snapshot: &std::collections::HashMap<&'static str, String>, name: &'static str| {+ let style_value = |snapshot: &std::collections::HashMap<&'static str, String>,+ name: &'static str| {snapshot.get(name).cloned().unwrap_or_default()};let measurements = nidsdiff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 53440fea..0346a104 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -6,7 +6,7 @@ use std::pin::Pin;use std::rc::Rc;use std::task::{Context, Poll};-use deno_core::{v8, JsRuntime, RuntimeOptions};+use deno_core::{JsRuntime, RuntimeOptions, v8};use obscura_dom::{DomTree, NodeId};#[cfg(feature = "render")]use obscura_net::{RequestCredentials, RequestMode, ResourceRequest};@@ -20,8 +20,8 @@ use crate::module_loader::{ModuleLoadActivity, ObscuraModuleLoader};#[cfg(all(test, feature = "render"))]use crate::ops::ensure_prepared_render;use crate::ops::{- build_extension, node_is_script, ObscuraState, RuntimeEvent, RuntimeExceptionEvent,- StoredNetworkResponseBody,+ ObscuraState, RuntimeEvent, RuntimeExceptionEvent, StoredNetworkResponseBody, build_extension,+ node_is_script,};#[cfg(feature = "render")]use crate::ops::{@@ -29,9 +29,7 @@ use crate::ops::{};#[cfg(feature = "render")]-struct RuntimeCanvasSurfaceSource<'a>(- &'a HashMap<NodeId, crate::ops::CanvasBackingSurface>,-);+struct RuntimeCanvasSurfaceSource<'a>(&'a HashMap<NodeId, crate::ops::CanvasBackingSurface>);#[cfg(feature = "render")]impl obscura_render::CanvasSurfaceSource for RuntimeCanvasSurfaceSource<'_> {@@ -153,13 +151,9 @@ fn with_sync_render_loading_disabled<R>(state: &mut ObscuraState,capture: impl FnOnce(&mut ObscuraState) -> R,) -> R {- let previous = state- .render_resources- .set_sync_loading_enabled(false);+ let previous = state.render_resources.set_sync_loading_enabled(false);let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| capture(state)));- state- .render_resources- .set_sync_loading_enabled(previous);+ state.render_resources.set_sync_loading_enabled(previous);match result {Ok(value) => value,Err(payload) => std::panic::resume_unwind(payload),@@ -558,12 +552,8 @@ impl ObscuraJsRuntime {let state_clone = state.clone();let import_map = state.borrow().import_map.clone();- let module_loader = ObscuraModuleLoader::with_page_state(- base_url,- proxy_url,- &state,- import_map.clone(),- );+ let module_loader =+ ObscuraModuleLoader::with_page_state(base_url, proxy_url, &state, import_map.clone());let module_load_activity = module_loader.activity();let loaded_module_specifiers = module_loader.loaded_specifiers();let module_loader = Rc::new(module_loader);@@ -770,7 +760,7 @@ impl ObscuraJsRuntime {&mut self,realm: &deno_core::v8::Global<deno_core::v8::Context>,) {- use deno_core::{v8, CONTEXT_STATE_SLOT_INDEX, MODULE_MAP_SLOT_INDEX};+ use deno_core::{CONTEXT_STATE_SLOT_INDEX, MODULE_MAP_SLOT_INDEX, v8};let main = self.runtime().main_context();let mut entered = self.runtime();@@ -1068,7 +1058,9 @@ impl ObscuraJsRuntime {entry.set(scope, key.into(), document);}let index = v8::Integer::new_from_unsigned(scope, frame_id);- registry.set(scope, index.into(), entry.into()).unwrap_or(false)+ registry+ .set(scope, index.into(), entry.into())+ .unwrap_or(false)}/// The table ops consult to find the calling realm's document.@@ -1269,6 +1261,10 @@ impl ObscuraJsRuntime {self.state.borrow_mut().pending_navigation.take()}+ pub fn has_pending_navigation(&self) -> bool {+ self.state.borrow().pending_navigation.is_some()+ }+pub fn take_pending_binding_calls(&self) -> Vec<(String, String)> {std::mem::take(&mut self.state.borrow_mut().pending_binding_calls)}@@ -1490,18 +1486,11 @@ impl ObscuraJsRuntime {pub fn set_screen_size_override(&mut self, size: Option<(f64, f64)>, emulated: bool) {let script = match size {Some((width, height))- if width.is_finite()- && height.is_finite()- && width > 0.0- && height > 0.0 =>+ if width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0 =>{- format!(- "globalThis.__obscura_set_screen_override({width},{height},{emulated});"- )+ format!("globalThis.__obscura_set_screen_override({width},{height},{emulated});")}- _ => format!(- "globalThis.__obscura_set_screen_override(null,null,{emulated});"- ),+ _ => format!("globalThis.__obscura_set_screen_override(null,null,{emulated});"),};let _ = self.execute_runtime_script("<set-screen-size>", script);}@@ -1517,10 +1506,7 @@ impl ObscuraJsRuntime {/// Select the document-timeline instant used by the next render flush./// Returns false for invalid times and preserves the current sample.#[cfg(feature = "render")]- pub fn set_animation_sample_time(- &self,- sample: obscura_render::AnimationSampleTime,- ) -> bool {+ pub fn set_animation_sample_time(&self, sample: obscura_render::AnimationSampleTime) -> bool {self.set_animation_sample(obscura_render::AnimationSample::document(sample.milliseconds,))@@ -1533,8 +1519,8 @@ impl ObscuraJsRuntime {}let mut state = self.state.borrow_mut();if state.animation_sample != sample {- let forward_document_sample =- sample.mode == obscura_render::AnimationSampleMode::DocumentTime+ let forward_document_sample = sample.mode+ == obscura_render::AnimationSampleMode::DocumentTime&& state.animation_sample.mode == obscura_render::AnimationSampleMode::DocumentTime&& sample.time.milliseconds > state.animation_sample.time.milliseconds;if forward_document_sample@@ -1620,11 +1606,7 @@ impl ObscuraJsRuntime {viewport: (f32, f32),base_url: Option<&str>,) -> Option<Vec<u8>> {- self.screenshot_prepared_with_surface_color(- viewport,- base_url,- [255, 255, 255, 255],- )+ self.screenshot_prepared_with_surface_color(viewport, base_url, [255, 255, 255, 255])}/// Paint an unprepared view of the current document against the runtime's@@ -1875,9 +1857,7 @@ impl ObscuraJsRuntime {.map(|value| value.trim().to_ascii_lowercase()).as_deref(){- Some("use-credentials") => {- crate::ops::ImageRequestProfile::CorsInclude- }+ Some("use-credentials") => crate::ops::ImageRequestProfile::CorsInclude,Some(_) => crate::ops::ImageRequestProfile::CorsSameOrigin,None => crate::ops::ImageRequestProfile::NoCorsInclude,};@@ -1912,11 +1892,7 @@ impl ObscuraJsRuntime {}#[cfg(feature = "render")]- fn seed_shared_render_resource(- &mut self,- url: String,- bytes: Option<std::sync::Arc<[u8]>>,- ) {+ fn seed_shared_render_resource(&mut self, url: String, bytes: Option<std::sync::Arc<[u8]>>) {let mut state = self.state.borrow_mut();match bytes {Some(bytes) => {@@ -2039,8 +2015,8 @@ impl ObscuraJsRuntime {candidates: Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)>,) -> Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)> {let mut state = self.state.borrow_mut();- let available = MAX_PENDING_RENDER_RESOURCES- .saturating_sub(state.render_resource_in_flight.len());+ let available =+ MAX_PENDING_RENDER_RESOURCES.saturating_sub(state.render_resource_in_flight.len());candidates.into_iter().filter(|(url, profile, is_font)| {@@ -2133,7 +2109,8 @@ impl ObscuraJsRuntime {let started = requests.len();let task = tokio::spawn(async move {use deno_core::futures::StreamExt as _;- let loads = deno_core::futures::stream::iter(requests.into_iter().map(|(raw, profile, is_font)| {+ let loads = deno_core::futures::stream::iter(requests.into_iter().map(+ |(raw, profile, is_font)| {let http_client = http_client.clone();#[cfg(feature = "stealth")]let stealth_client = stealth_client.clone();@@ -2154,7 +2131,7 @@ impl ObscuraJsRuntime {profile,is_font,response: None,- }+ };}};let kind = if is_font {@@ -2177,11 +2154,19 @@ impl ObscuraJsRuntime {#[cfg(feature = "stealth")]let response = match (stealth_client, http_client) {(Some(stealth_client), _) => stealth_client- .fetch_resource_with_callbacks(&parsed, request, callbacks.as_deref())+ .fetch_resource_with_callbacks(+ &parsed,+ request,+ callbacks.as_deref(),+ ).await.ok(),(None, Some(http_client)) => http_client- .fetch_resource_with_callbacks(&parsed, request, callbacks.as_deref())+ .fetch_resource_with_callbacks(+ &parsed,+ request,+ callbacks.as_deref(),+ ).await.ok(),(None, None) => None,@@ -2189,7 +2174,11 @@ impl ObscuraJsRuntime {#[cfg(not(feature = "stealth"))]let response = match http_client {Some(http_client) => http_client- .fetch_resource_with_callbacks(&parsed, request, callbacks.as_deref())+ .fetch_resource_with_callbacks(+ &parsed,+ request,+ callbacks.as_deref(),+ ).await.ok(),None => None,@@ -2221,7 +2210,8 @@ impl ObscuraJsRuntime {response: None,})})- }))+ },+ )).buffer_unordered(crate::ops::RENDER_RESOURCE_CONCURRENCY);deno_core::futures::pin_mut!(loads);while let Some(load) = loads.next().await {@@ -2237,9 +2227,15 @@ impl ObscuraJsRuntime {}notify.notify_waiters();});- state.render_resource_tasks.retain(|task| !task.is_finished());+ state+ .render_resource_tasks+ .retain(|task| !task.is_finished());state.render_resource_tasks.push(task);- tracing::debug!(started, generation, "started background render resource loads");+ tracing::debug!(+ started,+ generation,+ "started background render resource loads"+ );started}@@ -2297,10 +2293,11 @@ impl ObscuraJsRuntime {tracing::debug!(url = %load.url, "discarded render resource load of a retired document");continue;}- self.state- .borrow_mut()- .render_resource_in_flight- .remove(&(load.url.clone(), load.profile, load.is_font));+ self.state.borrow_mut().render_resource_in_flight.remove(&(+ load.url.clone(),+ load.profile,+ load.is_font,+ ));let is_font = load.is_font;let bytes = match &load.response {Some(response) if (200..300).contains(&response.status) => {@@ -2975,8 +2972,7 @@ impl ObscuraJsRuntime {Err(payload) => {let message = panic_payload_message(payload.as_ref());let outcome = if message.contains("Module already evaluated") {- self- .runtime()+ self.runtime().get_module_namespace(module_id).map(|_| ()).map_err(|error| format!("{} eval error: {}", what, error))@@ -3173,11 +3169,15 @@ impl ObscuraJsRuntime {let Some(script) = script else {if tc_scope.is_execution_terminating() {tc_scope.cancel_terminate_execution();- return Err(("JS error: Uncaught Error: execution terminated".to_string(), None));+ return Err((+ "JS error: Uncaught Error: execution terminated".to_string(),+ None,+ ));}return match tc_scope.exception() {Some(exception) => {- let error = deno_core::error::JsError::from_v8_exception(tc_scope, exception);+ let error =+ deno_core::error::JsError::from_v8_exception(tc_scope, exception);Err((format!("JS error: {error}"), Some(error)))}None => Err((@@ -3189,11 +3189,15 @@ impl ObscuraJsRuntime {if script.run(tc_scope).is_none() {if tc_scope.is_execution_terminating() {tc_scope.cancel_terminate_execution();- return Err(("JS error: Uncaught Error: execution terminated".to_string(), None));+ return Err((+ "JS error: Uncaught Error: execution terminated".to_string(),+ None,+ ));}return match tc_scope.exception() {Some(exception) => {- let error = deno_core::error::JsError::from_v8_exception(tc_scope, exception);+ let error =+ deno_core::error::JsError::from_v8_exception(tc_scope, exception);Err((format!("JS error: {error}"), Some(error)))}None => Err((@@ -3346,9 +3350,7 @@ impl ObscuraJsRuntime {/// Whether a parser-blocking script inserted by `document.write()` still/// has fetch or evaluation work outstanding.pub fn has_pending_parser_blocking_scripts(&mut self) -> bool {- self.evaluate(- "globalThis.__obscura_hasPendingParserBlockingScripts?.() === true",- )+ self.evaluate("globalThis.__obscura_hasPendingParserBlockingScripts?.() === true").ok().and_then(|value| value.as_bool()).unwrap_or(false)@@ -3445,11 +3447,11 @@ impl ObscuraJsRuntime {// per cooperative task. Adding the floor after the observation budget// guarantees that even a task beginning just before `deadline` gets// the same bounded completion allowance.- let synchronous_budget = budget- .saturating_add(std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS));- let token =- self.arm_watchdog(synchronous_budget- + std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS));+ let synchronous_budget =+ budget.saturating_add(std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS));+ let token = self.arm_watchdog(+ synchronous_budget + std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS),+ );let result = loop {if tokio::time::Instant::now() >= deadline {break Ok(());@@ -3529,12 +3531,10 @@ impl ObscuraJsRuntime {.poll_event_loop(cx, deno_core::PollEventLoopOptions::default());match tick {std::task::Poll::Ready(Ok(())) => std::task::Poll::Ready(Ok(true)),- std::task::Poll::Ready(Err(error)) => std::task::Poll::Ready(Err(format!(- "Event loop error: {error}"- ))),- std::task::Poll::Pending if waiting_for_wake => {- std::task::Poll::Ready(Ok(false))+ std::task::Poll::Ready(Err(error)) => {+ std::task::Poll::Ready(Err(format!("Event loop error: {error}")))}+ std::task::Poll::Pending if waiting_for_wake => std::task::Poll::Ready(Ok(false)),std::task::Poll::Pending => {waiting_for_wake = true;std::task::Poll::Pending@@ -3606,12 +3606,10 @@ impl ObscuraJsRuntime {tracing::warn!("page task error, continuing the event loop: {error}");std::task::Poll::Ready(Ok(false))}- std::task::Poll::Ready(Err(error)) => std::task::Poll::Ready(Err(format!(- "Event loop error: {error}"- ))),- std::task::Poll::Pending if waiting_for_wake => {- std::task::Poll::Ready(Ok(false))+ std::task::Poll::Ready(Err(error)) => {+ std::task::Poll::Ready(Err(format!("Event loop error: {error}")))}+ std::task::Poll::Pending if waiting_for_wake => std::task::Poll::Ready(Ok(false)),std::task::Poll::Pending => {waiting_for_wake = true;std::task::Poll::Pending@@ -3667,8 +3665,7 @@ impl ObscuraJsRuntime {let activity_tail = std::time::Duration::from_millis(OBSERVABLE_ACTIVITY_TAIL_MS);let mut activity_deadline = deadline.min(started + activity_tail);let token = self.arm_watchdog(- budget- .saturating_add(std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS))+ budget.saturating_add(std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS))+ std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS),);let mut generation = self.activity_generation();@@ -3736,10 +3733,8 @@ impl ObscuraJsRuntime {+ std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS)+ std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS),);- let tick = tokio::time::timeout_at(- policy_deadline,- self.run_cooperative_event_loop_tick(),- )+ let tick =+ tokio::time::timeout_at(policy_deadline, self.run_cooperative_event_loop_tick()).await;let tick_fired = self.disarm_watchdog(tick_watchdog);if tick_fired {@@ -3820,11 +3815,7 @@ impl ObscuraJsRuntime {/// added ~7s per click because Puppeteer's `isIntersectingViewport`/// disconnects its observer in the callback, but our scheduled/// re-fires keep the event loop "busy" until they all fire.- pub async fn resolve_promises_until<F>(- &mut self,- mut done_check: F,- max_total_ms: u64,- ) -> bool+ pub async fn resolve_promises_until<F>(&mut self, mut done_check: F, max_total_ms: u64) -> boolwhereF: FnMut(&mut Self) -> bool,{@@ -3846,11 +3837,8 @@ impl ObscuraJsRuntime {let event_loop = entered_runtime_future(&mut self.js_runtime, |runtime| {runtime.run_event_loop(deno_core::PollEventLoopOptions::default())});- let _ = tokio::time::timeout(- tokio::time::Duration::from_millis(tick_ms),- event_loop,- )- .await;+ let _ =+ tokio::time::timeout(tokio::time::Duration::from_millis(tick_ms), event_loop).await;if self.recover_heap_limit() {return false;}@@ -4053,10 +4041,10 @@ impl ObscuraJsRuntime {}let expression = self.evaluation_recipes.get(object_id)?.clone();let object_id_literal = js_string_literal(object_id);- let code = format!(- "globalThis.__obscura_objects[{object_id_literal}] = (\n{expression}\n);"- );- self.execute_runtime_script("<restore-cdp-object>", code).ok()?;+ let code =+ format!("globalThis.__obscura_objects[{object_id_literal}] = (\n{expression}\n);");+ self.execute_runtime_script("<restore-cdp-object>", code)+ .ok()?;let retrieval = format!("globalThis.__obscura_objects[{object_id_literal}]");self.object_store.insert(object_id.to_string(), retrieval.clone());@@ -4361,14 +4349,16 @@ mod tests {fn get_element_by_id_reflects_remove_attribute() {let mut rt = setup_runtime("<html><body><div id='test'>x</div></body></html>");assert_eq!(- rt.evaluate("document.getElementById('test') !== null").unwrap(),+ rt.evaluate("document.getElementById('test') !== null")+ .unwrap(),serde_json::json!(true),"the element should be found before its id is removed");rt.evaluate("document.getElementById('test').removeAttribute('id')").unwrap();assert_eq!(- rt.evaluate("document.getElementById('test') === null").unwrap(),+ rt.evaluate("document.getElementById('test') === null")+ .unwrap(),serde_json::json!(true),"getElementById must not return an element whose id was removed");@@ -4435,13 +4425,14 @@ mod tests {rt.mark_render_resources_in_flight(requests).len(),MAX_PENDING_RENDER_RESOURCES);- assert!(rt- .mark_render_resources_in_flight(vec![(+ assert!(+ rt.mark_render_resources_in_flight(vec![("https://assets.test/extra.png".to_string(),None,false,)])- .is_empty());+ .is_empty()+ );}/// A load that answers after the document was retired (abort is not a@@ -4453,10 +4444,13 @@ mod tests {let url = "https://example.test/a.svg".to_string();let mut rt = ObscuraJsRuntime::new();rt.set_http_client(std::sync::Arc::new(obscura_net::ObscuraHttpClient::new()));- rt.set_dom(parse_html(&format!("<html><body><img src=\"{url}\"></body></html>")));+ rt.set_dom(parse_html(&format!(+ "<html><body><img src=\"{url}\"></body></html>"+ )));rt.set_url("https://example.test/page");let body = std::sync::Arc::<[u8]>::from(- br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"></svg>"##.as_slice(),+ br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"></svg>"##+ .as_slice(),);let answer = |generation, tx: &tokio::sync::mpsc::UnboundedSender<_>| {tx.send(crate::ops::RenderResourceLoad {@@ -4478,9 +4472,15 @@ mod tests {rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);rt.abandon_render_resources();assert!(!rt.has_pending_render_resources());- assert!(answer(generation, &old_tx).is_err(), "retired channel is closed");+ assert!(+ answer(generation, &old_tx).is_err(),+ "retired channel is closed"+ );assert_eq!(rt.apply_render_resource_results(), 0);- assert!(!rt.render_resource_is_known(&url), "late bytes must not seed the runtime");+ assert!(+ !rt.render_resource_is_known(&url),+ "late bytes must not seed the runtime"+ );// The same runtime requests the URL again; a stale-generation answer// that somehow reaches the live channel is fenced too.@@ -4489,7 +4489,10 @@ mod tests {let live_tx = rt.state.borrow().render_resource_tx.clone();assert!(answer(generation.wrapping_sub(1), &live_tx).is_ok());assert_eq!(rt.apply_render_resource_results(), 0);- assert!(rt.has_pending_render_resources(), "stale answer must not clear the live request");+ assert!(+ rt.has_pending_render_resources(),+ "stale answer must not clear the live request"+ );assert!(!rt.render_resource_is_known(&url));assert!(answer(generation, &live_tx).is_ok());assert_eq!(rt.apply_render_resource_results(), 1);@@ -4504,17 +4507,25 @@ mod tests {async fn stealth_only_transport_starts_render_resource_loads() {let url = "http://127.0.0.1:9/a.svg".to_string();let mut rt = ObscuraJsRuntime::new();- rt.set_stealth_client(std::sync::Arc::new(obscura_net::StealthHttpClient::with_proxy(+ rt.set_stealth_client(std::sync::Arc::new(+ obscura_net::StealthHttpClient::with_proxy(std::sync::Arc::new(obscura_net::CookieJar::new()),None,true,- )));+ ),+ ));assert!(rt.has_page_transport());assert!(!rt.render_resource_sync_loading_enabled());- rt.set_dom(parse_html(&format!("<html><body><img src=\"{url}\"></body></html>")));+ rt.set_dom(parse_html(&format!(+ "<html><body><img src=\"{url}\"></body></html>"+ )));rt.set_url("http://127.0.0.1:9/page");let requests = rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);- assert_eq!(rt.start_render_resource_loads(requests), 1, "stealth client is a transport");+ assert_eq!(+ rt.start_render_resource_loads(requests),+ 1,+ "stealth client is a transport"+ );assert!(rt.has_pending_render_resources());// The unreachable origin answers with a failed load, which settles it.for _ in 0..200 {@@ -4523,35 +4534,90 @@ mod tests {}tokio::time::sleep(std::time::Duration::from_millis(25)).await;}- assert!(!rt.has_pending_render_resources(), "the load must finish through the stealth client");+ assert!(+ !rt.has_pending_render_resources(),+ "the load must finish through the stealth client"+ );assert!(rt.render_resource_is_known(&url));}#[cfg(feature = "render")]#[test]fn live_form_values_paint_without_mutating_content_attributes() {- let mut rt = setup_runtime("<!doctype html><html><body><input id=field value=initial><input id=box type=checkbox></body></html>");+ let mut rt = setup_runtime(+ "<!doctype html><html><body><input id=field value=initial><input id=box type=checkbox></body></html>",+ );rt.set_viewport(320.0, 120.0);- let before = rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap();- rt.evaluate("document.getElementById('field').value = 'changed'").unwrap();- let changed_value = rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap();+ let before = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();+ let prepared_address =+ rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize;+ rt.evaluate("document.getElementById('field').value = 'changed'")+ .unwrap();+ assert_eq!(+ rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,+ prepared_address,+ "live text values must not discard unchanged layout"+ );+ let changed_value = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();assert_ne!(before, changed_value, "live text value must affect pixels");- rt.evaluate("document.getElementById('box').checked = true").unwrap();- let after = rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap();+ rt.evaluate("document.getElementById('box').indeterminate = true")+ .unwrap();+ assert_eq!(+ rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,+ prepared_address,+ "indeterminate paint state must not discard unchanged layout"+ );+ let indeterminate = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();+ assert_ne!(+ changed_value, indeterminate,+ "indeterminate state must affect pixels"+ );+ rt.evaluate("document.getElementById('box').indeterminate = false")+ .unwrap();+ rt.evaluate("document.getElementById('box').checked = true")+ .unwrap();+ let after = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();assert_ne!(changed_value, after, "checked state must affect pixels");assert_eq!(rt.evaluate("[document.getElementById('field').value, document.getElementById('field').getAttribute('value'), document.getElementById('box').getAttribute('checked'), document.querySelectorAll(':checked').length]").unwrap(), serde_json::json!(["changed", "initial", null, 1]));rt.evaluate("(document.getElementById('field').value = 'initial', document.getElementById('box').checked = false)").unwrap();- assert_eq!(before, rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap());- rt.evaluate("document.getElementById('field').value = ''").unwrap();- assert_eq!(rt.evaluate("document.getElementById('field').value").unwrap(), serde_json::json!(""));- assert_ne!(before, rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap(), "empty current value must override a nonempty default");+ assert_eq!(+ before,+ rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap()+ );+ rt.evaluate("document.getElementById('field').value = ''")+ .unwrap();+ assert_eq!(+ rt.evaluate("document.getElementById('field').value")+ .unwrap(),+ serde_json::json!("")+ );+ assert_ne!(+ before,+ rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap(),+ "empty current value must override a nonempty default"+ );}#[test]fn cloned_controls_keep_current_value_and_checked_state() {- let mut rt = setup_runtime("<html><body><div id=group><input id=field value=default><input id=box type=checkbox></div></body></html>");+ let mut rt = setup_runtime(+ "<html><body><div id=group><input id=field value=default><input id=box type=checkbox></div></body></html>",+ );let result = rt.evaluate("(() => {const field=document.getElementById('field'), box=document.getElementById('box');field.value='current';box.checked=true;box.indeterminate=true;const clone=document.getElementById('group').cloneNode(true);return [clone.children[0].value,clone.children[0].getAttribute('value'),clone.children[1].checked,clone.children[1].indeterminate];})()").unwrap();- assert_eq!(result, serde_json::json!(["current", "default", true, false]));+ assert_eq!(+ result,+ serde_json::json!(["current", "default", true, false])+ );}#[cfg(feature = "render")]@@ -4561,15 +4627,26 @@ mod tests {"<html><body><form id=form><input id=field value=default><input id=box type=checkbox checked></form></body></html>",);rt.set_viewport(320.0, 120.0);- let before = rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap();+ let before = rt+ .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap();rt.evaluate("const field=document.getElementById('field'),box=document.getElementById('box');field.value='typed';box.checked=false;box.indeterminate=true").unwrap();- assert_ne!(before, rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap());- rt.evaluate("document.getElementById('form').reset()").unwrap();+ assert_ne!(+ before,+ rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap()+ );+ rt.evaluate("document.getElementById('form').reset()")+ .unwrap();assert_eq!(rt.evaluate("[field.value,field.getAttribute('value'),box.checked,box.indeterminate,box.hasAttribute('checked')]").unwrap(),serde_json::json!(["default", "default", true, false, true]));- assert_eq!(before, rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap());+ assert_eq!(+ before,+ rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))+ .unwrap()+ );}// SEC-503 / #820 — createObjectURL must reject non-Blob input (an object@@ -4849,9 +4926,7 @@ mod tests {// kept those declarations local to the compiled function, so they never// reached globalThis.let mut rt = setup_runtime("<html><body></body></html>");- rt.evaluate(- "setTimeout('var __leaked = 42; function __leakedFn(){ return 7; }', 0)",- )+ rt.evaluate("setTimeout('var __leaked = 42; function __leakedFn(){ return 7; }', 0)").unwrap();rt.run_event_loop_bounded(100).await.unwrap();let v = rt@@ -5901,7 +5976,9 @@ mod tests {#[test]fn clone_node_deep_copies_children_and_attributes() {- let mut rt = setup_runtime(r#"<html><body><ul id="l"><li class="a">one</li><li class="b">two</li></ul></body></html>"#);+ let mut rt = setup_runtime(+ r#"<html><body><ul id="l"><li class="a">one</li><li class="b">two</li></ul></body></html>"#,+ );let out = rt.evaluate("(function(){var c=document.getElementById('l').cloneNode(true); return c.children.length + '|' + c.children[0].className + '|' + c.children[1].textContent;})()",@@ -5927,7 +6004,9 @@ mod tests {#[test]fn clone_node_shallow_copies_attributes_without_children() {- let mut rt = setup_runtime(r#"<html><body><div id="d" data-x="7"><span>kid</span></div></body></html>"#);+ let mut rt = setup_runtime(+ r#"<html><body><div id="d" data-x="7"><span>kid</span></div></body></html>"#,+ );let out = rt.evaluate("(function(){var c=document.getElementById('d').cloneNode(false); return c.getAttribute('data-x') + '|' + c.childNodes.length;})()",@@ -5944,7 +6023,10 @@ mod tests {"(function(){var d=document.getElementById('d');d.style.color='red';d.style.fontSize='12px';var c=d.cloneNode(false);return c.style.color+'|'+c.style.fontSize+'|'+c.style.cssText;})()",).unwrap();- assert_eq!(out, serde_json::json!("red|12px|color: red; font-size: 12px;"));+ assert_eq!(+ out,+ serde_json::json!("red|12px|color: red; font-size: 12px;")+ );}#[test]@@ -5971,7 +6053,8 @@ mod tests {#[test]fn insert_adjacent_html_position_is_case_insensitive() {- let mut rt = setup_runtime(r#"<html><body><div id="host"><span>base</span></div></body></html>"#);+ let mut rt =+ setup_runtime(r#"<html><body><div id="host"><span>base</span></div></body></html>"#);let out = rt.evaluate("(function(){var h=document.getElementById('host'); h.insertAdjacentHTML('BeforeEnd','<b>x</b>'); return h.lastElementChild ? h.lastElementChild.tagName : 'NULL';})()").unwrap();@@ -6047,7 +6130,10 @@ mod tests {let v = rt.evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg');s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g');return s.getAttribute('xlink:href')+'|'+s.getAttributeNames()[0]+'|'+s.outerHTML;})()").unwrap();- assert_eq!(v, serde_json::json!("#g|xlink:href|<svg xlink:href=\"#g\"></svg>"));+ assert_eq!(+ v,+ serde_json::json!("#g|xlink:href|<svg xlink:href=\"#g\"></svg>")+ );}#[test]@@ -6085,9 +6171,7 @@ mod tests {.unwrap();assert_eq!(v,- serde_json::json!(- "NamespaceError|InvalidCharacterError|NamespaceError|NamespaceError"- )+ serde_json::json!("NamespaceError|InvalidCharacterError|NamespaceError|NamespaceError"));}@@ -6317,9 +6401,34 @@ mod tests {assert_eq!(result,serde_json::json!([- false, true, true, true, "undefined", 0, 1, 1,- "n1|n1|title|", "B", "#text,SPAN", "SPAN", 0, 0, "U", "SLOT", "P", "SPAN",- 0, "I,#text", "I", 0, "U", false, false, "undefined", "B", "B"+ false,+ true,+ true,+ true,+ "undefined",+ 0,+ 1,+ 1,+ "n1|n1|title|",+ "B",+ "#text,SPAN",+ "SPAN",+ 0,+ 0,+ "U",+ "SLOT",+ "P",+ "SPAN",+ 0,+ "I,#text",+ "I",+ 0,+ "U",+ false,+ false,+ "undefined",+ "B",+ "B"]));}@@ -6429,7 +6538,9 @@ mod tests {assert_eq!(result,serde_json::json!([- [true, true, true, true, true, true, true, true, true, true, true, "rendered"],+ [+ true, true, true, true, true, true, true, true, true, true, true, "rendered"+ ],[true, true, true],[true, true, true],[true, true, "inside", true, true, true],@@ -6780,8 +6891,17 @@ mod tests {assert_eq!(result,serde_json::json!([- "undefined", "", "anull", "teXst", "te", "teyo", "s",- "IndexSizeError", "TypeError", "IndexSizeError", "HierarchyRequestError"+ "undefined",+ "",+ "anull",+ "teXst",+ "te",+ "teyo",+ "s",+ "IndexSizeError",+ "TypeError",+ "IndexSizeError",+ "HierarchyRequestError"]));}@@ -6913,15 +7033,7 @@ mod tests {.unwrap();assert_eq!(result,- serde_json::json!([- true,- "{\"ready\":true}",- true,- 2,- true,- true,- "undefined"- ])+ serde_json::json!([true, "{\"ready\":true}", true, 2, true, true, "undefined"]));}@@ -6989,8 +7101,7 @@ mod tests {assert_eq!(result,serde_json::json!([- true, true, true, true, true, true, true, true, true, true, true, true,- true+ true, true, true, true, true, true, true, true, true, true, true, true, true]));}@@ -7079,7 +7190,9 @@ mod tests {.unwrap();assert_eq!(result,- serde_json::json!([true, false, true, true, false, true, true, false, true, false])+ serde_json::json!([+ true, false, true, true, false, true, true, false, true, false+ ]));}@@ -7539,7 +7652,9 @@ mod tests {"#,).unwrap(),- serde_json::json!(["17px", "17px", 1, "17px", "17px", "1.25", "17px", "1.25", true])+ serde_json::json!([+ "17px", "17px", 1, "17px", "17px", "1.25", "17px", "1.25", true+ ]));assert_eq!(@@ -7680,7 +7795,10 @@ mod tests {ticks, 6.0,"V8 maintenance wakes must not starve the repeating timer",);- rt.execute_script("clear-zero-interval", "clearInterval(globalThis.__zeroInterval)")+ rt.execute_script(+ "clear-zero-interval",+ "clearInterval(globalThis.__zeroInterval)",+ ).unwrap();}@@ -7722,7 +7840,10 @@ mod tests {delays[5].as_f64().unwrap() >= 2.0,"a timer nested from the sixth interval task must receive the four-millisecond clamp: {delays:?}",);- rt.execute_script("clear-top-interval", "clearInterval(globalThis.__topInterval)")+ rt.execute_script(+ "clear-top-interval",+ "clearInterval(globalThis.__topInterval)",+ ).unwrap();}@@ -7745,7 +7866,8 @@ mod tests {.unwrap();for _ in 0..8 {- if rt.evaluate("globalThis.__deepInterval !== undefined")+ if rt+ .evaluate("globalThis.__deepInterval !== undefined").unwrap()== serde_json::json!(true){@@ -7843,9 +7965,7 @@ mod tests {.unwrap();let started = std::time::Instant::now();- rt.run_event_loop_until_quiescent(2_000, 150)- .await- .unwrap();+ rt.run_event_loop_until_quiescent(2_000, 150).await.unwrap();let elapsed = started.elapsed();assert!(@@ -7871,17 +7991,12 @@ mod tests {.unwrap();let started = std::time::Instant::now();- rt.run_event_loop_until_quiescent(2_000, 150)- .await- .unwrap();+ rt.run_event_loop_until_quiescent(2_000, 150).await.unwrap();let elapsed = started.elapsed();assert!(elapsed >= std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS)- && elapsed- < std::time::Duration::from_millis(- SYNCHRONOUS_TASK_FLOOR_MS + 1_500,- ),+ && elapsed < std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS + 1_500,),"one synchronous callback drain escaped the bounded task allowance: {elapsed:?}");assert_eq!(@@ -7976,8 +8091,7 @@ mod tests {#[tokio::test(flavor = "current_thread")]async fn quiescent_event_loop_allows_fetch_hydration_within_network_grace() {- let (mut rt, accepted) =- delayed_fetch_runtime(std::time::Duration::from_millis(700));+ let (mut rt, accepted) = delayed_fetch_runtime(std::time::Duration::from_millis(700));rt.execute_script("quiescent-fetch-hydration","fetch('/hydrate').then(response => response.text()).then(text => {\@@ -7987,9 +8101,7 @@ mod tests {.unwrap();let started = std::time::Instant::now();- rt.run_event_loop_until_quiescent(3_000, 150)- .await- .unwrap();+ rt.run_event_loop_until_quiescent(3_000, 150).await.unwrap();let elapsed = started.elapsed();accepted@@ -8020,9 +8132,7 @@ mod tests {.unwrap();let started = std::time::Instant::now();- rt.run_event_loop_until_quiescent(4_000, 150)- .await- .unwrap();+ rt.run_event_loop_until_quiescent(4_000, 150).await.unwrap();let elapsed = started.elapsed();accepted@@ -8053,9 +8163,7 @@ mod tests {.unwrap();let started = std::time::Instant::now();- rt.run_event_loop_until_quiescent(4_000, 150)- .await- .unwrap();+ rt.run_event_loop_until_quiescent(4_000, 150).await.unwrap();let elapsed = started.elapsed();assert_eq!(@@ -8552,7 +8660,9 @@ mod tests {.unwrap();assert_eq!(result,- serde_json::json!("[false,false,false,false,false,true,true,true,false,false,false,true,false,true,true,false,false,true,false,true,false,true,false,true,true,true,false,false,true]")+ serde_json::json!(+ "[false,false,false,false,false,true,true,true,false,false,false,true,false,true,true,false,false,true,false,true,false,true,false,true,true,true,false,false,true]"+ ));}@@ -9408,9 +9518,11 @@ mod tests {assert_eq!(values[7], values[11]);assert_eq!(values[8], values[10]);assert_eq!(values[9], values[11]);- assert!(values[12..]+ assert!(+ values[12..].iter()- .all(|value| value == &serde_json::json!(true)));+ .all(|value| value == &serde_json::json!(true))+ );}#[cfg(feature = "render")]@@ -10321,10 +10433,12 @@ mod tests {Some(br#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"/>"#.to_vec()),);let state = rt.state.borrow();- let prepared = state.prepared_render.as_ref().expect("retained style graph");+ let prepared = state+ .prepared_render+ .as_ref()+ .expect("retained style graph");assert_eq!(- prepared as *const obscura_render::PreparedRender as usize,- prepared_address,+ prepared as *const obscura_render::PreparedRender as usize, prepared_address,"resource arrival waits for the next geometry flush");assert_eq!(@@ -10364,8 +10478,8 @@ mod tests {state.prepared_render.as_ref()- .expect("initial prepared render") as *const obscura_render::PreparedRender- as usize+ .expect("initial prepared render")+ as *const obscura_render::PreparedRender as usize};// Preserve already queued framework damage and coalesce repeated@@ -10397,14 +10511,22 @@ mod tests {state.pending_style_mutations.iter()- .filter(|mutation| matches!(mutation, obscura_render::RetainedStyleMutation::Resource))+ .filter(|mutation| matches!(+ mutation,+ obscura_render::RetainedStyleMutation::Resource+ )).count(),1,);- assert!(state.pending_style_mutations.iter().any(|mutation| matches!(+ assert!(+ state+ .pending_style_mutations+ .iter()+ .any(|mutation| matches!(mutation,obscura_render::RetainedStyleMutation::Attribute(_)- )));+ ))+ );}let after = rt@@ -10892,23 +11014,52 @@ mod tests {__animation.currentTime = 50;"#,).unwrap();- assert_eq!(rt.evaluate("box.style.opacity").unwrap(), serde_json::json!(".2"));- assert_eq!(rt.evaluate("box.getAnimations()[0] === __animation").unwrap(), serde_json::json!(true));- assert_eq!(rt.evaluate("document.getAnimations()[0] === __animation").unwrap(), serde_json::json!(true));- assert_eq!(rt.evaluate("__animation.playState").unwrap(), serde_json::json!("paused"));+ assert_eq!(+ rt.evaluate("box.style.opacity").unwrap(),+ serde_json::json!(".2")+ );+ assert_eq!(+ rt.evaluate("box.getAnimations()[0] === __animation")+ .unwrap(),+ serde_json::json!(true)+ );+ assert_eq!(+ rt.evaluate("document.getAnimations()[0] === __animation")+ .unwrap(),+ serde_json::json!(true)+ );+ assert_eq!(+ rt.evaluate("__animation.playState").unwrap(),+ serde_json::json!("paused")+ );assert_eq!(rt.evaluate("!('easingBezier' in __animation.effect.getTiming()) && !('linearEasing' in __animation.effect.getComputedTiming())").unwrap(),serde_json::json!(true),);let opacity = rt.evaluate("getComputedStyle(box).opacity").unwrap();let opacity = opacity.as_str().unwrap().parse::<f32>().unwrap();- assert!((opacity - 0.6).abs() < 0.001, "midpoint opacity was {opacity}");+ assert!(+ (opacity - 0.6).abs() < 0.001,+ "midpoint opacity was {opacity}"+ );rt.execute_script("cancel", "__animation.cancel()").unwrap();- assert_eq!(rt.evaluate("box.style.opacity").unwrap(), serde_json::json!(".2"));- assert_eq!(rt.evaluate("getComputedStyle(box).opacity").unwrap(), serde_json::json!("0.2"));- assert_eq!(rt.evaluate("box.getAnimations().length").unwrap(), serde_json::json!(0.0));- assert_eq!(rt.evaluate("document.getAnimations().length").unwrap(), serde_json::json!(0.0));+ assert_eq!(+ rt.evaluate("box.style.opacity").unwrap(),+ serde_json::json!(".2")+ );+ assert_eq!(+ rt.evaluate("getComputedStyle(box).opacity").unwrap(),+ serde_json::json!("0.2")+ );+ assert_eq!(+ rt.evaluate("box.getAnimations().length").unwrap(),+ serde_json::json!(0.0)+ );+ assert_eq!(+ rt.evaluate("document.getAnimations().length").unwrap(),+ serde_json::json!(0.0)+ );}#[cfg(feature = "render")]@@ -10931,9 +11082,18 @@ mod tests {rt.run_event_loop_bounded(20).await.unwrap();assert_eq!(rt.evaluate("__ready").unwrap(), serde_json::json!(true));assert_eq!(rt.evaluate("__finished").unwrap(), serde_json::json!(true));- assert_eq!(rt.evaluate("__finishEvent").unwrap(), serde_json::json!(true));- assert_eq!(rt.evaluate("__animation.playState").unwrap(), serde_json::json!("finished"));- assert_eq!(rt.evaluate("getComputedStyle(box).opacity").unwrap(), serde_json::json!("1"));+ assert_eq!(+ rt.evaluate("__finishEvent").unwrap(),+ serde_json::json!(true)+ );+ assert_eq!(+ rt.evaluate("__animation.playState").unwrap(),+ serde_json::json!("finished")+ );+ assert_eq!(+ rt.evaluate("getComputedStyle(box).opacity").unwrap(),+ serde_json::json!("1")+ );}#[cfg(feature = "render")]@@ -10978,9 +11138,11 @@ mod tests {rt.set_viewport(80.0, 60.0);rt.run_page_init();- assert!(rt.set_animation_sample_time(obscura_render::AnimationSampleTime {+ assert!(+ rt.set_animation_sample_time(obscura_render::AnimationSampleTime {milliseconds: 100.0,- }));+ })+ );let first = rt.screenshot_prepared((80.0, 60.0), Some("http://example.test/page")).expect("first static frame");@@ -10989,9 +11151,11 @@ mod tests {state.prepared_render.as_ref().unwrap() as *const _ as usize};- assert!(rt.set_animation_sample_time(obscura_render::AnimationSampleTime {+ assert!(+ rt.set_animation_sample_time(obscura_render::AnimationSampleTime {milliseconds: 250.0,- }));+ })+ );let second = rt.screenshot_prepared((80.0, 60.0), Some("http://example.test/page")).expect("second static frame");@@ -11086,9 +11250,7 @@ mod tests {);assert_eq!(state.pending_style_mutations,- vec![obscura_render::RetainedStyleMutation::WaapiAnimation {- node: box_node- }]+ vec![obscura_render::RetainedStyleMutation::WaapiAnimation { node: box_node }]);}let initial = rt@@ -11140,7 +11302,10 @@ mod tests {.unwrap().as_f64().unwrap();- assert!(animated_opacity > 0.9, "animated opacity={animated_opacity}");+ assert!(+ animated_opacity > 0.9,+ "animated opacity={animated_opacity}"+ );rt.evaluate("__cancelAnimation.cancel()").unwrap();assert!(@@ -11169,9 +11334,11 @@ mod tests {rt.set_viewport(80.0, 60.0);rt.run_page_init();- assert!(rt.set_animation_sample_time(obscura_render::AnimationSampleTime {+ assert!(+ rt.set_animation_sample_time(obscura_render::AnimationSampleTime {milliseconds: 150.0,- }));+ })+ );let completed = rt.screenshot_prepared((80.0, 60.0), Some("http://example.test/page")).expect("completed animation frame");@@ -11181,26 +11348,24 @@ mod tests {state.prepared_render.as_ref().unwrap() as *const _ as usize};- assert!(rt.set_animation_sample_time(obscura_render::AnimationSampleTime {+ assert!(+ rt.set_animation_sample_time(obscura_render::AnimationSampleTime {milliseconds: 300.0,- }));+ })+ );let later = rt.screenshot_prepared((80.0, 60.0), Some("http://example.test/page")).expect("later completed frame");assert_eq!(completed, later);assert_eq!(- rt.state- .borrow()- .prepared_render- .as_ref()- .unwrap() as *const _ as usize,+ rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,prepared_address,"a finite fill-forwards animation must not relayout after completion");- assert!(rt.set_animation_sample_time(obscura_render::AnimationSampleTime {- milliseconds: 0.0,- }));+ assert!(+ rt.set_animation_sample_time(obscura_render::AnimationSampleTime { milliseconds: 0.0 })+ );assert!(rt.state.borrow().prepared_render.is_none(),"backward timeline seeks must invalidate the completed frame"@@ -11243,9 +11408,11 @@ mod tests {let state = rt.state.borrow();state.prepared_render.as_ref().unwrap() as *const _ as usize};- assert!(rt.set_animation_sample_time(obscura_render::AnimationSampleTime {+ assert!(+ rt.set_animation_sample_time(obscura_render::AnimationSampleTime {milliseconds: 5_000.0,- }));+ })+ );let later = rt.screenshot_prepared((80.0, 60.0), Some("http://example.test/page")).expect("later frame");@@ -11295,13 +11462,18 @@ mod tests {rt.state.borrow_mut().animation_timeline_origin =std::time::Instant::now() - std::time::Duration::from_millis(1_000);- rt.evaluate("var box=document.getElementById('box');box.remove();document.body.appendChild(box)")+ rt.evaluate(+ "var box=document.getElementById('box');box.remove();document.body.appendChild(box)",+ ).unwrap();assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(1_100.0)));rt.screenshot_prepared((200.0, 80.0), Some("http://example.test/page")).unwrap();let restarted = animation_test_width(&rt, "box");- assert!((5.0..20.0).contains(&restarted), "restarted width={restarted}");+ assert!(+ (5.0..20.0).contains(&restarted),+ "restarted width={restarted}"+ );}#[cfg(feature = "render")]@@ -11417,7 +11589,10 @@ mod tests {let direct_rt = make_runtime();assert!(direct_rt.set_animation_sample(fixed));let direct = direct_rt- .screenshot_prepared((160.0, 100.0), Some("http://example.test/github-like-shell"))+ .screenshot_prepared(+ (160.0, 100.0),+ Some("http://example.test/github-like-shell"),+ ).expect("direct fixed-time capture");let mut geometry_rt = make_runtime();@@ -11427,7 +11602,10 @@ mod tests {assert_eq!(rect["width"].as_f64(), Some(120.0));assert!(geometry_rt.set_animation_sample(fixed));let after_geometry = geometry_rt- .screenshot_prepared((160.0, 100.0), Some("http://example.test/github-like-shell"))+ .screenshot_prepared(+ (160.0, 100.0),+ Some("http://example.test/github-like-shell"),+ ).expect("fixed-time capture after geometry");assert_eq!(@@ -11558,9 +11736,7 @@ mod tests {);assert!(rt.state.borrow().prepared_render.is_some());- rt.evaluate(- "document.getElementById('box').setAttributeNS(null, 'class', 'box')",- )+ rt.evaluate("document.getElementById('box').setAttributeNS(null, 'class', 'box')").unwrap();assert!(rt.state.borrow().prepared_render.is_some(),@@ -11956,9 +12132,7 @@ mod tests {.unwrap();rt.run_event_loop_bounded(40).await.unwrap();assert_eq!(- rt.evaluate(- "__resizeRecords.map(record => [record.content[0], record.border[0]])"- )+ rt.evaluate("__resizeRecords.map(record => [record.content[0], record.border[0]])").unwrap(),serde_json::json!([[102, 120], [122, 140]]));@@ -12283,7 +12457,8 @@ mod tests {.unwrap();rt.run_event_loop_bounded(40).await.unwrap();assert_eq!(- rt.evaluate("[__resizeCallbacks, __resizeLoopErrors]").unwrap(),+ rt.evaluate("[__resizeCallbacks, __resizeLoopErrors]")+ .unwrap(),serde_json::json!([2, 2]));}@@ -12469,11 +12644,7 @@ mod tests {rt.run_event_loop_bounded(100).await.unwrap();assert_eq!(rt.evaluate("__intersectionDeliveryOrder").unwrap(),- serde_json::json!([- "first-observer",- "second-observer",- "callback-posted-task",- ])+ serde_json::json!(["first-observer", "second-observer", "callback-posted-task",]));}@@ -12637,10 +12808,7 @@ mod tests {// clips it. Programmatic scrolling then reveals the complete box.assert_eq!(result.value.unwrap(),- serde_json::json!([- [false, 0, [0, 0, 0, 0]],- [true, 1, [10, 100, 100, 20]],- ])+ serde_json::json!([[false, 0, [0, 0, 0, 0]], [true, 1, [10, 100, 100, 20]],]));}@@ -13532,8 +13700,16 @@ mod tests {result,serde_json::json!([[true, 0, true, true, 1, 2],- ["\"a;b\"", "url(\"data:image/svg+xml;utf8,<svg/>\")"], true,- 73, 91, "91px", 11, 64, 2, "#box", true+ ["\"a;b\"", "url(\"data:image/svg+xml;utf8,<svg/>\")"],+ true,+ 73,+ 91,+ "91px",+ 11,+ 64,+ 2,+ "#box",+ true]));}@@ -13573,8 +13749,15 @@ mod tests {assert_eq!(result,serde_json::json!([- 1, 1, true,- ["\"a;b\"", "url(\"data:image/svg+xml;utf8,<svg/>\")", true, true],+ 1,+ 1,+ true,+ [+ "\"a;b\"",+ "url(\"data:image/svg+xml;utf8,<svg/>\")",+ true,+ true+ ],""]));@@ -13902,7 +14085,10 @@ mod tests {green_half.alpha());let clipped = pixmap.pixel(23, 8).expect("outside overflow clip");- assert_eq!((clipped.red(), clipped.green(), clipped.blue()), (0, 0, 255));+ assert_eq!(+ (clipped.red(), clipped.green(), clipped.blue()),+ (0, 0, 255)+ );let blank = pixmap.pixel(34, 8).expect("transparent blank canvas");assert_eq!((blank.red(), blank.green(), blank.blue()), (0, 0, 255));let overlay = pixmap.pixel(11, 8).expect("higher z-index overlay");@@ -13917,12 +14103,9 @@ mod tests {);let padded_content = pixmap.pixel(36, 23).expect("padded canvas content pixel");assert!(- padded_content.red() > 220- && padded_content.green() < 40- && padded_content.blue() < 40,+ padded_content.red() > 220 && padded_content.green() < 40 && padded_content.blue() < 40,"canvas bitmap must start at the CSS content-box origin");-}#[test]@@ -14224,10 +14407,12 @@ mod tests {assert_eq!(value["labels"], serde_json::json!(["Greek", "English"]));assert_eq!(value["selectedIndex"], 1);assert_eq!(value["value"], "en");- assert!(value["html"]+ assert!(+ value["html"].as_str().unwrap()- .contains(r#"<option value="en" selected="">English</option>"#));+ .contains(r#"<option value="en" selected="">English</option>"#)+ );}/// Regression for #105: `element.querySelector` and `querySelectorAll`@@ -14486,7 +14671,9 @@ mod tests {let base = format!("http://{address}");let mut rt = ObscuraJsRuntime::new();- rt.set_dom(parse_html(&format!(r#"<img id="image" src="{base}/plain.png">"#)));+ rt.set_dom(parse_html(&format!(+ r#"<img id="image" src="{base}/plain.png">"#+ )));// Deliberately make the image cross-origin from the document.rt.set_url("http://127.0.0.1:1/page.html");rt.set_http_client(std::sync::Arc::new(@@ -14515,7 +14702,10 @@ mod tests {serde_json::json!([true, 2, ["load"]]));- rt.execute_script("require-anonymous-cors", r#"image.crossOrigin = "anonymous";"#)+ rt.execute_script(+ "require-anonymous-cors",+ r#"image.crossOrigin = "anonymous";"#,+ ).unwrap();rt.run_event_loop_bounded(100).await.unwrap();assert_eq!(@@ -14859,20 +15049,16 @@ mod tests {let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));let loader_calls = calls.clone();let png = two_by_three_png();- let mut rt = parser_image_runtime(- r#"<img id="late" src="late.png">"#,- move |_url: &str| {+ let mut rt =+ parser_image_runtime(r#"<img id="late" src="late.png">"#, move |_url: &str| {loader_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);Some(png.clone())- },- );+ });{let mut state = rt.state.borrow_mut();let previous = state.render_resources.set_sync_loading_enabled(false);assert!(ensure_prepared_render(&mut state).is_some());- state- .render_resources- .set_sync_loading_enabled(previous);+ state.render_resources.set_sync_loading_enabled(previous);assert!(state.prepared_render.is_some());}assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);@@ -14888,9 +15074,7 @@ mod tests {.unwrap();rt.run_event_loop_bounded(100).await.unwrap();assert_eq!(- rt.evaluate(- "[late.complete, late.naturalWidth, late.naturalHeight, __lateEvents]"- )+ rt.evaluate("[late.complete, late.naturalWidth, late.naturalHeight, __lateEvents]").unwrap(),serde_json::json!([true, 2, 3, ["load"]]));@@ -14911,10 +15095,7 @@ mod tests {assert!(ensure_prepared_render(&mut state).is_some());assert!(state.prepared_render.is_some());}- rt.execute_script(- "reload-retained-image",- r#"late.src = "late.png";"#,- )+ rt.execute_script("reload-retained-image", r#"late.src = "late.png";"#).unwrap();rt.run_event_loop_bounded(100).await.unwrap();assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);@@ -14933,9 +15114,7 @@ mod tests {let mut state = missing.state.borrow_mut();let previous = state.render_resources.set_sync_loading_enabled(false);assert!(ensure_prepared_render(&mut state).is_some());- state- .render_resources- .set_sync_loading_enabled(previous);+ state.render_resources.set_sync_loading_enabled(previous);assert!(state.prepared_render.is_some());}missing@@ -14957,10 +15136,7 @@ mod tests {.unwrap(),serde_json::json!([true, 0, 0, ["error"]]));- assert_eq!(- missing_calls.load(std::sync::atomic::Ordering::SeqCst),- 1- );+ assert_eq!(missing_calls.load(std::sync::atomic::Ordering::SeqCst), 1);assert!(missing.state.borrow().prepared_render.is_some());}@@ -15001,9 +15177,7 @@ mod tests {.unwrap();rt.run_event_loop_bounded(100).await.unwrap();assert_eq!(- rt.evaluate(- "[__stableGetterResizeRecords, __obscura_nextPendingTimeoutDelay()]"- )+ rt.evaluate("[__stableGetterResizeRecords, __obscura_nextPendingTimeoutDelay()]").unwrap(),serde_json::json!([1, -1]));@@ -15023,9 +15197,7 @@ mod tests {// Cached lifecycle reads do not change intrinsic dimensions, so they// must not enqueue a rendering checkpoint (and its geometry walk).assert_eq!(- rt.evaluate(- "[__stableGetterResizeRecords, __obscura_nextPendingTimeoutDelay()]"- )+ rt.evaluate("[__stableGetterResizeRecords, __obscura_nextPendingTimeoutDelay()]").unwrap(),serde_json::json!([1, -1]));@@ -16053,7 +16225,13 @@ mod tests {// the object id a success uses and nothing said which branch ran.let mut rt = setup_runtime("<html><body></body></html>");let info = rt- .call_function_on_for_cdp("() => Promise.reject(new Error('boom'))", None, &[], true, true)+ .call_function_on_for_cdp(+ "() => Promise.reject(new Error('boom'))",+ None,+ &[],+ true,+ true,+ ).await.expect("a rejection is answered, not failed");assert!(info.thrown, "expected a thrown value, got {:?}", info.value);@@ -16090,7 +16268,10 @@ mod tests {.evaluate_for_cdp("undefined_variable_xyz", false, false).await.expect("a page error is not a protocol failure");- assert!(info.thrown, "a ReferenceError must come back flagged thrown");+ assert!(+ info.thrown,+ "a ReferenceError must come back flagged thrown"+ );assert_eq!(info.subtype.as_deref(), Some("error"));assert!(info.description.contains("ReferenceError"),@@ -16169,7 +16350,11 @@ mod tests {);let info = rt- .evaluate_for_cdp("(() => 8)()\n//# sourceURL=__puppeteer_evaluation_script__", true, false)+ .evaluate_for_cdp(+ "(() => 8)()\n//# sourceURL=__puppeteer_evaluation_script__",+ true,+ false,+ ).await.expect("a trailing sourceURL comment is legal");assert_eq!(@@ -16185,7 +16370,13 @@ mod tests {// call on the same runtime as thrown.let mut rt = setup_runtime("<html><body></body></html>");let rejected = rt- .call_function_on_for_cdp("() => Promise.reject(new Error('first'))", None, &[], true, true)+ .call_function_on_for_cdp(+ "() => Promise.reject(new Error('first'))",+ None,+ &[],+ true,+ true,+ ).await.unwrap();assert!(rejected.thrown);@@ -16640,7 +16831,8 @@ mod tests {// Start navigating to the victim origin. This only *queues* the// navigation; it must not retroactively move the cookie context.- rt.evaluate("location.href = 'https://victim.example/'").unwrap();+ rt.evaluate("location.href = 'https://victim.example/'")+ .unwrap();let result = rt.evaluate("document.cookie").unwrap();let cookie_str = result.as_str().unwrap();@@ -16656,12 +16848,13 @@ mod tests {let (mut rt, jar) = setup_runtime_with_cookies("<html><body></body></html>");let url = url::Url::parse("http://example.com/test").unwrap();rt.evaluate("document.cookie = 'temp=val; Path=/'").unwrap();- assert!(rt- .evaluate("document.cookie")+ assert!(+ rt.evaluate("document.cookie").unwrap().as_str().unwrap()- .contains("temp=val"));+ .contains("temp=val")+ );rt.evaluate("document.cookie = 'temp=; Max-Age=0'").unwrap();let result = rt.evaluate("document.cookie").unwrap();assert!(@@ -16919,9 +17112,7 @@ mod tests {<a id="link" href="x.json"></a></body></html>"#,);- let link = rt- .evaluate("document.getElementById('link').href")- .unwrap();+ let link = rt.evaluate("document.getElementById('link').href").unwrap();assert_eq!(link.as_str().unwrap(), "http://example.com/a/x.json");}@@ -16932,9 +17123,7 @@ mod tests {<a id="link" href="x.json"></a></body></html>"#,);- let link = rt- .evaluate("document.getElementById('link').href")- .unwrap();+ let link = rt.evaluate("document.getElementById('link').href").unwrap();assert_eq!(link.as_str().unwrap(), "http://example.com/deep/x.json");}@@ -16970,10 +17159,11 @@ mod tests {let base_uri = rt.evaluate("document.baseURI").unwrap();assert_eq!(base_uri.as_str().unwrap(), "http://example.com/deep/page");- let link = rt- .evaluate("document.getElementById('link').href")- .unwrap();- assert_eq!(link.as_str().unwrap(), "http://example.com/deep/data/x.json");+ let link = rt.evaluate("document.getElementById('link').href").unwrap();+ assert_eq!(+ link.as_str().unwrap(),+ "http://example.com/deep/data/x.json"+ );}#[test]@@ -16982,11 +17172,10 @@ mod tests {let mut rt = setup_runtime_at_deep_url(r#"<html><head></head><body><a id="link" href="x.json"></a></body></html>"#,);- rt.evaluate("history.pushState({}, '', '/other/route')").unwrap();-- let link = rt- .evaluate("document.getElementById('link').href")+ rt.evaluate("history.pushState({}, '', '/other/route')").unwrap();++ let link = rt.evaluate("document.getElementById('link').href").unwrap();assert_eq!(link.as_str().unwrap(), "http://example.com/other/x.json");}@@ -16997,12 +17186,14 @@ mod tests {<a id="link" href="x.json"></a></body></html>"#,);- rt.evaluate("history.pushState({}, '', '/other/route')").unwrap();-- let link = rt- .evaluate("document.getElementById('link').href")+ rt.evaluate("history.pushState({}, '', '/other/route')").unwrap();- assert_eq!(link.as_str().unwrap(), "http://example.com/other/assets/x.json");++ let link = rt.evaluate("document.getElementById('link').href").unwrap();+ assert_eq!(+ link.as_str().unwrap(),+ "http://example.com/other/assets/x.json"+ );}/// Guards the cache in `document_base_url_memoized`. Without it, each of these reads walked@@ -17039,9 +17230,7 @@ mod tests {let mut rt = setup_runtime_at_deep_url(r#"<html><head></head><body><a id="link" href="x.json"></a></body></html>"#,);- let before = rt- .evaluate("document.getElementById('link').href")- .unwrap();+ let before = rt.evaluate("document.getElementById('link').href").unwrap();assert_eq!(before.as_str().unwrap(), "http://example.com/deep/x.json");rt.evaluate(@@ -17053,27 +17242,27 @@ mod tests {).unwrap();- let after = rt- .evaluate("document.getElementById('link').href")- .unwrap();+ let after = rt.evaluate("document.getElementById('link').href").unwrap();assert_eq!(after.as_str().unwrap(), "http://example.com/x.json");}#[test]fn the_base_memo_notices_a_changed_href_attribute() {let mut rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);- let before = rt- .evaluate("document.getElementById('link').href")- .unwrap();- assert_eq!(before.as_str().unwrap(), "http://example.com/app/data/x.json");+ let before = rt.evaluate("document.getElementById('link').href").unwrap();+ assert_eq!(+ before.as_str().unwrap(),+ "http://example.com/app/data/x.json"+ );rt.evaluate("document.querySelector('base').setAttribute('href', '/other/')").unwrap();- let after = rt- .evaluate("document.getElementById('link').href")- .unwrap();- assert_eq!(after.as_str().unwrap(), "http://example.com/other/data/x.json");+ let after = rt.evaluate("document.getElementById('link').href").unwrap();+ assert_eq!(+ after.as_str().unwrap(),+ "http://example.com/other/data/x.json"+ );}#[tokio::test(flavor = "current_thread")]@@ -17113,8 +17302,14 @@ mod tests {// to fetch, so fetch takes over the resolution if it is removed from send, and the assert// still holds. It pins the result, not the layer.assert_eq!(seen.len(), 2, "one fetch, one XHR");- assert_eq!(seen[0].as_str().unwrap(), "http://example.com/app/data/x.json");- assert_eq!(seen[1].as_str().unwrap(), "http://example.com/app/data/y.json");+ assert_eq!(+ seen[0].as_str().unwrap(),+ "http://example.com/app/data/x.json"+ );+ assert_eq!(+ seen[1].as_str().unwrap(),+ "http://example.com/app/data/y.json"+ );}#[tokio::test(flavor = "current_thread")]@@ -17270,11 +17465,7 @@ mod tests {);}- fn cors_preflight_runtime() -> (- ObscuraJsRuntime,- String,- std::sync::mpsc::Receiver<String>,- ) {+ fn cors_preflight_runtime() -> (ObscuraJsRuntime, String, std::sync::mpsc::Receiver<String>) {let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();let address = listener.local_addr().unwrap();let target = format!("http://{address}/resource");@@ -17662,7 +17853,8 @@ mod tests {"HTTP/1.1 {status} Redirect\r\nLocation: /final\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")} else {- "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_string()+ "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"+ .to_string()};let _ = stream.write_all(response.as_bytes());}@@ -17682,9 +17874,8 @@ mod tests {let (mut stream, _) = target.accept().unwrap();let mut buffer = [0u8; 1024];let _ = stream.read(&mut buffer);- let _ = stream.write_all(- b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",- );+ let _ = stream+ .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok");});let source = std::net::TcpListener::bind("127.0.0.1:0").unwrap();@@ -17821,7 +18012,10 @@ mod tests {let value = result.value.unwrap();assert!(- value["url"].as_str().unwrap_or_default().ends_with("/hop/0"),+ value["url"]+ .as_str()+ .unwrap_or_default()+ .ends_with("/hop/0"),"Response.url did not report the final URL: {value}");assert_eq!(value["redirected"], true);@@ -17841,11 +18035,9 @@ mod tests {#[tokio::test(flavor = "current_thread")]async fn stealth_fetch_response_reports_the_final_redirect_url() {let mut rt = redirect_chain_runtime(2);- rt.set_stealth_client(std::sync::Arc::new(- obscura_net::StealthHttpClient::new(std::sync::Arc::new(- obscura_net::CookieJar::new(),- )),- ));+ rt.set_stealth_client(std::sync::Arc::new(obscura_net::StealthHttpClient::new(+ std::sync::Arc::new(obscura_net::CookieJar::new()),+ )));let result = rt.call_function_on_for_cdp(r#"async () => {@@ -17861,7 +18053,12 @@ mod tests {.unwrap();let value = result.value.unwrap();- assert!(value["url"].as_str().unwrap_or_default().ends_with("/hop/0"));+ assert!(+ value["url"]+ .as_str()+ .unwrap_or_default()+ .ends_with("/hop/0")+ );assert_eq!(value["redirected"], true);}@@ -17932,7 +18129,12 @@ mod tests {.await.unwrap();let value = result.value.unwrap();- assert!(value["url"].as_str().unwrap_or_default().ends_with("/final"));+ assert!(+ value["url"]+ .as_str()+ .unwrap_or_default()+ .ends_with("/final")+ );assert_eq!(value["redirected"], true);assert_eq!(*request_callbacks.lock().unwrap(),@@ -17984,7 +18186,12 @@ mod tests {.unwrap();let value = result.value.unwrap();assert_eq!(value["type"], "basic");- assert!(value["url"].as_str().unwrap_or_default().ends_with("/hop/0"));+ assert!(+ value["url"]+ .as_str()+ .unwrap_or_default()+ .ends_with("/hop/0")+ );assert_eq!(value["redirected"], true);}@@ -18030,11 +18237,9 @@ mod tests {#[tokio::test(flavor = "current_thread")]async fn stealth_cross_origin_no_cors_filters_response_identity() {let mut rt = cross_origin_redirect_runtime();- rt.set_stealth_client(std::sync::Arc::new(- obscura_net::StealthHttpClient::new(std::sync::Arc::new(- obscura_net::CookieJar::new(),- )),- ));+ rt.set_stealth_client(std::sync::Arc::new(obscura_net::StealthHttpClient::new(+ std::sync::Arc::new(obscura_net::CookieJar::new()),+ )));let result = rt.call_function_on_for_cdp(r#"async () => {@@ -18865,9 +19070,7 @@ mod tests {.and_then(|line| line.split_ascii_whitespace().nth(1)).unwrap_or("/");let body = match path {- "/entry.js" => {- "import './shared.js'; globalThis.__module_entry_ran = true;"- }+ "/entry.js" => "import './shared.js'; globalThis.__module_entry_ran = true;","/shared.js" => {"globalThis.__shared_module_runs = \(globalThis.__shared_module_runs || 0) + 1;"@@ -19086,7 +19289,8 @@ mod tests {rt.evaluate_prepared_module(shared, 1_000).await.unwrap();assert_eq!(- rt.evaluate("globalThis.__module_entry_ran === true").unwrap(),+ rt.evaluate("globalThis.__module_entry_ran === true")+ .unwrap(),serde_json::json!(true),);assert_eq!(@@ -19112,7 +19316,8 @@ mod tests {"unexpected heap failure: {error}",);assert_eq!(- rt.evaluate("globalThis.__runtime_survived_oom = true").unwrap(),+ rt.evaluate("globalThis.__runtime_survived_oom = true")+ .unwrap(),serde_json::json!(true),);}@@ -19165,9 +19370,11 @@ mod tests {.unwrap()}).collect::<Vec<_>>();- assert!(requests+ assert!(+ requests.iter()- .any(|request| request.starts_with("GET /entry.js ")));+ .any(|request| request.starts_with("GET /entry.js "))+ );let child = requests.iter().find(|request| request.starts_with("GET /child.js "))@@ -19258,7 +19465,10 @@ mod tests {.collect::<Vec<_>>();for request in &requests {let lower = request.to_ascii_lowercase();- assert!(lower.contains("\r\norigin: http://127.0.0.1:1\r\n"), "{request}");+ assert!(+ lower.contains("\r\norigin: http://127.0.0.1:1\r\n"),+ "{request}"+ );assert!(!lower.contains("\r\ncookie:"), "{request}");}let child = requests@@ -19701,7 +19911,9 @@ mod tests {.unwrap();assert_eq!(result,- serde_json::json!(["function", "function", "function", "function", true, 1, true])+ serde_json::json!([+ "function", "function", "function", "function", true, 1, true+ ]));}@@ -19976,7 +20188,9 @@ mod tests {.unwrap();assert_eq!(result,- serde_json::json!([true, true, true, 1, 1, 3, "Hello", -2, 80, 1, true, "metadata"])+ serde_json::json!([+ true, true, true, 1, 1, 3, "Hello", -2, 80, 1, true, "metadata"+ ]));}@@ -20567,9 +20781,7 @@ mod tests {std::env::set_var("LANG", "de-DE");let mut rt = setup_runtime("<html><body></body></html>");let result = rt- .evaluate(- "Intl.DateTimeFormat().resolvedOptions().locale + '|' + navigator.language",- )+ .evaluate("Intl.DateTimeFormat().resolvedOptions().locale + '|' + navigator.language").unwrap();assert_eq!(result,diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 6030faf7..90bea55e 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -12,7 +12,7 @@ use std::sync::Arc;use obscura_dom::tree::{DomTree, NodeId};use taffy::prelude::*;-use crate::{to_taffy_style, Rect};+use crate::{Rect, to_taffy_style};/// Text width for layout. With the `paint` feature this is exact (real glyph/// metrics from the embedded font, shared with rasterization). Without it@@ -543,13 +543,17 @@ pub enum RetainedStyleMutation {/// A document-timeline sample changed while the DOM and stylesheet stayed/// stable. Re-cascade this animation owner and its inheritance-dependent/// subtree while retaining unrelated branches.- Animation { node: NodeId },+ Animation {+ node: NodeId,+ },/// A Web Animation sample changed. Obscura's WAAPI surface currently/// animates only transform and opacity; neither property inherits, so the/// target alone needs a fresh animation cascade. Transform descendants/// are moved later by visual-geometry propagation, not by recascading/// their declarations.- WaapiAnimation { node: NodeId },+ WaapiAnimation {+ node: NodeId,+ },/// Cached image or font bytes became available. Resource selection,/// intrinsic sizes, shaping, layout, and paint must be rebuilt, but the/// DOM, stylesheet, and computed declarations are unchanged, so no style@@ -807,10 +811,7 @@ impl StickyLayout {port_parent_move.1 + port_sticky.1,)} else {- (- content_move.0 + inherited.0,- content_move.1 + inherited.1,- )+ (content_move.0 + inherited.0, content_move.1 + inherited.1)};let containing = Rect {x: frame.containing.x + containing_move.0,@@ -841,10 +842,7 @@ impl StickyLayout {);frame_offsets.insert(frame.id,- (- inherited.0 + x - normal.x,- inherited.1 + y - normal.y,- ),+ (inherited.0 + x - normal.x, inherited.1 + y - normal.y),);}frame_offsets@@ -1021,8 +1019,7 @@ impl DomLayout {) -> DerivedGeometryState {let content_size = self.scrolling_content_size_with_fixed(tree, viewport, viewport_fixed);let scroll_tree = self.scroll_tree(tree, viewport, content_size, viewport_fixed);- let sticky =- self.sticky_layout_with_geometry(tree, viewport, content_size, &scroll_tree);+ let sticky = self.sticky_layout_with_geometry(tree, viewport, content_size, &scroll_tree);DerivedGeometryState {content_size,sticky,@@ -1233,8 +1230,8 @@ impl DomLayout {movement_owner: &mut [Option<ScrollId>],) {let fixed = viewport_fixed.contains(&id);- let parent_fixed = rendered_parent(tree, id)- .is_some_and(|parent| viewport_fixed.contains(&parent));+ let parent_fixed =+ rendered_parent(tree, id).is_some_and(|parent| viewport_fixed.contains(&parent));// Only the boundary that enters the viewport-fixed coordinate// space drops root movement. Descendants inherit that zero-based// space and may establish ordinary nested scrolling areas.@@ -2604,10 +2601,11 @@ fn cascade_node_style(.get(&id).cloned().unwrap_or_else(|| parent_props.clone());- descendant_color_scheme_dark = styles- .get(&id)- .is_some_and(|style| style.color_scheme_dark);- if node.as_element().is_some_and(|elem| elem.local.as_ref() == "table") {+ descendant_color_scheme_dark = styles.get(&id).is_some_and(|style| style.color_scheme_dark);+ if node+ .as_element()+ .is_some_and(|elem| elem.local.as_ref() == "table")+ {descendant_cell_padding = node.get_attribute("cellpadding").and_then(|value| value.trim().parse::<f32>().ok())@@ -2973,7 +2971,8 @@ fn cascade_walk(visit.cell_padding,visit.color_scheme_dark,fresh_styles,- ) else {+ )+ else {continue;};@@ -3039,7 +3038,6 @@ fn cascade_walk(}}-#[derive(Default)]struct CssCounterState {values: HashMap<String, Vec<i32>>,@@ -3241,8 +3239,12 @@ pub fn layout_dom_with_resources(let intrinsic = intrinsic.iter().filter_map(|(&nid, &(width, height))| {- (width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0)- .then(|| (nid, crate::ReplacedIntrinsic::from_dimensions(width, height)))+ (width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0).then(|| {+ (+ nid,+ crate::ReplacedIntrinsic::from_dimensions(width, height),+ )+ })}).collect();layout_dom_with_web_fonts(tree, viewport, &intrinsic, &fonts)@@ -3362,11 +3364,7 @@ fn add_container_query_reset_scopes(}}-fn add_following_sibling_subtrees(- tree: &DomTree,- node: NodeId,- dirty: &mut HashSet<NodeId>,-) {+fn add_following_sibling_subtrees(tree: &DomTree, node: NodeId, dirty: &mut HashSet<NodeId>) {let mut sibling = tree.get_node(node).and_then(|node| node.next_sibling);while let Some(id) = sibling {add_style_subtree(tree, id, dirty);@@ -3481,9 +3479,7 @@ fn add_relational_tree_invalidation(let mut candidates = HashSet::new();match *mutation {TreeStyleMutation::Insert {- node,- old_parent,- ..+ node, old_parent, ..} => {add_inserted_relational_anchor_candidates(tree, node, &mut candidates);if let Some(old_parent) = old_parent {@@ -3529,12 +3525,7 @@ fn add_relational_tree_invalidation(}return false;}- add_relational_anchor_scope(- tree,- anchor,- invalidation.anchor_reaches,- dirty,- );+ add_relational_anchor_scope(tree, anchor, invalidation.anchor_reaches, dirty);}}true@@ -3590,8 +3581,7 @@ fn add_structural_candidate_scope(.structural_invalidations(state).into_iter().filter(|invalidation| {- !invalidation.inside_relational- && invalidation.subject_may_match(tree, candidate)+ !invalidation.inside_relational && invalidation.subject_may_match(tree, candidate)}).collect::<Vec<_>>();if invalidations.is_empty() {@@ -3669,10 +3659,7 @@ fn add_inserted_structural_scopes(add("first-child", &siblings[..siblings.len().min(2)]);}if position + 1 == siblings.len() {- add(- "last-child",- &siblings[position.saturating_sub(1)..],- );+ add("last-child", &siblings[position.saturating_sub(1)..]);}if siblings.len() <= 2 {add("only-child", &siblings);@@ -3858,8 +3845,7 @@ fn add_empty_parent_scope(.structural_invalidations("empty").into_iter().filter(|invalidation| {- !invalidation.inside_relational- && invalidation.subject_may_match(tree, parent)+ !invalidation.inside_relational && invalidation.subject_may_match(tree, parent)}).collect::<Vec<_>>();if invalidations.is_empty() {@@ -3947,12 +3933,7 @@ fn retained_style_plan(add_style_context_chain(tree, new_parent, &mut dirty);add_table_row_child_scope(tree, new_parent, &mut dirty);add_inserted_structural_scopes(- tree,- map,- node,- new_parent,- mutations,- &mut dirty,+ tree, map, node, new_parent, mutations, &mut dirty,);add_inserted_sibling_scopes(tree, map, node, new_parent, &mut dirty);add_empty_parent_scope(tree, map, new_parent, mutations, &mut dirty);@@ -4076,10 +4057,10 @@ fn retained_style_plan(}}-/// A selector-only `tabindex` mutation cannot change layout or paint when the-/// current stylesheet has no dependency on it. Keep this deliberately narrow:+/// Selector-only metadata cannot change layout or paint when the current+/// stylesheet has no dependency on it. Keep this deliberately narrow:/// other zero-dirty attributes can still affect native geometry.-pub(crate) fn can_retain_layout_for_tabindex(+pub(crate) fn can_retain_layout_for_metadata(tree: &DomTree,viewport: (f32, f32),cache: &mut crate::css::StylesheetCache,@@ -4088,7 +4069,11 @@ pub(crate) fn can_retain_layout_for_tabindex(if mutations.is_empty()|| !mutations.iter().all(|mutation| {matches!(mutation, RetainedStyleMutation::Attribute(attribute)- if attribute.name.eq_ignore_ascii_case("tabindex")+ if (attribute.name.eq_ignore_ascii_case("tabindex")+ || attribute+ .name+ .get(..5)+ .is_some_and(|prefix| prefix.eq_ignore_ascii_case("data-")))&& retained_attribute_mutation_kind(tree, attribute.node, &attribute.name)== RetainedAttributeMutationKind::Selector)})@@ -4396,10 +4381,7 @@ fn collect_shadow_stylesheets(}}let sheet = crate::css::Stylesheet::parse_for_viewport_and_media(- tree,- &sources,- viewport,- media_type,+ tree, &sources, viewport, media_type,);(root, std::sync::Arc::new(sheet))})@@ -4468,7 +4450,9 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(let shadow_sheets = collect_shadow_stylesheets(tree, viewport, media_type);let t_parse = t0.elapsed();- let retained_requested = retained.as_ref().map_or(0, |retained| retained.styles.len());+ let retained_requested = retained+ .as_ref()+ .map_or(0, |retained| retained.styles.len());let retained = retained.and_then(|mut retained| {// The document cache key intentionally contains only document-scope// sources. Until shadow sheets have their own retained cache keys and@@ -4550,8 +4534,7 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(.as_ref().map_or(0, |(retained, _)| retained.styles.len() - retained_fresh);let retained_fallback = usize::from(retained_requested != 0 && retained.is_none());- let (mut laid, _, mut query, mut cascade_time) =- layout_dom_once(+ let (mut laid, _, mut query, mut cascade_time) = layout_dom_once(tree,viewport,intrinsic,@@ -4566,7 +4549,21 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(if !sheet.has_container_queries() {if timing {let (r, i, c, a, l, u) = sheet.debug_stats();- eprintln!("[timing] parse+index={:?} stylesheet_cache_hit={} cascade={:?} rules={} id_keys={} class_keys={} attr_keys={} local_keys={} universal={} cq_passes=1 cq_termination=no-queries retained_reused={} retained_fresh={} retained_fallback={}", t_parse, stylesheet_cache_hit, cascade_time, r, i, c, a, l, u, retained_reused, retained_fresh, retained_fallback);+ eprintln!(+ "[timing] parse+index={:?} stylesheet_cache_hit={} cascade={:?} rules={} id_keys={} class_keys={} attr_keys={} local_keys={} universal={} cq_passes=1 cq_termination=no-queries retained_reused={} retained_fresh={} retained_fallback={}",+ t_parse,+ stylesheet_cache_hit,+ cascade_time,+ r,+ i,+ c,+ a,+ l,+ u,+ retained_reused,+ retained_fresh,+ retained_fallback+ );}return (laid,@@ -4591,7 +4588,21 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(if snapshot.boxes.is_empty() {if timing {let (r, i, c, a, l, u) = sheet.debug_stats();- eprintln!("[timing] parse+index={:?} stylesheet_cache_hit={} cascade={:?} rules={} id_keys={} class_keys={} attr_keys={} local_keys={} universal={} cq_passes=1 cq_termination=no-containers retained_reused={} retained_fresh={} retained_fallback={}", t_parse, stylesheet_cache_hit, cascade_time, r, i, c, a, l, u, retained_reused, retained_fresh, retained_fallback);+ eprintln!(+ "[timing] parse+index={:?} stylesheet_cache_hit={} cascade={:?} rules={} id_keys={} class_keys={} attr_keys={} local_keys={} universal={} cq_passes=1 cq_termination=no-containers retained_reused={} retained_fresh={} retained_fallback={}",+ t_parse,+ stylesheet_cache_hit,+ cascade_time,+ r,+ i,+ c,+ a,+ l,+ u,+ retained_reused,+ retained_fresh,+ retained_fallback+ );}return (laid,@@ -4639,8 +4650,7 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(});let mut needs_fallback = false;for pass in 2..=max_passes {- let (next, signature, pass_query, pass_cascade) =- layout_dom_once(+ let (next, signature, pass_query, pass_cascade) = layout_dom_once(tree,viewport,intrinsic,@@ -4697,8 +4707,7 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(// we return a layout whose conditional declarations contradict the// geometry used to choose them. Disable the unstable conditional// rules for this render and expose the downgrade in telemetry.- let (fallback, _, fallback_query, fallback_cascade) =- layout_dom_once(+ let (fallback, _, fallback_query, fallback_cascade) = layout_dom_once(tree,viewport,intrinsic,@@ -4720,7 +4729,26 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(if timing {let (r, i, c, a, l, u) = sheet.debug_stats();- eprintln!("[timing] parse+index={:?} stylesheet_cache_hit={} cascade_total={:?} rules={} id_keys={} class_keys={} attr_keys={} local_keys={} universal={} cq_passes={} cq_termination={:?} cq_evaluations={} cq_cache_hits={} cq_ancestor_steps={} retained_reused={} retained_fresh={} retained_fallback={}", t_parse, stylesheet_cache_hit, cascade_time, r, i, c, a, l, u, passes, termination, query.evaluations, query.cache_hits, query.ancestor_steps, retained_reused, retained_fresh, retained_fallback);+ eprintln!(+ "[timing] parse+index={:?} stylesheet_cache_hit={} cascade_total={:?} rules={} id_keys={} class_keys={} attr_keys={} local_keys={} universal={} cq_passes={} cq_termination={:?} cq_evaluations={} cq_cache_hits={} cq_ancestor_steps={} retained_reused={} retained_fresh={} retained_fallback={}",+ t_parse,+ stylesheet_cache_hit,+ cascade_time,+ r,+ i,+ c,+ a,+ l,+ u,+ passes,+ termination,+ query.evaluations,+ query.cache_hits,+ query.ancestor_steps,+ retained_reused,+ retained_fresh,+ retained_fallback+ );}(laid,@@ -4884,6 +4912,7 @@ fn layout_dom_once(text_indent: crate::Dimension,legacy_center: bool,visibility_hidden: bool,+ pointer_events_none: bool,has_zero_opacity: bool,list_style: crate::ListStyle,line_height: crate::LineHeight,@@ -4904,6 +4933,11 @@ fn layout_dom_once(/// taffy layout. Not a CSS-inherited property; it is recomputed to/// the element's own content width for its children.cb_width: f32,+ /// Definite content-box height of the current element's+ /// containing block. Functional percentage block sizes need the+ /// same basis as plain percentage heights rather than the visual+ /// viewport height.+ cb_height: f32,/// Whether the containing block has a definite height. Percentage/// heights in ordinary flow compute to auto when this is false;/// resolving them against a synthetic zero height collapses@@ -4936,6 +4970,7 @@ fn layout_dom_once(text_indent: crate::Dimension::Px(0.0),legacy_center: false,visibility_hidden: false,+ pointer_events_none: false,has_zero_opacity: false,// CSS initial value of list-style-type.list_style: crate::ListStyle::Disc,@@ -4952,6 +4987,7 @@ fn layout_dom_once(overflow_x: 0,overflow_y: 0,cb_width: 0.0,+ cb_height: 0.0,cb_height_definite: false,}}@@ -4987,6 +5023,7 @@ fn layout_dom_once(// i.e. the viewport width.let mut root_inh = Inherited::default();root_inh.cb_width = initial_cb_width;+ root_inh.cb_height = viewport.1;root_inh.cb_height_definite = true;// This set records computed definiteness after walking the real// containing-block chain. Merely retaining `height:Percent` is not@@ -4998,6 +5035,7 @@ fn layout_dom_once(// Default the child containing-block width to this element's own// (updated to its content width inside the block below).let mut child_cb_width = inh.cb_width;+ let mut child_cb_height = inh.cb_height;let mut child_cb_height_definite = false;let reused_computed_style = fresh_styles.as_ref()@@ -5050,9 +5088,10 @@ fn layout_dom_once(if let Some(indent) = style.text_indent {inh.text_indent = indent;}- inh.visibility_hidden = style- .visibility_hidden- .unwrap_or(inh.visibility_hidden);+ inh.visibility_hidden =+ style.visibility_hidden.unwrap_or(inh.visibility_hidden);+ inh.pointer_events_none =+ style.pointer_events_none.unwrap_or(inh.pointer_events_none);inh.has_zero_opacity |= style.opacity.is_some_and(|value| value <= 0.0);if let Some(value) = style.list_style {inh.list_style = value;@@ -5095,24 +5134,28 @@ fn layout_dom_once(inh.table_vertical_align = Some(value);}}- inh.overflow_x = if style.overflow_scroll_x {- 2- } else if style.overflow_clip_x {- 1- } else {- 0- };- inh.overflow_y = if style.overflow_scroll_y {- 2- } else if style.overflow_clip_y {- 1- } else {- 0- };+ (inh.overflow_x, inh.overflow_y) = crate::style::computed_overflow_axes(style);child_cb_height_definite = matches!(style.height,crate::Dimension::Px(_) | crate::Dimension::Percent(_));+ if child_cb_height_definite {+ let used_height = match style.height {+ crate::Dimension::Px(height) => height,+ crate::Dimension::Percent(percent) => percent * inh.cb_height,+ _ => 0.0,+ };+ child_cb_height = if style.box_sizing == crate::BoxSizing::ContentBox {+ used_height.max(0.0)+ } else {+ (used_height+ - style.padding.top+ - style.padding.bottom+ - style.border.top+ - style.border.bottom)+ .max(0.0)+ };+ }if child_cb_height_definite {definite_height_nodes.insert(id);}@@ -5125,7 +5168,8 @@ fn layout_dom_once(let definite_content_box = matches!(style.width,crate::Dimension::Px(_) | crate::Dimension::Percent(_)- ) && style.box_sizing == crate::BoxSizing::ContentBox;+ ) && style.box_sizing+ == crate::BoxSizing::ContentBox;child_cb_width = if definite_content_box {used_w.max(0.0)} else {@@ -5138,6 +5182,7 @@ fn layout_dom_once(};}inh.cb_width = child_cb_width;+ inh.cb_height = child_cb_height;inh.cb_height_definite = child_cb_height_definite;for child in style_children(tree, id).into_iter().rev() {queue.push((child, inh.clone()));@@ -5274,20 +5319,7 @@ fn layout_dom_once(style.overflow_inherit_y = false;}crate::style::recompute_overflow(style);- inh.overflow_x = if style.overflow_scroll_x {- 2- } else if style.overflow_clip_x {- 1- } else {- 0- };- inh.overflow_y = if style.overflow_scroll_y {- 2- } else if style.overflow_clip_y {- 1- } else {- 0- };+ (inh.overflow_x, inh.overflow_y) = crate::style::computed_overflow_axes(style);if let Some(expression) = style.row_gap_expression.as_deref() {style.row_gap = crate::style::resolve_contextual_length(expression,@@ -5349,7 +5381,11 @@ fn layout_dom_once(}}let percent_base = if matches!(index, 1 | 3 | 5) {+ if inh.cb_height_definite {+ inh.cb_height+ } else {viewport.1+ }} else {cb_w};@@ -5503,6 +5539,10 @@ fn layout_dom_once(None => style.text_indent = Some(inh.text_indent),}inh.visibility_hidden = style.visibility_hidden.unwrap_or(inh.visibility_hidden);+ match style.pointer_events_none {+ Some(value) => inh.pointer_events_none = value,+ None => style.pointer_events_none = Some(inh.pointer_events_none),+ }inh.has_zero_opacity |= style.opacity.is_some_and(|value| value <= 0.0);style.effectively_invisible = inh.visibility_hidden || inh.has_zero_opacity;match style.list_style {@@ -5660,20 +5700,8 @@ fn layout_dom_once(let host_grid_auto_rows = style.grid_auto_rows.clone();let host_grid_auto_column_calcs = style.grid_calc_expressions[2].clone();let host_grid_auto_row_calcs = style.grid_calc_expressions[3].clone();- let host_overflow_x = if style.overflow_scroll_x {- 2- } else if style.overflow_clip_x {- 1- } else {- 0- };- let host_overflow_y = if style.overflow_scroll_y {- 2- } else if style.overflow_clip_y {- 1- } else {- 0- };+ let (host_overflow_x, host_overflow_y) =+ crate::style::computed_overflow_axes(style);let settle_pseudo = |pseudo: &mut crate::LayoutStyle| {if pseudo.direction.is_none() {pseudo.direction = Some(host_direction);@@ -5920,11 +5948,29 @@ fn layout_dom_once(- style.border.right).max(0.0)};+ if child_cb_height_definite {+ let used_height = match style.height {+ crate::Dimension::Px(height) => height,+ crate::Dimension::Percent(percent) => percent * inh.cb_height,+ _ => 0.0,+ };+ child_cb_height = if style.box_sizing == crate::BoxSizing::ContentBox {+ used_height.max(0.0)+ } else {+ (used_height+ - style.padding.top+ - style.padding.bottom+ - style.border.top+ - style.border.bottom)+ .max(0.0)+ };+ }}inh.cb_width = child_cb_width;+ inh.cb_height = child_cb_height;inh.cb_height_definite = child_cb_height_definite;- for cid in style_children(tree, id).into_iter().rev() {- queue.push((cid, inh.clone()));+ for child in style_children(tree, id).into_iter().rev() {+ queue.push((child, inh.clone()));}}@@ -6102,7 +6148,10 @@ fn layout_dom_once(crate::inline::used_line_height(style).max(1.0) * rows + vertical_edges;assign_native_control_size(style,- native_control_grid_stretch.get(&id).copied().unwrap_or_default(),+ native_control_grid_stretch+ .get(&id)+ .copied()+ .unwrap_or_default(),intrinsic_width,intrinsic_height,horizontal_edges,@@ -6142,7 +6191,10 @@ fn layout_dom_once(crate::inline::used_line_height(style).max(1.0) * rows + vertical_edges;assign_native_control_size(style,- native_control_grid_stretch.get(&id).copied().unwrap_or_default(),+ native_control_grid_stretch+ .get(&id)+ .copied()+ .unwrap_or_default(),intrinsic_width,intrinsic_height,horizontal_edges,@@ -6205,7 +6257,10 @@ fn layout_dom_once(};assign_native_control_size(style,- native_control_grid_stretch.get(&id).copied().unwrap_or_default(),+ native_control_grid_stretch+ .get(&id)+ .copied()+ .unwrap_or_default(),intrinsic_width,intrinsic_height,horizontal_edges,@@ -6305,12 +6360,7 @@ fn layout_dom_once(&& style.width == crate::Dimension::Auto&& style.height == crate::Dimension::Auto).then(|| {- reliable_ratio_only_available_width(- tree,- nid,- &styles,- initial_cb_width,- )+ reliable_ratio_only_available_width(tree, nid, &styles, initial_cb_width).map(|width| (nid, width))}).flatten()@@ -6508,17 +6558,11 @@ fn layout_dom_once(&mut measure,);for &(tnode, dom, _) in group {- if styles- .get(&dom)- .is_some_and(|style| {+ if styles.get(&dom).is_some_and(|style| {style.width == crate::Dimension::Auto|| (style.table_layout_fixed- && matches!(- style.width,- crate::Dimension::Percent(_)- ))- })- {+ && matches!(style.width, crate::Dimension::Percent(_)))+ }) {if let Ok(layout) = taffy_tree.layout(tnode) {available_widths.insert(tnode, layout.size.width.max(0.0));}@@ -6538,22 +6582,18 @@ fn layout_dom_once(let (horizontal_spacing, _) = table_spacing(table_style);let mut used_outer = match table_style.width {crate::Dimension::Px(width)- if table_style.box_sizing- == crate::BoxSizing::ContentBox =>+ if table_style.box_sizing == crate::BoxSizing::ContentBox =>{// Border spacing lives inside a CSS table's// content box. It is artificial Taffy// padding in our grid model, but must not// enlarge an authored content-box width.width.max(0.0)- + (inline_outer_edges - horizontal_spacing * 2.0)- .max(0.0)+ + (inline_outer_edges - horizontal_spacing * 2.0).max(0.0)}crate::Dimension::Px(width) => width.max(0.0),- crate::Dimension::Percent(_) => available_widths- .get(&tnode)- .copied()- .unwrap_or_else(|| {+ crate::Dimension::Percent(_) => {+ available_widths.get(&tnode).copied().unwrap_or_else(|| {reliable_table_available_width(tree,dom,@@ -6561,7 +6601,8 @@ fn layout_dom_once(initial_cb_width,).unwrap_or(initial_cb_width)- }),+ })+ }_ => continue,};let interior_spacing =@@ -6569,9 +6610,8 @@ fn layout_dom_once(let target =(used_outer - inline_outer_edges - interior_spacing).max(0.0);let widths = distribute_fixed_table_columns(target, columns);- let required_outer = widths.iter().sum::<f32>()- + inline_outer_edges- + interior_spacing;+ let required_outer =+ widths.iter().sum::<f32>() + inline_outer_edges + interior_spacing;used_outer = used_outer.max(required_outer);let used_declaration =if table_style.box_sizing == crate::BoxSizing::ContentBox {@@ -6656,12 +6696,7 @@ fn layout_dom_once(.get(&tnode).copied().or_else(|| {- reliable_table_available_width(- tree,- dom,- &styles,- initial_cb_width,- )+ reliable_table_available_width(tree, dom, &styles, initial_cb_width)}).unwrap_or(initial_cb_width);let mut used_outer = match width_style {@@ -6943,7 +6978,7 @@ fn layout_dom_once();}}- }+ },);if apply_multicol_balance(&mut taffy_tree, &ifc_items.multicol) {let _ =@@ -7071,7 +7106,7 @@ fn layout_dom_once(let _ = tree.compute_layout(taffy_root, available);}}- }+ },);if apply_multicol_balance(&mut taffy_tree, &ifc_items.multicol) {let _ = taffy_tree.compute_layout(taffy_root, available);@@ -9728,9 +9763,9 @@ fn build_flex_grid_children(let mut index = 0;while index < effective_children.len() {let is_text = match effective_children[index] {- EffectiveGridChild::Dom(node) => tree.get_node(node).is_some_and(|node| {- matches!(node.data, obscura_dom::tree::NodeData::Text { .. })- }),+ EffectiveGridChild::Dom(node) => tree+ .get_node(node)+ .is_some_and(|node| matches!(node.data, obscura_dom::tree::NodeData::Text { .. })),EffectiveGridChild::Generated { .. } => false,};if !is_text {@@ -9753,9 +9788,10 @@ fn build_flex_grid_children(let mut run = Vec::new();while let Some(EffectiveGridChild::Dom(node)) = effective_children.get(index).copied() {- if !tree.get_node(node).is_some_and(|node| {- matches!(node.data, obscura_dom::tree::NodeData::Text { .. })- }) {+ if !tree+ .get_node(node)+ .is_some_and(|node| matches!(node.data, obscura_dom::tree::NodeData::Text { .. }))+ {break;}run.push(node);@@ -10440,10 +10476,8 @@ fn reliable_declared_content_width(return None;}- let needs_containing_width = matches!(- style.width,- crate::Dimension::Percent(_)- ) || matches!(style.min_width, crate::Dimension::Percent(_))+ let needs_containing_width = matches!(style.width, crate::Dimension::Percent(_))+ || matches!(style.min_width, crate::Dimension::Percent(_))|| matches!(style.max_width, crate::Dimension::Percent(_));let containing_width = needs_containing_width.then(|| {let mut parent = rendered_parent(tree, id);@@ -10455,13 +10489,7 @@ fn reliable_declared_content_width(parent = parent.and_then(|parent_id| rendered_parent(tree, parent_id));}if let Some(parent_id) = parent {- reliable_normal_flow_content_width(- tree,- parent_id,- styles,- initial_cb_width,- depth + 1,- )+ reliable_normal_flow_content_width(tree, parent_id, styles, initial_cb_width, depth + 1).or_else(|| {reliable_declared_content_width(tree,@@ -10529,8 +10557,7 @@ fn reliable_ratio_only_available_width(continue;};if parent_style.display_contents- || (parent_style.display == crate::Display::Inline- && !parent_style.is_inline_block)+ || (parent_style.display == crate::Display::Inline && !parent_style.is_inline_block){parent = rendered_parent(tree, parent_id);continue;@@ -10539,22 +10566,15 @@ fn reliable_ratio_only_available_width(}let containing_width = if let Some(parent_id) = parent {- reliable_normal_flow_content_width(tree, parent_id, styles, initial_cb_width, 0)- .or_else(|| {- reliable_declared_content_width(tree, parent_id, styles, initial_cb_width, 0)- })?+ reliable_normal_flow_content_width(tree, parent_id, styles, initial_cb_width, 0).or_else(+ || reliable_declared_content_width(tree, parent_id, styles, initial_cb_width, 0),+ )?} else {initial_cb_width};let horizontal_edges =image.padding.left + image.padding.right + image.border.left + image.border.right;- Some(- (containing_width- - image.margin.left- - image.margin.right- - horizontal_edges)- .max(0.0),- )+ Some((containing_width - image.margin.left - image.margin.right - horizontal_edges).max(0.0))}fn reliable_table_available_width(@@ -10880,10 +10900,7 @@ fn distribute_auto_table_columns(percentages: &[Option<f32>],) -> Vec<f32> {let count = minimums.len();- if count == 0- || preferreds.len() != count- || fixed.len() != count- || percentages.len() != count+ if count == 0 || preferreds.len() != count || fixed.len() != count || percentages.len() != count{return minimums.to_vec();}@@ -10982,9 +10999,7 @@ fn distribute_auto_table_columns(.collect();if candidates.is_empty() {candidates = (0..count)- .filter(|index| {- effective_percentages[*index].is_none() && fixed[*index].is_none()- })+ .filter(|index| effective_percentages[*index].is_none() && fixed[*index].is_none()).map(|index| (index, 1.0)).collect();}@@ -11209,9 +11224,7 @@ fn build_table(let is_cell = if native_html_table {matches!(local.as_deref(), Some("td") | Some("th"))} else {- styles- .get(&cid)- .is_some_and(|cell| cell.is_table_cell_box)+ styles.get(&cid).is_some_and(|cell| cell.is_table_cell_box)};if !is_cell {continue;@@ -11321,7 +11334,10 @@ fn build_table(let mut col_px: Vec<Option<f32>> = vec![None; ncols];let mut col_pct: Vec<Option<f32>> = vec![None; ncols];let fixed_layout = style.table_layout_fixed- && matches!(style.width, crate::Dimension::Px(_) | crate::Dimension::Percent(_));+ && matches!(+ style.width,+ crate::Dimension::Px(_) | crate::Dimension::Percent(_)+ );let mut fixed_columns = vec![FixedTableColumn::default(); ncols];let attr_width = |cid: NodeId| -> (Option<f32>, Option<f32>) {let Some(v) = tree@@ -11447,16 +11463,12 @@ fn build_table(let edges = cell_style.filter(|cell| cell.box_sizing == crate::BoxSizing::ContentBox).map(|cell| {- cell.padding.left- + cell.padding.right- + cell.border.left- + cell.border.right+ cell.padding.left + cell.padding.right + cell.border.left + cell.border.right}).unwrap_or(0.0);let outer_length = px.unwrap_or(0.0) + edges;let per_column_length =- ((outer_length + horizontal_spacing) / span as f32 - horizontal_spacing)- .max(0.0);+ ((outer_length + horizontal_spacing) / span as f32 - horizontal_spacing).max(0.0);let per_column_percentage = pct.unwrap_or(0.0).max(0.0) / span as f32;for column in &mut fixed_columns[*start..*start + span] {if !column.specified {@@ -11869,6 +11881,80 @@ enum DeferredFlexReflowPhase {FitContent,}+/// Return the max-content inline size for the common definite, no-wrap flex+/// row case without asking the layout engine to resolve a cyclic percentage.+/// Every item must have a fixed basis (or width); otherwise the general+/// intrinsic algorithm remains authoritative.+fn definite_row_flex_intrinsic_width(+ tree: &DomTree,+ id: NodeId,+ styles: &HashMap<NodeId, crate::LayoutStyle>,+) -> Option<f32> {+ let style = styles.get(&id)?;+ if style.display != crate::Display::Flex+ || style.internal_flex_container+ || matches!(+ style.flex_direction,+ Some(taffy::FlexDirection::Column | taffy::FlexDirection::ColumnReverse)+ )+ || matches!(+ style.flex_wrap,+ Some(taffy::FlexWrap::Wrap | taffy::FlexWrap::WrapReverse)+ )+ {+ return None;+ }++ let mut count = 0usize;+ let mut width = 0.0_f32;+ for child in rendered_children(tree, id) {+ let Some(child_style) = styles.get(&child) else {+ let node = tree.get_node(child)?;+ if matches!(+ &node.data,+ obscura_dom::tree::NodeData::Text { contents } if contents.trim().is_empty()+ ) {+ continue;+ }+ return None;+ };+ if child_style.display == crate::Display::None+ || matches!(child_style.position, Some(taffy::Position::Absolute))+ || child_style.float.is_some()+ || child_style.margin_auto[1]+ || child_style.margin_auto[3]+ || child_style.margin_percent[1].is_some()+ || child_style.margin_percent[3].is_some()+ || child_style.margin_relative[1].is_some()+ || child_style.margin_relative[3].is_some()+ || child_style.margin_expressions[1].is_some()+ || child_style.margin_expressions[3].is_some()+ {+ return None;+ }+ let basis = match child_style.flex_basis {+ crate::Dimension::Px(value) => value,+ crate::Dimension::Auto => match child_style.width {+ crate::Dimension::Px(value) => value,+ _ => return None,+ },+ _ => return None,+ };+ let edges = child_style.padding.left+ + child_style.padding.right+ + child_style.border.left+ + child_style.border.right;+ let outer = if child_style.box_sizing == crate::BoxSizing::BorderBox {+ basis+ } else {+ basis + edges+ };+ width += outer + child_style.margin.left + child_style.margin.right;+ count += 1;+ }+ (count > 0).then(|| width + style.column_gap.unwrap_or(0.0) * (count - 1) as f32)+}+/// During a flex item's intrinsic-size calculation, percentages in descendant/// inline sizes are cyclic: their containing block does not have its used/// width yet. Resolving those percentages against the width inherited from a@@ -11973,12 +12059,20 @@ fn defer_cyclic_flex_inline_sizes(}DeferredCyclicInlineSource::Percent(_) => Some(0.0),};- let Some(intrinsic) = intrinsic- else {+ let Some(intrinsic) = intrinsic else {continue;};+ let definite_row_width = (slot == 0+ && matches!(source, DeferredCyclicInlineSource::Percent(_)))+ .then(|| definite_row_flex_intrinsic_width(tree, id, styles))+ .flatten();if let Some(style) = styles.get_mut(&id) {- let intrinsic = crate::Dimension::Px(intrinsic.max(0.0));+ // A cyclic percentage preferred size uses the container's+ // max-content contribution. Preserve that contribution for a+ // definite no-wrap row; a zero width would erase all of its fixed+ // cells. Other cyclic forms retain the percentage-zero intrinsic+ // value and are restored after outer flex sizing.+ let intrinsic = crate::Dimension::Px(definite_row_width.unwrap_or(intrinsic).max(0.0));match slot {0 => style.width = intrinsic,2 => style.min_width = intrinsic,@@ -12012,11 +12106,7 @@ fn resolve_deferred_flex_inline_sizes<F>(mut relayout: F,) -> boolwhere- F: FnMut(- &mut TaffyTree<usize>,- &HashMap<NodeId, crate::LayoutStyle>,- DeferredFlexReflowPhase,- ),+ F: FnMut(&mut TaffyTree<usize>, &HashMap<NodeId, crate::LayoutStyle>, DeferredFlexReflowPhase),{if deferred.is_empty() {return false;@@ -12102,12 +12192,8 @@ where// alongside the width so the final layout resolves both// against the pinned flex item (#698).restore_maximum = Some(match style.max_width {- crate::Dimension::Percent(maximum) => {- taffy::Dimension::percent(maximum)- }- crate::Dimension::Px(maximum) => {- taffy::Dimension::length(maximum.max(0.0))- }+ crate::Dimension::Percent(maximum) => taffy::Dimension::percent(maximum),+ crate::Dimension::Px(maximum) => taffy::Dimension::length(maximum.max(0.0)),_ => taffy::Dimension::auto(),});}@@ -12220,9 +12306,7 @@ where.unwrap_or(root_fs);let value = match &entry.source {DeferredCyclicInlineSource::Expression(expression) => {- crate::style::resolve_contextual_length(- expression, em, root_fs, vw, vh, basis,- )+ crate::style::resolve_contextual_length(expression, em, root_fs, vw, vh, basis)}DeferredCyclicInlineSource::Percent(_) => unreachable!(),};@@ -12316,6 +12400,21 @@ fn build(let mut taffy_style = to_taffy_style(style);apply_container_size_containment(tree, id, style, styles, &mut taffy_style);+ // A definite-width inline-block establishes a block formatting context:+ // an in-flow block child's auto inline size fills the containing block.+ // Our inline-block stand-in uses a flex row to remain atomic in inline+ // layout, whose main-axis flex items otherwise shrink-wrap their content.+ // Express only this definite containing-block case as 100%; auto-width+ // inline-blocks must keep their normal shrink-to-fit intrinsic sizing.+ if style.width == crate::Dimension::Auto && is_in_flow_block_level(style) {+ let parent_style = rendered_parent(tree, id).and_then(|parent| styles.get(&parent));+ if parent_style+ .is_some_and(|parent| parent.is_inline_block && parent.width != crate::Dimension::Auto)+ {+ taffy_style.size.width = taffy::Dimension::percent(1.0);+ }+ }+// A non-stretched flex item in a column flex container uses fit-content// for its auto inline size. In a nested flex layout taffy can retain the// item's earlier max-content measurement after the outer row shrinks its@@ -12864,14 +12963,7 @@ fn build(&& !style.internal_flex_container{build_flex_grid_children(- tree,- id,- taffy_tree,- id_map,- words,- engine,- ifc_items,- styles,+ tree, id, taffy_tree, id_map, words, engine, ifc_items, styles,)} else {dom_children@@ -14550,9 +14642,7 @@ fn build_children_with_float_zone(&& dom_children.get(run_end).and_then(|cid| styles.get(cid))- .and_then(|style| {- (style.display != crate::Display::None).then_some(style.float)- })+ .and_then(|style| (style.display != crate::Display::None).then_some(style.float)).flatten()== Some(crate::Float::Right)).then(|| dom_children[run_end]);@@ -14905,13 +14995,7 @@ mod tests {assert_eq!(rendered_children(&tree, host),- vec![- before,- title_slot,- duplicate_title,- default_slot,- after,- ]+ vec![before, title_slot, duplicate_title, default_slot, after,]);assert_eq!(rendered_children(&tree, title_slot), vec![title_light]);assert_eq!(@@ -15196,18 +15280,38 @@ mod tests {let hidden = &laid.styles[&unslotted];assert_eq!(first.display, crate::Display::Block);- assert_eq!(first.width, crate::Dimension::Px(120.0), "document normal wins");- assert_eq!(first.height, crate::Dimension::Px(33.0), "document custom property wins");- assert_eq!(first.margin.left, 21.0, "shadow important beats inline important");- assert_eq!(first.padding.left, 17.0, "shadow important custom property wins");+ assert_eq!(+ first.width,+ crate::Dimension::Px(120.0),+ "document normal wins"+ );+ assert_eq!(+ first.height,+ crate::Dimension::Px(33.0),+ "document custom property wins"+ );+ assert_eq!(+ first.margin.left, 21.0,+ "shadow important beats inline important"+ );+ assert_eq!(+ first.padding.left, 17.0,+ "shadow important custom property wins"+ );assert_eq!(first.border.left, 3.0, "slot-qualified selector matches");- assert_eq!(first.border.right, 0.0, "ordinary shadow selector stays isolated");+ assert_eq!(+ first.border.right, 0.0,+ "ordinary shadow selector stays isolated"+ );assert_eq!(first.border.top, 0.0, "slotted argument must match");assert_eq!(laid.rects[&assigned_one].width, 140.0);assert_eq!(second.border.bottom, 4.0);assert_eq!(second.border.left, 0.0, "first shadow root cannot leak");- assert_eq!(hidden.border.left, 0.0, "unassigned light child is not slotted");+ assert_eq!(+ hidden.border.left, 0.0,+ "unassigned light child is not slotted"+ );assert!(!laid.rects.contains_key(&unslotted));}@@ -15582,8 +15686,28 @@ mod tests {#[test]fn sticky_horizontal_overconstraint_prioritizes_logical_inline_start() {- let ltr = sticky_axis_position(0.0, 80.0, -100.0, 100.0, 0.0, 100.0, Some(30.0), Some(30.0), false);- let rtl = sticky_axis_position(0.0, 80.0, -100.0, 100.0, 0.0, 100.0, Some(30.0), Some(30.0), true);+ let ltr = sticky_axis_position(+ 0.0,+ 80.0,+ -100.0,+ 100.0,+ 0.0,+ 100.0,+ Some(30.0),+ Some(30.0),+ false,+ );+ let rtl = sticky_axis_position(+ 0.0,+ 80.0,+ -100.0,+ 100.0,+ 0.0,+ 100.0,+ Some(30.0),+ Some(30.0),+ true,+ );assert_eq!(ltr, 30.0, "LTR physical left is inline-start");assert_eq!(rtl, -10.0, "RTL physical right is inline-start");}@@ -15609,9 +15733,10 @@ mod tests {let sticky = laid.root_sticky_layout(&tree, (200.0, 100.0));assert!(- sticky.frames.iter().any(|frame| {- frame.id == root_sticky && frame.scroll_owner == ScrollId::ROOT- }),+ sticky+ .frames+ .iter()+ .any(|frame| { frame.id == root_sticky && frame.scroll_owner == ScrollId::ROOT }),"display:contents cannot capture a sticky descendant",);assert!(@@ -15633,8 +15758,14 @@ mod tests {let laid = layout_dom(&tree, (120.0, 100.0));let id = tree.get_element_by_id("sticky").unwrap();let sticky = laid.root_sticky_layout(&tree, (120.0, 100.0));- assert_eq!(sticky.translation_for(id, (120.0, 100.0), (0.0, 0.0)).1, -40.0);- assert_eq!(sticky.translations((120.0, 100.0), (0.0, 0.0))[&id].1, -40.0);+ assert_eq!(+ sticky.translation_for(id, (120.0, 100.0), (0.0, 0.0)).1,+ -40.0+ );+ assert_eq!(+ sticky.translations((120.0, 100.0), (0.0, 0.0))[&id].1,+ -40.0+ );}#[test]@@ -15790,6 +15921,21 @@ mod tests {}}+ #[test]+ fn block_child_fills_a_definite_width_inline_block() {+ let tree = parse_html(+ r#"<style>html,body{margin:0}</style>+ <div id="host" style="display:inline-block;width:372px">+ <div id="child"><div style="width:96px;height:20px"></div></div>+ </div>"#,+ );+ let laid = layout_dom(&tree, (700.0, 300.0));+ let host = laid.rects[&tree.get_element_by_id("host").unwrap()];+ let child = laid.rects[&tree.get_element_by_id("child").unwrap()];+ assert!((host.width - 372.0).abs() < 0.01, "{host:?}");+ assert!((child.width - 372.0).abs() < 0.01, "{child:?}");+ }+#[test]fn inline_flex_and_grid_preserve_percentage_and_box_edge_geometry() {let tree = parse_html(@@ -16317,7 +16463,10 @@ mod tests {(0.0, 0.0, 780.0, 100.0),"the ordinary block border box spans beneath the outer float");- assert_eq!((nav.x, nav.y, nav.width, nav.height), (250.0, 20.0, 400.0, 50.0));+ assert_eq!(+ (nav.x, nav.y, nav.width, nav.height),+ (250.0, 20.0, 400.0, 50.0)+ );assert_eq!((right.x, right.y, right.width, right.height),(685.0, 20.0, 80.0, 50.0)@@ -16638,8 +16787,12 @@ mod tests {let theme = tree.get_element_by_id("theme").unwrap();let toggle = tree.get_element_by_id("toggle").unwrap();let counter_change = tree.get_element_by_id("counter-change").unwrap();- tree.with_node_mut(theme, |node| node.set_attribute("data-theme", "dark".into()));- tree.with_node_mut(toggle, |node| node.set_attribute("data-open", "true".into()));+ tree.with_node_mut(theme, |node| {+ node.set_attribute("data-theme", "dark".into())+ });+ tree.with_node_mut(toggle, |node| {+ node.set_attribute("data-open", "true".into())+ });tree.with_node_mut(counter_change, |node| {node.set_attribute("data-double", "true".into())});@@ -16683,7 +16836,10 @@ mod tests {let final_tree = parse_html(&final_html);let full = layout_dom(&final_tree, (300.0, 200.0));- assert_eq!(telemetry.termination, ContainerLayoutTermination::NoContainers);+ assert_eq!(+ telemetry.termination,+ ContainerLayoutTermination::NoContainers+ );assert!(telemetry.retained_reused > 0, "clean branch must be reused");assert!(telemetry.retained_fresh > 0, "dirty subtrees must be fresh");assert_eq!(telemetry.retained_fallback, 0);@@ -16706,13 +16862,11 @@ mod tests {"{id} rect");assert_eq!(- incremental.styles[&incremental_id].width,- full.styles[&full_id].width,+ incremental.styles[&incremental_id].width, full.styles[&full_id].width,"{id} width");assert_eq!(- incremental.styles[&incremental_id].color,- full.styles[&full_id].color,+ incremental.styles[&incremental_id].color, full.styles[&full_id].color,"{id} color");assert_eq!(@@ -16721,8 +16875,7 @@ mod tests {"{id} generated content");assert_eq!(- incremental.custom_properties[&incremental_id],- full.custom_properties[&full_id],+ incremental.custom_properties[&incremental_id], full.custom_properties[&full_id],"{id} custom properties");}@@ -16742,7 +16895,8 @@ mod tests {&tree,&sheet,&[RetainedStyleMutation::WaapiAnimation { node: target }],- ) else {+ )+ else {panic!("WAAPI target damage must remain retainable")};assert_eq!(dirty, HashSet::from([target]));@@ -16790,8 +16944,7 @@ mod tests {styles: std::mem::take(&mut initial.styles),custom_properties: std::mem::take(&mut initial.custom_properties),};- let (incremental, telemetry) =- layout_dom_with_web_fonts_pass_limit_at_animation_time(+ let (incremental, telemetry) = layout_dom_with_web_fonts_pass_limit_at_animation_time(&tree,(800.0, 600.0),&HashMap::new(),@@ -16964,12 +17117,28 @@ mod tests {}#[test]- fn unreferenced_tabindex_can_retain_layout_but_css_dependencies_cannot() {- for (css, reusable) in [- ("#target { width: 80px }", true),- ("[tabindex] { width: 160px }", false),- ("p::before { content: attr(tabindex) }", false),- ("section:has([tabindex]) p { height: 50px }", false),+ fn unreferenced_metadata_can_retain_layout_but_css_dependencies_cannot() {+ for (name, css, reusable) in [+ ("tabindex", "#target { width: 80px }", true),+ ("tabindex", "[tabindex] { width: 160px }", false),+ ("tabindex", "p::before { content: attr(tabindex) }", false),+ (+ "tabindex",+ "section:has([tabindex]) p { height: 50px }",+ false,+ ),+ ("data-state", "#target { width: 80px }", true),+ ("data-state", "[data-state] { width: 160px }", false),+ (+ "data-state",+ "p::before { content: attr(data-state) }",+ false,+ ),+ (+ "data-state",+ "section:has([data-state]) p { height: 50px }",+ false,+ ),] {let tree = parse_html(&format!("<style>{css}</style><section><p id=target>text</p></section>"@@ -16994,37 +17163,27 @@ mod tests {};assert_eq!(- can_retain_layout_for_tabindex(- &tree,- viewport,- &mut cache,- &[mutation("tabindex")],- ),+ can_retain_layout_for_metadata(&tree, viewport, &mut cache, &[mutation(name)]),reusable,- "{css}"+ "{name}: {css}");- for name in ["data-sized", "style", "hidden", "open"] {+ for name in ["style", "hidden", "open"] {assert!(- !can_retain_layout_for_tabindex(- &tree,- viewport,- &mut cache,- &[mutation(name)],- ),+ !can_retain_layout_for_metadata(&tree, viewport, &mut cache, &[mutation(name)]),"{name}");}- assert!(!can_retain_layout_for_tabindex(+ assert!(!can_retain_layout_for_metadata(&tree,viewport,&mut cache,&[RetainedStyleMutation::Resource],));- assert!(!can_retain_layout_for_tabindex(+ assert!(!can_retain_layout_for_metadata(&tree,(600.0, 300.0),&mut cache,- &[mutation("tabindex")],+ &[mutation(name)],));}}@@ -17108,11 +17267,7 @@ mod tests {/// `LayoutStyle` intentionally does not implement PartialEq because it is/// a large, evolving renderer-internal type; keeping this check centralized/// means new fields automatically enter the retained-vs-full oracle.- fn assert_computed_styles_match(- case: &str,- incremental: &DomLayout,- full: &DomLayout,- ) {+ fn assert_computed_styles_match(case: &str, incremental: &DomLayout, full: &DomLayout) {assert_eq!(incremental.styles.keys().collect::<HashSet<_>>(),full.styles.keys().collect::<HashSet<_>>(),@@ -17208,7 +17363,11 @@ mod tests {"{}: inline fragments",case.name);- assert_eq!(incremental.text_runs, full.text_runs, "{}: text runs", case.name);+ assert_eq!(+ incremental.text_runs, full.text_runs,+ "{}: text runs",+ case.name+ );assert_eq!(incremental.custom_properties, full.custom_properties,"{}: custom properties",@@ -17218,9 +17377,7 @@ mod tests {#[test]fn retained_attribute_styles_match_forced_full_selector_matrix() {- use RetainedDifferentialExpectation::{- ConservativeFallback, Incremental, ReuseAll,- };+ use RetainedDifferentialExpectation::{ConservativeFallback, Incremental, ReuseAll};let cases = [RetainedDifferentialCase {name: "self attribute selector",@@ -17520,14 +17677,7 @@ mod tests {mutation: TreeStyleMutation,expectation: RetainedDifferentialExpectation,) -> DomLayout {- finish_retained_tree_batch_case(- name,- tree,- cache,- initial,- &[mutation],- expectation,- )+ finish_retained_tree_batch_case(name, tree, cache, initial, &[mutation], expectation)}fn finish_retained_tree_batch_case(@@ -18254,12 +18404,11 @@ mod tests {tree.insert_before(old, before_b);tree.append_child(list, after_a);tree.append_child(list, after_b);- let mutations = [before_a, before_b, after_a, after_b].map(|node| {- TreeStyleMutation::Insert {+ let mutations =+ [before_a, before_b, after_a, after_b].map(|node| TreeStyleMutation::Insert {node,old_parent: None,new_parent: list,- }});finish_retained_tree_batch_case("batched first last only boundaries",@@ -18417,7 +18566,11 @@ mod tests {.into()],);let full = layout_dom(&tree, (800.0, 600.0));- assert_computed_styles_match("keyed start insertion large body branch", &incremental, &full);+ assert_computed_styles_match(+ "keyed start insertion large body branch",+ &incremental,+ &full,+ );assert_eq!(incremental.rects, full.rects);assert_eq!(telemetry.retained_fallback, 0, "{telemetry:?}");assert!(telemetry.retained_reused >= 2_000, "{telemetry:?}");@@ -18727,14 +18880,46 @@ mod tests {let node = |id: &str| tree.get_element_by_id(id).unwrap();let rect = |id: &str| -> Rect { laid.rects[&node(id)] };- assert!((rect("shell").width - 800.0).abs() < 0.01, "{:?}", rect("shell"));- assert!((rect("app").width - 800.0).abs() < 0.01, "{:?}", rect("app"));- assert!((rect("tabs").width - 800.0).abs() < 0.01, "{:?}", rect("tabs"));- assert!((rect("strip").width - 3200.0).abs() < 0.01, "{:?}", rect("strip"));- assert!((rect("pattern").width - 688.0).abs() < 0.01, "{:?}", rect("pattern"));- assert!((rect("pattern-inner").width - 672.0).abs() < 0.01, "{:?}", rect("pattern-inner"));- assert!((rect("banner-row").width - 800.0).abs() < 0.01, "{:?}", rect("banner-row"));- assert!((rect("banner").width - 290.0).abs() < 0.01, "{:?}", rect("banner"));+ assert!(+ (rect("shell").width - 800.0).abs() < 0.01,+ "{:?}",+ rect("shell")+ );+ assert!(+ (rect("app").width - 800.0).abs() < 0.01,+ "{:?}",+ rect("app")+ );+ assert!(+ (rect("tabs").width - 800.0).abs() < 0.01,+ "{:?}",+ rect("tabs")+ );+ assert!(+ (rect("strip").width - 3200.0).abs() < 0.01,+ "{:?}",+ rect("strip")+ );+ assert!(+ (rect("pattern").width - 688.0).abs() < 0.01,+ "{:?}",+ rect("pattern")+ );+ assert!(+ (rect("pattern-inner").width - 672.0).abs() < 0.01,+ "{:?}",+ rect("pattern-inner")+ );+ assert!(+ (rect("banner-row").width - 800.0).abs() < 0.01,+ "{:?}",+ rect("banner-row")+ );+ assert!(+ (rect("banner").width - 290.0).abs() < 0.01,+ "{:?}",+ rect("banner")+ );assert_eq!(laid.styles[&node("strip")].width,@@ -19081,10 +19266,20 @@ mod tests {let laid = layout_dom(&tree, (800.0, 300.0));let rect = |id: &str| laid.rects[&tree.get_element_by_id(id).unwrap()];for id in ["first", "later"] {- assert!((rect(id).width - 50.0).abs() < 0.1, "{}: {:?}", id, rect(id));+ assert!(+ (rect(id).width - 50.0).abs() < 0.1,+ "{}: {:?}",+ id,+ rect(id)+ );}for id in ["second", "last"] {- assert!((rect(id).width - 250.0).abs() < 0.1, "{}: {:?}", id, rect(id));+ assert!(+ (rect(id).width - 250.0).abs() < 0.1,+ "{}: {:?}",+ id,+ rect(id)+ );}}@@ -19101,11 +19296,27 @@ mod tests {);let laid = layout_dom(&tree, (800.0, 300.0));let rect = |id: &str| laid.rects[&tree.get_element_by_id(id).unwrap()];- assert!((rect("table").width - 300.0).abs() < 0.1, "{:?}", rect("table"));+ assert!(+ (rect("table").width - 300.0).abs() < 0.1,+ "{:?}",+ rect("table")+ );assert!((rect("first").x - 14.0).abs() < 0.1, "{:?}", rect("first"));- assert!((rect("first").width - 50.0).abs() < 0.1, "{:?}", rect("first"));- assert!((rect("second").x - 74.0).abs() < 0.1, "{:?}", rect("second"));- assert!((rect("second").width - 212.0).abs() < 0.1, "{:?}", rect("second"));+ assert!(+ (rect("first").width - 50.0).abs() < 0.1,+ "{:?}",+ rect("first")+ );+ assert!(+ (rect("second").x - 74.0).abs() < 0.1,+ "{:?}",+ rect("second")+ );+ assert!(+ (rect("second").width - 212.0).abs() < 0.1,+ "{:?}",+ rect("second")+ );}#[test]@@ -19121,9 +19332,21 @@ mod tests {);let laid = layout_dom(&tree, (800.0, 300.0));let rect = |id: &str| laid.rects[&tree.get_element_by_id(id).unwrap()];- assert!((rect("table").width - 308.0).abs() < 0.1, "{:?}", rect("table"));- assert!((rect("first").width - 50.0).abs() < 0.1, "{:?}", rect("first"));- assert!((rect("second").width - 220.0).abs() < 0.1, "{:?}", rect("second"));+ assert!(+ (rect("table").width - 308.0).abs() < 0.1,+ "{:?}",+ rect("table")+ );+ assert!(+ (rect("first").width - 50.0).abs() < 0.1,+ "{:?}",+ rect("first")+ );+ assert!(+ (rect("second").width - 220.0).abs() < 0.1,+ "{:?}",+ rect("second")+ );}#[test]@@ -19139,11 +19362,23 @@ mod tests {);let laid = layout_dom(&tree, (800.0, 300.0));let rect = |id: &str| laid.rects[&tree.get_element_by_id(id).unwrap()];- assert!((rect("table").width - 400.0).abs() < 0.1, "{:?}", rect("table"));+ assert!(+ (rect("table").width - 400.0).abs() < 0.1,+ "{:?}",+ rect("table")+ );// Final paint geometry is snapped to device pixels around the 92.5 /// 277.5 CSS-pixel track boundary.- assert!((rect("first").width - 92.5).abs() <= 0.5, "{:?}", rect("first"));- assert!((rect("second").width - 277.5).abs() <= 0.5, "{:?}", rect("second"));+ assert!(+ (rect("first").width - 92.5).abs() <= 0.5,+ "{:?}",+ rect("first")+ );+ assert!(+ (rect("second").width - 277.5).abs() <= 0.5,+ "{:?}",+ rect("second")+ );}#[test]@@ -19184,7 +19419,10 @@ mod tests {let first = laid.rects[&tree.get_element_by_id("first").unwrap()];let later = laid.rects[&tree.get_element_by_id("later").unwrap()];assert!(first.width >= 249.9, "{first:?}");- assert!((first.width - later.width).abs() < 0.1, "{first:?} {later:?}");+ assert!(+ (first.width - later.width).abs() < 0.1,+ "{first:?} {later:?}"+ );}#[test]@@ -19197,7 +19435,10 @@ mod tests {let assert_widths = |actual: Vec<f32>, expected: &[f32]| {assert_eq!(actual.len(), expected.len());for (actual, expected) in actual.iter().zip(expected) {- assert!((actual - expected).abs() < 0.01, "{actual:?} != {expected:?}");+ assert!(+ (actual - expected).abs() < 0.01,+ "{actual:?} != {expected:?}"+ );}};assert_widths(@@ -19301,7 +19542,10 @@ mod tests {Some([128, 0, 128, 255]));assert_eq!(style("physical-last").border.right, 4.0);- assert_eq!(style("physical-last").border_model.colors.right, Some([0, 128, 128, 255]));+ assert_eq!(+ style("physical-last").border_model.colors.right,+ Some([0, 128, 128, 255])+ );}#[test]@@ -19362,9 +19606,18 @@ mod tests {assert!((addon.x - (field.x + field.width)).abs() < 0.1);assert!((button.x - (addon.x + addon.width)).abs() < 0.1);assert!(((button.x + button.width) - (group.x + group.width)).abs() < 0.1);- assert!(addon.width > 80.0, "nowrap addon must keep its intrinsic width: {addon:?}");- assert!(button.width > 50.0, "nowrap button must keep its intrinsic width: {button:?}");- assert!(field.width > addon.width + button.width, "{field:?} {addon:?} {button:?}");+ assert!(+ addon.width > 80.0,+ "nowrap addon must keep its intrinsic width: {addon:?}"+ );+ assert!(+ button.width > 50.0,+ "nowrap button must keep its intrinsic width: {button:?}"+ );+ assert!(+ field.width > addon.width + button.width,+ "{field:?} {addon:?} {button:?}"+ );for cell in [field, addon, button] {assert!((cell.height - 34.0).abs() < 0.1, "{cell:?}");}@@ -20334,9 +20587,7 @@ mod tests {let generated = laid.generated_boxes.iter()- .find(|box_| {- box_.host == contents && box_.kind == GeneratedBoxKind::Before- })+ .find(|box_| box_.host == contents && box_.kind == GeneratedBoxKind::Before).expect("display:contents ::before must generate an effective grid item");assert_eq!(diff --git a/crates/obscura-render/src/inline.rs b/crates/obscura-render/src/inline.rsindex 9684c12a..bb6febf7 100644--- a/crates/obscura-render/src/inline.rs+++ b/crates/obscura-render/src/inline.rs@@ -872,10 +872,29 @@ pub struct TextEngine {loaded_families: HashMap<String, LoadedFamily>,swash: SwashCache,variable_swash: VariableSwashCache,+ shape_templates: HashMap<String, Vec<ShapeTemplate>>,+ shape_template_count: usize,+ #[cfg(test)]+ shape_template_hits: usize,items: Vec<InlineItem>,replaced: Vec<ReplacedItem>,}+// Repeated labels, table cells, and list/card rows are common, and building+// cosmic-text's attributed buffer for each identical run is measurable. Keep+// only small templates and stop admitting entries once this per-layout cache+// is full: memory stays bounded even for attacker-controlled page text.+const SHAPE_TEMPLATE_LIMIT: usize = 64;+const SHAPE_TEMPLATE_TEXT_LIMIT: usize = 256;++struct ShapeTemplate {+ font_size_bits: u32,+ line_height_bits: u32,+ wrap: Wrap,+ attrs: SpanAttrs,+ buffer: Buffer,+}+#[derive(Clone, Debug, Eq, Hash, PartialEq)]struct VariableCacheKey {glyph: CacheKey,@@ -1301,6 +1320,10 @@ impl TextEngine {loaded_families,swash: SwashCache::new(),variable_swash: VariableSwashCache::new(),+ shape_templates: HashMap::new(),+ shape_template_count: 0,+ #[cfg(test)]+ shape_template_hits: 0,items: Vec::new(),replaced: Vec::new(),}@@ -1620,7 +1643,31 @@ impl TextEngine {// ~invisible, matching the intent, and one page can never abort a worker.let cosmic_size = base_size.max(1.0);let metrics = Metrics::new(cosmic_size, line_h.max(1.0));- let mut buffer = Buffer::new(&mut self.font_system, metrics);+ let cacheable_template = clip_fills.is_empty()+ && owner_ranges.is_empty()+ && owner_boxes.is_empty()+ && boundary_events.is_empty()+ && text_len <= SHAPE_TEMPLATE_TEXT_LIMIT+ && spans.len() == 1;+ let template_text = cacheable_template.then(|| spans[0].0.as_str());+ let cached_buffer = template_text.and_then(|text| {+ self.shape_templates.get(text).and_then(|templates| {+ templates.iter().find_map(|template| {+ (template.font_size_bits == metrics.font_size.to_bits()+ && template.line_height_bits == metrics.line_height.to_bits()+ && template.wrap == layout_wrap+ && template.attrs == spans[0].1)+ .then(|| template.buffer.clone())+ })+ })+ });+ let template_hit = cached_buffer.is_some();+ #[cfg(test)]+ if template_hit {+ self.shape_template_hits += 1;+ }+ let mut buffer =+ cached_buffer.unwrap_or_else(|| Buffer::new(&mut self.font_system, metrics));// Install the used-layout mode now; intrinsic measurement temporarily// swaps to `min_content_wrap` below. Keeping those modes separate is// what prevents `overflow-wrap: break-word` from shrinking a@@ -1666,13 +1713,30 @@ impl TextEngine {(text.as_str(), attrs.to_attrs(variation_index))});let defaults = Attrs::new().family(Family::Name(FAMILY));- buffer.set_rich_text(- &mut self.font_system,- rich,- &defaults,- Shaping::Advanced,- None,- );+ if !template_hit {+ buffer.set_rich_text(+ &mut self.font_system,+ rich,+ &defaults,+ Shaping::Advanced,+ None,+ );+ if let Some(text) = template_text {+ if self.shape_template_count < SHAPE_TEMPLATE_LIMIT {+ self.shape_templates+ .entry(text.to_owned())+ .or_default()+ .push(ShapeTemplate {+ font_size_bits: metrics.font_size.to_bits(),+ line_height_bits: metrics.line_height.to_bits(),+ wrap: layout_wrap,+ attrs: spans[0].1.clone(),+ buffer: buffer.clone(),+ });+ self.shape_template_count += 1;+ }+ }+ }let marker_buffer = marker_attrs.map(|attrs| {let variation_index = attrs@@ -3859,6 +3923,32 @@ mod tests {);}+ #[test]+ fn repeated_plain_text_reuses_the_attributed_buffer_template() {+ let tree = obscura_dom::parse_html(+ "<p id='first'>repeated label</p><p id='second'>repeated label</p>",+ );+ let first = tree.get_element_by_id("first").unwrap();+ let second = tree.get_element_by_id("second").unwrap();+ let style = LayoutStyle {+ display: Display::Block,+ font_size: Some(16.0),+ line_height: Some(crate::LineHeight::Px(20.0)),+ ..Default::default()+ };+ let styles = HashMap::from([(first, style.clone()), (second, style)]);+ let mut engine = TextEngine::new();+ let first_item = engine.try_build(&tree, first, &styles).unwrap();+ let second_item = engine.try_build(&tree, second, &styles).unwrap();++ assert_eq!(engine.shape_template_count, 1);+ assert_eq!(engine.shape_template_hits, 1);+ assert_eq!(+ engine.measure(first_item, Some(120.0)),+ engine.measure(second_item, Some(120.0))+ );+ }+#[test]fn repeated_measurements_reuse_exact_results_and_preserve_final_paint() {let tree = obscura_dom::parse_html(diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rsindex 9d69c350..0992e406 100644--- a/crates/obscura-render/src/lib.rs+++ b/crates/obscura-render/src/lib.rs@@ -1413,6 +1413,9 @@ pub struct LayoutStyle {/// a real inherited CSS property). Resolved into `effectively_invisible`/// during `dom::layout_dom`'s inheritance pass.pub visibility_hidden: Option<bool>,+ /// Computed `pointer-events: none|auto`. The property is inherited, so+ /// `None` means the top-down style pass still needs the parent's value.+ pub pointer_events_none: Option<bool>,/// `opacity`, own (non-inherited) value in 0.0-1.0. `None` means the/// default of 1.0.pub opacity: Option<f32>,diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex d80059d7..bb62b0fc 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -23,9 +23,8 @@ static FONT_OBLIQUE_BYTES: &[u8] = include_bytes!("../assets/liberation-sans-oblstatic FONT_BOLD_OBLIQUE_BYTES: &[u8] = include_bytes!("../assets/liberation-sans-boldoblique.ttf");use crate::dom::{- layout_dom_with_web_fonts_and_retained_styles_with_animation_state,+ RetainedStyleMaps, layout_dom_with_web_fonts_and_retained_styles_with_animation_state,layout_dom_with_web_fonts_and_stylesheet_cache_for_media_with_animation_state,- RetainedStyleMaps,};const DEFAULT_RESOURCE_CACHE_ENTRIES: usize = 512;@@ -499,11 +498,7 @@ impl RenderResourceCache {}}- fn get_or_load_image(- &mut self,- url: &str,- profile: ImageRequestProfile,- ) -> Option<Arc<[u8]>> {+ fn get_or_load_image(&mut self, url: &str, profile: ImageRequestProfile) -> Option<Arc<[u8]>> {let key = image_resource_key(url, profile);if let Some(entry) = self.entries.get(&key) {match entry {@@ -926,12 +921,7 @@ impl PreparedRender {/// animation. Finite animations stop producing compositor damage after/// their active interval; paused and zero-duration animations never do.pub fn has_active_css_animations(&self) -> bool {- self.has_active_waapi_animations- || self- .layout- .styles- .values()- .any(css_animation_is_active)+ self.has_active_waapi_animations || self.layout.styles.values().any(css_animation_is_active)}fn has_active_declarative_css_animations(&self) -> bool {@@ -958,12 +948,15 @@ impl PreparedRender {let mut updates = Vec::new();let mut has_transform_effect = false;let mut has_opacity_effect = false;- for node in timeline.waapi_nodes().into_iter().filter(|node| connected(*node)) {+ for node in timeline+ .waapi_nodes()+ .into_iter()+ .filter(|node| connected(*node))+ {let Some(style) = self.layout.styles.get(&node) else {return false;};- let Some(sampled) =- crate::css::resample_visual_waapi(timeline, node, style, sample)+ let Some(sampled) = crate::css::resample_visual_waapi(timeline, node, style, sample)else {return false;};@@ -980,7 +973,8 @@ impl PreparedRender {return false;}for (node, sampled) in updates {- let style = self.layout+ let style = self+ .layout.styles.get_mut(&node).expect("WAAPI target passed preflight");@@ -997,11 +991,9 @@ impl PreparedRender {// already rejected any containing-block topology change. Reuse// the immutable viewport-fixed ownership instead of walking the// document again on every animation frame.- let derived = self.layout.derived_geometry_with_fixed(- tree,- self.viewport,- &self.viewport_fixed,- );+ let derived =+ self.layout+ .derived_geometry_with_fixed(tree, self.viewport, &self.viewport_fixed);self.content_size = derived.content_size;self.sticky = derived.sticky;self.scroll_tree = derived.scroll_tree;@@ -1016,10 +1008,7 @@ impl PreparedRender {/// to `sample`. The prepared style/paint sample deliberately stays/// unchanged; a later computed-style or paint consumer will materialize/// the exact requested sample through the normal retained-style path.- pub fn can_reuse_geometry_for_animation_sample(- &self,- sample: crate::AnimationSample,- ) -> bool {+ pub fn can_reuse_geometry_for_animation_sample(&self, sample: crate::AnimationSample) -> bool {sample.mode == crate::AnimationSampleMode::DocumentTime&& self.animation_sample.mode == crate::AnimationSampleMode::DocumentTime&& sample.time.milliseconds >= self.animation_sample.time.milliseconds@@ -1068,11 +1057,7 @@ impl PreparedRender {self.clamp_scroll_for_viewport(requested, self.viewport)}- fn clamp_scroll_for_viewport(- &self,- requested: (f32, f32),- viewport: (f32, f32),- ) -> (f32, f32) {+ fn clamp_scroll_for_viewport(&self, requested: (f32, f32), viewport: (f32, f32)) -> (f32, f32) {let clamp_axis = |requested: f32, content: f32, viewport: f32| {if requested.is_finite() {crate::quantize_scroll_value(requested, 1.0)@@ -1109,12 +1094,9 @@ impl PreparedRender {.flatten().and_then(|owner| cumulative.get(owner.index()).copied()).unwrap_or((0.0, 0.0));- let sticky = self.sticky.resolved_translation_for(- id,- self.viewport,- &self.scroll_tree,- &cumulative,- );+ let sticky =+ self.sticky+ .resolved_translation_for(id, self.viewport, &self.scroll_tree, &cumulative);movement.0 += sticky.0;movement.1 += sticky.1;movement@@ -1361,6 +1343,135 @@ impl PreparedRender {))}+ /// Whether hit testing must ignore this element's generated box.+ pub fn pointer_events_none(&self, id: obscura_dom::tree::NodeId) -> bool {+ self.layout+ .styles+ .get(&id)+ .and_then(|style| style.pointer_events_none)+ .unwrap_or(false)+ }++ /// Topmost DOM element at a viewport point, using the retained layout and+ /// the same stacking-context bands as paint. This keeps CSSOM hit testing+ /// off the JS-side O(elements) geometry loop and prevents a later DOM node+ /// in a negative z-index layer from covering normal-flow controls.+ pub fn hit_test(+ &self,+ tree: &DomTree,+ scroll: &ResolvedScrollState,+ x: f32,+ y: f32,+ ) -> Option<obscura_dom::tree::NodeId> {+ fn stacking_path(+ tree: &DomTree,+ laid: &crate::DomLayout,+ id: obscura_dom::tree::NodeId,+ ) -> Vec<i32> {+ // Stacking contexts are inherited through the DOM ancestor chain.+ // The rendered-parent helper deliberately skips some framework+ // wrapper boxes; using it here can detach a control from a fixed+ // ancestor's context and make the ancestor win its own hit test.+ let mut ancestors = tree.ancestors(id);+ ancestors.insert(0, id);+ ancestors.reverse();+ ancestors+ .into_iter()+ .filter_map(|node| stacking_z_index(tree, laid, node))+ .collect()+ }++ fn compare_stacking_paths(a: &[i32], b: &[i32]) -> std::cmp::Ordering {+ use std::cmp::Ordering;+ let common = a.len().min(b.len());+ for index in 0..common {+ let order = a[index].cmp(&b[index]);+ if order != Ordering::Equal {+ return order;+ }+ }+ if a.len() == b.len() {+ return Ordering::Equal;+ }+ // Ending the path means normal-flow content in this stacking+ // context: it paints after a negative child context and before a+ // zero-or-positive child context.+ if a.len() == common {+ if b[common] < 0 {+ Ordering::Greater+ } else {+ Ordering::Less+ }+ } else if a[common] < 0 {+ Ordering::Less+ } else {+ Ordering::Greater+ }+ }++ if !x.is_finite()+ || !y.is_finite()+ || x < 0.0+ || y < 0.0+ || x > self.viewport.0+ || y > self.viewport.1+ {+ return None;+ }+ let point = crate::Rect {+ x,+ y,+ // `f32::EPSILON` is smaller than one ULP at ordinary viewport+ // coordinates, so x + width can round back to x and appear empty+ // to `intersect_rect`. A sub-pixel probe remains point-like while+ // retaining a representable extent across the supported viewport.+ width: 0.001,+ height: 0.001,+ };+ let mut best: Option<(Vec<i32>, usize, usize, obscura_dom::tree::NodeId)> = None;+ for (order, id) in crate::dom::rendered_descendants(tree, tree.document())+ .into_iter()+ .enumerate()+ {+ let Some(style) = self.layout.styles.get(&id) else {+ continue;+ };+ if style.display == crate::Display::None+ || style.display_contents+ || style.visibility_hidden.unwrap_or(false)+ || style.pointer_events_none.unwrap_or(false)+ {+ continue;+ }+ let Some(rect) = self.viewport_rect_with_scroll(id, scroll) else {+ continue;+ };+ if x < rect.x || x > rect.x + rect.width || y < rect.y || y > rect.y + rect.height {+ continue;+ }+ if scroll+ .inherited_clip_for(id)+ .is_some_and(|clip| clip.intersect_rect(&point).is_none())+ {+ continue;+ }+ let path = stacking_path(tree, &self.layout, id);+ let depth = tree.ancestors(id).len();+ let replace = best+ .as_ref()+ .is_none_or(|(best_path, best_depth, best_order, _)| {+ compare_stacking_paths(&path, best_path)+ .then_with(|| depth.cmp(best_depth))+ .then_with(|| order.cmp(best_order))+ .is_gt()+ });+ if replace {+ best = Some((path, depth, order, id));+ }+ }+ best.map(|(_, _, _, id)| id)+ }+/// A compact CSSOM snapshot derived from the same final cascade and/// layout used by paint and geometry. Keeping this on `PreparedRender`/// lets script fetch all high-traffic computed properties in one op,@@ -1450,6 +1561,15 @@ impl PreparedRender {}.to_string(),);+ out.insert(+ "pointer-events",+ if style.pointer_events_none.unwrap_or(false) {+ "none"+ } else {+ "auto"+ }+ .to_string(),+ );out.insert("opacity", css_number(style.opacity.unwrap_or(1.0)));out.insert("background-color",@@ -1599,36 +1719,16 @@ impl PreparedRender {.to_string(),);- let overflow_axis = |specified: u8, clipped: bool, scroll: bool| {- if scroll {- // The compact layout model intentionally merges- // hidden/auto/scroll for clipping. `auto` is the least- // surprising computed scroll-container value.- "auto"- } else if specified == 1 || clipped {- "clip"- } else {- "visible"- }+ let overflow_axis = |computed: u8| match computed {+ 1 => "clip",+ 2 => "hidden",+ 3 => "scroll",+ 4 => "auto",+ _ => "visible",};- out.insert(- "overflow-x",- overflow_axis(- style.overflow_specified_x,- style.overflow_clip_x,- style.overflow_scroll_x,- )- .to_string(),- );- out.insert(- "overflow-y",- overflow_axis(- style.overflow_specified_y,- style.overflow_clip_y,- style.overflow_scroll_y,- )- .to_string(),- );+ let (overflow_x, overflow_y) = crate::style::computed_overflow_axes(style);+ out.insert("overflow-x", overflow_axis(overflow_x).to_string());+ out.insert("overflow-y", overflow_axis(overflow_y).to_string());for (name, value, auto) in [("margin-top", style.margin.top, style.margin_auto[0]),@@ -1948,10 +2048,22 @@ impl PreparedRender {}let fixed_box = matches!(style.width, crate::Dimension::Px(_))&& matches!(style.height, crate::Dimension::Px(_))- && matches!(style.min_width, crate::Dimension::Auto | crate::Dimension::Px(_))- && matches!(style.min_height, crate::Dimension::Auto | crate::Dimension::Px(_))- && matches!(style.max_width, crate::Dimension::Auto | crate::Dimension::Px(_))- && matches!(style.max_height, crate::Dimension::Auto | crate::Dimension::Px(_))+ && matches!(+ style.min_width,+ crate::Dimension::Auto | crate::Dimension::Px(_)+ )+ && matches!(+ style.min_height,+ crate::Dimension::Auto | crate::Dimension::Px(_)+ )+ && matches!(+ style.max_width,+ crate::Dimension::Auto | crate::Dimension::Px(_)+ )+ && matches!(+ style.max_height,+ crate::Dimension::Auto | crate::Dimension::Px(_)+ )&& !style.width_fit_content&& style.size_expressions.iter().all(Option::is_none);if !fixed_box {@@ -2019,11 +2131,7 @@ fn radius_value_css(value: crate::RadiusValue) -> String {fn corner_radius_css(radius: crate::CornerRadius) -> String {let x = radius_value_css(radius.x);let y = radius_value_css(radius.y);- if x == y {- x- } else {- format!("{x} {y}")- }+ if x == y { x } else { format!("{x} {y}") }}fn css_color([r, g, b, a]: [u8; 4]) -> String {@@ -2196,13 +2304,8 @@ pub fn paint_dom_scrolled_at_animation_time_with_surface_color_and_resources(surface_color: [u8; 4],resources: &mut RenderResourceCache,) -> Option<Pixmap> {- let mut prepared = prepare_dom_at_animation_time(- tree,- viewport,- base_url,- resources,- animation_sample_time,- )?;+ let mut prepared =+ prepare_dom_at_animation_time(tree, viewport, base_url, resources, animation_sample_time)?;paint_prepared_with_surface_color(tree, &mut prepared, resources, scroll, surface_color)}@@ -2505,12 +2608,7 @@ pub fn prepare_dom_with_retained_styles_with_animation_state(&& previous.base_url.as_deref() == base_url&& !previous.has_dynamic_fonts&& dynamic_fonts.is_empty()- && crate::dom::can_retain_layout_for_tabindex(- tree,- viewport,- stylesheet_cache,- mutations,- )+ && crate::dom::can_retain_layout_for_metadata(tree, viewport, stylesheet_cache, mutations)&& (!sample_changed|| (forward_document_sample&& previous.advance_inactive_animation_sample_time(animation_sample.time)))@@ -2519,11 +2617,7 @@ pub fn prepare_dom_with_retained_styles_with_animation_state(}let sampled_animation_mutations = sample_changed.then(|| {- retained_animation_restyle_mutations(- tree,- &previous.layout.styles,- animation_timeline,- )+ retained_animation_restyle_mutations(tree, &previous.layout.styles, animation_timeline)}).unwrap_or_default();let animation_mutations;@@ -2568,8 +2662,7 @@ fn retained_animation_restyle_mutations(let mut css_nodes = styles.iter().filter_map(|(node, style)| {- (style.animation_name.is_some() && style.animation_has_render_effect)- .then_some(*node)+ (style.animation_name.is_some() && style.animation_has_render_effect).then_some(*node)}).collect::<std::collections::HashSet<_>>();css_nodes.retain(|node| connected(*node));@@ -2639,7 +2732,8 @@ fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_internal(svg_font_database()};let mut laid = match retained {- Some((retained, mutations)) => layout_dom_with_web_fonts_and_retained_styles_with_animation_state(+ Some((retained, mutations)) => {+ layout_dom_with_web_fonts_and_retained_styles_with_animation_state(tree,viewport,&intrinsic,@@ -2649,7 +2743,8 @@ fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_internal(mutations,animation_sample,animation_timeline,- ),+ )+ }None => layout_dom_with_web_fonts_and_stylesheet_cache_for_media_with_animation_state(tree,viewport,@@ -3339,9 +3434,7 @@ fn paint_canvas_background(if let Some(color) = style.background_color {let mut paint = Paint::default();- paint.set_color(Color::from_rgba8(- color[0], color[1], color[2], color[3],- ));+ paint.set_color(Color::from_rgba8(color[0], color[1], color[2], color[3]));pixmap.fill_path(&path,&paint,@@ -4062,8 +4155,8 @@ fn paint_laid_dom_scrolled(if style.effectively_invisible {continue;}- let background_transfers_to_canvas = canvas_background- .is_some_and(|canvas| nid == canvas.root || nid == canvas.source);+ let background_transfers_to_canvas =+ canvas_background.is_some_and(|canvas| nid == canvas.root || nid == canvas.source);// A `transform: translate()` on this element or any ancestor offsets// this element's whole painted box (and, applied per node, its whole@@ -4461,21 +4554,9 @@ fn paint_laid_dom_scrolled(}if !paints_inline_fragments {- paint_css_border(- &mut pixmap,- &rect,- style,- element_clip_mask,- raster_scale,- );+ paint_css_border(&mut pixmap, &rect, style, element_clip_mask, raster_scale);}- paint_css_outline(- &mut pixmap,- &rect,- style,- element_clip_mask,- raster_scale,- );+ paint_css_outline(&mut pixmap, &rect, style, element_clip_mask, raster_scale);if box_on_surface && matches!(name.local.as_ref(), "img" | "video") {if let Some(source) = selected_images.get(&nid) {@@ -4745,8 +4826,8 @@ fn paint_laid_dom_scrolled(}}- let input_type = (name.local.as_ref() == "input")- .then(|| node.get_attribute("type").unwrap_or("text"));+ let input_type =+ (name.local.as_ref() == "input").then(|| node.get_attribute("type").unwrap_or("text"));let checkable = input_type.is_some_and(|kind| {kind.eq_ignore_ascii_case("checkbox") || kind.eq_ignore_ascii_case("radio")});@@ -4761,27 +4842,65 @@ fn paint_laid_dom_scrolled(let x = rect.x + (rect.width - size) / 2.0;let y = rect.y + (rect.height - size) / 2.0;let shape = if is_radio {- PathBuilder::from_circle(x + size / 2.0, y + size / 2.0, (size - 1.0).max(0.0) / 2.0)+ PathBuilder::from_circle(+ x + size / 2.0,+ y + size / 2.0,+ (size - 1.0).max(0.0) / 2.0,+ )} else {- tiny_skia::Rect::from_xywh(x + 0.5, y + 0.5, (size - 1.0).max(0.0), (size - 1.0).max(0.0))+ tiny_skia::Rect::from_xywh(+ x + 0.5,+ y + 0.5,+ (size - 1.0).max(0.0),+ (size - 1.0).max(0.0),+ ).map(PathBuilder::from_rect)};if let Some(shape) = shape {let mut control_paint = Paint::default();let selected = checked || indeterminate;- let color = if disabled { [160, 160, 160, 255] } else if selected { [0, 117, 255, 255] } else { [118, 118, 118, 255] };+ let color = if disabled {+ [160, 160, 160, 255]+ } else if selected {+ [0, 117, 255, 255]+ } else {+ [118, 118, 118, 255]+ };control_paint.set_color(Color::from_rgba8(color[0], color[1], color[2], color[3]));control_paint.anti_alias = true;- let stroke = tiny_skia::Stroke { width: 1.0, ..Default::default() };+ let stroke = tiny_skia::Stroke {+ width: 1.0,+ ..Default::default()+ };if !is_radio && selected {- pixmap.fill_path(&shape, &control_paint, FillRule::Winding, raster_transform(raster_scale), element_clip_mask);+ pixmap.fill_path(+ &shape,+ &control_paint,+ FillRule::Winding,+ raster_transform(raster_scale),+ element_clip_mask,+ );} else {- pixmap.stroke_path(&shape, &control_paint, &stroke, raster_transform(raster_scale), element_clip_mask);+ pixmap.stroke_path(+ &shape,+ &control_paint,+ &stroke,+ raster_transform(raster_scale),+ element_clip_mask,+ );}if selected {if is_radio {- if let Some(dot) = PathBuilder::from_circle(x + size / 2.0, y + size / 2.0, size * 0.25) {- pixmap.fill_path(&dot, &control_paint, FillRule::Winding, raster_transform(raster_scale), element_clip_mask);+ if let Some(dot) =+ PathBuilder::from_circle(x + size / 2.0, y + size / 2.0, size * 0.25)+ {+ pixmap.fill_path(+ &dot,+ &control_paint,+ FillRule::Winding,+ raster_transform(raster_scale),+ element_clip_mask,+ );}} else {let mut mark = PathBuilder::new();@@ -4794,8 +4913,17 @@ fn paint_laid_dom_scrolled(}if let Some(mark) = mark.finish() {control_paint.set_color(Color::WHITE);- let stroke = tiny_skia::Stroke { width: (size * 0.14).max(1.0), ..Default::default() };- pixmap.stroke_path(&mark, &control_paint, &stroke, raster_transform(raster_scale), element_clip_mask);+ let stroke = tiny_skia::Stroke {+ width: (size * 0.14).max(1.0),+ ..Default::default()+ };+ pixmap.stroke_path(+ &mark,+ &control_paint,+ &stroke,+ raster_transform(raster_scale),+ element_clip_mask,+ );}}}@@ -4807,11 +4935,14 @@ fn paint_laid_dom_scrolled(// not real content), so paint it directly from the attribute instead// of going through `paint_text_node`.if !checkable && (name.local.as_ref() == "input" || name.local.as_ref() == "textarea") {- let live_value = tree.form_control_state(nid).and_then(|control| control.value);- let value = live_value.as_deref().or_else(|| node.get_attribute("value"));+ let live_value = tree+ .form_control_state(nid)+ .and_then(|control| control.value);+ let value = live_value+ .as_deref()+ .or_else(|| node.get_attribute("value"));let has_value = value.is_some_and(|v| !v.is_empty())- || (name.local.as_ref() == "textarea"- && !tree.text_content(nid).is_empty());+ || (name.local.as_ref() == "textarea" && !tree.text_content(nid).is_empty());// A text `<input>`'s value is not a DOM text node either, so it// needs painting from its live state, falling back to the attribute.// Without this the@@ -4828,7 +4959,8 @@ fn paint_laid_dom_scrolled(let color = style.color.unwrap_or([0, 0, 0, 255]);let masked;let shown = if input_type- .is_some_and(|kind| kind.eq_ignore_ascii_case("password")) {+ .is_some_and(|kind| kind.eq_ignore_ascii_case("password"))+ {masked = "\u{2022}".repeat(value.chars().count());masked.as_str()} else {@@ -4993,14 +5125,12 @@ fn paint_surface_rect(pixmap: &Pixmap, raster_scale: f32) -> crate::Rect {}}-fn rect_intersects_paint_surface(- rect: &crate::Rect,- pixmap: &Pixmap,- raster_scale: f32,-) -> bool {+fn rect_intersects_paint_surface(rect: &crate::Rect, pixmap: &Pixmap, raster_scale: f32) -> bool {rect.width > 0.0&& rect.height > 0.0- && rect.intersect(&paint_surface_rect(pixmap, raster_scale)).is_some()+ && rect+ .intersect(&paint_surface_rect(pixmap, raster_scale))+ .is_some()}/// Conservative ink overflow for the non-text primitives emitted by one CSS@@ -5092,8 +5222,7 @@ fn paint_inline_fragment_decorations(Some(clip) => ink.intersect(&clip),None => Some(ink),};- if !visible_ink- .is_some_and(|ink| rect_intersects_paint_surface(&ink, pixmap, raster_scale))+ if !visible_ink.is_some_and(|ink| rect_intersects_paint_surface(&ink, pixmap, raster_scale)){continue;}@@ -5283,12 +5412,8 @@ struct ScrollPaintState<'a> {viewport_fixed: &'a std::collections::HashSet<obscura_dom::tree::NodeId>,sticky: Arc<std::collections::HashMap<obscura_dom::tree::NodeId, (f32, f32)>>,sticky_clips: Arc<std::collections::HashMap<obscura_dom::tree::NodeId, (f32, f32)>>,- viewport_fixed_clips: Arc<- std::collections::HashMap<- obscura_dom::tree::NodeId,- Option<crate::dom::OverflowClip>,- >,- >,+ viewport_fixed_clips:+ Arc<std::collections::HashMap<obscura_dom::tree::NodeId, Option<crate::dom::OverflowClip>>>,resolved: Option<&'a ResolvedScrollState>,clip_scope_root: Option<obscura_dom::tree::NodeId>,surface_extent: Option<(f32, f32)>,@@ -5301,10 +5426,7 @@ fn viewport_fixed_clip_map(laid: &crate::DomLayout,viewport_fixed: &std::collections::HashSet<obscura_dom::tree::NodeId>,sticky: &std::collections::HashMap<obscura_dom::tree::NodeId, (f32, f32)>,-) -> std::collections::HashMap<- obscura_dom::tree::NodeId,- Option<crate::dom::OverflowClip>,-> {+) -> std::collections::HashMap<obscura_dom::tree::NodeId, Option<crate::dom::OverflowClip>> {fn walk(tree: &DomTree,laid: &crate::DomLayout,@@ -5339,15 +5461,7 @@ fn viewport_fixed_clip_map(};for child in crate::dom::rendered_children(tree, id) {if viewport_fixed.contains(&child) {- walk(- tree,- laid,- viewport_fixed,- sticky,- child,- next.clone(),- out,- );+ walk(tree, laid, viewport_fixed, sticky, child, next.clone(), out);}}}@@ -5357,15 +5471,7 @@ fn viewport_fixed_clip_map(let starts_subtree = crate::dom::rendered_parent(tree, id).is_none_or(|parent| !viewport_fixed.contains(&parent));if starts_subtree {- walk(- tree,- laid,- viewport_fixed,- sticky,- id,- None,- &mut out,- );+ walk(tree, laid, viewport_fixed, sticky, id, None, &mut out);}}out@@ -5417,12 +5523,8 @@ impl<'a> ScrollPaintState<'a> {std::collections::HashMap::new()});let sticky_clips = Arc::new(sticky_layout.clip_translations_from(&sticky));- let viewport_fixed_clips = Arc::new(viewport_fixed_clip_map(- tree,- laid,- viewport_fixed,- &sticky,- ));+ let viewport_fixed_clips =+ Arc::new(viewport_fixed_clip_map(tree, laid, viewport_fixed, &sticky));(sticky, sticky_clips, viewport_fixed_clips)};Self {@@ -6259,8 +6361,7 @@ fn paint_box_shadow(let bottom = (shadow_bounds.y + shadow_bounds.height).ceil().min(pixmap.height() as f32) as i32;- let Some(mut shadow_pixmap) = Pixmap::new((right - left) as u32, (bottom - top) as u32)- else {+ let Some(mut shadow_pixmap) = Pixmap::new((right - left) as u32, (bottom - top) as u32) else {return;};let local_rect = crate::Rect {@@ -6268,14 +6369,12 @@ fn paint_box_shadow(y: rect.y - top as f32,..*rect};- let Some(mut shadow_mask) =- rounded_box_clip_mask_radii(+ let Some(mut shadow_mask) = rounded_box_clip_mask_radii(shadow_pixmap.width(),shadow_pixmap.height(),&local_rect,border_radii,- )- else {+ ) else {return;};shadow_mask.invert();@@ -6459,13 +6558,7 @@ pub fn screenshot_png_scrolled_at_animation_time(scroll: (f32, f32),animation_sample_time: crate::AnimationSampleTime,) -> Option<Vec<u8>> {- paint_dom_scrolled_at_animation_time(- tree,- viewport,- base_url,- scroll,- animation_sample_time,- )+ paint_dom_scrolled_at_animation_time(tree, viewport, base_url, scroll, animation_sample_time).and_then(|pixmap| pixmap.encode_png().ok())}@@ -6540,13 +6633,7 @@ pub fn screenshot_prepared_with_scroll_and_surface_color(scroll: &ResolvedScrollState,surface_color: [u8; 4],) -> Option<Vec<u8>> {- paint_prepared_with_scroll_and_surface_color(- tree,- prepared,- resources,- scroll,- surface_color,- )?+ paint_prepared_with_scroll_and_surface_color(tree, prepared, resources, scroll, surface_color)?.encode_png().ok()}@@ -8761,9 +8848,7 @@ fn paint_in_flow_generated_box(Some(clip) => ink.intersect(&clip),None => Some(ink),};- if !visible_ink- .is_some_and(|ink| rect_intersects_paint_surface(&ink, pixmap, raster_scale))- {+ if !visible_ink.is_some_and(|ink| rect_intersects_paint_surface(&ink, pixmap, raster_scale)) {return;}let ancestor_clip_mask = overflow_clip.as_ref().and_then(|clip| {@@ -9015,8 +9100,7 @@ fn paint_positioned_pseudo(width,height,};- let ancestor_clip = ancestor_overflow_clip- .map(|clip| clip.viewport_rect(clip_extent));+ let ancestor_clip = ancestor_overflow_clip.map(|clip| clip.viewport_rect(clip_extent));let visible = match ancestor_clip {Some(clip) => rect.intersect(&clip),None => Some(rect),@@ -9025,9 +9109,8 @@ fn paint_positioned_pseudo(if !rect_intersects_paint_surface(&non_text_ink_bounds(&rect, style), pixmap, raster_scale) {return;}- let ancestor_clip_mask = ancestor_overflow_clip.and_then(|clip| {- overflow_clip_mask(pixmap.width(), pixmap.height(), clip, clip_extent)- });+ let ancestor_clip_mask = ancestor_overflow_clip+ .and_then(|clip| overflow_clip_mask(pixmap.width(), pixmap.height(), clip, clip_extent));let radius = style.border_model.radii.resolve(rect.width, rect.height);let clip_path_mask = style.clip_path.as_ref().and_then(|polygon| {polygon_clip_mask(@@ -9670,11 +9753,9 @@ fn paint_canvas_surface(pixel[1] = ((pixel[1] as u32 * alpha + 127) / 255) as u8;pixel[2] = ((pixel[2] as u32 * alpha + 127) / 255) as u8;}- let Some(content) = tiny_skia::PixmapRef::from_bytes(- &premultiplied,- surface.width,- surface.height,- ) else {+ let Some(content) =+ tiny_skia::PixmapRef::from_bytes(&premultiplied, surface.width, surface.height)+ else {return false;};@@ -9801,9 +9882,7 @@ fn paint_image(image_dimensions(&bytes).map(|(w, h)| (w as f32, h as f32))};match intrinsic {- Some((iw, ih)) => {- object_fit_dest_positioned(rect, iw, ih, object_fit, object_position)- }+ Some((iw, ih)) => object_fit_dest_positioned(rect, iw, ih, object_fit, object_position),None => *rect,}};@@ -9976,7 +10055,9 @@ fn svg_image_intrinsic_metadata(bytes: &[u8]) -> Option<crate::ReplacedIntrinsic// subset whose quoted declarations may themselves contain `>`.let mut quote = None;let mut subset_depth = 0usize;- let end = remaining.char_indices().find_map(|(index, ch)| match quote {+ let end = remaining+ .char_indices()+ .find_map(|(index, ch)| match quote {Some(open) if ch == open => {quote = None;None@@ -10100,8 +10181,11 @@ fn svg_image_intrinsic_metadata(bytes: &[u8]) -> Option<crate::ReplacedIntrinsic.map(str::parse::<f32>).collect::<Result<Vec<_>, _>>().ok()?;- (values.len() == 4 && values[2].is_finite() && values[3].is_finite()- && values[2] > 0.0 && values[3] > 0.0)+ (values.len() == 4+ && values[2].is_finite()+ && values[3].is_finite()+ && values[2] > 0.0+ && values[3] > 0.0).then_some(values[2] / values[3])});let ratio = match (width, height) {@@ -10216,10 +10300,7 @@ fn cached_overflow_clip_mask(// `clip_scope_root` can synthesize a temporary rounded chain. Keeping its// root Arc alongside the pointer-based key prevents allocator reuse from// making a later, different chain alias this entry during the same paint.- cache.insert(- key,- (clip.rounded_chain().cloned(), Arc::clone(&mask)),- );+ cache.insert(key, (clip.rounded_chain().cloned(), Arc::clone(&mask)));Some(mask)}@@ -10413,8 +10494,9 @@ fn has_inline_svg_text(tree: &DomTree) -> bool {.into_iter().any(|nid| {tree.get_node(nid).is_some_and(|node| {- node.as_element()- .is_some_and(|name| matches!(name.local.as_ref(), "text" | "tspan" | "textPath"))+ node.as_element().is_some_and(|name| {+ matches!(name.local.as_ref(), "text" | "tspan" | "textPath")+ })})})}@@ -10655,11 +10737,9 @@ fn serialize_svg_node(let properties = custom_properties.and_then(|all| all.get(&nid)).map_or(&empty, std::rc::Rc::as_ref);- let Some(resolved) = resolve_svg_presentation_value(- aname,- attr.value.as_ref(),- properties,- ) else {+ let Some(resolved) =+ resolve_svg_presentation_value(aname, attr.value.as_ref(), properties)+ else {// A var() failure makes the declaration invalid at// computed value time. Omitting this low-specificity// presentation attribute lets usvg apply the property's@@ -11076,10 +11156,7 @@ fn inject_external_sprites(let properties = custom_properties.and_then(|all| all.get(&root)).map_or(&empty, std::rc::Rc::as_ref);- defs.push_str(&resolve_svg_markup_presentation_vars(- &symbol,- properties,- ));+ defs.push_str(&resolve_svg_markup_presentation_vars(&symbol, properties));rewrites.push((href.clone(), format!("#{frag}")));}if defs.is_empty() {@@ -11156,10 +11233,7 @@ fn resolve_svg_tag_presentation_vars(properties: &std::collections::HashMap<String, String>,) -> String {let bytes = tag.as_bytes();- if bytes.len() < 3- || bytes[0] != b'<'- || matches!(bytes[1], b'/' | b'!' | b'?')- {+ if bytes.len() < 3 || bytes[0] != b'<' || matches!(bytes[1], b'/' | b'!' | b'?') {return tag.to_string();}let mut cursor = 1;@@ -11623,16 +11697,12 @@ mod tests {);let opaque_center = pixmap.pixel(115, 35).expect("opaque center");assert!(- opaque_center.green() > 245- && opaque_center.red() < 10- && opaque_center.blue() < 10,+ opaque_center.green() > 245 && opaque_center.red() < 10 && opaque_center.blue() < 10,"opaque backgrounds must continue to cover the shadow: {opaque_center:?}");let rounded_corner = pixmap.pixel(21, 71).expect("rounded corner shadow");assert!(- rounded_corner.red() < 10- && rounded_corner.green() < 10- && rounded_corner.blue() < 10,+ rounded_corner.red() < 10 && rounded_corner.green() < 10 && rounded_corner.blue() < 10,"the hole must follow the rounded border box rather than its rectangular bounds: {rounded_corner:?}");let blurred_center = pixmap.pixel(115, 85).expect("blurred center");@@ -11647,9 +11717,7 @@ mod tests {);let blurred_edge = pixmap.pixel(142, 85).expect("blurred edge");assert!(- blurred_edge.red() < 240- && blurred_edge.green() < 240- && blurred_edge.blue() < 240,+ blurred_edge.red() < 240 && blurred_edge.green() < 240 && blurred_edge.blue() < 240,"the issue's 2px 2px 3px shadow must retain ink outside the box: {blurred_edge:?}");}@@ -11680,10 +11748,12 @@ mod tests {.expect("the real root after a comment");assert_eq!(commented.natural_size(), Some((12.0, 8.0)));- assert!(svg_image_intrinsic_metadata(+ assert!(+ svg_image_intrinsic_metadata(br#"<svg xmlns='http://www.w3.org/2000/svg' width='10' height='20'><g>"#,)- .is_none());+ .is_none()+ );}#[test]@@ -11769,12 +11839,18 @@ mod tests {);}assert_eq!(- (rect("#intrinsic-raster").width, rect("#intrinsic-raster").height),+ (+ rect("#intrinsic-raster").width,+ rect("#intrinsic-raster").height+ ),(2.0, 3.0),"a decoded image with real intrinsic axes must not stretch-fit");assert_eq!(- (rect("#positioned-image").width, rect("#positioned-image").height),+ (+ rect("#positioned-image").width,+ rect("#positioned-image").height+ ),(320.0, 320.0),"a definite positioned border-box honors edges and min/max widths");@@ -11784,12 +11860,8 @@ mod tests {"a floated percentage column resolves against its reliable containing width");- let display = |selector| {- prepared- .computed_style(node(selector))- .unwrap()["display"]- .clone()- };+ let display =+ |selector| prepared.computed_style(node(selector)).unwrap()["display"].clone();assert_eq!(display("#direct"), "inline");assert_eq!(display("#anchored"), "inline");assert_eq!(display("#authored-inline"), "inline");@@ -11817,8 +11889,8 @@ mod tests {</body></html>"#,);let mut resources = RenderResourceCache::default();- let mut prepared = prepare_dom(&tree, (200.0, 130.0), None, &mut resources)- .expect("placeholder layout");+ let mut prepared =+ prepare_dom(&tree, (200.0, 130.0), None, &mut resources).expect("placeholder layout");let node = |selector| tree.query_selector(selector).unwrap().unwrap();assert!(@@ -11859,7 +11931,10 @@ mod tests {}).count()};- assert!(non_white(0) > 10, "the native default placeholder must paint");+ assert!(+ non_white(0) > 10,+ "the native default placeholder must paint"+ );assert!((30..60).any(|y| (0..180).any(|x| {let pixel = pixmap.pixel(x, y).unwrap();@@ -11867,7 +11942,11 @@ mod tests {})),"the authored placeholder color must reach glyph paint");- assert_eq!(non_white(60), 0, "opacity:0 must suppress placeholder glyphs");+ assert_eq!(+ non_white(60),+ 0,+ "opacity:0 must suppress placeholder glyphs"+ );// `#filled` carries `value="actual"`, so the placeholder is suppressed// and the value paints in its place — Chromium 147 renders the value// here too. Assert glyphs are present *and* that they are the value's@@ -11907,7 +11986,10 @@ mod tests {cache.set_sync_loading_enabled(previous);cache.seed(url.to_string(), vec![9, 8, 7]);- assert_eq!(cache.get_or_load(url, false).as_deref(), Some([9, 8, 7].as_slice()));+ assert_eq!(+ cache.get_or_load(url, false).as_deref(),+ Some([9, 8, 7].as_slice())+ );assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);}@@ -11920,10 +12002,15 @@ mod tests {cache.set_sync_loading_enabled(false);assert!(cache.get_or_load(font, true).is_none());- assert!(cache.get_or_load(font, true).is_none(), "a repeated miss is reported once");- assert!(cache+ assert!(+ cache.get_or_load(font, true).is_none(),+ "a repeated miss is reported once"+ );+ assert!(+ cache.get_or_load_image(image, ImageRequestProfile::CorsInclude)- .is_none());+ .is_none()+ );assert!(cache.has_sync_misses());assert_eq!(cache.take_sync_misses(),@@ -11944,9 +12031,11 @@ mod tests {assert!(!cache.has_sync_misses(), "a hit is not a miss");cache.set_sync_loading_enabled(true);- assert!(cache+ assert!(+ cache.get_or_load("https://example.test/other.png", false)- .is_some());+ .is_some()+ );assert!(!cache.has_sync_misses(),"the synchronous compatibility loader never reports a miss"@@ -11962,17 +12051,23 @@ mod tests {);cache.set_sync_loading_enabled(false);- assert!(cache+ assert!(+ cache.get_or_load("https://example.test/first.png", false)- .is_none());- assert!(cache+ .is_none()+ );+ assert!(+ cache.get_or_load("https://example.test/second.png", false)- .is_none());+ .is_none()+ );assert_eq!(cache.take_sync_misses().len(), 1);- assert!(cache+ assert!(+ cache.get_or_load("https://example.test/second.png", false)- .is_none());+ .is_none()+ );assert_eq!(cache.take_sync_misses().len(),1,@@ -12012,7 +12107,13 @@ mod tests {let node = |selector| tree.query_selector(selector).unwrap().unwrap();let plain = prepared.layout().rects[&node("#plain")];let anonymous = prepared.layout().rects[&node("#anonymous")];- assert_eq!(prepared.selected_image(node("#plain")).unwrap().resolved_url, url);+ assert_eq!(+ prepared+ .selected_image(node("#plain"))+ .unwrap()+ .resolved_url,+ url+ );assert_eq!((plain.width, plain.height), (20.0, 10.0));assert_eq!((anonymous.width, anonymous.height), (40.0, 30.0));@@ -12295,9 +12396,7 @@ mod tests {let output = paint_dom(&tree, (100.0, 100.0), None).expect("paint");let below_body = output.pixel(15, 65).expect("pixel");assert!(- below_body.red() > 240- && below_body.green() > 240- && below_body.blue() > 240,+ below_body.red() > 240 && below_body.green() > 240 && below_body.blue() > 240,"body overflow must not be mistaken for a viewport clip when html already owns overflow: {below_body:?}");}@@ -12621,10 +12720,16 @@ mod tests {.expect("canvas paint");let inside = pixmap.pixel(10, 10).expect("inside body box");let outside = pixmap.pixel(90, 70).expect("outside body box");- assert_eq!(inside, outside, "transferred body background must not paint twice");+ assert_eq!(+ inside, outside,+ "transferred body background must not paint twice"+ );assert!((127..=128).contains(&inside.red()), "red blend: {inside:?}");assert_eq!(inside.green(), 0);- assert!((127..=128).contains(&inside.blue()), "blue blend: {inside:?}");+ assert!(+ (127..=128).contains(&inside.blue()),+ "blue blend: {inside:?}"+ );assert_eq!(inside.alpha(), 255);}@@ -12721,8 +12826,16 @@ mod tests {};assert_eq!(rgb(25, 25), (8, 127, 91), "left side keeps lead background");- assert_eq!(rgb(25, 55), (232, 89, 12), "left side keeps heading background");- assert_eq!(rgb(25, 70), (112, 72, 232), "left side keeps beside background");+ assert_eq!(+ rgb(25, 55),+ (232, 89, 12),+ "left side keeps heading background"+ );+ assert_eq!(+ rgb(25, 70),+ (112, 72, 232),+ "left side keeps beside background"+ );for y in [25, 55, 70] {assert_eq!(rgb(175, y),@@ -14753,14 +14866,14 @@ mod tests {</body></html>"#));let mut resources = RenderResourceCache::default();- let mut prepared = prepare_dom(&tree, (360.0, 220.0), None, &mut resources)- .expect("poster-aware layout");+ let mut prepared =+ prepare_dom(&tree, (360.0, 220.0), None, &mut resources).expect("poster-aware layout");let video = tree.get_element_by_id("poster").expect("video");let rect = prepared.document_rect(video).expect("video rect");assert_eq!((rect.width, rect.height), (300.0, 100.0));- let pixmap = paint_prepared(&tree, &mut prepared, &mut resources, (0.0, 0.0))- .expect("poster paint");+ let pixmap =+ paint_prepared(&tree, &mut prepared, &mut resources, (0.0, 0.0)).expect("poster paint");let red = pixmap.pixel(50, 50).expect("red stripe");let green = pixmap.pixel(150, 50).expect("green stripe");let blue = pixmap.pixel(250, 50).expect("blue stripe");@@ -15017,13 +15130,8 @@ mod tests {);let svg = tree.query_selector("svg").unwrap().unwrap();let layout = crate::dom::layout_dom(&tree, (160.0, 80.0));- let markup = serialize_svg_styled(- &tree,- svg,- &layout.styles,- &layout.custom_properties,- None,- );+ let markup =+ serialize_svg_styled(&tree, svg, &layout.styles, &layout.custom_properties, None);assert!(markup.contains("fill:#00cc55!important"),"computed author fill must cross the standalone boundary: {markup}"@@ -15217,13 +15325,7 @@ mod tests {);let svg = tree.query_selector("#icon").unwrap().unwrap();let laid = crate::dom::layout_dom(&tree, (70.0, 10.0));- let markup = serialize_svg_styled(- &tree,- svg,- &laid.styles,- &laid.custom_properties,- None,- );+ let markup = serialize_svg_styled(&tree, svg, &laid.styles, &laid.custom_properties, None);assert!(markup.contains(r##"fill="#dc1e28""##)@@ -15330,10 +15432,10 @@ mod tests {</body></html>"#,);let mut resources = RenderResourceCache::default();- let mut prepared = prepare_dom(&tree, (200.0, 120.0), None, &mut resources)- .expect("input layout");- let pixmap = paint_prepared(&tree, &mut prepared, &mut resources, (0.0, 0.0))- .expect("input paint");+ let mut prepared =+ prepare_dom(&tree, (200.0, 120.0), None, &mut resources).expect("input layout");+ let pixmap =+ paint_prepared(&tree, &mut prepared, &mut resources, (0.0, 0.0)).expect("input paint");let ink = |top: u32| {(top..top + 30).flat_map(|y| (0..180).map(move |x| (x, y)))@@ -15535,13 +15637,8 @@ mod tests {);let laid = crate::dom::layout_dom(&tree, (100.0, 100.0));let svg = tree.query_selector("#icon").unwrap().unwrap();- let mut markup = serialize_svg_styled(- &tree,- svg,- &laid.styles,- &laid.custom_properties,- None,- );+ let mut markup =+ serialize_svg_styled(&tree, svg, &laid.styles, &laid.custom_properties, None);let mut cache = RenderResourceCache::default();let mut sprite_cache = std::collections::HashMap::new();inject_external_sprites(@@ -15577,13 +15674,8 @@ mod tests {);let laid = crate::dom::layout_dom(&tree, (100.0, 100.0));let svg = tree.query_selector("#icon").unwrap().unwrap();- let mut markup = serialize_svg_styled(- &tree,- svg,- &laid.styles,- &laid.custom_properties,- None,- );+ let mut markup =+ serialize_svg_styled(&tree, svg, &laid.styles, &laid.custom_properties, None);let mut cache = RenderResourceCache::default();let mut sprite_cache = std::collections::HashMap::from([("icons.svg#badge".to_string(),@@ -15607,8 +15699,7 @@ mod tests {"external use reference must be localized: {markup}");assert!(- markup.contains(r##"fill="#e83e8c""##)- && markup.contains(r##"stroke="#224466""##),+ markup.contains(r##"fill="#e83e8c""##) && markup.contains(r##"stroke="#224466""##),"external symbol presentation values must use host properties and fallbacks: {markup}");assert!(@@ -15668,13 +15759,7 @@ mod tests {);let laid = crate::dom::layout_dom(&tree, (100.0, 100.0));let svg = tree.query_selector("#icon").unwrap().unwrap();- let markup = serialize_svg_styled(- &tree,- svg,- &laid.styles,- &laid.custom_properties,- None,- );+ let markup = serialize_svg_styled(&tree, svg, &laid.styles, &laid.custom_properties, None);assert!(!markup.to_ascii_lowercase().contains("light-dark("),"unsupported CSS Color 5 syntax must not reach usvg: {markup}"@@ -16006,7 +16091,10 @@ mod tests {let top = prepared.resolve_scroll_state(&tree, (0.0, 0.0), &HashMap::new());assert_eq!(- prepared.viewport_rect_with_scroll(plain_sticky, &top).unwrap().y,+ prepared+ .viewport_rect_with_scroll(plain_sticky, &top)+ .unwrap()+ .y,40.0,);let offsets = HashMap::from([@@ -16017,11 +16105,17 @@ mod tests {]);let scrolled = prepared.resolve_scroll_state(&tree, (0.0, 0.0), &offsets);assert_eq!(- prepared.element_scroll_metrics(plain, &scrolled).unwrap().offset,+ prepared+ .element_scroll_metrics(plain, &scrolled)+ .unwrap()+ .offset,(0.0, 60.0),);assert_eq!(- prepared.viewport_rect_with_scroll(plain, &scrolled).unwrap().y,+ prepared+ .viewport_rect_with_scroll(plain, &scrolled)+ .unwrap()+ .y,0.0,"scroll-container chrome must remain stationary",);@@ -16073,12 +16167,7 @@ mod tests {"calc() percentage inset must use the nested content-box basis",);- let pixels = paint_prepared_with_scroll(- &tree,- &mut prepared,- &mut resources,- &scrolled,- )+ let pixels = paint_prepared_with_scroll(&tree, &mut prepared, &mut resources, &scrolled).expect("paint");let plain_pixel = pixels.pixel(10, 10).unwrap();let percent_pixel = pixels.pixel(130, 65).unwrap();@@ -16124,8 +16213,8 @@ mod tests {assert!(prepared.viewport_fixed_nodes().contains(&fixed));assert!(!prepared.viewport_fixed_nodes().contains(&captured_fixed));- let tuple = paint_prepared(&tree, &mut prepared, &mut resources, (0.0, 0.0))- .expect("tuple paint");+ let tuple =+ paint_prepared(&tree, &mut prepared, &mut resources, (0.0, 0.0)).expect("tuple paint");let tuple_pixel = tuple.pixel(155, 15).unwrap();assert!(tuple_pixel.green() > 240 && tuple_pixel.red() < 20 && tuple_pixel.blue() < 20,@@ -16152,18 +16241,19 @@ mod tests {scroll.inherited_clip_for(fixed).is_none(),"a viewport-fixed boundary must clear document-space overflow clips",);- let resolved =- paint_prepared_with_scroll(&tree, &mut prepared, &mut resources, &scroll)+ let resolved = paint_prepared_with_scroll(&tree, &mut prepared, &mut resources, &scroll).expect("resolved paint");let resolved_pixel = resolved.pixel(155, 15).unwrap();assert!(- resolved_pixel.green() > 240- && resolved_pixel.red() < 20- && resolved_pixel.blue() < 20,+ resolved_pixel.green() > 240 && resolved_pixel.red() < 20 && resolved_pixel.blue() < 20,"the resolved paint path retained the ancestor scroller clip: {resolved_pixel:?}",);let captured_pixel = resolved.pixel(155, 55).unwrap();- assert!(captured_pixel.red() > 240 && captured_pixel.green() > 240 && captured_pixel.blue() > 240);+ assert!(+ captured_pixel.red() > 240+ && captured_pixel.green() > 240+ && captured_pixel.blue() > 240+ );let internal_clip_pixel = resolved.pixel(155, 80).unwrap();assert!(internal_clip_pixel.red() > 240@@ -16185,8 +16275,7 @@ mod tests {let calc = tree.get_element_by_id("calc").unwrap();let vh = tree.get_element_by_id("vh").unwrap();let mut resources = RenderResourceCache::with_loader(|_url: &str| None);- let prepared =- prepare_dom(&tree, (200.0, 200.0), None, &mut resources).expect("prepared");+ let prepared = prepare_dom(&tree, (200.0, 200.0), None, &mut resources).expect("prepared");let live = prepared.resolve_scroll_state_for_viewport(&tree,(0.0, 200.0),@@ -16200,10 +16289,22 @@ mod tests {(200.0, 100.0),);- assert_eq!(prepared.viewport_rect_with_scroll(calc, &live).unwrap().y, 101.0);- assert_eq!(prepared.viewport_rect_with_scroll(calc, &page).unwrap().y, 51.0);- assert_eq!(prepared.viewport_rect_with_scroll(vh, &live).unwrap().y, 20.0);- assert_eq!(prepared.viewport_rect_with_scroll(vh, &page).unwrap().y, 10.0);+ assert_eq!(+ prepared.viewport_rect_with_scroll(calc, &live).unwrap().y,+ 101.0+ );+ assert_eq!(+ prepared.viewport_rect_with_scroll(calc, &page).unwrap().y,+ 51.0+ );+ assert_eq!(+ prepared.viewport_rect_with_scroll(vh, &live).unwrap().y,+ 20.0+ );+ assert_eq!(+ prepared.viewport_rect_with_scroll(vh, &page).unwrap().y,+ 10.0+ );}#[test]@@ -16227,8 +16328,7 @@ mod tests {let clip = tree.get_element_by_id("clip").unwrap();let clip_sticky = tree.get_element_by_id("clip-sticky").unwrap();let mut resources = RenderResourceCache::with_loader(|_url: &str| None);- let prepared =- prepare_dom(&tree, (240.0, 120.0), None, &mut resources).expect("prepared");+ let prepared = prepare_dom(&tree, (240.0, 120.0), None, &mut resources).expect("prepared");assert!(prepared.scroll_container_nodes().any(|node| node == hidden));assert!(!prepared.scroll_container_nodes().any(|node| node == clip));@@ -16300,12 +16400,7 @@ mod tests {"outer sticky movement must affect the inner port and its content equally",);- let pixels = paint_prepared_with_scroll(- &tree,- &mut prepared,- &mut resources,- &scrolled,- )+ let pixels = paint_prepared_with_scroll(&tree, &mut prepared, &mut resources, &scrolled).expect("paint");let pixel = pixels.pixel(10, 7).unwrap();assert!(pixel.green() > 240 && pixel.red() < 20 && pixel.blue() < 20);@@ -16349,8 +16444,8 @@ mod tests {60.0,);- let pixels = paint_prepared(&tree, &mut prepared, &mut resources, (0.0, 0.0))- .expect("tuple paint");+ let pixels =+ paint_prepared(&tree, &mut prepared, &mut resources, (0.0, 0.0)).expect("tuple paint");let pixel = pixels.pixel(10, 65).unwrap();let fixed_pixel = pixels.pixel(130, 65).unwrap();assert!(pixel.green() > 240 && pixel.red() < 20 && pixel.blue() < 20);@@ -16497,18 +16592,36 @@ mod tests {let region = CaptureRegion::new(0.0, 0.0, 120.0, 220.0, 1.0);let screen_before = screenshot_prepared_region_with_scroll_and_backgrounds(- &tree, &mut prepared, &mut resources, &scroll, region, true,+ &tree,+ &mut prepared,+ &mut resources,+ &scroll,+ region,+ true,).expect("screen capture before print");let economy = screenshot_prepared_region_with_scroll_and_backgrounds(- &tree, &mut prepared, &mut resources, &scroll, region, false,+ &tree,+ &mut prepared,+ &mut resources,+ &scroll,+ region,+ false,).expect("print economy capture");let screen_after = screenshot_prepared_region_with_scroll_and_backgrounds(- &tree, &mut prepared, &mut resources, &scroll, region, true,+ &tree,+ &mut prepared,+ &mut resources,+ &scroll,+ region,+ true,).expect("screen capture after print");- assert_eq!(screen_before, screen_after, "print paint must not mutate retained style");+ assert_eq!(+ screen_before, screen_after,+ "print paint must not mutate retained style"+ );let screen = image::load_from_memory_with_format(&screen_before, image::ImageFormat::Png).unwrap()@@ -16888,7 +17001,10 @@ mod tests {&style,);assert_eq!(ink.x, 76.0, "outset shadow must widen the cull rect");- assert_eq!(ink.y, 0.0, "shadow blur must widen the cull rect vertically");+ assert_eq!(+ ink.y, 0.0,+ "shadow blur must widen the cull rect vertically"+ );assert_eq!(ink.x + ink.width, 127.0);}@@ -16943,9 +17059,7 @@ mod tests {let pixmap = paint_dom(&tree, (120.0, 120.0), None).expect("transformed outline");let outer_outline = pixmap.pixel(25, 50).expect("transformed outer outline");assert!(- outer_outline.red() > 220- && outer_outline.green() < 40- && outer_outline.blue() < 40,+ outer_outline.red() > 220 && outer_outline.green() < 40 && outer_outline.blue() < 40,"outline ink outside the border-box source bounds must survive the transform: {outer_outline:?}");}@@ -17019,8 +17133,7 @@ mod tests {#[test]fn animation_restyle_mutations_deduplicate_waapi_and_filter_disconnected_targets() {- let tree =- parse_html("<main><div id=connected></div><div id=detached></div></main>");+ let tree = parse_html("<main><div id=connected></div><div id=detached></div></main>");let connected = tree.get_element_by_id("connected").unwrap();let detached = tree.get_element_by_id("detached").unwrap();tree.remove_child(detached);@@ -17055,9 +17168,7 @@ mod tests {let mutations = retained_animation_restyle_mutations(&tree, &HashMap::new(), &timeline);assert_eq!(mutations,- vec![crate::dom::RetainedStyleMutation::WaapiAnimation {- node: connected- }],+ vec![crate::dom::RetainedStyleMutation::WaapiAnimation { node: connected }],"only connected WAAPI targets may enter retained style damage");}@@ -17084,18 +17195,16 @@ mod tests {hold_time_ms: None,play_state: crate::WaapiPlayState::Running,};- let sample = crate::AnimationSampleTime { milliseconds: 100.0 };+ let sample = crate::AnimationSampleTime {+ milliseconds: 100.0,+ };let mut timeline = crate::AnimationTimelineState::default();timeline.register_waapi(animation(1, Some(0.5), None));assert_eq!(timeline.active_waapi_effect_impact(sample),crate::AnimationEffectImpact::Paint,);- timeline.register_waapi(animation(- 2,- None,- Some("future-transform(1)".to_string()),- ));+ timeline.register_waapi(animation(2, None, Some("future-transform(1)".to_string())));assert_eq!(timeline.active_waapi_effect_impact(sample),crate::AnimationEffectImpact::Geometry,@@ -17230,8 +17339,7 @@ mod tests {let mut oracle_resources = RenderResourceCache::with_loader(|_url: &str| None);let mut oracle_cache = crate::css::StylesheetCache::default();let mut oracle_timeline = make_timeline();- let mut oracle =- prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(+ let mut oracle = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(&tree,viewport,None,@@ -17244,7 +17352,10 @@ mod tests {.expect("forced-full oracle");assert_eq!(candidate.layout.rects, oracle.layout.rects);- assert_eq!(candidate.layout.inline_fragments, oracle.layout.inline_fragments);+ assert_eq!(+ candidate.layout.inline_fragments,+ oracle.layout.inline_fragments+ );assert_eq!(candidate.layout.translates, oracle.layout.translates);assert_eq!(candidate.layout.transforms, oracle.layout.transforms);assert_eq!(candidate.layout.clip_rects, oracle.layout.clip_rects);@@ -17258,7 +17369,11 @@ mod tests {candidate.scroll_container_nodes().collect::<Vec<_>>(),oracle.scroll_container_nodes().collect::<Vec<_>>(),);- assert!(candidate.scroll_container_nodes().any(|node| node == scroller));+ assert!(+ candidate+ .scroll_container_nodes()+ .any(|node| node == scroller)+ );for node in [moving, affine, overflow] {assert_eq!(format!("{:?}", candidate.layout.styles[&node]),@@ -17299,7 +17414,9 @@ mod tests {oracle.viewport_rect_with_scroll(scroll_target, &oracle_scroll),);assert_ne!(- candidate.sticky.translations(viewport, candidate_scroll.root_offset),+ candidate+ .sticky+ .translations(viewport, candidate_scroll.root_offset),HashMap::new(),);let candidate_pixels = paint_prepared_with_scroll(@@ -17309,12 +17426,8 @@ mod tests {&candidate_scroll,).expect("candidate pixels");- let oracle_pixels = paint_prepared_with_scroll(- &tree,- &mut oracle,- &mut oracle_resources,- &oracle_scroll,- )+ let oracle_pixels =+ paint_prepared_with_scroll(&tree, &mut oracle, &mut oracle_resources, &oracle_scroll).expect("oracle pixels");assert_eq!(candidate_pixels.data(), oracle_pixels.data());}@@ -17421,8 +17534,7 @@ mod tests {).expect("initial render before delayed effect");assert_eq!(- prepared.layout.styles[&target].containing_block_triggers- & crate::CB_TRIGGER_TRANSFORM,+ prepared.layout.styles[&target].containing_block_triggers & crate::CB_TRIGGER_TRANSFORM,0,);assert!(!prepared.try_advance_visual_waapi_sample(@@ -17430,7 +17542,10 @@ mod tests {crate::AnimationSample::document(500.0),&timeline,));- assert_eq!(prepared.animation_sample, crate::AnimationSample::document(0.0));+ assert_eq!(+ prepared.animation_sample,+ crate::AnimationSample::document(0.0)+ );}#[test]@@ -17459,7 +17574,10 @@ mod tests {.expect("T=0 render");assert_eq!(at_zero.animation_sample_time().milliseconds, 0.0);assert_eq!(at_zero.layout.styles[&overlay].opacity, Some(1.0));- assert_ne!(at_zero.layout.styles[&overlay].visibility_hidden, Some(true));+ assert_ne!(+ at_zero.layout.styles[&overlay].visibility_hidden,+ Some(true)+ );assert!(at_zero.has_active_css_animations());let at_end = prepare_dom_with_dynamic_fonts_and_stylesheet_cache_at_animation_time(@@ -17469,7 +17587,9 @@ mod tests {&mut resources,&[],&mut stylesheets,- crate::AnimationSampleTime { milliseconds: 600.0 },+ crate::AnimationSampleTime {+ milliseconds: 600.0,+ },).expect("animation-end render");assert_eq!(at_end.layout.styles[&overlay].opacity, Some(0.0));diff --git a/crates/obscura-render/src/style.rs b/crates/obscura-render/src/style.rsindex eb59f970..23155df1 100644--- a/crates/obscura-render/src/style.rs+++ b/crates/obscura-render/src/style.rs@@ -562,14 +562,22 @@ struct ParsedOverflowAxis {inherit: bool,}+const OVERFLOW_VISIBLE: u8 = 0;+const OVERFLOW_CLIP: u8 = 1;+const OVERFLOW_HIDDEN: u8 = 2;+const OVERFLOW_SCROLL: u8 = 3;+const OVERFLOW_AUTO: u8 = 4;+fn parse_overflow_axis(value: &str) -> Option<ParsedOverflowAxis> {let lower = value.trim().to_ascii_lowercase();let (specified, inherit) = match lower.as_str() {- "visible" => (0, false),- "clip" => (1, false),- "hidden" | "scroll" | "auto" | "overlay" => (2, false),- "inherit" => (0, true),- "initial" | "unset" | "revert" | "revert-layer" => (0, false),+ "visible" => (OVERFLOW_VISIBLE, false),+ "clip" => (OVERFLOW_CLIP, false),+ "hidden" => (OVERFLOW_HIDDEN, false),+ "scroll" => (OVERFLOW_SCROLL, false),+ "auto" | "overlay" => (OVERFLOW_AUTO, false),+ "inherit" => (OVERFLOW_VISIBLE, true),+ "initial" | "unset" | "revert" | "revert-layer" => (OVERFLOW_VISIBLE, false),_ => return None,};Some(ParsedOverflowAxis { specified, inherit })@@ -618,23 +626,35 @@ fn parse_overflow_declaration(}}-pub(crate) fn recompute_overflow(style: &mut LayoutStyle) {- // CSS Overflow computed-value coupling: if exactly one axis is scrollable,- // `visible` on the other computes to `auto` and `clip` computes to- // `hidden`. A clip/visible pair remains genuinely axis-specific.+pub(crate) fn computed_overflow_axes(style: &LayoutStyle) -> (u8, u8) {let mut computed_x = style.overflow_specified_x;let mut computed_y = style.overflow_specified_y;- if (computed_x == 2) != (computed_y == 2) {- if computed_x == 2 {- computed_y = 2;+ if computed_x <= OVERFLOW_CLIP && computed_y > OVERFLOW_CLIP {+ computed_x = if computed_x == OVERFLOW_VISIBLE {+ OVERFLOW_AUTO} else {- computed_x = 2;- }+ OVERFLOW_HIDDEN+ };}- style.overflow_clip_x = computed_x != 0;- style.overflow_clip_y = computed_y != 0;- style.overflow_scroll_x = computed_x == 2;- style.overflow_scroll_y = computed_y == 2;+ if computed_y <= OVERFLOW_CLIP && computed_x > OVERFLOW_CLIP {+ computed_y = if computed_y == OVERFLOW_VISIBLE {+ OVERFLOW_AUTO+ } else {+ OVERFLOW_HIDDEN+ };+ }+ (computed_x, computed_y)+}++pub(crate) fn recompute_overflow(style: &mut LayoutStyle) {+ // CSS Overflow computed-value coupling: if exactly one axis is scrollable,+ // `visible` on the other computes to `auto` and `clip` computes to+ // `hidden`. A clip/visible pair remains genuinely axis-specific.+ let (computed_x, computed_y) = computed_overflow_axes(style);+ style.overflow_clip_x = computed_x != OVERFLOW_VISIBLE;+ style.overflow_clip_y = computed_y != OVERFLOW_VISIBLE;+ style.overflow_scroll_x = computed_x > OVERFLOW_CLIP;+ style.overflow_scroll_y = computed_y > OVERFLOW_CLIP;style.overflow_hidden = style.overflow_clip_x || style.overflow_clip_y;style.overflow_scroll_container = style.overflow_scroll_x || style.overflow_scroll_y;}@@ -1466,6 +1486,9 @@ fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {};}"visibility" => style.visibility_hidden = Some(value.eq_ignore_ascii_case("hidden")),+ "pointer-events" => {+ style.pointer_events_none = Some(value.eq_ignore_ascii_case("none"));+ }"opacity" => style.opacity = value.trim().parse::<f32>().ok(),"animation" => apply_animation_shorthand(style, value),"animation-name" => {@@ -2123,6 +2146,7 @@ pub fn supports_declaration(name: &str, value: &str) -> bool {| "overflow-y"| "scrollbar-gutter"| "visibility"+ | "pointer-events"| "opacity"| "animation"| "animation-name"@@ -2309,6 +2333,7 @@ pub fn supports_declaration(name: &str, value: &str) -> bool {value.to_ascii_lowercase().as_str(),"visible" | "hidden" | "collapse"),+ "pointer-events" => matches!(value.to_ascii_lowercase().as_str(), "auto" | "none"),"scrollbar-gutter" => matches!(value.to_ascii_lowercase().as_str(),"auto" | "stable" | "stable both-edges"diff --git a/crates/obscura-render/tests/layout_test.rs b/crates/obscura-render/tests/layout_test.rsindex 9ad9af42..c40f2bbd 100644--- a/crates/obscura-render/tests/layout_test.rs+++ b/crates/obscura-render/tests/layout_test.rs@@ -530,6 +530,26 @@ fn inset_absolute_uses_nearest_positioned_ancestor() {assert!((fixed.y - 40.0).abs() < 1.0, "fixed box did not use viewport y: {fixed:?}");}+#[test]+fn inset_absolute_fills_positioned_inline_flex_ancestor() {+ let tree = parse_html(+ r#"<body style="margin:0">+ <div style="display:flex">+ <div id="button" style="position:relative;display:inline-flex;width:115px;height:40px;padding:0 12px;box-sizing:border-box">+ <a id="overlay" style="position:absolute;inset:unset;top:50%;left:50%;width:max(48px,100%);height:max(48px,100%);transform:translate(-50%,-50%)"></a>+ </div>+ </div>+ </body>"#,+ );+ let layout = layout_dom(&tree, (1120.0, 780.0));+ let button = layout.rects[&tree.get_element_by_id("button").unwrap()];+ let overlay = layout.rects[&tree.get_element_by_id("overlay").unwrap()];++ assert_eq!((button.width, button.height), (115.0, 40.0));+ assert_eq!(overlay.width, 91.0);+ assert_eq!(overlay.height, 48.0, "functional percentage height must use the 40px containing block");+}+#[test]fn absolute_auto_axes_preserve_static_position_after_reparenting() {let tree = parse_html(include_str!("../../../render-repros/absolute-static-position.html"));@@ -3487,6 +3507,36 @@ fn cyclic_descendant_percentages_do_not_inflate_a_flex_items_intrinsic_minimum()}}+#[test]+fn cyclic_percentage_flex_row_keeps_its_intrinsic_content_width() {+ let tree = parse_html(+ r#"+ <style>+ html, body { margin:0 }+ #scroller { display:flex; width:768px }+ #month { flex:0 0 auto; width:auto; max-width:336px; padding:0 24px }+ #week { display:flex; width:100% }+ .day { flex:1 0 48px; width:48px; height:48px }+ </style>+ <div id="scroller"><div id="month"><div><div id="week">+ <div class="day"></div><div class="day"></div><div class="day"></div>+ <div class="day"></div><div class="day"></div><div class="day"></div>+ <div class="day"></div>+ </div></div></div></div>+ "#,+ );+ let layout = layout_dom(&tree, (1000.0, 400.0));+ let rect = |id| layout.rects[&tree.get_element_by_id(id).unwrap()];++ assert_eq!(rect("week").width, 336.0, "percentage row: {:?}", rect("week"));+ assert_eq!(+ rect("month").width,+ 384.0,+ "content width plus inline padding: {:?}",+ rect("month")+ );+}+/// Chromium resolves both spellings to the same 163px content width: the/// percentage is cyclic while the link's flex-item width is being measured,/// then resolves against that link's final width. Carbon Ads uses the bare