The headless browser for AI agents and web scraping
fix(render): invalidate attribute-derived retained content
SGavrl32fb98f6196b
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rsindex 66b4196e..95a60456 100644--- a/crates/obscura-dom/src/tree.rs+++ b/crates/obscura-dom/src/tree.rs@@ -637,6 +637,11 @@ impl DomTree {self.inner.borrow().shadow_roots_by_host.get(&host).copied()}+ /// Whether any native shadow roots exist, including detached roots.+ pub fn has_shadow_roots(&self) -> bool {+ !self.inner.borrow().shadow_roots.is_empty()+ }+pub fn shadow_root_info(&self, root: NodeId) -> Option<ShadowRoot> {self.inner.borrow().shadow_roots.get(&root).copied()}diff --git a/crates/obscura-render/src/css.rs b/crates/obscura-render/src/css.rsindex 0a592374..d5c08f77 100644--- a/crates/obscura-render/src/css.rs+++ b/crates/obscura-render/src/css.rs@@ -244,9 +244,14 @@ pub struct InvalidationMap {adjacent_sibling_selectors: bool,general_sibling_selectors: bool,unkeyed_sibling_selectors: bool,+ dynamic_attribute_reads: bool,}impl InvalidationMap {+ pub(crate) fn has_dynamic_attribute_reads(&self) -> bool {+ self.dynamic_attribute_reads+ }+pub fn id_dependencies(&self, id: &str) -> &[InvalidationDependency] {self.ids.get(id).map(Vec::as_slice).unwrap_or(&[])}@@ -1443,6 +1448,16 @@ fn note_selector_for_invalidation(/// in the selector. Keep this deliberately broader than the property parser;/// an extra self invalidation is cheap, while missing a supported `attr()`/// spelling would retain stale computed values.+#[cfg(feature = "paint")]+pub(crate) fn declaration_value_reads_attribute(value: &str, attribute: &str) -> bool {+ if !value.as_bytes().windows(4).any(|part| part.eq_ignore_ascii_case(b"attr")) {+ return false;+ }+ let mut dependencies = InvalidationMap::default();+ note_declaration_attribute_dependencies(&mut dependencies, value, 0);+ dependencies.has_dynamic_attribute_reads() || !dependencies.attribute_dependencies(attribute).is_empty()+}+fn note_declaration_attribute_dependencies(map: &mut InvalidationMap,declarations: &str,@@ -1518,6 +1533,10 @@ fn note_declaration_attribute_dependencies(name_start += 1;}let (attribute, name_end) = consume_css_identifier(&chars, name_start);+ if chars.get(name_end) == Some(&'(') {+ // An attribute name supplied by var() is resolved at computed-value time.+ map.dynamic_attribute_reads = true;+ }if !attribute.is_empty() && name_end <= close {map.push_attribute(attribute, rule_order, InvalidationReaches::SELF);}diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex f02d0e16..04941129 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -4098,6 +4098,9 @@ fn retained_style_plan(}let map = sheet.invalidation_map();+ if map.has_dynamic_attribute_reads() {+ return RetainedStylePlan::Full;+ }let mut dependencies = Vec::new();dependencies.extend_from_slice(map.attribute_dependencies(&name));if name == "id" {@@ -4212,12 +4215,17 @@ fn shadow_stylesheets_ignore_attributes<'a>(viewport: (f32, f32),names: impl Iterator<Item = &'a str> + Clone,) -> bool {- collect_shadow_stylesheets(tree, viewport, crate::CssMediaType::Screen)+ collect_shadow_stylesheet_sources(tree, viewport, crate::CssMediaType::Screen).values()- .all(|sheet| {- names- .clone()- .all(|name| sheet.invalidation_map().attribute_dependencies(name).is_empty())+ .flatten()+ .all(|source| {+ let bytes = source.as_bytes();+ // shortcut: uncertain source spellings use full layout; avoid parsing+ // shadow CSS twice when a dependency already requires that fallback.+ !bytes.contains(&b'\\')+ && !bytes.windows(4).any(|part| part.eq_ignore_ascii_case(b"attr"))+ && names.clone().all(|name| !name.is_empty()+ && !bytes.windows(name.len()).any(|part| part.eq_ignore_ascii_case(name.as_bytes())))})}@@ -4261,7 +4269,8 @@ pub(crate) fn image_source_updates_without_style_damage(}let sources = document_stylesheet_sources(tree, viewport, crate::CssMediaType::Screen);let (sheet, cache_hit) = cache.get_or_parse(tree, &sources, viewport, crate::CssMediaType::Screen);- if !cache_hit || names.iter().any(|name| !sheet.invalidation_map().attribute_dependencies(name).is_empty())+ if !cache_hit || sheet.invalidation_map().has_dynamic_attribute_reads()+ || names.iter().any(|name| !sheet.invalidation_map().attribute_dependencies(name).is_empty())|| !shadow_stylesheets_ignore_attributes(tree, viewport, names.iter().map(String::as_str)){return None;@@ -4490,6 +4499,25 @@ fn collect_shadow_stylesheets(viewport: (f32, f32),media_type: crate::CssMediaType,) -> HashMap<NodeId, std::sync::Arc<crate::css::Stylesheet>> {+ collect_shadow_stylesheet_sources(tree, viewport, media_type)+ .into_iter()+ .map(|(root, sources)| {+ let sheet = crate::css::Stylesheet::parse_for_viewport_and_media(+ tree, &sources, viewport, media_type,+ );+ (root, std::sync::Arc::new(sheet))+ })+ .collect()+}++fn collect_shadow_stylesheet_sources(+ tree: &DomTree,+ viewport: (f32, f32),+ media_type: crate::CssMediaType,+) -> HashMap<NodeId, Vec<String>> {+ if !tree.has_shadow_roots() {+ return HashMap::new();+ }let external = tree.external_stylesheets();let mut roots = Vec::new();let mut stack = vec![tree.document()];@@ -4542,10 +4570,7 @@ fn collect_shadow_stylesheets(sources.push(tree.text_content(node_id));}}- let sheet = crate::css::Stylesheet::parse_for_viewport_and_media(- tree, &sources, viewport, media_type,- );- (root, std::sync::Arc::new(sheet))+ (root, sources)}).collect()}diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex 74b594fe..100c91fb 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -2945,6 +2945,20 @@ pub fn prepare_dom_with_retained_styles_at_animation_time()}+fn cached_custom_properties_ignore_attributes(+ previous: &PreparedRender,+ mutations: &[crate::dom::RetainedStyleMutation],+) -> bool {+ mutations.iter().all(|mutation| {+ let crate::dom::RetainedStyleMutation::Attribute(attribute) = mutation else { return true; };+ previous.layout.custom_properties.get(&attribute.node).is_none_or(|properties| {+ properties.values().all(|value| {+ !crate::css::declaration_value_reads_attribute(value, &attribute.name)+ })+ })+ })+}+pub fn prepare_dom_with_retained_styles_with_animation_state(tree: &DomTree,viewport: (f32, f32),@@ -2962,7 +2976,9 @@ pub fn prepare_dom_with_retained_styles_with_animation_state(&& previous.animation_sample.mode == crate::AnimationSampleMode::DocumentTime&& animation_sample.mode == crate::AnimationSampleMode::DocumentTime&& animation_sample.time.milliseconds >= previous.animation_sample.time.milliseconds;- if sample_changed && !forward_document_sample {+ if (sample_changed && !forward_document_sample)+ || !cached_custom_properties_ignore_attributes(&previous, mutations)+ {drop(previous);return prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(tree,@@ -13107,6 +13123,67 @@ mod tests {}}+ #[test]+ fn retained_content_tracks_attributes_read_through_inline_custom_properties() {+ let mut failures = Vec::new();+ for (binding, content_value, inline) in [+ ("inline", "var(--label)", "--label:attr(data-label)"),+ ("dynamic-inline", "var(--label)", "--key:data-label;--label:attr(var(--key))"),+ ("dynamic-sheet", "attr(var(--key))", "--key:data-label"),+ ] {+ for shadow in [true, false] {+ let content = format!(r#"<style>+ span {{ display:inline-block; font-size:24px }}+ span::before {{ content:{content_value} }}+ i {{ display:inline-block; width:12px; height:12px; background:red }}+ </style><span data-label="A" style="{inline}"></span><i></i>"#);+ let html = if shadow {+ format!("<x-host id=host><template shadowrootmode=open>{content}</template></x-host>")+ } else { content.to_string() };+ let tree = parse_html(&html);+ let root = if shadow {+ tree.shadow_root(tree.get_element_by_id("host").unwrap()).unwrap()+ } else { tree.document() };+ let target = tree.descendants(root).into_iter().find(|id| {+ tree.with_node(*id, |node| node.get_attribute("data-label").is_some()).unwrap_or(false)+ }).unwrap();+ let viewport = (400.0, 160.0);+ let mut resources = RenderResourceCache::with_loader(|_: &str| None);+ let mut cache = crate::css::StylesheetCache::default();+ let mut previous = prepare_dom_with_dynamic_fonts_and_stylesheet_cache(+ &tree, viewport, None, &mut resources, &[], &mut cache,+ ).unwrap();+ let before = paint_prepared(&tree, &mut previous, &mut resources, (0.0, 0.0)).unwrap();+ tree.with_node_mut(target, |node| node.set_attribute("data-label", "Longer label".into()));+ let mut retained = prepare_dom_with_retained_attribute_styles(+ &tree, viewport, None, &mut resources, &[], &mut cache, previous,+ &[crate::dom::AttributeStyleMutation {+ node: target, name: "data-label".into(), old_value: Some("A".into()),+ new_value: Some("Longer label".into()),+ }],+ ).unwrap();+ let mut oracle = prepare_dom(&tree, viewport, None, &mut resources).unwrap();+ let expected = paint_prepared(&tree, &mut oracle, &mut resources, (0.0, 0.0)).unwrap();+ let actual = paint_prepared(&tree, &mut retained, &mut resources, (0.0, 0.0)).unwrap();+ if let Some(directory) = std::env::var_os("OBSCURA_RENDER_EVIDENCE_DIR") {+ let directory = std::path::PathBuf::from(directory);+ std::fs::create_dir_all(&directory).unwrap();+ let scope = format!("{}-{binding}", if shadow { "shadow" } else { "light" });+ before.save_png(directory.join(format!("initial-{scope}.png"))).unwrap();+ actual.save_png(directory.join(format!("actual-{scope}.png"))).unwrap();+ expected.save_png(directory.join(format!("oracle-{scope}.png"))).unwrap();+ }+ if binding == "inline" {+ assert!(before.data() != expected.data(), "fixture must change generated content: shadow={shadow}");+ }+ if retained.layout.rects != oracle.layout.rects || actual.data() != expected.data() {+ failures.push(format!("{binding}, shadow={shadow}"));+ }+ }+ }+ assert!(failures.is_empty(), "stale generated content: {failures:?}");+ }+#[test]fn retained_image_source_changes_preserve_equal_intrinsics_and_refresh_pixels() {let make_resources = || {