The headless browser for AI agents and web scraping
fix(render): stop transform measurement layout churn
SGavrl30e8d7a4bb23
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 0d94927b..674a7182 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -2012,7 +2012,10 @@ function _domEventDispatch(target, event) {path.push(ancestor);ancestor = ancestor.parentNode || null;}- if (target !== globalThis && path[path.length - 1] !== globalThis) {+ // Detached nodes have no event parent. Connected paths reach Window through+ // Document, except for load, whose Document parent is null by specification.+ const reachesDocument = target === document || path[path.length - 1] === document;+ if (reachesDocument && event.type !== "load") {path.push(globalThis);}@@ -3535,6 +3538,10 @@ class Element extends Node {// Element for element nodes, and node ids are never freed-and-reused), so this// is constant. Overrides Node's dynamic getter to drop one op per nodeType read.get nodeType() { return 1; }+ // DOM wrappers must not carry Object's default brand. Libraries such as+ // Swiper use Object.prototype.toString to distinguish plain option objects+ // from host elements before recursively merging them.+ get [Symbol.toStringTag]() { return "HTMLElement"; }get tagName() {// An element's qualified name is immutable for its lifetime. React reads// nodeName/tagName repeatedly while hydrating; crossing the native bridge@@ -4862,11 +4869,13 @@ class Element extends Node {}get offsetWidth() {if (this._isViewportRoot()) return globalThis.innerWidth || 1280;- return this.getBoundingClientRect().width;+ const metrics = this._renderBoxMetrics();+ return metrics ? metrics.offsetWidth : this.getBoundingClientRect().width;}get offsetHeight() {if (this._isViewportRoot()) return globalThis.innerHeight || 720;- return this.getBoundingClientRect().height;+ const metrics = this._renderBoxMetrics();+ return metrics ? metrics.offsetHeight : this.getBoundingClientRect().height;}get offsetParent() {if (!this.isConnected || this._renderBoxGeometry() === null) return null;@@ -4927,6 +4936,29 @@ class Element extends Node {return metrics ? metrics.height : 20;}_renderClientMetrics() {+ const metrics = this._renderBoxMetrics();+ return metrics ? { width: metrics.clientWidth, height: metrics.clientHeight } : metrics;+ }+ _renderBoxMetrics() {+ if (typeof __obscuraCore.ops.op_layout_box_metrics === 'function') {+ try {+ const raw = __obscuraCore.ops.op_layout_box_metrics(String(this._nid | 0));+ if (!raw) return { clientWidth: 0, clientHeight: 0, offsetWidth: 0, offsetHeight: 0 };+ const metrics = JSON.parse(raw);+ if (metrics && Number.isFinite(metrics.clientWidth)+ && Number.isFinite(metrics.clientHeight)+ && Number.isFinite(metrics.offsetWidth)+ && Number.isFinite(metrics.offsetHeight)) {+ return {+ clientWidth: Math.round(Math.max(0, metrics.clientWidth)),+ clientHeight: Math.round(Math.max(0, metrics.clientHeight)),+ offsetWidth: Math.round(Math.max(0, metrics.offsetWidth)),+ offsetHeight: Math.round(Math.max(0, metrics.offsetHeight)),+ };+ }+ } catch (_error) {}+ return { clientWidth: 0, clientHeight: 0, offsetWidth: 0, offsetHeight: 0 };+ }if (typeof __obscuraCore.ops.op_layout_geometry !== 'function') return null;try {const raw = __obscuraCore.ops.op_layout_geometry(String(this._nid | 0));@@ -4939,12 +4971,14 @@ class Element extends Node {// subpixel precision for getBoundingClientRect(); client metrics round// to whole CSS pixels like Chromium.return {- width: Math.round(Math.max(0, geometry.clientWidth)),- height: Math.round(Math.max(0, geometry.clientHeight)),+ clientWidth: Math.round(Math.max(0, geometry.clientWidth)),+ clientHeight: Math.round(Math.max(0, geometry.clientHeight)),+ offsetWidth: Math.round(Math.max(0, geometry.width)),+ offsetHeight: Math.round(Math.max(0, geometry.height)),};}} catch (_error) {}- return { width: 0, height: 0 };+ return { clientWidth: 0, clientHeight: 0, offsetWidth: 0, offsetHeight: 0 };}// `undefined` means this is a non-render build. `null` means the render// engine is present but this element has no associated CSS box (for@@ -12405,7 +12439,9 @@ Object.defineProperty(SVGAnimatedString.prototype, 'animVal', {Object.defineProperty(SVGAnimatedString.prototype, Symbol.toStringTag, { value: 'SVGAnimatedString', configurable: true });_markNative(SVGAnimatedString);-class SVGElement extends Element {}+class SVGElement extends Element {+ get [Symbol.toStringTag]() { return "SVGElement"; }+}class SVGGraphicsElement extends SVGElement {}class SVGGeometryElement extends SVGGraphicsElement {}class SVGPathElement extends SVGGeometryElement {}diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 00ac9ff7..767ce274 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -948,6 +948,7 @@ fn retained_style_mutation(cmd: &str,arg1: &str,arg2: &str,+ keep_inline_style_values: bool,) -> Option<obscura_render::RetainedStyleMutation> {let node = NodeId::new(arg1.parse::<u32>().ok()?);// The retained planner and document stylesheet cache are intentionally@@ -965,18 +966,17 @@ fn retained_style_mutation({return None;}- let keeps_selector_value = !name.eq_ignore_ascii_case("style");+ let keep_value = keep_inline_style_values || !name.eq_ignore_ascii_case("style");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))- .flatten()+ old_value: keep_value.then(|| {+ dom.with_node(node, |node| node.get_attribute(name).map(str::to_owned))+ .flatten()}).flatten(),- new_value: keeps_selector_value.then(|| value.to_string()),+ new_value: keep_value.then(|| value.to_string()),}.into(),)@@ -987,15 +987,14 @@ fn retained_style_mutation({return None;}- let keeps_selector_value = !arg2.eq_ignore_ascii_case("style");+ let keep_value = keep_inline_style_values || !arg2.eq_ignore_ascii_case("style");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))- .flatten()+ old_value: keep_value.then(|| {+ dom.with_node(node, |node| node.get_attribute(arg2).map(str::to_owned))+ .flatten()}).flatten(),new_value: None,@@ -1067,7 +1066,8 @@ const MAX_PENDING_STYLE_MUTATIONS: usize = 4_096;/// Rendering observes the attribute state at flush boundaries. Repeated writes/// to the same node/name therefore retain the first old value and final new/// value; intermediate values were never rendered and cannot affect selector-/// matching. Inline style uses the same rule without storing serialized values.+/// matching. Inline style keeps the first/final serialized values so CSSOM+/// metrics can distinguish transform-only edits from layout damage.#[cfg(feature = "render")]pub(crate) fn queue_retained_style_mutation(pending: &mut Vec<obscura_render::RetainedStyleMutation>,@@ -1611,10 +1611,20 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->.map(|dom| render_mutation_impact(dom, &cmd, &arg1, &arg2)).unwrap_or_default();#[cfg(feature = "render")]+ let keep_inline_style_values = state.prepared_render.is_some();+ #[cfg(feature = "render")]let retained_style_mutation = state.dom.as_ref()- .and_then(|dom| retained_style_mutation(dom, &cmd, &arg1, &arg2));+ .and_then(|dom| {+ retained_style_mutation(+ dom,+ &cmd,+ &arg1,+ &arg2,+ keep_inline_style_values,+ )+ });let invalidate = impact.connected && impact.actual_change;if invalidate {state.activity_generation = state.activity_generation.wrapping_add(1);@@ -4856,7 +4866,8 @@ mod tests {&dom,"set_attribute",&child.index().to_string(),- "class\0changed"+ "class\0changed",+ false,).is_none(),"shadow mutations require a full scoped cascade"@@ -6266,6 +6277,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_box_metrics());ops.push(op_layout_hit_test());ops.push(op_resize_observer_measurements());ops.push(op_intersection_observer_measurements());@@ -6669,6 +6681,49 @@ fn ensure_prepared_geometry(state: &mut ObscuraState) -> Option<&obscura_render:ensure_prepared_render_with_base_url(state, base_url)}+/// Prepare untransformed CSSOM View box metrics. A pending inline transform+/// must change visual rectangles and paint, but it cannot change client or+/// offset sizes. Keep that narrow distinction so libraries may measure while+/// composing transforms without rebuilding layout after every write.+#[cfg(feature = "render")]+fn ensure_prepared_box_metrics(+ state: &mut ObscuraState,+ target: NodeId,+) -> Option<&obscura_render::PreparedRender> {+ let base_url = document_base_url_for_javascript_task(state);+ let target_ancestors = state+ .dom+ .as_ref()+ .map(|dom| dom.ancestors(target))+ .unwrap_or_default();+ let paint_only_inline_styles = !state.pending_style_mutations.is_empty()+ && state.pending_style_mutations.iter().all(|mutation| {+ matches!(+ mutation,+ obscura_render::RetainedStyleMutation::Attribute(attribute)+ if attribute.name.eq_ignore_ascii_case("style")+ && !target_ancestors.contains(&attribute.node)+ && obscura_render::style::inline_style_change_preserves_box_metrics(+ attribute.old_value.as_deref(),+ attribute.new_value.as_deref(),+ )+ )+ });+ let reusable = (!state.animation_timeline.has_pending_start_candidates()+ || paint_only_inline_styles)+ && state.prepared_render.as_ref().is_some_and(|prepared| {+ prepared.viewport() == state.viewport+ && prepared.base_url() == base_url.as_deref()+ && (prepared.animation_sample() == state.animation_sample+ || prepared.can_reuse_geometry_for_animation_sample(state.animation_sample))+ })+ && (state.pending_style_mutations.is_empty() || paint_only_inline_styles);+ if reusable {+ return state.prepared_render.as_ref();+ }+ ensure_prepared_render_with_base_url(state, base_url)+}+#[cfg(feature = "render")]pub(crate) fn sample_live_document_animations(state: &mut ObscuraState) {if state.animation_sampled_task_generation == state.animation_task_generation {@@ -7232,6 +7287,35 @@ fn op_layout_geometry(state: &OpState, #[string] nid_str: String) -> String {String::new()}+/// Untransformed padding- and border-box sizes for CSSOM View. Keeping this+/// separate from visual geometry is both spec-correct and lets transform-only+/// style writes retain layout until a visual consumer actually needs them.+#[cfg(feature = "render")]+#[op2]+#[string]+fn op_layout_box_metrics(state: &OpState, #[string] nid_str: String) -> String {+ let shared = state.borrow::<SharedState>().clone();+ let nid = NodeId::new(nid_str.parse().unwrap_or(0));+ let mut gs = shared.borrow_mut();+ sample_live_document_animations(&mut gs);+ let Some(prepared) = ensure_prepared_box_metrics(&mut gs, nid) else {+ return String::new();+ };+ let Some((client_width, client_height)) = prepared.client_size(nid) else {+ return String::new();+ };+ let Some((offset_width, offset_height)) = prepared.border_size(nid) else {+ return String::new();+ };+ serde_json::json!({+ "clientWidth": client_width,+ "clientHeight": client_height,+ "offsetWidth": offset_width,+ "offsetHeight": offset_height,+ })+ .to_string()+}+/// 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")]diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 6628a862..678ea566 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -7506,6 +7506,58 @@ mod tests {);}+ #[test]+ fn dom_events_only_reach_window_through_document() {+ let mut rt = setup_runtime("<html><head></head><body></body></html>");+ assert_eq!(+ rt.evaluate(+ "const seen = [];\+ window.addEventListener('load', () => seen.push('window-capture'), true);\+ window.addEventListener('click', () => seen.push('window-click-capture'), true);\+ document.addEventListener('load', () => seen.push('document-capture'), true);\+ document.addEventListener('load', () => seen.push('document-bubble'));\+ const script = document.createElement('script');\+ script.addEventListener('load', () => seen.push('script'));\+ document.head.appendChild(script);\+ script.dispatchEvent(new Event('load'));\+ script.dispatchEvent(new Event('click'));\+ script.remove();\+ script.dispatchEvent(new Event('load'));\+ script.dispatchEvent(new Event('click'));\+ return seen"+ )+ .unwrap(),+ serde_json::json!([+ "document-capture",+ "script",+ "window-click-capture",+ "script"+ ])+ );+ }++ #[test]+ fn elements_have_host_object_brands_for_plain_object_guards() {+ let mut rt = setup_runtime("<html><body><div id='carousel'></div></body></html>");+ assert_eq!(+ rt.evaluate(+ "const element = document.getElementById('carousel');\+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\+ const isPlainObject = value => typeof value === 'object' && value !== null\+ && value.constructor\+ && Object.prototype.toString.call(value).slice(8, -1) === 'Object';\+ const target = {};\+ const source = { element };\+ target.element = isPlainObject(source.element) ? {} : source.element;\+ return [Object.prototype.toString.call(element),\+ Object.prototype.toString.call(svg), isPlainObject(element),\+ target.element === element]"+ )+ .unwrap(),+ serde_json::json!(["[object HTMLElement]", "[object SVGElement]", false, true])+ );+ }+#[test]fn meta_http_equiv_reflection_supports_snapshot_csp_filtering() {let mut rt = setup_runtime(@@ -12022,6 +12074,86 @@ mod tests {assert!(after >= before + 7.0, "before={before}, after={after}");}+ #[cfg(feature = "render")]+ #[test]+ fn transform_only_writes_retain_untransformed_cssom_box_metrics() {+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(parse_html(+ r#"<html style="margin:0"><body style="margin:0">+ <div id="box" style="width:40px;height:20px;transform:scale(2)"></div>+ <div id="parent" style="width:80px;height:20px">+ <div id="fixed" style="position:fixed;width:50%;height:5px"></div>+ </div>+ </body></html>"#,+ ));+ rt.set_viewport(200.0, 100.0);+ rt.run_page_init();++ let initial = rt+ .evaluate(+ r#"(() => {+ const box = document.getElementById('box');+ return [box.offsetWidth, box.clientWidth, box.getBoundingClientRect().width];+ })()"#,+ )+ .unwrap();+ assert_eq!(initial[0].as_f64(), Some(40.0));+ assert_eq!(initial[1].as_f64(), Some(40.0));+ assert_eq!(initial[2].as_f64(), Some(80.0));++ let retained = rt+ .evaluate(+ r#"(() => {+ const box = document.getElementById('box');+ box.style.transform = 'scale(3)';+ return [box.offsetWidth, box.clientWidth];+ })()"#,+ )+ .unwrap();+ let retained = retained.as_array().unwrap();+ assert_eq!(retained[0].as_f64(), Some(40.0));+ assert_eq!(retained[1].as_f64(), Some(40.0));+ assert!(+ !rt.state.borrow().pending_style_mutations.is_empty(),+ "layout-only metrics must leave transform paint damage pending"+ );++ assert_eq!(+ rt.evaluate("document.getElementById('box').getBoundingClientRect().width")+ .unwrap()+ .as_f64(),+ Some(120.0),+ "visual geometry must still materialize the pending transform"+ );+ assert!(rt.state.borrow().pending_style_mutations.is_empty());++ assert_eq!(+ rt.evaluate(+ "(() => { const box = document.getElementById('box'); box.style.width='70px'; return box.offsetWidth; })()"+ )+ .unwrap()+ .as_f64(),+ Some(70.0),+ "layout-affecting inline edits must not use the transform fast path"+ );++ assert_eq!(+ rt.evaluate("document.getElementById('fixed').offsetWidth")+ .unwrap()+ .as_f64(),+ Some(100.0)+ );+ assert_eq!(+ rt.evaluate(+ "(() => { document.getElementById('parent').style.transform='translateZ(0)'; return document.getElementById('fixed').offsetWidth; })()"+ )+ .unwrap()+ .as_f64(),+ Some(40.0),+ "an ancestor transform can change a positioned descendant's containing block"+ );+ }+#[cfg(feature = "render")]#[tokio::test(flavor = "current_thread")]async fn autocomplete_attribute_retains_prepared_render_until_geometry_flush() {diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex e1283da4..3014aa98 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -1353,6 +1353,18 @@ impl PreparedRender {))}+ /// Untransformed border-box size used by CSSOM View's `offsetWidth` and+ /// `offsetHeight`. Unlike `getBoundingClientRect()`, transforms do not+ /// participate in these integer layout metrics.+ pub fn border_size(&self, id: obscura_dom::tree::NodeId) -> Option<(f32, f32)> {+ let rect = self.layout.rects.get(&id)?;+ let style = self.layout.styles.get(&id)?;+ if style.ignores_used_box_sizes() {+ return Some((0.0, 0.0));+ }+ Some((rect.width.max(0.0), rect.height.max(0.0)))+ }+/// Whether hit testing must ignore this element's generated box.pub fn pointer_events_none(&self, id: obscura_dom::tree::NodeId) -> bool {self.layoutdiff --git a/crates/obscura-render/src/style.rs b/crates/obscura-render/src/style.rsindex ab3b2e0d..f4273d2c 100644--- a/crates/obscura-render/src/style.rs+++ b/crates/obscura-render/src/style.rs@@ -505,6 +505,46 @@ pub(crate) fn split_declarations(css: &str) -> Vec<&str> {parts}+/// Whether an inline-style edit can leave CSSOM View's untransformed box+/// metrics intact. This is deliberately narrower than "paint only": callers+/// use it only for `client*`/`offset*`, while transformed visual rectangles+/// still force an exact render. Comparing every other declaration in source+/// order keeps shorthands, custom properties, priorities, and duplicate+/// declarations conservative without maintaining a second CSS cascade.+pub fn inline_style_change_preserves_box_metrics(old: Option<&str>, new: Option<&str>) -> bool {+ fn next_layout_declaration<'a>(+ declarations: &mut impl Iterator<Item = &'a str>,+ ) -> Option<(&'a str, &'a str)> {+ loop {+ let raw = declarations.next()?;+ let Some((name, value)) = raw.trim().split_once(':') else {+ continue;+ };+ let name = name.trim();+ if name.eq_ignore_ascii_case("transform")+ || name.eq_ignore_ascii_case("-webkit-transform")+ {+ continue;+ }+ return Some((name, value.trim()));+ }+ }++ let mut old = old.into_iter().flat_map(split_declarations);+ let mut new = new.into_iter().flat_map(split_declarations);+ loop {+ match (+ next_layout_declaration(&mut old),+ next_layout_declaration(&mut new),+ ) {+ (Some((old_name, old_value)), Some((new_name, new_value)))+ if old_name.eq_ignore_ascii_case(new_name) && old_value == new_value => {}+ (None, None) => return true,+ _ => return false,+ }+ }+}+fn parse_containment(value: &str) -> Option<u8> {use crate::{CONTAIN_SIZE, CONTAIN_INLINE_SIZE, CONTAIN_LAYOUT, CONTAIN_STYLE, CONTAIN_PAINT};let value = value.trim().to_ascii_lowercase();