Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(rendering): avoid stylesheet reparsing during animation scans

ldm0458f3c995148
diff --git a/moli-renderer-v8/src/native_bridge/element/animations.rs b/moli-renderer-v8/src/native_bridge/element/animations.rs
index c6a5c4595..7d87f7db3 100644
--- a/moli-renderer-v8/src/native_bridge/element/animations.rs
+++ b/moli-renderer-v8/src/native_bridge/element/animations.rs
@@ -3,6 +3,7 @@ use crate::native_bridge::JsContextHost;
use super::css_animation_start_applies;
use super::events::{construct_simple_event, dispatch_public_event};
+use super::styles::StyleObservation;
pub(crate) fn queue_animation_start_for_listener_target(
scope: &mut v8::PinScope<'_, '_>,
@@ -15,13 +16,19 @@ pub(crate) fn queue_animation_start_for_listener_target(
fn active_animation_handles(runtime: &JsContextHost, document_handle: DomHandle) -> Vec<DomHandle> {
let mut out = Vec::new();
let mut stack = vec![document_handle];
+ // The traversal has no script callbacks. Share its style observation, then
+ // revalidate each candidate separately when dispatching reentrant listeners.
+ let mut observation = StyleObservation::new(runtime);
while let Some(handle) = stack.pop() {
- if css_animation_start_applies(runtime, handle) {
- out.push(handle);
- }
let Some(node) = runtime.dom_host().node(handle) else {
continue;
};
+ if node.is_connected()
+ && node.as_element().is_some()
+ && observation.read(handle).css_animation_start_applies()
+ {
+ out.push(handle);
+ }
let mut children = runtime.dom_host().child_handles(handle).collect::<Vec<_>>();
if node.as_element().is_some()
&& let Some(shadow_root) = runtime.dom_host().shadow_root_handle(handle)
diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/specified_values.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/specified_values.rs
index 785c80577..e58c24095 100644
--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/specified_values.rs
+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/specified_values.rs
@@ -1,10 +1,6 @@
use super::*;
pub(crate) fn css_animation_start_applies(runtime: &JsContextHost, handle: DomHandle) -> bool {
- // This is a yes/no predicate for queuing animationstart, not a computed-style
- // value read. Resolve active animation names once and scan keyframes for the
- // small property subset Moli models instead of rewalking stylesheets once
- // per supported property.
if !runtime
.dom_host()
.node(handle)
@@ -13,27 +9,35 @@ pub(crate) fn css_animation_start_applies(runtime: &JsContextHost, handle: DomHa
return false;
}
- let read = ComputedStyleRead::new(runtime, handle);
- let resolution = read.resolution_context();
- let names = active_css_animation_names_with_resolution(runtime, handle, resolution);
- if names.is_empty() {
- return false;
- }
+ ComputedStyleRead::new(runtime, handle).css_animation_start_applies()
+}
- let Some(document) = stylesheet_source_document_for_handle(runtime, handle) else {
- return false;
- };
- for source in effective_raw_stylesheet_sources(
- runtime,
- document,
- false,
- resolution.computation.viewport(),
- ) {
- if keyframe_has_supported_animation_values(&source.serialized_css_text(), &names) {
- return true;
+impl ComputedStyleRead<'_> {
+ pub(in crate::native_bridge::element) fn css_animation_start_applies(&self) -> bool {
+ let resolution = self.resolution_context();
+ let names =
+ active_css_animation_names_with_resolution(self.runtime, self.handle, resolution);
+ if names.is_empty() {
+ return false;
+ }
+
+ let Some(document) = stylesheet_source_document_for_handle(self.runtime, self.handle)
+ else {
+ return false;
+ };
+ for source in effective_raw_stylesheet_sources(
+ self.runtime,
+ document,
+ false,
+ resolution.computation.viewport(),
+ ) {
+ let rules = source_keyframe_rule_snapshots(&source, &names);
+ if keyframe_rule_snapshots_have_supported_animation_values(&rules, &names, 0) {
+ return true;
+ }
}
+ false
}
- false
}
pub(super) fn active_css_animation_midpoint_px_with_resolution(
@@ -144,9 +148,8 @@ fn active_css_animation_property_values_with_resolution(
false,
resolution.computation.viewport(),
) {
- if let Some(values) =
- keyframe_property_values(&source.serialized_css_text(), &names, property)
- {
+ let rules = source_keyframe_rule_snapshots(&source, &names);
+ if let Some(values) = keyframe_rule_snapshots_property_values(&rules, &names, property, 0) {
return Some(values);
}
}
@@ -227,6 +230,68 @@ fn ident_is_animation_shorthand_keyword(value: &str) -> bool {
)
}
+/// Installed stylesheets already own a parsed rule tree. Project only matching
+/// keyframes: serializing and reparsing the complete stylesheet for every
+/// animated element can block unrelated script and network tasks for many
+/// seconds on pages with loading skeletons (issue #1698).
+fn source_keyframe_rule_snapshots(
+ source: &StyloStylesheetSource,
+ animation_names: &[String],
+) -> Vec<moli_css_parse::CssRuleSnapshot> {
+ let Some(stylesheet) = source.parsed_stylesheet() else {
+ return moli_css_parse::parse_stylesheet_rule_snapshots_with_stylo(
+ &source.serialized_css_text(),
+ );
+ };
+ let guard = stylesheet.shared_lock.read();
+ let contents = stylesheet.contents.read_with(&guard);
+ let mut snapshots = Vec::new();
+ collect_native_keyframe_rule_snapshots(
+ &contents.rules.read_with(&guard).0,
+ &guard,
+ animation_names,
+ 0,
+ &mut snapshots,
+ );
+ snapshots
+}
+
+fn collect_native_keyframe_rule_snapshots(
+ rules: &[style::stylesheets::CssRule],
+ guard: &style::shared_lock::SharedRwLockReadGuard<'_>,
+ animation_names: &[String],
+ depth: usize,
+ snapshots: &mut Vec<moli_css_parse::CssRuleSnapshot>,
+) {
+ if depth > KEYFRAME_NESTING_DEPTH_LIMIT {
+ return;
+ }
+ for rule in rules {
+ match rule {
+ style::stylesheets::CssRule::Keyframes(keyframes)
+ if animation_names.iter().any(|name| {
+ name.eq_ignore_ascii_case(keyframes.read_with(guard).name.as_atom())
+ }) =>
+ {
+ snapshots.push(moli_css_parse::css_rule_snapshot_from_native_with_stylo(
+ rule, guard,
+ ));
+ }
+ style::stylesheets::CssRule::Media(_) | style::stylesheets::CssRule::Supports(_) => {
+ collect_native_keyframe_rule_snapshots(
+ rule.children(guard),
+ guard,
+ animation_names,
+ depth + 1,
+ snapshots,
+ );
+ }
+ _ => {}
+ }
+ }
+}
+
+#[cfg(test)]
pub(super) fn keyframe_property_values(
css_text: &str,
animation_names: &[String],
@@ -238,6 +303,7 @@ pub(super) fn keyframe_property_values(
pub(super) const KEYFRAME_NESTING_DEPTH_LIMIT: usize = 32;
+#[cfg(test)]
pub(super) fn keyframe_has_supported_animation_values(
css_text: &str,
animation_names: &[String],
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cross_document_and_animations.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cross_document_and_animations.rs
index 5d0f5aedc..20bd6d755 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cross_document_and_animations.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cross_document_and_animations.rs
@@ -1156,6 +1156,100 @@ async fn css_animation_start_and_midpoint_style_are_observable() {
assert_eq!(result, "1|250px|1");
}
+#[tokio::test(flavor = "current_thread")]
+async fn window_animation_scan_does_not_serialize_installed_stylesheets() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
+ let mut vm = new_parsed_page_task_executor_test_vm(
+ "https://animation-scan-scaling.test/",
+ "<html><head></head><body></body></html>",
+ &loader,
+ );
+ vm.eval(
+ r#"
+const style = document.head.appendChild(document.createElement('style'));
+style.textContent = Array.from({length: 256}, (_, i) =>
+ `.unrelated-${i} { color: rgb(1, 2, 3); }`
+).join('\n') + `
+ @media all { @supports (display: block) {
+ @keyframes move { from { left: 0px; } to { left: 20px; } }
+ @keyframes shimmer { from { background-position: 0 50%; }
+ to { background-position: -100% 50%; } }
+ } }
+ .animated { position: relative; animation: move 1s linear; }
+ .skeleton { animation: shimmer 1s infinite; }
+`;
+document.body.innerHTML = Array.from({length: 32}, () =>
+ '<div class="animated"></div><div class="skeleton"></div>'
+).join('');
+globalThis.__animationScanEvents = 0;
+addEventListener('animationstart', () => { __animationScanEvents++; });
+getComputedStyle(document.querySelector('.animated')).animationName;
+"#,
+ )
+ .expect("large stylesheet and loading skeleton should initialize");
+ crate::live_stylesheet::reset_live_stylesheet_css_text_projection_count_for_test();
+
+ assert!(
+ vm.run_one_rendering_update_executor_turn(&loader)
+ .await
+ .expect("window animation scan should complete")
+ );
+ assert_eq!(
+ vm.eval(
+ r#"[
+ __animationScanEvents,
+ getComputedStyle(document.querySelector('.animated')).left,
+ document.querySelector('.animated').getAnimations().length,
+ document.querySelector('.skeleton').getAnimations().length
+ ].join('|')"#,
+ )
+ .expect("animation events and midpoint should remain observable"),
+ "32|10px|1|0"
+ );
+ assert_eq!(
+ crate::live_stylesheet::live_stylesheet_css_text_projection_count_for_test(),
+ 0,
+ "animation scans and value reads must use native rules, without serializing full stylesheets"
+ );
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn window_animation_scan_revalidates_keyframes_after_listener_cssom_mutation() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
+ let mut vm = new_parsed_page_task_executor_test_vm(
+ "https://animation-scan-cssom-mutation.test/",
+ r#"<html><head><style>
+ @keyframes move { from { left: 0px; } to { left: 20px; } }
+ .animated { position: relative; animation: move 1s linear; }
+ </style></head><body>
+ <div id="first" class="animated"></div><div id="second" class="animated"></div>
+ </body></html>"#,
+ &loader,
+ );
+ vm.eval(
+ r#"
+globalThis.__animationScanTargets = [];
+addEventListener('animationstart', event => {
+ __animationScanTargets.push(event.target.id);
+ document.styleSheets[0].deleteRule(0);
+});
+"#,
+ )
+ .expect("reentrant animation listener should initialize");
+
+ assert!(
+ vm.run_one_rendering_update_executor_turn(&loader)
+ .await
+ .expect("window animation scan should complete")
+ );
+ assert_eq!(
+ vm.eval("__animationScanTargets.join('|')")
+ .expect("animation targets should be readable"),
+ "first",
+ "removing keyframes in the first listener must suppress the second element's stale event"
+ );
+}
+
#[test]
fn raw_keyframe_scanner_respects_owner_media_changes() {
let mut vm = new_parsed_test_vm(