The headless browser for AI agents and web scraping
perf(js): avoid repeated computed-style work
SGavrl35b94482f769
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex cbc55b84..f8ce93e5 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -516,6 +516,8 @@ pub struct ObscuraState {/// parsing/indexing when ordered CSS source and viewport remain identical.#[cfg(feature = "render")]pub stylesheet_cache: obscura_render::StylesheetCache,+ #[cfg(feature = "render")]+ pub(crate) style_query_cache: Option<StyleQueryCache>,/// Script-created faces in this document's `FontFaceSet`. This is separate/// from the DOM so the bridge does not manufacture a selector-visible/// `<style>` element merely to feed the renderer.@@ -713,6 +715,8 @@ impl ObscuraState {#[cfg(feature = "render")]stylesheet_cache: obscura_render::StylesheetCache::default(),#[cfg(feature = "render")]+ style_query_cache: None,+ #[cfg(feature = "render")]dynamic_fonts: Vec::new(),#[cfg(feature = "render")]canvas_surfaces: HashMap::new(),@@ -8046,6 +8050,8 @@ pub(crate) fn sample_live_document_animations(state: &mut ObscuraState) {pub(crate) fn begin_animation_task(state: &mut ObscuraState) {state.animation_task_generation = state.animation_task_generation.wrapping_add(1);+ #[cfg(feature = "render")]+ { state.style_query_cache = None; }}#[op2(fast)]@@ -8795,6 +8801,16 @@ fn op_intersection_observer_measurements(state: &OpState, #[string] nids_json: S/// CSSOM snapshot and completeness flag. Non-geometric reads can resolve only/// the ancestor cascade while leaving layout damage pending for geometry/paint.+#[cfg(feature = "render")]+pub(crate) struct StyleQueryCache {+ task_generation: u64,+ activity_generation: u64,+ stylesheet_generation: u64,+ viewport: (f32, f32),+ media: obscura_render::CssMediaType,+ cascade: obscura_render::dom::NonGeometricStyleCache,+}+#[cfg(feature = "render")]#[op2]#[string]@@ -8815,15 +8831,36 @@ fn op_computed_style(prepared.viewport() != gs.viewport || prepared.base_url() != base_url.as_deref()|| prepared.animation_sample() != gs.animation_sample}) || !gs.pending_style_mutations.is_empty();- if pseudo.is_empty() && needs_layout && gs.animation_timeline.waapi_nodes().is_empty() {- if let Some(snapshot) = gs.dom.as_ref().and_then(|dom| {- obscura_render::dom::computed_style_without_layout(- dom, nid, gs.viewport, gs.render_media, &gs.stylesheet_cache, &property,- )+ if pseudo.is_empty() && needs_layout && gs.animation_timeline.waapi_nodes().is_empty()+ && obscura_render::dom::NonGeometricStyleCache::supports(&property)+ {+ let mut cached = gs.style_query_cache.take();+ let stylesheet_generation = gs.dom.as_ref().map_or(0, |dom| dom.external_stylesheet_generation());+ if !cached.as_ref().is_some_and(|cache| {+ cache.task_generation == gs.animation_task_generation+ && cache.activity_generation == gs.activity_generation+ && cache.stylesheet_generation == stylesheet_generation+ && cache.viewport == gs.viewport && cache.media == gs.render_media}) {+ cached = gs.dom.as_ref().and_then(|dom| {+ obscura_render::dom::NonGeometricStyleCache::new(+ dom, gs.viewport, gs.render_media, &gs.stylesheet_cache,+ )+ }).map(|cascade| StyleQueryCache {+ task_generation: gs.animation_task_generation,+ activity_generation: gs.activity_generation,+ stylesheet_generation, viewport: gs.viewport, media: gs.render_media, cascade,+ });+ }+ let snapshot = cached.as_mut().and_then(|cache| {+ cache.cascade.resolve(gs.dom.as_ref()?, nid, &property)+ });+ gs.style_query_cache = cached;+ if let Some(snapshot) = snapshot {return serde_json::json!([false, snapshot]).to_string();}}+ gs.style_query_cache = None;let Some(prepared) = ensure_prepared_render_with_base_url(&mut gs, base_url) else {return String::new();};@@ -8839,6 +8876,11 @@ fn op_computed_style();return serde_json::json!([true, { "content": content, "display": display }]).to_string();}+ if pseudo.is_empty() && obscura_render::dom::NonGeometricStyleCache::supports(&property) {+ if let Some(snapshot) = prepared.computed_non_geometric_style(nid) {+ return serde_json::json!([false, snapshot]).to_string();+ }+ }let Some(snapshot) = prepared.computed_style(nid) else {return String::new();};diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 3d23c050..bf505cb5 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -1246,6 +1246,7 @@ impl ObscuraJsRuntime {#[cfg(feature = "render")]{gs.prepared_render = None;+ gs.style_query_cache = None;gs.animation_sample = obscura_render::AnimationSample::default();gs.animation_timeline = obscura_render::AnimationTimelineState::default();gs.animation_timeline_origin = std::time::Instant::now();@@ -4071,6 +4072,7 @@ impl ObscuraJsRuntime {#[cfg(feature = "render")]{state.prepared_render = None;+ state.style_query_cache = None;state.pending_style_mutations.clear();let render_resources = crate::ops::fresh_render_resources(&state);state.render_resources = render_resources;@@ -9091,6 +9093,78 @@ mod tests {]));}+ #[cfg(feature = "render")]+ #[tokio::test(flavor = "current_thread")]+ async fn computed_style_sibling_reads_do_not_repeat_the_ancestor_cascade() {+ let variables = (0..2500).map(|i| format!("--token-{i}:{i}px;"))+ .collect::<String>();+ let mut rt = setup_runtime(&format!(r#"<!doctype html><style>+ body {{ {variables} color:rgb(12,34,56) }}+ .row {{ display:block; width:var(--token-80); height:1px }}+ body[data-active=yes] {{ color:rgb(78,90,12) }}+ </style><body><main><section>{}</section></main></body>"#,+ "<div class=row></div>".repeat(1024)));+ // Prime the compiled stylesheet, then leave layout damage pending.+ rt.evaluate("document.body.getBoundingClientRect().width").unwrap();+ let started = std::time::Instant::now();+ assert_eq!(rt.evaluate(r#"(() => {+ let matched = 0;+ for (const row of document.querySelectorAll('.row')) {+ const style = getComputedStyle(row);+ matched += style.display === 'block' && style.color === 'rgb(12, 34, 56)';+ }+ return matched;+ })()"#).unwrap(), serde_json::json!(1024.0));+ assert!(started.elapsed() < std::time::Duration::from_secs(1),+ "style-only reads serialized the full CSS variable environment: {:?}", started.elapsed());+ let started = std::time::Instant::now();+ assert_eq!(rt.evaluate(r#"(() => {+ document.body.setAttribute('data-active', 'yes');+ let matched = 0;+ for (const row of document.querySelectorAll('.row')) {+ const style = getComputedStyle(row);+ matched += style.display === 'block' && style.color === 'rgb(78, 90, 12)';+ }+ return matched;+ })()"#).unwrap(), serde_json::json!(1024.0));+ assert!(started.elapsed() < std::time::Duration::from_secs(1),+ "sibling style reads repeated their large inherited cascade: {:?}", started.elapsed());+ assert!(!rt.state.borrow().pending_style_mutations.is_empty());+ assert_eq!(rt.evaluate("getComputedStyle(document.querySelector('.row')).width").unwrap(),+ serde_json::json!("80px"));+ assert_eq!(rt.evaluate(r#"(() => {+ const style = getComputedStyle(document.querySelector('.row'));+ return [style.getPropertyValue('--token-80'), style.length > 2500];+ })()"#).unwrap(), serde_json::json!(["80px", true]));+ }++ #[cfg(feature = "render")]+ #[tokio::test(flavor = "current_thread")]+ async fn non_geometric_style_cache_observes_mutations_between_sibling_reads() {+ let mut rt = setup_runtime(r#"<!doctype html><style>+ body { --tone:blue; color:var(--tone) }+ body[data-active=yes] { --tone:red }+ section { display:flex }+ .row { display:inline }+ </style><body><section><span class=row id=first></span>+ <span class=row id=second></span></section></body>"#);+ rt.evaluate("document.body.getBoundingClientRect().width").unwrap();+ assert_eq!(rt.evaluate(r#"(() => {+ const first = document.getElementById('first');+ const second = document.getElementById('second');+ document.body.setAttribute('data-active', 'yes');+ const before = getComputedStyle(second).color;+ document.body.removeAttribute('data-active');+ const after = getComputedStyle(first).color;+ document.querySelector('section').style.display = 'block';+ const display = getComputedStyle(second).display;+ document.querySelector('style').sheet.insertRule('.row { color:green }', 0);+ return [before, after, display, getComputedStyle(first).color];+ })()"#).unwrap(), serde_json::json!([+ "rgb(255, 0, 0)", "rgb(0, 0, 255)", "inline", "rgb(0, 128, 0)"+ ]));+ }+#[cfg(feature = "render")]#[tokio::test(flavor = "current_thread")]async fn computed_style_non_geometric_reads_defer_layout_without_losing_damage() {diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex f6ef26fc..4abe493a 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -4540,88 +4540,133 @@ pub fn computed_style_without_layout(cache: &crate::css::StylesheetCache,property: &str,) -> Option<HashMap<&'static str, String>> {- if !matches!(property, "display" | "float" | "clear" | "position" | "z-index"- | "visibility" | "pointer-events" | "opacity" | "background-color"- | "background-origin" | "background-clip" | "color")- || !tree.is_connected(id)- {- return None;- }- let sources = document_stylesheet_sources(tree, viewport, media_type);- let sheet = cache.get(&sources, viewport, media_type)?;- let mut path = tree.ancestors(id);- path.reverse();- path.push(id);- if path.iter().any(|node| tree.shadow_root(*node).is_some() || tree.is_shadow_root(*node)- || tree.borrow_node(*node).is_some_and(|node| {- node.as_element().is_some_and(|element| element.local.as_ref() == "input")- && node.get_attribute("type").is_some_and(|kind| kind.trim().eq_ignore_ascii_case("hidden"))- })) {- return None;+ if !NonGeometricStyleCache::supports(property) { return None; }+ NonGeometricStyleCache::new(tree, viewport, media_type, cache)?.resolve(tree, id, property)+}++/// Ancestor cascade shared by non-geometric reads in one unchanged JS task.+/// The owner must discard it on document, style, viewport or media changes.+#[cfg(feature = "paint")]+pub struct NonGeometricStyleCache {+ sheet: std::sync::Arc<crate::css::Stylesheet>,+ viewport: (f32, f32),+ quirks: bool,+ has_container_queries: bool,+ styles: HashMap<NodeId, crate::LayoutStyle>,+ custom_properties: HashMap<NodeId, std::rc::Rc<HashMap<String, String>>>,+ ancestors: HashMap<NodeId, (Option<f32>, bool, bool, bool)>,+}++#[cfg(feature = "paint")]+impl NonGeometricStyleCache {+ pub fn supports(property: &str) -> bool {+ matches!(property, "display" | "float" | "clear" | "position" | "z-index"+ | "visibility" | "pointer-events" | "opacity" | "background-color"+ | "background-origin" | "background-clip" | "color")}- let quirks = !tree.children(tree.document()).iter().any(|node| {- tree.borrow_node(*node).is_some_and(|node| {- matches!(node.data, obscura_dom::tree::NodeData::Doctype { .. })++ pub fn new(+ tree: &DomTree,+ viewport: (f32, f32),+ media_type: crate::CssMediaType,+ cache: &crate::css::StylesheetCache,+ ) -> Option<Self> {+ let sources = document_stylesheet_sources(tree, viewport, media_type);+ let sheet = cache.get(&sources, viewport, media_type)?;+ let quirks = !tree.children(tree.document()).iter().any(|node| {+ tree.borrow_node(*node).is_some_and(|node| {+ matches!(node.data, obscura_dom::tree::NodeData::Doctype { .. })+ })+ });+ Some(Self {+ has_container_queries: sheet.has_container_queries(), sheet, viewport, quirks,+ styles: HashMap::new(), custom_properties: HashMap::new(), ancestors: HashMap::new(),})- });- let mut matcher = tree.matcher();- let mut styles = HashMap::new();- let mut custom_properties = HashMap::new();- let mut props = std::rc::Rc::new(HashMap::new());- let mut cell_padding = None;- let mut dark = false;- let mut color = None;- let mut pointer_events = false;- let shadow_sheets = HashMap::new();- let mut timeline = crate::AnimationTimelineState::default();- let mut ancestor_display_none = false;- for &node in &path {- let (next_props, next_padding, next_dark, element) = cascade_node_style(- tree, node, &sheet, &sheet, &shadow_sheets, &mut matcher,- &mut styles, &mut custom_properties, &props, &mut None, quirks,- viewport, crate::AnimationSample::default(), &mut timeline,- cell_padding, dark, None, ancestor_display_none,- )?;- props = next_props;- cell_padding = next_padding;- dark = next_dark;- if !element { continue; }- matcher.push_ancestor(tree, node);- let style = styles.get_mut(&node)?;- ancestor_display_none |= style.display == crate::Display::None;- // Display inheritance and live effects retain the complete normalization- // path. A query cannot become active without a query container on this- // ancestor path, including named normal/style containers.- if style.display_inherit || style.animation_name.is_some()- || (sheet.has_container_queries()- && (style.container_type != crate::ContainerType::Normal- || !style.container_names.is_empty()))- {+ }++ pub fn resolve(+ &mut self, tree: &DomTree, id: NodeId, property: &str,+ ) -> Option<HashMap<&'static str, String>> {+ if !Self::supports(property) || !tree.is_connected(id) {return None;}- color = style.color.or(color);- style.color = color;- pointer_events = style.pointer_events_none.unwrap_or(pointer_events);- style.pointer_events_none = Some(pointer_events);- }- // Use the same outer-display fixup as layout, including transparent- // display:contents ancestors and flex/grid items.- let mut parent_is_item_container = false;- let mut root = true;- for node in path {- let Some(style) = styles.get_mut(&node) else { continue };- if root || (parent_is_item_container && !style.display_contents)- || style.position == Some(taffy::Position::Absolute) || style.float.is_some()- {- crate::blockify_outer_display(style);+ let mut path = tree.ancestors(id);+ path.reverse();+ path.push(id);+ if path.iter().any(|node| tree.shadow_root(*node).is_some() || tree.is_shadow_root(*node)+ || tree.borrow_node(*node).is_some_and(|node| {+ node.as_element().is_some_and(|element| element.local.as_ref() == "input")+ && node.get_attribute("type").is_some_and(|kind| kind.trim().eq_ignore_ascii_case("hidden"))+ })) {+ return None;}- root = false;- if !style.display_contents {- parent_is_item_container = style.display == crate::Display::Grid- || (style.display == crate::Display::Flex && !style.internal_flex_container);+ let mut matcher = tree.matcher();+ let mut props = std::rc::Rc::new(HashMap::new());+ let mut cell_padding = None;+ let mut dark = false;+ let mut color = None;+ let mut pointer_events = false;+ let shadow_sheets = HashMap::new();+ let mut timeline = crate::AnimationTimelineState::default();+ let mut ancestor_display_none = false;+ let mut parent_is_item_container = false;+ let mut root = true;+ for &node in &path {+ if let Some(&(padding, scheme, hidden, item_container)) = self.ancestors.get(&node) {+ props = self.custom_properties.get(&node)?.clone();+ cell_padding = padding;+ dark = scheme;+ ancestor_display_none = hidden;+ parent_is_item_container = item_container;+ let style = self.styles.get(&node)?;+ color = style.color;+ pointer_events = style.pointer_events_none.unwrap_or(false);+ root = false;+ matcher.push_ancestor(tree, node);+ continue;+ }+ let (next_props, next_padding, next_dark, element) = cascade_node_style(+ tree, node, &self.sheet, &self.sheet, &shadow_sheets, &mut matcher,+ &mut self.styles, &mut self.custom_properties, &props, &mut None, self.quirks,+ self.viewport, crate::AnimationSample::default(), &mut timeline,+ cell_padding, dark, None, ancestor_display_none,+ )?;+ props = next_props;+ cell_padding = next_padding;+ dark = next_dark;+ if !element { continue; }+ matcher.push_ancestor(tree, node);+ let style = self.styles.get_mut(&node)?;+ ancestor_display_none |= style.display == crate::Display::None;+ // Display inheritance and live effects retain the complete normalization+ // path. A query cannot become active without a query container on this+ // ancestor path, including named normal/style containers.+ if style.display_inherit || style.animation_name.is_some()+ || (self.has_container_queries+ && (style.container_type != crate::ContainerType::Normal+ || !style.container_names.is_empty()))+ {+ return None;+ }+ color = style.color.or(color);+ style.color = color;+ pointer_events = style.pointer_events_none.unwrap_or(pointer_events);+ style.pointer_events_none = Some(pointer_events);+ // Normalize before retaining an ancestor for its next descendant.+ if root || (parent_is_item_container && !style.display_contents)+ || style.position == Some(taffy::Position::Absolute) || style.float.is_some()+ {+ crate::blockify_outer_display(style);+ }+ root = false;+ if !style.display_contents {+ parent_is_item_container = style.display == crate::Display::Grid+ || (style.display == crate::Display::Flex && !style.internal_flex_container);+ }+ self.ancestors.insert(node, (cell_padding, dark, ancestor_display_none, parent_is_item_container));}+ Some(crate::paint::non_geometric_computed_style(self.styles.get(&id)?))}- Some(crate::paint::non_geometric_computed_style(styles.get(&id)?))}fn document_stylesheet_sources(diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex 1cc00704..f3370cfc 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -1705,6 +1705,15 @@ impl PreparedRender {None}+ /// Read common style-only properties without copying the full CSSOM and+ /// inherited custom-property environment for each element.+ pub fn computed_non_geometric_style(+ &self,+ id: obscura_dom::tree::NodeId,+ ) -> Option<HashMap<&'static str, String>> {+ Some(non_geometric_computed_style(self.layout.styles.get(&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,@@ -12597,6 +12606,9 @@ mod tests {for active in ["yes", "no"] {tree.with_node_mut(body, |node| node.set_attribute("data-active", active.into()));let full = prepare_dom(&tree, viewport, None, &mut resources).unwrap();+ let mut shared = crate::dom::NonGeometricStyleCache::new(+ &tree, viewport, crate::CssMediaType::Screen, &cache,+ ).unwrap();for name in ["flex", "contents", "item", "float", "suppressed", "suppressed-child"] {let id = tree.get_element_by_id(name).unwrap();let fast = crate::dom::computed_style_without_layout(@@ -12607,6 +12619,16 @@ mod tests {assert_eq!(value, expected[property], "{name}.{property} with {active}");}}+ // Reverse the usual traversal, crossing branches and then reading+ // cached ancestors after their children.+ for name in ["item", "contents", "flex", "suppressed-child", "suppressed", "float"] {+ let id = tree.get_element_by_id(name).unwrap();+ let fast = shared.resolve(&tree, id, "color").unwrap();+ let expected = full.computed_style(id).unwrap();+ for (property, value) in fast {+ assert_eq!(value, expected[property], "shared {name}.{property} with {active}");+ }+ }for name in ["inherit", "hidden", "animated", "query"] {assert!(crate::dom::computed_style_without_layout(&tree, tree.get_element_by_id(name).unwrap(), viewport,