The headless browser for AI agents and web scraping
Reuse geometry during paint-only animations
SGavrl292ca755a7bd
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex a6f6d78e..c82c0263 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -2521,7 +2521,10 @@ mod tests {use super::{cors_response_allows, glob_match, validate_fetch_url, FetchCredentials};#[cfg(feature = "render")]- use super::{node_is_connected, retained_style_mutation, shadow_including_connected_nodes};+ use super::{+ ensure_prepared_geometry, ensure_prepared_render, node_is_connected,+ retained_style_mutation, shadow_including_connected_nodes, ObscuraState,+ };#[cfg(feature = "render")]use obscura_dom::{parse_html, ShadowRootMode};@@ -2631,6 +2634,60 @@ mod tests {assert!(!node_is_connected(&dom, child));assert!(!shadow_including_connected_nodes(&dom).contains(&child));}++ #[cfg(feature = "render")]+ #[test]+ fn geometry_consumer_defers_paint_only_sample_until_exact_consumer() {+ let dom = parse_html(+ r#"<style>+ @keyframes fade { from { opacity:0 } to { opacity:1 } }+ #box { width:40px;height:20px;animation:fade 1000ms linear both }+ </style><div id="box"></div>"#,+ );+ let box_node = dom.get_element_by_id("box").unwrap();+ let mut state = ObscuraState::new();+ state.dom = Some(dom);+ state.animation_sample = obscura_render::AnimationSample::document(0.0);+ ensure_prepared_render(&mut state).expect("initial render");+ assert_eq!(+ state.prepared_render.as_ref().unwrap().layout().styles[&box_node].opacity,+ Some(0.0),+ );++ state.animation_sample = obscura_render::AnimationSample::document(500.0);+ let geometry = ensure_prepared_geometry(&mut state).expect("retained geometry");+ assert_eq!(geometry.animation_sample_time().milliseconds, 0.0);+ assert_eq!(geometry.document_rect(box_node).unwrap().width, 40.0);+ assert_eq!(geometry.layout().styles[&box_node].opacity, Some(0.0));++ let exact = ensure_prepared_render(&mut state).expect("exact sampled style");+ assert_eq!(exact.animation_sample_time().milliseconds, 500.0);+ let opacity = exact.layout().styles[&box_node].opacity.unwrap();+ assert!((opacity - 0.5).abs() < 0.01, "exact opacity was {opacity}");+ assert_eq!(exact.document_rect(box_node).unwrap().width, 40.0);+ }++ #[cfg(feature = "render")]+ #[test]+ fn geometry_consumer_materializes_geometry_animation_sample() {+ let dom = parse_html(+ r#"<style>+ @keyframes grow { from { width:20px } to { width:100px } }+ #box { height:20px;animation:grow 1000ms linear both }+ </style><div id="box"></div>"#,+ );+ let box_node = dom.get_element_by_id("box").unwrap();+ let mut state = ObscuraState::new();+ state.dom = Some(dom);+ state.animation_sample = obscura_render::AnimationSample::document(0.0);+ ensure_prepared_render(&mut state).expect("initial render");++ state.animation_sample = obscura_render::AnimationSample::document(500.0);+ let geometry = ensure_prepared_geometry(&mut state).expect("sampled geometry");+ assert_eq!(geometry.animation_sample_time().milliseconds, 500.0);+ let width = geometry.document_rect(box_node).unwrap().width;+ assert!((width - 60.0).abs() < 0.1, "sampled width was {width}");+ }}fn validate_fetch_url(url: &url::Url, allow_private_network: bool) -> Result<(), String> {@@ -3739,6 +3796,29 @@ pub(crate) fn ensure_prepared_render(state.prepared_render.as_ref()}+/// Prepare enough state for a geometry-only CSSOM consumer. A forward sample+/// with only paint effects may read the retained layout without resampling its+/// 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> {+ let base_url = document_base_url(state);+ let reusable = state.pending_style_mutations.is_empty()+ && !state.animation_timeline.has_pending_start_candidates()+ && 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))+ });+ if reusable {+ return state.prepared_render.as_ref();+ }+ ensure_prepared_render(state)+}+#[cfg(feature = "render")]pub(crate) fn sample_live_document_animations(state: &mut ObscuraState) {if state.animation_sampled_task_generation == state.animation_task_generation {@@ -3787,7 +3867,24 @@ fn op_begin_render_task(state: &OpState) {#[cfg(feature = "render")]pub(crate) fn ensure_resolved_scroll(state: &mut ObscuraState) -> Option<()> {- ensure_prepared_render(state)?;+ ensure_resolved_scroll_for_consumer(state, false)+}++#[cfg(feature = "render")]+fn ensure_resolved_scroll_for_geometry(state: &mut ObscuraState) -> Option<()> {+ ensure_resolved_scroll_for_consumer(state, true)+}++#[cfg(feature = "render")]+fn ensure_resolved_scroll_for_consumer(+ state: &mut ObscuraState,+ geometry_only: bool,+) -> Option<()> {+ if geometry_only {+ ensure_prepared_geometry(state)?;+ } else {+ ensure_prepared_render(state)?;+ }if state.resolved_scroll.as_ref()@@ -4206,7 +4303,29 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> String#[cfg(feature = "render")]pub(crate) fn clamp_scroll_offset(state: &mut ObscuraState, requested: (f32, f32)) -> (f32, f32) {- let clamped = ensure_prepared_render(state)+ clamp_scroll_offset_for_consumer(state, requested, false)+}++#[cfg(feature = "render")]+fn clamp_scroll_offset_for_geometry(+ state: &mut ObscuraState,+ requested: (f32, f32),+) -> (f32, f32) {+ clamp_scroll_offset_for_consumer(state, requested, true)+}++#[cfg(feature = "render")]+fn clamp_scroll_offset_for_consumer(+ state: &mut ObscuraState,+ requested: (f32, f32),+ geometry_only: bool,+) -> (f32, f32) {+ let prepared = if geometry_only {+ ensure_prepared_geometry(state)+ } else {+ ensure_prepared_render(state)+ };+ let clamped = prepared.map(|prepared| prepared.clamp_scroll(requested)).unwrap_or((0.0, 0.0));if state.scroll_offset != clamped {@@ -4236,7 +4355,7 @@ fn op_layout_geometry(state: &OpState, #[string] nid_str: String) -> String {let nid = obscura_dom::tree::NodeId::new(nid);let mut gs = shared.borrow_mut();sample_live_document_animations(&mut gs);- if ensure_resolved_scroll(&mut gs).is_some() {+ if ensure_resolved_scroll_for_geometry(&mut gs).is_some() {let Some((_, scroll)) = gs.resolved_scroll.as_ref() else {return String::new();};@@ -4301,7 +4420,7 @@ fn op_resize_observer_measurements(state: &OpState, #[string] nids_json: String)let shared = state.borrow::<SharedState>().clone();let mut gs = shared.borrow_mut();sample_live_document_animations(&mut gs);- if ensure_resolved_scroll(&mut gs).is_none() {+ if ensure_resolved_scroll_for_geometry(&mut gs).is_none() {return serde_json::to_string(&vec![serde_json::Value::Null; nids.len()]).unwrap_or_else(|_| "[]".to_string());}@@ -4369,7 +4488,7 @@ fn op_intersection_observer_measurements(let shared = state.borrow::<SharedState>().clone();let mut gs = shared.borrow_mut();sample_live_document_animations(&mut gs);- if ensure_resolved_scroll(&mut gs).is_none() {+ if ensure_resolved_scroll_for_geometry(&mut gs).is_none() {return serde_json::to_string(&vec![serde_json::Value::Null; nids.len()]).unwrap_or_else(|_| "[]".to_string());}@@ -4459,7 +4578,7 @@ fn op_layout_metrics(state: &OpState) -> String {let mut gs = shared.borrow_mut();sample_live_document_animations(&mut gs);let viewport = gs.viewport;- let content = ensure_prepared_render(&mut gs)+ let content = ensure_prepared_geometry(&mut gs).map(|prepared| prepared.content_size()).unwrap_or(viewport);format!(@@ -4476,7 +4595,7 @@ fn op_element_scroll_metrics(state: &OpState, #[string] nid_str: String) -> Strilet nid = NodeId::new(nid_str.parse().unwrap_or(0));let mut gs = shared.borrow_mut();sample_live_document_animations(&mut gs);- if ensure_resolved_scroll(&mut gs).is_none() {+ if ensure_resolved_scroll_for_geometry(&mut gs).is_none() {return String::new();}let Some((_, scroll)) = gs.resolved_scroll.as_ref() else {@@ -4513,7 +4632,7 @@ fn op_element_scroll_to(state: &OpState, #[string] nid_str: String, x: f64, y: flet nid = NodeId::new(nid_str.parse().unwrap_or(0));let mut gs = shared.borrow_mut();sample_live_document_animations(&mut gs);- if ensure_resolved_scroll(&mut gs).is_none() {+ if ensure_resolved_scroll_for_geometry(&mut gs).is_none() {return String::new();}let current = gs.resolved_scroll.as_ref().and_then(|(_, scroll)| {@@ -4557,7 +4676,7 @@ fn op_scroll_offset(state: &OpState) -> String {let mut gs = shared.borrow_mut();sample_live_document_animations(&mut gs);let requested = gs.scroll_offset;- let (x, y) = clamp_scroll_offset(&mut gs, requested);+ let (x, y) = clamp_scroll_offset_for_geometry(&mut gs, requested);format!("{{\"x\":{},\"y\":{}}}", x, y)}@@ -4568,6 +4687,6 @@ fn op_scroll_to(state: &OpState, x: f64, y: f64) -> String {let shared = state.borrow::<SharedState>().clone();let mut gs = shared.borrow_mut();sample_live_document_animations(&mut gs);- let (x, y) = clamp_scroll_offset(&mut gs, (x as f32, y as f32));+ let (x, y) = clamp_scroll_offset_for_geometry(&mut gs, (x as f32, y as f32));format!("{{\"x\":{},\"y\":{}}}", x, y)}diff --git a/crates/obscura-render/src/css.rs b/crates/obscura-render/src/css.rsindex 68e9cfc8..0486c424 100644--- a/crates/obscura-render/src/css.rs+++ b/crates/obscura-render/src/css.rs@@ -1937,6 +1937,48 @@ enum AnimatedProperty {Visibility,}+impl AnimatedProperty {+ fn effect_impact(self) -> crate::AnimationEffectImpact {+ use AnimatedProperty::*;+ match self {+ Opacity+ | Color+ | BackgroundColor+ | BorderTopColor+ | BorderRightColor+ | BorderBottomColor+ | BorderLeftColor+ | BackgroundPosition+ | Visibility => crate::AnimationEffectImpact::Paint,+ Transform+ | Translate+ | Rotate+ | Scale+ | Width+ | Height+ | MinWidth+ | MinHeight+ | MaxWidth+ | MaxHeight+ | Top+ | Right+ | Bottom+ | Left+ | MarginTop+ | MarginRight+ | MarginBottom+ | MarginLeft+ | PaddingTop+ | PaddingRight+ | PaddingBottom+ | PaddingLeft+ | RowGap+ | ColumnGap+ | FlexBasis => crate::AnimationEffectImpact::Geometry,+ }+ }+}+#[derive(Clone, Debug, PartialEq, Eq)]struct AnimatedDeclaration {name: String,@@ -3960,6 +4002,7 @@ impl Stylesheet {.iter().any(|&(_, _, i)| self.rules[i].important_flags.has_animation);style.animation_has_render_effect = false;+ style.animation_effect_impact = crate::AnimationEffectImpact::None;if !self.keyframes.is_empty() && (style.animation_name.is_some() || important_has_animation){let mut animation_style = style.clone();@@ -3994,6 +4037,13 @@ impl Stylesheet {if let Some(name) = animation_style.animation_name.as_deref() {if let Some(keyframes) = self.keyframes.get(name) {style.animation_has_render_effect = !keyframes.tracks.is_empty();+ style.animation_effect_impact = keyframes+ .tracks+ .keys()+ .copied()+ .map(AnimatedProperty::effect_impact)+ .max()+ .unwrap_or_default();let local_sample = animation_timeline.sample_for(nid,crate::AnimationInstanceKey {@@ -8209,6 +8259,50 @@ mod tests {);}+ #[test]+ fn animation_effect_impact_separates_paint_from_geometry_tracks() {+ let sampled = |declarations: &str| {+ sampled_animation_style(+ &format!(+ "@keyframes effect {{ from {{ {declarations} }} to {{ {declarations} }} }}\+ #target {{ animation:effect 1s linear infinite }}"+ ),+ 100.0,+ "target",+ )+ .animation_effect_impact+ };++ assert_eq!(+ sampled("opacity:.5;color:red;background-color:blue;border-color:green;\+ background-position:20% 30%;visibility:hidden"),+ crate::AnimationEffectImpact::Paint,+ );+ for declarations in [+ "transform:translateX(1px)",+ "translate:1px 2px",+ "rotate:10deg",+ "scale:2",+ "width:20px",+ "height:20px",+ "inset:1px",+ "margin:1px",+ "padding:1px",+ "gap:1px",+ "flex-basis:20px",+ ] {+ assert_eq!(+ sampled(declarations),+ crate::AnimationEffectImpact::Geometry,+ "{declarations}",+ );+ }+ assert_eq!(+ sampled("--unsupported:1"),+ crate::AnimationEffectImpact::None,+ );+ }+#[test]fn animation_samples_geometry_transform_and_paint_properties_at_t0() {let css = r#"diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rsindex 1fd63817..e1a269c7 100644--- a/crates/obscura-render/src/lib.rs+++ b/crates/obscura-render/src/lib.rs@@ -1237,6 +1237,10 @@ pub struct LayoutStyle {/// renderer can sample. Unsupported custom-property-only animations must/// not keep layout or screencast damage active forever.pub animation_has_render_effect: bool,+ /// Strongest effect of the selected CSS keyframes. Geometry consumers use+ /// this to retain an older sampled layout only when every live effect is+ /// known to be paint-only.+ pub(crate) animation_effect_impact: AnimationEffectImpact,/// Local time used for this element's sampled animation instance.pub animation_local_time_ms: f32,/// `vertical-align` for a table cell's content. Cells effectively default@@ -1714,6 +1718,19 @@ pub struct AnimationSample {pub mode: AnimationSampleMode,}+/// Strongest renderer-visible consequence of an animation effect.+///+/// Ordering is intentional: aggregating with `max` keeps unknown or+/// geometry-affecting tracks conservative while still distinguishing+/// compositor/paint-only effects from an inactive animation.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]+pub enum AnimationEffectImpact {+ #[default]+ None,+ Paint,+ Geometry,+}+impl AnimationSample {pub fn document(milliseconds: f32) -> Self {Self {@@ -1969,20 +1986,39 @@ impl AnimationTimelineState {}pub(crate) fn has_active_waapi(&self, document_time: AnimationSampleTime) -> bool {- self.waapi.values().any(|animation| {- if animation.play_state != WaapiPlayState::Running- || animation.timing.duration_ms <= 0.0- || animation.timing.iteration_count <= 0.0- {- return false;- }- let local = animation.hold_time_ms.unwrap_or_else(|| {- (document_time.milliseconds - animation.start_time_ms).max(0.0)- });- let end = animation.timing.delay_ms- + animation.timing.duration_ms * animation.timing.iteration_count;- local < end.max(0.0)- })+ self.waapi+ .values()+ .any(|animation| waapi_is_active(animation, document_time))+ }++ pub(crate) fn active_waapi_effect_impact(+ &self,+ document_time: AnimationSampleTime,+ ) -> AnimationEffectImpact {+ self.waapi+ .values()+ .filter(|animation| waapi_is_active(animation, document_time))+ .map(|animation| {+ if animation+ .keyframes+ .iter()+ .any(|frame| frame.transform.is_some())+ {+ // A specified WAAPI transform remains geometry-affecting+ // even when this renderer cannot parse its value.+ AnimationEffectImpact::Geometry+ } else if animation+ .keyframes+ .iter()+ .any(|frame| frame.opacity.is_some())+ {+ AnimationEffectImpact::Paint+ } else {+ AnimationEffectImpact::None+ }+ })+ .max()+ .unwrap_or_default()}pub(crate) fn sample_for(@@ -2058,6 +2094,21 @@ impl AnimationTimelineState {}}+fn waapi_is_active(animation: &WaapiAnimation, document_time: AnimationSampleTime) -> bool {+ if animation.play_state != WaapiPlayState::Running+ || animation.timing.duration_ms <= 0.0+ || animation.timing.iteration_count <= 0.0+ {+ return false;+ }+ let local = animation.hold_time_ms.unwrap_or_else(|| {+ (document_time.milliseconds - animation.start_time_ms).max(0.0)+ });+ let end = animation.timing.delay_ms+ + animation.timing.duration_ms * animation.timing.iteration_count;+ local < end.max(0.0)+}+/// The implemented `text-wrap-style` values. Other line-breaking strategies/// such as `pretty` remain unsupported until their distinct scoring model is/// available; treating them as `auto` would make `@supports` lie.diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex e6c1922d..e1fee51a 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -831,6 +831,7 @@ pub struct PreparedRender {viewport: (f32, f32),animation_sample: crate::AnimationSample,has_active_waapi_animations: bool,+ active_animation_impact: crate::AnimationEffectImpact,root_font_size: f32,base_url: Option<String>,content_size: (f32, f32),@@ -859,19 +860,26 @@ 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(|style| {- if style.animation_name.is_none()- || !style.animation_has_render_effect- || style.animation_timing.play_state == crate::AnimationPlayState::Paused- || style.animation_timing.duration_ms <= 0.0- || style.animation_timing.iteration_count <= 0.0- {- return false;- }- let end = style.animation_timing.delay_ms- + style.animation_timing.duration_ms * style.animation_timing.iteration_count;- end.is_infinite() || style.animation_local_time_ms < end.max(0.0)- })+ self.has_active_waapi_animations+ || self+ .layout+ .styles+ .values()+ .any(css_animation_is_active)+ }++ /// Whether a geometry-only consumer may retain this layout while moving+ /// 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 {+ sample.mode == crate::AnimationSampleMode::DocumentTime+ && self.animation_sample.mode == crate::AnimationSampleMode::DocumentTime+ && sample.time.milliseconds >= self.animation_sample.time.milliseconds+ && self.active_animation_impact < crate::AnimationEffectImpact::Geometry}/// Advance a frame whose animation cascade is already time-invariant.@@ -2376,6 +2384,16 @@ fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_internal(viewport,animation_sample,has_active_waapi_animations: animation_timeline.has_active_waapi(animation_sample.time),+ active_animation_impact: laid+ .styles+ .values()+ .filter(|style| css_animation_is_active(style))+ .map(|style| style.animation_effect_impact)+ .chain(std::iter::once(+ animation_timeline.active_waapi_effect_impact(animation_sample.time),+ ))+ .max()+ .unwrap_or_default(),root_font_size,base_url: base_url.map(str::to_string),content_size,@@ -2388,6 +2406,20 @@ fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_internal(})}+fn css_animation_is_active(style: &crate::LayoutStyle) -> bool {+ if style.animation_name.is_none()+ || !style.animation_has_render_effect+ || style.animation_timing.play_state == crate::AnimationPlayState::Paused+ || style.animation_timing.duration_ms <= 0.0+ || style.animation_timing.iteration_count <= 0.0+ {+ return false;+ }+ let end = style.animation_timing.delay_ms+ + style.animation_timing.duration_ms * style.animation_timing.iteration_count;+ end.is_infinite() || style.animation_local_time_ms < end.max(0.0)+}+/// Paint one root-scroll position from an already prepared resource-aware/// layout. Resource bytes and glyph caches are reused across calls.pub fn paint_prepared(@@ -15534,6 +15566,46 @@ mod tests {);}+ #[test]+ fn active_waapi_transform_is_conservatively_geometry_affecting() {+ let tree = parse_html("<div id=target></div>");+ let target = tree.get_element_by_id("target").unwrap();+ let animation = |id, opacity, transform| crate::WaapiAnimation {+ id,+ node: target,+ keyframes: vec![crate::WaapiKeyframe {+ offset: 0.0,+ opacity,+ transform,+ }],+ timing: crate::AnimationTiming {+ duration_ms: 1_000.0,+ ..crate::AnimationTiming::default()+ },+ easing: None,+ linear_easing: None,+ start_time_ms: 0.0,+ hold_time_ms: None,+ play_state: crate::WaapiPlayState::Running,+ };+ 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()),+ ));+ assert_eq!(+ timeline.active_waapi_effect_impact(sample),+ crate::AnimationEffectImpact::Geometry,+ );+ }+#[test]fn prepared_render_samples_explicit_animation_time_and_reports_live_damage() {let tree = parse_html(